From 48765b7db662430e3c9a6434dfb017f60db2d966 Mon Sep 17 00:00:00 2001 From: Rupenieks Date: Tue, 9 Jun 2020 15:48:40 +0200 Subject: [PATCH 1/4] OAuth2 support --- .../PipedriveOAuth2Api.credentials.ts | 47 +++++++++++++++++++ .../nodes/Pipedrive/GenericFunctions.ts | 37 +++++++++------ .../nodes/Pipedrive/Pipedrive.node.ts | 37 ++++++++++++++- .../nodes/Pipedrive/PipedriveTrigger.node.ts | 22 ++++++--- packages/nodes-base/package.json | 1 + 5 files changed, 121 insertions(+), 23 deletions(-) create mode 100644 packages/nodes-base/credentials/PipedriveOAuth2Api.credentials.ts diff --git a/packages/nodes-base/credentials/PipedriveOAuth2Api.credentials.ts b/packages/nodes-base/credentials/PipedriveOAuth2Api.credentials.ts new file mode 100644 index 0000000000..813202739f --- /dev/null +++ b/packages/nodes-base/credentials/PipedriveOAuth2Api.credentials.ts @@ -0,0 +1,47 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class PipedriveOAuth2Api implements ICredentialType { + name = 'pipedriveOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Pipedrive OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://oauth.pipedrive.com/oauth/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://oauth.pipedrive.com/oauth/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'string' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'header', + }, + ]; +} diff --git a/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts b/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts index 32e8194359..9809d0feb3 100644 --- a/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts @@ -23,7 +23,6 @@ export interface ICustomProperties { [key: string]: ICustomInterface; } - /** * Make an API request to Pipedrive * @@ -34,16 +33,7 @@ export interface ICustomProperties { * @returns {Promise} */ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctions, method: string, endpoint: string, body: IDataObject, query?: IDataObject, formData?: IDataObject, downloadFile?: boolean): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('pipedriveApi'); - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - - if (query === undefined) { - query = {}; - } - - query.api_token = credentials.apiToken; + const authenticationMethod = this.getNodeParameter('authentication', 0); const options: OptionsWithUri = { method, @@ -65,8 +55,27 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio options.formData = formData; } + if (query === undefined) { + query = {}; + } + + let responseData; + try { - const responseData = await this.helpers.request(options); + if (authenticationMethod === 'accessToken') { + + const credentials = this.getCredentials('pipedriveApi'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + query.api_token = credentials.apiToken; + + responseData = await this.helpers.request(options); + + } else { + responseData = await this.helpers.requestOAuth2!.call(this, 'pipedriveOAuth2Api', options); + } if (downloadFile === true) { return { @@ -82,7 +91,7 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio additionalData: responseData.additional_data, data: responseData.data, }; - } catch (error) { + } catch(error) { if (error.statusCode === 401) { // Return a clear error throw new Error('The Pipedrive credentials are not valid!'); @@ -102,8 +111,6 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio } } - - /** * Make an API request to paginated Pipedrive endpoint * and return all results diff --git a/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts b/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts index 8ae9c42630..3aef48ce59 100644 --- a/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts +++ b/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts @@ -61,9 +61,44 @@ export class Pipedrive implements INodeType { { name: 'pipedriveApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'pipedriveOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'The resource to operate on.', + }, { displayName: 'Resource', name: 'resource', diff --git a/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts b/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts index 2c55246a32..0fb3d37f99 100644 --- a/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts +++ b/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts @@ -52,14 +52,21 @@ export class PipedriveTrigger implements INodeType { { name: 'pipedriveApi', required: true, + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, }, { - name: 'httpBasicAuth', + name: 'pipedriveOAuth2Api', required: true, displayOptions: { show: { authentication: [ - 'basicAuth', + 'oAuth2', ], }, }, @@ -80,15 +87,16 @@ export class PipedriveTrigger implements INodeType { type: 'options', options: [ { - name: 'Basic Auth', - value: 'basicAuth' + name: 'Access Token', + value: 'accessToken' }, { - name: 'None', - value: 'none' + name: 'OAuth2', + value: 'oAuth2' }, + ], - default: 'none', + default: 'accessToken', description: 'If authentication should be activated for the webhook (makes it more scure).', }, { diff --git a/packages/nodes-base/package.json b/packages/nodes-base/package.json index 3f28db9dec..57332957ee 100644 --- a/packages/nodes-base/package.json +++ b/packages/nodes-base/package.json @@ -99,6 +99,7 @@ "dist/credentials/PagerDutyApi.credentials.js", "dist/credentials/PayPalApi.credentials.js", "dist/credentials/PipedriveApi.credentials.js", + "dist/credentials/PipedriveOAuth2Api.credentials.js", "dist/credentials/Postgres.credentials.js", "dist/credentials/Redis.credentials.js", "dist/credentials/RocketchatApi.credentials.js", From c1b4c570fdd5020a6b7ed161988816b8a8aebf20 Mon Sep 17 00:00:00 2001 From: Rupenieks Date: Wed, 24 Jun 2020 16:02:44 +0200 Subject: [PATCH 2/4] re-added basicAuth for authentication --- .../nodes/Pipedrive/GenericFunctions.ts | 2 +- .../nodes/Pipedrive/Pipedrive.node.ts | 14 +++++++++----- .../nodes/Pipedrive/PipedriveTrigger.node.ts | 18 +++++++++++------- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts b/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts index 9809d0feb3..59ba514acf 100644 --- a/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts @@ -62,7 +62,7 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio let responseData; try { - if (authenticationMethod === 'accessToken') { + if (authenticationMethod === 'basicAuth') { const credentials = this.getCredentials('pipedriveApi'); if (credentials === undefined) { diff --git a/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts b/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts index 3aef48ce59..48a619a331 100644 --- a/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts +++ b/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts @@ -64,7 +64,7 @@ export class Pipedrive implements INodeType { displayOptions: { show: { authentication: [ - 'accessToken', + 'basicAuth', ], }, }, @@ -88,16 +88,20 @@ export class Pipedrive implements INodeType { type: 'options', options: [ { - name: 'Access Token', - value: 'accessToken', + name: 'Basic Auth', + value: 'basicAuth' }, { name: 'OAuth2', value: 'oAuth2', }, + { + name: 'None', + value: 'none', + }, ], - default: 'accessToken', - description: 'The resource to operate on.', + default: 'basicAuth', + description: 'Method of authentication.', }, { displayName: 'Resource', diff --git a/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts b/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts index 0fb3d37f99..ca4a1a7ec8 100644 --- a/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts +++ b/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts @@ -55,7 +55,7 @@ export class PipedriveTrigger implements INodeType { displayOptions: { show: { authentication: [ - 'accessToken', + 'basicAuth', ], }, }, @@ -72,6 +72,7 @@ export class PipedriveTrigger implements INodeType { }, }, ], + ], webhooks: [ { name: 'default', @@ -87,17 +88,20 @@ export class PipedriveTrigger implements INodeType { type: 'options', options: [ { - name: 'Access Token', - value: 'accessToken' + name: 'Basic Auth', + value: 'basicAuth' }, { name: 'OAuth2', - value: 'oAuth2' + value: 'oAuth2', + }, + { + name: 'None', + value: 'none', }, - ], - default: 'accessToken', - description: 'If authentication should be activated for the webhook (makes it more scure).', + default: 'basicAuth', + description: 'Method of authentication.', }, { displayName: 'Action', From b187a8fd7dfd27cee56dd606c00ef581612c95f0 Mon Sep 17 00:00:00 2001 From: ricardo Date: Thu, 23 Jul 2020 16:51:05 -0400 Subject: [PATCH 3/4] Merge branch 'Master' into 'Pipedrive-OAuth2-support' --- .github/workflows/docker-images-rpi.yml | 28 + .gitignore | 1 + CONTRIBUTING.md | 10 +- LICENSE.md | 2 +- README.md | 4 +- {docs/images => assets}/n8n-logo.png | Bin {docs/images => assets}/n8n-screenshot.png | Bin docker/compose/subfolderWithSSL/README.md | 26 + .../subfolderWithSSL/docker-compose.yml | 57 + docker/images/n8n-custom/Dockerfile | 2 + docker/images/n8n-custom/Dockerfile copy | 49 + docker/images/n8n-rhel7/Dockerfile | 23 + docker/images/n8n-rhel7/README.md | 16 + docker/images/n8n-rpi/Dockerfile | 20 + docker/images/n8n-rpi/README.md | 21 + docker/images/n8n-ubuntu/Dockerfile | 2 + docker/images/n8n/Dockerfile | 2 + docker/images/n8n/README.md | 155 ++- docs/.nojekyll | 0 docs/CNAME | 1 - docs/README.md | 10 - docs/_sidebar.md | 43 - docs/configuration.md | 244 ----- docs/create-node.md | 145 --- docs/data-structure.md | 39 - docs/database.md | 109 -- docs/development.md | 3 - docs/docker.md | 7 - docs/faq.md | 47 - docs/index.html | 53 - docs/key-components.md | 25 - docs/keyboard-shortcuts.md | 28 - docs/license.md | 5 - docs/node-basics.md | 76 -- docs/nodes.md | 247 ----- docs/quick-start.md | 43 - docs/security.md | 13 - docs/sensitive-data.md | 18 - docs/server-setup.md | 183 ---- docs/setup.md | 35 - docs/start-workflows-via-cli.md | 15 - docs/test.md | 3 - docs/troubleshooting.md | 58 -- docs/tutorials.md | 26 - docs/workflow.md | 111 -- package.json | 1 + packages/cli/LICENSE.md | 2 +- packages/cli/README.md | 4 +- packages/cli/commands/execute.ts | 5 + packages/cli/commands/start.ts | 6 +- packages/cli/config/index.ts | 97 +- packages/cli/migrations/ormconfig.ts | 10 +- packages/cli/package.json | 10 +- packages/cli/src/ActiveWorkflowRunner.ts | 185 +++- packages/cli/src/CredentialsOverwrites.ts | 3 +- packages/cli/src/Db.ts | 62 +- packages/cli/src/ExternalHooks.ts | 79 ++ packages/cli/src/GenericHelpers.ts | 5 +- packages/cli/src/Interfaces.ts | 31 + packages/cli/src/Server.ts | 204 +++- packages/cli/src/TestWebhooks.ts | 4 +- packages/cli/src/WebhookHelpers.ts | 30 + .../cli/src/WorkflowExecuteAdditionalData.ts | 48 +- packages/cli/src/WorkflowRunner.ts | 4 + .../src/databases/mongodb/ExecutionEntity.ts | 1 + .../src/databases/mongodb/WebhookEntity.ts | 30 + packages/cli/src/databases/mongodb/index.ts | 2 + .../151594910478695-CreateIndexStoppedAt.ts | 22 + .../migrations/1592679094242-WebhookModel.ts | 57 + .../src/databases/mongodb/migrations/index.ts | 2 + .../src/databases/mysqldb/ExecutionEntity.ts | 1 + .../src/databases/mysqldb/WebhookEntity.ts | 25 + packages/cli/src/databases/mysqldb/index.ts | 1 + .../1588157391238-InitialMigration.ts | 8 +- .../migrations/1592447867632-WebhookModel.ts | 59 ++ .../1594902918301-CreateIndexStoppedAt.ts | 20 + .../src/databases/mysqldb/migrations/index.ts | 4 +- .../databases/postgresdb/ExecutionEntity.ts | 1 + .../src/databases/postgresdb/WebhookEntity.ts | 25 + .../cli/src/databases/postgresdb/index.ts | 2 + .../1587669153312-InitialMigration.ts | 19 +- .../migrations/1589476000887-WebhookModel.ts | 69 ++ .../1594828256133-CreateIndexStoppedAt.ts | 25 + .../databases/postgresdb/migrations/index.ts | 3 + .../src/databases/sqlite/ExecutionEntity.ts | 1 + .../cli/src/databases/sqlite/WebhookEntity.ts | 25 + packages/cli/src/databases/sqlite/index.ts | 2 +- .../1588102412422-InitialMigration.ts | 13 +- .../migrations/1592445003908-WebhookModel.ts | 63 ++ .../1594825041918-CreateIndexStoppedAt.ts | 20 + .../src/databases/sqlite/migrations/index.ts | 4 +- packages/cli/src/index.ts | 1 + packages/core/LICENSE.md | 2 +- packages/core/README.md | 2 +- packages/core/package.json | 9 +- packages/core/src/ActiveWebhooks.ts | 9 +- packages/core/src/NodeExecuteFunctions.ts | 42 +- packages/core/src/UserSettings.ts | 9 +- packages/core/src/WorkflowExecute.ts | 10 +- packages/editor-ui/LICENSE.md | 2 +- packages/editor-ui/README.md | 2 +- packages/editor-ui/package.json | 10 +- packages/editor-ui/public/index.html | 5 +- .../src/components/ExpressionInput.vue | 7 + .../editor-ui/src/components/MainSidebar.vue | 4 +- .../editor-ui/src/components/NodeWebhooks.vue | 3 +- packages/editor-ui/src/components/RunData.vue | 8 +- packages/editor-ui/src/router.ts | 3 +- packages/editor-ui/src/store.ts | 5 +- packages/editor-ui/src/views/NodeView.vue | 11 + packages/editor-ui/vue.config.js | 1 + packages/node-dev/LICENSE.md | 2 +- packages/node-dev/README.md | 26 +- packages/node-dev/package.json | 6 +- packages/node-dev/src/Build.ts | 2 +- packages/node-dev/templates/webhook/simple.ts | 2 +- packages/nodes-base/LICENSE.md | 2 +- packages/nodes-base/README.md | 2 +- .../credentials/CircleCiApi.credentials.ts | 17 + .../credentials/CrateDb.credentials.ts | 69 ++ .../credentials/DriftOAuth2Api.credentials.ts | 47 + .../credentials/EventbriteApi.credentials.ts | 2 +- .../EventbriteOAuth2Api.credentials.ts | 47 + .../GitlabOAuth2Api.credentials.ts | 53 + .../GoogleDriveOAuth2Api.credentials.ts | 26 + .../GoogleTasksOAuth2Api.credentials.ts | 22 + .../HubspotOAuth2Api.credentials.ts | 53 + .../MailchimpOAuth2Api.credentials.ts | 54 + .../MauticOAuth2Api.credentials.ts | 55 + .../credentials/MessageBirdApi.credentials.ts | 14 + .../credentials/MicrosoftSql.credentials.ts | 47 + .../credentials/NextCloudApi.credentials.ts | 2 +- .../NextCloudOAuth2Api.credentials.ts | 54 + .../PagerDutyOAuth2Api.credentials.ts | 45 + .../PipedriveOAuth2Api.credentials.ts | 3 +- .../credentials/PostmarkApi.credentials.ts | 18 + .../credentials/QuestDb.credentials.ts | 69 ++ .../credentials/Signl4Api.credentials.ts | 18 + .../credentials/SlackOAuth2Api.credentials.ts | 3 - .../SpotifyOAuth2Api.credentials.ts | 53 + .../SurveyMonkeyOAuth2Api.credentials.ts | 55 + .../TypeformOAuth2Api.credentials.ts | 53 + .../WebflowOAuth2Api.credentials.ts | 50 + .../credentials/XeroOAuth2Api.credentials.ts | 51 + .../credentials/ZendeskApi.credentials.ts | 7 +- .../ZendeskOAuth2Api.credentials.ts | 79 ++ .../credentials/ZoomApi.credentials.ts | 14 + .../credentials/ZoomOAuth2Api.credentials.ts | 42 + packages/nodes-base/gulpfile.js | 2 +- .../nodes/Affinity/AffinityTrigger.node.ts | 6 +- .../nodes/CircleCi/CircleCi.node.ts | 140 +++ .../nodes/CircleCi/GenericFunctions.ts | 67 ++ .../nodes/CircleCi/PipelineDescription.ts | 229 ++++ .../nodes-base/nodes/CircleCi/circleCi.png | Bin 0 -> 4787 bytes .../nodes-base/nodes/CrateDb/CrateDb.node.ts | 246 +++++ packages/nodes-base/nodes/CrateDb/cratedb.png | Bin 0 -> 475 bytes packages/nodes-base/nodes/DateTime.node.ts | 3 +- packages/nodes-base/nodes/Drift/Drift.node.ts | 35 + .../nodes/Drift/GenericFunctions.ts | 38 +- .../nodes-base/nodes/Dropbox/Dropbox.node.ts | 21 +- .../Eventbrite/EventbriteTrigger.node.ts | 74 +- .../nodes/Eventbrite/GenericFunctions.ts | 33 +- .../nodes/Facebook/FacebookGraphApi.node.ts | 8 + .../nodes-base/nodes/Github/Github.node.ts | 27 +- .../nodes/Github/GithubTrigger.node.ts | 37 +- .../nodes/Gitlab/GenericFunctions.ts | 43 +- .../nodes-base/nodes/Gitlab/Gitlab.node.ts | 60 +- .../nodes/Gitlab/GitlabTrigger.node.ts | 61 +- .../nodes/Google/Calendar/EventDescription.ts | 149 +-- .../nodes/Google/Calendar/EventInterface.ts | 4 +- .../nodes/Google/Calendar/GenericFunctions.ts | 10 +- .../Google/Calendar/GoogleCalendar.node.ts | 216 ++-- .../nodes/Google/Drive/GenericFunctions.ts | 142 +++ .../nodes/Google/Drive/GoogleDrive.node.ts | 172 +-- packages/nodes-base/nodes/Google/GoogleApi.ts | 23 - .../nodes/Google/Sheet/GoogleSheets.node.ts | 16 +- .../nodes/Google/Task/GenericFunctions.ts | 92 ++ .../nodes/Google/Task/GoogleTasks.node.ts | 279 +++++ .../nodes/Google/Task/TaskDescription.ts | 493 +++++++++ .../nodes/Google/Task/googleTasks.png | Bin 0 -> 3290 bytes .../nodes/HackerNews/GenericFunctions.ts | 80 ++ .../nodes/HackerNews/HackerNews.node.ts | 384 +++++++ .../nodes/HackerNews/hackernews.png | Bin 0 -> 1952 bytes packages/nodes-base/nodes/HttpRequest.node.ts | 2 +- .../nodes/Hubspot/GenericFunctions.ts | 49 +- .../nodes-base/nodes/Hubspot/Hubspot.node.ts | 37 +- .../nodes/Hubspot/HubspotTrigger.node.ts | 24 +- .../nodes-base/nodes/Jira/IssueDescription.ts | 4 +- .../nodes/Mailchimp/GenericFunctions.ts | 72 +- .../nodes/Mailchimp/Mailchimp.node.ts | 407 +++++++- .../nodes/Mailchimp/MailchimpTrigger.node.ts | 37 +- .../nodes/Mattermost/Mattermost.node.ts | 20 +- .../nodes/Mautic/ContactDescription.ts | 562 +++++++++- .../nodes/Mautic/GenericFunctions.ts | 40 +- .../nodes-base/nodes/Mautic/Mautic.node.ts | 184 +++- .../nodes/Mautic/MauticTrigger.node.ts | 36 +- .../nodes/MessageBird/GenericFunctions.ts | 64 ++ .../nodes/MessageBird/MessageBird.node.ts | 364 +++++++ .../nodes/MessageBird/messagebird.png | Bin 0 -> 1305 bytes .../nodes/Microsoft/Sql/GenericFunctions.ts | 144 +++ .../nodes/Microsoft/Sql/MicrosoftSql.node.ts | 394 +++++++ .../nodes/Microsoft/Sql/TableInterface.ts | 7 + .../nodes-base/nodes/Microsoft/Sql/mssql.png | Bin 0 -> 3447 bytes .../nodes/MondayCom/BoardItemDescription.ts | 201 ++++ .../nodes/MondayCom/MondayCom.node.ts | 78 ++ .../nodes-base/nodes/MongoDb/MongoDb.node.ts | 13 +- .../nodes/MongoDb/mongo.node.options.ts | 30 +- packages/nodes-base/nodes/Msg91/Msg91.node.ts | 2 +- .../nodes/NextCloud/GenericFunctions.ts | 63 ++ .../nodes/NextCloud/NextCloud.node.ts | 75 +- .../nodes-base/nodes/OpenWeatherMap.node.ts | 14 +- .../nodes/PagerDuty/GenericFunctions.ts | 26 +- .../nodes/PagerDuty/PagerDuty.node.ts | 34 + .../nodes/Pipedrive/GenericFunctions.ts | 43 +- .../nodes/Pipedrive/Pipedrive.node.ts | 226 +++- .../nodes/Pipedrive/PipedriveTrigger.node.ts | 33 +- .../nodes/Postgres/Postgres.node.functions.ts | 129 +++ .../nodes/Postgres/Postgres.node.ts | 140 +-- .../nodes/Postmark/GenericFunctions.ts | 93 ++ .../nodes/Postmark/PostmarkTrigger.node.ts | 256 +++++ .../nodes-base/nodes/Postmark/postmark.png | Bin 0 -> 1297 bytes .../nodes-base/nodes/QuestDb/QuestDb.node.ts | 246 +++++ packages/nodes-base/nodes/QuestDb/questdb.png | Bin 0 -> 2835 bytes packages/nodes-base/nodes/Redis/Redis.node.ts | 1 + .../nodes/Rocketchat/Rocketchat.node.ts | 6 +- .../nodes/Salesforce/GenericFunctions.ts | 2 +- .../nodes/Signl4/GenericFunctions.ts | 52 + .../nodes-base/nodes/Signl4/Signl4.node.ts | 325 ++++++ packages/nodes-base/nodes/Signl4/signl4.png | Bin 0 -> 3045 bytes .../nodes/Slack/MessageDescription.ts | 6 +- packages/nodes-base/nodes/Slack/Slack.node.ts | 119 ++- .../nodes/Spotify/GenericFunctions.ts | 84 ++ .../nodes-base/nodes/Spotify/Spotify.node.ts | 816 +++++++++++++++ packages/nodes-base/nodes/Spotify/spotify.png | Bin 0 -> 6664 bytes .../nodes/SurveyMonkey/GenericFunctions.ts | 25 +- .../SurveyMonkey/SurveyMonkeyTrigger.node.ts | 44 +- .../nodes/Trello/AttachmentDescription.ts | 2 +- .../nodes/Trello/ChecklistDescription.ts | 6 +- .../nodes/Trello/LabelDescription.ts | 2 +- .../nodes/Twitter/TweetDescription.ts | 2 +- .../nodes-base/nodes/Twitter/Twitter.node.ts | 10 +- .../nodes/Typeform/GenericFunctions.ts | 29 +- .../nodes/Typeform/TypeformTrigger.node.ts | 37 +- .../nodes-base/nodes/Uplead/Uplead.node.ts | 4 +- .../nodes/Webflow/GenericFunctions.ts | 38 +- .../nodes/Webflow/WebflowTrigger.node.ts | 37 +- packages/nodes-base/nodes/Webhook.node.ts | 3 +- .../nodes/Xero/ContactDescription.ts | 838 +++++++++++++++ .../nodes-base/nodes/Xero/GenericFunctions.ts | 76 ++ .../nodes/Xero/IContactInterface.ts | 44 + .../nodes/Xero/InvoiceDescription.ts | 983 ++++++++++++++++++ .../nodes-base/nodes/Xero/InvoiceInterface.ts | 40 + packages/nodes-base/nodes/Xero/Xero.node.ts | 681 ++++++++++++ packages/nodes-base/nodes/Xero/xero.png | Bin 0 -> 9587 bytes .../nodes/Zendesk/GenericFunctions.ts | 40 +- .../nodes-base/nodes/Zendesk/Zendesk.node.ts | 37 +- .../nodes/Zendesk/ZendeskTrigger.node.ts | 37 +- .../nodes-base/nodes/Zoom/GenericFunctions.ts | 104 ++ .../nodes/Zoom/MeetingDescription.ts | 751 +++++++++++++ .../Zoom/MeetingRegistrantDescription.ts | 443 ++++++++ .../nodes/Zoom/WebinarDescription.ts | 665 ++++++++++++ packages/nodes-base/nodes/Zoom/Zoom.node.ts | 821 +++++++++++++++ packages/nodes-base/nodes/Zoom/zoom.png | Bin 0 -> 1848 bytes packages/nodes-base/nodes/utils/utilities.ts | 57 + packages/nodes-base/package.json | 502 +++++++-- packages/workflow/LICENSE.md | 2 +- packages/workflow/README.md | 2 +- packages/workflow/package.json | 2 +- packages/workflow/src/Interfaces.ts | 4 +- packages/workflow/src/NodeHelpers.ts | 79 +- packages/workflow/src/Workflow.ts | 10 +- 271 files changed, 17019 insertions(+), 2796 deletions(-) create mode 100644 .github/workflows/docker-images-rpi.yml rename {docs/images => assets}/n8n-logo.png (100%) rename {docs/images => assets}/n8n-screenshot.png (100%) create mode 100644 docker/compose/subfolderWithSSL/README.md create mode 100644 docker/compose/subfolderWithSSL/docker-compose.yml create mode 100644 docker/images/n8n-custom/Dockerfile copy create mode 100644 docker/images/n8n-rhel7/Dockerfile create mode 100644 docker/images/n8n-rhel7/README.md create mode 100644 docker/images/n8n-rpi/Dockerfile create mode 100644 docker/images/n8n-rpi/README.md delete mode 100644 docs/.nojekyll delete mode 100644 docs/CNAME delete mode 100644 docs/README.md delete mode 100644 docs/_sidebar.md delete mode 100644 docs/configuration.md delete mode 100644 docs/create-node.md delete mode 100644 docs/data-structure.md delete mode 100644 docs/database.md delete mode 100644 docs/development.md delete mode 100644 docs/docker.md delete mode 100644 docs/faq.md delete mode 100644 docs/index.html delete mode 100644 docs/key-components.md delete mode 100644 docs/keyboard-shortcuts.md delete mode 100644 docs/license.md delete mode 100644 docs/node-basics.md delete mode 100644 docs/nodes.md delete mode 100644 docs/quick-start.md delete mode 100644 docs/security.md delete mode 100644 docs/sensitive-data.md delete mode 100644 docs/server-setup.md delete mode 100644 docs/setup.md delete mode 100644 docs/start-workflows-via-cli.md delete mode 100644 docs/test.md delete mode 100644 docs/troubleshooting.md delete mode 100644 docs/tutorials.md delete mode 100644 docs/workflow.md create mode 100644 packages/cli/src/ExternalHooks.ts create mode 100644 packages/cli/src/databases/mongodb/WebhookEntity.ts create mode 100644 packages/cli/src/databases/mongodb/migrations/151594910478695-CreateIndexStoppedAt.ts create mode 100644 packages/cli/src/databases/mongodb/migrations/1592679094242-WebhookModel.ts create mode 100644 packages/cli/src/databases/mysqldb/WebhookEntity.ts create mode 100644 packages/cli/src/databases/mysqldb/migrations/1592447867632-WebhookModel.ts create mode 100644 packages/cli/src/databases/mysqldb/migrations/1594902918301-CreateIndexStoppedAt.ts create mode 100644 packages/cli/src/databases/postgresdb/WebhookEntity.ts create mode 100644 packages/cli/src/databases/postgresdb/migrations/1589476000887-WebhookModel.ts create mode 100644 packages/cli/src/databases/postgresdb/migrations/1594828256133-CreateIndexStoppedAt.ts create mode 100644 packages/cli/src/databases/sqlite/WebhookEntity.ts create mode 100644 packages/cli/src/databases/sqlite/migrations/1592445003908-WebhookModel.ts create mode 100644 packages/cli/src/databases/sqlite/migrations/1594825041918-CreateIndexStoppedAt.ts create mode 100644 packages/nodes-base/credentials/CircleCiApi.credentials.ts create mode 100644 packages/nodes-base/credentials/CrateDb.credentials.ts create mode 100644 packages/nodes-base/credentials/DriftOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/EventbriteOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/GitlabOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/GoogleDriveOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/GoogleTasksOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/HubspotOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/MailchimpOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/MauticOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/MessageBirdApi.credentials.ts create mode 100644 packages/nodes-base/credentials/MicrosoftSql.credentials.ts create mode 100644 packages/nodes-base/credentials/NextCloudOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/PagerDutyOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/PostmarkApi.credentials.ts create mode 100644 packages/nodes-base/credentials/QuestDb.credentials.ts create mode 100644 packages/nodes-base/credentials/Signl4Api.credentials.ts create mode 100644 packages/nodes-base/credentials/SpotifyOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/SurveyMonkeyOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/TypeformOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/WebflowOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/XeroOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/ZendeskOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/credentials/ZoomApi.credentials.ts create mode 100644 packages/nodes-base/credentials/ZoomOAuth2Api.credentials.ts create mode 100644 packages/nodes-base/nodes/CircleCi/CircleCi.node.ts create mode 100644 packages/nodes-base/nodes/CircleCi/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/CircleCi/PipelineDescription.ts create mode 100644 packages/nodes-base/nodes/CircleCi/circleCi.png create mode 100644 packages/nodes-base/nodes/CrateDb/CrateDb.node.ts create mode 100644 packages/nodes-base/nodes/CrateDb/cratedb.png create mode 100644 packages/nodes-base/nodes/Google/Drive/GenericFunctions.ts delete mode 100644 packages/nodes-base/nodes/Google/GoogleApi.ts create mode 100644 packages/nodes-base/nodes/Google/Task/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Google/Task/GoogleTasks.node.ts create mode 100644 packages/nodes-base/nodes/Google/Task/TaskDescription.ts create mode 100644 packages/nodes-base/nodes/Google/Task/googleTasks.png create mode 100644 packages/nodes-base/nodes/HackerNews/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/HackerNews/HackerNews.node.ts create mode 100644 packages/nodes-base/nodes/HackerNews/hackernews.png create mode 100644 packages/nodes-base/nodes/MessageBird/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/MessageBird/MessageBird.node.ts create mode 100644 packages/nodes-base/nodes/MessageBird/messagebird.png create mode 100644 packages/nodes-base/nodes/Microsoft/Sql/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Microsoft/Sql/MicrosoftSql.node.ts create mode 100644 packages/nodes-base/nodes/Microsoft/Sql/TableInterface.ts create mode 100644 packages/nodes-base/nodes/Microsoft/Sql/mssql.png create mode 100644 packages/nodes-base/nodes/NextCloud/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Postgres/Postgres.node.functions.ts create mode 100644 packages/nodes-base/nodes/Postmark/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Postmark/PostmarkTrigger.node.ts create mode 100644 packages/nodes-base/nodes/Postmark/postmark.png create mode 100644 packages/nodes-base/nodes/QuestDb/QuestDb.node.ts create mode 100644 packages/nodes-base/nodes/QuestDb/questdb.png create mode 100644 packages/nodes-base/nodes/Signl4/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Signl4/Signl4.node.ts create mode 100644 packages/nodes-base/nodes/Signl4/signl4.png create mode 100644 packages/nodes-base/nodes/Spotify/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Spotify/Spotify.node.ts create mode 100644 packages/nodes-base/nodes/Spotify/spotify.png create mode 100644 packages/nodes-base/nodes/Xero/ContactDescription.ts create mode 100644 packages/nodes-base/nodes/Xero/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Xero/IContactInterface.ts create mode 100644 packages/nodes-base/nodes/Xero/InvoiceDescription.ts create mode 100644 packages/nodes-base/nodes/Xero/InvoiceInterface.ts create mode 100644 packages/nodes-base/nodes/Xero/Xero.node.ts create mode 100644 packages/nodes-base/nodes/Xero/xero.png create mode 100644 packages/nodes-base/nodes/Zoom/GenericFunctions.ts create mode 100644 packages/nodes-base/nodes/Zoom/MeetingDescription.ts create mode 100644 packages/nodes-base/nodes/Zoom/MeetingRegistrantDescription.ts create mode 100644 packages/nodes-base/nodes/Zoom/WebinarDescription.ts create mode 100644 packages/nodes-base/nodes/Zoom/Zoom.node.ts create mode 100644 packages/nodes-base/nodes/Zoom/zoom.png create mode 100644 packages/nodes-base/nodes/utils/utilities.ts diff --git a/.github/workflows/docker-images-rpi.yml b/.github/workflows/docker-images-rpi.yml new file mode 100644 index 0000000000..c6db9ed95b --- /dev/null +++ b/.github/workflows/docker-images-rpi.yml @@ -0,0 +1,28 @@ +name: Docker Image CI - Rpi + +on: + push: + tags: + - n8n@* + +jobs: + armv7_job: + runs-on: ubuntu-18.04 + name: Build on ARMv7 (Rpi) + steps: + - uses: actions/checkout@v1 + - name: Get the version + id: vars + run: echo ::set-output name=tag::$(echo ${GITHUB_REF:14}) + + - name: Log in to Docker registry + run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + + - name: Set up Docker Buildx + uses: crazy-max/ghaction-docker-buildx@v1 + with: + version: latest + - name: Run Buildx (push image) + if: success() + run: | + docker buildx build --platform linux/arm/v7 --build-arg N8N_VERSION=${{steps.vars.outputs.tag}} -t n8nio/n8n:${{steps.vars.outputs.tag}}-rpi --output type=image,push=true docker/images/n8n-rpi diff --git a/.gitignore b/.gitignore index b3eac39207..0441d445b4 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ _START_PACKAGE .env .vscode .idea +.prettierrc.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 568f8fc9a7..fcc046beef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,7 +38,7 @@ The most important directories: execution, active webhooks and workflows - [/packages/editor-ui](/packages/editor-ui) - Vue frontend workflow editor - - [/packages/node-dev](/packages/node-dev) - Simple CLI to create new n8n-nodes + - [/packages/node-dev](/packages/node-dev) - CLI to create new n8n-nodes - [/packages/nodes-base](/packages/nodes-base) - Base n8n nodes - [/packages/workflow](/packages/workflow) - Workflow code with interfaces which get used by front- & backend @@ -159,7 +159,7 @@ tests of all packages. ## Create Custom Nodes -It is very easy to create own nodes for n8n. More information about that can +It is very straightforward to create your own nodes for n8n. More information about that can be found in the documentation of "n8n-node-dev" which is a small CLI which helps with n8n-node-development. @@ -177,9 +177,9 @@ If you want to create a node which should be added to n8n follow these steps: 1. Create a new folder for the new node. For a service named "Example" the folder would be called: `/packages/nodes-base/nodes/Example` - 1. If there is already a similar node simply copy the existing one in the new folder and rename it. If none exists yet, create a boilerplate node with [n8n-node-dev](https://github.com/n8n-io/n8n/tree/master/packages/node-dev) and copy that one in the folder. + 1. If there is already a similar node, copy the existing one in the new folder and rename it. If none exists yet, create a boilerplate node with [n8n-node-dev](https://github.com/n8n-io/n8n/tree/master/packages/node-dev) and copy that one in the folder. - 1. If the node needs credentials because it has to authenticate with an API or similar create new ones. Existing ones can be found in folder `/packages/nodes-base/credentials`. Also there it is the easiest to simply copy existing similar ones. + 1. If the node needs credentials because it has to authenticate with an API or similar create new ones. Existing ones can be found in folder `/packages/nodes-base/credentials`. Also there it is the easiest to copy existing similar ones. 1. Add the path to the new node (and optionally credentials) to package.json of `nodes-base`. It already contains a property `n8n` with its own keys `credentials` and `nodes`. @@ -236,6 +236,6 @@ docsify serve ./docs That we do not have any potential problems later it is sadly necessary to sign a [Contributor License Agreement](CONTRIBUTOR_LICENSE_AGREEMENT.md). That can be done literally with the push of a button. -We used the most simple one that exists. It is from [Indie Open Source](https://indieopensource.com/forms/cla) which uses plain English and is literally just a few lines long. +We used the most simple one that exists. It is from [Indie Open Source](https://indieopensource.com/forms/cla) which uses plain English and is literally only a few lines long. A bot will automatically comment on the pull request once it got opened asking for the agreement to be signed. Before it did not get signed it is sadly not possible to merge it in. diff --git a/LICENSE.md b/LICENSE.md index aac54547eb..24a7d38fc9 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -215,7 +215,7 @@ Licensor: n8n GmbH same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2020 n8n GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index a9a161f9a2..eb692157a1 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # n8n - Workflow Automation Tool -![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/docs/images/n8n-logo.png) +![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/assets/n8n-logo.png) n8n is a free and open [fair-code](http://faircode.io) licensed node based Workflow Automation Tool. It can be self-hosted, easily extended, and so also used with internal tools. -n8n.io - Screenshot +n8n.io - Screenshot diff --git a/docs/images/n8n-logo.png b/assets/n8n-logo.png similarity index 100% rename from docs/images/n8n-logo.png rename to assets/n8n-logo.png diff --git a/docs/images/n8n-screenshot.png b/assets/n8n-screenshot.png similarity index 100% rename from docs/images/n8n-screenshot.png rename to assets/n8n-screenshot.png diff --git a/docker/compose/subfolderWithSSL/README.md b/docker/compose/subfolderWithSSL/README.md new file mode 100644 index 0000000000..61fcb5b7e7 --- /dev/null +++ b/docker/compose/subfolderWithSSL/README.md @@ -0,0 +1,26 @@ +# n8n on Subfolder with SSL + +Starts n8n and deployes it on a subfolder + + +## Start + +To start n8n in a subfolder simply start docker-compose by executing the following +command in the current folder. + + +**IMPORTANT:** But before you do that change the default users and passwords in the `.env` file! + +``` +docker-compose up -d +``` + +To stop it execute: + +``` +docker-compose stop +``` + +## Configuration + +The default name of the database, user and password for MongoDB can be changed in the `.env` file in the current directory. diff --git a/docker/compose/subfolderWithSSL/docker-compose.yml b/docker/compose/subfolderWithSSL/docker-compose.yml new file mode 100644 index 0000000000..5e540abbb5 --- /dev/null +++ b/docker/compose/subfolderWithSSL/docker-compose.yml @@ -0,0 +1,57 @@ +version: "3" + +services: + traefik: + image: "traefik" + command: + - "--api=true" + - "--api.insecure=true" + - "--api.dashboard=true" + - "--providers.docker=true" + - "--providers.docker.exposedbydefault=false" + - "--entrypoints.websecure.address=:443" + - "--certificatesresolvers.mytlschallenge.acme.tlschallenge=true" + - "--certificatesresolvers.mytlschallenge.acme.email=${SSL_EMAIL}" + - "--certificatesresolvers.mytlschallenge.acme.storage=/letsencrypt/acme.json" + - /home/jan/www/n8n/n8n:/data + ports: + - "443:443" + - "80:80" + volumes: + - ${DATA_FOLDER}/letsencrypt:/letsencrypt + - /var/run/docker.sock:/var/run/docker.sock:ro + n8n: + image: n8nio/n8n + ports: + - "127.0.0.1:5678:5678" + labels: + - traefik.enable=true + - traefik.http.routers.n8n.rule=Host(`${DOMAIN_NAME}`) + - traefik.http.routers.n8n.tls=true + - traefik.http.routers.n8n.entrypoints=websecure + - "traefik.http.routers.n8n.rule=PathPrefix(`/${SUBFOLDER}{regex:$$|/.*}`)" + - "traefik.http.middlewares.n8n-stripprefix.stripprefix.prefixes=/${SUBFOLDER}" + - "traefik.http.routers.n8n.middlewares=n8n-stripprefix" + - traefik.http.routers.n8n.tls.certresolver=mytlschallenge + - traefik.http.middlewares.n8n.headers.SSLRedirect=true + - traefik.http.middlewares.n8n.headers.STSSeconds=315360000 + - traefik.http.middlewares.n8n.headers.browserXSSFilter=true + - traefik.http.middlewares.n8n.headers.contentTypeNosniff=true + - traefik.http.middlewares.n8n.headers.forceSTSHeader=true + - traefik.http.middlewares.n8n.headers.SSLHost=${DOMAIN_NAME} + - traefik.http.middlewares.n8n.headers.STSIncludeSubdomains=true + - traefik.http.middlewares.n8n.headers.STSPreload=true + environment: + - N8N_BASIC_AUTH_ACTIVE=true + - N8N_BASIC_AUTH_USER + - N8N_BASIC_AUTH_PASSWORD + - N8N_HOST=${DOMAIN_NAME} + - N8N_PORT=5678 + - N8N_PROTOCOL=https + - NODE_ENV=production + - N8N_PATH + - WEBHOOK_TUNNEL_URL=http://${DOMAIN_NAME}${N8N_PATH} + - VUE_APP_URL_BASE_API=http://${DOMAIN_NAME}${N8N_PATH} + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ${DATA_FOLDER}/.n8n:/root/.n8n diff --git a/docker/images/n8n-custom/Dockerfile b/docker/images/n8n-custom/Dockerfile index f4e4af4ed7..d12f8f6b08 100644 --- a/docker/images/n8n-custom/Dockerfile +++ b/docker/images/n8n-custom/Dockerfile @@ -42,3 +42,5 @@ COPY --from=builder /data ./ COPY docker/images/n8n-custom/docker-entrypoint.sh /docker-entrypoint.sh ENTRYPOINT ["tini", "--", "/docker-entrypoint.sh"] + +EXPOSE 5678/tcp diff --git a/docker/images/n8n-custom/Dockerfile copy b/docker/images/n8n-custom/Dockerfile copy new file mode 100644 index 0000000000..19f08a16dd --- /dev/null +++ b/docker/images/n8n-custom/Dockerfile copy @@ -0,0 +1,49 @@ +FROM node:12.16-alpine as builder +# FROM node:12.16-alpine + +# Update everything and install needed dependencies +RUN apk add --update graphicsmagick tzdata git tini su-exec + +USER root + +# Install all needed dependencies +RUN apk --update add --virtual build-dependencies python build-base ca-certificates && \ + npm_config_user=root npm install -g full-icu lerna + +ENV NODE_ICU_DATA /usr/local/lib/node_modules/full-icu + +WORKDIR /data + +COPY lerna.json . +COPY package.json . +COPY packages/cli/ ./packages/cli/ +COPY packages/core/ ./packages/core/ +COPY packages/editor-ui/ ./packages/editor-ui/ +COPY packages/nodes-base/ ./packages/nodes-base/ +COPY packages/workflow/ ./packages/workflow/ +RUN rm -rf node_modules packages/*/node_modules packages/*/dist + +RUN npm install --loglevel notice +RUN lerna bootstrap --hoist +RUN npm run build + + +FROM node:12.16-alpine + +WORKDIR /data + +# Install all needed dependencies +RUN npm_config_user=root npm install -g full-icu + +USER root + +ENV NODE_ICU_DATA /usr/local/lib/node_modules/full-icu + +COPY --from=builder /data ./ + +RUN apk add --update graphicsmagick tzdata git tini su-exec + +COPY docker/images/n8n-dev/docker-entrypoint.sh /docker-entrypoint.sh +ENTRYPOINT ["tini", "--", "/docker-entrypoint.sh"] + +EXPOSE 5678/tcp diff --git a/docker/images/n8n-rhel7/Dockerfile b/docker/images/n8n-rhel7/Dockerfile new file mode 100644 index 0000000000..949d436602 --- /dev/null +++ b/docker/images/n8n-rhel7/Dockerfile @@ -0,0 +1,23 @@ +FROM richxsl/rhel7 + +ARG N8N_VERSION + +RUN if [ -z "$N8N_VERSION" ] ; then echo "The N8N_VERSION argument is missing!" ; exit 1; fi + +RUN \ + yum install -y gcc-c++ make + +RUN \ + curl -sL https://rpm.nodesource.com/setup_12.x | sudo -E bash - + +RUN \ + sudo yum install nodejs + +# Set a custom user to not have n8n run as root +USER root + +RUN npm_config_user=root npm install -g n8n@${N8N_VERSION} + +WORKDIR /data + +CMD "n8n" diff --git a/docker/images/n8n-rhel7/README.md b/docker/images/n8n-rhel7/README.md new file mode 100644 index 0000000000..015f7ac07f --- /dev/null +++ b/docker/images/n8n-rhel7/README.md @@ -0,0 +1,16 @@ +## Build Docker-Image + +``` +docker build --build-arg N8N_VERSION= -t n8nio/n8n: . + +# For example: +docker build --build-arg N8N_VERSION=0.36.1 -t n8nio/n8n:0.36.1-rhel7 . +``` + + +``` +docker run -it --rm \ + --name n8n \ + -p 5678:5678 \ + n8nio/n8n:0.25.0-ubuntu +``` diff --git a/docker/images/n8n-rpi/Dockerfile b/docker/images/n8n-rpi/Dockerfile new file mode 100644 index 0000000000..b60d50bdeb --- /dev/null +++ b/docker/images/n8n-rpi/Dockerfile @@ -0,0 +1,20 @@ +FROM arm32v7/node:12.16 + +ARG N8N_VERSION + +RUN if [ -z "$N8N_VERSION" ] ; then echo "The N8N_VERSION argument is missing!" ; exit 1; fi + +RUN \ + apt-get update && \ + apt-get -y install graphicsmagick gosu + +RUN npm_config_user=root npm install -g full-icu n8n@${N8N_VERSION} + +ENV NODE_ICU_DATA /usr/local/lib/node_modules/full-icu +ENV NODE_ENV production + +WORKDIR /data + +USER node + +CMD n8n diff --git a/docker/images/n8n-rpi/README.md b/docker/images/n8n-rpi/README.md new file mode 100644 index 0000000000..9eca14e3f6 --- /dev/null +++ b/docker/images/n8n-rpi/README.md @@ -0,0 +1,21 @@ +## n8n - Raspberry PI Docker Image + +Dockerfile to build n8n for Raspberry PI. + +For information about how to run n8n with Docker check the generic +[Docker-Readme](https://github.com/n8n-io/n8n/tree/master/docker/images/n8n/README.md) + + +``` +docker build --build-arg N8N_VERSION= -t n8nio/n8n: . + +# For example: +docker build --build-arg N8N_VERSION=0.43.0 -t n8nio/n8n:0.43.0-rpi . +``` + +``` +docker run -it --rm \ + --name n8n \ + -p 5678:5678 \ + n8nio/n8n:0.70.0-rpi +``` diff --git a/docker/images/n8n-ubuntu/Dockerfile b/docker/images/n8n-ubuntu/Dockerfile index 200506f058..94935f0602 100644 --- a/docker/images/n8n-ubuntu/Dockerfile +++ b/docker/images/n8n-ubuntu/Dockerfile @@ -19,3 +19,5 @@ WORKDIR /data COPY docker-entrypoint.sh /docker-entrypoint.sh ENTRYPOINT ["/docker-entrypoint.sh"] + +EXPOSE 5678/tcp diff --git a/docker/images/n8n/Dockerfile b/docker/images/n8n/Dockerfile index c0997dcabd..af8f29cc5c 100644 --- a/docker/images/n8n/Dockerfile +++ b/docker/images/n8n/Dockerfile @@ -22,3 +22,5 @@ WORKDIR /data COPY docker-entrypoint.sh /docker-entrypoint.sh ENTRYPOINT ["tini", "--", "/docker-entrypoint.sh"] + +EXPOSE 5678/tcp diff --git a/docker/images/n8n/README.md b/docker/images/n8n/README.md index e1b39d82d6..977c53fef4 100644 --- a/docker/images/n8n/README.md +++ b/docker/images/n8n/README.md @@ -1,30 +1,28 @@ # n8n - Workflow Automation -![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/docs/images/n8n-logo.png) +![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/assets/n8n-logo.png) n8n is a free and open [fair-code](http://faircode.io) licensed node based Workflow Automation Tool. It can be self-hosted, easily extended, and so also used with internal tools. -n8n.io - Screenshot - +n8n.io - Screenshot ## Contents -- [Demo](#demo) -- [Available integrations](#available-integrations) -- [Documentation](#documentation) -- [Start n8n in Docker](#start-n8n-in-docker) -- [Start with tunnel](#start-with-tunnel) -- [Securing n8n](#securing-n8n) -- [Persist data](#persist-data) -- [Passing Sensitive Data via File](#passing-sensitive-data-via-file) -- [Updating a Running docker-compose Instance](#updating-a-running-docker-compose-instance) -- [Example Setup with Lets Encrypt](#example-setup-with-lets-encrypt) -- [What does n8n mean and how do you pronounce it](#what-does-n8n-mean-and-how-do-you-pronounce-it) -- [Support](#support) -- [Jobs](#jobs) -- [Upgrading](#upgrading) -- [License](#license) - + - [Demo](#demo) + - [Available integrations](#available-integrations) + - [Documentation](#documentation) + - [Start n8n in Docker](#start-n8n-in-docker) + - [Start with tunnel](#start-with-tunnel) + - [Securing n8n](#securing-n8n) + - [Persist data](#persist-data) + - [Passing Sensitive Data via File](#passing-sensitive-data-via-file) + - [Updating a Running docker-compose Instance](#updating-a-running-docker-compose-instance) + - [Example Setup with Lets Encrypt](#example-setup-with-lets-encrypt) + - [What does n8n mean and how do you pronounce it](#what-does-n8n-mean-and-how-do-you-pronounce-it) + - [Support](#support) + - [Jobs](#jobs) + - [Upgrading](#upgrading) + - [License](#license) ## Demo @@ -49,9 +47,9 @@ Additional information and example workflows on the n8n.io website: [https://n8n ``` docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ - n8nio/n8n + --name n8n \ + -p 5678:5678 \ + n8nio/n8n ``` You can then access n8n by opening: @@ -71,14 +69,13 @@ To use it simply start n8n with `--tunnel` ``` docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ - -v ~/.n8n:/root/.n8n \ - n8nio/n8n \ - n8n start --tunnel + --name n8n \ + -p 5678:5678 \ + -v ~/.n8n:/root/.n8n \ + n8nio/n8n \ + n8n start --tunnel ``` - ## Securing n8n By default n8n can be accessed by everybody. This is OK if you have it only running @@ -93,7 +90,6 @@ N8N_BASIC_AUTH_USER= N8N_BASIC_AUTH_PASSWORD= ``` - ## Persist data The workflow data gets by default saved in an SQLite database in the user @@ -102,10 +98,10 @@ settings like webhook URL and encryption key. ``` docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ - -v ~/.n8n:/root/.n8n \ - n8nio/n8n + --name n8n \ + -p 5678:5678 \ + -v ~/.n8n:/root/.n8n \ + n8nio/n8n ``` ### Start with other Database @@ -121,7 +117,6 @@ for the credentials. If none gets found n8n creates automatically one on startup. In case credentials are already saved with a different encryption key it can not be used anymore as encrypting it is not possible anymore. - #### Use with MongoDB > **WARNING**: Use Postgres if possible! Mongo has problems with saving large @@ -129,40 +124,39 @@ it can not be used anymore as encrypting it is not possible anymore. > may be dropped in the future. Replace the following placeholders with the actual data: - - - - - - - - - - + - MONGO_DATABASE + - MONGO_HOST + - MONGO_PORT + - MONGO_USER + - MONGO_PASSWORD ``` docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ + --name n8n \ + -p 5678:5678 \ -e DB_TYPE=mongodb \ -e DB_MONGODB_CONNECTION_URL="mongodb://:@:/" \ - -v ~/.n8n:/root/.n8n \ - n8nio/n8n \ - n8n start + -v ~/.n8n:/root/.n8n \ + n8nio/n8n \ + n8n start ``` A full working setup with docker-compose can be found [here](https://github.com/n8n-io/n8n/blob/master/docker/compose/withMongo/README.md) - #### Use with PostgresDB Replace the following placeholders with the actual data: - - - - - - - - - - - - + - POSTGRES_DATABASE + - POSTGRES_HOST + - POSTGRES_PASSWORD + - POSTGRES_PORT + - POSTGRES_USER + - POSTGRES_SCHEMA ``` docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ + --name n8n \ + -p 5678:5678 \ -e DB_TYPE=postgresdb \ -e DB_POSTGRESDB_DATABASE= \ -e DB_POSTGRESDB_HOST= \ @@ -170,39 +164,37 @@ docker run -it --rm \ -e DB_POSTGRESDB_USER= \ -e DB_POSTGRESDB_SCHEMA= \ -e DB_POSTGRESDB_PASSWORD= \ - -v ~/.n8n:/root/.n8n \ - n8nio/n8n \ - n8n start + -v ~/.n8n:/root/.n8n \ + n8nio/n8n \ + n8n start ``` A full working setup with docker-compose can be found [here](https://github.com/n8n-io/n8n/blob/master/docker/compose/withPostgres/README.md) - #### Use with MySQL Replace the following placeholders with the actual data: - - - - - - - - - - + - MYSQLDB_DATABASE + - MYSQLDB_HOST + - MYSQLDB_PASSWORD + - MYSQLDB_PORT + - MYSQLDB_USER ``` docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ + --name n8n \ + -p 5678:5678 \ -e DB_TYPE=mysqldb \ -e DB_MYSQLDB_DATABASE= \ -e DB_MYSQLDB_HOST= \ -e DB_MYSQLDB_PORT= \ -e DB_MYSQLDB_USER= \ -e DB_MYSQLDB_PASSWORD= \ - -v ~/.n8n:/root/.n8n \ - n8nio/n8n \ - n8n start + -v ~/.n8n:/root/.n8n \ + n8nio/n8n \ + n8n start ``` - ## Passing Sensitive Data via File To avoid passing sensitive information via environment variables "_FILE" may be @@ -211,16 +203,15 @@ with the given name. That makes it possible to load data easily from Docker- and Kubernetes-Secrets. The following environment variables support file input: - - DB_MONGODB_CONNECTION_URL_FILE - - DB_POSTGRESDB_DATABASE_FILE - - DB_POSTGRESDB_HOST_FILE - - DB_POSTGRESDB_PASSWORD_FILE - - DB_POSTGRESDB_PORT_FILE - - DB_POSTGRESDB_USER_FILE - - DB_POSTGRESDB_SCHEMA_FILE - - N8N_BASIC_AUTH_PASSWORD_FILE - - N8N_BASIC_AUTH_USER_FILE - + - DB_MONGODB_CONNECTION_URL_FILE + - DB_POSTGRESDB_DATABASE_FILE + - DB_POSTGRESDB_HOST_FILE + - DB_POSTGRESDB_PASSWORD_FILE + - DB_POSTGRESDB_PORT_FILE + - DB_POSTGRESDB_USER_FILE + - DB_POSTGRESDB_SCHEMA_FILE + - N8N_BASIC_AUTH_PASSWORD_FILE + - N8N_BASIC_AUTH_USER_FILE ## Example Setup with Lets Encrypt @@ -235,7 +226,7 @@ docker pull n8nio/n8n # Stop current setup sudo docker-compose stop # Delete it (will only delete the docker-containers, data is stored separately) -sudo docker-compose rm +sudo docker-compose rm # Then start it again sudo docker-compose up -d ``` @@ -251,11 +242,11 @@ the environment variable `TZ`. Example to use the same timezone for both: ``` docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ + --name n8n \ + -p 5678:5678 \ -e GENERIC_TIMEZONE="Europe/Berlin" \ -e TZ="Europe/Berlin" \ - n8nio/n8n + n8nio/n8n ``` diff --git a/docs/.nojekyll b/docs/.nojekyll deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/CNAME b/docs/CNAME deleted file mode 100644 index 3ea71f7d8f..0000000000 --- a/docs/CNAME +++ /dev/null @@ -1 +0,0 @@ -docs.n8n.io \ No newline at end of file diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 3454cc15e2..0000000000 --- a/docs/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# n8n Documentation - -This is the documentation of n8n, a free and open [fair-code](http://faircode.io) licensed node-based Workflow Automation Tool. - -It covers everything from setup to usage and development. It is still a work in progress and all contributions are welcome. - - -## What is n8n? - -n8n (pronounced nodemation) helps you to interconnect every app with an API in the world with each other to share and manipulate its data without a single line of code. It is an easy to use, user-friendly and highly customizable service, which uses an intuitive user interface for you to design your unique workflows very fast. Hosted on your server and not based in the cloud, it keeps your sensible data very secure in your own trusted database. diff --git a/docs/_sidebar.md b/docs/_sidebar.md deleted file mode 100644 index 6cbe725286..0000000000 --- a/docs/_sidebar.md +++ /dev/null @@ -1,43 +0,0 @@ -- Home - - - [Welcome](/) - -- Getting started - - - [Key Components](key-components.md) - - [Quick Start](quick-start.md) - - [Setup](setup.md) - - [Tutorials](tutorials.md) - - [Docker](docker.md) - -- Advanced - - - [Configuration](configuration.md) - - [Data Structure](data-structure.md) - - [Database](database.md) - - [Keyboard Shortcuts](keyboard-shortcuts.md) - - [Node Basics](node-basics.md) - - [Nodes](nodes.md) - - [Security](security.md) - - [Sensitive Data](sensitive-data.md) - - [Server Setup](server-setup.md) - - [Start Workflows via CLI](start-workflows-via-cli.md) - - [Workflow](workflow.md) - -- Development - - - [Create Node](create-node.md) - - [Development](development.md) - - -- Other - - - [FAQ](faq.md) - - [License](license.md) - - [Troubleshooting](troubleshooting.md) - - -- Links - - - [![Jobs](https://n8n.io/favicon.ico ':size=16')Jobs](https://jobs.n8n.io) - - [![Website](https://n8n.io/favicon.ico ':size=16')n8n.io](https://n8n.io) diff --git a/docs/configuration.md b/docs/configuration.md deleted file mode 100644 index 63b8c95f12..0000000000 --- a/docs/configuration.md +++ /dev/null @@ -1,244 +0,0 @@ - - -# Configuration - -It is possible to change some of the n8n defaults via special environment variables. -The ones that currently exist are: - - -## Publish - -Sets how n8n should be made available. - -```bash -# The port n8n should be made available on -N8N_PORT=5678 - -# The IP address n8n should listen on -N8N_LISTEN_ADDRESS=0.0.0.0 - -# This ones are currently only important for the webhook URL creation. -# So if "WEBHOOK_TUNNEL_URL" got set they do get ignored. It is however -# encouraged to set them correctly anyway in case they will become -# important in the future. -N8N_PROTOCOL=https -N8N_HOST=n8n.example.com -``` - - -## Base URL - -Tells the frontend how to reach the REST API of the backend. - -```bash -export VUE_APP_URL_BASE_API="https://n8n.example.com/" -``` - - -## Execution Data Manual Runs - -n8n creates a random encryption key automatically on the first launch and saves -it in the `~/.n8n` folder. That key is used to encrypt the credentials before -they get saved to the database. It is also possible to overwrite that key and -set it via an environment variable. - -```bash -export N8N_ENCRYPTION_KEY="" -``` - - -## Execution Data Manual Runs - -Normally executions which got started via the Editor UI will not be saved as -they are normally only for testing and debugging. That default can be changed -with this environment variable. - -```bash -export EXECUTIONS_DATA_SAVE_MANUAL_EXECUTIONS=true -``` - -This setting can also be overwritten on a per workflow basis in the workflow -settings in the Editor UI. - - -## Execution Data Error/Success - -When a workflow gets executed, it will save the result in the database. That's -the case for executions that succeeded and for the ones that failed. The -default behavior can be changed like this: - -```bash -export EXECUTIONS_DATA_SAVE_ON_ERROR=none -export EXECUTIONS_DATA_SAVE_ON_SUCCESS=none -``` - -Possible values are: - - **all**: Saves all data - - **none**: Does not save anything (recommended if a workflow runs very often and/or processes a lot of data, set up "Error Workflow" instead) - -These settings can also be overwritten on a per workflow basis in the workflow -settings in the Editor UI. - - -## Execute In Same Process - -All workflows get executed in their own separate process. This ensures that all CPU cores -get used and that they do not block each other on CPU intensive tasks. Additionally, this makes sure that -the crash of one execution does not take down the whole application. The disadvantage is, however, -that it slows down the start-time considerably and uses much more memory. So in case the -workflows are not CPU intensive and they have to start very fast, it is possible to run them -all directly in the main-process with this setting. - -```bash -export EXECUTIONS_PROCESS=main -``` - - -## Exclude Nodes - -It is possible to not allow users to use nodes of a specific node type. For example, if you -do not want that people can write data to the disk with the "n8n-nodes-base.writeBinaryFile" -node and that they cannot execute commands with the "n8n-nodes-base.executeCommand" node, you can -set the following: - -```bash -export NODES_EXCLUDE="[\"n8n-nodes-base.executeCommand\",\"n8n-nodes-base.writeBinaryFile\"]" -``` - - -## Custom Nodes Location - -Every user can add custom nodes that get loaded by n8n on startup. The default -location is in the subfolder `.n8n/custom` of the user who started n8n. -Additional folders can be defined with an environment variable. - -```bash -export N8N_CUSTOM_EXTENSIONS="/home/jim/n8n/custom-nodes;/data/n8n/nodes" -``` - - -## Use built-in and external modules in Function-Nodes - -For security reasons, importing modules is restricted by default in the Function-Nodes. -It is, however, possible to lift that restriction for built-in and external modules by -setting the following environment variables: -- `NODE_FUNCTION_ALLOW_BUILTIN`: For builtin modules -- `NODE_FUNCTION_ALLOW_EXTERNAL`: For external modules sourced from n8n/node_modules directory. External module support is disabled when env variable is not set. - -```bash -# Allows usage of all builtin modules -export NODE_FUNCTION_ALLOW_BUILTIN=* - -# Allows usage of only crypto -export NODE_FUNCTION_ALLOW_BUILTIN=crypto - -# Allows usage of only crypto and fs -export NODE_FUNCTION_ALLOW_BUILTIN=crypto,fs - -# Allow usage of external npm modules. Wildcard matching is not supported. -export NODE_FUNCTION_ALLOW_EXTERNAL=moment,lodash -``` - - -## SSL - -It is possible to start n8n with SSL enabled by supplying a certificate to use: - - -```bash -export N8N_PROTOCOL=https -export N8N_SSL_KEY=/data/certs/server.key -export N8N_SSL_CERT=/data/certs/server.pem -``` - - - -## Timezone - -The timezone is set by default to "America/New_York". For instance, it is used by the -Cron node to know at what time the workflow should be started. To set a different -default timezone simply set `GENERIC_TIMEZONE` to the appropriate value. For example, -if you want to set the timezone to Berlin (Germany): - -```bash -export GENERIC_TIMEZONE="Europe/Berlin" -``` - -You can find the name of your timezone here: -[https://momentjs.com/timezone/](https://momentjs.com/timezone/) - - -## User Folder - -User-specific data like the encryption key, SQLite database file, and -the ID of the tunnel (if used) gets saved by default in the subfolder -`.n8n` of the user who started n8n. It is possible to overwrite the -user-folder via an environment variable. - -```bash -export N8N_USER_FOLDER="/home/jim/n8n" -``` - - -## Webhook URL - -The webhook URL will normally be created automatically by combining -`N8N_PROTOCOL`, `N8N_HOST` and `N8N_PORT`. However, if n8n runs behind a -reverse proxy that would not work. That's because n8n runs internally -on port 5678 but is exposed to the web via the reverse proxy on port 443. In -that case, it is important to set the webhook URL manually so that it can be -displayed correctly in the Editor UI and even more important is that the correct -webhook URLs get registred with the external services. - -```bash -export WEBHOOK_TUNNEL_URL="https://n8n.example.com/" -``` - - -## Configuration via file - -It is also possible to configure n8n using a configuration file. - -It is not necessary to define all values but only the ones that should be -different from the defaults. - -If needed multiple files can also be supplied to. For example, have generic -base settings and some specific ones depending on the environment. - -The path to the JSON configuration file to use can be set using the environment -variable `N8N_CONFIG_FILES`. - -```bash -# Single file -export N8N_CONFIG_FILES=/folder/my-config.json - -# Multiple files can be comma-separated -export N8N_CONFIG_FILES=/folder/my-config.json,/folder/production.json -``` - -A possible configuration file could look like this: -```json -{ - "executions": { - "process": "main", - "saveDataOnSuccess": "none" - }, - "generic": { - "timezone": "Europe/Berlin" - }, - "security": { - "basicAuth": { - "active": true, - "user": "frank", - "password": "some-secure-password" - } - }, - "nodes": { - "exclude": "[\"n8n-nodes-base.executeCommand\",\"n8n-nodes-base.writeBinaryFile\"]" - } -} -``` - -All possible values which can be set and their defaults can be found here: - -[https://github.com/n8n-io/n8n/blob/master/packages/cli/config/index.ts](https://github.com/n8n-io/n8n/blob/master/packages/cli/config/index.ts) diff --git a/docs/create-node.md b/docs/create-node.md deleted file mode 100644 index aa19393983..0000000000 --- a/docs/create-node.md +++ /dev/null @@ -1,145 +0,0 @@ -# Create Node - -It is quite easy to create your own nodes in n8n. Mainly three things have to be defined: - - 1. Generic information like name, description, image/icon - 1. The parameters to display via which the user can interact with it - 1. The code to run once the node gets executed - -To simplify the development process, we created a very basic CLI which creates boilerplate code to get started, builds the node (as they are written in TypeScript), and copies it to the correct location. - - -## Create the first basic node - - 1. Install the n8n-node-dev CLI: `npm install -g n8n-node-dev` - 1. Create and go into the newly created folder in which you want to keep the code of the node - 1. Use CLI to create boilerplate node code: `n8n-node-dev new` - 1. Answer the questions (the “Execute” node type is the regular node type that you probably want to create). - It will then create the node in the current folder. - 1. Program… Add the functionality to the node - 1. Build the node and copy to correct location: `n8n-node-dev build` - That command will build the JavaScript version of the node from the TypeScript code and copy it to the user folder where custom nodes get read from `~/.n8n/custom/` - 1. Restart n8n and refresh the window so that the new node gets displayed - - -## Create own custom n8n-nodes-module - -If you want to create multiple custom nodes which are either: - - - Only for yourself/your company - - Are only useful for a small number of people - - Require many or large dependencies - -It is best to create your own `n8n-nodes-module` which can be installed separately. -That is a simple npm package that contains the nodes and is set up in a way -that n8n can automatically find and load them on startup. - -When creating such a module the following rules have to be followed that n8n -can automatically find the nodes in the module: - - - The name of the module has to start with `n8n-nodes-` - - The `package.json` file has to contain a key `n8n` with the paths to nodes and credentials - - The module has to be installed alongside n8n - -An example starter module which contains one node and credentials and implements -the above can be found here: - -[https://github.com/n8n-io/n8n-nodes-starter](https://github.com/n8n-io/n8n-nodes-starter) - - -### Setup to use n8n-nodes-module - -To use a custom `n8n-nodes-module`, it simply has to be installed alongside n8n. -For example like this: - -```bash -# Create folder for n8n installation -mkdir my-n8n -cd my-n8n - -# Install n8n -npm install n8n - -# Install custom nodes module -npm install n8n-nodes-my-custom-nodes - -# Start n8n -n8n -``` - - -### Development/Testing of custom n8n-nodes-module - -This works in the same way as for any other npm module. - -Execute in the folder which contains the code of the custom `n8n-nodes-module` -which should be loaded with n8n: - -```bash -# Build the code -npm run build - -# "Publish" the package locally -npm link -``` - -Then in the folder in which n8n is installed: - -```bash -# "Install" the above locally published module -npm link n8n-nodes-my-custom-nodes - -# Start n8n -n8n -``` - - - -## Node Development Guidelines - - -Please make sure that everything works correctly and that no unnecessary code gets added. It is important to follow the following guidelines: - - -### Do not change incoming data - -Never change the incoming data a node receives (which can be queried with `this.getInputData()`) as it gets shared by all nodes. If data has to get added, changed or deleted it has to be cloned and the new data returned. If that is not done, sibling nodes which execute after the current one will operate on the altered data and would process different data than they were supposed to. -It is however not needed to always clone all the data. If a node for, example only, changes only the binary data but not the JSON data, a new item can be created which reuses the reference to the JSON item. - -An example can be seen in the code of the [ReadBinaryFile-Node](https://github.com/n8n-io/n8n/blob/master/packages/nodes-base/nodes/ReadBinaryFile.node.ts#L69-L83). - - -### Write nodes in TypeScript - -All code of n8n is written in TypeScript and hence, the nodes should also be written in TypeScript. That makes development easier, faster, and avoids at least some bugs. - - -### Use the built in request library - -Some third-party services have their own libraries on npm which make it easier to create an integration. It can be quite tempting to use them. The problem with those is that you add another dependency and not just one you add but also all the dependencies of the dependencies. This means more and more code gets added, has to get loaded, can introduce security vulnerabilities, bugs and so on. So please use the built-in module which can be used like this: - -```typescript -const response = await this.helpers.request(options); -``` - -That is simply using the npm package [`request-promise-native`](https://github.com/request/request-promise-native) which is the basic npm `request` module but with promises. For a full set of `options` consider looking at [the underlying `request` options documentation](https://github.com/request/request#requestoptions-callback). - - -### Reuse parameter names - -When a node can perform multiple operations like edit and delete some kind of entity, for both operations, it would need an entity-id. Do not call them "editId" and "deleteId" simply call them "id". n8n can handle multiple parameters with the same name without a problem as long as only one is visible. To make sure that is the case, the "displayOptions" can be used. By keeping the same name, the value can be kept if a user switches the operation from "edit" to "delete". - - -### Create an "Options" parameter - -Some nodes may need a lot of options. Add only the very important ones to the top level and for all others, create an "Options" parameter where they can be added if needed. This ensures that the interface stays clean and does not unnecessarily confuse people. A good example of that would be the XML node. - - -### Follow exiting parameter naming guideline - -There is not much of a guideline yet but if your node can do multiple things, call the parameter which sets the behavior either "mode" (like "Merge" and "XML" node) or "operation" like the most other ones. If these operations can be done on different resources (like "User" or "Order) create a "resource" parameter (like "Pipedrive" and "Trello" node) - - -### Node Icons - -Check existing node icons as a reference when you create own ones. The resolution of an icon should be 60x60px and saved as PNG. diff --git a/docs/data-structure.md b/docs/data-structure.md deleted file mode 100644 index daeea8474d..0000000000 --- a/docs/data-structure.md +++ /dev/null @@ -1,39 +0,0 @@ -# Data Structure - -For "basic usage" it is not necessarily needed to understand how the data that -gets passed from one node to another is structured. However, it becomes important if you want to: - - - create your own node - - write custom expressions - - use the Function or Function Item node - - you want to get the most out of n8n - - -In n8n, all the data that is passed between nodes is an array of objects. It has the following structure: - -```json -[ - { - // Each item has to contain a "json" property. But it can be an empty object like {}. - // Any kind of JSON data is allowed. So arrays and the data being deeply nested is fine. - json: { // The actual data n8n operates on (required) - // This data is only an example it could be any kind of JSON data - jsonKeyName: 'keyValue', - anotherJsonKey: { - lowerLevelJsonKey: 1 - } - }, - // Binary data of item. The most items in n8n do not contain any (optional) - binary: { - // The key-name "binaryKeyName" is only an example. Any kind of key-name is possible. - binaryKeyName: { - data: '....', // Base64 encoded binary data (required) - mimeType: 'image/png', // Optional but should be set if possible (optional) - fileExtension: 'png', // Optional but should be set if possible (optional) - fileName: 'example.png', // Optional but should be set if possible (optional) - } - } - }, - ... -] -``` diff --git a/docs/database.md b/docs/database.md deleted file mode 100644 index 041520cf15..0000000000 --- a/docs/database.md +++ /dev/null @@ -1,109 +0,0 @@ -# Database - -By default, n8n uses SQLite to save credentials, past executions, and workflows. However, -n8n also supports MongoDB and PostgresDB. - - -## Shared Settings - -The following environment variables get used by all databases: - - - `DB_TABLE_PREFIX` (default: '') - Prefix for table names - - -## MongoDB - -!> **WARNING**: Use PostgresDB, if possible! MongoDB has problems saving large - amounts of data in a document, among other issues. So, support - may be dropped in the future. - -To use MongoDB as the database, you can provide the following environment variables like -in the example below: - - `DB_TYPE=mongodb` - - `DB_MONGODB_CONNECTION_URL=` - -Replace the following placeholders with the actual data: - - MONGO_DATABASE - - MONGO_HOST - - MONGO_PORT - - MONGO_USER - - MONGO_PASSWORD - -```bash -export DB_TYPE=mongodb -export DB_MONGODB_CONNECTION_URL=mongodb://MONGO_USER:MONGO_PASSWORD@MONGO_HOST:MONGO_PORT/MONGO_DATABASE -n8n start -``` - - -## PostgresDB - -To use PostgresDB as the database, you can provide the following environment variables - - `DB_TYPE=postgresdb` - - `DB_POSTGRESDB_DATABASE` (default: 'n8n') - - `DB_POSTGRESDB_HOST` (default: 'localhost') - - `DB_POSTGRESDB_PORT` (default: 5432) - - `DB_POSTGRESDB_USER` (default: 'root') - - `DB_POSTGRESDB_PASSWORD` (default: empty) - - `DB_POSTGRESDB_SCHEMA` (default: 'public') - - -```bash -export DB_TYPE=postgresdb -export DB_POSTGRESDB_DATABASE=n8n -export DB_POSTGRESDB_HOST=postgresdb -export DB_POSTGRESDB_PORT=5432 -export DB_POSTGRESDB_USER=n8n -export DB_POSTGRESDB_PASSWORD=n8n -export DB_POSTGRESDB_SCHEMA=n8n - -n8n start -``` - -## MySQL / MariaDB - -The compatibility with MySQL/MariaDB has been tested. Even then, it is advisable to observe the operation of the application with this database as this option has been recently added. If you spot any problems, feel free to submit a burg report or a pull request. - -To use MySQL as database you can provide the following environment variables: - - `DB_TYPE=mysqldb` or `DB_TYPE=mariadb` - - `DB_MYSQLDB_DATABASE` (default: 'n8n') - - `DB_MYSQLDB_HOST` (default: 'localhost') - - `DB_MYSQLDB_PORT` (default: 3306) - - `DB_MYSQLDB_USER` (default: 'root') - - `DB_MYSQLDB_PASSWORD` (default: empty) - - -```bash -export DB_TYPE=mysqldb -export DB_MYSQLDB_DATABASE=n8n -export DB_MYSQLDB_HOST=mysqldb -export DB_MYSQLDB_PORT=3306 -export DB_MYSQLDB_USER=n8n -export DB_MYSQLDB_PASSWORD=n8n - -n8n start -``` - -## SQLite - -This is the default database that gets used if nothing is defined. - -The database file is located at: -`~/.n8n/database.sqlite` - - -## Other Databases - -Currently, only the databases mentioned above are supported. n8n internally uses -[TypeORM](https://typeorm.io), so adding support for the following databases -should not be too much work: - - - CockroachDB - - Microsoft SQL - - Oracle - -If you cannot use any of the currently supported databases for some reason and -you can code, we'd appreciate your support in the form of a pull request. If not, you can request -for support here: - -[https://community.n8n.io/c/feature-requests/cli](https://community.n8n.io/c/feature-requests/cli) diff --git a/docs/development.md b/docs/development.md deleted file mode 100644 index d7d8de4744..0000000000 --- a/docs/development.md +++ /dev/null @@ -1,3 +0,0 @@ -# Development - -Have you found a bug :bug:? Or maybe you have a nice feature :sparkles: to contribute? The [CONTRIBUTING guide](https://github.com/n8n-io/n8n/blob/master/CONTRIBUTING.md) will help you get your development environment ready in minutes. diff --git a/docs/docker.md b/docs/docker.md deleted file mode 100644 index 317b5b9552..0000000000 --- a/docs/docker.md +++ /dev/null @@ -1,7 +0,0 @@ -# Docker - -Detailed information about how to run n8n in Docker can be found in the README -of the [Docker Image](https://github.com/n8n-io/n8n/blob/master/docker/images/n8n/README.md). - -A basic step by step example setup of n8n with docker-compose and Let's Encrypt is available on the -[Server Setup](server-setup.md) page. diff --git a/docs/faq.md b/docs/faq.md deleted file mode 100644 index 2b03a0b76d..0000000000 --- a/docs/faq.md +++ /dev/null @@ -1,47 +0,0 @@ -# FAQ - -## Integrations - - -### Can you create an integration for service X? - -You can request new integrations to be added to our forum. There is a special section for that where -other users can also upvote it so that we know which integrations are important and should be -created next. Request a new feature [here](https://community.n8n.io/c/feature-requests/nodes). - - -### An integration exists already but a feature is missing. Can you add it? - -Adding new functionality to an existing integration is normally not that complicated. So the chance is -high that we can do that quite fast. Post your feature request in the forum and we'll see -what we can do. Request a new feature [here](https://community.n8n.io/c/feature-requests/nodes). - - -### How can I create an integration myself? - -Information about that can be found in the [CONTRIBUTING guide](https://github.com/n8n-io/n8n/blob/master/CONTRIBUTING.md). - - -## License - - -### Which license does n8n use? - -n8n is [fair-code](http://faircode.io) licensed under [Apache 2.0 with Commons Clause](https://github.com/n8n-io/n8n/blob/master/packages/cli/LICENSE.md) - - -### Is n8n open-source? - -No. The [Commons Clause](https://commonsclause.com) that is attached to the Apache 2.0 license takes away some rights. Hence, according to the definition of the [Open Source Initiative (OSI)](https://opensource.org/osd), n8n is not open-source. Nonetheless, the source code is open and everyone (individuals and companies) can use it for free. However, it is not allowed to make money directly with n8n. - -For instance, one cannot charge others to host or support n8n. However, to make things simpler, we grant everyone (individuals and companies) the right to offer consulting or support without prior permission as long as it is less than 30,000 USD ($30k) per annum. -If your revenue from services based on n8n is greater than $30k per annum, we'd invite you to become a partner and apply for a license. If you have any questions about this, feel free to reach out to us at [license@n8n.io](mailto:license@n8n.io). - - -### Why is n8n not open-source but [fair-code](http://faircode.io) licensed instead? - -We love open-source and the idea that everybody can freely use and extend what we wrote. Our community is at the heart of everything that we do and we understand that people who contribute to a project are the main drivers that push a project forward. So to make sure that the project continues to evolve and stay alive in the longer run, we decided to attach the Commons Clause. This ensures that no other person or company can make money directly with n8n. Especially if it competes with how we plan to finance our further development. For the greater majority of the people, it will not make any difference at all. At the same time, it protects the project. - -As n8n itself depends on and uses a lot of other open-source projects, it is only fair that we support them back. That is why we have planned to contribute a certain percentage of revenue/profit every month to these projects. - -We have already started with the first monthly contributions via [Open Collective](https://opencollective.com/n8n). It is not much yet, but we hope to be able to ramp that up substantially over time. diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index bd53af45e6..0000000000 --- a/docs/index.html +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - n8n Documentation - - - - - - - - -
- - - - - - - - - - - - - diff --git a/docs/key-components.md b/docs/key-components.md deleted file mode 100644 index 9caba3a0b0..0000000000 --- a/docs/key-components.md +++ /dev/null @@ -1,25 +0,0 @@ -# Key Components - - -## Connection - -A connection establishes a link between nodes to route data through the workflow. Each node can have one or multiple connections. - - -## Node - -A node is an entry point for retrieving data, a function to process data or an exit for sending data. The data process includes filtering, recomposing and changing data. There can be one or several nodes for your API, service or app. You can easily connect multiple nodes, which allows you to create simple and complex workflows with them intuitively. - -For example, consider a Google Sheets node. It can be used to retrieve or write data to a Google Sheet. - - -## Trigger Node - -A trigger node is a node that starts a workflow and supplies the initial data. What triggers it, depends on the node. It could be the time, a webhook call or an event from an external service. - -For example, consider a Trello trigger node. When a Trello Board gets updated, it will trigger a workflow to start using the data from the updated board. - - -## Workflow - -A workflow is a canvas on which you can place and connect nodes. A workflow can be started manually or by trigger nodes. A workflow run ends when all active and connected nodes have processed their data. diff --git a/docs/keyboard-shortcuts.md b/docs/keyboard-shortcuts.md deleted file mode 100644 index ace6db8d8e..0000000000 --- a/docs/keyboard-shortcuts.md +++ /dev/null @@ -1,28 +0,0 @@ -# Keyboard Shortcuts - -The following keyboard shortcuts can currently be used: - -## General - - - **Ctrl + Left Mouse Button**: Move/Pan Node View - - **Ctrl + a**: Select all nodes - - **Ctrl + Alt + n**: Create new workflow - - **Ctrl + o**: Open workflow - - **Ctrl + s**: Save the current workflow - - **Ctrl + v**: Paste nodes - - **Tab**: Open "Node Creator". Type to filter and navigate with arrow keys. To create press "enter" - - -## With node(s) selected - - - **ArrowDown**: Select sibling node bellow the current one - - **ArrowLeft**: Select node left of the current one - - **ArrowRight**: Select node right of the current one - - **ArrowUp**: Select sibling node above the current one - - **Ctrl + c**: Copy nodes - - **Ctrl + x**: Cut nodes - - **d**: Deactivate nodes - - **Delete**: Delete nodes - - **F2**: Rename node - - **Shift + ArrowLeft**: Select all nodes left of the current one - - **Shift + ArrowRight**: Select all nodes right of the current one diff --git a/docs/license.md b/docs/license.md deleted file mode 100644 index ace732e676..0000000000 --- a/docs/license.md +++ /dev/null @@ -1,5 +0,0 @@ -# License - -n8n is [fair-code](http://faircode.io) licensed under [Apache 2.0 with Commons Clause](https://github.com/n8n-io/n8n/blob/master/packages/cli/LICENSE.md) - -Additional information about the license can be found in the [FAQ](faq.md?id=license) and [fair-code](http://faircode.io). diff --git a/docs/node-basics.md b/docs/node-basics.md deleted file mode 100644 index aea6bf6e33..0000000000 --- a/docs/node-basics.md +++ /dev/null @@ -1,76 +0,0 @@ -# Node Basics - - -## Types - -There are two main node types in n8n: Trigger nodes and Regular nodes. - - -### Trigger Nodes - -The Trigger nodes start a workflow and supply the initial data. A workflow can contain multiple trigger nodes but with each execution, only one of them will execute. This is because the other trigger nodes would not have any input as they are the nodes from which the execution of the workflow starts. - - -### Regular Nodes - -These nodes do the actual work. They can add, remove, and edit the data in the flow as well as request and send data to external APIs. They can do everything possible with Node.js in general. - - -## Credentials - -External services need a way to identify and authenticate users. This data can range from an API key over an email/password combination to a very long multi-line private key and can be saved in n8n as credentials. - -Nodes in n8n can then request that credential information. As an additional layer of security credentials can only be accessed by node types which specifically have the right to do so. - -To make sure that the data is secure, it gets saved to the database encrypted. A random personal encryption key is used which gets automatically generated on the first run of n8n and then saved under `~/.n8n/config`. - - -## Expressions - -With the help of expressions, it is possible to set node parameters dynamically by referencing other data. That can be data from the flow, nodes, the environment or self-generated data. Expressions are normal text with placeholders (everything between {{...}}) that can execute JavaScript code, which offers access to special variables to access data. - -An expression could look like this: - -My name is: `{{$node["Webhook"].json["query"]["name"]}}` - -This one would return "My name is: " and then attach the value that the node with the name "Webhook" outputs and there select the property "query" and its key "name". So if the node would output this data: - -```json -{ - "query": { - "name": "Jim" - } -} -``` - -the value would be: "My name is: Jim" - -The following special variables are available: - - - **$binary**: Incoming binary data of a node - - **$evaluateExpression**: Evaluates a string as expression - - **$env**: Environment variables - - **$items**: Environment variables - - **$json**: Incoming JSON data of a node - - **$node**: Data of other nodes (binary, context, json, parameter, runIndex) - - **$parameters**: Parameters of the current node - - **$runIndex**: The current run index (first time node gets executed it is 0, second time 1, ...) - - **$workflow**: Returns workflow metadata like: active, id, name - -Normally it is not needed to write the JavaScript variables manually as they can be selected with the help of the Expression Editor. - - -## Parameters - -Parameters can be set for most nodes in n8n. The values that get set define what exactly a node does. - -Parameter values are static by default and are always the same no matter what kind of data the node processes. However, it is possible to set the values dynamically with the help of an Expression. Using Expressions, it is possible to make the parameter value dependent on other factors like the data of flow or parameters of other nodes. - -More information about it can be found under [Expressions](#expressions). - - -## Pausing Node - -Sometimes when creating and debugging a workflow, it is helpful to not execute specific nodes. To do that without disconnecting each node, you can pause them. When a node gets paused, the data passes through the node without being changed. - -There are two ways to pause a node. You can either press the pause button which gets displayed above the node when hovering over it or select the node and press “d”. diff --git a/docs/nodes.md b/docs/nodes.md deleted file mode 100644 index 8b9c7cbf0e..0000000000 --- a/docs/nodes.md +++ /dev/null @@ -1,247 +0,0 @@ -# Nodes - -## Function and Function Item Nodes - -These are the most powerful nodes in n8n. With these, almost everything can be done if you know how to -write JavaScript code. Both nodes work very similarly. They give you access to the incoming data -and you can manipulate it. - - -### Difference between both nodes - -The difference is that the code of the Function node gets executed only once. It receives the -full items (JSON and binary data) as an array and expects an array of items as a return value. The items -returned can be totally different from the incoming ones. So it is not only possible to remove and edit -existing items, but also to add or return totally new ones. - -The code of the Function Item node on the other hand gets executed once for every item. It receives -one item at a time as input and also just the JSON data. As a return value, it expects the JSON data -of one single item. That makes it possible to add, remove and edit JSON properties of items -but it is not possible to add new or remove existing items. Accessing and changing binary data is only -possible via the methods `getBinaryData` and `setBinaryData`. - -Both nodes support promises. So instead of returning the item or items directly, it is also possible to -return a promise which resolves accordingly. - - -### Function-Node - -#### Variable: items - -It contains all the items that the node received as input. - -Information about how the data is structured can be found on the page [Data Structure](data-structure.md). - -The data can be accessed and manipulated like this: - -```typescript -// Sets the JSON data property "myFileName" of the first item to the name of the -// file which is set in the binary property "image" of the same item. -items[0].json.myFileName = items[0].binary.image.fileName; - -return items; -``` - -This example creates 10 dummy items with the ids 0 to 9: - -```typescript -const newItems = []; - -for (let i=0;i<10;i++) { - newItems.push({ - json: { - id: i - } - }); -} - -return newItems; -``` - - -#### Method: $item(index: number, runIndex?: number) - -With `$item` it is possible to access the data of parent nodes. That can be the item data but also -the parameters. It expects as input an index of the item the data should be returned for. This is -needed because for each item the data returned can be different. This is probably obvious for the -item data itself but maybe less for data like parameters. The reason why it is also needed, is -that they may contain an expression. Expressions get always executed of the context for an item. -If that would not be the case, for example, the Email Send node not would be able to send multiple -emails at once to different people. Instead, the same person would receive multiple emails. - -The index is 0 based. So `$item(0)` will return the first item, `$item(1)` the second one, ... - -By default the item of the last run of the node will be returned. So if the referenced node ran -3x (its last runIndex is 2) and the current node runs the first time (its runIndex is 0) the -data of runIndex 2 of the referenced node will be returned. - -For more information about what data can be accessed via $node, check [here](#variable-node). - -Example: - -```typescript -// Returns the value of the JSON data property "myNumber" of Node "Set" (first item) -const myNumber = $item(0).$node["Set"].json["myNumber"]; -// Like above but data of the 6th item -const myNumber = $item(5).$node["Set"].json["myNumber"]; - -// Returns the value of the parameter "channel" of Node "Slack". -// If it contains an expression the value will be resolved with the -// data of the first item. -const channel = $item(0).$node["Slack"].parameter["channel"]; -// Like above but resolved with the value of the 10th item. -const channel = $item(9).$node["Slack"].parameter["channel"]; -``` - - -#### Method: $items(nodeName?: string, outputIndex?: number, runIndex?: number) - -Gives access to all the items of current or parent nodes. If no parameters get supplied, -it returns all the items of the current node. -If a node-name is given, it returns the items the node output on its first output -(index: 0, most nodes only have one output, exceptions are IF and Switch-Node) on -its last run. - -Example: - -```typescript -// Returns all the items of the current node and current run -const allItems = $items(); - -// Returns all items the node "IF" outputs (index: 0 which is Output "true" of its most recent run) -const allItems = $items("IF"); - -// Returns all items the node "IF" outputs (index: 0 which is Output "true" of the same run as current node) -const allItems = $items("IF", 0, $runIndex); - -// Returns all items the node "IF" outputs (index: 1 which is Output "false" of run 0 which is the first run) -const allItems = $items("IF", 1, 0); -``` - - -#### Variable: $node - -Works exactly like `$item` with the difference that it will always return the data of the first item and -the last run of the node. - -```typescript -// Returns the fileName of binary property "data" of Node "HTTP Request" -const fileName = $node["HTTP Request"].binary["data"]["fileName"]}} - -// Returns the context data "noItemsLeft" of Node "SplitInBatches" -const noItemsLeft = $node["SplitInBatches"].context["noItemsLeft"]; - -// Returns the value of the JSON data property "myNumber" of Node "Set" -const myNumber = $node["Set"].json['myNumber']; - -// Returns the value of the parameter "channel" of Node "Slack" -const channel = $node["Slack"].parameter["channel"]; - -// Returns the index of the last run of Node "HTTP Request" -const runIndex = $node["HTTP Request"].runIndex}} -``` - - -#### Variable: $runIndex - -Contains the index of the current run of the node. - -```typescript -// Returns all items the node "IF" outputs (index: 0 which is Output "true" of the same run as current node) -const allItems = $items("IF", 0, $runIndex); -``` - - -#### Variable: $workflow - -Gives information about the current workflow. - -```typescript -const isActive = $workflow.active; -const workflowId = $workflow.id; -const workflowName = $workflow.name; -``` - - -#### Method: $evaluateExpression(expression: string, itemIndex: number) - -Evaluates a given string as expression. -If no `itemIndex` is provided it uses by default in the Function-Node the data of item 0 and -in the Function Item-Node the data of the current item. - -Example: - -```javascript -items[0].json.variable1 = $evaluateExpression('{{1+2}}'); -items[0].json.variable2 = $evaluateExpression($node["Set"].json["myExpression"], 1); - -return items; -``` - - -#### Method: getWorkflowStaticData(type) - -Gives access to the static workflow data. -It is possible to save data directly with the workflow. This data should, however, be very small. -A common use case is to for example to save a timestamp of the last item that got processed from -an RSS-Feed or database. It will always return an object. Properties can then read, delete or -set on that object. When the workflow execution succeeds, n8n will check automatically if the data -has changed and will save it, if necessary. - -There are two types of static data. The "global" and the "node" one. Global static data is the -same in the whole workflow. And every node in the workflow can access it. The node static data -, however, is different for every node and only the node which set it can retrieve it again. - -Example: - -```javascript -// Get the global workflow static data -const staticData = getWorkflowStaticData('global'); -// Get the static data of the node -const staticData = getWorkflowStaticData('node'); - -// Access its data -const lastExecution = staticData.lastExecution; - -// Update its data -staticData.lastExecution = new Date().getTime(); - -// Delete data -delete staticData.lastExecution; -``` - -It is important to know that the static data can not be read and written when testing via the UI. -The data there will always be empty and the changes will not persist. Only when a workflow -is active and it gets called by a Trigger or Webhook, the static data will be saved. - - - -### Function Item-Node - - -#### Variable: item - -It contains the "json" data of the currently processed item. - -The data can be accessed and manipulated like this: - -```json -// Uses the data of an already existing key to create a new additional one -item.newIncrementedCounter = item.existingCounter + 1; -return item; -``` - - -#### Method: getBinaryData() - -Returns all the binary data (all keys) of the item which gets currently processed. - - -#### Method: setBinaryData(binaryData) - -Sets all the binary data (all keys) of the item which gets currently processed. - - -#### Method: getWorkflowStaticData(type) - -As described above for Function node. diff --git a/docs/quick-start.md b/docs/quick-start.md deleted file mode 100644 index 0c33cafbe8..0000000000 --- a/docs/quick-start.md +++ /dev/null @@ -1,43 +0,0 @@ -# Quick Start - - -## Give n8n a spin - -To spin up n8n, you can run: - -```bash -npx n8n -``` - -It will download everything that is needed to start n8n. - -You can then access n8n by opening: -[http://localhost:5678](http://localhost:5678) - - -## Start with docker - -To play around with n8n, you can also start it using docker: - -```bash -docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ - n8nio/n8n -``` - -Be aware that all the data will be lost once the docker container gets removed. To -persist the data mount the `~/.n8n` folder: - -```bash -docker run -it --rm \ - --name n8n \ - -p 5678:5678 \ - -v ~/.n8n:/root/.n8n \ - n8nio/n8n -``` - -More information about the Docker setup can be found in the README file of the -[Docker Image](https://github.com/n8n-io/n8n/blob/master/docker/images/n8n/README.md). - -In case you run into issues, check out the [troubleshooting](troubleshooting.md) page or ask for help in the community [forum](https://community.n8n.io/). diff --git a/docs/security.md b/docs/security.md deleted file mode 100644 index 5682b2c29a..0000000000 --- a/docs/security.md +++ /dev/null @@ -1,13 +0,0 @@ -# Security - -By default, n8n can be accessed by everybody. This is okay if you only have it running -locally but if you deploy it on a server which is accessible from the web, you have -to make sure that n8n is protected. -Right now we have very basic protection in place using basic-auth. It can be activated -by setting the following environment variables: - -```bash -export N8N_BASIC_AUTH_ACTIVE=true -export N8N_BASIC_AUTH_USER= -export N8N_BASIC_AUTH_PASSWORD= -``` diff --git a/docs/sensitive-data.md b/docs/sensitive-data.md deleted file mode 100644 index fa7b0bb1b6..0000000000 --- a/docs/sensitive-data.md +++ /dev/null @@ -1,18 +0,0 @@ -# Sensitive Data via File - -To avoid passing sensitive information via environment variables, "_FILE" may be -appended to some environment variables. It will then load the data from a file -with the given name. That makes it possible to load data easily from -Docker and Kubernetes secrets. - -The following environment variables support file input: - - - DB_MONGODB_CONNECTION_URL_FILE - - DB_POSTGRESDB_DATABASE_FILE - - DB_POSTGRESDB_HOST_FILE - - DB_POSTGRESDB_PASSWORD_FILE - - DB_POSTGRESDB_PORT_FILE - - DB_POSTGRESDB_USER_FILE - - DB_POSTGRESDB_SCHEMA_FILE - - N8N_BASIC_AUTH_PASSWORD_FILE - - N8N_BASIC_AUTH_USER_FILE diff --git a/docs/server-setup.md b/docs/server-setup.md deleted file mode 100644 index d34d076a6f..0000000000 --- a/docs/server-setup.md +++ /dev/null @@ -1,183 +0,0 @@ -# Server Setup - -!> ***Important***: Make sure that you secure your n8n instance as described under [Security](security.md). - - -## Example setup with docker-compose - -If you have already installed docker and docker-compose, then you can directly start with step 4. - - -### 1. Install Docker - -This can vary depending on the Linux distribution used. Example bellow is for Ubuntu: - -```bash -sudo apt update -sudo apt install apt-transport-https ca-certificates curl software-properties-common -curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - -sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable" -sudo apt update -sudo apt install docker-ce -y -``` - -### 2. Optional: If it should run as not root user - -Run when logged in as the user that should also be allowed to run docker: - -```bash -sudo usermod -aG docker ${USER} -su - ${USER} -``` - -### 3. Install Docker-compose - -This can vary depending on the Linux distribution used. Example bellow is for Ubuntu: - -Check before what version the latestand replace "1.24.1" with that version accordingly. -https://github.com/docker/compose/releases - -```bash -sudo curl -L https://github.com/docker/compose/releases/download/1.24.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose -sudo chmod +x /usr/local/bin/docker-compose -``` - - -### 4. Setup DNS - -Add A record to route the subdomain accordingly. - -``` -Type: A -Name: n8n (or whatever the subdomain should be) -IP address: -``` - - -### 5. Create docker-compose file - -Save this file as `docker-compose.yml` - -Normally no changes should be needed. - -```yaml -version: "3" - -services: - traefik: - image: "traefik" - command: - - "--api=true" - - "--api.insecure=true" - - "--providers.docker=true" - - "--providers.docker.exposedbydefault=false" - - "--entrypoints.websecure.address=:443" - - "--certificatesresolvers.mytlschallenge.acme.tlschallenge=true" - - "--certificatesresolvers.mytlschallenge.acme.email=${SSL_EMAIL}" - - "--certificatesresolvers.mytlschallenge.acme.storage=/letsencrypt/acme.json" - ports: - - "443:443" - volumes: - - ${DATA_FOLDER}/letsencrypt:/letsencrypt - - /var/run/docker.sock:/var/run/docker.sock:ro - - n8n: - image: n8nio/n8n - ports: - - "127.0.0.1:5678:5678" - labels: - - traefik.enable=true - - traefik.http.routers.n8n.rule=Host(`${SUBDOMAIN}.${DOMAIN_NAME}`) - - traefik.http.routers.n8n.tls=true - - traefik.http.routers.n8n.entrypoints=websecure - - traefik.http.routers.n8n.tls.certresolver=mytlschallenge - - traefik.http.middlewares.n8n.headers.SSLRedirect=true - - traefik.http.middlewares.n8n.headers.STSSeconds=315360000 - - traefik.http.middlewares.n8n.headers.browserXSSFilter=true - - traefik.http.middlewares.n8n.headers.contentTypeNosniff=true - - traefik.http.middlewares.n8n.headers.forceSTSHeader=true - - traefik.http.middlewares.n8n.headers.SSLHost=${DOMAIN_NAME} - - traefik.http.middlewares.n8n.headers.STSIncludeSubdomains=true - - traefik.http.middlewares.n8n.headers.STSPreload=true - environment: - - N8N_BASIC_AUTH_ACTIVE=true - - N8N_BASIC_AUTH_USER - - N8N_BASIC_AUTH_PASSWORD - - N8N_HOST=${SUBDOMAIN}.${DOMAIN_NAME} - - N8N_PORT=5678 - - N8N_LISTEN_ADDRESS=0.0.0.0 - - N8N_PROTOCOL=https - - NODE_ENV=production - - WEBHOOK_TUNNEL_URL=https://${SUBDOMAIN}.${DOMAIN_NAME}/ - - VUE_APP_URL_BASE_API=https://${SUBDOMAIN}.${DOMAIN_NAME}/ - volumes: - - /var/run/docker.sock:/var/run/docker.sock - - ${DATA_FOLDER}/.n8n:/root/.n8n -``` - - -### 6. Create `.env` file - -Create `.env` file and change it accordingly. - -```bash -# Folder where data should be saved -DATA_FOLDER=/root/n8n/ - -# The top level domain to serve from -DOMAIN_NAME=example.com - -# The subdomain to serve from -SUBDOMAIN=n8n - -# DOMAIN_NAME and SUBDOMAIN combined decide where n8n will be reachable from -# above example would result in: https://n8n.example.com - -# The user name to use for autentication - IMPORTANT ALWAYS CHANGE! -N8N_BASIC_AUTH_USER=user - -# The password to use for autentication - IMPORTANT ALWAYS CHANGE! -N8N_BASIC_AUTH_PASSWORD=password - -# Optional timezone to set which gets used by Cron-Node by default -# If not set New York time will be used -GENERIC_TIMEZONE=Europe/Berlin - -# The email address to use for the SSL certificate creation -SSL_EMAIL=user@example.com -``` - - -### 7. Create data folder - -Create the folder which is defined as `DATA_FOLDER`. In the example -above, it is `/root/n8n/`. - -In that folder, the database file from SQLite as well as the encryption key will be saved. - -The folder can be created like this: -``` -mkdir /root/n8n/ -``` - - -### 8. Start docker-compose setup - -n8n can now be started via: - -```bash -sudo docker-compose up -d -``` - -In case it should ever be stopped that can be done with this command: -```bash -sudo docker-compose stop -``` - - -### 9. Done - -n8n will now be reachable via the above defined subdomain + domain combination. -The above example would result in: https://n8n.example.com - -n8n will only be reachable via https and not via http. diff --git a/docs/setup.md b/docs/setup.md deleted file mode 100644 index 27e65e54ea..0000000000 --- a/docs/setup.md +++ /dev/null @@ -1,35 +0,0 @@ -# Setup - - -## Installation - -To install n8n globally: - -```bash -npm install n8n -g -``` - -## Start - -After the installation n8n can be started by simply typing in: - -```bash -n8n -# or -n8n start -``` - - -## Start with tunnel - -!> **WARNING**: This is only meant for local development and testing. It should not be used in production! - -To be able to use webhooks for trigger nodes of external services like GitHub, n8n has to be reachable from the web. To make that easy, n8n has a special tunnel service, which redirects requests from our servers to your local n8n instance (uses this code: [https://github.com/localtunnel/localtunnel](https://github.com/localtunnel/localtunnel)). - -To use it, simply start n8n with `--tunnel` - -```bash -n8n start --tunnel -``` - -In case you run into issues, check out the [troubleshooting](troubleshooting.md) page or ask for help in the community [forum](https://community.n8n.io/). diff --git a/docs/start-workflows-via-cli.md b/docs/start-workflows-via-cli.md deleted file mode 100644 index 6327f32963..0000000000 --- a/docs/start-workflows-via-cli.md +++ /dev/null @@ -1,15 +0,0 @@ -# Start Workflows via CLI - -Workflows cannot be only started by triggers, webhooks or manually via the -Editor. It is also possible to start them directly via the CLI. - -Execute a saved workflow by its ID: - -```bash -n8n execute --id -``` - -Execute a workflow from a workflow file: -```bash -n8n execute --file -``` diff --git a/docs/test.md b/docs/test.md deleted file mode 100644 index 02a308b3ad..0000000000 --- a/docs/test.md +++ /dev/null @@ -1,3 +0,0 @@ -# This is a simple test - -with some text diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md deleted file mode 100644 index 7e6b4b058b..0000000000 --- a/docs/troubleshooting.md +++ /dev/null @@ -1,58 +0,0 @@ -# Troubleshooting - -## Windows - -If you are experiencing issues running n8n with the typical flow of: - -```powershell -npx n8n -``` - -### Requirements - -Please ensure that you have the following requirements fulfilled: - -- Install latest version of [NodeJS](https://nodejs.org/en/download/) -- Install [Python 2.7](https://www.python.org/downloads/release/python-2717/) (It is okay to have multiple versions installed on the machine) -- Windows SDK -- C++ Desktop Development Tools -- Windows Build Tools - -#### Install build tools - -If you haven't satisfied the above, follow this procedure through your PowerShell (run with administrative privileges). -This command installs the build tools, windows SDK and the C++ development tools in one package. - -```powershell -npm install --global --production windows-build-tools -``` - -#### Configure npm to use Python version 2.7 - -```powershell -npm config set python python2.7 -``` - -#### Configure npm to use correct msvs version - -```powershell -npm config set msvs_version 2017 --global -``` - -### Lesser known issues: - -#### mmmagic npm package when using MSbuild tools with Visual Studio - -While installing this package, `node-gyp` is run and it might fail to install it with an error appearing in the ballpark of: - -``` -gyp ERR! stack Error: spawn C:\Program Files (x86)\Microsoft Visual Studio\2019\**Enterprise**\MSBuild\Current\Bin\MSBuild.exe ENOENT -``` - -It is seeking the `MSBuild.exe` in a directory that does not exist. If you are using Visual Studio Community or vice versa, you can change the path of MSBuild with command: - -```powershell -npm config set msbuild_path "C:\Program Files (x86)\Microsoft Visual Studio\2019\**Community**\MSBuild\Current\Bin\MSBuild.exe" -``` - -Attempt to install package again after running the command above. diff --git a/docs/tutorials.md b/docs/tutorials.md deleted file mode 100644 index 527274be53..0000000000 --- a/docs/tutorials.md +++ /dev/null @@ -1,26 +0,0 @@ -# Tutorials - - -## Examples - -Example workflows which show what can be done with n8n can be found here: -[https://n8n.io/workflows](https://n8n.io/workflows) - -If you want to know how a node can get used in context, you can search for it here: -[https://n8n.io/nodes](https://n8n.io/nodes). There it shows in which workflows the -node got used. - - - -## Videos - - - [Slack Notification on Github Star](https://www.youtube.com/watch?v=3w7xIMKLVAg) - - [Typeform to Google Sheet and Slack or Email](https://www.youtube.com/watch?v=rn3-d4IiW44) - - -### Community Tutorials - - - [n8n basics 1/3 - Getting Started](https://www.youtube.com/watch?v=JIaxjH2CyFc) - - [n8n basics 2/3 - Simple Workflow](https://www.youtube.com/watch?v=ovlxledZfM4) - - [n8n basics 3/3 - Transforming JSON](https://www.youtube.com/watch?v=wGAEAcfwV8w) - - [n8n Google Integration - Using Google Sheets and Google Api nodes](https://www.youtube.com/watch?v=KFqx8OmkqVE) diff --git a/docs/workflow.md b/docs/workflow.md deleted file mode 100644 index 344504d158..0000000000 --- a/docs/workflow.md +++ /dev/null @@ -1,111 +0,0 @@ -# Workflow - - -## Activate - -Activating a workflow means that the Trigger and Webhook nodes get activated and can trigger a workflow to run. By default all the newly created workflows are deactivated. That means that even if a Trigger node like the Cron node should start a workflow because a predefined time is reached, it will not unless the workflow gets activated. It is only possible to activate a workflow which contains a Trigger or a Webhook node. - - -## Data Flow - -Nodes do not only process one "item", they process multiple ones. So if the Trello node is set to "Create-Card" and it has an expression set for "Name" to be set depending on "name" property, it will create a card for each item, always choosing the name-property-value of the current one. - -This data would, for example, create two boards. One named "test1" the other one named "test2": - -```json -[ - { - name: "test1" - }, - { - name: "test2" - } -] -``` - - -## Error Workflows - -For each workflow, an optional "Error Workflow" can be set. It gets executed in case the execution of the workflow fails. That makes it possible to, for instance, inform the user via Email or Slack if something goes wrong. The same "Error Workflow" can be set on multiple workflows. - -The only difference between a regular workflow and an "Error Workflow" is that it contains an "Error Trigger" node. So it is important to make sure that this node gets created before setting a workflow as "Error Workflow". - -The "Error Trigger" node will trigger in case the execution fails and receives information about it. The data looks like this: - -```json -[ - { - "execution": { - "id": "231", - "url": "https://n8n.example.com/execution/231", - "retryOf": "34", - "error": { - "message": "Example Error Message", - "stack": "Stacktrace" - }, - "lastNodeExecuted": "Node With Error", - "mode": "manual" - }, - "workflow": { - "id": "1", - "name": "Example Workflow" - } - } -] - -``` - -All information is always present except: -- **execution.id**: Only present when the execution gets saved in the database -- **execution.url**: Only present when the execution gets saved in the database -- **execution.retryOf**: Only present when the execution is a retry of a previously failed execution - - -### Setting Error Workflow - -An "Error Workflow" can be set in the Workflow Settings which can be accessed by pressing the "Workflow" button in the menu on the on the left side. The last option is "Settings". In the window that appears, the "Error Workflow" can be selected via the Dropdown "Error Workflow". - - -## Share Workflows - -All workflows are JSON and can be shared very easily. - -There are multiple ways to download a workflow as JSON to then share it with other people via Email, Slack, Skype, Dropbox, … - - 1. Press the "Download" button under the Workflow menu in the sidebar on the left. It then downloads the workflow as a JSON file. - 1. Select the nodes in the editor which should be exported and then copy them (Ctrl + c). The nodes then get saved as JSON in the clipboard and can be pasted wherever desired (Ctrl + v). - -Importing that JSON representation again into n8n is as easy and can also be done in different ways: - - 1. Press "Import from File" or "Import from URL" under the Workflow menu in the sidebar on the left. - 1. Copy the JSON workflow to the clipboard (Ctrl + c) and then simply pasting it directly into the editor (Ctrl + v). - - -## Workflow Settings - -On each workflow, it is possible to set some custom settings and overwrite some of the global default settings. Currently, the following settings can be set: - - -### Error Workflow - -Workflow to run in case the execution of the current workflow fails. More information in section [Error Workflows](#error-workflows). - - -### Timezone - -The timezone to use in the current workflow. If not set, the global Timezone (by default "New York" gets used). For instance, this is important for the Cron Trigger node. - - -### Save Data Error Execution - -If the Execution data of the workflow should be saved when it fails. - - -### Save Data Success Execution - -If the Execution data of the workflow should be saved when it succeeds. - - -### Save Manual Executions - -If executions started from the Editor UI should be saved. diff --git a/package.json b/package.json index 0c7d8dac15..30fcfb7959 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "start:default": "cd packages/cli/bin && ./n8n", "start:windows": "cd packages/cli/bin && n8n", "test": "lerna run test", + "tslint": "lerna exec npm run tslint", "watch": "lerna run --parallel watch" }, "devDependencies": { diff --git a/packages/cli/LICENSE.md b/packages/cli/LICENSE.md index aac54547eb..24a7d38fc9 100644 --- a/packages/cli/LICENSE.md +++ b/packages/cli/LICENSE.md @@ -215,7 +215,7 @@ Licensor: n8n GmbH same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2020 n8n GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/cli/README.md b/packages/cli/README.md index be5f42ae8b..5ae03ffa41 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -1,10 +1,10 @@ # n8n - Workflow Automation Tool -![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/docs/images/n8n-logo.png) +![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/assets/n8n-logo.png) n8n is a free and open [fair-code](http://faircode.io) licensed node based Workflow Automation Tool. It can be self-hosted, easily extended, and so also used with internal tools. -n8n.io - Screenshot +n8n.io - Screenshot ## Contents diff --git a/packages/cli/commands/execute.ts b/packages/cli/commands/execute.ts index cdea6a2a0d..3eb5956e9d 100644 --- a/packages/cli/commands/execute.ts +++ b/packages/cli/commands/execute.ts @@ -11,6 +11,7 @@ import { ActiveExecutions, CredentialsOverwrites, Db, + ExternalHooks, GenericHelpers, IWorkflowBase, IWorkflowExecutionDataProcess, @@ -108,6 +109,10 @@ export class Execute extends Command { const credentialsOverwrites = CredentialsOverwrites(); await credentialsOverwrites.init(); + // Load all external hooks + const externalHooks = ExternalHooks(); + await externalHooks.init(); + // Add the found types to an instance other parts of the application can use const nodeTypes = NodeTypes(); await nodeTypes.init(loadNodesAndCredentials.nodeTypes); diff --git a/packages/cli/commands/start.ts b/packages/cli/commands/start.ts index 10dde58b35..1b76459de7 100644 --- a/packages/cli/commands/start.ts +++ b/packages/cli/commands/start.ts @@ -5,7 +5,6 @@ import { } from 'n8n-core'; import { Command, flags } from '@oclif/command'; const open = require('open'); -// import { dirname } from 'path'; import * as config from '../config'; import { @@ -13,6 +12,7 @@ import { CredentialTypes, CredentialsOverwrites, Db, + ExternalHooks, GenericHelpers, LoadNodesAndCredentials, NodeTypes, @@ -113,6 +113,10 @@ export class Start extends Command { const credentialsOverwrites = CredentialsOverwrites(); await credentialsOverwrites.init(); + // Load all external hooks + const externalHooks = ExternalHooks(); + await externalHooks.init(); + // Add the found types to an instance other parts of the application can use const nodeTypes = NodeTypes(); await nodeTypes.init(loadNodesAndCredentials.nodeTypes); diff --git a/packages/cli/config/index.ts b/packages/cli/config/index.ts index 648d579b30..2759c6d794 100644 --- a/packages/cli/config/index.ts +++ b/packages/cli/config/index.ts @@ -63,6 +63,34 @@ const config = convict({ default: 'public', env: 'DB_POSTGRESDB_SCHEMA' }, + + ssl: { + ca: { + doc: 'SSL certificate authority', + format: String, + default: '', + env: 'DB_POSTGRESDB_SSL_CA', + }, + cert: { + doc: 'SSL certificate', + format: String, + default: '', + env: 'DB_POSTGRESDB_SSL_CERT', + }, + key: { + doc: 'SSL key', + format: String, + default: '', + env: 'DB_POSTGRESDB_SSL_KEY', + }, + rejectUnauthorized: { + doc: 'If unauthorized SSL connections should be rejected', + format: 'Boolean', + default: true, + env: 'DB_POSTGRESDB_SSL_REJECT_UNAUTHORIZED', + }, + } + }, mysqldb: { database: { @@ -100,15 +128,23 @@ const config = convict({ credentials: { overwrite: { - // Allows to set default values for credentials which - // get automatically prefilled and the user does not get - // displayed and can not change. - // Format: { CREDENTIAL_NAME: { PARAMTER: VALUE }} - doc: 'Overwrites for credentials', - format: '*', - default: '{}', - env: 'CREDENTIALS_OVERWRITE' - } + data: { + // Allows to set default values for credentials which + // get automatically prefilled and the user does not get + // displayed and can not change. + // Format: { CREDENTIAL_NAME: { PARAMTER: VALUE }} + doc: 'Overwrites for credentials', + format: '*', + default: '{}', + env: 'CREDENTIALS_OVERWRITE_DATA' + }, + endpoint: { + doc: 'Fetch credentials from API', + format: String, + default: '', + env: 'CREDENTIALS_OVERWRITE_ENDPOINT', + }, + }, }, executions: { @@ -125,8 +161,8 @@ const config = convict({ // If a workflow executes all the data gets saved by default. This // could be a problem when a workflow gets executed a lot and processes - // a lot of data. To not write the database full it is possible to - // not save the execution at all. + // a lot of data. To not exceed the database's capacity it is possible to + // prune the database regularly or to not save the execution at all. // Depending on if the execution did succeed or error a different // save behaviour can be set. saveDataOnError: { @@ -149,9 +185,34 @@ const config = convict({ // in the editor. saveDataManualExecutions: { doc: 'Save data of executions when started manually via editor', + format: 'Boolean', default: false, env: 'EXECUTIONS_DATA_SAVE_MANUAL_EXECUTIONS' }, + + // To not exceed the database's capacity and keep its size moderate + // the execution data gets pruned regularly (default: 1 hour interval). + // All saved execution data older than the max age will be deleted. + // Pruning is currently not activated by default, which will change in + // a future version. + pruneData: { + doc: 'Delete data of past executions on a rolling basis', + format: 'Boolean', + default: false, + env: 'EXECUTIONS_DATA_PRUNE' + }, + pruneDataMaxAge: { + doc: 'How old (hours) the execution data has to be to get deleted', + format: Number, + default: 336, + env: 'EXECUTIONS_DATA_MAX_AGE' + }, + pruneDataTimeout: { + doc: 'Timeout (seconds) after execution data has been pruned', + format: Number, + default: 3600, + env: 'EXECUTIONS_DATA_PRUNE_TIMEOUT' + }, }, generic: { @@ -168,6 +229,13 @@ const config = convict({ }, // How n8n can be reached (Editor & REST-API) + path: { + format: String, + default: '/', + arg: 'path', + env: 'N8N_PATH', + doc: 'Path n8n is deployed to' + }, host: { format: String, default: 'localhost', @@ -271,6 +339,13 @@ const config = convict({ }, }, + externalHookFiles: { + doc: 'Files containing external hooks. Multiple files can be separated by colon (":")', + format: String, + default: '', + env: 'EXTERNAL_HOOK_FILES' + }, + nodes: { exclude: { doc: 'Nodes not to load', diff --git a/packages/cli/migrations/ormconfig.ts b/packages/cli/migrations/ormconfig.ts index 2a0cda0d9c..1ea583beb4 100644 --- a/packages/cli/migrations/ormconfig.ts +++ b/packages/cli/migrations/ormconfig.ts @@ -44,9 +44,9 @@ module.exports = [ "logging": false, "host": "localhost", "username": "postgres", - "password": "docker", + "password": "", "port": 5432, - "database": "postgres", + "database": "n8n", "schema": "public", "entities": Object.values(PostgresDb), "migrations": [ @@ -68,7 +68,7 @@ module.exports = [ "username": "root", "password": "password", "host": "localhost", - "port": "3308", + "port": "3306", "logging": false, "entities": Object.values(MySQLDb), "migrations": [ @@ -90,7 +90,7 @@ module.exports = [ "username": "root", "password": "password", "host": "localhost", - "port": "3308", + "port": "3306", "logging": false, "entities": Object.values(MySQLDb), "migrations": [ @@ -105,4 +105,4 @@ module.exports = [ "subscribersDir": "./src/databases/mysqldb/Subscribers" } }, -]; \ No newline at end of file +]; diff --git a/packages/cli/package.json b/packages/cli/package.json index 325a73d874..4749a2ed0d 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "n8n", - "version": "0.68.2", + "version": "0.74.0", "description": "n8n Workflow Automation Tool", "license": "SEE LICENSE IN LICENSE.md", "homepage": "https://n8n.io", @@ -100,10 +100,10 @@ "lodash.get": "^4.4.2", "mongodb": "^3.5.5", "mysql2": "^2.0.1", - "n8n-core": "~0.35.0", - "n8n-editor-ui": "~0.46.0", - "n8n-nodes-base": "~0.63.1", - "n8n-workflow": "~0.32.0", + "n8n-core": "~0.39.0", + "n8n-editor-ui": "~0.50.0", + "n8n-nodes-base": "~0.69.0", + "n8n-workflow": "~0.35.0", "oauth-1.0a": "^2.2.6", "open": "^7.0.0", "pg": "^7.11.0", diff --git a/packages/cli/src/ActiveWorkflowRunner.ts b/packages/cli/src/ActiveWorkflowRunner.ts index 9fef6ed243..c7f7ea1d69 100644 --- a/packages/cli/src/ActiveWorkflowRunner.ts +++ b/packages/cli/src/ActiveWorkflowRunner.ts @@ -11,11 +11,11 @@ import { WorkflowHelpers, WorkflowRunner, WorkflowExecuteAdditionalData, + IWebhookDb, } from './'; import { ActiveWorkflows, - ActiveWebhooks, NodeExecuteFunctions, } from 'n8n-core'; @@ -26,7 +26,7 @@ import { INode, INodeExecutionData, IRunExecutionData, - IWebhookData, + NodeHelpers, IWorkflowExecuteAdditionalData as IWorkflowExecuteAdditionalDataWorkflow, WebhookHttpMethod, Workflow, @@ -35,22 +35,23 @@ import { import * as express from 'express'; - export class ActiveWorkflowRunner { private activeWorkflows: ActiveWorkflows | null = null; - private activeWebhooks: ActiveWebhooks | null = null; + private activationErrors: { [key: string]: IActivationError; } = {}; async init() { + // Get the active workflows from database + + // NOTE + // Here I guess we can have a flag on the workflow table like hasTrigger + // so intead of pulling all the active wehhooks just pull the actives that have a trigger const workflowsData: IWorkflowDb[] = await Db.collections.Workflow!.find({ active: true }) as IWorkflowDb[]; - this.activeWebhooks = new ActiveWebhooks(); - - // Add them as active workflows this.activeWorkflows = new ActiveWorkflows(); if (workflowsData.length !== 0) { @@ -58,20 +59,27 @@ export class ActiveWorkflowRunner { console.log(' Start Active Workflows:'); console.log(' ================================'); + const nodeTypes = NodeTypes(); + for (const workflowData of workflowsData) { - console.log(` - ${workflowData.name}`); - try { - await this.add(workflowData.id.toString(), workflowData); - console.log(` => Started`); - } catch (error) { - console.log(` => ERROR: Workflow could not be activated:`); - console.log(` ${error.message}`); + + const workflow = new Workflow({ id: workflowData.id.toString(), name: workflowData.name, nodes: workflowData.nodes, connections: workflowData.connections, active: workflowData.active, nodeTypes, staticData: workflowData.staticData, settings: workflowData.settings}); + + if (workflow.getTriggerNodes().length !== 0 + || workflow.getPollNodes().length !== 0) { + console.log(` - ${workflowData.name}`); + try { + await this.add(workflowData.id.toString(), workflowData); + console.log(` => Started`); + } catch (error) { + console.log(` => ERROR: Workflow could not be activated:`); + console.log(` ${error.message}`); + } } } } } - /** * Removes all the currently active workflows * @@ -94,7 +102,6 @@ export class ActiveWorkflowRunner { return; } - /** * Checks if a webhook for the given method and path exists and executes the workflow. * @@ -110,30 +117,41 @@ export class ActiveWorkflowRunner { throw new ResponseHelper.ResponseError('The "activeWorkflows" instance did not get initialized yet.', 404, 404); } - const webhookData: IWebhookData | undefined = this.activeWebhooks!.get(httpMethod, path); + const webhook = await Db.collections.Webhook?.findOne({ webhookPath: path, method: httpMethod }) as IWebhookDb; - if (webhookData === undefined) { + // check if something exist + if (webhook === undefined) { // The requested webhook is not registered throw new ResponseHelper.ResponseError(`The requested webhook "${httpMethod} ${path}" is not registered.`, 404, 404); } - const workflowData = await Db.collections.Workflow!.findOne(webhookData.workflowId); + const workflowData = await Db.collections.Workflow!.findOne(webhook.workflowId); if (workflowData === undefined) { - throw new ResponseHelper.ResponseError(`Could not find workflow with id "${webhookData.workflowId}"`, 404, 404); + throw new ResponseHelper.ResponseError(`Could not find workflow with id "${webhook.workflowId}"`, 404, 404); } const nodeTypes = NodeTypes(); - const workflow = new Workflow({ id: webhookData.workflowId, name: workflowData.name, nodes: workflowData.nodes, connections: workflowData.connections, active: workflowData.active, nodeTypes, staticData: workflowData.staticData, settings: workflowData.settings}); + const workflow = new Workflow({ id: webhook.workflowId.toString(), name: workflowData.name, nodes: workflowData.nodes, connections: workflowData.connections, active: workflowData.active, nodeTypes, staticData: workflowData.staticData, settings: workflowData.settings}); + + const credentials = await WorkflowCredentials([workflow.getNode(webhook.node as string) as INode]); + + const additionalData = await WorkflowExecuteAdditionalData.getBase(credentials); + + const webhookData = NodeHelpers.getNodeWebhooks(workflow, workflow.getNode(webhook.node as string) as INode, additionalData).filter((webhook) => { + return (webhook.httpMethod === httpMethod && webhook.path === path); + })[0]; // Get the node which has the webhook defined to know where to start from and to // get additional data const workflowStartNode = workflow.getNode(webhookData.node); + if (workflowStartNode === null) { throw new ResponseHelper.ResponseError('Could not find node to process webhook.', 404, 404); } return new Promise((resolve, reject) => { const executionMode = 'webhook'; + //@ts-ignore WebhookHelpers.executeWebhook(workflow, webhookData, workflowData, workflowStartNode, executionMode, undefined, req, res, (error: Error | null, data: object) => { if (error !== null) { return reject(error); @@ -143,19 +161,14 @@ export class ActiveWorkflowRunner { }); } - /** * Returns the ids of the currently active workflows * * @returns {string[]} * @memberof ActiveWorkflowRunner */ - getActiveWorkflows(): string[] { - if (this.activeWorkflows === null) { - return []; - } - - return this.activeWorkflows.allActiveWorkflows(); + getActiveWorkflows(): Promise { + return Db.collections.Workflow?.find({ select: ['id'] }) as Promise; } @@ -166,15 +179,11 @@ export class ActiveWorkflowRunner { * @returns {boolean} * @memberof ActiveWorkflowRunner */ - isActive(id: string): boolean { - if (this.activeWorkflows !== null) { - return this.activeWorkflows.isActive(id); - } - - return false; + async isActive(id: string): Promise { + const workflow = await Db.collections.Workflow?.findOne({ id }) as IWorkflowDb; + return workflow?.active as boolean; } - /** * Return error if there was a problem activating the workflow * @@ -190,7 +199,6 @@ export class ActiveWorkflowRunner { return this.activationErrors[id]; } - /** * Adds all the webhooks of the workflow * @@ -202,12 +210,69 @@ export class ActiveWorkflowRunner { */ async addWorkflowWebhooks(workflow: Workflow, additionalData: IWorkflowExecuteAdditionalDataWorkflow, mode: WorkflowExecuteMode): Promise { const webhooks = WebhookHelpers.getWorkflowWebhooks(workflow, additionalData); + let path = '' as string | undefined; for (const webhookData of webhooks) { - await this.activeWebhooks!.add(workflow, webhookData, mode); - // Save static data! - await WorkflowHelpers.saveStaticData(workflow); + + const node = workflow.getNode(webhookData.node) as INode; + node.name = webhookData.node; + + path = node.parameters.path as string; + + if (node.parameters.path === undefined) { + path = workflow.getSimpleParameterValue(node, webhookData.webhookDescription['path']) as string | undefined; + + if (path === undefined) { + // TODO: Use a proper logger + console.error(`No webhook path could be found for node "${node.name}" in workflow "${workflow.id}".`); + continue; + } + } + + const isFullPath: boolean = workflow.getSimpleParameterValue(node, webhookData.webhookDescription['isFullPath'], false) as boolean; + + const webhook = { + workflowId: webhookData.workflowId, + webhookPath: NodeHelpers.getNodeWebhookPath(workflow.id as string, node, path, isFullPath), + node: node.name, + method: webhookData.httpMethod, + } as IWebhookDb; + + try { + + await Db.collections.Webhook?.insert(webhook); + + const webhookExists = await workflow.runWebhookMethod('checkExists', webhookData, NodeExecuteFunctions, mode, false); + if (webhookExists === false) { + // If webhook does not exist yet create it + await workflow.runWebhookMethod('create', webhookData, NodeExecuteFunctions, mode, false); + } + + } catch (error) { + + let errorMessage = ''; + + await Db.collections.Webhook?.delete({ workflowId: workflow.id }); + + // if it's a workflow from the the insert + // TODO check if there is standard error code for deplicate key violation that works + // with all databases + if (error.name === 'MongoError' || error.name === 'QueryFailedError') { + + errorMessage = `The webhook path [${webhook.webhookPath}] and method [${webhook.method}] already exist.`; + + } else if (error.detail) { + // it's a error runnig the webhook methods (checkExists, create) + errorMessage = error.detail; + } else { + errorMessage = error.message; + } + + throw new Error(errorMessage); + } } + // Save static data! + await WorkflowHelpers.saveStaticData(workflow); } @@ -227,13 +292,29 @@ export class ActiveWorkflowRunner { const nodeTypes = NodeTypes(); const workflow = new Workflow({ id: workflowId, name: workflowData.name, nodes: workflowData.nodes, connections: workflowData.connections, active: workflowData.active, nodeTypes, staticData: workflowData.staticData, settings: workflowData.settings }); - await this.activeWebhooks!.removeWorkflow(workflow); + const mode = 'internal'; - // Save the static workflow data if needed - await WorkflowHelpers.saveStaticData(workflow); + const credentials = await WorkflowCredentials(workflowData.nodes); + const additionalData = await WorkflowExecuteAdditionalData.getBase(credentials); + + const webhooks = WebhookHelpers.getWorkflowWebhooks(workflow, additionalData); + + for (const webhookData of webhooks) { + await workflow.runWebhookMethod('delete', webhookData, NodeExecuteFunctions, mode, false); + } + + // if it's a mongo objectId convert it to string + if (typeof workflowData.id === 'object') { + workflowData.id = workflowData.id.toString(); + } + + const webhook = { + workflowId: workflowData.id, + } as IWebhookDb; + + await Db.collections.Webhook?.delete(webhook); } - /** * Runs the given workflow * @@ -322,7 +403,6 @@ export class ActiveWorkflowRunner { }); } - /** * Makes a workflow active * @@ -361,7 +441,11 @@ export class ActiveWorkflowRunner { // Add the workflows which have webhooks defined await this.addWorkflowWebhooks(workflowInstance, additionalData, mode); - await this.activeWorkflows.add(workflowId, workflowInstance, additionalData, getTriggerFunctions, getPollFunctions); + + if (workflowInstance.getTriggerNodes().length !== 0 + || workflowInstance.getPollNodes().length !== 0) { + await this.activeWorkflows.add(workflowId, workflowInstance, additionalData, getTriggerFunctions, getPollFunctions); + } if (this.activationErrors[workflowId] !== undefined) { // If there were activation errors delete them @@ -386,7 +470,6 @@ export class ActiveWorkflowRunner { await WorkflowHelpers.saveStaticData(workflowInstance!); } - /** * Makes a workflow inactive * @@ -395,6 +478,7 @@ export class ActiveWorkflowRunner { * @memberof ActiveWorkflowRunner */ async remove(workflowId: string): Promise { + if (this.activeWorkflows !== null) { // Remove all the webhooks of the workflow await this.removeWorkflowWebhooks(workflowId); @@ -404,8 +488,13 @@ export class ActiveWorkflowRunner { delete this.activationErrors[workflowId]; } - // Remove the workflow from the "list" of active workflows - return this.activeWorkflows.remove(workflowId); + // if it's active in memory then it's a trigger + // so remove from list of actives workflows + if (this.activeWorkflows.isActive(workflowId)) { + this.activeWorkflows.remove(workflowId); + } + + return; } throw new Error(`The "activeWorkflows" instance did not get initialized yet.`); diff --git a/packages/cli/src/CredentialsOverwrites.ts b/packages/cli/src/CredentialsOverwrites.ts index a6e115100e..ca09b87626 100644 --- a/packages/cli/src/CredentialsOverwrites.ts +++ b/packages/cli/src/CredentialsOverwrites.ts @@ -20,7 +20,7 @@ class CredentialsOverwritesClass { return; } - const data = await GenericHelpers.getConfigValue('credentials.overwrite') as string; + const data = await GenericHelpers.getConfigValue('credentials.overwrite.data') as string; try { this.overwriteData = JSON.parse(data); @@ -30,6 +30,7 @@ class CredentialsOverwritesClass { } applyOverwrite(type: string, data: ICredentialDataDecryptedObject) { + const overwrites = this.get(type); if (overwrites === undefined) { diff --git a/packages/cli/src/Db.ts b/packages/cli/src/Db.ts index 54633adb13..06eeca7976 100644 --- a/packages/cli/src/Db.ts +++ b/packages/cli/src/Db.ts @@ -14,6 +14,8 @@ import { getRepository, } from 'typeorm'; +import { TlsOptions } from 'tls'; + import * as config from '../config'; import { @@ -27,22 +29,31 @@ export let collections: IDatabaseCollections = { Credentials: null, Execution: null, Workflow: null, + Webhook: null, }; import { - InitialMigration1587669153312 + InitialMigration1587669153312, + WebhookModel1589476000887, + CreateIndexStoppedAt1594828256133, } from './databases/postgresdb/migrations'; import { - InitialMigration1587563438936 + InitialMigration1587563438936, + WebhookModel1592679094242, + CreateIndexStoppedAt1594910478695, } from './databases/mongodb/migrations'; import { - InitialMigration1588157391238 + InitialMigration1588157391238, + WebhookModel1592447867632, + CreateIndexStoppedAt1594902918301, } from './databases/mysqldb/migrations'; import { - InitialMigration1588102412422 + InitialMigration1588102412422, + WebhookModel1592445003908, + CreateIndexStoppedAt1594825041918, } from './databases/sqlite/migrations'; import * as path from 'path'; @@ -64,7 +75,11 @@ export async function init(): Promise { entityPrefix, url: await GenericHelpers.getConfigValue('database.mongodb.connectionUrl') as string, useNewUrlParser: true, - migrations: [InitialMigration1587563438936], + migrations: [ + InitialMigration1587563438936, + WebhookModel1592679094242, + CreateIndexStoppedAt1594910478695, + ], migrationsRun: true, migrationsTableName: `${entityPrefix}migrations`, }; @@ -72,6 +87,22 @@ export async function init(): Promise { case 'postgresdb': entities = PostgresDb; + + const sslCa = await GenericHelpers.getConfigValue('database.postgresdb.ssl.ca') as string; + const sslCert = await GenericHelpers.getConfigValue('database.postgresdb.ssl.cert') as string; + const sslKey = await GenericHelpers.getConfigValue('database.postgresdb.ssl.key') as string; + const sslRejectUnauthorized = await GenericHelpers.getConfigValue('database.postgresdb.ssl.rejectUnauthorized') as boolean; + + let ssl: TlsOptions | undefined = undefined; + if (sslCa !== '' || sslCert !== '' || sslKey !== '' || sslRejectUnauthorized !== true) { + ssl = { + ca: sslCa || undefined, + cert: sslCert || undefined, + key: sslKey || undefined, + rejectUnauthorized: sslRejectUnauthorized, + }; + } + connectionOptions = { type: 'postgres', entityPrefix, @@ -81,10 +112,16 @@ export async function init(): Promise { port: await GenericHelpers.getConfigValue('database.postgresdb.port') as number, username: await GenericHelpers.getConfigValue('database.postgresdb.user') as string, schema: config.get('database.postgresdb.schema'), - migrations: [InitialMigration1587669153312], + migrations: [ + InitialMigration1587669153312, + WebhookModel1589476000887, + CreateIndexStoppedAt1594828256133, + ], migrationsRun: true, migrationsTableName: `${entityPrefix}migrations`, + ssl, }; + break; case 'mariadb': @@ -98,7 +135,11 @@ export async function init(): Promise { password: await GenericHelpers.getConfigValue('database.mysqldb.password') as string, port: await GenericHelpers.getConfigValue('database.mysqldb.port') as number, username: await GenericHelpers.getConfigValue('database.mysqldb.user') as string, - migrations: [InitialMigration1588157391238], + migrations: [ + InitialMigration1588157391238, + WebhookModel1592447867632, + CreateIndexStoppedAt1594902918301, + ], migrationsRun: true, migrationsTableName: `${entityPrefix}migrations`, }; @@ -110,7 +151,11 @@ export async function init(): Promise { type: 'sqlite', database: path.join(n8nFolder, 'database.sqlite'), entityPrefix, - migrations: [InitialMigration1588102412422], + migrations: [ + InitialMigration1588102412422, + WebhookModel1592445003908, + CreateIndexStoppedAt1594825041918 + ], migrationsRun: true, migrationsTableName: `${entityPrefix}migrations`, }; @@ -135,6 +180,7 @@ export async function init(): Promise { collections.Credentials = getRepository(entities.CredentialsEntity); collections.Execution = getRepository(entities.ExecutionEntity); collections.Workflow = getRepository(entities.WorkflowEntity); + collections.Webhook = getRepository(entities.WebhookEntity); return collections; } diff --git a/packages/cli/src/ExternalHooks.ts b/packages/cli/src/ExternalHooks.ts new file mode 100644 index 0000000000..355415158a --- /dev/null +++ b/packages/cli/src/ExternalHooks.ts @@ -0,0 +1,79 @@ +import { + Db, + IExternalHooksFunctions, + IExternalHooksClass, +} from './'; + +import * as config from '../config'; + + +class ExternalHooksClass implements IExternalHooksClass { + + externalHooks: { + [key: string]: Array<() => {}> + } = {}; + initDidRun = false; + + + async init(): Promise { + if (this.initDidRun === true) { + return; + } + + const externalHookFiles = config.get('externalHookFiles').split(':'); + + // Load all the provided hook-files + for (let hookFilePath of externalHookFiles) { + hookFilePath = hookFilePath.trim(); + if (hookFilePath !== '') { + try { + const hookFile = require(hookFilePath); + + for (const resource of Object.keys(hookFile)) { + for (const operation of Object.keys(hookFile[resource])) { + // Save all the hook functions directly under their string + // format in an array + const hookString = `${resource}.${operation}`; + if (this.externalHooks[hookString] === undefined) { + this.externalHooks[hookString] = []; + } + + this.externalHooks[hookString].push.apply(this.externalHooks[hookString], hookFile[resource][operation]); + } + } + } catch (error) { + throw new Error(`Problem loading external hook file "${hookFilePath}": ${error.message}`); + } + } + } + + this.initDidRun = true; + } + + async run(hookName: string, hookParameters?: any[]): Promise { // tslint:disable-line:no-any + const externalHookFunctions: IExternalHooksFunctions = { + dbCollections: Db.collections, + }; + + if (this.externalHooks[hookName] === undefined) { + return; + } + + for(const externalHookFunction of this.externalHooks[hookName]) { + await externalHookFunction.apply(externalHookFunctions, hookParameters); + } + } + +} + + + +let externalHooksInstance: ExternalHooksClass | undefined; + +export function ExternalHooks(): ExternalHooksClass { + if (externalHooksInstance === undefined) { + externalHooksInstance = new ExternalHooksClass(); + } + + return externalHooksInstance; +} diff --git a/packages/cli/src/GenericHelpers.ts b/packages/cli/src/GenericHelpers.ts index 8b02b73e8e..cab67f7bce 100644 --- a/packages/cli/src/GenericHelpers.ts +++ b/packages/cli/src/GenericHelpers.ts @@ -40,11 +40,12 @@ export function getBaseUrl(): string { const protocol = config.get('protocol') as string; const host = config.get('host') as string; const port = config.get('port') as number; + const path = config.get('path') as string; if (protocol === 'http' && port === 80 || protocol === 'https' && port === 443) { - return `${protocol}://${host}/`; + return `${protocol}://${host}${path}`; } - return `${protocol}://${host}:${port}/`; + return `${protocol}://${host}:${port}${path}`; } diff --git a/packages/cli/src/Interfaces.ts b/packages/cli/src/Interfaces.ts index abab09bd13..2aecd27466 100644 --- a/packages/cli/src/Interfaces.ts +++ b/packages/cli/src/Interfaces.ts @@ -49,8 +49,15 @@ export interface IDatabaseCollections { Credentials: Repository | null; Execution: Repository | null; Workflow: Repository | null; + Webhook: Repository | null; } +export interface IWebhookDb { + workflowId: number | string | ObjectID; + webhookPath: string; + method: string; + node: string; +} export interface IWorkflowBase extends IWorkflowBaseWorkflow { id?: number | string | ObjectID; @@ -197,6 +204,30 @@ export interface IExecutingWorkflowData { workflowExecution?: PCancelable; } +export interface IExternalHooks { + credentials?: { + create?: Array<{ (this: IExternalHooksFunctions, credentialsData: ICredentialsEncrypted): Promise; }> + delete?: Array<{ (this: IExternalHooksFunctions, credentialId: string): Promise; }> + update?: Array<{ (this: IExternalHooksFunctions, credentialsData: ICredentialsDb): Promise; }> + }; + workflow?: { + activate?: Array<{ (this: IExternalHooksFunctions, workflowData: IWorkflowDb): Promise; }> + create?: Array<{ (this: IExternalHooksFunctions, workflowData: IWorkflowBase): Promise; }> + delete?: Array<{ (this: IExternalHooksFunctions, workflowId: string): Promise; }> + execute?: Array<{ (this: IExternalHooksFunctions, workflowData: IWorkflowDb, mode: WorkflowExecuteMode): Promise; }> + update?: Array<{ (this: IExternalHooksFunctions, workflowData: IWorkflowDb): Promise; }> + }; +} + +export interface IExternalHooksFunctions { + dbCollections: IDatabaseCollections; +} + +export interface IExternalHooksClass { + init(): Promise; + run(hookName: string, hookParameters?: any[]): Promise; // tslint:disable-line:no-any +} + export interface IN8nConfig { database: IN8nConfigDatabase; endpoints: IN8nConfigEndpoints; diff --git a/packages/cli/src/Server.ts b/packages/cli/src/Server.ts index 7c8716dd8c..09ef7e18a6 100644 --- a/packages/cli/src/Server.ts +++ b/packages/cli/src/Server.ts @@ -18,7 +18,7 @@ import * as clientOAuth2 from 'client-oauth2'; import * as clientOAuth1 from 'oauth-1.0a'; import { RequestOptions } from 'oauth-1.0a'; import * as csrf from 'csrf'; -import * as requestPromise from 'request-promise-native'; +import * as requestPromise from 'request-promise-native'; import { createHmac } from 'crypto'; import { @@ -27,6 +27,7 @@ import { CredentialsHelper, CredentialTypes, Db, + ExternalHooks, IActivationError, ICustomRequest, ICredentialsDb, @@ -41,6 +42,7 @@ import { IExecutionsListResponse, IExecutionsStopData, IExecutionsSummary, + IExternalHooksClass, IN8nUISettings, IPackageVersions, IWorkflowBase, @@ -56,6 +58,9 @@ import { WorkflowExecuteAdditionalData, WorkflowRunner, GenericHelpers, + CredentialsOverwrites, + ICredentialsOverwrite, + LoadNodesAndCredentials, } from './'; import { @@ -103,6 +108,8 @@ class App { testWebhooks: TestWebhooks.TestWebhooks; endpointWebhook: string; endpointWebhookTest: string; + endpointPresetCredentials: string; + externalHooks: IExternalHooksClass; saveDataErrorExecution: string; saveDataSuccessExecution: string; saveManualExecutions: boolean; @@ -110,11 +117,14 @@ class App { activeExecutionsInstance: ActiveExecutions.ActiveExecutions; push: Push.Push; versions: IPackageVersions | undefined; + restEndpoint: string; protocol: string; - sslKey: string; + sslKey: string; sslCert: string; + presetCredentialsLoaded: boolean; + constructor() { this.app = express(); @@ -124,6 +134,7 @@ class App { this.saveDataSuccessExecution = config.get('executions.saveDataOnSuccess') as string; this.saveManualExecutions = config.get('executions.saveDataManualExecutions') as boolean; this.timezone = config.get('generic.timezone') as string; + this.restEndpoint = config.get('endpoints.rest') as string; this.activeWorkflowRunner = ActiveWorkflowRunner.getInstance(); this.testWebhooks = TestWebhooks.getInstance(); @@ -132,8 +143,13 @@ class App { this.activeExecutionsInstance = ActiveExecutions.getInstance(); this.protocol = config.get('protocol'); - this.sslKey = config.get('ssl_key'); + this.sslKey = config.get('ssl_key'); this.sslCert = config.get('ssl_cert'); + + this.externalHooks = ExternalHooks(); + + this.presetCredentialsLoaded = false; + this.endpointPresetCredentials = config.get('credentials.overwrite.endpoint') as string; } @@ -188,7 +204,7 @@ class App { } // Check for and validate JWT if configured - const jwtAuthActive = config.get('security.jwtAuth.active') as boolean; + const jwtAuthActive = config.get('security.jwtAuth.active') as boolean; if (jwtAuthActive === true) { const jwtAuthHeader = await GenericHelpers.getConfigValue('security.jwtAuth.jwtHeader') as string; if (jwtAuthHeader === '') { @@ -230,7 +246,7 @@ class App { // Get push connections this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { - if (req.url.indexOf('/rest/push') === 0) { + if (req.url.indexOf(`/${this.restEndpoint}/push`) === 0) { // TODO: Later also has to add some kind of authentication token if (req.query.sessionId === undefined) { next(new Error('The query parameter "sessionId" is missing!')); @@ -266,7 +282,7 @@ class App { normalize: true, // Trim whitespace inside text nodes normalizeTags: true, // Transform tags to lowercase explicitArray: false, // Only put properties in array if length > 1 - } })); + } })); this.app.use(bodyParser.text({ limit: '16mb', verify: (req, res, buf) => { @@ -279,7 +295,7 @@ class App { this.app.use(history({ rewrites: [ { - from: new RegExp(`^\/(rest|healthz|css|js|${this.endpointWebhook}|${this.endpointWebhookTest})\/?.*$`), + from: new RegExp(`^\/(${this.restEndpoint}|healthz|css|js|${this.endpointWebhook}|${this.endpointWebhookTest})\/?.*$`), to: (context) => { return context.parsedUrl!.pathname!.toString(); } @@ -349,9 +365,9 @@ class App { // Creates a new workflow - this.app.post('/rest/workflows', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.post(`/${this.restEndpoint}/workflows`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { - const newWorkflowData = req.body; + const newWorkflowData = req.body as IWorkflowBase; newWorkflowData.name = newWorkflowData.name.trim(); newWorkflowData.createdAt = this.getCurrentDate(); @@ -359,6 +375,8 @@ class App { newWorkflowData.id = undefined; + await this.externalHooks.run('workflow.create', [newWorkflowData]); + // Save the workflow in DB const result = await Db.collections.Workflow!.save(newWorkflowData); @@ -370,7 +388,7 @@ class App { // Reads and returns workflow data from an URL - this.app.get('/rest/workflows/from-url', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/workflows/from-url`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { if (req.query.url === undefined) { throw new ResponseHelper.ResponseError(`The parameter "url" is missing!`, undefined, 400); } @@ -398,7 +416,7 @@ class App { // Returns workflows - this.app.get('/rest/workflows', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/workflows`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const findQuery = {} as FindManyOptions; if (req.query.filter) { findQuery.where = JSON.parse(req.query.filter as string); @@ -418,7 +436,7 @@ class App { // Returns a specific workflow - this.app.get('/rest/workflows/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/workflows/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const result = await Db.collections.Workflow!.findOne(req.params.id); if (result === undefined) { @@ -432,12 +450,16 @@ class App { // Updates an existing workflow - this.app.patch('/rest/workflows/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.patch(`/${this.restEndpoint}/workflows/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { - const newWorkflowData = req.body; + const newWorkflowData = req.body as IWorkflowBase; const id = req.params.id; - if (this.activeWorkflowRunner.isActive(id)) { + await this.externalHooks.run('workflow.update', [newWorkflowData]); + + const isActive = await this.activeWorkflowRunner.isActive(id); + + if (isActive) { // When workflow gets saved always remove it as the triggers could have been // changed and so the changes would not take effect await this.activeWorkflowRunner.remove(id); @@ -478,6 +500,8 @@ class App { if (responseData.active === true) { // When the workflow is supposed to be active add it again try { + await this.externalHooks.run('workflow.activate', [responseData]); + await this.activeWorkflowRunner.add(id); } catch (error) { // If workflow could not be activated set it again to inactive @@ -499,10 +523,14 @@ class App { // Deletes a specific workflow - this.app.delete('/rest/workflows/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.delete(`/${this.restEndpoint}/workflows/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const id = req.params.id; - if (this.activeWorkflowRunner.isActive(id)) { + await this.externalHooks.run('workflow.delete', [id]); + + const isActive = await this.activeWorkflowRunner.isActive(id); + + if (isActive) { // Before deleting a workflow deactivate it await this.activeWorkflowRunner.remove(id); } @@ -513,7 +541,7 @@ class App { })); - this.app.post('/rest/workflows/run', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.post(`/${this.restEndpoint}/workflows/run`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const workflowData = req.body.workflowData; const runData: IRunData | undefined = req.body.runData; const startNodes: string[] | undefined = req.body.startNodes; @@ -562,7 +590,7 @@ class App { // Returns parameter values which normally get loaded from an external API or // get generated dynamically - this.app.get('/rest/node-parameter-options', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/node-parameter-options`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const nodeType = req.query.nodeType as string; let credentials: INodeCredentials | undefined = undefined; const currentNodeParameters = JSON.parse('' + req.query.currentNodeParameters) as INodeParameters; @@ -584,7 +612,7 @@ class App { // Returns all the node-types - this.app.get('/rest/node-types', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/node-types`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const returnData: INodeTypeDescription[] = []; @@ -607,7 +635,7 @@ class App { // Returns the node icon - this.app.get(['/rest/node-icon/:nodeType', '/rest/node-icon/:scope/:nodeType'], async (req: express.Request, res: express.Response): Promise => { + this.app.get([`/${this.restEndpoint}/node-icon/:nodeType`, `/${this.restEndpoint}/node-icon/:scope/:nodeType`], async (req: express.Request, res: express.Response): Promise => { const nodeTypeName = `${req.params.scope ? `${req.params.scope}/` : ''}${req.params.nodeType}`; const nodeTypes = NodeTypes(); @@ -641,13 +669,14 @@ class App { // Returns the active workflow ids - this.app.get('/rest/active', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { - return this.activeWorkflowRunner.getActiveWorkflows(); + this.app.get(`/${this.restEndpoint}/active`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + const activeWorkflows = await this.activeWorkflowRunner.getActiveWorkflows(); + return activeWorkflows.map(workflow => workflow.id.toString()) as string[]; })); // Returns if the workflow with the given id had any activation errors - this.app.get('/rest/active/error/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/active/error/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const id = req.params.id; return this.activeWorkflowRunner.getActivationError(id); })); @@ -660,16 +689,18 @@ class App { // Deletes a specific credential - this.app.delete('/rest/credentials/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.delete(`/${this.restEndpoint}/credentials/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const id = req.params.id; + await this.externalHooks.run('credentials.delete', [id]); + await Db.collections.Credentials!.delete({ id }); return true; })); // Creates new credentials - this.app.post('/rest/credentials', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.post(`/${this.restEndpoint}/credentials`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const incomingData = req.body; if (!incomingData.name || incomingData.name.length < 3) { @@ -708,6 +739,8 @@ class App { credentials.setData(incomingData.data, encryptionKey); const newCredentialsData = credentials.getDataToSave() as ICredentialsDb; + await this.externalHooks.run('credentials.create', [newCredentialsData]); + // Add special database related data newCredentialsData.createdAt = this.getCurrentDate(); newCredentialsData.updatedAt = this.getCurrentDate(); @@ -725,7 +758,7 @@ class App { // Updates existing credentials - this.app.patch('/rest/credentials/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.patch(`/${this.restEndpoint}/credentials/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const incomingData = req.body; const id = req.params.id; @@ -783,6 +816,8 @@ class App { // Add special database related data newCredentialsData.updatedAt = this.getCurrentDate(); + await this.externalHooks.run('credentials.update', [newCredentialsData]); + // Update the credentials in DB await Db.collections.Credentials!.update(id, newCredentialsData); @@ -804,7 +839,7 @@ class App { // Returns specific credentials - this.app.get('/rest/credentials/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/credentials/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const findQuery = {} as FindManyOptions; // Make sure the variable has an expected value @@ -839,7 +874,7 @@ class App { // Returns all the saved credentials - this.app.get('/rest/credentials', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/credentials`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const findQuery = {} as FindManyOptions; if (req.query.filter) { findQuery.where = JSON.parse(req.query.filter as string); @@ -881,7 +916,7 @@ class App { // Returns all the credential types which are defined in the loaded n8n-modules - this.app.get('/rest/credential-types', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/credential-types`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const returnData: ICredentialType[] = []; @@ -899,9 +934,10 @@ class App { // ---------------------------------------- // Authorize OAuth Data - this.app.get('/rest/oauth1-credential/auth', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/oauth1-credential/auth`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { if (req.query.id === undefined) { - throw new Error('Required credential id is missing!'); + res.status(500).send('Required credential id is missing!'); + return ''; } const result = await Db.collections.Credentials!.findOne(req.query.id as string); @@ -913,7 +949,8 @@ class App { let encryptionKey = undefined; encryptionKey = await UserSettings.getEncryptionKey(); if (encryptionKey === undefined) { - throw new Error('No encryption key got found to decrypt the credentials!'); + res.status(500).send('No encryption key got found to decrypt the credentials!'); + return ''; } // Decrypt the currently saved credentials @@ -942,9 +979,9 @@ class App { }, }); - const callback = `${WebhookHelpers.getWebhookBaseUrl()}rest/oauth1-credential/callback?cid=${req.query.id}`; + const callback = `${WebhookHelpers.getWebhookBaseUrl()}${this.restEndpoint}/oauth1-credential/callback?cid=${req.query.id}`; - const options: RequestOptions = { + const options: RequestOptions = { method: 'POST', url: (_.get(oauthCredentials, 'requestTokenUrl') as string), data: { @@ -981,11 +1018,12 @@ class App { })); // Verify and store app code. Generate access tokens and store for respective credential. - this.app.get('/rest/oauth1-credential/callback', async (req: express.Request, res: express.Response) => { + this.app.get(`/${this.restEndpoint}/oauth1-credential/callback`, async (req: express.Request, res: express.Response) => { const { oauth_verifier, oauth_token, cid } = req.query; if (oauth_verifier === undefined || oauth_token === undefined) { - throw new Error('Insufficient parameters for OAuth1 callback'); + const errorResponse = new ResponseHelper.ResponseError('Insufficient parameters for OAuth1 callback. Received following query parameters: ' + JSON.stringify(req.query), undefined, 503); + return ResponseHelper.sendErrorResponse(res, errorResponse); } const result = await Db.collections.Credentials!.findOne(cid as any); // tslint:disable-line:no-any @@ -1011,7 +1049,7 @@ class App { const decryptedDataOriginal = credentialsHelper.getDecrypted(result.name, result.type, true); const oauthCredentials = credentialsHelper.applyDefaultsAndOverwrites(decryptedDataOriginal, result.type); - const options: OptionsWithUrl = { + const options: OptionsWithUrl = { method: 'POST', url: _.get(oauthCredentials, 'accessTokenUrl') as string, qs: { @@ -1053,9 +1091,10 @@ class App { // Authorize OAuth Data - this.app.get('/rest/oauth2-credential/auth', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/oauth2-credential/auth`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { if (req.query.id === undefined) { - throw new Error('Required credential id is missing!'); + res.status(500).send('Required credential id is missing.'); + return ''; } const result = await Db.collections.Credentials!.findOne(req.query.id as string); @@ -1067,7 +1106,8 @@ class App { let encryptionKey = undefined; encryptionKey = await UserSettings.getEncryptionKey(); if (encryptionKey === undefined) { - throw new Error('No encryption key got found to decrypt the credentials!'); + res.status(500).send('No encryption key got found to decrypt the credentials!'); + return ''; } // Decrypt the currently saved credentials @@ -1094,7 +1134,7 @@ class App { clientSecret: _.get(oauthCredentials, 'clientSecret', '') as string, accessTokenUri: _.get(oauthCredentials, 'accessTokenUrl', '') as string, authorizationUri: _.get(oauthCredentials, 'authUrl', '') as string, - redirectUri: `${WebhookHelpers.getWebhookBaseUrl()}rest/oauth2-credential/callback`, + redirectUri: `${WebhookHelpers.getWebhookBaseUrl()}${this.restEndpoint}/oauth2-credential/callback`, scopes: _.split(_.get(oauthCredentials, 'scope', 'openid,') as string, ','), state: stateEncodedStr, }); @@ -1127,11 +1167,12 @@ class App { // ---------------------------------------- // Verify and store app code. Generate access tokens and store for respective credential. - this.app.get('/rest/oauth2-credential/callback', async (req: express.Request, res: express.Response) => { + this.app.get(`/${this.restEndpoint}/oauth2-credential/callback`, async (req: express.Request, res: express.Response) => { const {code, state: stateEncoded } = req.query; if (code === undefined || stateEncoded === undefined) { - throw new Error('Insufficient parameters for OAuth2 callback'); + const errorResponse = new ResponseHelper.ResponseError('Insufficient parameters for OAuth2 callback. Received following query parameters: ' + JSON.stringify(req.query), undefined, 503); + return ResponseHelper.sendErrorResponse(res, errorResponse); } let state; @@ -1181,17 +1222,20 @@ class App { }, }; } + const redirectUri = `${WebhookHelpers.getWebhookBaseUrl()}${this.restEndpoint}/oauth2-credential/callback`; const oAuthObj = new clientOAuth2({ clientId: _.get(oauthCredentials, 'clientId') as string, clientSecret: _.get(oauthCredentials, 'clientSecret', '') as string, accessTokenUri: _.get(oauthCredentials, 'accessTokenUrl', '') as string, authorizationUri: _.get(oauthCredentials, 'authUrl', '') as string, - redirectUri: `${WebhookHelpers.getWebhookBaseUrl()}rest/oauth2-credential/callback`, + redirectUri, scopes: _.split(_.get(oauthCredentials, 'scope', 'openid,') as string, ',') }); - const oauthToken = await oAuthObj.code.getToken(req.originalUrl, options); + const queryParameters = req.originalUrl.split('?').splice(1, 1).join(''); + + const oauthToken = await oAuthObj.code.getToken(`${redirectUri}?${queryParameters}`, options); if (oauthToken === undefined) { const errorResponse = new ResponseHelper.ResponseError('Unable to get access tokens!', undefined, 404); @@ -1227,7 +1271,7 @@ class App { // Returns all finished executions - this.app.get('/rest/executions', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/executions`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { let filter: any = {}; // tslint:disable-line:no-any if (req.query.filter) { @@ -1292,7 +1336,7 @@ class App { // Returns a specific execution - this.app.get('/rest/executions/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/executions/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const result = await Db.collections.Execution!.findOne(req.params.id); if (result === undefined) { @@ -1306,7 +1350,7 @@ class App { // Retries a failed execution - this.app.post('/rest/executions/:id/retry', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.post(`/${this.restEndpoint}/executions/:id/retry`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { // Get the data to execute const fullExecutionDataFlatted = await Db.collections.Execution!.findOne(req.params.id); @@ -1380,7 +1424,7 @@ class App { // Delete Executions // INFORMATION: We use POST instead of DELETE to not run into any issues // with the query data getting to long - this.app.post('/rest/executions/delete', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.post(`/${this.restEndpoint}/executions/delete`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const deleteData = req.body as IExecutionDeleteFilter; if (deleteData.deleteBefore !== undefined) { @@ -1407,7 +1451,7 @@ class App { // Returns all the currently working executions - this.app.get('/rest/executions-current', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/executions-current`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const executingWorkflows = this.activeExecutionsInstance.getActiveExecutions(); const returnData: IExecutionsSummary[] = []; @@ -1436,7 +1480,7 @@ class App { })); // Forces the execution to stop - this.app.post('/rest/executions-current/:id/stop', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.post(`/${this.restEndpoint}/executions-current/:id/stop`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const executionId = req.params.id; // Stopt he execution and wait till it is done and we got the data @@ -1458,7 +1502,7 @@ class App { // Removes a test webhook - this.app.delete('/rest/test-webhook/:id', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.delete(`/${this.restEndpoint}/test-webhook/:id`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { const workflowId = req.params.id; return this.testWebhooks.cancelTestWebhook(workflowId); })); @@ -1470,7 +1514,7 @@ class App { // ---------------------------------------- // Returns all the available timezones - this.app.get('/rest/options/timezones', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/options/timezones`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { return timezones; })); @@ -1483,7 +1527,7 @@ class App { // Returns the settings which are needed in the UI - this.app.get('/rest/settings', ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { + this.app.get(`/${this.restEndpoint}/settings`, ResponseHelper.send(async (req: express.Request, res: express.Response): Promise => { return { endpointWebhook: this.endpointWebhook, endpointWebhookTest: this.endpointWebhookTest, @@ -1629,9 +1673,57 @@ class App { }); + if (this.endpointPresetCredentials !== '') { + + // POST endpoint to set preset credentials + this.app.post(`/${this.endpointPresetCredentials}`, async (req: express.Request, res: express.Response) => { + + if (this.presetCredentialsLoaded === false) { + + const body = req.body as ICredentialsOverwrite; + + if (req.headers['content-type'] !== 'application/json') { + ResponseHelper.sendErrorResponse(res, new Error('Body must be a valid JSON, make sure the content-type is application/json')); + return; + } + + const loadNodesAndCredentials = LoadNodesAndCredentials(); + + const credentialsOverwrites = CredentialsOverwrites(); + + await credentialsOverwrites.init(body); + + const credentialTypes = CredentialTypes(); + + await credentialTypes.init(loadNodesAndCredentials.credentialTypes); + + this.presetCredentialsLoaded = true; + + ResponseHelper.sendSuccessResponse(res, { success: true }, true, 200); + + } else { + ResponseHelper.sendErrorResponse(res, new Error('Preset credentials can be set once')); + } + }); + } + + + // Read the index file and replace the path placeholder + const editorUiPath = require.resolve('n8n-editor-ui'); + const filePath = pathJoin(pathDirname(editorUiPath), 'dist', 'index.html'); + const n8nPath = config.get('path'); + + let readIndexFile = readFileSync(filePath, 'utf8'); + readIndexFile = readIndexFile.replace(/\/%BASE_PATH%\//g, n8nPath); + readIndexFile = readIndexFile.replace(/\/favicon.ico/g, `${n8nPath}/favicon.ico`); + + // Serve the altered index.html file separately + this.app.get(`/index.html`, async (req: express.Request, res: express.Response) => { + res.send(readIndexFile); + }); + // Serve the website const startTime = (new Date()).toUTCString(); - const editorUiPath = require.resolve('n8n-editor-ui'); this.app.use('/', express.static(pathJoin(pathDirname(editorUiPath), 'dist'), { index: 'index.html', setHeaders: (res, path) => { diff --git a/packages/cli/src/TestWebhooks.ts b/packages/cli/src/TestWebhooks.ts index 45ae624e2b..a20fa76c88 100644 --- a/packages/cli/src/TestWebhooks.ts +++ b/packages/cli/src/TestWebhooks.ts @@ -141,12 +141,14 @@ export class TestWebhooks { let key: string; for (const webhookData of webhooks) { key = this.activeWebhooks!.getWebhookKey(webhookData.httpMethod, webhookData.path); + + await this.activeWebhooks!.add(workflow, webhookData, mode); + this.testWebhookData[key] = { sessionId, timeout, workflowData, }; - await this.activeWebhooks!.add(workflow, webhookData, mode); // Save static data! this.testWebhookData[key].workflowData.staticData = workflow.staticData; diff --git a/packages/cli/src/WebhookHelpers.ts b/packages/cli/src/WebhookHelpers.ts index d39e3f5dee..cbfb7be95c 100644 --- a/packages/cli/src/WebhookHelpers.ts +++ b/packages/cli/src/WebhookHelpers.ts @@ -69,6 +69,33 @@ export function getWorkflowWebhooks(workflow: Workflow, additionalData: IWorkflo return returnData; } +/** + * Returns all the webhooks which should be created for the give workflow + * + * @export + * @param {string} workflowId + * @param {Workflow} workflow + * @returns {IWebhookData[]} + */ +export function getWorkflowWebhooksBasic(workflow: Workflow): IWebhookData[] { + // Check all the nodes in the workflow if they have webhooks + + const returnData: IWebhookData[] = []; + + let parentNodes: string[] | undefined; + + for (const node of Object.values(workflow.nodes)) { + if (parentNodes !== undefined && !parentNodes.includes(node.name)) { + // If parentNodes are given check only them if they have webhooks + // and no other ones + continue; + } + returnData.push.apply(returnData, NodeHelpers.getNodeWebhooksBasic(workflow, node)); + } + + return returnData; +} + /** * Executes a webhook @@ -149,6 +176,9 @@ export function getWorkflowWebhooks(workflow: Workflow, additionalData: IWorkflo }; } + // Save static data if it changed + await WorkflowHelpers.saveStaticData(workflow); + if (webhookData.webhookDescription['responseHeaders'] !== undefined) { const responseHeaders = workflow.getComplexParameterValue(workflowStartNode, webhookData.webhookDescription['responseHeaders'], undefined) as { entries?: Array<{ diff --git a/packages/cli/src/WorkflowExecuteAdditionalData.ts b/packages/cli/src/WorkflowExecuteAdditionalData.ts index 1c672410c5..4230e79f58 100644 --- a/packages/cli/src/WorkflowExecuteAdditionalData.ts +++ b/packages/cli/src/WorkflowExecuteAdditionalData.ts @@ -1,6 +1,7 @@ import { CredentialsHelper, Db, + ExternalHooks, IExecutionDb, IExecutionFlattedDb, IPushDataExecutionFinished, @@ -40,6 +41,8 @@ import { import * as config from '../config'; +import { LessThanOrEqual } from "typeorm"; + /** * Checks if there was an error and if errorWorkflow is defined. If so it collects @@ -78,6 +81,30 @@ function executeErrorWorkflow(workflowData: IWorkflowBase, fullRunData: IRun, mo } } +/** + * Prunes Saved Execution which are older than configured. + * Throttled to be executed just once in configured timeframe. + * + */ +let throttling = false; +function pruneExecutionData(): void { + if (!throttling) { + throttling = true; + const timeout = config.get('executions.pruneDataTimeout') as number; // in seconds + const maxAge = config.get('executions.pruneDataMaxAge') as number; // in h + const date = new Date(); // today + date.setHours(date.getHours() - maxAge); + + // throttle just on success to allow for self healing on failure + Db.collections.Execution!.delete({ stoppedAt: LessThanOrEqual(date.toISOString()) }) + .then(data => + setTimeout(() => { + throttling = false; + }, timeout * 1000) + ).catch(err => throttling = false); + } +} + /** * Pushes the execution out to all connected clients @@ -188,6 +215,11 @@ function hookFunctionsSave(parentProcessMode?: string): IWorkflowExecuteHooks { workflowExecuteAfter: [ async function (this: WorkflowHooks, fullRunData: IRun, newStaticData: IDataObject): Promise { + // Prune old execution data + if (config.get('executions.pruneData')) { + pruneExecutionData(); + } + const isManualMode = [this.mode, parentProcessMode].includes('manual'); try { @@ -303,6 +335,10 @@ export async function executeWorkflow(workflowInfo: IExecuteWorkflowInfo, additi workflowData = workflowInfo.code; } + const externalHooks = ExternalHooks(); + await externalHooks.init(); + await externalHooks.run('workflow.execute', [workflowData, mode]); + const nodeTypes = NodeTypes(); const workflowName = workflowData ? workflowData.name : undefined; @@ -311,14 +347,14 @@ export async function executeWorkflow(workflowInfo: IExecuteWorkflowInfo, additi // Does not get used so set it simply to empty string const executionId = ''; - // Create new additionalData to have different workflow loaded and to call - // different webooks - const additionalDataIntegrated = await getBase(additionalData.credentials); - additionalDataIntegrated.hooks = getWorkflowHooksIntegrated(mode, executionId, workflowData!, { parentProcessMode: additionalData.hooks!.mode }); - // Get the needed credentials for the current workflow as they will differ to the ones of the // calling workflow. - additionalDataIntegrated.credentials = await WorkflowCredentials(workflowData!.nodes); + const credentials = await WorkflowCredentials(workflowData!.nodes); + + // Create new additionalData to have different workflow loaded and to call + // different webooks + const additionalDataIntegrated = await getBase(credentials); + additionalDataIntegrated.hooks = getWorkflowHooksIntegrated(mode, executionId, workflowData!, { parentProcessMode: additionalData.hooks!.mode }); // Find Start-Node const requiredNodeTypes = ['n8n-nodes-base.start']; diff --git a/packages/cli/src/WorkflowRunner.ts b/packages/cli/src/WorkflowRunner.ts index 48ecff4cc0..c0d08f446c 100644 --- a/packages/cli/src/WorkflowRunner.ts +++ b/packages/cli/src/WorkflowRunner.ts @@ -2,6 +2,7 @@ import { ActiveExecutions, CredentialsOverwrites, CredentialTypes, + ExternalHooks, ICredentialsOverwrite, ICredentialsTypeData, IProcessMessageDataHook, @@ -100,6 +101,9 @@ export class WorkflowRunner { * @memberof WorkflowRunner */ async run(data: IWorkflowExecutionDataProcess, loadStaticData?: boolean): Promise { + const externalHooks = ExternalHooks(); + await externalHooks.run('workflow.execute', [data.workflowData, data.executionMode]); + const executionsProcess = config.get('executions.process') as string; if (executionsProcess === 'main') { return this.runMainProcess(data, loadStaticData); diff --git a/packages/cli/src/databases/mongodb/ExecutionEntity.ts b/packages/cli/src/databases/mongodb/ExecutionEntity.ts index ba5071a36d..02a639d66a 100644 --- a/packages/cli/src/databases/mongodb/ExecutionEntity.ts +++ b/packages/cli/src/databases/mongodb/ExecutionEntity.ts @@ -39,6 +39,7 @@ export class ExecutionEntity implements IExecutionFlattedDb { @Column('Date') startedAt: Date; + @Index() @Column('Date') stoppedAt: Date; diff --git a/packages/cli/src/databases/mongodb/WebhookEntity.ts b/packages/cli/src/databases/mongodb/WebhookEntity.ts new file mode 100644 index 0000000000..dbf90f3da1 --- /dev/null +++ b/packages/cli/src/databases/mongodb/WebhookEntity.ts @@ -0,0 +1,30 @@ +import { + Column, + Entity, + Index, + ObjectID, + ObjectIdColumn, +} from 'typeorm'; + +import { + IWebhookDb, + } from '../../Interfaces'; + +@Entity() +export class WebhookEntity implements IWebhookDb { + + @ObjectIdColumn() + id: ObjectID; + + @Column() + workflowId: number; + + @Column() + webhookPath: string; + + @Column() + method: string; + + @Column() + node: string; +} diff --git a/packages/cli/src/databases/mongodb/index.ts b/packages/cli/src/databases/mongodb/index.ts index 164d67fd0c..bd6b9abd60 100644 --- a/packages/cli/src/databases/mongodb/index.ts +++ b/packages/cli/src/databases/mongodb/index.ts @@ -1,3 +1,5 @@ export * from './CredentialsEntity'; export * from './ExecutionEntity'; export * from './WorkflowEntity'; +export * from './WebhookEntity'; + diff --git a/packages/cli/src/databases/mongodb/migrations/151594910478695-CreateIndexStoppedAt.ts b/packages/cli/src/databases/mongodb/migrations/151594910478695-CreateIndexStoppedAt.ts new file mode 100644 index 0000000000..9cfe4480dc --- /dev/null +++ b/packages/cli/src/databases/mongodb/migrations/151594910478695-CreateIndexStoppedAt.ts @@ -0,0 +1,22 @@ +import { MigrationInterface } from "typeorm"; +import { + MongoQueryRunner, +} from 'typeorm/driver/mongodb/MongoQueryRunner'; + +import * as config from '../../../../config'; + +export class CreateIndexStoppedAt1594910478695 implements MigrationInterface { + name = 'CreateIndexStoppedAt1594910478695' + + public async up(queryRunner: MongoQueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + await queryRunner.manager.createCollectionIndex(`${tablePrefix}execution_entity`, 'stoppedAt', { name: `IDX_${tablePrefix}execution_entity_stoppedAt`}); + } + + public async down(queryRunner: MongoQueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + await queryRunner.manager.dropCollectionIndex + (`${tablePrefix}execution_entity`, `IDX_${tablePrefix}execution_entity_stoppedAt`); + } + +} diff --git a/packages/cli/src/databases/mongodb/migrations/1592679094242-WebhookModel.ts b/packages/cli/src/databases/mongodb/migrations/1592679094242-WebhookModel.ts new file mode 100644 index 0000000000..c05a44f765 --- /dev/null +++ b/packages/cli/src/databases/mongodb/migrations/1592679094242-WebhookModel.ts @@ -0,0 +1,57 @@ +import { + MigrationInterface, +} from 'typeorm'; + +import { + IWorkflowDb, + NodeTypes, + WebhookHelpers, +} from '../../..'; + +import { + Workflow, +} from 'n8n-workflow/dist/src/Workflow'; + +import { + IWebhookDb, +} from '../../../Interfaces'; + +import * as config from '../../../../config'; + +import { + MongoQueryRunner, +} from 'typeorm/driver/mongodb/MongoQueryRunner'; + +export class WebhookModel1592679094242 implements MigrationInterface { + name = 'WebhookModel1592679094242'; + + async up(queryRunner: MongoQueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + const workflows = await queryRunner.cursor( `${tablePrefix}workflow_entity`, { active: true }).toArray() as IWorkflowDb[]; + const data: IWebhookDb[] = []; + const nodeTypes = NodeTypes(); + for (const workflow of workflows) { + const workflowInstance = new Workflow({ id: workflow.id as string, name: workflow.name, nodes: workflow.nodes, connections: workflow.connections, active: workflow.active, nodeTypes, staticData: workflow.staticData, settings: workflow.settings }); + const webhooks = WebhookHelpers.getWorkflowWebhooksBasic(workflowInstance); + for (const webhook of webhooks) { + data.push({ + workflowId: workflowInstance.id as string, + webhookPath: webhook.path, + method: webhook.httpMethod, + node: webhook.node, + }); + } + } + + if (data.length !== 0) { + await queryRunner.manager.insertMany(`${tablePrefix}webhook_entity`, data); + } + + await queryRunner.manager.createCollectionIndex(`${tablePrefix}webhook_entity`, ['webhookPath', 'method'], { unique: true, background: false }); + } + + async down(queryRunner: MongoQueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + await queryRunner.dropTable(`${tablePrefix}webhook_entity`); + } +} diff --git a/packages/cli/src/databases/mongodb/migrations/index.ts b/packages/cli/src/databases/mongodb/migrations/index.ts index a60bdc7cf8..ae4a6deb38 100644 --- a/packages/cli/src/databases/mongodb/migrations/index.ts +++ b/packages/cli/src/databases/mongodb/migrations/index.ts @@ -1 +1,3 @@ export * from './1587563438936-InitialMigration'; +export * from './1592679094242-WebhookModel'; +export * from './151594910478695-CreateIndexStoppedAt'; diff --git a/packages/cli/src/databases/mysqldb/ExecutionEntity.ts b/packages/cli/src/databases/mysqldb/ExecutionEntity.ts index e0c084fcfc..3db01032b2 100644 --- a/packages/cli/src/databases/mysqldb/ExecutionEntity.ts +++ b/packages/cli/src/databases/mysqldb/ExecutionEntity.ts @@ -39,6 +39,7 @@ export class ExecutionEntity implements IExecutionFlattedDb { @Column('datetime') startedAt: Date; + @Index() @Column('datetime') stoppedAt: Date; diff --git a/packages/cli/src/databases/mysqldb/WebhookEntity.ts b/packages/cli/src/databases/mysqldb/WebhookEntity.ts new file mode 100644 index 0000000000..a78fd34ae9 --- /dev/null +++ b/packages/cli/src/databases/mysqldb/WebhookEntity.ts @@ -0,0 +1,25 @@ +import { + Column, + Entity, + PrimaryColumn, +} from 'typeorm'; + +import { + IWebhookDb, + } from '../../Interfaces'; + +@Entity() +export class WebhookEntity implements IWebhookDb { + + @Column() + workflowId: number; + + @PrimaryColumn() + webhookPath: string; + + @PrimaryColumn() + method: string; + + @Column() + node: string; +} diff --git a/packages/cli/src/databases/mysqldb/index.ts b/packages/cli/src/databases/mysqldb/index.ts index 164d67fd0c..a3494531db 100644 --- a/packages/cli/src/databases/mysqldb/index.ts +++ b/packages/cli/src/databases/mysqldb/index.ts @@ -1,3 +1,4 @@ export * from './CredentialsEntity'; export * from './ExecutionEntity'; export * from './WorkflowEntity'; +export * from './WebhookEntity'; diff --git a/packages/cli/src/databases/mysqldb/migrations/1588157391238-InitialMigration.ts b/packages/cli/src/databases/mysqldb/migrations/1588157391238-InitialMigration.ts index fc11ef32fb..1d1d4d8cc5 100644 --- a/packages/cli/src/databases/mysqldb/migrations/1588157391238-InitialMigration.ts +++ b/packages/cli/src/databases/mysqldb/migrations/1588157391238-InitialMigration.ts @@ -8,8 +8,8 @@ export class InitialMigration1588157391238 implements MigrationInterface { async up(queryRunner: QueryRunner): Promise { const tablePrefix = config.get('database.tablePrefix'); - await queryRunner.query('CREATE TABLE IF NOT EXISTS `' + tablePrefix + 'credentials_entity` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(128) NOT NULL, `data` text NOT NULL, `type` varchar(32) NOT NULL, `nodesAccess` json NOT NULL, `createdAt` datetime NOT NULL, `updatedAt` datetime NOT NULL, INDEX `IDX_07fde106c0b471d8cc80a64fc8` (`type`), PRIMARY KEY (`id`)) ENGINE=InnoDB', undefined); - await queryRunner.query('CREATE TABLE IF NOT EXISTS `' + tablePrefix + 'execution_entity` (`id` int NOT NULL AUTO_INCREMENT, `data` text NOT NULL, `finished` tinyint NOT NULL, `mode` varchar(255) NOT NULL, `retryOf` varchar(255) NULL, `retrySuccessId` varchar(255) NULL, `startedAt` datetime NOT NULL, `stoppedAt` datetime NOT NULL, `workflowData` json NOT NULL, `workflowId` varchar(255) NULL, INDEX `IDX_c4d999a5e90784e8caccf5589d` (`workflowId`), PRIMARY KEY (`id`)) ENGINE=InnoDB', undefined); + await queryRunner.query('CREATE TABLE IF NOT EXISTS `' + tablePrefix + 'credentials_entity` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(128) NOT NULL, `data` text NOT NULL, `type` varchar(32) NOT NULL, `nodesAccess` json NOT NULL, `createdAt` datetime NOT NULL, `updatedAt` datetime NOT NULL, INDEX `IDX_' + tablePrefix + '07fde106c0b471d8cc80a64fc8` (`type`), PRIMARY KEY (`id`)) ENGINE=InnoDB', undefined); + await queryRunner.query('CREATE TABLE IF NOT EXISTS `' + tablePrefix + 'execution_entity` (`id` int NOT NULL AUTO_INCREMENT, `data` text NOT NULL, `finished` tinyint NOT NULL, `mode` varchar(255) NOT NULL, `retryOf` varchar(255) NULL, `retrySuccessId` varchar(255) NULL, `startedAt` datetime NOT NULL, `stoppedAt` datetime NOT NULL, `workflowData` json NOT NULL, `workflowId` varchar(255) NULL, INDEX `IDX_' + tablePrefix + 'c4d999a5e90784e8caccf5589d` (`workflowId`), PRIMARY KEY (`id`)) ENGINE=InnoDB', undefined); await queryRunner.query('CREATE TABLE IF NOT EXISTS`' + tablePrefix + 'workflow_entity` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(128) NOT NULL, `active` tinyint NOT NULL, `nodes` json NOT NULL, `connections` json NOT NULL, `createdAt` datetime NOT NULL, `updatedAt` datetime NOT NULL, `settings` json NULL, `staticData` json NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB', undefined); } @@ -17,9 +17,9 @@ export class InitialMigration1588157391238 implements MigrationInterface { const tablePrefix = config.get('database.tablePrefix'); await queryRunner.query('DROP TABLE `' + tablePrefix + 'workflow_entity`', undefined); - await queryRunner.query('DROP INDEX `IDX_c4d999a5e90784e8caccf5589d` ON `' + tablePrefix + 'execution_entity`', undefined); + await queryRunner.query('DROP INDEX `IDX_' + tablePrefix + 'c4d999a5e90784e8caccf5589d` ON `' + tablePrefix + 'execution_entity`', undefined); await queryRunner.query('DROP TABLE `' + tablePrefix + 'execution_entity`', undefined); - await queryRunner.query('DROP INDEX `IDX_07fde106c0b471d8cc80a64fc8` ON `' + tablePrefix + 'credentials_entity`', undefined); + await queryRunner.query('DROP INDEX `IDX_' + tablePrefix + '07fde106c0b471d8cc80a64fc8` ON `' + tablePrefix + 'credentials_entity`', undefined); await queryRunner.query('DROP TABLE `' + tablePrefix + 'credentials_entity`', undefined); } diff --git a/packages/cli/src/databases/mysqldb/migrations/1592447867632-WebhookModel.ts b/packages/cli/src/databases/mysqldb/migrations/1592447867632-WebhookModel.ts new file mode 100644 index 0000000000..8a49080462 --- /dev/null +++ b/packages/cli/src/databases/mysqldb/migrations/1592447867632-WebhookModel.ts @@ -0,0 +1,59 @@ +import { + MigrationInterface, + QueryRunner, +} from 'typeorm'; + +import * as config from '../../../../config'; + +import { + IWorkflowDb, + NodeTypes, + WebhookHelpers, +} from '../../..'; + +import { + Workflow, +} from 'n8n-workflow'; + +import { + IWebhookDb, +} from '../../../Interfaces'; + +export class WebhookModel1592447867632 implements MigrationInterface { + name = 'WebhookModel1592447867632'; + + async up(queryRunner: QueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + + await queryRunner.query(`CREATE TABLE IF NOT EXISTS ${tablePrefix}webhook_entity (workflowId int NOT NULL, webhookPath varchar(255) NOT NULL, method varchar(255) NOT NULL, node varchar(255) NOT NULL, PRIMARY KEY (webhookPath, method)) ENGINE=InnoDB`); + + const workflows = await queryRunner.query(`SELECT * FROM ${tablePrefix}workflow_entity WHERE active=true`) as IWorkflowDb[]; + const data: IWebhookDb[] = []; + const nodeTypes = NodeTypes(); + for (const workflow of workflows) { + const workflowInstance = new Workflow({ id: workflow.id as string, name: workflow.name, nodes: workflow.nodes, connections: workflow.connections, active: workflow.active, nodeTypes, staticData: workflow.staticData, settings: workflow.settings }); + const webhooks = WebhookHelpers.getWorkflowWebhooksBasic(workflowInstance); + for (const webhook of webhooks) { + data.push({ + workflowId: workflowInstance.id as string, + webhookPath: webhook.path, + method: webhook.httpMethod, + node: webhook.node, + }); + } + } + + if (data.length !== 0) { + await queryRunner.manager.createQueryBuilder() + .insert() + .into(`${tablePrefix}webhook_entity`) + .values(data) + .execute(); + } + } + + async down(queryRunner: QueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + await queryRunner.query(`DROP TABLE ${tablePrefix}webhook_entity`); + } +} diff --git a/packages/cli/src/databases/mysqldb/migrations/1594902918301-CreateIndexStoppedAt.ts b/packages/cli/src/databases/mysqldb/migrations/1594902918301-CreateIndexStoppedAt.ts new file mode 100644 index 0000000000..2cc4c86367 --- /dev/null +++ b/packages/cli/src/databases/mysqldb/migrations/1594902918301-CreateIndexStoppedAt.ts @@ -0,0 +1,20 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; + +import * as config from '../../../../config'; + +export class CreateIndexStoppedAt1594902918301 implements MigrationInterface { + name = 'CreateIndexStoppedAt1594902918301' + + public async up(queryRunner: QueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + + await queryRunner.query('CREATE INDEX `IDX_' + tablePrefix + 'cefb067df2402f6aed0638a6c1` ON `' + tablePrefix + 'execution_entity` (`stoppedAt`)'); + } + + public async down(queryRunner: QueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + + await queryRunner.query('DROP INDEX `IDX_' + tablePrefix + 'cefb067df2402f6aed0638a6c1` ON `' + tablePrefix + 'execution_entity`'); + } + +} diff --git a/packages/cli/src/databases/mysqldb/migrations/index.ts b/packages/cli/src/databases/mysqldb/migrations/index.ts index ac2dcab467..7c0cb217ef 100644 --- a/packages/cli/src/databases/mysqldb/migrations/index.ts +++ b/packages/cli/src/databases/mysqldb/migrations/index.ts @@ -1 +1,3 @@ -export * from './1588157391238-InitialMigration'; \ No newline at end of file +export * from './1588157391238-InitialMigration'; +export * from './1592447867632-WebhookModel'; +export * from './1594902918301-CreateIndexStoppedAt'; diff --git a/packages/cli/src/databases/postgresdb/ExecutionEntity.ts b/packages/cli/src/databases/postgresdb/ExecutionEntity.ts index 8a7f691f0f..8b45336c2f 100644 --- a/packages/cli/src/databases/postgresdb/ExecutionEntity.ts +++ b/packages/cli/src/databases/postgresdb/ExecutionEntity.ts @@ -39,6 +39,7 @@ export class ExecutionEntity implements IExecutionFlattedDb { @Column('timestamp') startedAt: Date; + @Index() @Column('timestamp') stoppedAt: Date; diff --git a/packages/cli/src/databases/postgresdb/WebhookEntity.ts b/packages/cli/src/databases/postgresdb/WebhookEntity.ts new file mode 100644 index 0000000000..6e511cde74 --- /dev/null +++ b/packages/cli/src/databases/postgresdb/WebhookEntity.ts @@ -0,0 +1,25 @@ +import { + Column, + Entity, + PrimaryColumn, +} from 'typeorm'; + +import { + IWebhookDb, + } from '../../'; + +@Entity() +export class WebhookEntity implements IWebhookDb { + + @Column() + workflowId: number; + + @PrimaryColumn() + webhookPath: string; + + @PrimaryColumn() + method: string; + + @Column() + node: string; +} diff --git a/packages/cli/src/databases/postgresdb/index.ts b/packages/cli/src/databases/postgresdb/index.ts index 164d67fd0c..bd6b9abd60 100644 --- a/packages/cli/src/databases/postgresdb/index.ts +++ b/packages/cli/src/databases/postgresdb/index.ts @@ -1,3 +1,5 @@ export * from './CredentialsEntity'; export * from './ExecutionEntity'; export * from './WorkflowEntity'; +export * from './WebhookEntity'; + diff --git a/packages/cli/src/databases/postgresdb/migrations/1587669153312-InitialMigration.ts b/packages/cli/src/databases/postgresdb/migrations/1587669153312-InitialMigration.ts index 555015c10d..eace7a92fb 100644 --- a/packages/cli/src/databases/postgresdb/migrations/1587669153312-InitialMigration.ts +++ b/packages/cli/src/databases/postgresdb/migrations/1587669153312-InitialMigration.ts @@ -1,4 +1,5 @@ -import { MigrationInterface, QueryRunner } from 'typeorm'; +import { + MigrationInterface, QueryRunner } from 'typeorm'; import * as config from '../../../../config'; @@ -7,29 +8,31 @@ export class InitialMigration1587669153312 implements MigrationInterface { async up(queryRunner: QueryRunner): Promise { let tablePrefix = config.get('database.tablePrefix'); + const tablePrefixIndex = tablePrefix; const schema = config.get('database.postgresdb.schema'); if (schema) { tablePrefix = schema + '.' + tablePrefix; } - await queryRunner.query(`CREATE TABLE IF NOT EXISTS ${tablePrefix}credentials_entity ("id" SERIAL NOT NULL, "name" character varying(128) NOT NULL, "data" text NOT NULL, "type" character varying(32) NOT NULL, "nodesAccess" json NOT NULL, "createdAt" TIMESTAMP NOT NULL, "updatedAt" TIMESTAMP NOT NULL, CONSTRAINT PK_814c3d3c36e8a27fa8edb761b0e PRIMARY KEY ("id"))`, undefined); - await queryRunner.query(`CREATE INDEX IF NOT EXISTS IDX_07fde106c0b471d8cc80a64fc8 ON ${tablePrefix}credentials_entity (type) `, undefined); - await queryRunner.query(`CREATE TABLE IF NOT EXISTS ${tablePrefix}execution_entity ("id" SERIAL NOT NULL, "data" text NOT NULL, "finished" boolean NOT NULL, "mode" character varying NOT NULL, "retryOf" character varying, "retrySuccessId" character varying, "startedAt" TIMESTAMP NOT NULL, "stoppedAt" TIMESTAMP NOT NULL, "workflowData" json NOT NULL, "workflowId" character varying, CONSTRAINT PK_e3e63bbf986767844bbe1166d4e PRIMARY KEY ("id"))`, undefined); - await queryRunner.query(`CREATE INDEX IF NOT EXISTS IDX_c4d999a5e90784e8caccf5589d ON ${tablePrefix}execution_entity ("workflowId") `, undefined); - await queryRunner.query(`CREATE TABLE IF NOT EXISTS ${tablePrefix}workflow_entity ("id" SERIAL NOT NULL, "name" character varying(128) NOT NULL, "active" boolean NOT NULL, "nodes" json NOT NULL, "connections" json NOT NULL, "createdAt" TIMESTAMP NOT NULL, "updatedAt" TIMESTAMP NOT NULL, "settings" json, "staticData" json, CONSTRAINT PK_eded7d72664448da7745d551207 PRIMARY KEY ("id"))`, undefined); + await queryRunner.query(`CREATE TABLE IF NOT EXISTS ${tablePrefix}credentials_entity ("id" SERIAL NOT NULL, "name" character varying(128) NOT NULL, "data" text NOT NULL, "type" character varying(32) NOT NULL, "nodesAccess" json NOT NULL, "createdAt" TIMESTAMP NOT NULL, "updatedAt" TIMESTAMP NOT NULL, CONSTRAINT PK_${tablePrefixIndex}814c3d3c36e8a27fa8edb761b0e PRIMARY KEY ("id"))`, undefined); + await queryRunner.query(`CREATE INDEX IF NOT EXISTS IDX_${tablePrefixIndex}07fde106c0b471d8cc80a64fc8 ON ${tablePrefix}credentials_entity (type) `, undefined); + await queryRunner.query(`CREATE TABLE IF NOT EXISTS ${tablePrefix}execution_entity ("id" SERIAL NOT NULL, "data" text NOT NULL, "finished" boolean NOT NULL, "mode" character varying NOT NULL, "retryOf" character varying, "retrySuccessId" character varying, "startedAt" TIMESTAMP NOT NULL, "stoppedAt" TIMESTAMP NOT NULL, "workflowData" json NOT NULL, "workflowId" character varying, CONSTRAINT PK_${tablePrefixIndex}e3e63bbf986767844bbe1166d4e PRIMARY KEY ("id"))`, undefined); + await queryRunner.query(`CREATE INDEX IF NOT EXISTS IDX_${tablePrefixIndex}c4d999a5e90784e8caccf5589d ON ${tablePrefix}execution_entity ("workflowId") `, undefined); + await queryRunner.query(`CREATE TABLE IF NOT EXISTS ${tablePrefix}workflow_entity ("id" SERIAL NOT NULL, "name" character varying(128) NOT NULL, "active" boolean NOT NULL, "nodes" json NOT NULL, "connections" json NOT NULL, "createdAt" TIMESTAMP NOT NULL, "updatedAt" TIMESTAMP NOT NULL, "settings" json, "staticData" json, CONSTRAINT PK_${tablePrefixIndex}eded7d72664448da7745d551207 PRIMARY KEY ("id"))`, undefined); } async down(queryRunner: QueryRunner): Promise { let tablePrefix = config.get('database.tablePrefix'); + const tablePrefixIndex = tablePrefix; const schema = config.get('database.postgresdb.schema'); if (schema) { tablePrefix = schema + '.' + tablePrefix; } await queryRunner.query(`DROP TABLE ${tablePrefix}workflow_entity`, undefined); - await queryRunner.query(`DROP INDEX IDX_c4d999a5e90784e8caccf5589d`, undefined); + await queryRunner.query(`DROP INDEX IDX_${tablePrefixIndex}c4d999a5e90784e8caccf5589d`, undefined); await queryRunner.query(`DROP TABLE ${tablePrefix}execution_entity`, undefined); - await queryRunner.query(`DROP INDEX IDX_07fde106c0b471d8cc80a64fc8`, undefined); + await queryRunner.query(`DROP INDEX IDX_${tablePrefixIndex}07fde106c0b471d8cc80a64fc8`, undefined); await queryRunner.query(`DROP TABLE ${tablePrefix}credentials_entity`, undefined); } diff --git a/packages/cli/src/databases/postgresdb/migrations/1589476000887-WebhookModel.ts b/packages/cli/src/databases/postgresdb/migrations/1589476000887-WebhookModel.ts new file mode 100644 index 0000000000..e53fc28915 --- /dev/null +++ b/packages/cli/src/databases/postgresdb/migrations/1589476000887-WebhookModel.ts @@ -0,0 +1,69 @@ +import { + MigrationInterface, + QueryRunner, +} from 'typeorm'; + +import { + IWorkflowDb, + NodeTypes, + WebhookHelpers, +} from '../../..'; + +import { + Workflow, +} from 'n8n-workflow'; + +import { + IWebhookDb, +} from '../../../Interfaces'; + +import * as config from '../../../../config'; + +export class WebhookModel1589476000887 implements MigrationInterface { + name = 'WebhookModel1589476000887'; + + async up(queryRunner: QueryRunner): Promise { + let tablePrefix = config.get('database.tablePrefix'); + const tablePrefixIndex = tablePrefix; + const schema = config.get('database.postgresdb.schema'); + if (schema) { + tablePrefix = schema + '.' + tablePrefix; + } + + await queryRunner.query(`CREATE TABLE ${tablePrefix}webhook_entity ("workflowId" integer NOT NULL, "webhookPath" character varying NOT NULL, "method" character varying NOT NULL, "node" character varying NOT NULL, CONSTRAINT "PK_${tablePrefixIndex}b21ace2e13596ccd87dc9bf4ea6" PRIMARY KEY ("webhookPath", "method"))`, undefined); + + const workflows = await queryRunner.query(`SELECT * FROM ${tablePrefix}workflow_entity WHERE active=true`) as IWorkflowDb[]; + const data: IWebhookDb[] = []; + const nodeTypes = NodeTypes(); + for (const workflow of workflows) { + const workflowInstance = new Workflow({ id: workflow.id as string, name: workflow.name, nodes: workflow.nodes, connections: workflow.connections, active: workflow.active, nodeTypes, staticData: workflow.staticData, settings: workflow.settings }); + const webhooks = WebhookHelpers.getWorkflowWebhooksBasic(workflowInstance); + for (const webhook of webhooks) { + data.push({ + workflowId: workflowInstance.id as string, + webhookPath: webhook.path, + method: webhook.httpMethod, + node: webhook.node, + }); + } + } + + if (data.length !== 0) { + await queryRunner.manager.createQueryBuilder() + .insert() + .into(`${tablePrefix}webhook_entity`) + .values(data) + .execute(); + } + } + + async down(queryRunner: QueryRunner): Promise { + let tablePrefix = config.get('database.tablePrefix'); + const schema = config.get('database.postgresdb.schema'); + if (schema) { + tablePrefix = schema + '.' + tablePrefix; + } + await queryRunner.query(`DROP TABLE ${tablePrefix}webhook_entity`, undefined); + } + +} diff --git a/packages/cli/src/databases/postgresdb/migrations/1594828256133-CreateIndexStoppedAt.ts b/packages/cli/src/databases/postgresdb/migrations/1594828256133-CreateIndexStoppedAt.ts new file mode 100644 index 0000000000..7dd9578634 --- /dev/null +++ b/packages/cli/src/databases/postgresdb/migrations/1594828256133-CreateIndexStoppedAt.ts @@ -0,0 +1,25 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; + +import * as config from '../../../../config'; + +export class CreateIndexStoppedAt1594828256133 implements MigrationInterface { + name = 'CreateIndexStoppedAt1594828256133' + + public async up(queryRunner: QueryRunner): Promise { + let tablePrefix = config.get('database.tablePrefix'); + const tablePrefixPure = tablePrefix; + const schema = config.get('database.postgresdb.schema'); + if (schema) { + tablePrefix = schema + '.' + tablePrefix; + } + + await queryRunner.query(`CREATE INDEX IF NOT EXISTS IDX_${tablePrefixPure}33228da131bb1112247cf52a42 ON ${tablePrefix}execution_entity ("stoppedAt") `); + } + + public async down(queryRunner: QueryRunner): Promise { + let tablePrefix = config.get('database.tablePrefix'); + + await queryRunner.query(`DROP INDEX IDX_${tablePrefix}33228da131bb1112247cf52a42`); + } + +} diff --git a/packages/cli/src/databases/postgresdb/migrations/index.ts b/packages/cli/src/databases/postgresdb/migrations/index.ts index 5bb6551492..3b10537067 100644 --- a/packages/cli/src/databases/postgresdb/migrations/index.ts +++ b/packages/cli/src/databases/postgresdb/migrations/index.ts @@ -1 +1,4 @@ export * from './1587669153312-InitialMigration'; +export * from './1589476000887-WebhookModel'; +export * from './1594828256133-CreateIndexStoppedAt'; + diff --git a/packages/cli/src/databases/sqlite/ExecutionEntity.ts b/packages/cli/src/databases/sqlite/ExecutionEntity.ts index 825fed7fb5..bb7de2605d 100644 --- a/packages/cli/src/databases/sqlite/ExecutionEntity.ts +++ b/packages/cli/src/databases/sqlite/ExecutionEntity.ts @@ -39,6 +39,7 @@ export class ExecutionEntity implements IExecutionFlattedDb { @Column() startedAt: Date; + @Index() @Column() stoppedAt: Date; diff --git a/packages/cli/src/databases/sqlite/WebhookEntity.ts b/packages/cli/src/databases/sqlite/WebhookEntity.ts new file mode 100644 index 0000000000..a78fd34ae9 --- /dev/null +++ b/packages/cli/src/databases/sqlite/WebhookEntity.ts @@ -0,0 +1,25 @@ +import { + Column, + Entity, + PrimaryColumn, +} from 'typeorm'; + +import { + IWebhookDb, + } from '../../Interfaces'; + +@Entity() +export class WebhookEntity implements IWebhookDb { + + @Column() + workflowId: number; + + @PrimaryColumn() + webhookPath: string; + + @PrimaryColumn() + method: string; + + @Column() + node: string; +} diff --git a/packages/cli/src/databases/sqlite/index.ts b/packages/cli/src/databases/sqlite/index.ts index 2c7d6e25e9..a3494531db 100644 --- a/packages/cli/src/databases/sqlite/index.ts +++ b/packages/cli/src/databases/sqlite/index.ts @@ -1,4 +1,4 @@ export * from './CredentialsEntity'; export * from './ExecutionEntity'; export * from './WorkflowEntity'; - +export * from './WebhookEntity'; diff --git a/packages/cli/src/databases/sqlite/migrations/1588102412422-InitialMigration.ts b/packages/cli/src/databases/sqlite/migrations/1588102412422-InitialMigration.ts index 31b271d633..09a0da911a 100644 --- a/packages/cli/src/databases/sqlite/migrations/1588102412422-InitialMigration.ts +++ b/packages/cli/src/databases/sqlite/migrations/1588102412422-InitialMigration.ts @@ -1,4 +1,7 @@ -import { MigrationInterface, QueryRunner } from "typeorm"; +import { + MigrationInterface, + QueryRunner, +} from 'typeorm'; import * as config from '../../../../config'; @@ -9,9 +12,9 @@ export class InitialMigration1588102412422 implements MigrationInterface { const tablePrefix = config.get('database.tablePrefix'); await queryRunner.query(`CREATE TABLE IF NOT EXISTS "${tablePrefix}credentials_entity" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(128) NOT NULL, "data" text NOT NULL, "type" varchar(32) NOT NULL, "nodesAccess" text NOT NULL, "createdAt" datetime NOT NULL, "updatedAt" datetime NOT NULL)`, undefined); - await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_07fde106c0b471d8cc80a64fc8" ON "${tablePrefix}credentials_entity" ("type") `, undefined); + await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_${tablePrefix}07fde106c0b471d8cc80a64fc8" ON "${tablePrefix}credentials_entity" ("type") `, undefined); await queryRunner.query(`CREATE TABLE IF NOT EXISTS "${tablePrefix}execution_entity" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "data" text NOT NULL, "finished" boolean NOT NULL, "mode" varchar NOT NULL, "retryOf" varchar, "retrySuccessId" varchar, "startedAt" datetime NOT NULL, "stoppedAt" datetime NOT NULL, "workflowData" text NOT NULL, "workflowId" varchar)`, undefined); - await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_c4d999a5e90784e8caccf5589d" ON "${tablePrefix}execution_entity" ("workflowId") `, undefined); + await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_${tablePrefix}c4d999a5e90784e8caccf5589d" ON "${tablePrefix}execution_entity" ("workflowId") `, undefined); await queryRunner.query(`CREATE TABLE IF NOT EXISTS "${tablePrefix}workflow_entity" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(128) NOT NULL, "active" boolean NOT NULL, "nodes" text NOT NULL, "connections" text NOT NULL, "createdAt" datetime NOT NULL, "updatedAt" datetime NOT NULL, "settings" text, "staticData" text)`, undefined); } @@ -19,9 +22,9 @@ export class InitialMigration1588102412422 implements MigrationInterface { const tablePrefix = config.get('database.tablePrefix'); await queryRunner.query(`DROP TABLE "${tablePrefix}workflow_entity"`, undefined); - await queryRunner.query(`DROP INDEX "IDX_c4d999a5e90784e8caccf5589d"`, undefined); + await queryRunner.query(`DROP INDEX "IDX_${tablePrefix}c4d999a5e90784e8caccf5589d"`, undefined); await queryRunner.query(`DROP TABLE "${tablePrefix}execution_entity"`, undefined); - await queryRunner.query(`DROP INDEX "IDX_07fde106c0b471d8cc80a64fc8"`, undefined); + await queryRunner.query(`DROP INDEX "IDX_${tablePrefix}07fde106c0b471d8cc80a64fc8"`, undefined); await queryRunner.query(`DROP TABLE "${tablePrefix}credentials_entity"`, undefined); } diff --git a/packages/cli/src/databases/sqlite/migrations/1592445003908-WebhookModel.ts b/packages/cli/src/databases/sqlite/migrations/1592445003908-WebhookModel.ts new file mode 100644 index 0000000000..92704482b2 --- /dev/null +++ b/packages/cli/src/databases/sqlite/migrations/1592445003908-WebhookModel.ts @@ -0,0 +1,63 @@ +import { + MigrationInterface, + QueryRunner, +} from 'typeorm'; + +import * as config from '../../../../config'; + +import { + IWorkflowDb, + NodeTypes, + WebhookHelpers, +} from '../../..'; + +import { + Workflow, +} from 'n8n-workflow'; + +import { + IWebhookDb, +} from '../../../Interfaces'; + +export class WebhookModel1592445003908 implements MigrationInterface { + name = 'WebhookModel1592445003908'; + + async up(queryRunner: QueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + + await queryRunner.query(`CREATE TABLE IF NOT EXISTS ${tablePrefix}webhook_entity ("workflowId" integer NOT NULL, "webhookPath" varchar NOT NULL, "method" varchar NOT NULL, "node" varchar NOT NULL, PRIMARY KEY ("webhookPath", "method"))`); + + const workflows = await queryRunner.query(`SELECT * FROM ${tablePrefix}workflow_entity WHERE active=true`) as IWorkflowDb[]; + const data: IWebhookDb[] = []; + const nodeTypes = NodeTypes(); + for (const workflow of workflows) { + workflow.nodes = JSON.parse(workflow.nodes as unknown as string); + workflow.connections = JSON.parse(workflow.connections as unknown as string); + workflow.staticData = JSON.parse(workflow.staticData as unknown as string); + workflow.settings = JSON.parse(workflow.settings as unknown as string); + const workflowInstance = new Workflow({ id: workflow.id as string, name: workflow.name, nodes: workflow.nodes, connections: workflow.connections, active: workflow.active, nodeTypes, staticData: workflow.staticData, settings: workflow.settings }); + const webhooks = WebhookHelpers.getWorkflowWebhooksBasic(workflowInstance); + for (const webhook of webhooks) { + data.push({ + workflowId: workflowInstance.id as string, + webhookPath: webhook.path, + method: webhook.httpMethod, + node: webhook.node, + }); + } + } + + if (data.length !== 0) { + await queryRunner.manager.createQueryBuilder() + .insert() + .into(`${tablePrefix}webhook_entity`) + .values(data) + .execute(); + } + } + + async down(queryRunner: QueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + await queryRunner.query(`DROP TABLE ${tablePrefix}webhook_entity`); + } +} diff --git a/packages/cli/src/databases/sqlite/migrations/1594825041918-CreateIndexStoppedAt.ts b/packages/cli/src/databases/sqlite/migrations/1594825041918-CreateIndexStoppedAt.ts new file mode 100644 index 0000000000..cfa4812020 --- /dev/null +++ b/packages/cli/src/databases/sqlite/migrations/1594825041918-CreateIndexStoppedAt.ts @@ -0,0 +1,20 @@ +import {MigrationInterface, QueryRunner} from "typeorm"; + +import * as config from '../../../../config'; + +export class CreateIndexStoppedAt1594825041918 implements MigrationInterface { + name = 'CreateIndexStoppedAt1594825041918' + + public async up(queryRunner: QueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + + await queryRunner.query(`CREATE INDEX "IDX_${tablePrefix}cefb067df2402f6aed0638a6c1" ON "execution_entity" ("stoppedAt") `); + } + + public async down(queryRunner: QueryRunner): Promise { + const tablePrefix = config.get('database.tablePrefix'); + + await queryRunner.query(`DROP INDEX "IDX_${tablePrefix}cefb067df2402f6aed0638a6c1"`); + } + +} diff --git a/packages/cli/src/databases/sqlite/migrations/index.ts b/packages/cli/src/databases/sqlite/migrations/index.ts index 8d9a0a0b16..f0a2068b92 100644 --- a/packages/cli/src/databases/sqlite/migrations/index.ts +++ b/packages/cli/src/databases/sqlite/migrations/index.ts @@ -1 +1,3 @@ -export * from './1588102412422-InitialMigration'; \ No newline at end of file +export * from './1588102412422-InitialMigration'; +export * from './1592445003908-WebhookModel'; +export * from './1594825041918-CreateIndexStoppedAt' diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 3916e79edd..3a6337a35d 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,6 +1,7 @@ export * from './CredentialsHelper'; export * from './CredentialTypes'; export * from './CredentialsOverwrites'; +export * from './ExternalHooks'; export * from './Interfaces'; export * from './LoadNodesAndCredentials'; export * from './NodeTypes'; diff --git a/packages/core/LICENSE.md b/packages/core/LICENSE.md index aac54547eb..24a7d38fc9 100644 --- a/packages/core/LICENSE.md +++ b/packages/core/LICENSE.md @@ -215,7 +215,7 @@ Licensor: n8n GmbH same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2020 n8n GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/core/README.md b/packages/core/README.md index c1b11d9fbf..b1e2e31410 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -1,6 +1,6 @@ # n8n-core -![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/docs/images/n8n-logo.png) +![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/assets/n8n-logo.png) Core components for n8n diff --git a/packages/core/package.json b/packages/core/package.json index 259ce7d4cb..4fb55a9d8d 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "n8n-core", - "version": "0.35.0", + "version": "0.39.0", "description": "Core functionality of n8n", "license": "SEE LICENSE IN LICENSE.md", "homepage": "https://n8n.io", @@ -30,7 +30,7 @@ "@types/express": "^4.16.1", "@types/jest": "^24.0.18", "@types/lodash.get": "^4.4.6", - "@types/mmmagic": "^0.4.29", + "@types/mime-types": "^2.1.0", "@types/node": "^10.10.1", "@types/request-promise-native": "^1.0.15", "jest": "^24.9.0", @@ -43,9 +43,10 @@ "client-oauth2": "^4.2.5", "cron": "^1.7.2", "crypto-js": "3.1.9-1", + "file-type": "^14.6.2", "lodash.get": "^4.4.2", - "mmmagic": "^0.5.2", - "n8n-workflow": "~0.32.0", + "mime-types": "^2.1.27", + "n8n-workflow": "~0.35.0", "p-cancelable": "^2.0.0", "request": "^2.88.2", "request-promise-native": "^1.0.7" diff --git a/packages/core/src/ActiveWebhooks.ts b/packages/core/src/ActiveWebhooks.ts index 17cf753830..529fe01af3 100644 --- a/packages/core/src/ActiveWebhooks.ts +++ b/packages/core/src/ActiveWebhooks.ts @@ -35,13 +35,20 @@ export class ActiveWebhooks { throw new Error('Webhooks can only be added for saved workflows as an id is needed!'); } + const webhookKey = this.getWebhookKey(webhookData.httpMethod, webhookData.path); + + //check that there is not a webhook already registed with that path/method + if (this.webhookUrls[webhookKey] !== undefined) { + throw new Error(`Test-Webhook can not be activated because another one with the same method "${webhookData.httpMethod}" and path "${webhookData.path}" is already active!`); + } + if (this.workflowWebhooks[webhookData.workflowId] === undefined) { this.workflowWebhooks[webhookData.workflowId] = []; } // Make the webhook available directly because sometimes to create it successfully // it gets called - this.webhookUrls[this.getWebhookKey(webhookData.httpMethod, webhookData.path)] = webhookData; + this.webhookUrls[webhookKey] = webhookData; const webhookExists = await workflow.runWebhookMethod('checkExists', webhookData, NodeExecuteFunctions, mode, this.testWebhooks); if (webhookExists === false) { diff --git a/packages/core/src/NodeExecuteFunctions.ts b/packages/core/src/NodeExecuteFunctions.ts index d500d56f88..f9811099ec 100644 --- a/packages/core/src/NodeExecuteFunctions.ts +++ b/packages/core/src/NodeExecuteFunctions.ts @@ -44,14 +44,9 @@ import * as express from 'express'; import * as path from 'path'; import { OptionsWithUrl, OptionsWithUri } from 'request'; import * as requestPromise from 'request-promise-native'; - -import { Magic, MAGIC_MIME_TYPE } from 'mmmagic'; - import { createHmac } from 'crypto'; - - -const magic = new Magic(MAGIC_MIME_TYPE); - +import { fromBuffer } from 'file-type'; +import { lookup } from 'mime-types'; /** @@ -66,18 +61,28 @@ const magic = new Magic(MAGIC_MIME_TYPE); */ export async function prepareBinaryData(binaryData: Buffer, filePath?: string, mimeType?: string): Promise { if (!mimeType) { - // If not mime type is given figure it out - mimeType = await new Promise( - (resolve, reject) => { - magic.detect(binaryData, (err: Error, mimeType: string) => { - if (err) { - return reject(err); - } + // If no mime type is given figure it out - return resolve(mimeType); - }); + if (filePath) { + // Use file path to guess mime type + const mimeTypeLookup = lookup(filePath); + if (mimeTypeLookup) { + mimeType = mimeTypeLookup; } - ); + } + + if (!mimeType) { + // Use buffer to guess mime type + const fileTypeData = await fromBuffer(binaryData); + if (fileTypeData) { + mimeType = fileTypeData.mime; + } + } + + if (!mimeType) { + // Fall back to text + mimeType = 'text/plain'; + } } const returnData: IBinaryData = { @@ -413,7 +418,8 @@ export function getNodeWebhookUrl(name: string, workflow: Workflow, node: INode, return undefined; } - return NodeHelpers.getNodeWebhookUrl(baseUrl, workflow.id!, node, path.toString()); + const isFullPath: boolean = workflow.getSimpleParameterValue(node, webhookDescription['isFullPath'], false) as boolean; + return NodeHelpers.getNodeWebhookUrl(baseUrl, workflow.id!, node, path.toString(), isFullPath); } diff --git a/packages/core/src/UserSettings.ts b/packages/core/src/UserSettings.ts index 211341ed25..fb38fc779c 100644 --- a/packages/core/src/UserSettings.ts +++ b/packages/core/src/UserSettings.ts @@ -41,8 +41,13 @@ export async function prepareUserSettings(): Promise { userSettings = {}; } - // Settings and/or key do not exist. So generate a new encryption key - userSettings.encryptionKey = randomBytes(24).toString('base64'); + if (process.env[ENCRYPTION_KEY_ENV_OVERWRITE] !== undefined) { + // Use the encryption key which got set via environment + userSettings.encryptionKey = process.env[ENCRYPTION_KEY_ENV_OVERWRITE]; + } else { + // Generate a new encryption key + userSettings.encryptionKey = randomBytes(24).toString('base64'); + } console.log(`UserSettings got generated and saved to: ${settingsPath}`); diff --git a/packages/core/src/WorkflowExecute.ts b/packages/core/src/WorkflowExecute.ts index 1e8b8898a7..c30be39ca1 100644 --- a/packages/core/src/WorkflowExecute.ts +++ b/packages/core/src/WorkflowExecute.ts @@ -459,7 +459,7 @@ export class WorkflowExecute { let executionData: IExecuteData; let executionError: IExecutionError | undefined; let executionNode: INode; - let nodeSuccessData: INodeExecutionData[][] | null; + let nodeSuccessData: INodeExecutionData[][] | null | undefined; let runIndex: number; let startTime: number; let taskData: ITaskData; @@ -593,9 +593,15 @@ export class WorkflowExecute { } } - this.runExecutionData.resultData.lastNodeExecuted = executionData.node.name; nodeSuccessData = await workflow.runNode(executionData.node, executionData.data, this.runExecutionData, runIndex, this.additionalData, NodeExecuteFunctions, this.mode); + if (nodeSuccessData === undefined) { + // Node did not get executed + nodeSuccessData = null; + } else { + this.runExecutionData.resultData.lastNodeExecuted = executionData.node.name; + } + if (nodeSuccessData === null || nodeSuccessData[0][0] === undefined) { if (executionData.node.alwaysOutputData === true) { nodeSuccessData = nodeSuccessData || []; diff --git a/packages/editor-ui/LICENSE.md b/packages/editor-ui/LICENSE.md index aac54547eb..24a7d38fc9 100644 --- a/packages/editor-ui/LICENSE.md +++ b/packages/editor-ui/LICENSE.md @@ -215,7 +215,7 @@ Licensor: n8n GmbH same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2020 n8n GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/editor-ui/README.md b/packages/editor-ui/README.md index cf05ce87d1..f4949d3d8e 100644 --- a/packages/editor-ui/README.md +++ b/packages/editor-ui/README.md @@ -1,6 +1,6 @@ # n8n-editor-ui -![n8n.io - Workflow Automation](https://n8n.io/n8n-logo.png) +![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/assets/n8n-logo.png) The UI to create and update n8n workflows diff --git a/packages/editor-ui/package.json b/packages/editor-ui/package.json index 8543d2fdd0..4bcc6b8579 100644 --- a/packages/editor-ui/package.json +++ b/packages/editor-ui/package.json @@ -1,6 +1,6 @@ { "name": "n8n-editor-ui", - "version": "0.46.0", + "version": "0.50.0", "description": "Workflow Editor UI for n8n", "license": "SEE LICENSE IN LICENSE.md", "homepage": "https://n8n.io", @@ -14,7 +14,7 @@ "url": "git+https://github.com/n8n-io/n8n.git" }, "scripts": { - "build": "vue-cli-service build", + "build": "cross-env VUE_APP_PUBLIC_PATH=\"/%BASE_PATH%/\" vue-cli-service build", "dev": "npm run serve", "lint": "vue-cli-service lint", "serve": "cross-env VUE_APP_URL_BASE_API=http://localhost:5678/ vue-cli-service serve", @@ -23,7 +23,9 @@ "test:e2e": "vue-cli-service test:e2e", "test:unit": "vue-cli-service test:unit" }, - "dependencies": {}, + "dependencies": { + "uuid": "^8.1.0" + }, "devDependencies": { "@beyonk/google-fonts-webpack-plugin": "^1.2.3", "@fortawesome/fontawesome-svg-core": "^1.2.19", @@ -64,7 +66,7 @@ "lodash.debounce": "^4.0.8", "lodash.get": "^4.4.2", "lodash.set": "^4.3.2", - "n8n-workflow": "~0.32.0", + "n8n-workflow": "~0.35.0", "node-sass": "^4.12.0", "prismjs": "^1.17.1", "quill": "^2.0.0-dev.3", diff --git a/packages/editor-ui/public/index.html b/packages/editor-ui/public/index.html index 2f2450023d..b533aea170 100644 --- a/packages/editor-ui/public/index.html +++ b/packages/editor-ui/public/index.html @@ -4,12 +4,13 @@ - + + n8n.io - Workflow Automation
diff --git a/packages/editor-ui/src/components/ExpressionInput.vue b/packages/editor-ui/src/components/ExpressionInput.vue index 543eb12f22..d0c734e2c6 100644 --- a/packages/editor-ui/src/components/ExpressionInput.vue +++ b/packages/editor-ui/src/components/ExpressionInput.vue @@ -122,6 +122,13 @@ export default mixins( readOnly: !!this.resolvedValue, modules: { autoformat: {}, + keyboard: { + bindings: { + 'list autofill': { + prefix: /^$/, + }, + }, + }, }, }); diff --git a/packages/editor-ui/src/components/MainSidebar.vue b/packages/editor-ui/src/components/MainSidebar.vue index 71388c2cd3..baea830b01 100644 --- a/packages/editor-ui/src/components/MainSidebar.vue +++ b/packages/editor-ui/src/components/MainSidebar.vue @@ -16,7 +16,7 @@ @@ -208,6 +208,8 @@ export default mixins( data () { return { aboutDialogVisible: false, + // @ts-ignore + basePath: this.$store.getters.getBaseUrl, isCollapsed: true, credentialNewDialogVisible: false, credentialOpenDialogVisible: false, diff --git a/packages/editor-ui/src/components/NodeWebhooks.vue b/packages/editor-ui/src/components/NodeWebhooks.vue index b649575a0b..e2875a49fd 100644 --- a/packages/editor-ui/src/components/NodeWebhooks.vue +++ b/packages/editor-ui/src/components/NodeWebhooks.vue @@ -110,8 +110,9 @@ export default mixins( const workflowId = this.$store.getters.workflowId; const path = this.getValue(webhookData, 'path'); + const isFullPath = this.getValue(webhookData, 'isFullPath') as unknown as boolean || false; - return NodeHelpers.getNodeWebhookUrl(baseUrl, workflowId, this.node, path); + return NodeHelpers.getNodeWebhookUrl(baseUrl, workflowId, this.node, path, isFullPath); }, }, watch: { diff --git a/packages/editor-ui/src/components/RunData.vue b/packages/editor-ui/src/components/RunData.vue index b3729e4f68..42fbaa5b19 100644 --- a/packages/editor-ui/src/components/RunData.vue +++ b/packages/editor-ui/src/components/RunData.vue @@ -19,7 +19,7 @@
- + Results: {{ dataCount }} Results: @@ -248,7 +248,11 @@ export default mixins( return executionData.resultData.runData; }, maxDisplayItemsOptions (): number[] { - return [25, 50, 100, 250, 500, 1000, this.dataCount].filter(option => option <= this.dataCount); + const options = [25, 50, 100, 250, 500, 1000].filter(option => option <= this.dataCount); + if (!options.includes(this.dataCount)) { + options.push(this.dataCount); + } + return options; }, node (): INodeUi | null { return this.$store.getters.activeNode; diff --git a/packages/editor-ui/src/router.ts b/packages/editor-ui/src/router.ts index e82b30b588..348a1ea66b 100644 --- a/packages/editor-ui/src/router.ts +++ b/packages/editor-ui/src/router.ts @@ -8,7 +8,8 @@ Vue.use(Router); export default new Router({ mode: 'history', - base: process.env.BASE_URL, + // @ts-ignore + base: window.BASE_PATH === '/%BASE_PATH%/' ? '/' : window.BASE_PATH, routes: [ { path: '/execution/:id', diff --git a/packages/editor-ui/src/store.ts b/packages/editor-ui/src/store.ts index b9762bb616..e0ba93b7cf 100644 --- a/packages/editor-ui/src/store.ts +++ b/packages/editor-ui/src/store.ts @@ -29,8 +29,6 @@ import { XYPositon, } from './Interface'; -import { get } from 'lodash'; - Vue.use(Vuex); export const store = new Vuex.Store({ @@ -40,7 +38,8 @@ export const store = new Vuex.Store({ activeWorkflows: [] as string[], activeActions: [] as string[], activeNode: null as string | null, - baseUrl: process.env.VUE_APP_URL_BASE_API ? process.env.VUE_APP_URL_BASE_API : '/', + // @ts-ignore + baseUrl: process.env.VUE_APP_URL_BASE_API ? process.env.VUE_APP_URL_BASE_API : (window.BASE_PATH === '/%BASE_PATH%/' ? '/' : window.BASE_PATH), credentials: null as ICredentialsResponse[] | null, credentialTypes: null as ICredentialType[] | null, endpointWebhook: 'webhook', diff --git a/packages/editor-ui/src/views/NodeView.vue b/packages/editor-ui/src/views/NodeView.vue index de89534e09..e22b98f595 100644 --- a/packages/editor-ui/src/views/NodeView.vue +++ b/packages/editor-ui/src/views/NodeView.vue @@ -126,6 +126,8 @@ import RunData from '@/components/RunData.vue'; import mixins from 'vue-typed-mixins'; +import { v4 as uuidv4 } from 'uuid'; + import { debounce } from 'lodash'; import axios from 'axios'; import { @@ -946,6 +948,10 @@ export default mixins( // Check if node-name is unique else find one that is newNodeData.name = this.getUniqueNodeName(newNodeData.name); + if (nodeTypeData.webhooks && nodeTypeData.webhooks.length) { + newNodeData.webhookId = uuidv4(); + } + await this.addNodes([newNodeData]); // Automatically deselect all nodes and select the current one and also active @@ -1579,6 +1585,11 @@ export default mixins( console.error(e); // eslint-disable-line no-console } node.parameters = nodeParameters !== null ? nodeParameters : {}; + + // if it's a webhook and the path is empty set the UUID as the default path + if (node.type === 'n8n-nodes-base.webhook' && node.parameters.path === '') { + node.parameters.path = node.webhookId as string; + } } foundNodeIssues = this.getNodeIssues(nodeType, node); diff --git a/packages/editor-ui/vue.config.js b/packages/editor-ui/vue.config.js index f70f41c5b2..cdcd8259f9 100644 --- a/packages/editor-ui/vue.config.js +++ b/packages/editor-ui/vue.config.js @@ -29,4 +29,5 @@ module.exports = { }, }, }, + publicPath: process.env.VUE_APP_PUBLIC_PATH ? process.env.VUE_APP_PUBLIC_PATH : '/', }; diff --git a/packages/node-dev/LICENSE.md b/packages/node-dev/LICENSE.md index aac54547eb..24a7d38fc9 100644 --- a/packages/node-dev/LICENSE.md +++ b/packages/node-dev/LICENSE.md @@ -215,7 +215,7 @@ Licensor: n8n GmbH same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2020 n8n GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/node-dev/README.md b/packages/node-dev/README.md index 1c3d8df52f..526b45cebf 100644 --- a/packages/node-dev/README.md +++ b/packages/node-dev/README.md @@ -1,6 +1,6 @@ # n8n-node-dev -![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/docs/images/n8n-logo.png) +![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/assets/n8n-logo.png) Currently very simple and not very sophisticated CLI which makes it easier to create credentials and nodes in TypeScript for n8n. @@ -127,7 +127,7 @@ export class MyNode implements INodeType { The "description" property has to be set on all nodes because it contains all the base information. Additionally do all nodes have to have exactly one of the -following methods defined which contains the the actual logic: +following methods defined which contains the actual logic: **Regular node** @@ -138,8 +138,8 @@ Method get called when the workflow gets executed By default always `execute` should be used especially when creating a third-party integration. The reason for that is that it is way more flexible and allows to, for example, return a different amount of items than it received -as input. This is very important when a node should query data like return -all users. In that case, does the node normally just receive one input-item +as input. This is very important when a node should query data like *return +all users*. In that case, does the node normally just receive one input-item but returns as many as users exist. So in doubt always `execute` should be used! @@ -188,10 +188,10 @@ The following properties can be set in the node description: - **outputs** [required]: Types of outputs the node has (currently only "main" exists) and the amount - **outputNames** [optional]: In case a node has multiple outputs names can be set that users know what data to expect - **maxNodes** [optional]: If not an unlimited amount of nodes of that type can exist in a workflow the max-amount can be specified - - **name** [required]: Nme of the node (for n8n to use internally in camelCase) + - **name** [required]: Name of the node (for n8n to use internally, in camelCase) - **properties** [required]: Properties which get displayed in the Editor UI and can be set by the user - **subtitle** [optional]: Text which should be displayed underneath the name of the node in the Editor UI (can be an expression) - - **version** [required]: Version of the node. Currently always "1" (integer). For future usage does not get used yet. + - **version** [required]: Version of the node. Currently always "1" (integer). For future usage, does not get used yet. - **webhooks** [optional]: Webhooks the node should listen to @@ -200,12 +200,12 @@ The following properties can be set in the node description: The following properties can be set in the node properties: - **default** [required]: Default value of the property - - **description** [required]: Description to display users in Editor UI - - **displayName** [required]: Name to display users in Editor UI + - **description** [required]: Description that is displayed to users in the Editor UI + - **displayName** [required]: Name that is displayed to users in the Editor UI - **displayOptions** [optional]: Defines logic to decide if a property should be displayed or not - - **name** [required]: Name of the property (for n8n to use internally in camelCase) + - **name** [required]: Name of the property (for n8n to use internally, in camelCase) - **options** [optional]: The options the user can select when type of property is "collection", "fixedCollection" or "options" - - **placeholder** [optional]: Placeholder text to display users in Editor UI + - **placeholder** [optional]: Placeholder text that is displayed to users in the Editor UI - **type** [required]: Type of the property. If it is for example a "string", "number", ... - **typeOptions** [optional]: Additional options for type. Like for example the min or max value of a number - **required** [optional]: Defines if the value has to be set or if it can stay empty @@ -215,11 +215,11 @@ The following properties can be set in the node properties: The following properties can be set in the node property options. -All properties are optional. The most, however, work only work when the node-property is of a specfic type. +All properties are optional. However, most only work when the node-property is of a specfic type. - - **alwaysOpenEditWindow** [type: string]: If set then the "Editor Window" will always open when the user tries to edit the field. Is helpful when long texts normally get used in the property + - **alwaysOpenEditWindow** [type: string]: If set then the "Editor Window" will always open when the user tries to edit the field. Helpful if long text is typically used in the property. - **loadOptionsMethod** [type: options]: Method to use to load options from an external service - - **maxValue** [type: number]: Maximal value of the number + - **maxValue** [type: number]: Maximum value of the number - **minValue** [type: number]: Minimum value of the number - **multipleValues** [type: all]: If set the property gets turned into an Array and the user can add multiple values - **multipleValueButtonText** [type: all]: Custom text for add button in case "multipleValues" got set diff --git a/packages/node-dev/package.json b/packages/node-dev/package.json index 9d859de394..8df65a2792 100644 --- a/packages/node-dev/package.json +++ b/packages/node-dev/package.json @@ -1,6 +1,6 @@ { "name": "n8n-node-dev", - "version": "0.7.0", + "version": "0.9.0", "description": "CLI to simplify n8n credentials/node development", "license": "SEE LICENSE IN LICENSE.md", "homepage": "https://n8n.io", @@ -58,8 +58,8 @@ "change-case": "^4.1.1", "copyfiles": "^2.1.1", "inquirer": "^7.0.0", - "n8n-core": "^0.31.0", - "n8n-workflow": "^0.28.0", + "n8n-core": "^0.36.0", + "n8n-workflow": "^0.33.0", "replace-in-file": "^6.0.0", "request": "^2.88.2", "tmp-promise": "^2.0.2", diff --git a/packages/node-dev/src/Build.ts b/packages/node-dev/src/Build.ts index ddb74add0a..fd695efb4b 100644 --- a/packages/node-dev/src/Build.ts +++ b/packages/node-dev/src/Build.ts @@ -105,10 +105,10 @@ export async function buildFiles (options?: IBuildOptions): Promise { } return new Promise((resolve, reject) => { + copyfiles([join(process.cwd(), './*.png'), outputDirectory], { up: true }, () => resolve(outputDirectory)); buildProcess.on('exit', code => { // Remove the tmp tsconfig file tsconfigData.cleanup(); - copyfiles([join(process.cwd(), './*.png'), outputDirectory], { up: true }, () => resolve(outputDirectory)); }); }); } diff --git a/packages/node-dev/templates/webhook/simple.ts b/packages/node-dev/templates/webhook/simple.ts index eaf1521e84..ab81ca51d2 100644 --- a/packages/node-dev/templates/webhook/simple.ts +++ b/packages/node-dev/templates/webhook/simple.ts @@ -27,7 +27,7 @@ export class ClassNameReplace implements INodeType { { name: 'default', httpMethod: 'POST', - reponseMode: 'onReceived', + responseMode: 'onReceived', // Each webhook property can either be hardcoded // like the above ones or referenced from a parameter // like the "path" property bellow diff --git a/packages/nodes-base/LICENSE.md b/packages/nodes-base/LICENSE.md index aac54547eb..24a7d38fc9 100644 --- a/packages/nodes-base/LICENSE.md +++ b/packages/nodes-base/LICENSE.md @@ -215,7 +215,7 @@ Licensor: n8n GmbH same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2020 n8n GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/nodes-base/README.md b/packages/nodes-base/README.md index bd069d0c3a..cfa12a488d 100644 --- a/packages/nodes-base/README.md +++ b/packages/nodes-base/README.md @@ -1,6 +1,6 @@ # n8n-nodes-base -![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/docs/images/n8n-logo.png) +![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/assets/n8n-logo.png) The nodes which are included by default in n8n diff --git a/packages/nodes-base/credentials/CircleCiApi.credentials.ts b/packages/nodes-base/credentials/CircleCiApi.credentials.ts new file mode 100644 index 0000000000..ef3104b5e6 --- /dev/null +++ b/packages/nodes-base/credentials/CircleCiApi.credentials.ts @@ -0,0 +1,17 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +export class CircleCiApi implements ICredentialType { + name = 'circleCiApi'; + displayName = 'CircleCI API'; + properties = [ + { + displayName: 'Personal API Token', + name: 'apiKey', + type: 'string' as NodePropertyTypes, + default: '', + }, + ]; +} diff --git a/packages/nodes-base/credentials/CrateDb.credentials.ts b/packages/nodes-base/credentials/CrateDb.credentials.ts new file mode 100644 index 0000000000..a5e0fb776c --- /dev/null +++ b/packages/nodes-base/credentials/CrateDb.credentials.ts @@ -0,0 +1,69 @@ +import { ICredentialType, NodePropertyTypes } from 'n8n-workflow'; + +export class CrateDb implements ICredentialType { + name = 'crateDb'; + displayName = 'CrateDB'; + properties = [ + { + displayName: 'Host', + name: 'host', + type: 'string' as NodePropertyTypes, + default: 'localhost', + }, + { + displayName: 'Database', + name: 'database', + type: 'string' as NodePropertyTypes, + default: 'doc', + }, + { + displayName: 'User', + name: 'user', + type: 'string' as NodePropertyTypes, + default: 'crate', + }, + { + displayName: 'Password', + name: 'password', + type: 'string' as NodePropertyTypes, + typeOptions: { + password: true, + }, + default: '', + }, + { + displayName: 'SSL', + name: 'ssl', + type: 'options' as NodePropertyTypes, + options: [ + { + name: 'disable', + value: 'disable', + }, + { + name: 'allow', + value: 'allow', + }, + { + name: 'require', + value: 'require', + }, + { + name: 'verify (not implemented)', + value: 'verify', + }, + { + name: 'verify-full (not implemented)', + value: 'verify-full', + }, + ], + default: 'disable', + }, + { + displayName: 'Port', + name: 'port', + type: 'number' as NodePropertyTypes, + default: 5432, + }, + ]; +} diff --git a/packages/nodes-base/credentials/DriftOAuth2Api.credentials.ts b/packages/nodes-base/credentials/DriftOAuth2Api.credentials.ts new file mode 100644 index 0000000000..1d25c49dfe --- /dev/null +++ b/packages/nodes-base/credentials/DriftOAuth2Api.credentials.ts @@ -0,0 +1,47 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class DriftOAuth2Api implements ICredentialType { + name = 'driftOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Drift OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://dev.drift.com/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://driftapi.com/oauth2/token', + required: true, + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'body', + }, + ]; +} diff --git a/packages/nodes-base/credentials/EventbriteApi.credentials.ts b/packages/nodes-base/credentials/EventbriteApi.credentials.ts index 9fa48753fb..e54be8580c 100644 --- a/packages/nodes-base/credentials/EventbriteApi.credentials.ts +++ b/packages/nodes-base/credentials/EventbriteApi.credentials.ts @@ -8,7 +8,7 @@ export class EventbriteApi implements ICredentialType { displayName = 'Eventbrite API'; properties = [ { - displayName: 'API Key', + displayName: 'Private Key', name: 'apiKey', type: 'string' as NodePropertyTypes, default: '', diff --git a/packages/nodes-base/credentials/EventbriteOAuth2Api.credentials.ts b/packages/nodes-base/credentials/EventbriteOAuth2Api.credentials.ts new file mode 100644 index 0000000000..46a9df4266 --- /dev/null +++ b/packages/nodes-base/credentials/EventbriteOAuth2Api.credentials.ts @@ -0,0 +1,47 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class EventbriteOAuth2Api implements ICredentialType { + name = 'eventbriteOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Eventbrite OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://www.eventbrite.com/oauth/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://www.eventbrite.com/oauth/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'body' + }, + ]; +} diff --git a/packages/nodes-base/credentials/GitlabOAuth2Api.credentials.ts b/packages/nodes-base/credentials/GitlabOAuth2Api.credentials.ts new file mode 100644 index 0000000000..bfd7f5afbc --- /dev/null +++ b/packages/nodes-base/credentials/GitlabOAuth2Api.credentials.ts @@ -0,0 +1,53 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class GitlabOAuth2Api implements ICredentialType { + name = 'gitlabOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Gitlab OAuth2 API'; + properties = [ + { + displayName: 'Gitlab Server', + name: 'server', + type: 'string' as NodePropertyTypes, + default: 'https://gitlab.com' + }, + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://gitlab.com/oauth/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://gitlab.com/oauth/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: 'api', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'body', + }, + ]; +} diff --git a/packages/nodes-base/credentials/GoogleDriveOAuth2Api.credentials.ts b/packages/nodes-base/credentials/GoogleDriveOAuth2Api.credentials.ts new file mode 100644 index 0000000000..77b0a9504c --- /dev/null +++ b/packages/nodes-base/credentials/GoogleDriveOAuth2Api.credentials.ts @@ -0,0 +1,26 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +const scopes = [ + 'https://www.googleapis.com/auth/drive', + 'https://www.googleapis.com/auth/drive.appdata', + 'https://www.googleapis.com/auth/drive.photos.readonly', +]; + +export class GoogleDriveOAuth2Api implements ICredentialType { + name = 'googleDriveOAuth2Api'; + extends = [ + 'googleOAuth2Api', + ]; + displayName = 'Google Drive OAuth2 API'; + properties = [ + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: scopes.join(' '), + }, + ]; +} diff --git a/packages/nodes-base/credentials/GoogleTasksOAuth2Api.credentials.ts b/packages/nodes-base/credentials/GoogleTasksOAuth2Api.credentials.ts new file mode 100644 index 0000000000..ac1242be2b --- /dev/null +++ b/packages/nodes-base/credentials/GoogleTasksOAuth2Api.credentials.ts @@ -0,0 +1,22 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +const scopes = [ + 'https://www.googleapis.com/auth/tasks', +]; + +export class GoogleTasksOAuth2Api implements ICredentialType { + name = 'googleTasksOAuth2Api'; + extends = ['googleOAuth2Api']; + displayName = 'Google Tasks OAuth2 API'; + properties = [ + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: scopes.join(' ') + }, + ]; +} diff --git a/packages/nodes-base/credentials/HubspotOAuth2Api.credentials.ts b/packages/nodes-base/credentials/HubspotOAuth2Api.credentials.ts new file mode 100644 index 0000000000..ce18b899df --- /dev/null +++ b/packages/nodes-base/credentials/HubspotOAuth2Api.credentials.ts @@ -0,0 +1,53 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +const scopes = [ + 'contacts', + 'forms', + 'tickets', +]; + +export class HubspotOAuth2Api implements ICredentialType { + name = 'hubspotOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Hubspot OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://app.hubspot.com/oauth/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://api.hubapi.com/oauth/v1/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: scopes.join(' '), + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: 'grant_type=authorization_code', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'body', + description: 'Resource to consume.', + }, + ]; +} diff --git a/packages/nodes-base/credentials/MailchimpOAuth2Api.credentials.ts b/packages/nodes-base/credentials/MailchimpOAuth2Api.credentials.ts new file mode 100644 index 0000000000..886424b6a6 --- /dev/null +++ b/packages/nodes-base/credentials/MailchimpOAuth2Api.credentials.ts @@ -0,0 +1,54 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class MailchimpOAuth2Api implements ICredentialType { + name = 'mailchimpOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Mailchimp OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://login.mailchimp.com/oauth2/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://login.mailchimp.com/oauth2/token', + required: true, + }, + { + displayName: 'Metadata', + name: 'metadataUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://login.mailchimp.com/oauth2/metadata', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'header', + }, + ]; +} diff --git a/packages/nodes-base/credentials/MauticOAuth2Api.credentials.ts b/packages/nodes-base/credentials/MauticOAuth2Api.credentials.ts new file mode 100644 index 0000000000..8c52f9372c --- /dev/null +++ b/packages/nodes-base/credentials/MauticOAuth2Api.credentials.ts @@ -0,0 +1,55 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +export class MauticOAuth2Api implements ICredentialType { + name = 'mauticOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Mautic OAuth2 API'; + properties = [ + { + displayName: 'URL', + name: 'url', + type: 'string' as NodePropertyTypes, + default: '', + placeholder: 'https://name.mautic.net', + }, + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'string' as NodePropertyTypes, + default: '', + placeholder: 'https://name.mautic.net/oauth/v2/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'string' as NodePropertyTypes, + default: '', + placeholder: 'https://name.mautic.net/oauth/v2/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'header', + }, + ]; +} diff --git a/packages/nodes-base/credentials/MessageBirdApi.credentials.ts b/packages/nodes-base/credentials/MessageBirdApi.credentials.ts new file mode 100644 index 0000000000..e67c6a0c9e --- /dev/null +++ b/packages/nodes-base/credentials/MessageBirdApi.credentials.ts @@ -0,0 +1,14 @@ +import { ICredentialType, NodePropertyTypes } from 'n8n-workflow'; + +export class MessageBirdApi implements ICredentialType { + name = 'messageBirdApi'; + displayName = 'MessageBird API'; + properties = [ + { + displayName: 'API Key', + name: 'accessKey', + type: 'string' as NodePropertyTypes, + default: '' + } + ]; +} diff --git a/packages/nodes-base/credentials/MicrosoftSql.credentials.ts b/packages/nodes-base/credentials/MicrosoftSql.credentials.ts new file mode 100644 index 0000000000..812e9bfdd7 --- /dev/null +++ b/packages/nodes-base/credentials/MicrosoftSql.credentials.ts @@ -0,0 +1,47 @@ +import { ICredentialType, NodePropertyTypes } from 'n8n-workflow'; + +export class MicrosoftSql implements ICredentialType { + name = 'microsoftSql'; + displayName = 'Microsoft SQL'; + properties = [ + { + displayName: 'Server', + name: 'server', + type: 'string' as NodePropertyTypes, + default: 'localhost' + }, + { + displayName: 'Database', + name: 'database', + type: 'string' as NodePropertyTypes, + default: 'master' + }, + { + displayName: 'User', + name: 'user', + type: 'string' as NodePropertyTypes, + default: 'sa' + }, + { + displayName: 'Password', + name: 'password', + type: 'string' as NodePropertyTypes, + typeOptions: { + password: true + }, + default: '' + }, + { + displayName: 'Port', + name: 'port', + type: 'number' as NodePropertyTypes, + default: 1433 + }, + { + displayName: 'Domain', + name: 'domain', + type: 'string' as NodePropertyTypes, + default: '' + } + ]; +} diff --git a/packages/nodes-base/credentials/NextCloudApi.credentials.ts b/packages/nodes-base/credentials/NextCloudApi.credentials.ts index c75632df00..3081455506 100644 --- a/packages/nodes-base/credentials/NextCloudApi.credentials.ts +++ b/packages/nodes-base/credentials/NextCloudApi.credentials.ts @@ -12,7 +12,7 @@ export class NextCloudApi implements ICredentialType { displayName: 'Web DAV URL', name: 'webDavUrl', type: 'string' as NodePropertyTypes, - placeholder: 'https://nextcloud.example.com/remote.php/webdav/', + placeholder: 'https://nextcloud.example.com/remote.php/webdav', default: '', }, { diff --git a/packages/nodes-base/credentials/NextCloudOAuth2Api.credentials.ts b/packages/nodes-base/credentials/NextCloudOAuth2Api.credentials.ts new file mode 100644 index 0000000000..9379ee5203 --- /dev/null +++ b/packages/nodes-base/credentials/NextCloudOAuth2Api.credentials.ts @@ -0,0 +1,54 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class NextCloudOAuth2Api implements ICredentialType { + name = 'nextCloudOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'NextCloud OAuth2 API'; + properties = [ + { + displayName: 'Web DAV URL', + name: 'webDavUrl', + type: 'string' as NodePropertyTypes, + placeholder: 'https://nextcloud.example.com/remote.php/webdav', + default: '', + }, + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'string' as NodePropertyTypes, + default: 'https://nextcloud.example.com/apps/oauth2/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'string' as NodePropertyTypes, + default: 'https://nextcloud.example.com/apps/oauth2/api/v1/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'body', + }, + ]; +} diff --git a/packages/nodes-base/credentials/PagerDutyOAuth2Api.credentials.ts b/packages/nodes-base/credentials/PagerDutyOAuth2Api.credentials.ts new file mode 100644 index 0000000000..28b44011db --- /dev/null +++ b/packages/nodes-base/credentials/PagerDutyOAuth2Api.credentials.ts @@ -0,0 +1,45 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +export class PagerDutyOAuth2Api implements ICredentialType { + name = 'pagerDutyOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'PagerDuty OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://app.pagerduty.com/oauth/authorize', + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://app.pagerduty.com/oauth/token', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'header', + description: 'Method of authentication.', + }, + ]; +} diff --git a/packages/nodes-base/credentials/PipedriveOAuth2Api.credentials.ts b/packages/nodes-base/credentials/PipedriveOAuth2Api.credentials.ts index 813202739f..3902bb6212 100644 --- a/packages/nodes-base/credentials/PipedriveOAuth2Api.credentials.ts +++ b/packages/nodes-base/credentials/PipedriveOAuth2Api.credentials.ts @@ -3,7 +3,6 @@ import { NodePropertyTypes, } from 'n8n-workflow'; - export class PipedriveOAuth2Api implements ICredentialType { name = 'pipedriveOAuth2Api'; extends = [ @@ -28,7 +27,7 @@ export class PipedriveOAuth2Api implements ICredentialType { { displayName: 'Scope', name: 'scope', - type: 'string' as NodePropertyTypes, + type: 'hidden' as NodePropertyTypes, default: '', }, { diff --git a/packages/nodes-base/credentials/PostmarkApi.credentials.ts b/packages/nodes-base/credentials/PostmarkApi.credentials.ts new file mode 100644 index 0000000000..b5f73621c4 --- /dev/null +++ b/packages/nodes-base/credentials/PostmarkApi.credentials.ts @@ -0,0 +1,18 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class PostmarkApi implements ICredentialType { + name = 'postmarkApi'; + displayName = 'Postmark API'; + properties = [ + { + displayName: 'Server API Token', + name: 'serverToken', + type: 'string' as NodePropertyTypes, + default: '', + }, + ]; +} diff --git a/packages/nodes-base/credentials/QuestDb.credentials.ts b/packages/nodes-base/credentials/QuestDb.credentials.ts new file mode 100644 index 0000000000..24c1522737 --- /dev/null +++ b/packages/nodes-base/credentials/QuestDb.credentials.ts @@ -0,0 +1,69 @@ +import { ICredentialType, NodePropertyTypes } from 'n8n-workflow'; + +export class QuestDb implements ICredentialType { + name = 'questDb'; + displayName = 'QuestDB'; + properties = [ + { + displayName: 'Host', + name: 'host', + type: 'string' as NodePropertyTypes, + default: 'localhost', + }, + { + displayName: 'Database', + name: 'database', + type: 'string' as NodePropertyTypes, + default: 'qdb', + }, + { + displayName: 'User', + name: 'user', + type: 'string' as NodePropertyTypes, + default: 'admin', + }, + { + displayName: 'Password', + name: 'password', + type: 'string' as NodePropertyTypes, + typeOptions: { + password: true, + }, + default: 'quest', + }, + { + displayName: 'SSL', + name: 'ssl', + type: 'options' as NodePropertyTypes, + options: [ + { + name: 'disable', + value: 'disable', + }, + { + name: 'allow', + value: 'allow', + }, + { + name: 'require', + value: 'require', + }, + { + name: 'verify (not implemented)', + value: 'verify', + }, + { + name: 'verify-full (not implemented)', + value: 'verify-full', + }, + ], + default: 'disable', + }, + { + displayName: 'Port', + name: 'port', + type: 'number' as NodePropertyTypes, + default: 8812, + }, + ]; +} diff --git a/packages/nodes-base/credentials/Signl4Api.credentials.ts b/packages/nodes-base/credentials/Signl4Api.credentials.ts new file mode 100644 index 0000000000..842136de02 --- /dev/null +++ b/packages/nodes-base/credentials/Signl4Api.credentials.ts @@ -0,0 +1,18 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +export class Signl4Api implements ICredentialType { + name = 'signl4Api'; + displayName = 'SIGNL4 Webhook'; + properties = [ + { + displayName: 'Team Secret', + name: 'teamSecret', + type: 'string' as NodePropertyTypes, + default: '', + description: 'The team secret is the last part of your SIGNL4 webhook URL.' + }, + ]; +} diff --git a/packages/nodes-base/credentials/SlackOAuth2Api.credentials.ts b/packages/nodes-base/credentials/SlackOAuth2Api.credentials.ts index b56699fe68..0426ceee02 100644 --- a/packages/nodes-base/credentials/SlackOAuth2Api.credentials.ts +++ b/packages/nodes-base/credentials/SlackOAuth2Api.credentials.ts @@ -6,15 +6,12 @@ import { //https://api.slack.com/authentication/oauth-v2 const userScopes = [ 'chat:write', - 'conversations:history', - 'conversations:read', 'files:read', 'files:write', 'stars:read', 'stars:write', ]; - export class SlackOAuth2Api implements ICredentialType { name = 'slackOAuth2Api'; extends = [ diff --git a/packages/nodes-base/credentials/SpotifyOAuth2Api.credentials.ts b/packages/nodes-base/credentials/SpotifyOAuth2Api.credentials.ts new file mode 100644 index 0000000000..1dc9f1057a --- /dev/null +++ b/packages/nodes-base/credentials/SpotifyOAuth2Api.credentials.ts @@ -0,0 +1,53 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class SpotifyOAuth2Api implements ICredentialType { + name = 'spotifyOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Spotify OAuth2 API'; + properties = [ + { + displayName: 'Spotify Server', + name: 'server', + type: 'hidden' as NodePropertyTypes, + default: 'https://api.spotify.com/', + }, + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://accounts.spotify.com/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://accounts.spotify.com/api/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: 'user-read-playback-state playlist-read-collaborative user-modify-playback-state playlist-modify-public user-read-currently-playing playlist-read-private user-read-recently-played playlist-modify-private', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'header', + } + ]; +} diff --git a/packages/nodes-base/credentials/SurveyMonkeyOAuth2Api.credentials.ts b/packages/nodes-base/credentials/SurveyMonkeyOAuth2Api.credentials.ts new file mode 100644 index 0000000000..26949d879f --- /dev/null +++ b/packages/nodes-base/credentials/SurveyMonkeyOAuth2Api.credentials.ts @@ -0,0 +1,55 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +const scopes = [ + 'surveys_read', + 'collectors_read', + 'responses_read', + 'responses_read_detail', + 'webhooks_write', + 'webhooks_read', +]; + +export class SurveyMonkeyOAuth2Api implements ICredentialType { + name = 'surveyMonkeyOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'SurveyMonkey OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://api.surveymonkey.com/oauth/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://api.surveymonkey.com/oauth/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: scopes.join(','), + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'body' + }, + ]; +} diff --git a/packages/nodes-base/credentials/TypeformOAuth2Api.credentials.ts b/packages/nodes-base/credentials/TypeformOAuth2Api.credentials.ts new file mode 100644 index 0000000000..a876e87ed0 --- /dev/null +++ b/packages/nodes-base/credentials/TypeformOAuth2Api.credentials.ts @@ -0,0 +1,53 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +const scopes = [ + 'webhooks:write', + 'webhooks:read', + 'forms:read', +]; + + +export class TypeformOAuth2Api implements ICredentialType { + name = 'typeformOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Typeform OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://api.typeform.com/oauth/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://api.typeform.com/oauth/token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: scopes.join(','), + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'header', + }, + ]; +} diff --git a/packages/nodes-base/credentials/WebflowOAuth2Api.credentials.ts b/packages/nodes-base/credentials/WebflowOAuth2Api.credentials.ts new file mode 100644 index 0000000000..ba5501910c --- /dev/null +++ b/packages/nodes-base/credentials/WebflowOAuth2Api.credentials.ts @@ -0,0 +1,50 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + + +export class WebflowOAuth2Api implements ICredentialType { + name = 'webflowOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Webflow OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://webflow.com/oauth/authorize', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://api.webflow.com/oauth/access_token', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + description: 'For some services additional query parameters have to be set which can be defined here.', + placeholder: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'body', + description: '', + }, + ]; +} diff --git a/packages/nodes-base/credentials/XeroOAuth2Api.credentials.ts b/packages/nodes-base/credentials/XeroOAuth2Api.credentials.ts new file mode 100644 index 0000000000..2db47c13de --- /dev/null +++ b/packages/nodes-base/credentials/XeroOAuth2Api.credentials.ts @@ -0,0 +1,51 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +const scopes = [ + 'offline_access', + 'accounting.transactions', + 'accounting.settings', + 'accounting.contacts', +]; + +export class XeroOAuth2Api implements ICredentialType { + name = 'xeroOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Xero OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://login.xero.com/identity/connect/authorize', + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://identity.xero.com/connect/token', + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: scopes.join(' '), + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'header', + }, + ]; +} diff --git a/packages/nodes-base/credentials/ZendeskApi.credentials.ts b/packages/nodes-base/credentials/ZendeskApi.credentials.ts index 29048c1172..4f285912b6 100644 --- a/packages/nodes-base/credentials/ZendeskApi.credentials.ts +++ b/packages/nodes-base/credentials/ZendeskApi.credentials.ts @@ -8,10 +8,11 @@ export class ZendeskApi implements ICredentialType { displayName = 'Zendesk API'; properties = [ { - displayName: 'URL', - name: 'url', + displayName: 'Subdomain', + name: 'subdomain', type: 'string' as NodePropertyTypes, - default: '', + description: 'The subdomain of your Zendesk work environment.', + default: 'n8n', }, { displayName: 'Email', diff --git a/packages/nodes-base/credentials/ZendeskOAuth2Api.credentials.ts b/packages/nodes-base/credentials/ZendeskOAuth2Api.credentials.ts new file mode 100644 index 0000000000..06428456e6 --- /dev/null +++ b/packages/nodes-base/credentials/ZendeskOAuth2Api.credentials.ts @@ -0,0 +1,79 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +const scopes = [ + 'read', + 'write', +]; + +export class ZendeskOAuth2Api implements ICredentialType { + name = 'zendeskOAuth2Api'; + extends = [ + 'oAuth2Api', + ]; + displayName = 'Zendesk OAuth2 API'; + properties = [ + { + displayName: 'Subdomain', + name: 'subdomain', + type: 'string' as NodePropertyTypes, + default: '', + placeholder: 'n8n', + description: 'The subdomain of your Zendesk work environment.', + required: true, + }, + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'string' as NodePropertyTypes, + default: 'https://{SUBDOMAIN_HERE}.zendesk.com/oauth/authorizations/new', + description: 'URL to get authorization code. Replace {SUBDOMAIN_HERE} with your subdomain.', + required: true, + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'string' as NodePropertyTypes, + default: 'https://{SUBDOMAIN_HERE}.zendesk.com/oauth/tokens', + description: 'URL to get access token. Replace {SUBDOMAIN_HERE} with your subdomain.', + required: true, + }, + { + displayName: 'Client ID', + name: 'clientId', + type: 'string' as NodePropertyTypes, + default: '', + required: true, + }, + { + displayName: 'Client Secret', + name: 'clientSecret', + type: 'string' as NodePropertyTypes, + default: '', + required: true, + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: scopes.join(' '), + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '', + description: 'For some services additional query parameters have to be set which can be defined here.', + placeholder: '', + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'body', + description: 'Resource to consume.', + }, + ]; +} diff --git a/packages/nodes-base/credentials/ZoomApi.credentials.ts b/packages/nodes-base/credentials/ZoomApi.credentials.ts new file mode 100644 index 0000000000..6efd857568 --- /dev/null +++ b/packages/nodes-base/credentials/ZoomApi.credentials.ts @@ -0,0 +1,14 @@ +import { ICredentialType, NodePropertyTypes } from 'n8n-workflow'; + +export class ZoomApi implements ICredentialType { + name = 'zoomApi'; + displayName = 'Zoom API'; + properties = [ + { + displayName: 'JWT Token', + name: 'accessToken', + type: 'string' as NodePropertyTypes, + default: '' + } + ]; +} diff --git a/packages/nodes-base/credentials/ZoomOAuth2Api.credentials.ts b/packages/nodes-base/credentials/ZoomOAuth2Api.credentials.ts new file mode 100644 index 0000000000..f85cc75254 --- /dev/null +++ b/packages/nodes-base/credentials/ZoomOAuth2Api.credentials.ts @@ -0,0 +1,42 @@ +import { + ICredentialType, + NodePropertyTypes, +} from 'n8n-workflow'; + +export class ZoomOAuth2Api implements ICredentialType { + name = 'zoomOAuth2Api'; + extends = ['oAuth2Api']; + displayName = 'Zoom OAuth2 API'; + properties = [ + { + displayName: 'Authorization URL', + name: 'authUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://zoom.us/oauth/authorize' + }, + { + displayName: 'Access Token URL', + name: 'accessTokenUrl', + type: 'hidden' as NodePropertyTypes, + default: 'https://zoom.us/oauth/token' + }, + { + displayName: 'Scope', + name: 'scope', + type: 'hidden' as NodePropertyTypes, + default: '' + }, + { + displayName: 'Auth URI Query Parameters', + name: 'authQueryParameters', + type: 'hidden' as NodePropertyTypes, + default: '' + }, + { + displayName: 'Authentication', + name: 'authentication', + type: 'hidden' as NodePropertyTypes, + default: 'header' + } + ]; +} diff --git a/packages/nodes-base/gulpfile.js b/packages/nodes-base/gulpfile.js index 9771a4017c..58ba6ec51a 100644 --- a/packages/nodes-base/gulpfile.js +++ b/packages/nodes-base/gulpfile.js @@ -1,7 +1,7 @@ const { src, dest } = require('gulp'); function copyIcons() { - return src('nodes/**/*.png') + return src('nodes/**/*.{png,svg}') .pipe(dest('dist/nodes')); } diff --git a/packages/nodes-base/nodes/Affinity/AffinityTrigger.node.ts b/packages/nodes-base/nodes/Affinity/AffinityTrigger.node.ts index 6b57d46804..3d387e7b4d 100644 --- a/packages/nodes-base/nodes/Affinity/AffinityTrigger.node.ts +++ b/packages/nodes-base/nodes/Affinity/AffinityTrigger.node.ts @@ -52,10 +52,10 @@ export class AffinityTrigger implements INodeType { options: [ { name: 'file.created', - value: 'file.deleted', + value: 'file.created', }, { - name: 'file.created', + name: 'file.deleted', value: 'file.deleted', }, { @@ -136,7 +136,7 @@ export class AffinityTrigger implements INodeType { }, { name: 'opportunity.deleted', - value: 'organization.deleted', + value: 'opportunity.deleted', }, { name: 'person.created', diff --git a/packages/nodes-base/nodes/CircleCi/CircleCi.node.ts b/packages/nodes-base/nodes/CircleCi/CircleCi.node.ts new file mode 100644 index 0000000000..a15a9511e2 --- /dev/null +++ b/packages/nodes-base/nodes/CircleCi/CircleCi.node.ts @@ -0,0 +1,140 @@ +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + IDataObject, + INodeTypeDescription, + INodeExecutionData, + INodeType, +} from 'n8n-workflow'; + +import { + pipelineFields, + pipelineOperations, +} from './PipelineDescription'; + +import { + circleciApiRequest, + circleciApiRequestAllItems, +} from './GenericFunctions'; + +export class CircleCi implements INodeType { + description: INodeTypeDescription = { + displayName: 'CircleCI', + name: 'circleCi', + icon: 'file:circleCi.png', + group: ['output'], + version: 1, + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + description: 'Consume CircleCI API', + defaults: { + name: 'CircleCI', + color: '#04AA51', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'circleCiApi', + required: true, + } + ], + properties: [ + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: ' Pipeline', + value: 'pipeline', + }, + ], + default: 'pipeline', + description: 'Resource to consume.', + }, + ...pipelineOperations, + ...pipelineFields, + ], + }; + + async execute(this: IExecuteFunctions): Promise { + const items = this.getInputData(); + const returnData: IDataObject[] = []; + const length = items.length as unknown as number; + const qs: IDataObject = {}; + let responseData; + const resource = this.getNodeParameter('resource', 0) as string; + const operation = this.getNodeParameter('operation', 0) as string; + + for (let i = 0; i < length; i++) { + if (resource === 'pipeline') { + if (operation === 'get') { + const vcs = this.getNodeParameter('vcs', i) as string; + let slug = this.getNodeParameter('projectSlug', i) as string; + const pipelineNumber = this.getNodeParameter('pipelineNumber', i) as number; + + slug = slug.replace(new RegExp(/\//g), '%2F'); + + const endpoint = `/project/${vcs}/${slug}/pipeline/${pipelineNumber}`; + + responseData = await circleciApiRequest.call(this, 'GET', endpoint, {}, qs); + } + if (operation === 'getAll') { + const vcs = this.getNodeParameter('vcs', i) as string; + const filters = this.getNodeParameter('filters', i) as IDataObject; + const returnAll = this.getNodeParameter('returnAll', i) as boolean; + let slug = this.getNodeParameter('projectSlug', i) as string; + + slug = slug.replace(new RegExp(/\//g), '%2F'); + + if (filters.branch) { + qs.branch = filters.branch; + } + + const endpoint = `/project/${vcs}/${slug}/pipeline`; + + if (returnAll === true) { + responseData = await circleciApiRequestAllItems.call(this, 'items', 'GET', endpoint, {}, qs); + + } else { + qs.limit = this.getNodeParameter('limit', i) as number; + responseData = await circleciApiRequest.call(this, 'GET', endpoint, {}, qs); + responseData = responseData.items; + responseData = responseData.splice(0, qs.limit); + } + } + + if (operation === 'trigger') { + const vcs = this.getNodeParameter('vcs', i) as string; + let slug = this.getNodeParameter('projectSlug', i) as string; + + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + + slug = slug.replace(new RegExp(/\//g), '%2F'); + + const endpoint = `/project/${vcs}/${slug}/pipeline`; + + const body: IDataObject = {}; + + if (additionalFields.branch) { + body.branch = additionalFields.branch as string; + } + + if (additionalFields.tag) { + body.tag = additionalFields.tag as string; + } + + responseData = await circleciApiRequest.call(this, 'POST', endpoint, body, qs); + } + } + if (Array.isArray(responseData)) { + returnData.push.apply(returnData, responseData as IDataObject[]); + } else { + returnData.push(responseData as IDataObject); + } + } + return [this.helpers.returnJsonArray(returnData)]; + } +} diff --git a/packages/nodes-base/nodes/CircleCi/GenericFunctions.ts b/packages/nodes-base/nodes/CircleCi/GenericFunctions.ts new file mode 100644 index 0000000000..fb30950a1a --- /dev/null +++ b/packages/nodes-base/nodes/CircleCi/GenericFunctions.ts @@ -0,0 +1,67 @@ +import { + OptionsWithUri, +} from 'request'; + +import { + IExecuteFunctions, + IExecuteSingleFunctions, + IHookFunctions, + ILoadOptionsFunctions, +} from 'n8n-core'; + +import { + IDataObject, +} from 'n8n-workflow'; + +export async function circleciApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise { // tslint:disable-line:no-any + const credentials = this.getCredentials('circleCiApi'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + let options: OptionsWithUri = { + headers: { + 'Circle-Token': credentials.apiKey, + 'Accept': 'application/json', + }, + method, + qs, + body, + uri: uri ||`https://circleci.com/api/v2${resource}`, + json: true + }; + options = Object.assign({}, options, option); + if (Object.keys(options.body).length === 0) { + delete options.body; + } + try { + return await this.helpers.request!(options); + } catch (err) { + if (err.response && err.response.body && err.response.body.message) { + // Try to return the error prettier + throw new Error(`CircleCI error response [${err.statusCode}]: ${err.response.body.message}`); + } + + // If that data does not exist for some reason return the actual error + throw err; } +} + +/** + * Make an API request to paginated CircleCI endpoint + * and return all results + */ +export async function circleciApiRequestAllItems(this: IHookFunctions | IExecuteFunctions| ILoadOptionsFunctions, propertyName: string, method: string, resource: string, body: any = {}, query: IDataObject = {}): Promise { // tslint:disable-line:no-any + + const returnData: IDataObject[] = []; + + let responseData; + + do { + responseData = await circleciApiRequest.call(this, method, resource, body, query); + returnData.push.apply(returnData, responseData[propertyName]); + query['page-token'] = responseData.next_page_token; + } while ( + responseData.next_page_token !== undefined && + responseData.next_page_token !== null + ); + return returnData; +} diff --git a/packages/nodes-base/nodes/CircleCi/PipelineDescription.ts b/packages/nodes-base/nodes/CircleCi/PipelineDescription.ts new file mode 100644 index 0000000000..520fdbcd05 --- /dev/null +++ b/packages/nodes-base/nodes/CircleCi/PipelineDescription.ts @@ -0,0 +1,229 @@ +import { + INodeProperties, +} from 'n8n-workflow'; + +export const pipelineOperations = [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'pipeline', + ], + }, + }, + options: [ + { + name: 'Get', + value: 'get', + description: 'Get a pipeline', + }, + { + name: 'Get All', + value: 'getAll', + description: 'Get all pipelines', + }, + { + name: 'Trigger', + value: 'trigger', + description: 'Trigger a pipeline', + }, + ], + default: 'get', + description: 'The operation to perform.', + }, +] as INodeProperties[]; + +export const pipelineFields = [ + +/* -------------------------------------------------------------------------- */ +/* pipeline:shared */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Provider', + name: 'vcs', + type: 'options', + options: [ + { + name: 'Bitbucket', + value: 'bitbucket', + }, + { + name: 'GitHub', + value: 'github', + }, + ], + displayOptions: { + show: { + operation: [ + 'get', + 'getAll', + 'trigger', + ], + resource: [ + 'pipeline', + ], + }, + }, + default: '', + description: 'Version control system', + }, + { + displayName: 'Project Slug', + name: 'projectSlug', + type: 'string', + displayOptions: { + show: { + operation: [ + 'get', + 'getAll', + 'trigger', + ], + resource: [ + 'pipeline', + ], + }, + }, + default: '', + placeholder: 'n8n-io/n8n', + description: 'Project slug in the form org-name/repo-name', + }, + +/* -------------------------------------------------------------------------- */ +/* pipeline:get */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Pipeline Number', + name: 'pipelineNumber', + type: 'number', + typeOptions: { + minValue: 1, + }, + displayOptions: { + show: { + operation: [ + 'get', + ], + resource: [ + 'pipeline', + ], + }, + }, + default: 1, + description: 'The number of the pipeline', + }, + +/* -------------------------------------------------------------------------- */ +/* pipeline:getAll */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'pipeline', + ], + }, + }, + default: false, + description: 'If all results should be returned or only up to a given limit.', + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'pipeline', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 500, + }, + default: 100, + description: 'How many results to return.', + }, + { + displayName: 'Filters', + name: 'filters', + type: 'collection', + placeholder: 'Add Filter', + default: {}, + displayOptions: { + show: { + resource: [ + 'pipeline', + ], + operation: [ + 'getAll', + ], + }, + }, + options: [ + { + displayName: 'Branch', + name: 'branch', + type: 'string', + default: '', + description: 'The name of a vcs branch.', + }, + ], + }, + +/* -------------------------------------------------------------------------- */ +/* pipeline:trigger */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + resource: [ + 'pipeline', + ], + operation: [ + 'trigger', + ], + }, + }, + options: [ + { + displayName: 'Branch', + name: 'branch', + type: 'string', + default: '', + description: `The branch where the pipeline ran.
+ The HEAD commit on this branch was used for the pipeline.
+ Note that branch and tag are mutually exclusive.`, + }, + { + displayName: 'Tag', + name: 'tag', + type: 'string', + default: '', + description: `The tag used by the pipeline.
+ The commit that this tag points to was used for the pipeline.
+ Note that branch and tag are mutually exclusive`, + }, + ], + }, +] as INodeProperties[]; diff --git a/packages/nodes-base/nodes/CircleCi/circleCi.png b/packages/nodes-base/nodes/CircleCi/circleCi.png new file mode 100644 index 0000000000000000000000000000000000000000..1708a6a3dd604cd31db2718e9052fb312246e0eb GIT binary patch literal 4787 zcmY*dcRbr$+)k(!vs$xOW7LijJ1Q+=lNhyE3AIOzh*7lmNTo*YloF$6FRh}qHZ3hR zs;DYKhg!Ai%f0vQecy9F=RD8({+{piJ>T=^F9~U^!wBLA0RR9-JzXu+Q$(CCTI$n1 zKziZsDF891I@bZU!#t~}hr4JiJvSpGfcPn=1yBK50hDKw(+L1_1E~Jy0DwO5(jRUL z6#Z920RSX;0M7lZu{p&vDtWg3K}sUsPkW(vb4|A&^D zkkHUj=}>uTzd(10tcr>XL`DuGCnt5Pkivxd203G;d@+LmnEbDg78>Ic=;0sa;pZ!G z=IeaZFE~gY3_dILXZ&-|AP=|yD*0mmZR@l_$k`W&th5Z|kN0UR>@2Ek66k?Gt$gNx zRTlQQ^8dyDtpkIc75_h%`KQyrqo=K21;HSHp6x2g@YNM-0D#3sPwSdF7C2r&pUP{& z)%P>Jcy_k=(9_4q!$u;R;(DGyd>TADzJf)8`a<`5B1j0_tyL!56D{Of!OfC!1F0ti z0woG?8ZheKMF_m3$jFXwZul6P#U9eyx;w{p`?nu?W^Q(Fa;DX1^{Gm@+whn0qmj@T zD)Ja|uZvCsYrPSn@yQhF;NW16f2hZJlXXt+D|^rJ9>u1j2AQPWq9rN2)_05=+`$#? z-cT)!!ub39D=mi+N|kBE2!k+7<(!stuZ8ItP%mkt_h_k$3_ieL;|mclpnUkD3abK* z^U+qdx1S6}eByZ4dTSH3pWRmc38tvHQ#BngWp)D;m%X>U_o!tdS5% z0%~2;VHgjn5%ejtEctD)eqt|PeDGuL>Fx_Qxni?uCNDdr`e@97!R36p_V#x7{jlGN z_+x?=ID?h;GK;T19sE}k*izT?xo9p7Shg5`0%bj!-=E_xEiJXJ@DlO5cR6xb$H)|R`%&eu!3#-d$YdS}VYmF9j+u83$5t&T7uSdDxk2pO z&v7k8uArJDM+c{j;!2E~AcnaV%FIzjwu&fOuac~MVKYE;0g~cCuj}aR<&%OpN!2I~ zBy87l71*fvzL_)}c~#WMI?x@5O=^Yl`N8XVX$igoZC8M%c*Zma`@t6YdF4EuMJ2lv zLuPt?4Ghi{WvilG80eI->;t2fV}xRk{g$FRy|T1SmZ`3p(B$l_I;42$w;3_| z2#UVKD%xm3q%E*mH9y#28p=@`k~ZyOK{9cM5qelCzI}3f4tA|w#efNv%ZnSKeZ@?S z^~&bM4+1MHXZmdUbVUdph0$ZA%ytmHS@##V8mStCD?N!4ce%mujag3 z4kA)2qM#&vP15zH8Ceoye4*HjLwM3hKfB)F&CB+ibZ1!7aN{nmzZ*RVazBoqBkJC8 zT^#Fpjt|-SttUpUPuuzxOLV(N-7fDif;6A;GRMX`0-G8VU zb2H@Pk$epREf}D!KkeCA@ghT$3O3by--ab{|Kja|OTucpeEpj)h4AKkA!5^&S<`wR zO$q`7moCRV)^^IfG?&IxtRvT&lFJ^RT4R|gVR_}tKsX8!T8laFeMf*vfR*8s67q{) z>fAz4yXDsY(frBrVPB)SM6Jkm%O^2LD3ZAa!u2?3`QQ9c=wVn}v zJ}w7((dXt>#-)O}1PI#gN>;VQkIk;GE|Ypsb$(_C`VQVa>P#b_UYF?F5W4ze zEpjqJA^uK!;q@o&JyaE31)i{m&g9JiU*5G|qE}axaRp2^`PwMz&ZDd3o|(F1il42l zT|x$n)XK`$#~lfIIJ*YYlWGiluj2Y`Coay+ScI8_Ca7Ngc89m54V%{AfMhr|<$J9P=SY z3uVoEn^LyWK!UuYFYaG8Ak~9xK;%7Ul-L?LsXbYWdevdikZWven4H|Qxv-d7RQRn| z(x~2ELr!&5C=wdyT|~$Ma|w2h_l{B4@9gZDO;1nXc-q_?vPIr_`~Lm=bHSt6eu#5b zJ%8PL|7UvB(`M4f0gzfJqSRPy_3nPdT6T8!Av3RPkj%T8ahUGse9oLl*XsmFli7p` z62%!~by>eg*2=TX`MY$?2MU)mS>IIYCtJyTkpwle z`*9!otS5dh7{(6`>1SZ4S9U{o=dS(stH@~aN7kw~U3&_LIbhXf7u7sz*bZn&@+YQq7hpn@XfQbQLE$eTC-XHL$%4|2(+fe)|IsVMh zny3S7w)^!YOMHy<@Fu0t$E1*&y+qOv*;B-3P7eQ?nCuJ25ty5E)!k6)bj*Uc)Ycf3fHXFHPzu zjw7_0vs%C&M0$o+h8rG9S6eHLbC)jkSMv?p9%8?f{TWMx^(v!o=1np|%D?M$u@5U& zd4l^wb@9sM)_Q|pktjdY-}=e4wCZXt_b;_Ox;$2-zO^W95?PjMV9a4+tNcuOPh|wV zR_f58AEBQy;C9>)k8-@*m#AZoNAY_!nB^im>HWY>(S*PZT47cd$S#T77o4VqaCm97 zNJ~8@S(3Z_6i3XbP9gelecnQ-dniFwNTQXH!mvxu^Cq@smC&q1>W(wiG&qi#ueCM19?u zXPI9~RSmBs!*YTot!1)uaTgp4A4W{#$MSUXyaenv>6u3)Oksb=RU-;RSPMa!+G>@` zq`JI@5~Y_uk1{4sQbN))i^{XW%L{sQvg#&x41N)l^E=qqJ(iDnW4F`&G5CX_QiX#h zcz{niNq)?6nY!sh7gW6zm$LUweeB#ST2_Gt_dL8gb|Uwpev;Gd!|7>V!yb1Eq-E@m zLwb*9n|Q{3vnup>buw* zNW~~jy3dX`xO5VP4^( z`mTgM9qTUJwbN43H0Q{gSy@6wG4Ar_yz$E2Rjo4%?dY8!)vJon$X_%c422 z@}X|+YCs&02|bKBZzKks5EWzU7oD0WYkgm0E-~bf=bJ0wbl3a&k*vidggw-e&)@y4 zS_$zkn3{^X*YGAHI)G2XEi@qICLYy-0OKbgBPu7m;se8j3nW7+E66C0Ms>ci^! zAD}dDHUCBlU-!Zv1n!s6OLr2cZKo5aXu@SnCv^p+(XsGsyCs69ILiB1ZQ<~8vgCYY zMSJ{Vle<$D*JoIxfQzC`6-$X;Ef}(y=qHRh4nm;(n3f0Agu62A%IpGt$a0gzsSFz! z!IYMtFRc`Lfyw9icAN`&MY6nvTwrQpF*m%N${`;-?aBP)Z9bKo{=Y5?Xr4$C3ocYy z)MJ|SmTo4%W&IYoZ(n`=mxU&=A7iW~XYw+A5_^ohb}Rb(la~-QQUxF2^JY9*V{xJ7 z4fN%v)@Fgq?|TOGw@%9Ted3&pNKvV)+v2Uv1Lh<(BKDZNHxiLFg&LBGhAUDKwFw=}CuwfalY;6zeFZ+wxl`)D;M+Yf+yw0CjM#rLtu{RU!e z8}dc-SHG1@tF}E)mZe0AEW{Y|WUaK++7vY$Tc9{-Ha@WLs}2MTr_ff@ed9#Eaz1MN zru{p-L#BP(cq~$|GqD3^JZ9j)>VhlmF;&~k%~aO7AG`J(ibTJ>*QU%q4*nQc6qx^N zkve|XDRBJrk#mTRFBWoa2vTM1rwYjTj9@9>HFrG6ap=s;o)Fv5O{2^<^O4KJ$vjA4 z{@kNELz{-qPWhlC$kcI>5|KIH4{o8TNy7%c-jr%{@x;^^wsaX0xpiplj6Vr0U~qa} zxoFUZg?GW*D2;g2MYmiI&IKq%IzBwOdnhLI!Q4>3+zJ(UjOFmVWU}zJAvN%DL)uqu u+qi14ueG=0kbmwMdp>t4AD;i`fd;;Qu0&L5g!}Bzjh?o#R_%4C*#7|%x28b= literal 0 HcmV?d00001 diff --git a/packages/nodes-base/nodes/CrateDb/CrateDb.node.ts b/packages/nodes-base/nodes/CrateDb/CrateDb.node.ts new file mode 100644 index 0000000000..1d7ec41dbb --- /dev/null +++ b/packages/nodes-base/nodes/CrateDb/CrateDb.node.ts @@ -0,0 +1,246 @@ +import { IExecuteFunctions } from 'n8n-core'; +import { IDataObject, INodeExecutionData, INodeType, INodeTypeDescription } from 'n8n-workflow'; + +import * as pgPromise from 'pg-promise'; + +import { pgInsert, pgQuery, pgUpdate } from '../Postgres/Postgres.node.functions'; + +export class CrateDb implements INodeType { + description: INodeTypeDescription = { + displayName: 'CrateDB', + name: 'crateDb', + icon: 'file:cratedb.png', + group: ['input'], + version: 1, + description: 'Gets, add and update data in CrateDB.', + defaults: { + name: 'CrateDB', + color: '#47889f', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'crateDb', + required: true, + }, + ], + properties: [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + options: [ + { + name: 'Execute Query', + value: 'executeQuery', + description: 'Executes a SQL query.', + }, + { + name: 'Insert', + value: 'insert', + description: 'Insert rows in database.', + }, + { + name: 'Update', + value: 'update', + description: 'Updates rows in database.', + }, + ], + default: 'insert', + description: 'The operation to perform.', + }, + + // ---------------------------------- + // executeQuery + // ---------------------------------- + { + displayName: 'Query', + name: 'query', + type: 'string', + typeOptions: { + rows: 5, + }, + displayOptions: { + show: { + operation: ['executeQuery'], + }, + }, + default: '', + placeholder: 'SELECT id, name FROM product WHERE id < 40', + required: true, + description: 'The SQL query to execute.', + }, + + // ---------------------------------- + // insert + // ---------------------------------- + { + displayName: 'Schema', + name: 'schema', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: 'public', + required: true, + description: 'Name of the schema the table belongs to', + }, + { + displayName: 'Table', + name: 'table', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: '', + required: true, + description: 'Name of the table in which to insert data to.', + }, + { + displayName: 'Columns', + name: 'columns', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: '', + placeholder: 'id,name,description', + description: + 'Comma separated list of the properties which should used as columns for the new rows.', + }, + { + displayName: 'Return Fields', + name: 'returnFields', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: '*', + description: 'Comma separated list of the fields that the operation will return', + }, + + // ---------------------------------- + // update + // ---------------------------------- + { + displayName: 'Table', + name: 'table', + type: 'string', + displayOptions: { + show: { + operation: ['update'], + }, + }, + default: '', + required: true, + description: 'Name of the table in which to update data in', + }, + { + displayName: 'Update Key', + name: 'updateKey', + type: 'string', + displayOptions: { + show: { + operation: ['update'], + }, + }, + default: 'id', + required: true, + description: + 'Name of the property which decides which rows in the database should be updated. Normally that would be "id".', + }, + { + displayName: 'Columns', + name: 'columns', + type: 'string', + displayOptions: { + show: { + operation: ['update'], + }, + }, + default: '', + placeholder: 'name,description', + description: + 'Comma separated list of the properties which should used as columns for rows to update.', + }, + ], + }; + + async execute(this: IExecuteFunctions): Promise { + const credentials = this.getCredentials('crateDb'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + const pgp = pgPromise(); + + const config = { + host: credentials.host as string, + port: credentials.port as number, + database: credentials.database as string, + user: credentials.user as string, + password: credentials.password as string, + ssl: !['disable', undefined].includes(credentials.ssl as string | undefined), + sslmode: (credentials.ssl as string) || 'disable', + }; + + const db = pgp(config); + + let returnItems = []; + + const items = this.getInputData(); + const operation = this.getNodeParameter('operation', 0) as string; + + if (operation === 'executeQuery') { + // ---------------------------------- + // executeQuery + // ---------------------------------- + + const queryResult = await pgQuery(this.getNodeParameter, pgp, db, items); + + returnItems = this.helpers.returnJsonArray(queryResult as IDataObject[]); + } else if (operation === 'insert') { + // ---------------------------------- + // insert + // ---------------------------------- + + const [insertData, insertItems] = await pgInsert(this.getNodeParameter, pgp, db, items); + + // Add the id to the data + for (let i = 0; i < insertData.length; i++) { + returnItems.push({ + json: { + ...insertData[i], + ...insertItems[i], + }, + }); + } + } else if (operation === 'update') { + // ---------------------------------- + // update + // ---------------------------------- + + const updateItems = await pgUpdate(this.getNodeParameter, pgp, db, items); + + returnItems = this.helpers.returnJsonArray(updateItems); + } else { + await pgp.end(); + throw new Error(`The operation "${operation}" is not supported!`); + } + + // Close the connection + await pgp.end(); + + return this.prepareOutputData(returnItems); + } +} diff --git a/packages/nodes-base/nodes/CrateDb/cratedb.png b/packages/nodes-base/nodes/CrateDb/cratedb.png new file mode 100644 index 0000000000000000000000000000000000000000..d2e90eade715e7a78024e942a0107ccefd9fdc76 GIT binary patch literal 475 zcmeAS@N?(olHy`uVBq!ia0vp^HXzKw1|+Ti+$;i8oCO|{#S9GG!XV7ZFl&wk0|R5P zr;B4qM&sLC8~vCZ1sWboe!F($!KN^=xJ5TI9!f`iVly#wQ=Vofa_i;~Cb4}DQoTzR zuc=Mh*VNgYapcgc#|CcwskN+S*EZ}pb3MQ9|B2WgZ*5O7|4scPxIz3Nx@ zuw}d3cW}7=n`par-MKEC(;AzFPbtP1ty>gcKAZjNmRYwR7Cb4A&^nmD{c`Qz-FttA zA7o&-CXsxWA*Sizv;$JfHP6_%`C6Nkk00Fl_`!|Bf;ScxWsXg?_uFgFslWd1e%$V` z=8{zzE4SRv;$TS7^;r5fYH?-66WdGMT4wX#?+gCl#QOT9>S6(h*r&qTY)=j@{1Ky5 zmvOWY$-rg$60BP-?=U@JUio@qh-mEE_a+JI5m+{>1`^(l@-XT=lX#qxB!d<6}t9m3hO| zDxe|6P!cWYwAY=vf<^pq+_#FtDyP5A85iaMXPuBp?(v-w&(zQqD7_^=9vE8;p00i_ I>zopr0Cm^hivR!s literal 0 HcmV?d00001 diff --git a/packages/nodes-base/nodes/DateTime.node.ts b/packages/nodes-base/nodes/DateTime.node.ts index 953375e8d9..15c33dcffc 100644 --- a/packages/nodes-base/nodes/DateTime.node.ts +++ b/packages/nodes-base/nodes/DateTime.node.ts @@ -243,9 +243,10 @@ export class DateTime implements INodeType { if (currentDate === undefined) { continue; } - if (!moment(currentDate as string | number).isValid()) { + if (options.fromFormat === undefined && !moment(currentDate as string | number).isValid()) { throw new Error('The date input format could not be recognized. Please set the "From Format" field'); } + if (Number.isInteger(currentDate as unknown as number)) { newDate = moment.unix(currentDate as unknown as number); } else { diff --git a/packages/nodes-base/nodes/Drift/Drift.node.ts b/packages/nodes-base/nodes/Drift/Drift.node.ts index 53a9a2695e..46afa3d519 100644 --- a/packages/nodes-base/nodes/Drift/Drift.node.ts +++ b/packages/nodes-base/nodes/Drift/Drift.node.ts @@ -37,9 +37,44 @@ export class Drift implements INodeType { { name: 'driftApi', required: true, + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'driftOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'The resource to operate on.', + }, { displayName: 'Resource', name: 'resource', diff --git a/packages/nodes-base/nodes/Drift/GenericFunctions.ts b/packages/nodes-base/nodes/Drift/GenericFunctions.ts index 47b38a86e3..904fc4c6b3 100644 --- a/packages/nodes-base/nodes/Drift/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Drift/GenericFunctions.ts @@ -12,25 +12,15 @@ import { } from 'n8n-workflow'; export async function driftApiRequest(this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, query: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise { // tslint:disable-line:no-any - - const credentials = this.getCredentials('driftApi'); - - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - - const endpoint = 'https://driftapi.com'; - let options: OptionsWithUri = { - headers: { - Authorization: `Bearer ${credentials.accessToken}`, - }, + headers: {}, method, body, qs: query, - uri: uri || `${endpoint}${resource}`, + uri: uri || `https://driftapi.com${resource}`, json: true }; + if (!Object.keys(body).length) { delete options.form; } @@ -38,11 +28,27 @@ export async function driftApiRequest(this: IExecuteFunctions | IWebhookFunction delete options.qs; } options = Object.assign({}, options, option); + + const authenticationMethod = this.getNodeParameter('authentication', 0); + try { - return await this.helpers.request!(options); + if (authenticationMethod === 'accessToken') { + const credentials = this.getCredentials('driftApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.headers!['Authorization'] = `Bearer ${credentials.accessToken}`; + + return await this.helpers.request!(options); + } else { + return await this.helpers.requestOAuth2!.call(this, 'driftOAuth2Api', options); + } } catch (error) { - if (error.response) { - const errorMessage = error.message || (error.response.body && error.response.body.message ); + + if (error.response && error.response.body && error.response.body.error) { + const errorMessage = error.response.body.error.message; throw new Error(`Drift error response [${error.statusCode}]: ${errorMessage}`); } throw error; diff --git a/packages/nodes-base/nodes/Dropbox/Dropbox.node.ts b/packages/nodes-base/nodes/Dropbox/Dropbox.node.ts index 6140568bc2..20c8248c56 100644 --- a/packages/nodes-base/nodes/Dropbox/Dropbox.node.ts +++ b/packages/nodes-base/nodes/Dropbox/Dropbox.node.ts @@ -2,6 +2,7 @@ import { BINARY_ENCODING, IExecuteFunctions, } from 'n8n-core'; + import { IDataObject, INodeTypeDescription, @@ -9,8 +10,9 @@ import { INodeType, } from 'n8n-workflow'; -import { OptionsWithUri } from 'request'; - +import { + OptionsWithUri +} from 'request'; export class Dropbox implements INodeType { description: INodeTypeDescription = { @@ -23,7 +25,7 @@ export class Dropbox implements INodeType { description: 'Access data on Dropbox', defaults: { name: 'Dropbox', - color: '#22BB44', + color: '#0061FF', }, inputs: ['main'], outputs: ['main'], @@ -454,6 +456,7 @@ export class Dropbox implements INodeType { let requestMethod = ''; let body: IDataObject | Buffer; let isJson = false; + let query: IDataObject = {}; let headers: IDataObject; @@ -470,8 +473,9 @@ export class Dropbox implements INodeType { // ---------------------------------- requestMethod = 'POST'; - headers['Dropbox-API-Arg'] = JSON.stringify({ - path: this.getNodeParameter('path', i) as string, + + query.arg = JSON.stringify({ + path: this.getNodeParameter('path', i) as string }); endpoint = 'https://content.dropboxapi.com/2/files/download'; @@ -483,9 +487,10 @@ export class Dropbox implements INodeType { requestMethod = 'POST'; headers['Content-Type'] = 'application/octet-stream'; - headers['Dropbox-API-Arg'] = JSON.stringify({ + + query.arg = JSON.stringify({ mode: 'overwrite', - path: this.getNodeParameter('path', i) as string, + path: this.getNodeParameter('path', i) as string }); endpoint = 'https://content.dropboxapi.com/2/files/upload'; @@ -594,8 +599,8 @@ export class Dropbox implements INodeType { const options: OptionsWithUri = { headers, method: requestMethod, - qs: {}, uri: endpoint, + qs: query, json: isJson, }; diff --git a/packages/nodes-base/nodes/Eventbrite/EventbriteTrigger.node.ts b/packages/nodes-base/nodes/Eventbrite/EventbriteTrigger.node.ts index fdeae599c2..0c9158b6c3 100644 --- a/packages/nodes-base/nodes/Eventbrite/EventbriteTrigger.node.ts +++ b/packages/nodes-base/nodes/Eventbrite/EventbriteTrigger.node.ts @@ -35,7 +35,25 @@ export class EventbriteTrigger implements INodeType { { name: 'eventbriteApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'privateKey', + ], + }, + }, + }, + { + name: 'eventbriteOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], webhooks: [ { @@ -46,6 +64,23 @@ export class EventbriteTrigger implements INodeType { }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Private Key', + value: 'privateKey', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'privateKey', + description: 'The resource to operate on.', + }, { displayName: 'Organization', name: 'organization', @@ -149,7 +184,6 @@ export class EventbriteTrigger implements INodeType { description: 'By default does the webhook-data only contain the URL to receive
the object data manually. If this option gets activated it
will resolve the data automatically.', }, ], - }; methods = { @@ -192,23 +226,39 @@ export class EventbriteTrigger implements INodeType { default: { async checkExists(this: IHookFunctions): Promise { const webhookData = this.getWorkflowStaticData('node'); - if (webhookData.webhookId === undefined) { - return false; + const webhookUrl = this.getNodeWebhookUrl('default'); + const organisation = this.getNodeParameter('organization') as string; + const actions = this.getNodeParameter('actions') as string[]; + + const endpoint = `/organizations/${organisation}/webhooks/`; + + const { webhooks } = await eventbriteApiRequest.call(this, 'GET', endpoint); + + const check = (currentActions: string[], webhookActions: string[]) => { + for (const currentAction of currentActions) { + if (!webhookActions.includes(currentAction)) { + return false; + } + } + return true; + }; + + for (const webhook of webhooks) { + if (webhook.endpoint_url === webhookUrl && check(actions, webhook.actions)) { + webhookData.webhookId = webhook.id; + return true; + } } - const endpoint = `/webhooks/${webhookData.webhookId}/`; - try { - await eventbriteApiRequest.call(this, 'GET', endpoint); - } catch (e) { - return false; - } - return true; + + return false; }, async create(this: IHookFunctions): Promise { const webhookUrl = this.getNodeWebhookUrl('default'); const webhookData = this.getWorkflowStaticData('node'); + const organisation = this.getNodeParameter('organization') as string; const event = this.getNodeParameter('event') as string; const actions = this.getNodeParameter('actions') as string[]; - const endpoint = `/webhooks/`; + const endpoint = `/organizations/${organisation}/webhooks/`; const body: IDataObject = { endpoint_url: webhookUrl, actions: actions.join(','), diff --git a/packages/nodes-base/nodes/Eventbrite/GenericFunctions.ts b/packages/nodes-base/nodes/Eventbrite/GenericFunctions.ts index 285c89b1f8..2392a0ae20 100644 --- a/packages/nodes-base/nodes/Eventbrite/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Eventbrite/GenericFunctions.ts @@ -1,4 +1,7 @@ -import { OptionsWithUri } from 'request'; +import { + OptionsWithUri, +} from 'request'; + import { IExecuteFunctions, IExecuteSingleFunctions, @@ -6,16 +9,14 @@ import { ILoadOptionsFunctions, IWebhookFunctions, } from 'n8n-core'; -import { IDataObject } from 'n8n-workflow'; + +import { + IDataObject, +} from 'n8n-workflow'; export async function eventbriteApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions | IWebhookFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('eventbriteApi'); - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - let options: OptionsWithUri = { - headers: { 'Authorization': `Bearer ${credentials.apiKey}`}, + headers: {}, method, qs, body, @@ -27,14 +28,26 @@ export async function eventbriteApiRequest(this: IHookFunctions | IExecuteFuncti delete options.body; } + const authenticationMethod = this.getNodeParameter('authentication', 0); + try { - return await this.helpers.request!(options); + if (authenticationMethod === 'privateKey') { + const credentials = this.getCredentials('eventbriteApi'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.headers!['Authorization'] = `Bearer ${credentials.apiKey}`; + + return await this.helpers.request!(options); + } else { + return await this.helpers.requestOAuth2!.call(this, 'eventbriteOAuth2Api', options); + } } catch (error) { let errorMessage = error.message; if (error.response.body && error.response.body.error_description) { errorMessage = error.response.body.error_description; } - throw new Error('Eventbrite Error: ' + errorMessage); } } diff --git a/packages/nodes-base/nodes/Facebook/FacebookGraphApi.node.ts b/packages/nodes-base/nodes/Facebook/FacebookGraphApi.node.ts index 59c55a33f4..f1fc3b8881 100644 --- a/packages/nodes-base/nodes/Facebook/FacebookGraphApi.node.ts +++ b/packages/nodes-base/nodes/Facebook/FacebookGraphApi.node.ts @@ -137,6 +137,13 @@ export class FacebookGraphApi implements INodeType { placeholder: 'videos', required: false, }, + { + displayName: 'Ignore SSL Issues', + name: 'allowUnauthorizedCerts', + type: 'boolean', + default: false, + description: 'Still download the response even if SSL certificate validation is not possible. (Not recommended)', + }, { displayName: 'Send Binary Data', name: 'sendBinaryData', @@ -301,6 +308,7 @@ export class FacebookGraphApi implements INodeType { qs: { access_token: graphApiCredentials!.accessToken, }, + rejectUnauthorized: !this.getNodeParameter('allowUnauthorizedCerts', itemIndex, false) as boolean, }; if (options !== undefined) { diff --git a/packages/nodes-base/nodes/Github/Github.node.ts b/packages/nodes-base/nodes/Github/Github.node.ts index 00133ec302..408c0a4360 100644 --- a/packages/nodes-base/nodes/Github/Github.node.ts +++ b/packages/nodes-base/nodes/Github/Github.node.ts @@ -17,14 +17,14 @@ import { export class Github implements INodeType { description: INodeTypeDescription = { - displayName: 'Github', + displayName: 'GitHub', name: 'github', icon: 'file:github.png', group: ['input'], version: 1, - description: 'Retrieve data from Github API.', + description: 'Retrieve data from GitHub API.', defaults: { - name: 'Github', + name: 'GitHub', color: '#665533', }, inputs: ['main'], @@ -178,7 +178,7 @@ export class Github implements INodeType { { name: 'Get', value: 'get', - description: 'Get the data of a single issues', + description: 'Get the data of a single issue', }, ], default: 'create', @@ -220,7 +220,7 @@ export class Github implements INodeType { { name: 'List Popular Paths', value: 'listPopularPaths', - description: 'Get the data of a file in repositoryGet the top 10 popular content paths over the last 14 days.', + description: 'Get the top 10 popular content paths over the last 14 days.', }, { name: 'List Referrers', @@ -244,11 +244,6 @@ export class Github implements INodeType { }, }, options: [ - { - name: 'Get Emails', - value: 'getEmails', - description: 'Returns the email addresses of a user', - }, { name: 'Get Repositories', value: 'getRepositories', @@ -463,7 +458,7 @@ export class Github implements INodeType { description: 'The name of the author of the commit.', }, { - displayName: 'EMail', + displayName: 'Email', name: 'email', type: 'string', default: '', @@ -496,7 +491,7 @@ export class Github implements INodeType { description: 'The name of the committer of the commit.', }, { - displayName: 'EMail', + displayName: 'Email', name: 'email', type: 'string', default: '', @@ -1019,28 +1014,28 @@ export class Github implements INodeType { name: 'assignee', type: 'string', default: '', - description: 'Return only issuse which are assigned to a specific user.', + description: 'Return only issues which are assigned to a specific user.', }, { displayName: 'Creator', name: 'creator', type: 'string', default: '', - description: 'Return only issuse which were created by a specific user.', + description: 'Return only issues which were created by a specific user.', }, { displayName: 'Mentioned', name: 'mentioned', type: 'string', default: '', - description: 'Return only issuse in which a specific user was mentioned.', + description: 'Return only issues in which a specific user was mentioned.', }, { displayName: 'Labels', name: 'labels', type: 'string', default: '', - description: 'Return only issuse with the given labels. Multiple lables can be separated by comma.', + description: 'Return only issues with the given labels. Multiple lables can be separated by comma.', }, { displayName: 'Updated Since', diff --git a/packages/nodes-base/nodes/Github/GithubTrigger.node.ts b/packages/nodes-base/nodes/Github/GithubTrigger.node.ts index 2a14b5d3db..1360d7536a 100644 --- a/packages/nodes-base/nodes/Github/GithubTrigger.node.ts +++ b/packages/nodes-base/nodes/Github/GithubTrigger.node.ts @@ -34,7 +34,25 @@ export class GithubTrigger implements INodeType { { name: 'githubApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'githubOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], webhooks: [ { @@ -45,6 +63,23 @@ export class GithubTrigger implements INodeType { }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'The resource to operate on.', + }, { displayName: 'Repository Owner', name: 'owner', diff --git a/packages/nodes-base/nodes/Gitlab/GenericFunctions.ts b/packages/nodes-base/nodes/Gitlab/GenericFunctions.ts index 8f1811b8c7..3085f17678 100644 --- a/packages/nodes-base/nodes/Gitlab/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Gitlab/GenericFunctions.ts @@ -1,11 +1,13 @@ import { IExecuteFunctions, IHookFunctions, + ILoadOptionsFunctions, } from 'n8n-core'; import { IDataObject, } from 'n8n-workflow'; +import { OptionsWithUri } from 'request'; /** * Make an API request to Gitlab @@ -17,24 +19,43 @@ import { * @returns {Promise} */ export async function gitlabApiRequest(this: IHookFunctions | IExecuteFunctions, method: string, endpoint: string, body: object, query?: object): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('gitlabApi'); - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - - const options = { + const options : OptionsWithUri = { method, - headers: { - 'Private-Token': `${credentials.accessToken}`, - }, + headers: {}, body, qs: query, - uri: `${(credentials.server as string).replace(/\/$/, '')}/api/v4${endpoint}`, + uri: '', json: true }; + if (query === undefined) { + delete options.qs; + } + + const authenticationMethod = this.getNodeParameter('authentication', 0); + try { - return await this.helpers.request(options); + if (authenticationMethod === 'accessToken') { + const credentials = this.getCredentials('gitlabApi'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.headers!['Private-Token'] = `${credentials.accessToken}`; + + options.uri = `${(credentials.server as string).replace(/\/$/, '')}/api/v4${endpoint}`; + + return await this.helpers.request(options); + } else { + const credentials = this.getCredentials('gitlabOAuth2Api'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.uri = `${(credentials.server as string).replace(/\/$/, '')}/api/v4${endpoint}`; + + return await this.helpers.requestOAuth2!.call(this, 'gitlabOAuth2Api', options); + } } catch (error) { if (error.statusCode === 401) { // Return a clear error diff --git a/packages/nodes-base/nodes/Gitlab/Gitlab.node.ts b/packages/nodes-base/nodes/Gitlab/Gitlab.node.ts index 39d71ae3da..fa485e452a 100644 --- a/packages/nodes-base/nodes/Gitlab/Gitlab.node.ts +++ b/packages/nodes-base/nodes/Gitlab/Gitlab.node.ts @@ -13,7 +13,6 @@ import { gitlabApiRequest, } from './GenericFunctions'; - export class Gitlab implements INodeType { description: INodeTypeDescription = { displayName: 'Gitlab', @@ -33,9 +32,44 @@ export class Gitlab implements INodeType { { name: 'gitlabApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'gitlabOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'The resource to operate on.', + }, { displayName: 'Resource', name: 'resource', @@ -793,10 +827,26 @@ export class Gitlab implements INodeType { const items = this.getInputData(); const returnData: IDataObject[] = []; - const credentials = this.getCredentials('gitlabApi'); + let credentials; - if (credentials === undefined) { - throw new Error('No credentials got returned!'); + const authenticationMethod = this.getNodeParameter('authentication', 0); + + try { + if (authenticationMethod === 'accessToken') { + credentials = this.getCredentials('gitlabApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + } else { + credentials = this.getCredentials('gitlabOAuth2Api'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + } + } catch (error) { + throw new Error(error); } // Operations which overwrite the returned data diff --git a/packages/nodes-base/nodes/Gitlab/GitlabTrigger.node.ts b/packages/nodes-base/nodes/Gitlab/GitlabTrigger.node.ts index 28987c2458..05c2095715 100644 --- a/packages/nodes-base/nodes/Gitlab/GitlabTrigger.node.ts +++ b/packages/nodes-base/nodes/Gitlab/GitlabTrigger.node.ts @@ -14,7 +14,6 @@ import { gitlabApiRequest, } from './GenericFunctions'; - export class GitlabTrigger implements INodeType { description: INodeTypeDescription = { displayName: 'Gitlab Trigger', @@ -34,7 +33,25 @@ export class GitlabTrigger implements INodeType { { name: 'gitlabApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'gitlabOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], webhooks: [ { @@ -45,6 +62,23 @@ export class GitlabTrigger implements INodeType { }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'The resource to operate on.', + }, { displayName: 'Repository Owner', name: 'owner', @@ -135,7 +169,10 @@ export class GitlabTrigger implements INodeType { // Webhook got created before so check if it still exists const owner = this.getNodeParameter('owner') as string; const repository = this.getNodeParameter('repository') as string; - const endpoint = `/projects/${owner}%2F${repository}/hooks/${webhookData.webhookId}`; + + const path = (`${owner}/${repository}`).replace(/\//g,'%2F'); + + const endpoint = `/projects/${path}/hooks/${webhookData.webhookId}`; try { await gitlabApiRequest.call(this, 'GET', endpoint, {}); @@ -175,15 +212,22 @@ export class GitlabTrigger implements INodeType { events[`${e}_events`] = true; } - const endpoint = `/projects/${owner}%2F${repository}/hooks`; + // gitlab set the push_events to true when the field it's not sent. + // set it to false when it's not picked by the user. + if (events['push_events'] === undefined) { + events['push_events'] = false; + } + + const path = (`${owner}/${repository}`).replace(/\//g,'%2F'); + + const endpoint = `/projects/${path}/hooks`; const body = { url: webhookUrl, - events, + ...events, enable_ssl_verification: false, }; - let responseData; try { responseData = await gitlabApiRequest.call(this, 'POST', endpoint, body); @@ -208,7 +252,10 @@ export class GitlabTrigger implements INodeType { if (webhookData.webhookId !== undefined) { const owner = this.getNodeParameter('owner') as string; const repository = this.getNodeParameter('repository') as string; - const endpoint = `/projects/${owner}%2F${repository}/hooks/${webhookData.webhookId}`; + + const path = (`${owner}/${repository}`).replace(/\//g,'%2F'); + + const endpoint = `/projects/${path}/hooks/${webhookData.webhookId}`; const body = {}; try { diff --git a/packages/nodes-base/nodes/Google/Calendar/EventDescription.ts b/packages/nodes-base/nodes/Google/Calendar/EventDescription.ts index e92582a847..545ed841f1 100644 --- a/packages/nodes-base/nodes/Google/Calendar/EventDescription.ts +++ b/packages/nodes-base/nodes/Google/Calendar/EventDescription.ts @@ -1,4 +1,6 @@ -import { INodeProperties } from "n8n-workflow"; +import { + INodeProperties, +} from 'n8n-workflow'; export const eventOperations = [ { @@ -37,37 +39,36 @@ export const eventOperations = [ name: 'Update', value: 'update', description: 'Update an event', - }, + } ], default: 'create', - description: 'The operation to perform.', - }, + description: 'The operation to perform.' + } ] as INodeProperties[]; export const eventFields = [ - -/* -------------------------------------------------------------------------- */ -/* event:create */ -/* -------------------------------------------------------------------------- */ + /* -------------------------------------------------------------------------- */ + /* event:create */ + /* -------------------------------------------------------------------------- */ { displayName: 'Calendar', name: 'calendar', type: 'options', typeOptions: { - loadOptionsMethod: 'getCalendars', + loadOptionsMethod: 'getCalendars' }, required: true, displayOptions: { show: { operation: [ - 'create', + 'create' ], resource: [ - 'event', + 'event' ], }, }, - default: '', + default: '' }, { displayName: 'Start', @@ -85,7 +86,7 @@ export const eventFields = [ }, }, default: '', - description: 'Start time of the event.', + description: 'Start time of the event.' }, { displayName: 'End', @@ -103,7 +104,7 @@ export const eventFields = [ }, }, default: '', - description: 'End time of the event.', + description: 'End time of the event.' }, { displayName: 'Use Default Reminders', @@ -119,7 +120,7 @@ export const eventFields = [ ], }, }, - default: true, + default: true }, { displayName: 'Additional Fields', @@ -153,7 +154,7 @@ export const eventFields = [ }, ], default: 'no', - description: 'Wheater the event is all day or not', + description: 'Wheater the event is all day or not' }, { displayName: 'Attendees', @@ -176,6 +177,15 @@ export const eventFields = [ default: '', description: 'The color of the event.', }, + { + displayName: 'Description', + name: 'description', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', + }, { displayName: 'Guests Can Invite Others', name: 'guestsCanInviteOthers', @@ -239,7 +249,7 @@ export const eventFields = [ { name: 'Yearly', value: 'yearly', - }, + } ], default: '', }, @@ -254,9 +264,9 @@ export const eventFields = [ name: 'repeatHowManyTimes', type: 'number', typeOptions: { - minValue: 1, + minValue: 1 }, - default: 1, + default: 1 }, { displayName: 'Send Updates', @@ -266,7 +276,7 @@ export const eventFields = [ { name: 'All', value: 'all', - description: ' Notifications are sent to all guests', + description: 'Notifications are sent to all guests' }, { name: 'External Only', @@ -276,8 +286,8 @@ export const eventFields = [ { name: 'None', value: 'none', - description: ' No notifications are sent. This value should only be used for migration use case', - }, + description: 'No notifications are sent. This value should only be used for migration use case', + } ], description: 'Whether to send notifications about the creation of the new event', default: '', @@ -303,7 +313,7 @@ export const eventFields = [ name: 'Busy', value: 'opaque', description: ' The event does block time on the calendar.', - }, + } ], default: 'opaque', description: 'Whether the event blocks time on the calendar', @@ -316,7 +326,7 @@ export const eventFields = [ loadOptionsMethod: 'getTimezones', }, default: '', - description: 'The timezone the event will have set. By default events are schedule on timezone set in n8n.' + description: 'The timezone the event will have set. By default events are schedule on timezone set in n8n.', }, { displayName: 'Visibility', @@ -331,7 +341,7 @@ export const eventFields = [ { name: 'Default', value: 'default', - description: ' Uses the default visibility for events on the calendar.', + description: 'Uses the default visibility for events on the calendar.', }, { name: 'Private', @@ -345,7 +355,7 @@ export const eventFields = [ }, ], default: 'default', - description: 'Visibility of the event.', + description: 'Visibility of the event.' }, ], }, @@ -356,7 +366,7 @@ export const eventFields = [ default: '', placeholder: 'Add Reminder', typeOptions: { - multipleValues: true, + multipleValues: true }, required: false, displayOptions: { @@ -404,13 +414,13 @@ export const eventFields = [ default: 0, }, ], - } + }, ], - description: `If the event doesn't use the default reminders, this lists the reminders specific to the event`, + description: `If the event doesn't use the default reminders, this lists the reminders specific to the event` }, -/* -------------------------------------------------------------------------- */ -/* event:delete */ -/* -------------------------------------------------------------------------- */ + /* -------------------------------------------------------------------------- */ + /* event:delete */ + /* -------------------------------------------------------------------------- */ { displayName: 'Calendar', name: 'calendar', @@ -429,7 +439,7 @@ export const eventFields = [ ], }, }, - default: '', + default: '' }, { displayName: 'Event ID', @@ -473,7 +483,7 @@ export const eventFields = [ { name: 'All', value: 'all', - description: ' Notifications are sent to all guests', + description: 'Notifications are sent to all guests', }, { name: 'External Only', @@ -483,17 +493,17 @@ export const eventFields = [ { name: 'None', value: 'none', - description: ' No notifications are sent. This value should only be used for migration use case', - }, + description: 'No notifications are sent. This value should only be used for migration use case', + } ], description: 'Whether to send notifications about the creation of the new event', default: '', }, ], }, -/* -------------------------------------------------------------------------- */ -/* event:get */ -/* -------------------------------------------------------------------------- */ + /* -------------------------------------------------------------------------- */ + /* event:get */ + /* -------------------------------------------------------------------------- */ { displayName: 'Calendar', name: 'calendar', @@ -512,7 +522,7 @@ export const eventFields = [ ], }, }, - default: '', + default: '' }, { displayName: 'Event ID', @@ -565,12 +575,12 @@ export const eventFields = [ }, default: '', description: `Time zone used in the response. The default is the time zone of the calendar.`, - }, - ], + } + ] }, -/* -------------------------------------------------------------------------- */ -/* event:getAll */ -/* -------------------------------------------------------------------------- */ + /* -------------------------------------------------------------------------- */ + /* event:getAll */ + /* -------------------------------------------------------------------------- */ { displayName: 'Calendar', name: 'calendar', @@ -589,7 +599,7 @@ export const eventFields = [ ], }, }, - default: '', + default: '' }, { displayName: 'Return All', @@ -678,7 +688,7 @@ export const eventFields = [ name: 'Updated', value: 'updated', description: 'Order by last modification time (ascending).', - }, + } ], default: '', description: 'The order of the events returned in the result.', @@ -743,18 +753,18 @@ export const eventFields = [ default: '', description: `Lower bound for an event's last modification time (as a RFC3339 timestamp) to filter by. When specified, entries deleted since this time will always be included regardless of showDeleted`, - }, - ], + } + ] }, -/* -------------------------------------------------------------------------- */ -/* event:update */ -/* -------------------------------------------------------------------------- */ + /* -------------------------------------------------------------------------- */ + /* event:update */ + /* -------------------------------------------------------------------------- */ { displayName: 'Calendar', name: 'calendar', type: 'options', typeOptions: { - loadOptionsMethod: 'getCalendars', + loadOptionsMethod: 'getCalendars' }, required: true, displayOptions: { @@ -800,7 +810,7 @@ export const eventFields = [ ], }, }, - default: true, + default: true }, { displayName: 'Update Fields', @@ -831,7 +841,7 @@ export const eventFields = [ { name: 'No', value: 'no', - }, + } ], default: 'no', description: 'Wheater the event is all day or not', @@ -857,6 +867,15 @@ export const eventFields = [ default: '', description: 'The color of the event.', }, + { + displayName: 'Description', + name: 'description', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', + }, { displayName: 'End', name: 'end', @@ -927,7 +946,7 @@ export const eventFields = [ { name: 'Yearly', value: 'yearly', - }, + } ], default: '', }, @@ -971,8 +990,8 @@ export const eventFields = [ { name: 'None', value: 'none', - description: ' No notifications are sent. This value should only be used for migration use case', - }, + description: 'No notifications are sent. This value should only be used for migration use case', + } ], description: 'Whether to send notifications about the creation of the new event', default: '', @@ -1011,7 +1030,7 @@ export const eventFields = [ loadOptionsMethod: 'getTimezones', }, default: '', - description: 'The timezone the event will have set. By default events are schedule on n8n timezone ' + description: 'The timezone the event will have set. By default events are schedule on n8n timezone', }, { displayName: 'Visibility', @@ -1026,7 +1045,7 @@ export const eventFields = [ { name: 'Default', value: 'default', - description: ' Uses the default visibility for events on the calendar.', + description: 'Uses the default visibility for events on the calendar.', }, { name: 'Public', @@ -1037,7 +1056,7 @@ export const eventFields = [ name: 'Private', value: 'private', description: 'The event is private and only event attendees may view event details.', - }, + } ], default: 'default', description: 'Visibility of the event.', @@ -1051,7 +1070,7 @@ export const eventFields = [ default: '', placeholder: 'Add Reminder', typeOptions: { - multipleValues: true, + multipleValues: true }, required: false, displayOptions: { @@ -1084,7 +1103,7 @@ export const eventFields = [ { name: 'Popup', value: 'popup', - }, + } ], default: '', }, @@ -1099,8 +1118,8 @@ export const eventFields = [ default: 0, }, ], - } + }, ], description: `If the event doesn't use the default reminders, this lists the reminders specific to the event`, - }, + } ] as INodeProperties[]; diff --git a/packages/nodes-base/nodes/Google/Calendar/EventInterface.ts b/packages/nodes-base/nodes/Google/Calendar/EventInterface.ts index 72bf96cc80..14cda0fe41 100644 --- a/packages/nodes-base/nodes/Google/Calendar/EventInterface.ts +++ b/packages/nodes-base/nodes/Google/Calendar/EventInterface.ts @@ -1,4 +1,6 @@ -import { IDataObject } from "n8n-workflow"; +import { + IDataObject, + } from 'n8n-workflow'; export interface IReminder { useDefault?: boolean; diff --git a/packages/nodes-base/nodes/Google/Calendar/GenericFunctions.ts b/packages/nodes-base/nodes/Google/Calendar/GenericFunctions.ts index 18d808cef7..caf4c9868d 100644 --- a/packages/nodes-base/nodes/Google/Calendar/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Google/Calendar/GenericFunctions.ts @@ -33,9 +33,15 @@ export async function googleApiRequest(this: IExecuteFunctions | IExecuteSingleF //@ts-ignore return await this.helpers.requestOAuth2.call(this, 'googleCalendarOAuth2Api', options); } catch (error) { - if (error.response && error.response.body && error.response.body.message) { + if (error.response && error.response.body && error.response.body.error) { + + let errors = error.response.body.error.errors; + + errors = errors.map((e: IDataObject) => e.message); // Try to return the error prettier - throw new Error(`Google Calendar error response [${error.statusCode}]: ${error.response.body.message}`); + throw new Error( + `Google Calendar error response [${error.statusCode}]: ${errors.join('|')}` + ); } throw error; } diff --git a/packages/nodes-base/nodes/Google/Calendar/GoogleCalendar.node.ts b/packages/nodes-base/nodes/Google/Calendar/GoogleCalendar.node.ts index 1f185935d7..4c8208590e 100644 --- a/packages/nodes-base/nodes/Google/Calendar/GoogleCalendar.node.ts +++ b/packages/nodes-base/nodes/Google/Calendar/GoogleCalendar.node.ts @@ -46,7 +46,7 @@ export class GoogleCalendar implements INodeType { { name: 'googleCalendarOAuth2Api', required: true, - }, + } ], properties: [ { @@ -60,7 +60,7 @@ export class GoogleCalendar implements INodeType { }, ], default: 'event', - description: 'The resource to operate on.', + description: 'The resource to operate on.' }, ...eventOperations, ...eventFields, @@ -71,55 +71,70 @@ export class GoogleCalendar implements INodeType { loadOptions: { // Get all the calendars to display them to user so that he can // select them easily - async getCalendars(this: ILoadOptionsFunctions): Promise { + async getCalendars( + this: ILoadOptionsFunctions + ): Promise { const returnData: INodePropertyOptions[] = []; - const calendars = await googleApiRequestAllItems.call(this, 'items', 'GET', '/calendar/v3/users/me/calendarList'); + const calendars = await googleApiRequestAllItems.call( + this, + 'items', + 'GET', + '/calendar/v3/users/me/calendarList' + ); for (const calendar of calendars) { const calendarName = calendar.summary; const calendarId = calendar.id; returnData.push({ name: calendarName, - value: calendarId, + value: calendarId }); } return returnData; }, // Get all the colors to display them to user so that he can // select them easily - async getColors(this: ILoadOptionsFunctions): Promise { + async getColors( + this: ILoadOptionsFunctions + ): Promise { const returnData: INodePropertyOptions[] = []; - const { calendar } = await googleApiRequest.call(this, 'GET', '/calendar/v3/colors'); - for (const key of Object.keys(calendar)) { - const colorName = calendar[key].background; + const { event } = await googleApiRequest.call( + this, + 'GET', + '/calendar/v3/colors' + ); + for (const key of Object.keys(event)) { + const colorName = `Background: ${event[key].background} - Foreground: ${event[key].foreground}`; const colorId = key; returnData.push({ - name: `${colorName} - ${colorId}`, - value: colorId, + name: `${colorName}`, + value: colorId }); } return returnData; }, // Get all the timezones to display them to user so that he can // select them easily - async getTimezones(this: ILoadOptionsFunctions): Promise { + async getTimezones( + this: ILoadOptionsFunctions + ): Promise { const returnData: INodePropertyOptions[] = []; for (const timezone of moment.tz.names()) { const timezoneName = timezone; const timezoneId = timezone; returnData.push({ name: timezoneName, - value: timezoneId, + value: timezoneId }); } return returnData; - }, - }, + } + } }; async execute(this: IExecuteFunctions): Promise { const items = this.getInputData(); const returnData: IDataObject[] = []; - const length = items.length as unknown as number; + const length = (items.length as unknown) as number; const qs: IDataObject = {}; let responseData; const resource = this.getNodeParameter('resource', 0) as string; @@ -131,8 +146,14 @@ export class GoogleCalendar implements INodeType { const calendarId = this.getNodeParameter('calendar', i) as string; const start = this.getNodeParameter('start', i) as string; const end = this.getNodeParameter('end', i) as string; - const useDefaultReminders = this.getNodeParameter('useDefaultReminders', i) as boolean; - const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + const useDefaultReminders = this.getNodeParameter( + 'useDefaultReminders', + i + ) as boolean; + const additionalFields = this.getNodeParameter( + 'additionalFields', + i + ) as IDataObject; if (additionalFields.maxAttendees) { qs.maxAttendees = additionalFields.maxAttendees as number; } @@ -145,17 +166,19 @@ export class GoogleCalendar implements INodeType { const body: IEvent = { start: { dateTime: start, - timeZone: additionalFields.timeZone || this.getTimezone(), + timeZone: additionalFields.timeZone || this.getTimezone() }, end: { dateTime: end, - timeZone: additionalFields.timeZone || this.getTimezone(), + timeZone: additionalFields.timeZone || this.getTimezone() } }; if (additionalFields.attendees) { - body.attendees = (additionalFields.attendees as string[]).map(attendee => { - return { email: attendee }; - }); + body.attendees = (additionalFields.attendees as string[]).map( + attendee => { + return { email: attendee }; + } + ); } if (additionalFields.color) { body.colorId = additionalFields.color as string; @@ -188,9 +211,12 @@ export class GoogleCalendar implements INodeType { body.visibility = additionalFields.visibility as string; } if (!useDefaultReminders) { - const reminders = (this.getNodeParameter('remindersUi', i) as IDataObject).remindersValues as IDataObject[]; + const reminders = (this.getNodeParameter( + 'remindersUi', + i + ) as IDataObject).remindersValues as IDataObject[]; body.reminders = { - useDefault: false, + useDefault: false }; if (reminders) { body.reminders.overrides = reminders; @@ -198,32 +224,54 @@ export class GoogleCalendar implements INodeType { } if (additionalFields.allday) { body.start = { - date: moment(start).utc().format('YYYY-MM-DD'), + date: moment(start) + .utc() + .format('YYYY-MM-DD') }; body.end = { - date: moment(end).utc().format('YYYY-MM-DD'), + date: moment(end) + .utc() + .format('YYYY-MM-DD') }; } //exampel: RRULE:FREQ=WEEKLY;INTERVAL=2;COUNT=10;UNTIL=20110701T170000Z //https://icalendar.org/iCalendar-RFC-5545/3-8-5-3-recurrence-rule.html body.recurrence = []; - if (additionalFields.repeatHowManyTimes - && additionalFields.repeatUntil) { - throw new Error(`You can set either 'Repeat How Many Times' or 'Repeat Until' but not both`); + if ( + additionalFields.repeatHowManyTimes && + additionalFields.repeatUntil + ) { + throw new Error( + `You can set either 'Repeat How Many Times' or 'Repeat Until' but not both` + ); } if (additionalFields.repeatFrecuency) { - body.recurrence?.push(`FREQ=${(additionalFields.repeatFrecuency as string).toUpperCase()};`); + body.recurrence?.push( + `FREQ=${(additionalFields.repeatFrecuency as string).toUpperCase()};` + ); } if (additionalFields.repeatHowManyTimes) { - body.recurrence?.push(`COUNT=${additionalFields.repeatHowManyTimes};`); + body.recurrence?.push( + `COUNT=${additionalFields.repeatHowManyTimes};` + ); } if (additionalFields.repeatUntil) { - body.recurrence?.push(`UNTIL=${moment(additionalFields.repeatUntil as string).utc().format('YYYYMMDDTHHmmss')}Z`); + body.recurrence?.push( + `UNTIL=${moment(additionalFields.repeatUntil as string) + .utc() + .format('YYYYMMDDTHHmmss')}Z` + ); } if (body.recurrence.length !== 0) { body.recurrence = [`RRULE:${body.recurrence.join('')}`]; } - responseData = await googleApiRequest.call(this, 'POST', `/calendar/v3/calendars/${calendarId}/events`, body, qs); + responseData = await googleApiRequest.call( + this, + 'POST', + `/calendar/v3/calendars/${calendarId}/events`, + body, + qs + ); } //https://developers.google.com/calendar/v3/reference/events/delete if (operation === 'delete') { @@ -233,8 +281,13 @@ export class GoogleCalendar implements INodeType { if (options.sendUpdates) { qs.sendUpdates = options.sendUpdates as number; } - responseData = await googleApiRequest.call(this, 'DELETE', `/calendar/v3/calendars/${calendarId}/events/${eventId}`, {}); - responseData = { success: true }; + responseData = await googleApiRequest.call( + this, + 'DELETE', + `/calendar/v3/calendars/${calendarId}/events/${eventId}`, + {} + ); + responseData = { success: true }; } //https://developers.google.com/calendar/v3/reference/events/get if (operation === 'get') { @@ -247,7 +300,13 @@ export class GoogleCalendar implements INodeType { if (options.timeZone) { qs.timeZone = options.timeZone as string; } - responseData = await googleApiRequest.call(this, 'GET', `/calendar/v3/calendars/${calendarId}/events/${eventId}`, {}, qs); + responseData = await googleApiRequest.call( + this, + 'GET', + `/calendar/v3/calendars/${calendarId}/events/${eventId}`, + {}, + qs + ); } //https://developers.google.com/calendar/v3/reference/events/list if (operation === 'getAll') { @@ -288,10 +347,23 @@ export class GoogleCalendar implements INodeType { qs.updatedMin = options.updatedMin as string; } if (returnAll) { - responseData = await googleApiRequestAllItems.call(this, 'items', 'GET', `/calendar/v3/calendars/${calendarId}/events`, {}, qs); + responseData = await googleApiRequestAllItems.call( + this, + 'items', + 'GET', + `/calendar/v3/calendars/${calendarId}/events`, + {}, + qs + ); } else { qs.maxResults = this.getNodeParameter('limit', i) as number; - responseData = await googleApiRequest.call(this, 'GET', `/calendar/v3/calendars/${calendarId}/events`, {}, qs); + responseData = await googleApiRequest.call( + this, + 'GET', + `/calendar/v3/calendars/${calendarId}/events`, + {}, + qs + ); responseData = responseData.items; } } @@ -299,8 +371,14 @@ export class GoogleCalendar implements INodeType { if (operation === 'update') { const calendarId = this.getNodeParameter('calendar', i) as string; const eventId = this.getNodeParameter('eventId', i) as string; - const useDefaultReminders = this.getNodeParameter('useDefaultReminders', i) as boolean; - const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; + const useDefaultReminders = this.getNodeParameter( + 'useDefaultReminders', + i + ) as boolean; + const updateFields = this.getNodeParameter( + 'updateFields', + i + ) as IDataObject; if (updateFields.maxAttendees) { qs.maxAttendees = updateFields.maxAttendees as number; } @@ -314,19 +392,21 @@ export class GoogleCalendar implements INodeType { if (updateFields.start) { body.start = { dateTime: updateFields.start, - timeZone: updateFields.timeZone || this.getTimezone(), + timeZone: updateFields.timeZone || this.getTimezone() }; } if (updateFields.end) { body.end = { dateTime: updateFields.end, - timeZone: updateFields.timeZone || this.getTimezone(), + timeZone: updateFields.timeZone || this.getTimezone() }; } if (updateFields.attendees) { - body.attendees = (updateFields.attendees as string[]).map(attendee => { - return { email: attendee }; - }); + body.attendees = (updateFields.attendees as string[]).map( + attendee => { + return { email: attendee }; + } + ); } if (updateFields.color) { body.colorId = updateFields.color as string; @@ -359,46 +439,64 @@ export class GoogleCalendar implements INodeType { body.visibility = updateFields.visibility as string; } if (!useDefaultReminders) { - const reminders = (this.getNodeParameter('remindersUi', i) as IDataObject).remindersValues as IDataObject[]; + const reminders = (this.getNodeParameter( + 'remindersUi', + i + ) as IDataObject).remindersValues as IDataObject[]; body.reminders = { - useDefault: false, + useDefault: false }; if (reminders) { body.reminders.overrides = reminders; } } - if (updateFields.allday - && updateFields.start - && updateFields.end) { + if (updateFields.allday && updateFields.start && updateFields.end) { body.start = { - date: moment(updateFields.start as string).utc().format('YYYY-MM-DD'), + date: moment(updateFields.start as string) + .utc() + .format('YYYY-MM-DD') }; body.end = { - date: moment(updateFields.end as string).utc().format('YYYY-MM-DD'), + date: moment(updateFields.end as string) + .utc() + .format('YYYY-MM-DD') }; } //exampel: RRULE:FREQ=WEEKLY;INTERVAL=2;COUNT=10;UNTIL=20110701T170000Z //https://icalendar.org/iCalendar-RFC-5545/3-8-5-3-recurrence-rule.html body.recurrence = []; - if (updateFields.repeatHowManyTimes - && updateFields.repeatUntil) { - throw new Error(`You can set either 'Repeat How Many Times' or 'Repeat Until' but not both`); + if (updateFields.repeatHowManyTimes && updateFields.repeatUntil) { + throw new Error( + `You can set either 'Repeat How Many Times' or 'Repeat Until' but not both` + ); } if (updateFields.repeatFrecuency) { - body.recurrence?.push(`FREQ=${(updateFields.repeatFrecuency as string).toUpperCase()};`); + body.recurrence?.push( + `FREQ=${(updateFields.repeatFrecuency as string).toUpperCase()};` + ); } if (updateFields.repeatHowManyTimes) { body.recurrence?.push(`COUNT=${updateFields.repeatHowManyTimes};`); } if (updateFields.repeatUntil) { - body.recurrence?.push(`UNTIL=${moment(updateFields.repeatUntil as string).utc().format('YYYYMMDDTHHmmss')}Z`); + body.recurrence?.push( + `UNTIL=${moment(updateFields.repeatUntil as string) + .utc() + .format('YYYYMMDDTHHmmss')}Z` + ); } if (body.recurrence.length !== 0) { body.recurrence = [`RRULE:${body.recurrence.join('')}`]; } else { delete body.recurrence; } - responseData = await googleApiRequest.call(this, 'PATCH', `/calendar/v3/calendars/${calendarId}/events/${eventId}`, body, qs); + responseData = await googleApiRequest.call( + this, + 'PATCH', + `/calendar/v3/calendars/${calendarId}/events/${eventId}`, + body, + qs + ); } } } diff --git a/packages/nodes-base/nodes/Google/Drive/GenericFunctions.ts b/packages/nodes-base/nodes/Google/Drive/GenericFunctions.ts new file mode 100644 index 0000000000..7d15e492ad --- /dev/null +++ b/packages/nodes-base/nodes/Google/Drive/GenericFunctions.ts @@ -0,0 +1,142 @@ +import { + OptionsWithUri, +} from 'request'; + +import { + IExecuteFunctions, + IExecuteSingleFunctions, + ILoadOptionsFunctions, +} from 'n8n-core'; + +import { + IDataObject, +} from 'n8n-workflow'; + +import * as moment from 'moment-timezone'; + +import * as jwt from 'jsonwebtoken'; + +export async function googleApiRequest(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise { // tslint:disable-line:no-any + const authenticationMethod = this.getNodeParameter('authentication', 0, 'serviceAccount') as string; + + let options: OptionsWithUri = { + headers: { + 'Content-Type': 'application/json', + }, + method, + body, + qs, + uri: uri || `https://www.googleapis.com${resource}`, + json: true, + }; + options = Object.assign({}, options, option); + try { + if (Object.keys(body).length === 0) { + delete options.body; + } + + if (authenticationMethod === 'serviceAccount') { + const credentials = this.getCredentials('googleApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + const { access_token } = await getAccessToken.call(this, credentials as IDataObject); + + options.headers!.Authorization = `Bearer ${access_token}`; + //@ts-ignore + return await this.helpers.request(options); + } else { + //@ts-ignore + return await this.helpers.requestOAuth2.call(this, 'googleDriveOAuth2Api', options); + } + } catch (error) { + if (error.response && error.response.body && error.response.body.error) { + + let errorMessages; + + if (error.response.body.error.errors) { + // Try to return the error prettier + errorMessages = error.response.body.error.errors; + + errorMessages = errorMessages.map((errorItem: IDataObject) => errorItem.message); + + errorMessages = errorMessages.join('|'); + + } else if (error.response.body.error.message) { + errorMessages = error.response.body.error.message; + } + + throw new Error(`Google Drive error response [${error.statusCode}]: ${errorMessages}`); + } + throw error; + } +} + +export async function googleApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, propertyName: string, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise { // tslint:disable-line:no-any + + const returnData: IDataObject[] = []; + + let responseData; + query.maxResults = 100; + + do { + responseData = await googleApiRequest.call(this, method, endpoint, body, query); + query.pageToken = responseData['nextPageToken']; + returnData.push.apply(returnData, responseData[propertyName]); + } while ( + responseData['nextPageToken'] !== undefined && + responseData['nextPageToken'] !== '' + ); + + return returnData; +} + +function getAccessToken(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, credentials: IDataObject): Promise { + //https://developers.google.com/identity/protocols/oauth2/service-account#httprest + + const scopes = [ + 'https://www.googleapis.com/auth/drive', + 'https://www.googleapis.com/auth/drive.appdata', + 'https://www.googleapis.com/auth/drive.photos.readonly', + ]; + + const now = moment().unix(); + + const signature = jwt.sign( + { + 'iss': credentials.email as string, + 'sub': credentials.email as string, + 'scope': scopes.join(' '), + 'aud': `https://oauth2.googleapis.com/token`, + 'iat': now, + 'exp': now + 3600, + }, + credentials.privateKey as string, + { + algorithm: 'RS256', + header: { + 'kid': credentials.privateKey as string, + 'typ': 'JWT', + 'alg': 'RS256', + }, + } + ); + + const options: OptionsWithUri = { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + method: 'POST', + form: { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: signature, + }, + uri: 'https://oauth2.googleapis.com/token', + json: true + }; + + //@ts-ignore + return this.helpers.request(options); +} diff --git a/packages/nodes-base/nodes/Google/Drive/GoogleDrive.node.ts b/packages/nodes-base/nodes/Google/Drive/GoogleDrive.node.ts index 387a3d7bc0..f6291b1045 100644 --- a/packages/nodes-base/nodes/Google/Drive/GoogleDrive.node.ts +++ b/packages/nodes-base/nodes/Google/Drive/GoogleDrive.node.ts @@ -1,10 +1,8 @@ -import { google } from 'googleapis'; -const { Readable } = require('stream'); - import { BINARY_ENCODING, IExecuteFunctions, } from 'n8n-core'; + import { IDataObject, INodeTypeDescription, @@ -12,8 +10,9 @@ import { INodeType, } from 'n8n-workflow'; -import { getAuthenticationClient } from '../GoogleApi'; - +import { + googleApiRequest, +} from './GenericFunctions'; export class GoogleDrive implements INodeType { description: INodeTypeDescription = { @@ -34,9 +33,43 @@ export class GoogleDrive implements INodeType { { name: 'googleApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'serviceAccount', + ], + }, + }, + }, + { + name: 'googleDriveOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Service Account', + value: 'serviceAccount', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'serviceAccount', + }, { displayName: 'Resource', name: 'resource', @@ -764,7 +797,7 @@ export class GoogleDrive implements INodeType { { name: 'domain', value: 'domain', - description:"All files shared to the user's domain that are searchable", + description: 'All files shared to the user\'s domain that are searchable', }, { name: 'drive', @@ -813,26 +846,6 @@ export class GoogleDrive implements INodeType { const items = this.getInputData(); const returnData: IDataObject[] = []; - const credentials = this.getCredentials('googleApi'); - - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - - const scopes = [ - 'https://www.googleapis.com/auth/drive', - 'https://www.googleapis.com/auth/drive.appdata', - 'https://www.googleapis.com/auth/drive.photos.readonly', - ]; - - const client = await getAuthenticationClient(credentials.email as string, credentials.privateKey as string, scopes); - - const drive = google.drive({ - version: 'v3', - // @ts-ignore - auth: client, - }); - const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; @@ -857,22 +870,20 @@ export class GoogleDrive implements INodeType { const fileId = this.getNodeParameter('fileId', i) as string; - const copyOptions = { - fileId, + const body: IDataObject = { fields: queryFields, - requestBody: {} as IDataObject, }; const optionProperties = ['name', 'parents']; for (const propertyName of optionProperties) { if (options[propertyName] !== undefined) { - copyOptions.requestBody[propertyName] = options[propertyName]; + body[propertyName] = options[propertyName]; } } - const response = await drive.files.copy(copyOptions); + const response = await googleApiRequest.call(this, 'POST', `/drive/v3/files/${fileId}/copy`, body); - returnData.push(response.data as IDataObject); + returnData.push(response as IDataObject); } else if (operation === 'download') { // ---------------------------------- @@ -881,15 +892,13 @@ export class GoogleDrive implements INodeType { const fileId = this.getNodeParameter('fileId', i) as string; - const response = await drive.files.get( - { - fileId, - alt: 'media', - }, - { - responseType: 'arraybuffer', - }, - ); + const requestOptions = { + resolveWithFullResponse: true, + encoding: null, + json: false, + }; + + const response = await googleApiRequest.call(this, 'GET', `/drive/v3/files/${fileId}`, {}, { alt: 'media' }, undefined, requestOptions); let mimeType: string | undefined; if (response.headers['content-type']) { @@ -912,7 +921,7 @@ export class GoogleDrive implements INodeType { const dataPropertyNameDownload = this.getNodeParameter('binaryPropertyName', i) as string; - const data = Buffer.from(response.data as string); + const data = Buffer.from(response.body as string); items[i].binary![dataPropertyNameDownload] = await this.helpers.prepareBinaryData(data as unknown as Buffer, undefined, mimeType); @@ -936,7 +945,7 @@ export class GoogleDrive implements INodeType { queryCorpora = options.corpora as string; } - let driveId : string | undefined; + let driveId: string | undefined; driveId = options.driveId as string; if (driveId === '') { driveId = undefined; @@ -988,20 +997,19 @@ export class GoogleDrive implements INodeType { const pageSize = this.getNodeParameter('limit', i) as number; - const res = await drive.files.list({ + const qs = { pageSize, orderBy: 'modifiedTime', fields: `nextPageToken, files(${queryFields})`, spaces: querySpaces, - corpora: queryCorpora, - driveId, q: queryString, - includeItemsFromAllDrives: (queryCorpora !== '' || driveId !== ''), // Actually depracated, - supportsAllDrives: (queryCorpora !== '' || driveId !== ''), // see https://developers.google.com/drive/api/v3/reference/files/list - // However until June 2020 still needs to be set, to avoid API errors. - }); + includeItemsFromAllDrives: (queryCorpora !== '' || driveId !== ''), + supportsAllDrives: (queryCorpora !== '' || driveId !== ''), + }; - const files = res!.data.files; + const response = await googleApiRequest.call(this, 'GET', `/drive/v3/files`, {}, qs); + + const files = response!.files; return [this.helpers.returnJsonArray(files as IDataObject[])]; @@ -1044,29 +1052,35 @@ export class GoogleDrive implements INodeType { const name = this.getNodeParameter('name', i) as string; const parents = this.getNodeParameter('parents', i) as string[]; - const response = await drive.files.create({ - requestBody: { - name, - originalFilename, - parents, - }, + let qs: IDataObject = { fields: queryFields, - media: { - mimeType, - body: ((buffer: Buffer) => { - const readableInstanceStream = new Readable({ - read() { - this.push(buffer); - this.push(null); - } - }); + uploadType: 'media', + }; - return readableInstanceStream; - })(body), + const requestOptions = { + headers: { + 'Content-Type': mimeType, + 'Content-Length': body.byteLength, }, - }); + encoding: null, + json: false, + }; - returnData.push(response.data as IDataObject); + let response = await googleApiRequest.call(this, 'POST', `/upload/drive/v3/files`, body, qs, undefined, requestOptions); + + body = { + mimeType, + name, + originalFilename, + }; + + qs = { + addParents: parents.join(','), + }; + + response = await googleApiRequest.call(this, 'PATCH', `/drive/v3/files/${JSON.parse(response).id}`, body, qs); + + returnData.push(response as IDataObject); } } else if (resource === 'folder') { @@ -1077,19 +1091,19 @@ export class GoogleDrive implements INodeType { const name = this.getNodeParameter('name', i) as string; - const fileMetadata = { + const body = { name, mimeType: 'application/vnd.google-apps.folder', parents: options.parents || [], }; - const response = await drive.files.create({ - // @ts-ignore - resource: fileMetadata, + const qs = { fields: queryFields, - }); + }; - returnData.push(response.data as IDataObject); + const response = await googleApiRequest.call(this, 'POST', '/drive/v3/files', body, qs); + + returnData.push(response as IDataObject); } } if (['file', 'folder'].includes(resource)) { @@ -1100,9 +1114,7 @@ export class GoogleDrive implements INodeType { const fileId = this.getNodeParameter('fileId', i) as string; - await drive.files.delete({ - fileId, - }); + const response = await googleApiRequest.call(this, 'DELETE', `/drive/v3/files/${fileId}`); // If we are still here it did succeed returnData.push({ diff --git a/packages/nodes-base/nodes/Google/GoogleApi.ts b/packages/nodes-base/nodes/Google/GoogleApi.ts deleted file mode 100644 index 64ba9f9bec..0000000000 --- a/packages/nodes-base/nodes/Google/GoogleApi.ts +++ /dev/null @@ -1,23 +0,0 @@ - -import { JWT } from 'google-auth-library'; -import { google } from 'googleapis'; - - -/** - * Returns the authentication client needed to access spreadsheet - */ -export async function getAuthenticationClient(email: string, privateKey: string, scopes: string[]): Promise { - const client = new google.auth.JWT( - email, - undefined, - privateKey, - scopes, - undefined - ); - - // TODO: Check later if this or the above should be cached - await client.authorize(); - - // @ts-ignore - return client; -} diff --git a/packages/nodes-base/nodes/Google/Sheet/GoogleSheets.node.ts b/packages/nodes-base/nodes/Google/Sheet/GoogleSheets.node.ts index 90e4e8b1fd..042eb39105 100644 --- a/packages/nodes-base/nodes/Google/Sheet/GoogleSheets.node.ts +++ b/packages/nodes-base/nodes/Google/Sheet/GoogleSheets.node.ts @@ -622,7 +622,7 @@ export class GoogleSheets implements INodeType { // ---------------------------------- // append // ---------------------------------- - const keyRow = this.getNodeParameter('keyRow', 0) as number; + const keyRow = parseInt(this.getNodeParameter('keyRow', 0) as string, 10); const items = this.getInputData(); @@ -670,7 +670,7 @@ export class GoogleSheets implements INodeType { sheetId: range.sheetId, dimension: deletePropertyToDimensions[propertyName] as string, startIndex: range.startIndex, - endIndex: range.startIndex + range.amount, + endIndex: parseInt(range.startIndex.toString(), 10) + parseInt(range.amount.toString(), 10), } } }); @@ -693,8 +693,8 @@ export class GoogleSheets implements INodeType { return []; } - const dataStartRow = this.getNodeParameter('dataStartRow', 0) as number; - const keyRow = this.getNodeParameter('keyRow', 0) as number; + const dataStartRow = parseInt(this.getNodeParameter('dataStartRow', 0) as string, 10); + const keyRow = parseInt(this.getNodeParameter('keyRow', 0) as string, 10); const items = this.getInputData(); @@ -735,8 +735,8 @@ export class GoogleSheets implements INodeType { } ]; } else { - const dataStartRow = this.getNodeParameter('dataStartRow', 0) as number; - const keyRow = this.getNodeParameter('keyRow', 0) as number; + const dataStartRow = parseInt(this.getNodeParameter('dataStartRow', 0) as string, 10); + const keyRow = parseInt(this.getNodeParameter('keyRow', 0) as string, 10); returnData = sheet.structureArrayDataByColumn(sheetData, keyRow, dataStartRow); } @@ -769,8 +769,8 @@ export class GoogleSheets implements INodeType { const data = await sheet.batchUpdate(updateData, valueInputMode); } else { const keyName = this.getNodeParameter('key', 0) as string; - const keyRow = this.getNodeParameter('keyRow', 0) as number; - const dataStartRow = this.getNodeParameter('dataStartRow', 0) as number; + const keyRow = parseInt(this.getNodeParameter('keyRow', 0) as string, 10); + const dataStartRow = parseInt(this.getNodeParameter('dataStartRow', 0) as string, 10); const setData: IDataObject[] = []; items.forEach((item) => { diff --git a/packages/nodes-base/nodes/Google/Task/GenericFunctions.ts b/packages/nodes-base/nodes/Google/Task/GenericFunctions.ts new file mode 100644 index 0000000000..55a690ad73 --- /dev/null +++ b/packages/nodes-base/nodes/Google/Task/GenericFunctions.ts @@ -0,0 +1,92 @@ +import { + OptionsWithUri, +} from 'request'; + +import { + IExecuteFunctions, + IExecuteSingleFunctions, + ILoadOptionsFunctions, +} from 'n8n-core'; + +import { + IDataObject, +} from 'n8n-workflow'; + +export async function googleApiRequest( + this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, + method: string, + resource: string, + body: IDataObject = {}, + qs: IDataObject = {}, + uri?: string, + headers: IDataObject = {} +): Promise { // tslint:disable-line:no-any + const options: OptionsWithUri = { + headers: { + 'Content-Type': 'application/json' + }, + method, + body, + qs, + uri: uri || `https://www.googleapis.com${resource}`, + json: true + }; + + try { + if (Object.keys(headers).length !== 0) { + options.headers = Object.assign({}, options.headers, headers); + } + if (Object.keys(body).length === 0) { + delete options.body; + } + //@ts-ignore + return await this.helpers.requestOAuth2.call( + this, + 'googleTasksOAuth2Api', + options + ); + } catch (error) { + if (error.response && error.response.body && error.response.body.error) { + + let errors = error.response.body.error.errors; + + errors = errors.map((e: IDataObject) => e.message); + // Try to return the error prettier + throw new Error( + `Google Tasks error response [${error.statusCode}]: ${errors.join('|')}` + ); + } + throw error; + } +} + +export async function googleApiRequestAllItems( + this: IExecuteFunctions | ILoadOptionsFunctions, + propertyName: string, + method: string, + endpoint: string, + body: IDataObject = {}, + query: IDataObject = {} +): Promise { // tslint:disable-line:no-any + const returnData: IDataObject[] = []; + + let responseData; + query.maxResults = 100; + + do { + responseData = await googleApiRequest.call( + this, + method, + endpoint, + body, + query + ); + query.pageToken = responseData['nextPageToken']; + returnData.push.apply(returnData, responseData[propertyName]); + } while ( + responseData['nextPageToken'] !== undefined && + responseData['nextPageToken'] !== '' + ); + + return returnData; +} diff --git a/packages/nodes-base/nodes/Google/Task/GoogleTasks.node.ts b/packages/nodes-base/nodes/Google/Task/GoogleTasks.node.ts new file mode 100644 index 0000000000..603bc1af5e --- /dev/null +++ b/packages/nodes-base/nodes/Google/Task/GoogleTasks.node.ts @@ -0,0 +1,279 @@ +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + IDataObject, + ILoadOptionsFunctions, + INodeExecutionData, + INodePropertyOptions, + INodeType, + INodeTypeDescription, +} from 'n8n-workflow'; + +import { + googleApiRequest, + googleApiRequestAllItems, +} from './GenericFunctions'; + +import { + taskOperations, + taskFields, +} from './TaskDescription'; + +export class GoogleTasks implements INodeType { + description: INodeTypeDescription = { + displayName: 'Google Tasks', + name: 'googleTasks', + icon: 'file:googleTasks.png', + group: ['input'], + version: 1, + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + description: 'Consume Google Tasks API.', + defaults: { + name: 'Google Tasks', + color: '#3E87E4' + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'googleTasksOAuth2Api', + required: true + } + ], + properties: [ + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: 'Task', + value: 'task' + } + ], + default: 'task', + description: 'The resource to operate on.' + }, + ...taskOperations, + ...taskFields + ] + }; + methods = { + loadOptions: { + // Get all the tasklists to display them to user so that he can select them easily + + async getTasks( + this: ILoadOptionsFunctions + ): Promise { + const returnData: INodePropertyOptions[] = []; + const tasks = await googleApiRequestAllItems.call( + this, + 'items', + 'GET', + '/tasks/v1/users/@me/lists' + ); + for (const task of tasks) { + const taskName = task.title; + const taskId = task.id; + returnData.push({ + name: taskName, + value: taskId + }); + } + return returnData; + } + } + }; + + async execute(this: IExecuteFunctions): Promise { + const items = this.getInputData(); + const returnData: IDataObject[] = []; + const length = (items.length as unknown) as number; + const qs: IDataObject = {}; + let responseData; + const resource = this.getNodeParameter('resource', 0) as string; + const operation = this.getNodeParameter('operation', 0) as string; + let body: IDataObject = {}; + for (let i = 0; i < length; i++) { + if (resource === 'task') { + if (operation === 'create') { + body = {}; + //https://developers.google.com/tasks/v1/reference/tasks/insert + const taskId = this.getNodeParameter('task', i) as string; + body.title = this.getNodeParameter('title', i) as string; + const additionalFields = this.getNodeParameter( + 'additionalFields', + i + ) as IDataObject; + + if (additionalFields.parent) { + qs.parent = additionalFields.parent as string; + } + if (additionalFields.previous) { + qs.previous = additionalFields.previous as string; + } + + if (additionalFields.status) { + body.status = additionalFields.status as string; + } + + if (additionalFields.notes) { + body.notes = additionalFields.notes as string; + } + if (additionalFields.dueDate) { + body.dueDate = additionalFields.dueDate as string; + } + + if (additionalFields.completed) { + body.completed = additionalFields.completed as string; + } + + if (additionalFields.deleted) { + body.deleted = additionalFields.deleted as boolean; + } + + responseData = await googleApiRequest.call( + this, + 'POST', + `/tasks/v1/lists/${taskId}/tasks`, + body, + qs + ); + } + if (operation === 'delete') { + //https://developers.google.com/tasks/v1/reference/tasks/delete + const taskListId = this.getNodeParameter('task', i) as string; + const taskId = this.getNodeParameter('taskId', i) as string; + + responseData = await googleApiRequest.call( + this, + 'DELETE', + `/tasks/v1/lists/${taskListId}/tasks/${taskId}`, + {} + ); + responseData = { success: true }; + } + if (operation === 'get') { + //https://developers.google.com/tasks/v1/reference/tasks/get + const taskListId = this.getNodeParameter('task', i) as string; + const taskId = this.getNodeParameter('taskId', i) as string; + responseData = await googleApiRequest.call( + this, + 'GET', + `/tasks/v1/lists/${taskListId}/tasks/${taskId}`, + {}, + qs + ); + } + if (operation === 'getAll') { + //https://developers.google.com/tasks/v1/reference/tasks/list + const returnAll = this.getNodeParameter('returnAll', i) as boolean; + const taskListId = this.getNodeParameter('task', i) as string; + const options = this.getNodeParameter( + 'additionalFields', + i + ) as IDataObject; + if (options.completedMax) { + qs.completedMax = options.completedMax as string; + } + if (options.completedMin) { + qs.completedMin = options.completedMin as string; + } + if (options.dueMin) { + qs.dueMin = options.dueMin as string; + } + if (options.dueMax) { + qs.dueMax = options.dueMax as string; + } + if (options.showCompleted) { + qs.showCompleted = options.showCompleted as boolean; + } + if (options.showDeleted) { + qs.showDeleted = options.showDeleted as boolean; + } + if (options.showHidden) { + qs.showHidden = options.showHidden as boolean; + } + if (options.updatedMin) { + qs.updatedMin = options.updatedMin as string; + } + + if (returnAll) { + responseData = await googleApiRequestAllItems.call( + this, + 'items', + 'GET', + `/tasks/v1/lists/${taskListId}/tasks`, + {}, + qs + ); + } else { + qs.maxResults = this.getNodeParameter('limit', i) as number; + responseData = await googleApiRequest.call( + this, + 'GET', + `/tasks/v1/lists/${taskListId}/tasks`, + {}, + qs + ); + responseData = responseData.items; + } + } + if (operation === 'update') { + body = {}; + //https://developers.google.com/tasks/v1/reference/tasks/patch + const taskListId = this.getNodeParameter('task', i) as string; + const taskId = this.getNodeParameter('taskId', i) as string; + const updateFields = this.getNodeParameter( + 'updateFields', + i + ) as IDataObject; + + if (updateFields.previous) { + qs.previous = updateFields.previous as string; + } + + if (updateFields.status) { + body.status = updateFields.status as string; + } + + if (updateFields.notes) { + body.notes = updateFields.notes as string; + } + + if (updateFields.title) { + body.title = updateFields.title as string; + } + + if (updateFields.dueDate) { + body.dueDate = updateFields.dueDate as string; + } + + if (updateFields.completed) { + body.completed = updateFields.completed as string; + } + + if (updateFields.deleted) { + body.deleted = updateFields.deleted as boolean; + } + + responseData = await googleApiRequest.call( + this, + 'PATCH', + `/tasks/v1/lists/${taskListId}/tasks/${taskId}`, + body, + qs + ); + } + } + if (Array.isArray(responseData)) { + returnData.push.apply(returnData, responseData as IDataObject[]); + } else if (responseData !== undefined) { + returnData.push(responseData as IDataObject); + } + } + return [this.helpers.returnJsonArray(returnData)]; + } +} diff --git a/packages/nodes-base/nodes/Google/Task/TaskDescription.ts b/packages/nodes-base/nodes/Google/Task/TaskDescription.ts new file mode 100644 index 0000000000..3300572f2c --- /dev/null +++ b/packages/nodes-base/nodes/Google/Task/TaskDescription.ts @@ -0,0 +1,493 @@ +import { + INodeProperties, +} from 'n8n-workflow'; + +export const taskOperations = [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'task', + ], + }, + }, + options: [ + { + name: 'Create', + value: 'create', + description: 'Add a task to tasklist', + }, + { + name: 'Delete', + value: 'delete', + description: 'Delete a task', + }, + { + name: 'Get', + value: 'get', + description: 'Retrieve a task', + }, + { + name: 'Get All', + value: 'getAll', + description: 'Retrieve all tasks from a tasklist', + }, + { + name: 'Update', + value: 'update', + description: 'Update a task', + } + ], + default: 'create', + description: 'The operation to perform.', + } +] as INodeProperties[]; + +export const taskFields = [ + /* -------------------------------------------------------------------------- */ + /* task:create */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'TaskList', + name: 'task', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTasks', + }, + required: true, + displayOptions: { + show: { + operation: [ + 'create', + ], + resource: [ + 'task', + ], + }, + }, + default: '', + }, + { + displayName: 'Title', + name: 'title', + type: 'string', + default: '', + description: 'Title of the task.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'create', + ], + resource: [ + 'task', + ], + } + }, + options: [ + { + displayName: 'Completion Date', + name: 'completed', + type: 'dateTime', + default: '', + description: `Completion date of the task (as a RFC 3339 timestamp). This field is omitted if the task has not been completed.`, + }, + { + displayName: 'Deleted', + name: 'deleted', + type: 'boolean', + default: false, + description: 'Flag indicating whether the task has been deleted.', + }, + { + displayName: 'Due Date', + name: 'dueDate', + type: 'dateTime', + default: '', + description: 'Due date of the task.', + }, + { + displayName: 'Notes', + name: 'notes', + type: 'string', + default: '', + description: 'Additional Notes.', + }, + { + displayName: 'Parent', + name: 'parent', + type: 'string', + default: '', + description: 'Parent task identifier. If the task is created at the top level, this parameter is omitted.', + }, + { + displayName: 'Previous', + name: 'previous', + type: 'string', + default: '', + description: 'Previous sibling task identifier. If the task is created at the first position among its siblings, this parameter is omitted.', + }, + { + displayName: 'Status', + name: 'status', + type: 'options', + options: [ + { + name: 'Needs Action', + value: 'needsAction', + }, + { + name: 'Completed', + value: 'completed', + } + ], + default: '', + description: 'Current status of the task.', + }, + + ], + }, + /* -------------------------------------------------------------------------- */ + /* task:delete */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'TaskList', + name: 'task', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTasks', + }, + required: true, + displayOptions: { + show: { + operation: [ + 'delete', + ], + resource: [ + 'task', + ], + }, + }, + default: '', + }, + { + displayName: 'Task ID', + name: 'taskId', + type: 'string', + required: true, + displayOptions: { + show: { + operation: [ + 'delete', + ], + resource: [ + 'task', + ], + }, + }, + default: '', + }, + /* -------------------------------------------------------------------------- */ + /* task:get */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'TaskList', + name: 'task', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTasks', + }, + required: true, + displayOptions: { + show: { + operation: [ + 'get', + ], + resource: [ + 'task', + ], + } + }, + default: '', + }, + { + displayName: 'Task ID', + name: 'taskId', + type: 'string', + required: true, + displayOptions: { + show: { + operation: [ + 'get', + ], + resource: [ + 'task', + ], + }, + }, + default: '', + }, + /* -------------------------------------------------------------------------- */ + /* task:getAll */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'TaskList', + name: 'task', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTasks', + }, + required: true, + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'task', + ], + }, + }, + default: '', + }, + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'task', + ], + }, + }, + default: false, + description: 'If all results should be returned or only up to a given limit.', + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'task', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 100 + }, + default: 20, + description: 'How many results to return.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'task', + ], + }, + }, + options: [ + { + displayName: 'Completed Max', + name: 'completedMax', + type: 'dateTime', + default: '', + description: 'Upper bound for a task completion date (as a RFC 3339 timestamp) to filter by.', + }, + { + displayName: 'Completed Min', + name: 'completedMin', + type: 'dateTime', + default: '', + description: 'Lower bound for a task completion date (as a RFC 3339 timestamp) to filter by.', + }, + { + displayName: 'Due Min', + name: 'dueMin', + type: 'dateTime', + default: '', + description: 'Lower bound for a task due date (as a RFC 3339 timestamp) to filter by.', + }, + { + displayName: 'Due Max', + name: 'dueMax', + type: 'dateTime', + default: '', + description: 'Upper bound for a task due date (as a RFC 3339 timestamp) to filter by.', + }, + { + displayName: 'Show Completed', + name: 'showCompleted', + type: 'boolean', + default: true, + description: 'Flag indicating whether completed tasks are returned in the result', + }, + { + displayName: 'Show Deleted', + name: 'showDeleted', + type: 'boolean', + default: false, + description: 'Flag indicating whether deleted tasks are returned in the result', + }, + { + displayName: 'Show Hidden', + name: 'showHidden', + type: 'boolean', + default: false, + description: 'Flag indicating whether hidden tasks are returned in the result', + }, + { + displayName: 'Updated Min', + name: 'updatedMin', + type: 'dateTime', + default: '', + description: 'Lower bound for a task last modification time (as a RFC 3339 timestamp) to filter by.', + }, + ] + }, + /* -------------------------------------------------------------------------- */ + /* task:update */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'TaskList', + name: 'task', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTasks', + }, + required: true, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'task', + ], + }, + }, + default: '', + }, + { + displayName: 'Task ID', + name: 'taskId', + type: 'string', + required: true, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'task', + ], + }, + }, + default: '', + }, + { + displayName: 'Update Fields', + name: 'updateFields', + type: 'collection', + placeholder: 'Update Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'task', + ], + } + }, + options: [ + { + displayName: 'Completion Date', + name: 'completed', + type: 'dateTime', + default: '', + description: `Completion date of the task (as a RFC 3339 timestamp). This field is omitted if the task has not been completed.`, + }, + + { + displayName: 'Deleted', + name: 'deleted', + type: 'boolean', + default: false, + description: 'Flag indicating whether the task has been deleted.', + }, + { + displayName: 'Notes', + name: 'notes', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', + description: 'Additional Notes.', + }, + { + displayName: 'Previous', + name: 'previous', + type: 'string', + default: '', + description: 'Previous sibling task identifier. If the task is created at the first position among its siblings, this parameter is omitted.', + }, + { + displayName: 'Status', + name: 'status', + type: 'options', + options: [ + { + name: 'Needs Update', + value: 'needsAction', + }, + { + name: 'Completed', + value: 'completed', + } + ], + default: '', + description: 'Current status of the task.', + }, + { + displayName: 'Title', + name: 'title', + type: 'string', + default: '', + description: 'Title of the task.', + }, + ], + }, +] as INodeProperties[]; diff --git a/packages/nodes-base/nodes/Google/Task/googleTasks.png b/packages/nodes-base/nodes/Google/Task/googleTasks.png new file mode 100644 index 0000000000000000000000000000000000000000..bbc31280afdc23d93d1d012775e301395d8d6558 GIT binary patch literal 3290 zcmZuzcQo8>79J8^)DVOy35i4*eaIlnL^o=P7QHikCWPp1^xj4Jh!Ubjiq7Z+8;M{> zNkoe}dYKvXTiM-ncK_IW&wcK5pL6d$?|a^V-gpCjjcc@Av>*`ZnwF-z(Pf7I3F<3< z6anE!m+7jDik=Dx)Ram`w4=DJ$^48oR6+F<+#8pLAQEPdG_nie^Z5(m?B?mjhYa*_ z;&bysI)G^ZAT8g&4NTiJO?18-2>8DP5PLT-5bYoQ&wwUWtn z{}qo%Jd`dkHEE!00s}~Y{0smH003M7#7q1aCH)~62LN#Vhv10-fpjU6E{MQ|O61nw zCB1AT0tOjJ%Ap&oFITlwPoWW8`e|o6iATmMM~Y!P7r?o05VbAT-ZcFHmUwKOvZWZd zsu41;g4)xF*(Y59kAk*TQ73wdd+_LaXwbSr20=USOb>Mc3;BIW1e5|7Vd2w60v-?G z)xvj9F90jlSKat+otQPl=rMfnH3A-hr|)&n0gsb#I^pB0k?Y10-*o(YOcSQ{UJm1k zKwk4oXvJprAW;Q50Yh!Ao&rvp3&`SCMdv2#1gzf6FUbw-6@$n7X#VX1h(l0T%M9R_ zxBRMg7vlUex8=7@+Lmt8`owSG*AcJ{043-{oyeKxp{I|+jvuF<3@-rIaRVkvORXQ1 zeY2+0J{{Hn1BkA|_WuH`G7qqa0ID9R>ee&81^A?WsIHA1ZS{6e_;7@#$U~o*1b;lh zUxbxlTvI0(`<;#D(?I*fVpXT)iddh%qFg!)WBcP1h4j?{>wa{z$7U|ZQq zY(Ku$71V`4Y6$&-w;t~0f{ppUs+JQ-jDgYj(UhgH2M*Njbujx=^BXppT~DGQ<6o+Z zG0$0-Ks5~~HfoR$*@Y*UX&Pox1ChKUHip*?`Px0ezmB~XDIPM1=7GkS8}FV*l+ZXt z%V(YdtEU9c!MvG6>fHzTDWm>=o92}n ztrM@^I^QNrcPk!x&Q9W_d}A?TMER~-h@R^@lYITmRv>d%Ut~_?i2AoNpeM426h7j@ zd?wPfPyPy(3yw5%Vx^p;mU6sp)h+8TraLB67a=@0DJ{A&ZL5``e|M6DIPeP1XN4Nb zA#X`Wdrejk^yac{msb?s_(zG?HV-c^0y-DmbXy`Oyn4@D$%lthtyGG_-{WUc&#>S7 z_x}C|$e@kjN`>m0IVrVo@EP6_BSBC#B=A~n?rjCukCcdd4Vm+SElV{FQlU^UD5|(o zE}y5M1^aTcx^ePeS-pn2j>|md+uyP#uc@|D8{R4^`XVIrkAk4Zr8NWMQgev}#z72M z7egPbZJCq@&7PCROx_Qkp!}1RB#1`aTN{Lk|AqmTsfN3qw|#(3uGEKOJifE9xv!)wVxnUEm$qgq>78DXC&CaQe>_r5v5IW>d23tS ztNkpgTl6*M%rf6tYwMM=x~-xt#psw=5~d(|N+J2h%@#6AC@v z&tDo>@{bA6tB$m*@NMxIK4@$IR<(h|x)(LGNN>=-v|psYcgsYPQzlcGUE>CB)CyzZ z9a|=dr4?6cV0=H>;16$h^T=h(nb{<->s!iOJFZbN6{SQ2!7q@`_-ysuYn0T!?6x`m z(6Z}Y0yxHsks`Ed6>EL{Kv7c*yJ3;Li0r1xr`u71VUG6QD(!5vqt`}+GQ312^X~

U@>#&tup@H!K?iYlVd; z96m;e_)zK=g&A-`@V?q9VLVxNIa!H}q2Q=tGonwM)P7pVyP#e9!Dse+wDpL5-Oy5i z+Zzg$#kiP~=a={MFBF-#PUb^b9LUy62l-k1zzM242l(vn&ozQ%JHCU&=xHl4JsoTR z_8f-kJgxMcXJZre^kdsw=F>xV+AGY$ejUA<58-f)Uj@&_Xnc2Ed;PS!d4p33s9U2- z4j`3T@zcj`TVdN%v*f~`>NW?;RaYmG(+U}!WC&}Us&6>>#G7KD#&yX&o9JqhQrX8} zi$w2k=5PLj@`TTh69T_La7n{R% z6A`4gw%LEz8pL+hm72OHi+Ug>R54569kUUDQx3k^Bh871iL4GsYfNo#R(3f1Bqj)q z5D-B+Ctv+t)hZ3hIJLyXV?D#fX~ZX9->33bI|C@P9nKZFzCB_8hW?fv?}+c4#0-l$P*_8pM)XgGlYJw8vx)Dx8PMgc9Ff!uJCa5J`3{7}vNFDrU|8wV}QMEU(?7FA% z$%c$4%hUczJ}#ZMSnmc}vigf0cZ7Ywu2nFkt@B+l*hbBJz^HunxX|*1B=J%#w;40m+89FGt4c*^E)Rw1?xCB`f4~VDs2| zN}9;m=M`~xw|RN+!ARs0=PW8&obR1$nUn2KV`w8V+_0GaM)qC^Q!$h=#*Ar$D$J3G zQ{!>F#ZzmFFn+4ma6xV6I+l}+kkRSMMFvlo)7fP+mJX>gCdZm^tgvm67XU5xeQgx7 zj}8i2 zAVOZH_QoW1gd%D`Nlz<7ojjBOgJ;wl1k}SLw%CsyV|qp*%k9`@326XGhNrjzi`_BmE`K= z(bSr{i}mv}_^Du_%m%UDqRt=!p-_E<(qH9`zu$uFm)zP^(IPDw zy3hIvX{NM2d0)3U3s^q4ttXz=1;S4sJ$sF9?;x(}mHo(xO51krbv~17KDHu7&ffb9 z?+q{Klg#)XI0mL%O$?T7s#|MUL*&78JTnX$f(< z!Rp9*XuSM6M%`4DVI^w7UI`*I|3lu2aTO$FkJ*&6Y`EzmbZampyzs8+CyZ}F3S7YC zaO7^{cg<&azUFdr3?Dsb$W`^Xq}%2AfGCniO0(aK6aPf&26I|o0cSQ=3n-TqwLDvx zpbuZ?JPe~1e_0Y80ipjvwuoZ0z@oM68}A6o`d-;8jW0DTNaJ9RXJC)h^&I`8S(cFp z;e5W2JMLtsl`|pW+AXqB-O|7D^BzA{_P9*4wfw%Y)%SM z%OxXIXYV+yvs<3GX>(g??B zSCP9-#8TYXgmIPWI*Zke8vlI*<7YEwDa1S=trvGDAS%eR&-luMhqxeY^nk|0t=yy; s1Af{Ie$k%~or@&} + */ +export async function hackerNewsApiRequest(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, qs: IDataObject): Promise { // tslint:disable-line:no-any + const options: OptionsWithUri = { + method, + qs, + uri: `http://hn.algolia.com/api/v1/${endpoint}`, + json: true, + }; + + try { + return await this.helpers.request!(options); + } catch (error) { + + if (error.response && error.response.body && error.response.body.error) { + // Try to return the error prettier + throw new Error(`Hacker News error response [${error.statusCode}]: ${error.response.body.error}`); + } + + throw error; + } +} + + +/** + * Make an API request to HackerNews + * and return all results + * + * @export + * @param {(IHookFunctions | IExecuteFunctions)} this + * @param {string} method + * @param {string} endpoint + * @param {IDataObject} qs + * @returns {Promise} + */ +export async function hackerNewsApiRequestAllItems(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, qs: IDataObject): Promise { // tslint:disable-line:no-any + + qs.hitsPerPage = 100; + + const returnData: IDataObject[] = []; + + let responseData; + let itemsReceived = 0; + + do { + responseData = await hackerNewsApiRequest.call(this, method, endpoint, qs); + returnData.push.apply(returnData, responseData.hits); + + if (returnData !== undefined) { + itemsReceived += returnData.length; + } + + } while ( + responseData.nbHits > itemsReceived + ); + + return returnData; +} diff --git a/packages/nodes-base/nodes/HackerNews/HackerNews.node.ts b/packages/nodes-base/nodes/HackerNews/HackerNews.node.ts new file mode 100644 index 0000000000..b77d5d35bd --- /dev/null +++ b/packages/nodes-base/nodes/HackerNews/HackerNews.node.ts @@ -0,0 +1,384 @@ +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + INodeExecutionData, + INodeType, + INodeTypeDescription, + IDataObject, +} from 'n8n-workflow'; + +import { + hackerNewsApiRequest, + hackerNewsApiRequestAllItems, +} from './GenericFunctions'; + +export class HackerNews implements INodeType { + description: INodeTypeDescription = { + displayName: 'Hacker News', + name: 'hackerNews', + icon: 'file:hackernews.png', + group: ['transform'], + version: 1, + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + description: 'Consume Hacker News API', + defaults: { + name: 'Hacker News', + color: '#ff6600', + }, + inputs: ['main'], + outputs: ['main'], + properties: [ + // ---------------------------------- + // Resources + // ---------------------------------- + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: 'All', + value: 'all', + }, + { + name: 'Article', + value: 'article', + }, + { + name: 'User', + value: 'user', + }, + ], + default: 'article', + description: 'Resource to consume.', + }, + + + // ---------------------------------- + // Operations + // ---------------------------------- + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'all', + ], + }, + }, + options: [ + { + name: 'Get All', + value: 'getAll', + description: 'Get all items', + }, + ], + default: 'getAll', + description: 'Operation to perform.', + }, + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'article', + ], + }, + }, + options: [ + { + name: 'Get', + value: 'get', + description: 'Get a Hacker News article', + }, + ], + default: 'get', + description: 'Operation to perform.', + }, + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'user', + ], + }, + }, + options: [ + { + name: 'Get', + value: 'get', + description: 'Get a Hacker News user', + }, + ], + default: 'get', + description: 'Operation to perform.', + }, + // ---------------------------------- + // Fields + // ---------------------------------- + { + displayName: 'Article ID', + name: 'articleId', + type: 'string', + required: true, + default: '', + description: 'The ID of the Hacker News article to be returned', + displayOptions: { + show: { + resource: [ + 'article', + ], + operation: [ + 'get', + ], + }, + }, + }, + { + displayName: 'Username', + name: 'username', + type: 'string', + required: true, + default: '', + description: 'The Hacker News user to be returned', + displayOptions: { + show: { + resource: [ + 'user', + ], + operation: [ + 'get', + ], + }, + }, + }, + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + default: false, + description: 'Whether to return all results for the query or only up to a limit.', + displayOptions: { + show: { + resource: [ + 'all', + ], + operation: [ + 'getAll', + ], + }, + }, + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + default: 100, + description: 'Limit of Hacker News articles to be returned for the query.', + displayOptions: { + show: { + resource: [ + 'all', + ], + operation: [ + 'getAll', + ], + returnAll: [ + false, + ], + }, + }, + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + resource: [ + 'article', + ], + operation: [ + 'get', + ], + }, + }, + options: [ + { + displayName: 'Include comments', + name: 'includeComments', + type: 'boolean', + default: false, + description: 'Whether to include all the comments in a Hacker News article.', + }, + ], + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + resource: [ + 'all', + ], + operation: [ + 'getAll', + ], + }, + }, + options: [ + { + displayName: 'Keyword', + name: 'keyword', + type: 'string', + default: '', + description: 'The keyword for filtering the results of the query.', + }, + { + displayName: 'Tags', + name: 'tags', + type: 'multiOptions', + options: [ + { + name: 'Story', + value: 'story', + description: 'Returns query results filtered by story tag', + }, + { + name: 'Comment', + value: 'comment', + description: 'Returns query results filtered by comment tag', + }, + { + name: 'Poll', + value: 'poll', + description: 'Returns query results filtered by poll tag', + }, + { + name: 'Show HN', + value: 'show_hn', // snake case per HN tags + description: 'Returns query results filtered by Show HN tag', + }, + { + name: 'Ask HN', + value: 'ask_hn', // snake case per HN tags + description: 'Returns query results filtered by Ask HN tag', + }, + { + name: 'Front Page', + value: 'front_page', // snake case per HN tags + description: 'Returns query results filtered by Front Page tag', + }, + ], + default: '', + description: 'Tags for filtering the results of the query.', + }, + ], + }, + ], + }; + + + async execute(this: IExecuteFunctions): Promise { + const items = this.getInputData(); + const returnData: IDataObject[] = []; + + const resource = this.getNodeParameter('resource', 0) as string; + const operation = this.getNodeParameter('operation', 0) as string; + let returnAll = false; + + for (let i = 0; i < items.length; i++) { + + let qs: IDataObject = {}; + let endpoint = ''; + let includeComments = false; + + if (resource === 'all') { + if (operation === 'getAll') { + + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + const keyword = additionalFields.keyword as string; + const tags = additionalFields.tags as string[]; + + qs = { + query: keyword, + tags: tags ? tags.join() : '', + }; + + returnAll = this.getNodeParameter('returnAll', i) as boolean; + + if (!returnAll) { + qs.hitsPerPage = this.getNodeParameter('limit', i) as number; + } + + endpoint = 'search?'; + + } else { + throw new Error(`The operation '${operation}' is unknown!`); + } + } else if (resource === 'article') { + + if (operation === 'get') { + + endpoint = `items/${this.getNodeParameter('articleId', i)}`; + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + includeComments = additionalFields.includeComments as boolean; + + } else { + throw new Error(`The operation '${operation}' is unknown!`); + } + + } else if (resource === 'user') { + + if (operation === 'get') { + endpoint = `users/${this.getNodeParameter('username', i)}`; + + } else { + throw new Error(`The operation '${operation}' is unknown!`); + } + + } else { + throw new Error(`The resource '${resource}' is unknown!`); + } + + + let responseData; + if (returnAll === true) { + responseData = await hackerNewsApiRequestAllItems.call(this, 'GET', endpoint, qs); + } else { + responseData = await hackerNewsApiRequest.call(this, 'GET', endpoint, qs); + if (resource === 'all' && operation === 'getAll') { + responseData = responseData.hits; + } + } + + if (resource === 'article' && operation === 'get' && !includeComments) { + delete responseData.children; + } + + if (Array.isArray(responseData)) { + returnData.push.apply(returnData, responseData as IDataObject[]); + } else { + returnData.push(responseData as IDataObject); + } + + } + + return [this.helpers.returnJsonArray(returnData)]; + + } +} diff --git a/packages/nodes-base/nodes/HackerNews/hackernews.png b/packages/nodes-base/nodes/HackerNews/hackernews.png new file mode 100644 index 0000000000000000000000000000000000000000..67ba3047ff3d07ec99bd35a2124161d8779cbb0f GIT binary patch literal 1952 zcmcgrX;f3m622?~23dy1u;_@03>aYof-0>ydUrHtJ8JrRQ30LU0tVJ;N`hp zjbuQ=Fied>clIXYmPJ=lSgaVEI}$-L*ooEH787{3! zg&cVpV~#{a;AIicRe@2)aJ(DFt^?Jl(A+dU>j3VCAp~HI84wMEKd!(-%7||WM_$1= z3amZ_XM`wa1H8e4U_nZxvF4DFs?WqZ3V5g%=zR=DgD}<%apXbXUi3{&bctjLR3@TN z?-7n*Wdh=2Pb;rXgd;Y#zT~Fz8)T7 zfJf-#T;;xwP)*{!8uPt9cVQT5y?(8HOKH^CvOGD|uhGUqj_M*#S`B(IaqB5VsbWt8tBB`rT-YVBsVwi$} z;q2r?e{pNC_~4+I=8hY;6wSO&)6CsFmld@I47{pJwu+RbKWO-m$<{Pf@p+w+fw?YF zauLjf&%^yedbyLVrK-J##%Wncd~^&$(x{V9o?PKRZ)`E`uqx`ayD+P@(XvNJdnINW zpRwtOoDVAArp+s6G%~Jfy=Jtoa505La1&7L+tSNBLDE3f& zwM3`q{8X~5%Z1!7lb-du2JxJWLL0aKBWn$!Y=gcl5URPxm-uN0zMi{o^=7%HS%pb` z$E1_J;fhPl$cFR>A0iqb8l8LDXZq4@c>KYP4p~p5KxC!;N;oz?o>O*RaaNbI`_1dS z=O;RD)~lCxtLx9Z8Lq|HC^{9 zGhd$mI)CsXpYcnObwy#u3Ja3l^*gsFcM5fNYUS??`hF*1<@u5euFsV*D-_#n_D5&B zPPXrqkG}n;@DIz?2F+H*0}~DWT*q~y=Q53m1Cg5@Gq0-ejy&U3&WIJnlnqY?NMtvJ zVD4G`bnii4aHmy31^1SnzmWl1J#5#e@6+OzneQCgN;Z6+^5WZACY7(J6m!DK{L7iF zg~RU-t-4N;~d@2^W0Ew)D=QXI8U*FFo+A;*OKywy{=d)eW5C+m`RH^buHRnz7< z{VmOHP0pHCHF@``yEt#1xPvJV^b(?GU6OuP3^LiB9@M-I1I9N;$vTWUEL^^HfjPQCLpp_Pt7HN$|eaf^rL5r*`^NR_c-PGO7iaX6W?@Of*r zyV*3(wrK zi)DVfrTcGd1~sKsnMRI|^AmnI8medBr)p(C6^aWQPPlhI0ycpjS_;*TB#rL_i?*CR z@|(UM{nQ5~hbYqDAHS(`XM3{UI@K(rmi{fOPM%-s-dU?})^u#xySZ;!%;3NFlndIi z>ZAfSuc4DfDB0URSDmzM~RZ_vItLaLJ`Z@la^b^oXmF+%T^AtfbkX&m_ykIvVH7is+u!`pE zN86W2+t)*jHceS@T>2?QXW+N>eG~5;NbVm^b`3YLBL1m9-{luR?HG^8KFY^vVe9}t zn`IOk!aroRox$|lo2X7EKx-F4EMm((=-&v;nrcn8pl-CVqWW0b*i-H7tv67pRC_9w h;ugB+zX-fztPoDr|0ej7TSNo_W4L%amu~Y<`UkDC^S=N9 literal 0 HcmV?d00001 diff --git a/packages/nodes-base/nodes/HttpRequest.node.ts b/packages/nodes-base/nodes/HttpRequest.node.ts index 417d80eeea..08d3a0ac15 100644 --- a/packages/nodes-base/nodes/HttpRequest.node.ts +++ b/packages/nodes-base/nodes/HttpRequest.node.ts @@ -802,7 +802,7 @@ export class HttpRequest implements INodeType { if (oAuth2Api !== undefined) { //@ts-ignore - response = await this.helpers.requestOAuth2.call(this, 'oAuth2Api', requestOptions); + response = await this.helpers.requestOAuth2.call(this, 'oAuth2Api', requestOptions, 'Bearer'); } else { response = await this.helpers.request(requestOptions); } diff --git a/packages/nodes-base/nodes/Hubspot/GenericFunctions.ts b/packages/nodes-base/nodes/Hubspot/GenericFunctions.ts index 969c392cdd..d8d68abfb6 100644 --- a/packages/nodes-base/nodes/Hubspot/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Hubspot/GenericFunctions.ts @@ -15,11 +15,12 @@ import { export async function hubspotApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: any = {}, query: IDataObject = {}, uri?: string): Promise { // tslint:disable-line:no-any - const node = this.getNode(); - const credentialName = Object.keys(node.credentials!)[0]; - const credentials = this.getCredentials(credentialName); + let authenticationMethod = this.getNodeParameter('authentication', 0); + + if (this.getNode().type.includes('Trigger')) { + authenticationMethod = 'developerApi'; + } - query!.hapikey = credentials!.apiKey as string; const options: OptionsWithUri = { method, qs: query, @@ -28,18 +29,42 @@ export async function hubspotApiRequest(this: IHookFunctions | IExecuteFunctions json: true, useQuerystring: true, }; + try { - return await this.helpers.request!(options); + if (authenticationMethod === 'apiKey') { + const credentials = this.getCredentials('hubspotApi'); + + options.qs.hapikey = credentials!.apiKey as string; + + return await this.helpers.request!(options); + } else if (authenticationMethod === 'developerApi') { + const credentials = this.getCredentials('hubspotDeveloperApi'); + + options.qs.hapikey = credentials!.apiKey as string; + + return await this.helpers.request!(options); + } else { + // @ts-ignore + return await this.helpers.requestOAuth2!.call(this, 'hubspotOAuth2Api', options, 'Bearer'); + } } catch (error) { - if (error.response && error.response.body && error.response.body.errors) { - // Try to return the error prettier - let errorMessages = error.response.body.errors; + let errorMessages; - if (errorMessages[0].message) { - // @ts-ignore - errorMessages = errorMessages.map(errorItem => errorItem.message); + if (error.response && error.response.body) { + + if (error.response.body.message) { + + errorMessages = [error.response.body.message]; + + } else if (error.response.body.errors) { + // Try to return the error prettier + errorMessages = error.response.body.errors; + + if (errorMessages[0].message) { + // @ts-ignore + errorMessages = errorMessages.map(errorItem => errorItem.message); + } } - throw new Error(`Hubspot error response [${error.statusCode}]: ${errorMessages.join('|')}`); } diff --git a/packages/nodes-base/nodes/Hubspot/Hubspot.node.ts b/packages/nodes-base/nodes/Hubspot/Hubspot.node.ts index 6c1d7be400..adf01d1ec3 100644 --- a/packages/nodes-base/nodes/Hubspot/Hubspot.node.ts +++ b/packages/nodes-base/nodes/Hubspot/Hubspot.node.ts @@ -73,9 +73,44 @@ export class Hubspot implements INodeType { { name: 'hubspotApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'apiKey', + ], + }, + }, + }, + { + name: 'hubspotOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'API Key', + value: 'apiKey', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'apiKey', + description: 'The method of authentication.', + }, { displayName: 'Resource', name: 'resource', diff --git a/packages/nodes-base/nodes/Hubspot/HubspotTrigger.node.ts b/packages/nodes-base/nodes/Hubspot/HubspotTrigger.node.ts index 25028f88e8..47b2318b36 100644 --- a/packages/nodes-base/nodes/Hubspot/HubspotTrigger.node.ts +++ b/packages/nodes-base/nodes/Hubspot/HubspotTrigger.node.ts @@ -246,7 +246,13 @@ export class HubspotTrigger implements INodeType { }; async webhook(this: IWebhookFunctions): Promise { - const credentials = this.getCredentials('hubspotDeveloperApi'); + + const credentials = this.getCredentials('hubspotDeveloperApi') as IDataObject; + + if (credentials === undefined) { + throw new Error('No credentials found!'); + } + const req = this.getRequestObject(); const bodyData = req.body; const headerData = this.getHeaderData(); @@ -254,12 +260,18 @@ export class HubspotTrigger implements INodeType { if (headerData['x-hubspot-signature'] === undefined) { return {}; } - const hash = `${credentials!.clientSecret}${JSON.stringify(bodyData)}`; - const signature = createHash('sha256').update(hash).digest('hex'); - //@ts-ignore - if (signature !== headerData['x-hubspot-signature']) { - return {}; + + // check signare if client secret is defined + + if (credentials.clientSecret !== '') { + const hash = `${credentials!.clientSecret}${JSON.stringify(bodyData)}`; + const signature = createHash('sha256').update(hash).digest('hex'); + //@ts-ignore + if (signature !== headerData['x-hubspot-signature']) { + return {}; + } } + for (let i = 0; i < bodyData.length; i++) { const subscriptionType = bodyData[i].subscriptionType as string; if (subscriptionType.includes('contact')) { diff --git a/packages/nodes-base/nodes/Jira/IssueDescription.ts b/packages/nodes-base/nodes/Jira/IssueDescription.ts index bdb06179df..d29c9a5350 100644 --- a/packages/nodes-base/nodes/Jira/IssueDescription.ts +++ b/packages/nodes-base/nodes/Jira/IssueDescription.ts @@ -41,12 +41,12 @@ export const issueOperations = [ { name: 'Notify', value: 'notify', - description: 'Creates an email notification for an issue and adds it to the mail queue.', + description: 'Create an email notification for an issue and add it to the mail queue', }, { name: 'Status', value: 'transitions', - description: `Returns either all transitions or a transition that can be performed by the user on an issue, based on the issue's status.`, + description: `Return either all transitions or a transition that can be performed by the user on an issue, based on the issue's status`, }, { name: 'Delete', diff --git a/packages/nodes-base/nodes/Mailchimp/GenericFunctions.ts b/packages/nodes-base/nodes/Mailchimp/GenericFunctions.ts index 91dfcdde85..99c0af67fd 100644 --- a/packages/nodes-base/nodes/Mailchimp/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Mailchimp/GenericFunctions.ts @@ -1,5 +1,5 @@ import { - OptionsWithUri, + OptionsWithUrl, } from 'request'; import { @@ -14,37 +14,53 @@ import { } from 'n8n-workflow'; export async function mailchimpApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, endpoint: string, method: string, body: any = {}, qs: IDataObject = {} ,headers?: object): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('mailchimpApi'); - - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - - const headerWithAuthentication = Object.assign({}, headers, { Authorization: `apikey ${credentials.apiKey}` }); - - if (!(credentials.apiKey as string).includes('-')) { - throw new Error('The API key is not valid!'); - } - - const datacenter = (credentials.apiKey as string).split('-').pop(); + const authenticationMethod = this.getNodeParameter('authentication', 0) as string; const host = 'api.mailchimp.com/3.0'; - const options: OptionsWithUri = { - headers: headerWithAuthentication, + const options: OptionsWithUrl = { + headers: { + 'Accept': 'application/json' + }, method, qs, - uri: `https://${datacenter}.${host}${endpoint}`, + body, + url: ``, json: true, }; - if (Object.keys(body).length !== 0) { - options.body = body; + if (Object.keys(body).length === 0) { + delete options.body; } + try { - return await this.helpers.request!(options); + if (authenticationMethod === 'apiKey') { + const credentials = this.getCredentials('mailchimpApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.headers = Object.assign({}, headers, { Authorization: `apikey ${credentials.apiKey}` }); + + if (!(credentials.apiKey as string).includes('-')) { + throw new Error('The API key is not valid!'); + } + + const datacenter = (credentials.apiKey as string).split('-').pop(); + options.url = `https://${datacenter}.${host}${endpoint}`; + return await this.helpers.request!(options); + } else { + const credentials = this.getCredentials('mailchimpOAuth2Api') as IDataObject; + + const { api_endpoint } = await getMetadata.call(this, credentials.oauthTokenData as IDataObject); + + options.url = `${api_endpoint}/3.0${endpoint}`; + //@ts-ignore + return await this.helpers.requestOAuth2!.call(this, 'mailchimpOAuth2Api', options, 'Bearer'); + } } catch (error) { - if (error.response.body && error.response.body.detail) { + if (error.respose && error.response.body && error.response.body.detail) { throw new Error(`Mailchimp Error response [${error.statusCode}]: ${error.response.body.detail}`); } throw error; @@ -80,3 +96,17 @@ export function validateJSON(json: string | undefined): any { // tslint:disable- } return result; } + +function getMetadata(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, oauthTokenData: IDataObject) { + const credentials = this.getCredentials('mailchimpOAuth2Api') as IDataObject; + const options: OptionsWithUrl = { + headers: { + 'Accept': 'application/json', + 'Authorization': `OAuth ${oauthTokenData.access_token}`, + }, + method: 'GET', + url: credentials.metadataUrl as string, + json: true, + }; + return this.helpers.request!(options); +} diff --git a/packages/nodes-base/nodes/Mailchimp/Mailchimp.node.ts b/packages/nodes-base/nodes/Mailchimp/Mailchimp.node.ts index cb54ac24e9..ff5ee63645 100644 --- a/packages/nodes-base/nodes/Mailchimp/Mailchimp.node.ts +++ b/packages/nodes-base/nodes/Mailchimp/Mailchimp.node.ts @@ -47,6 +47,7 @@ interface ICreateMemberBody { timestamp_opt?: string; tags?: string[]; merge_fields?: IDataObject; + interests?: IDataObject; } export class Mailchimp implements INodeType { @@ -69,14 +70,53 @@ export class Mailchimp implements INodeType { { name: 'mailchimpApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'apiKey', + ], + }, + }, + }, + { + name: 'mailchimpOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'API Key', + value: 'apiKey', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'apiKey', + description: 'Method of authentication.', + }, { displayName: 'Resource', name: 'resource', type: 'options', options: [ + { + name: 'List Group', + value: 'listGroup', + }, { name: 'Member', value: 'member', @@ -159,6 +199,28 @@ export class Mailchimp implements INodeType { default: 'create', description: 'The operation to perform.', }, + { + displayName: 'Operation', + name: 'operation', + type: 'options', + required: true, + displayOptions: { + show: { + resource: [ + 'listGroup', + ], + }, + }, + options: [ + { + name: 'Get All', + value: 'getAll', + description: 'Get all groups', + }, + ], + default: 'getAll', + description: 'The operation to perform.', + }, /* -------------------------------------------------------------------------- */ /* member:create */ /* -------------------------------------------------------------------------- */ @@ -221,27 +283,22 @@ export class Mailchimp implements INodeType { { name: 'Subscribed', value: 'subscribed', - description: '', }, { name: 'Unsubscribed', value: 'unsubscribed', - description: '', }, { name: 'Cleaned', value: 'cleaned', - description: '', }, { name: 'Pending', value: 'pending', - description: '', }, { name: 'Transactional', value: 'transactional', - description: '', }, ], default: '', @@ -252,7 +309,6 @@ export class Mailchimp implements INodeType { name: 'jsonParameters', type: 'boolean', default: false, - description: '', displayOptions: { show: { resource:[ @@ -289,12 +345,10 @@ export class Mailchimp implements INodeType { { name: 'HTML', value: 'html', - description: '', }, { name: 'Text', value: 'text', - description: '', }, ], default: '', @@ -461,7 +515,6 @@ export class Mailchimp implements INodeType { alwaysOpenEditWindow: true, }, default: '', - description: '', displayOptions: { show: { resource:[ @@ -484,7 +537,86 @@ export class Mailchimp implements INodeType { alwaysOpenEditWindow: true, }, default: '', - description: '', + displayOptions: { + show: { + resource:[ + 'member', + ], + operation: [ + 'create', + ], + jsonParameters: [ + true, + ], + }, + }, + }, + { + displayName: 'Interest Groups', + name: 'groupsUi', + placeholder: 'Add Interest Group', + type: 'fixedCollection', + default: {}, + typeOptions: { + multipleValues: true, + }, + displayOptions: { + show: { + resource:[ + 'member' + ], + operation: [ + 'create', + ], + jsonParameters: [ + false, + ], + }, + }, + options: [ + { + name: 'groupsValues', + displayName: 'Group', + typeOptions: { + multipleValueButtonText: 'Add Interest Group', + }, + values: [ + { + displayName: 'Category ID', + name: 'categoryId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getGroupCategories', + loadOptionsDependsOn: [ + 'list', + ], + }, + default: '', + }, + { + displayName: 'Category Field ID', + name: 'categoryFieldId', + type: 'string', + default: '', + }, + { + displayName: 'Value', + name: 'value', + type: 'boolean', + default: false, + }, + ], + }, + ], + }, + { + displayName: 'Interest Groups', + name: 'groupJson', + type: 'json', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', displayOptions: { show: { resource:[ @@ -737,12 +869,10 @@ export class Mailchimp implements INodeType { { name: 'HTML', value: 'html', - description: '', }, { name: 'Text', value: 'text', - description: '', }, ], default: '', @@ -756,27 +886,22 @@ export class Mailchimp implements INodeType { { name: 'Subscribed', value: 'subscribed', - description: '', }, { name: 'Unsubscribed', value: 'unsubscribed', - description: '', }, { name: 'Cleaned', value: 'cleaned', - description: '', }, { name: 'Pending', value: 'pending', - description: '', }, { name: 'Transactional', value: 'transactional', - description: '', }, ], default: '', @@ -839,7 +964,6 @@ export class Mailchimp implements INodeType { name: 'jsonParameters', type: 'boolean', default: false, - description: '', displayOptions: { show: { resource:[ @@ -876,17 +1000,73 @@ export class Mailchimp implements INodeType { { name: 'HTML', value: 'html', - description: '', }, { name: 'Text', value: 'text', - description: '', }, ], default: '', description: 'Type of email this member asked to get', }, + { + displayName: 'Interest Groups', + name: 'groupsUi', + placeholder: 'Add Interest Group', + type: 'fixedCollection', + default: {}, + typeOptions: { + multipleValues: true, + }, + displayOptions: { + show: { + '/resource':[ + 'member' + ], + '/operation':[ + 'update', + ], + '/jsonParameters': [ + false, + ], + }, + }, + options: [ + { + name: 'groupsValues', + displayName: 'Group', + typeOptions: { + multipleValueButtonText: 'Add Interest Group', + }, + values: [ + { + displayName: 'Category ID', + name: 'categoryId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getGroupCategories', + loadOptionsDependsOn: [ + 'list', + ], + }, + default: '', + }, + { + displayName: 'Category Field ID', + name: 'categoryFieldId', + type: 'string', + default: '', + }, + { + displayName: 'Value', + name: 'value', + type: 'boolean', + default: false, + }, + ], + }, + ], + }, { displayName: 'Language', name: 'language', @@ -989,27 +1169,22 @@ export class Mailchimp implements INodeType { { name: 'Subscribed', value: 'subscribed', - description: '', }, { name: 'Unsubscribed', value: 'unsubscribed', - description: '', }, { name: 'Cleaned', value: 'cleaned', - description: '', }, { name: 'Pending', value: 'pending', - description: '', }, { name: 'Transactional', value: 'transactional', - description: '', }, ], default: '', @@ -1084,7 +1259,6 @@ export class Mailchimp implements INodeType { alwaysOpenEditWindow: true, }, default: '', - description: '', displayOptions: { show: { resource:[ @@ -1107,7 +1281,28 @@ export class Mailchimp implements INodeType { alwaysOpenEditWindow: true, }, default: '', - description: '', + displayOptions: { + show: { + resource:[ + 'member', + ], + operation: [ + 'update', + ], + jsonParameters: [ + true, + ], + }, + }, + }, + { + displayName: 'Interest Groups', + name: 'groupJson', + type: 'json', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', displayOptions: { show: { resource:[ @@ -1215,6 +1410,96 @@ export class Mailchimp implements INodeType { }, ], }, +/* -------------------------------------------------------------------------- */ +/* member:getAll */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'List', + name: 'list', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getLists', + }, + displayOptions: { + show: { + resource: [ + 'listGroup', + ], + operation: [ + 'getAll', + ], + }, + }, + default: '', + options: [], + required: true, + description: 'List of lists', + }, + { + displayName: 'Group Category', + name: 'groupCategory', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getGroupCategories', + loadOptionsDependsOn: [ + 'list', + ], + }, + displayOptions: { + show: { + resource: [ + 'listGroup', + ], + operation: [ + 'getAll', + ], + }, + }, + default: '', + options: [], + required: true, + }, + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + displayOptions: { + show: { + resource: [ + 'listGroup', + ], + operation: [ + 'getAll', + ], + }, + }, + default: false, + description: 'If all results should be returned or only up to a given limit.', + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + displayOptions: { + show: { + resource: [ + 'listGroup', + ], + operation: [ + 'getAll', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 1000, + }, + default: 500, + description: 'How many results to return.', + }, ], }; @@ -1226,7 +1511,7 @@ export class Mailchimp implements INodeType { // select them easily async getLists(this: ILoadOptionsFunctions): Promise { const returnData: INodePropertyOptions[] = []; - const { lists } = await mailchimpApiRequest.call(this, '/lists', 'GET'); + const lists = await mailchimpApiRequestAllItems.call(this, '/lists', 'GET', 'lists'); for (const list of lists) { const listName = list.name; const listId = list.id; @@ -1254,6 +1539,23 @@ export class Mailchimp implements INodeType { } return returnData; }, + + // Get all the interest fields to display them to user so that he can + // select them easily + async getGroupCategories(this: ILoadOptionsFunctions): Promise { + const returnData: INodePropertyOptions[] = []; + const listId = this.getCurrentNodeParameter('list'); + const { categories } = await mailchimpApiRequest.call(this, `/lists/${listId}/interest-categories`, 'GET'); + for (const category of categories) { + const categoryName = category.title; + const categoryId = category.id; + returnData.push({ + name: categoryName, + value: categoryId, + }); + } + return returnData; + }, } }; @@ -1267,6 +1569,22 @@ export class Mailchimp implements INodeType { const operation = this.getNodeParameter('operation', 0) as string; for (let i = 0; i < length; i++) { + if (resource === 'listGroup') { + //https://mailchimp.com/developer/reference/lists/interest-categories/#get_/lists/-list_id-/interest-categories/-interest_category_id- + if (operation === 'getAll') { + const listId = this.getNodeParameter('list', i) as string; + const categoryId = this.getNodeParameter('groupCategory', i) as string; + const returnAll = this.getNodeParameter('returnAll', i) as boolean; + + if (returnAll === true) { + responseData = await mailchimpApiRequestAllItems.call(this, `/lists/${listId}/interest-categories/${categoryId}/interests`, 'GET', 'interests', {}, qs); + } else { + qs.count = this.getNodeParameter('limit', i) as number; + responseData = await mailchimpApiRequest.call(this, `/lists/${listId}/interest-categories/${categoryId}/interests`, 'GET', {}, qs); + responseData = responseData.interests; + } + } + } if (resource === 'member') { //https://mailchimp.com/developer/reference/lists/list-members/#post_/lists/-list_id-/members if (operation === 'create') { @@ -1328,15 +1646,29 @@ export class Mailchimp implements INodeType { } body.merge_fields = mergeFields; } + + const groupsValues = (this.getNodeParameter('groupsUi', i) as IDataObject).groupsValues as IDataObject[]; + if (groupsValues) { + const groups = {}; + for (let i = 0; i < groupsValues.length; i++) { + // @ts-ignore + groups[groupsValues[i].categoryFieldId] = groupsValues[i].value; + } + body.interests = groups; + } } else { const locationJson = validateJSON(this.getNodeParameter('locationJson', i) as string); const mergeFieldsJson = validateJSON(this.getNodeParameter('mergeFieldsJson', i) as string); + const groupJson = validateJSON(this.getNodeParameter('groupJson', i) as string); if (locationJson) { body.location = locationJson; } if (mergeFieldsJson) { body.merge_fields = mergeFieldsJson; } + if (groupJson) { + body.interests = groupJson; + } } responseData = await mailchimpApiRequest.call(this, `/lists/${listId}/members`, 'POST', body); } @@ -1469,15 +1801,31 @@ export class Mailchimp implements INodeType { body.merge_fields = mergeFields; } } + if (updateFields.groupsUi) { + const groupsValues = (updateFields.groupsUi as IDataObject).groupsValues as IDataObject[]; + if (groupsValues) { + const groups = {}; + for (let i = 0; i < groupsValues.length; i++) { + // @ts-ignore + groups[groupsValues[i].categoryFieldId] = groupsValues[i].value; + } + body.interests = groups; + } + } } else { const locationJson = validateJSON(this.getNodeParameter('locationJson', i) as string); const mergeFieldsJson = validateJSON(this.getNodeParameter('mergeFieldsJson', i) as string); + const groupJson = validateJSON(this.getNodeParameter('groupJson', i) as string); + if (locationJson) { body.location = locationJson; } if (mergeFieldsJson) { body.merge_fields = mergeFieldsJson; } + if (groupJson) { + body.interests = groupJson; + } } responseData = await mailchimpApiRequest.call(this, `/lists/${listId}/members/${email}`, 'PUT', body); } @@ -1536,6 +1884,7 @@ export class Mailchimp implements INodeType { responseData = { success: true }; } } + if (Array.isArray(responseData)) { returnData.push.apply(returnData, responseData as IDataObject[]); } else { diff --git a/packages/nodes-base/nodes/Mailchimp/MailchimpTrigger.node.ts b/packages/nodes-base/nodes/Mailchimp/MailchimpTrigger.node.ts index 25eac04c20..9fbd80a0f5 100644 --- a/packages/nodes-base/nodes/Mailchimp/MailchimpTrigger.node.ts +++ b/packages/nodes-base/nodes/Mailchimp/MailchimpTrigger.node.ts @@ -33,7 +33,25 @@ export class MailchimpTrigger implements INodeType { { name: 'mailchimpApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'apiKey', + ], + }, + }, + }, + { + name: 'mailchimpOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], webhooks: [ { @@ -50,6 +68,23 @@ export class MailchimpTrigger implements INodeType { } ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'API Key', + value: 'apiKey', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'apiKey', + description: 'Method of authentication.', + }, { displayName: 'List', name: 'list', diff --git a/packages/nodes-base/nodes/Mattermost/Mattermost.node.ts b/packages/nodes-base/nodes/Mattermost/Mattermost.node.ts index 0aa50f3d0e..cc7bc65ee3 100644 --- a/packages/nodes-base/nodes/Mattermost/Mattermost.node.ts +++ b/packages/nodes-base/nodes/Mattermost/Mattermost.node.ts @@ -62,7 +62,7 @@ export class Mattermost implements INodeType { }, ], default: 'message', - description: 'The resource to operate on.', + description: 'The resource to operate on', }, @@ -95,22 +95,22 @@ export class Mattermost implements INodeType { { name: 'Delete', value: 'delete', - description: 'Soft-deletes a channel', + description: 'Soft delete a channel', }, { name: 'Member', value: 'members', - description: 'Get a page of members for a channel.', + description: 'Get a page of members for a channel', }, { name: 'Restore', value: 'restore', - description: 'Restores a soft-deleted channel', + description: 'Restores a soft deleted channel', }, { name: 'Statistics', value: 'statistics', - description: 'Get statistics for a channel.', + description: 'Get statistics for a channel', }, ], default: 'create', @@ -131,7 +131,7 @@ export class Mattermost implements INodeType { { name: 'Delete', value: 'delete', - description: 'Soft deletes a post, by marking the post as deleted in the database.', + description: 'Soft delete a post, by marking the post as deleted in the database', }, { name: 'Post', @@ -140,7 +140,7 @@ export class Mattermost implements INodeType { }, ], default: 'post', - description: 'The operation to perform.', + description: 'The operation to perform', }, @@ -191,7 +191,7 @@ export class Mattermost implements INodeType { }, }, required: true, - description: 'The non-unique UI name for the channel.', + description: 'The non-unique UI name for the channel', }, { displayName: 'Name', @@ -210,7 +210,7 @@ export class Mattermost implements INodeType { }, }, required: true, - description: 'The unique handle for the channel, will be present in the channel URL.', + description: 'The unique handle for the channel, will be present in the channel URL', }, { displayName: 'Type', @@ -264,7 +264,7 @@ export class Mattermost implements INodeType { ], }, }, - description: 'The ID of the channel to soft-delete.', + description: 'The ID of the channel to soft delete', }, // ---------------------------------- diff --git a/packages/nodes-base/nodes/Mautic/ContactDescription.ts b/packages/nodes-base/nodes/Mautic/ContactDescription.ts index b9eb9b0f42..1ea81acbc8 100644 --- a/packages/nodes-base/nodes/Mautic/ContactDescription.ts +++ b/packages/nodes-base/nodes/Mautic/ContactDescription.ts @@ -226,6 +226,94 @@ export const contactFields = [ }, }, options: [ + { + displayName: 'Address', + name: 'addressUi', + placeholder: 'Address', + type: 'fixedCollection', + typeOptions: { + multipleValues: false, + }, + default: {}, + options: [ + { + name: 'addressValues', + displayName: 'Address', + values: [ + { + displayName: 'Address Line 1', + name: 'address1', + type: 'string', + default: '', + }, + { + displayName: 'Address Line 2', + name: 'address2', + type: 'string', + default: '', + }, + { + displayName: 'City', + name: 'city', + type: 'string', + default: '', + }, + { + displayName: 'State', + name: 'state', + type: 'string', + default: '', + }, + { + displayName: 'Country', + name: 'country', + type: 'string', + default: '', + }, + { + displayName: 'Zip Code', + name: 'zipCode', + type: 'string', + default: '', + }, + ], + }, + ], + }, + { + displayName: 'B2B or B2C', + name: 'b2bOrb2c', + type: 'options', + options: [ + { + name: 'B2B', + value: 'B2B', + }, + { + name: 'B2C', + value: 'B2C', + }, + ], + default: '', + }, + { + displayName: 'CRM ID', + name: 'crmId', + type: 'string', + default: '', + }, + { + displayName: 'Fax', + name: 'fax', + type: 'string', + default: '', + }, + { + displayName: 'Has Purchased', + name: 'hasPurchased', + type: 'boolean', + default: false, + }, { displayName: 'IP Address', name: 'ipAddress', @@ -240,6 +328,12 @@ export const contactFields = [ default: '', description: 'Date/time in UTC;', }, + { + displayName: 'Mobile', + name: 'mobile', + type: 'string', + default: '', + }, { displayName: 'Owner ID', name: 'ownerId', @@ -247,6 +341,112 @@ export const contactFields = [ default: '', description: 'ID of a Mautic user to assign this contact to', }, + { + displayName: 'Phone', + name: 'phone', + type: 'string', + default: '', + }, + { + displayName: 'Prospect or Customer', + name: 'prospectOrCustomer', + type: 'options', + options: [ + { + name: 'Prospect', + value: 'Prospect', + }, + { + name: 'Customer', + value: 'Customer', + }, + ], + default: '', + }, + { + displayName: 'Sandbox', + name: 'sandbox', + type: 'boolean', + default: false, + }, + { + displayName: 'Stage', + name: 'stage', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getStages', + }, + default: '', + }, + { + displayName: 'Tags', + name: 'tags', + type: 'multiOptions', + typeOptions: { + loadOptionsMethod: 'getTags', + }, + default: '', + }, + { + displayName: 'Social Media', + name: 'socialMediaUi', + placeholder: 'Social Media', + type: 'fixedCollection', + typeOptions: { + multipleValues: false, + }, + default: {}, + options: [ + { + name: 'socialMediaValues', + displayName: 'Social Media', + values: [ + { + displayName: 'Facebook', + name: 'facebook', + type: 'string', + default: '', + }, + { + displayName: 'Foursquare', + name: 'foursquare', + type: 'string', + default: '', + }, + { + displayName: 'Instagram', + name: 'instagram', + type: 'string', + default: '', + }, + { + displayName: 'LinkedIn', + name: 'linkedIn', + type: 'string', + default: '', + }, + { + displayName: 'Skype', + name: 'skype', + type: 'string', + default: '', + }, + { + displayName: 'Twitter', + name: 'twitter', + type: 'string', + default: '', + }, + ], + }, + ], + }, + { + displayName: 'Website', + name: 'website', + type: 'string', + default: '', + }, ], }, @@ -318,6 +518,103 @@ export const contactFields = [ default: '', description: 'Contact parameters', }, + { + displayName: 'Address', + name: 'addressUi', + placeholder: 'Address', + type: 'fixedCollection', + typeOptions: { + multipleValues: false, + }, + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: {}, + options: [ + { + name: 'addressValues', + displayName: 'Address', + values: [ + { + displayName: 'Address Line 1', + name: 'address1', + type: 'string', + default: '', + }, + { + displayName: 'Address Line 2', + name: 'address2', + type: 'string', + default: '', + }, + { + displayName: 'City', + name: 'city', + type: 'string', + default: '', + }, + { + displayName: 'State', + name: 'state', + type: 'string', + default: '', + }, + { + displayName: 'Country', + name: 'country', + type: 'string', + default: '', + }, + { + displayName: 'Zip Code', + name: 'zipCode', + type: 'string', + default: '', + }, + ], + }, + ], + }, + { + displayName: 'B2B or B2C', + name: 'b2bOrb2c', + type: 'options', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + options: [ + { + name: 'B2B', + value: 'B2B', + }, + { + name: 'B2C', + value: 'B2C', + }, + ], + default: '', + }, + { + displayName: 'CRM ID', + name: 'crmId', + type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + }, { displayName: 'Email', name: 'email', @@ -332,6 +629,19 @@ export const contactFields = [ default: '', description: 'Email address of the contact.', }, + { + displayName: 'Fax', + name: 'fax', + type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + }, { displayName: 'First Name', name: 'firstName', @@ -346,6 +656,47 @@ export const contactFields = [ default: '', description: 'First Name', }, + { + displayName: 'Has Purchased', + name: 'hasPurchased', + type: 'boolean', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: false, + }, + { + displayName: 'IP Address', + name: 'ipAddress', + type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + description: 'IP address to associate with the contact', + }, + { + displayName: 'Last Active', + name: 'lastActive', + type: 'dateTime', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + description: 'Date/time in UTC;', + }, { displayName: 'Last Name', name: 'lastName', @@ -360,6 +711,60 @@ export const contactFields = [ default: '', description: 'LastName', }, + { + displayName: 'Mobile', + name: 'mobile', + type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + }, + { + displayName: 'Owner ID', + name: 'ownerId', + type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + description: 'ID of a Mautic user to assign this contact to', + }, + { + displayName: 'Phone', + name: 'phone', + type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + }, + { + displayName: 'Position', + name: 'position', + type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + description: 'Position', + }, { displayName: 'Primary Company', name: 'company', @@ -378,9 +783,9 @@ export const contactFields = [ description: 'Primary company', }, { - displayName: 'Position', - name: 'position', - type: 'string', + displayName: 'Prospect or Customer', + name: 'prospectOrCustomer', + type: 'options', displayOptions: { show: { '/jsonParameters': [ @@ -388,8 +793,62 @@ export const contactFields = [ ], }, }, + options: [ + { + name: 'Prospect', + value: 'Prospect', + }, + { + name: 'Customer', + value: 'Customer', + }, + ], + default: '', + }, + { + displayName: 'Sandbox', + name: 'sandbox', + type: 'boolean', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: false, + }, + { + displayName: 'Stage', + name: 'stage', + type: 'options', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + typeOptions: { + loadOptionsMethod: 'getStages', + }, + default: '', + }, + { + displayName: 'Tags', + name: 'tags', + type: 'multiOptions', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + typeOptions: { + loadOptionsMethod: 'getTags', + }, default: '', - description: 'Position', }, { displayName: 'Title', @@ -405,27 +864,94 @@ export const contactFields = [ default: '', description: 'Title', }, + { + displayName: 'Social Media', + name: 'socialMediaUi', + placeholder: 'Social Media', + type: 'fixedCollection', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + typeOptions: { + multipleValues: false, + }, + default: {}, + options: [ + { + name: 'socialMediaValues', + displayName: 'Social Media', + values: [ + { + displayName: 'Facebook', + name: 'facebook', + type: 'string', + default: '', + }, + { + displayName: 'Foursquare', + name: 'foursquare', + type: 'string', + default: '', + }, + { + displayName: 'Instagram', + name: 'instagram', + type: 'string', + default: '', + }, + { + displayName: 'LinkedIn', + name: 'linkedIn', + type: 'string', + default: '', + }, + { + displayName: 'Skype', + name: 'skype', + type: 'string', + default: '', + }, + { + displayName: 'Twitter', + name: 'twitter', + type: 'string', + default: '', + }, + ], + }, + ], + }, + { + displayName: 'Website', + name: 'website', + type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, + default: '', + }, { displayName: 'IP Address', name: 'ipAddress', type: 'string', + displayOptions: { + show: { + '/jsonParameters': [ + false, + ], + }, + }, default: '', description: 'IP address to associate with the contact', }, - { - displayName: 'Last Active', - name: 'lastActive', - type: 'dateTime', - default: '', - description: 'Date/time in UTC;', - }, - { - displayName: 'Owner ID', - name: 'ownerId', - type: 'string', - default: '', - description: 'ID of a Mautic user to assign this contact to', - }, ], }, diff --git a/packages/nodes-base/nodes/Mautic/GenericFunctions.ts b/packages/nodes-base/nodes/Mautic/GenericFunctions.ts index 6b179db7fd..9861690254 100644 --- a/packages/nodes-base/nodes/Mautic/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Mautic/GenericFunctions.ts @@ -10,7 +10,6 @@ import { import { IDataObject, } from 'n8n-workflow'; -import { errors } from 'imap-simple'; interface OMauticErrorResponse { errors: Array<{ @@ -19,7 +18,7 @@ interface OMauticErrorResponse { }>; } -function getErrors(error: OMauticErrorResponse): string { +export function getErrors(error: OMauticErrorResponse): string { const returnErrors: string[] = []; for (const errorItem of error.errors) { @@ -31,23 +30,40 @@ function getErrors(error: OMauticErrorResponse): string { export async function mauticApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: any = {}, query?: IDataObject, uri?: string): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('mauticApi'); - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - const base64Key = Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64'); + const authenticationMethod = this.getNodeParameter('authentication', 0, 'credentials') as string; + const options: OptionsWithUri = { - headers: { Authorization: `Basic ${base64Key}` }, + headers: {}, method, qs: query, - uri: uri || `${credentials.url}/api${endpoint}`, + uri: uri || `/api${endpoint}`, body, json: true }; - try { - const returnData = await this.helpers.request!(options); - if (returnData.error) { + try { + + let returnData; + + if (authenticationMethod === 'credentials') { + const credentials = this.getCredentials('mauticApi') as IDataObject; + + const base64Key = Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64'); + + options.headers!.Authorization = `Basic ${base64Key}`; + + options.uri = `${credentials.url}${options.uri}`; + //@ts-ignore + returnData = await this.helpers.request(options); + } else { + const credentials = this.getCredentials('mauticOAuth2Api') as IDataObject; + + options.uri = `${credentials.url}${options.uri}`; + //@ts-ignore + returnData = await this.helpers.requestOAuth2.call(this, 'mauticOAuth2Api', options); + } + + if (returnData.errors) { // They seem to to sometimes return 200 status but still error. throw new Error(getErrors(returnData)); } diff --git a/packages/nodes-base/nodes/Mautic/Mautic.node.ts b/packages/nodes-base/nodes/Mautic/Mautic.node.ts index 50abcda83e..7bdafe7605 100644 --- a/packages/nodes-base/nodes/Mautic/Mautic.node.ts +++ b/packages/nodes-base/nodes/Mautic/Mautic.node.ts @@ -1,5 +1,3 @@ -import { snakeCase } from 'change-case'; - import { IExecuteFunctions, } from 'n8n-core'; @@ -15,12 +13,18 @@ import { mauticApiRequest, mauticApiRequestAllItems, validateJSON, + getErrors, } from './GenericFunctions'; + import { contactFields, contactOperations, } from './ContactDescription'; +import { + snakeCase, + } from 'change-case'; + export class Mautic implements INodeType { description: INodeTypeDescription = { displayName: 'Mautic', @@ -40,9 +44,43 @@ export class Mautic implements INodeType { { name: 'mauticApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'credentials', + ], + }, + }, + }, + { + name: 'mauticOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Credentials', + value: 'credentials', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'credentials', + }, { displayName: 'Resource', name: 'resource', @@ -77,6 +115,32 @@ export class Mautic implements INodeType { } return returnData; }, + // Get all the available tags to display them to user so that he can + // select them easily + async getTags(this: ILoadOptionsFunctions): Promise { + const returnData: INodePropertyOptions[] = []; + const tags = await mauticApiRequestAllItems.call(this, 'tags', 'GET', '/tags'); + for (const tag of tags) { + returnData.push({ + name: tag.tag, + value: tag.tag, + }); + } + return returnData; + }, + // Get all the available stages to display them to user so that he can + // select them easily + async getStages(this: ILoadOptionsFunctions): Promise { + const returnData: INodePropertyOptions[] = []; + const stages = await mauticApiRequestAllItems.call(this, 'stages', 'GET', '/stages'); + for (const stage of stages) { + returnData.push({ + name: stage.name, + value: stage.id, + }); + } + return returnData; + }, }, }; @@ -124,6 +188,62 @@ export class Mautic implements INodeType { if (additionalFields.ownerId) { body.ownerId = additionalFields.ownerId as string; } + if (additionalFields.addressUi) { + const addressValues = (additionalFields.addressUi as IDataObject).addressValues as IDataObject; + if (addressValues) { + body.address1 = addressValues.address1 as string; + body.address2 = addressValues.address2 as string; + body.city = addressValues.city as string; + body.state = addressValues.state as string; + body.country = addressValues.country as string; + body.zipcode = addressValues.zipCode as string; + } + } + if (additionalFields.socialMediaUi) { + const socialMediaValues = (additionalFields.socialMediaUi as IDataObject).socialMediaValues as IDataObject; + if (socialMediaValues) { + body.facebook = socialMediaValues.facebook as string; + body.foursquare = socialMediaValues.foursquare as string; + body.instagram = socialMediaValues.instagram as string; + body.linkedin = socialMediaValues.linkedIn as string; + body.skype = socialMediaValues.skype as string; + body.twitter = socialMediaValues.twitter as string; + } + } + if (additionalFields.b2bOrb2c) { + body.b2b_or_b2c = additionalFields.b2bOrb2c as string; + } + if (additionalFields.crmId) { + body.crm_id = additionalFields.crmId as string; + } + if (additionalFields.fax) { + body.fax = additionalFields.fax as string; + } + if (additionalFields.hasPurchased) { + body.haspurchased = additionalFields.hasPurchased as boolean; + } + if (additionalFields.mobile) { + body.mobile = additionalFields.mobile as string; + } + if (additionalFields.phone) { + body.phone = additionalFields.phone as string; + } + if (additionalFields.prospectOrCustomer) { + body.prospect_or_customer = additionalFields.prospectOrCustomer as string; + } + if (additionalFields.sandbox) { + body.sandbox = additionalFields.sandbox as boolean; + } + if (additionalFields.stage) { + body.stage = additionalFields.stage as string; + } + if (additionalFields.tags) { + body.tags = additionalFields.tags as string; + } + if (additionalFields.website) { + body.website = additionalFields.website as string; + } + responseData = await mauticApiRequest.call(this, 'POST', '/contacts/new', body); responseData = responseData.contact; } @@ -167,6 +287,61 @@ export class Mautic implements INodeType { if (updateFields.ownerId) { body.ownerId = updateFields.ownerId as string; } + if (updateFields.addressUi) { + const addressValues = (updateFields.addressUi as IDataObject).addressValues as IDataObject; + if (addressValues) { + body.address1 = addressValues.address1 as string; + body.address2 = addressValues.address2 as string; + body.city = addressValues.city as string; + body.state = addressValues.state as string; + body.country = addressValues.country as string; + body.zipcode = addressValues.zipCode as string; + } + } + if (updateFields.socialMediaUi) { + const socialMediaValues = (updateFields.socialMediaUi as IDataObject).socialMediaValues as IDataObject; + if (socialMediaValues) { + body.facebook = socialMediaValues.facebook as string; + body.foursquare = socialMediaValues.foursquare as string; + body.instagram = socialMediaValues.instagram as string; + body.linkedin = socialMediaValues.linkedIn as string; + body.skype = socialMediaValues.skype as string; + body.twitter = socialMediaValues.twitter as string; + } + } + if (updateFields.b2bOrb2c) { + body.b2b_or_b2c = updateFields.b2bOrb2c as string; + } + if (updateFields.crmId) { + body.crm_id = updateFields.crmId as string; + } + if (updateFields.fax) { + body.fax = updateFields.fax as string; + } + if (updateFields.hasPurchased) { + body.haspurchased = updateFields.hasPurchased as boolean; + } + if (updateFields.mobile) { + body.mobile = updateFields.mobile as string; + } + if (updateFields.phone) { + body.phone = updateFields.phone as string; + } + if (updateFields.prospectOrCustomer) { + body.prospect_or_customer = updateFields.prospectOrCustomer as string; + } + if (updateFields.sandbox) { + body.sandbox = updateFields.sandbox as boolean; + } + if (updateFields.stage) { + body.stage = updateFields.stage as string; + } + if (updateFields.tags) { + body.tags = updateFields.tags as string; + } + if (updateFields.website) { + body.website = updateFields.website as string; + } responseData = await mauticApiRequest.call(this, 'PATCH', `/contacts/${contactId}/edit`, body); responseData = responseData.contact; } @@ -193,6 +368,9 @@ export class Mautic implements INodeType { qs.limit = this.getNodeParameter('limit', i) as number; qs.start = 0; responseData = await mauticApiRequest.call(this, 'GET', '/contacts', {}, qs); + if (responseData.errors) { + throw new Error(getErrors(responseData)); + } responseData = responseData.contacts; responseData = Object.values(responseData); } diff --git a/packages/nodes-base/nodes/Mautic/MauticTrigger.node.ts b/packages/nodes-base/nodes/Mautic/MauticTrigger.node.ts index a3ba20f28a..4f844e1188 100644 --- a/packages/nodes-base/nodes/Mautic/MauticTrigger.node.ts +++ b/packages/nodes-base/nodes/Mautic/MauticTrigger.node.ts @@ -38,7 +38,25 @@ export class MauticTrigger implements INodeType { { name: 'mauticApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'credentials', + ], + }, + }, + }, + { + name: 'mauticOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], webhooks: [ { @@ -49,6 +67,22 @@ export class MauticTrigger implements INodeType { }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Credentials', + value: 'credentials', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'credentials', + }, { displayName: 'Events', name: 'events', diff --git a/packages/nodes-base/nodes/MessageBird/GenericFunctions.ts b/packages/nodes-base/nodes/MessageBird/GenericFunctions.ts new file mode 100644 index 0000000000..5a7eda2210 --- /dev/null +++ b/packages/nodes-base/nodes/MessageBird/GenericFunctions.ts @@ -0,0 +1,64 @@ +import { + OptionsWithUri, +} from 'request'; + +import { + IExecuteFunctions, + IHookFunctions, +} from 'n8n-core'; + +import { + IDataObject, +} from 'n8n-workflow'; + +/** + * Make an API request to Message Bird + * + * @param {IHookFunctions} this + * @param {string} method + * @param {string} url + * @param {object} body + * @returns {Promise} + */ +export async function messageBirdApiRequest( + this: IHookFunctions | IExecuteFunctions, + method: string, + resource: string, + body: IDataObject, + query: IDataObject = {}, +): Promise { // tslint:disable-line:no-any + const credentials = this.getCredentials('messageBirdApi'); + if (credentials === undefined) { + throw new Error('No credentials returned!'); + } + + const options: OptionsWithUri = { + headers: { + Accept: 'application/json', + Authorization: `AccessKey ${credentials.accessKey}`, + }, + method, + qs: query, + body, + uri: `https://rest.messagebird.com${resource}`, + json: true, + }; + + try { + return await this.helpers.request(options); + } catch (error) { + if (error.statusCode === 401) { + throw new Error('The Message Bird credentials are not valid!'); + } + + if (error.response && error.response.body && error.response.body.errors) { + // Try to return the error prettier + const errorMessage = error.response.body.errors.map((e: IDataObject) => e.description); + + throw new Error(`MessageBird Error response [${error.statusCode}]: ${errorMessage.join('|')}`); + } + + // If that data does not exist for some reason return the actual error + throw error; + } +} diff --git a/packages/nodes-base/nodes/MessageBird/MessageBird.node.ts b/packages/nodes-base/nodes/MessageBird/MessageBird.node.ts new file mode 100644 index 0000000000..46f70c85d6 --- /dev/null +++ b/packages/nodes-base/nodes/MessageBird/MessageBird.node.ts @@ -0,0 +1,364 @@ +import { + IExecuteFunctions, + } from 'n8n-core'; + +import { + IDataObject, + INodeTypeDescription, + INodeExecutionData, + INodeType, +} from 'n8n-workflow'; + +import { + messageBirdApiRequest, +} from './GenericFunctions'; + +export class MessageBird implements INodeType { + description: INodeTypeDescription = { + displayName: 'MessageBird', + name: 'messageBird', + icon: 'file:messagebird.png', + group: ['output'], + version: 1, + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + description: 'Sending SMS', + defaults: { + name: 'MessageBird', + color: '#2481d7', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'messageBirdApi', + required: true, + }, + ], + properties: [ + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: 'SMS', + value: 'sms', + }, + ], + default: 'sms', + description: 'The resource to operate on.', + }, + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'sms', + ], + }, + }, + options: [ + { + name: 'Send', + value: 'send', + description: 'Send text messages (SMS)', + }, + ], + default: 'send', + description: 'The operation to perform.', + }, + + // ---------------------------------- + // sms:send + // ---------------------------------- + { + displayName: 'From', + name: 'originator', + type: 'string', + default: '', + placeholder: '14155238886', + required: true, + displayOptions: { + show: { + operation: [ + 'send', + ], + resource: [ + 'sms', + ], + }, + }, + description: 'The number from which to send the message.', + }, + { + displayName: 'To', + name: 'recipients', + type: 'string', + default: '', + placeholder: '14155238886/+14155238886', + required: true, + displayOptions: { + show: { + operation: [ + 'send', + ], + resource: [ + 'sms', + ], + }, + }, + description: 'All recipients separated by commas.', + }, + { + displayName: 'Message', + name: 'message', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'send', + ], + resource: [ + 'sms', + ], + }, + }, + description: 'The message to be send.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Fields', + default: {}, + options: [ + { + displayName: 'Created Date-time', + name: 'createdDatetime', + type: 'dateTime', + default: '', + description: 'The date and time of the creation of the message in RFC3339 format (Y-m-dTH:i:sP).', + }, + { + displayName: 'Datacoding', + name: 'datacoding', + type: 'options', + options: [ + { + name: 'Auto', + value: 'auto', + }, + { + name: 'Plain', + value: 'plain', + }, + { + name: 'Unicode', + value: 'unicode', + }, + ], + default: '', + description: 'Using unicode will limit the maximum number of characters to 70 instead of 160.', + }, + { + displayName: 'Gateway', + name: 'gateway', + type: 'number', + default: '', + description: 'The SMS route that is used to send the message.', + }, + { + displayName: 'Group IDs', + name: 'groupIds', + placeholder: '1,2', + type: 'string', + default: '', + description: 'Group IDs separated by commas, If provided recipients can be omitted.', + }, + { + displayName: 'Message Type', + name: 'mclass', + type: 'options', + placeholder: 'Permissible values from 0-3', + options: [ + { + name: 'Flash', + value: 1, + }, + { + name: 'Normal', + value: 0, + }, + ], + default: 1, + description: 'Indicated the message type. 1 is a normal message, 0 is a flash message.', + }, + { + displayName: 'Reference', + name: 'reference', + type: 'string', + default: '', + description: 'A client reference.', + }, + { + displayName: 'Report Url', + name: 'reportUrl', + type: 'string', + default: '', + description: 'The status report URL to be used on a per-message basis.
Reference is required for a status report webhook to be sent.', + }, + { + displayName: 'Scheduled Date-time', + name: 'scheduledDatetime', + type: 'dateTime', + default: '', + description: 'The scheduled date and time of the message in RFC3339 format (Y-m-dTH:i:sP).', + }, + { + displayName: 'Type', + name: 'type', + type: 'options', + options: [ + { + name: 'Binary', + value: 'binary', + }, + { + name: 'Flash', + value: 'flash', + }, + { + name: 'SMS', + value: 'sms', + }, + ], + default: '', + description: 'The type of message.
Values can be: sms, binary, or flash.', + }, + { + displayName: 'Type Details', + name: 'typeDetails', + type: 'string', + default: '', + description: 'A hash with extra information.
Is only used when a binary message is sent.', + }, + { + displayName: 'Validity', + name: 'validity', + type: 'number', + default: 1, + typeOptions: { + minValue: 1, + }, + description: 'The amount of seconds that the message is valid.', + }, + ], + }, + ], + }; + + async execute(this: IExecuteFunctions): Promise { + const items = this.getInputData(); + const returnData: IDataObject[] = []; + + let operation: string; + let resource: string; + + // For POST + let bodyRequest: IDataObject; + // For Query string + let qs: IDataObject; + + let requestMethod; + + for (let i = 0; i < items.length; i++) { + qs = {}; + + resource = this.getNodeParameter('resource', i) as string; + operation = this.getNodeParameter('operation', i) as string; + + if (resource === 'sms') { + //https://developers.messagebird.com/api/sms-messaging/#sms-api + if (operation === 'send') { + // ---------------------------------- + // sms:send + // ---------------------------------- + + requestMethod = 'POST'; + const originator = this.getNodeParameter('originator', i) as string; + const body = this.getNodeParameter('message', i) as string; + + bodyRequest = { + recipients: [], + originator, + body + }; + const additionalFields = this.getNodeParameter( + 'additionalFields', + i + ) as IDataObject; + + if (additionalFields.groupIds) { + bodyRequest.groupIds = additionalFields.groupIds as string; + } + if (additionalFields.type) { + bodyRequest.type = additionalFields.type as string; + } + if (additionalFields.reference) { + bodyRequest.reference = additionalFields.reference as string; + } + if (additionalFields.reportUrl) { + bodyRequest.reportUrl = additionalFields.reportUrl as string; + } + if (additionalFields.validity) { + bodyRequest.validity = additionalFields.reportUrl as number; + } + if (additionalFields.gateway) { + bodyRequest.gateway = additionalFields.gateway as string; + } + if (additionalFields.typeDetails) { + bodyRequest.typeDetails = additionalFields.typeDetails as string; + } + if (additionalFields.datacoding) { + bodyRequest.datacoding = additionalFields.datacoding as string; + } + if (additionalFields.mclass) { + bodyRequest.mclass = additionalFields.mclass as number; + } + if (additionalFields.scheduledDatetime) { + bodyRequest.scheduledDatetime = additionalFields.scheduledDatetime as string; + } + if (additionalFields.createdDatetime) { + bodyRequest.createdDatetime = additionalFields.createdDatetime as string; + } + + const receivers = this.getNodeParameter('recipients', i) as string; + + bodyRequest.recipients = receivers.split(',').map(item => { + return parseInt(item, 10); + }); + } else { + throw new Error(`The operation "${operation}" is not known!`); + } + } else { + throw new Error(`The resource "${resource}" is not known!`); + } + + const responseData = await messageBirdApiRequest.call( + this, + requestMethod, + '/messages', + bodyRequest, + qs + ); + + returnData.push(responseData as IDataObject); + } + + return [this.helpers.returnJsonArray(returnData)]; + } +} diff --git a/packages/nodes-base/nodes/MessageBird/messagebird.png b/packages/nodes-base/nodes/MessageBird/messagebird.png new file mode 100644 index 0000000000000000000000000000000000000000..006b762950d6604ab0e58a3ebf90e984f04907f6 GIT binary patch literal 1305 zcmeAS@N?(olHy`uVBq!ia0vp^HXzKw1|+Ti+$;i8Ea{HEjtmSN`?>!lvI6-E$sR$z z3=CCj3=9n|3=F@3LJcn%7)lKo7+xg+bI6B3hk`{3u+q^6EQYb$Fqb0`Z}TW&b_ z-}^zkqPOjSoVabPclqS!dv2C(uD$;xw(Q>QzqM&~pR4cBRJYJmeeF@1E!)8ShQay( z-v%)C+MTap-D$>irE9Gdwtt&E^F~OQ4%<4-R^B*+t+V@d4m{vFV|PYphuMeSz6BZV zI!Dg3d@^9G{r=#y+z-Pktq1y_Hm^UBV~`uYa2pR_*`cd~Mn;z-!?$b;KXCBv%-8YN zZM*-o^>ZglY3epIiN9If%Im6qd;Thh?b;h-R8F#9dM1*|JbxG0@^vr%7oJwj;9Zg@ zJ=2?KNy{stibCNK(Zg#!e`vA<3vRg_D_!w_@`WeuGu)4ockQ1YS7^3>3%e1zH0^7I z`J9~Q>DwI^+cU0F+$*a1@Y#~e8}|}3{)^sWvdd_Tz543=^FJT1#;wq465jjaEyLxzEI2Nx`2e|Nhi>6UA@9h-Qwmce%K z$TJ~@9u6EC>zZ_zuKfM#C;PrVJa+st)sCVo-LHOB|I&Z6c`NIl71yLJZt=9fyRt88 zQP9q1B3fMG+s?Z_tk7>sd+_*qV*K4x)yEDMq$L!7xh52G;Cu6h2jMTH7A2Y{2T9Ig z_CI`^H>*G{^uFy5vpo50b_Q8(cE4TMzWhGxiuU2hoBq{!Hm*A0wB-A<=kE?MJMY%G zeSqPj#hiT$eGa~3*dr1!@5Xb_zQ9FYceZ_ck`?>P^Zxe;2|b=!9YLNFf9>Xc*sJ8f z_9avJr(J!EeEc!EdYbA>n4Lk*jUt-nsCK2}_KiCcQ_ zwcR%5$KNb$hpVD{F0v+cN64?YdVdmE zSm~eo!`Kkg_J1y0^#<<37d!Yie@;7W%&oI3OqSP5I||Jl(eT z+b+pn{PRl=S4cd59`&qYY1LJkJfHo_n-)#9toW}~(t74_)5=9#ZKisE*}c<{(S7#< zW9F4PA`u)F+3I_OR)7CfAz_v8_&fDS?UXk*9r2S|WThW|t$Nz_NUSDWXWctqztxw| zZ{EJ}{kmI4X}^lQ1+ybxwlZPW)%M51ZrULboFyt I=akR{0A)r^>i_@% literal 0 HcmV?d00001 diff --git a/packages/nodes-base/nodes/Microsoft/Sql/GenericFunctions.ts b/packages/nodes-base/nodes/Microsoft/Sql/GenericFunctions.ts new file mode 100644 index 0000000000..601d3b5393 --- /dev/null +++ b/packages/nodes-base/nodes/Microsoft/Sql/GenericFunctions.ts @@ -0,0 +1,144 @@ +import { IDataObject, INodeExecutionData } from 'n8n-workflow'; +import { ITables } from './TableInterface'; + +/** + * Returns a copy of the item which only contains the json data and + * of that only the defined properties + * + * @param {INodeExecutionData} item The item to copy + * @param {string[]} properties The properties it should include + * @returns + */ +export function copyInputItem( + item: INodeExecutionData, + properties: string[], +): IDataObject { + // Prepare the data to insert and copy it to be returned + const newItem: IDataObject = {}; + for (const property of properties) { + if (item.json[property] === undefined) { + newItem[property] = null; + } else { + newItem[property] = JSON.parse(JSON.stringify(item.json[property])); + } + } + return newItem; +} + +/** + * Creates an ITables with the columns for the operations + * + * @param {INodeExecutionData[]} items The items to extract the tables/columns for + * @param {function} getNodeParam getter for the Node's Parameters + * @returns {ITables} {tableName: {colNames: [items]}}; + */ +export function createTableStruct( + getNodeParam: Function, + items: INodeExecutionData[], + additionalProperties: string[] = [], + keyName?: string, +): ITables { + return items.reduce((tables, item, index) => { + const table = getNodeParam('table', index) as string; + const columnString = getNodeParam('columns', index) as string; + const columns = columnString.split(',').map(column => column.trim()); + const itemCopy = copyInputItem(item, columns.concat(additionalProperties)); + const keyParam = keyName + ? (getNodeParam(keyName, index) as string) + : undefined; + if (tables[table] === undefined) { + tables[table] = {}; + } + if (tables[table][columnString] === undefined) { + tables[table][columnString] = []; + } + if (keyName) { + itemCopy[keyName] = keyParam; + } + tables[table][columnString].push(itemCopy); + return tables; + }, {} as ITables); +} + +/** + * Executes a queue of queries on given ITables. + * + * @param {ITables} tables The ITables to be processed. + * @param {function} buildQueryQueue function that builds the queue of promises + * @returns {Promise} + */ +export function executeQueryQueue( + tables: ITables, + buildQueryQueue: Function, +): Promise { // tslint:disable-line:no-any + return Promise.all( + Object.keys(tables).map(table => { + const columnsResults = Object.keys(tables[table]).map(columnString => { + return Promise.all( + buildQueryQueue({ + table, + columnString, + items: tables[table][columnString], + }), + ); + }); + return Promise.all(columnsResults); + }), + ); +} + +/** + * Extracts the values from the item for INSERT + * + * @param {IDataObject} item The item to extract + * @returns {string} (Val1, Val2, ...) + */ +export function extractValues(item: IDataObject): string { + return `(${Object.values(item as any) // tslint:disable-line:no-any + .map(val => (typeof val === 'string' ? `'${val}'` : val)) // maybe other types such as dates have to be handled as well + .join(',')})`; +} + +/** + * Extracts the SET from the item for UPDATE + * + * @param {IDataObject} item The item to extract from + * @param {string[]} columns The columns to update + * @returns {string} col1 = val1, col2 = val2 + */ +export function extractUpdateSet(item: IDataObject, columns: string[]): string { + return columns + .map( + column => + `${column} = ${ + typeof item[column] === 'string' ? `'${item[column]}'` : item[column] + }`, + ) + .join(','); +} + +/** + * Extracts the WHERE condition from the item for UPDATE + * + * @param {IDataObject} item The item to extract from + * @param {string} key The column name to build the condition with + * @returns {string} id = '123' + */ +export function extractUpdateCondition(item: IDataObject, key: string): string { + return `${key} = ${ + typeof item[key] === 'string' ? `'${item[key]}'` : item[key] + }`; +} + +/** + * Extracts the WHERE condition from the items for DELETE + * + * @param {IDataObject[]} items The items to extract the values from + * @param {string} key The column name to extract the value from for the delete condition + * @returns {string} (Val1, Val2, ...) + */ +export function extractDeleteValues(items: IDataObject[], key: string): string { + return `(${items + .map(item => (typeof item[key] === 'string' ? `'${item[key]}'` : item[key])) + .join(',')})`; +} diff --git a/packages/nodes-base/nodes/Microsoft/Sql/MicrosoftSql.node.ts b/packages/nodes-base/nodes/Microsoft/Sql/MicrosoftSql.node.ts new file mode 100644 index 0000000000..a13a2425ca --- /dev/null +++ b/packages/nodes-base/nodes/Microsoft/Sql/MicrosoftSql.node.ts @@ -0,0 +1,394 @@ +import { IExecuteFunctions } from 'n8n-core'; +import { + IDataObject, + INodeExecutionData, + INodeType, + INodeTypeDescription, +} from 'n8n-workflow'; + +import { chunk, flatten } from '../../utils/utilities'; + +import * as mssql from 'mssql'; + +import { ITables } from './TableInterface'; + +import { + copyInputItem, + createTableStruct, + executeQueryQueue, + extractDeleteValues, + extractUpdateCondition, + extractUpdateSet, + extractValues, +} from './GenericFunctions'; + +export class MicrosoftSql implements INodeType { + description: INodeTypeDescription = { + displayName: 'Microsoft SQL', + name: 'microsoftSql', + icon: 'file:mssql.png', + group: ['input'], + version: 1, + description: 'Gets, add and update data in Microsoft SQL.', + defaults: { + name: 'Microsoft SQL', + color: '#1d4bab', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'microsoftSql', + required: true, + }, + ], + properties: [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + options: [ + { + name: 'Execute Query', + value: 'executeQuery', + description: 'Executes a SQL query.', + }, + { + name: 'Insert', + value: 'insert', + description: 'Insert rows in database.', + }, + { + name: 'Update', + value: 'update', + description: 'Updates rows in database.', + }, + { + name: 'Delete', + value: 'delete', + description: 'Deletes rows in database.', + }, + ], + default: 'insert', + description: 'The operation to perform.', + }, + + // ---------------------------------- + // executeQuery + // ---------------------------------- + { + displayName: 'Query', + name: 'query', + type: 'string', + typeOptions: { + rows: 5, + }, + displayOptions: { + show: { + operation: ['executeQuery'], + }, + }, + default: '', + placeholder: 'SELECT id, name FROM product WHERE id < 40', + required: true, + description: 'The SQL query to execute.', + }, + + // ---------------------------------- + // insert + // ---------------------------------- + { + displayName: 'Table', + name: 'table', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: '', + required: true, + description: 'Name of the table in which to insert data to.', + }, + { + displayName: 'Columns', + name: 'columns', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: '', + placeholder: 'id,name,description', + description: + 'Comma separated list of the properties which should used as columns for the new rows.', + }, + + // ---------------------------------- + // update + // ---------------------------------- + { + displayName: 'Table', + name: 'table', + type: 'string', + displayOptions: { + show: { + operation: ['update'], + }, + }, + default: '', + required: true, + description: 'Name of the table in which to update data in', + }, + { + displayName: 'Update Key', + name: 'updateKey', + type: 'string', + displayOptions: { + show: { + operation: ['update'], + }, + }, + default: 'id', + required: true, + description: + 'Name of the property which decides which rows in the database should be updated. Normally that would be "id".', + }, + { + displayName: 'Columns', + name: 'columns', + type: 'string', + displayOptions: { + show: { + operation: ['update'], + }, + }, + default: '', + placeholder: 'name,description', + description: + 'Comma separated list of the properties which should used as columns for rows to update.', + }, + + // ---------------------------------- + // delete + // ---------------------------------- + { + displayName: 'Table', + name: 'table', + type: 'string', + displayOptions: { + show: { + operation: ['delete'], + }, + }, + default: '', + required: true, + description: 'Name of the table in which to delete data.', + }, + { + displayName: 'Delete Key', + name: 'deleteKey', + type: 'string', + displayOptions: { + show: { + operation: ['delete'], + }, + }, + default: 'id', + required: true, + description: + 'Name of the property which decides which rows in the database should be deleted. Normally that would be "id".', + }, + ], + }; + + async execute(this: IExecuteFunctions): Promise { + const credentials = this.getCredentials('microsoftSql'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + const config = { + server: credentials.server as string, + port: credentials.port as number, + database: credentials.database as string, + user: credentials.user as string, + password: credentials.password as string, + domain: credentials.domain ? (credentials.domain as string) : undefined, + }; + + const pool = new mssql.ConnectionPool(config); + await pool.connect(); + + let returnItems = []; + + const items = this.getInputData(); + const operation = this.getNodeParameter('operation', 0) as string; + + try { + if (operation === 'executeQuery') { + // ---------------------------------- + // executeQuery + // ---------------------------------- + + const rawQuery = this.getNodeParameter('query', 0) as string; + + const queryResult = await pool.request().query(rawQuery); + + const result = + queryResult.recordsets.length > 1 + ? flatten(queryResult.recordsets) + : queryResult.recordsets[0]; + + returnItems = this.helpers.returnJsonArray(result as IDataObject[]); + } else if (operation === 'insert') { + // ---------------------------------- + // insert + // ---------------------------------- + + const tables = createTableStruct(this.getNodeParameter, items); + await executeQueryQueue( + tables, + ({ + table, + columnString, + items, + }: { + table: string; + columnString: string; + items: IDataObject[]; + }): Array> => { + return chunk(items, 1000).map(insertValues => { + const values = insertValues + .map((item: IDataObject) => extractValues(item)) + .join(','); + + return pool + .request() + .query( + `INSERT INTO ${table}(${columnString}) VALUES ${values};`, + ); + }); + }, + ); + + returnItems = items; + } else if (operation === 'update') { + // ---------------------------------- + // update + // ---------------------------------- + + const updateKeys = items.map( + (item, index) => this.getNodeParameter('updateKey', index) as string, + ); + const tables = createTableStruct( + this.getNodeParameter, + items, + ['updateKey'].concat(updateKeys), + 'updateKey', + ); + await executeQueryQueue( + tables, + ({ + table, + columnString, + items, + }: { + table: string; + columnString: string; + items: IDataObject[]; + }): Array> => { + return items.map(item => { + const columns = columnString + .split(',') + .map(column => column.trim()); + + const setValues = extractUpdateSet(item, columns); + const condition = extractUpdateCondition( + item, + item.updateKey as string, + ); + + return pool + .request() + .query(`UPDATE ${table} SET ${setValues} WHERE ${condition};`); + }); + }, + ); + + returnItems = items; + } else if (operation === 'delete') { + // ---------------------------------- + // delete + // ---------------------------------- + + const tables = items.reduce((tables, item, index) => { + const table = this.getNodeParameter('table', index) as string; + const deleteKey = this.getNodeParameter('deleteKey', index) as string; + if (tables[table] === undefined) { + tables[table] = {}; + } + if (tables[table][deleteKey] === undefined) { + tables[table][deleteKey] = []; + } + tables[table][deleteKey].push(item); + return tables; + }, {} as ITables); + + const queriesResults = await Promise.all( + Object.keys(tables).map(table => { + const deleteKeyResults = Object.keys(tables[table]).map( + deleteKey => { + const deleteItemsList = chunk( + tables[table][deleteKey].map(item => + copyInputItem(item as INodeExecutionData, [deleteKey]), + ), + 1000, + ); + const queryQueue = deleteItemsList.map(deleteValues => { + return pool + .request() + .query( + `DELETE FROM ${table} WHERE ${deleteKey} IN ${extractDeleteValues( + deleteValues, + deleteKey, + )};`, + ); + }); + return Promise.all(queryQueue); + }, + ); + return Promise.all(deleteKeyResults); + }), + ); + + const rowsDeleted = flatten(queriesResults).reduce( + (acc: number, resp: mssql.IResult): number => + (acc += resp.rowsAffected.reduce((sum, val) => (sum += val))), + 0, + ); + + returnItems = this.helpers.returnJsonArray({ + rowsDeleted, + } as IDataObject); + } else { + await pool.close(); + throw new Error(`The operation "${operation}" is not supported!`); + } + } catch (err) { + if (this.continueOnFail() === true) { + returnItems = items; + } else { + await pool.close(); + throw err; + } + } + + // Close the connection + await pool.close(); + + return this.prepareOutputData(returnItems); + } +} diff --git a/packages/nodes-base/nodes/Microsoft/Sql/TableInterface.ts b/packages/nodes-base/nodes/Microsoft/Sql/TableInterface.ts new file mode 100644 index 0000000000..c260c36ab3 --- /dev/null +++ b/packages/nodes-base/nodes/Microsoft/Sql/TableInterface.ts @@ -0,0 +1,7 @@ +import { IDataObject } from 'n8n-workflow'; + +export interface ITables { + [key: string]: { + [key: string]: IDataObject[]; + }; +} diff --git a/packages/nodes-base/nodes/Microsoft/Sql/mssql.png b/packages/nodes-base/nodes/Microsoft/Sql/mssql.png new file mode 100644 index 0000000000000000000000000000000000000000..18349dc1cc58adfd3e724c264f96d2e3546b4474 GIT binary patch literal 3447 zcmXAr2{=^!7sn@r$oeWG(O_0%r?M0wyp|?gWhq-oB8*UEDMAPl!w3;&UxyiFH)fcz zjD6q6zDtVef8XbSpXc8DyXQH-b3W&M&+mC|6xu|Oi$j*)jNm=-$9I_V)uWKQbY4lDieOXER!>7XfRtn&pTT+Y7Et{5w4h^(|x)6!Nvau9e(FXzm0o({hNO{$UCXGNT|p zE(0fmB@;gt)WhJ5ODl9FtQ`vJLBbZ~5v1;Z0Dz8!0-lSD%f<~!aC(Ez+y@k4oq69m;_KMFg!q8Xf7_m zfRQXLr`%ko?ic|+!&(|6A;FaauX?Sm2q_s2D4F@#cf|%KWtsVmulYrm){A*x3jV#F zLhiP7H6iV zxVt#m+ub)cP*+k!p8VY2+L$Mm7UyN+(vscp-?*-f5Q4R?PX z%Oy0aAFc2AFK49wYuGn%bk;p~Fb4+{zk}cZuT!g}qp65PG0*gaOuwn1t)Lr?K0Sn; zYdk*&%*~sE-6i)IgQ%Tvj*?m2@MG&`z}c`l+lyVm5m6b=30 zTb1~~WAwKckFI=F5vHi76Q3I}mc==d!WSCOjj$j|Yl_Riuzfkl$0jA#4?j3LKmJnT zlWU6Ia~j(bRT@JD^BZIQgZm?6MdqKL7rhgv7g(&q9`|5@TrMficiQsl&bzsna4q#8 zvy~EjAWjK*f_s3+-T5f=Bgs{sE^NS&?XPizBLfg$tk+~dxa`8W&jRxKuaY(?$+u-2 zXB%U!J)=Op^;I{}(N`xzXYC5t5;g)?`ny=`a@Mz0L|7<%zM>(7>&o;$VegNev|Ar_ zFZE1qx0#12v?;}1VYXuV=zmc$g*;G>k1IyhcQJe-IrueNf;R5FYcJ+1&o>)YuWK_S z42eb%()VvF+~55N&NU@9B>)&ihDj{4@E%6x7d<`-XbLk$?&m~?%%L^b zBP3)TycMDu#9H=)?(;XDIF#GdXom4dQ|>*@yNC91%r8R0h0vMkXr3Q56BizhOl@_J z1Xc?fQPl{ehO?uoUl;?1+D6xuiiF>HcwO(Eo)8#XN1=IkmLbfqfD1 zTQ1s-!G29VCG{pa-_6&sM@wGGURx^vr})LgbF=F!tQd~>qvQog9xB@}{=dd&9J*pZ zF=>z1$FRx%l+iQW4X>ncgon#{wVjDbd~S|zwk-I8T4i~wec0;euySlaQ+P+YJtVz_-2jKa=_ae1IdgCjM|ge2pP^Y z=ZCXo9B0BWbkNh^i-%LhYu5^IP5PxafoIZS*Izh@X|LTARArm$4TndrpW+AaJflUt zOWFMT_OW--1a|X+=K7F*Y;o|sbA*GQS z=X@c7YHX)^?UAQUf*@=9NQP%m(!y?Zfl!DK$8O{W!C43A&L3y^kQK@N!fqdo6R|(D zG_GVM>${Y1sI)&{t`Gbhl|A#kr$@$>UH*a|s15Z~ux8}kDrQ+AuS_D(AK_o&=r54E zcbO**Q!{e!$*hl>3Z`mnbuj4M9AD5=(chc%XF?LQQ^xs@)&~W9n3tnUQkIe~M{mdT zTbo3_WDlhj+B)0n2CqN<_miias@SQ8bhAYylTr=iVHx8ci6A0V$d%1>u4e;n6HI5; z=A}>V3Cx6#fAk-ZJ4n82OZ+30C&oh4tvh0!TJapS4$W~{+@3}HYTz<5zq^&Nx9fNC zfa1XqVIa)KDIUE0^su(!%h)#VVZIIpN<2X}tIKbJnE+Cp!q@awTuafveLjNQA#+N5#&6et(1MDu2bp4~e1{Vk7hY4i5==WDyG z6YsvtYw9|=uX#?~FNr?1FmZBqki*JZyCi06CFER>6b8F#E(Ht1~Rx^4WMGb|0#^H38T;h3pTwSE2R@20ci z&PoQNUrFuX9F=4GW1;7bt47N%3)wm?SYI?(X4V%vz$D%H9XRwr^E@{8-t~cM`4b)N zOmhSgEpW|=vj4z8z&K5z=1-0Zo9^u(0SrFS^*2F+DYP(_Bk8^M0Eo8<}SPn=!Pb~<10RfW2VQMKrK z85h6Ms^`pq^RQZVfcFo#kng$Z@^#6oV+0y~`%tyi-yq&K<(W>DA#> zHYT0e9fPxsNt086qIm7_Ger!cyTd_Xmc2R;d)NcJPk3ojHm=VGA4sw<3b2QRrx^?p zsuJ&Lm5RzGrf0;W^Wv2!xjb-JH_M5z)5>}$=XGvEJ@lSA8^>5(V&xDKf>`@kS$i5& zD3oZ$oa3OUOFH!;9074@!m4Jjm8Or#8bt4?gyCG*#FFd8u)ZAQR=|rp|WC0_#nORXgD`&Ie7RrxGNE zJac@lQUhc0{kBWblkpoiR;=4K`d{T`#eHdZROnbLcj9#7P_SG3>K6&Y*rc_EFB;HW zC}&GC(}SS3M2CuQ9hQ$@9Jw#4d!cFkJ_yW9OCf`f#^(``4ZJE&X->Mk{nlMBf?;V| z0D9pc3v=_GF@2?pRmX;*;q|+3zjN3ez)h)KseG0GSAAUlkPNu~;Ez&;fPjZwtP2c9oDnrz% SQGp*wkb$m=PRUKXu>S$oUE5&* literal 0 HcmV?d00001 diff --git a/packages/nodes-base/nodes/MondayCom/BoardItemDescription.ts b/packages/nodes-base/nodes/MondayCom/BoardItemDescription.ts index c6725279ed..9537c32521 100644 --- a/packages/nodes-base/nodes/MondayCom/BoardItemDescription.ts +++ b/packages/nodes-base/nodes/MondayCom/BoardItemDescription.ts @@ -15,6 +15,21 @@ export const boardItemOperations = [ }, }, options: [ + { + name: 'Add Update', + value: 'addUpdate', + description: `Add an update to an item.`, + }, + { + name: 'Change Column Value', + value: 'changeColumnValue', + description: 'Change a column value for a board item', + }, + { + name: 'Change Multiple Column Values', + value: 'changeMultipleColumnValues', + description: 'Change multiple column values for a board item', + }, { name: 'Create', value: 'create', @@ -48,6 +63,192 @@ export const boardItemOperations = [ export const boardItemFields = [ +/* -------------------------------------------------------------------------- */ +/* boardItem:addUpdate */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Item ID', + name: 'itemId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'addUpdate', + ], + }, + }, + description: 'The unique identifier of the item to add update to.', + }, + { + displayName: 'Update Text', + name: 'value', + type: 'string', + required: true, + default: '', + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'addUpdate', + ], + }, + }, + description: 'The update text to add.', + }, +/* -------------------------------------------------------------------------- */ +/* boardItem:changeColumnValue */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Board ID', + name: 'boardId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getBoards', + }, + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'changeColumnValue', + ], + }, + }, + description: 'The unique identifier of the board.', + }, + { + displayName: 'Item ID', + name: 'itemId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'changeColumnValue', + ], + }, + }, + description: 'The unique identifier of the item to to change column of.', + }, + { + displayName: 'Column ID', + name: 'columnId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getColumns', + loadOptionsDependsOn: [ + 'boardId' + ], + }, + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'changeColumnValue', + ], + }, + }, + description: `The column's unique identifier.`, + }, + { + displayName: 'Value', + name: 'value', + type: 'json', + required: true, + default: '', + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'changeColumnValue', + ], + }, + }, + description: 'The column value in JSON format. Documentation can be found here.', + }, +/* -------------------------------------------------------------------------- */ +/* boardItem:changeMultipleColumnValues */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Board ID', + name: 'boardId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getBoards', + }, + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'changeMultipleColumnValues', + ], + }, + }, + description: 'The unique identifier of the board.', + }, + { + displayName: 'Item ID', + name: 'itemId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'changeMultipleColumnValues', + ], + }, + }, + description: `Item's ID` + }, + { + displayName: 'Column Values', + name: 'columnValues', + type: 'json', + required: true, + default: '', + displayOptions: { + show: { + resource: [ + 'boardItem', + ], + operation: [ + 'changeMultipleColumnValues', + ], + }, + }, + description: 'The column fields and values in JSON format. Documentation can be found here.', + typeOptions: { + alwaysOpenEditWindow: true, + }, + }, /* -------------------------------------------------------------------------- */ /* boardItem:create */ /* -------------------------------------------------------------------------- */ diff --git a/packages/nodes-base/nodes/MondayCom/MondayCom.node.ts b/packages/nodes-base/nodes/MondayCom/MondayCom.node.ts index f8e538e5cb..5dc7457081 100644 --- a/packages/nodes-base/nodes/MondayCom/MondayCom.node.ts +++ b/packages/nodes-base/nodes/MondayCom/MondayCom.node.ts @@ -455,6 +455,84 @@ export class MondayCom implements INodeType { } } if (resource === 'boardItem') { + if (operation === 'addUpdate') { + const itemId = parseInt((this.getNodeParameter('itemId', i) as string), 10); + const value = this.getNodeParameter('value', i) as string; + + const body: IGraphqlBody = { + query: + `mutation ($itemId: Int!, $value: String!) { + create_update (item_id: $itemId, body: $value) { + id + } + }`, + variables: { + itemId, + value, + }, + }; + + responseData = await mondayComApiRequest.call(this, body); + responseData = responseData.data.create_update; + } + if (operation === 'changeColumnValue') { + const boardId = parseInt(this.getNodeParameter('boardId', i) as string, 10); + const itemId = parseInt((this.getNodeParameter('itemId', i) as string), 10); + const columnId = this.getNodeParameter('columnId', i) as string; + const value = this.getNodeParameter('value', i) as string; + + const body: IGraphqlBody = { + query: + `mutation ($boardId: Int!, $itemId: Int!, $columnId: String!, $value: JSON!) { + change_column_value (board_id: $boardId, item_id: $itemId, column_id: $columnId, value: $value) { + id + } + }`, + variables: { + boardId, + itemId, + columnId, + }, + }; + + try { + JSON.parse(value); + } catch (e) { + throw new Error('Custom Values must be a valid JSON'); + } + body.variables.value = JSON.stringify(JSON.parse(value)); + + responseData = await mondayComApiRequest.call(this, body); + responseData = responseData.data.change_column_value; + } + if (operation === 'changeMultipleColumnValues') { + const boardId = parseInt(this.getNodeParameter('boardId', i) as string, 10); + const itemId = parseInt((this.getNodeParameter('itemId', i) as string), 10); + const columnValues = this.getNodeParameter('columnValues', i) as string; + + const body: IGraphqlBody = { + query: + `mutation ($boardId: Int!, $itemId: Int!, $columnValues: JSON!) { + change_multiple_column_values (board_id: $boardId, item_id: $itemId, column_values: $columnValues) { + id + } + }`, + variables: { + boardId, + itemId, + }, + }; + + try { + JSON.parse(columnValues); + } catch (e) { + throw new Error('Custom Values must be a valid JSON'); + } + body.variables.columnValues = JSON.stringify(JSON.parse(columnValues)); + + responseData = await mondayComApiRequest.call(this, body); + responseData = responseData.data.change_multiple_column_values; + } if (operation === 'create') { const boardId = parseInt(this.getNodeParameter('boardId', i) as string, 10); const groupId = this.getNodeParameter('groupId', i) as string; diff --git a/packages/nodes-base/nodes/MongoDb/MongoDb.node.ts b/packages/nodes-base/nodes/MongoDb/MongoDb.node.ts index dbd7ab2929..d91a287b88 100644 --- a/packages/nodes-base/nodes/MongoDb/MongoDb.node.ts +++ b/packages/nodes-base/nodes/MongoDb/MongoDb.node.ts @@ -32,7 +32,18 @@ export class MongoDb implements INodeType { const items = this.getInputData(); const operation = this.getNodeParameter('operation', 0) as string; - if (operation === 'find') { + if (operation === 'delete') { + // ---------------------------------- + // delete + // ---------------------------------- + + const { deletedCount } = await mdb + .collection(this.getNodeParameter('collection', 0) as string) + .deleteMany(JSON.parse(this.getNodeParameter('query', 0) as string)); + + returnItems = this.helpers.returnJsonArray([{ deletedCount }]); + + } else if (operation === 'find') { // ---------------------------------- // find // ---------------------------------- diff --git a/packages/nodes-base/nodes/MongoDb/mongo.node.options.ts b/packages/nodes-base/nodes/MongoDb/mongo.node.options.ts index 190ff3de88..953a45a620 100644 --- a/packages/nodes-base/nodes/MongoDb/mongo.node.options.ts +++ b/packages/nodes-base/nodes/MongoDb/mongo.node.options.ts @@ -28,6 +28,11 @@ export const nodeDescription: INodeTypeDescription = { name: 'operation', type: 'options', options: [ + { + name: 'Delete', + value: 'delete', + description: 'Delete documents.' + }, { name: 'Find', value: 'find', @@ -57,13 +62,36 @@ export const nodeDescription: INodeTypeDescription = { description: 'MongoDB Collection' }, + // ---------------------------------- + // delete + // ---------------------------------- + { + displayName: 'Delete Query (JSON format)', + name: 'query', + type: 'json', + typeOptions: { + rows: 5 + }, + displayOptions: { + show: { + operation: [ + 'delete' + ], + }, + }, + default: '{}', + placeholder: `{ "birth": { "$gt": "1950-01-01" } }`, + required: true, + description: 'MongoDB Delete query.' + }, + // ---------------------------------- // find // ---------------------------------- { displayName: 'Query (JSON format)', name: 'query', - type: 'string', + type: 'json', typeOptions: { rows: 5 }, diff --git a/packages/nodes-base/nodes/Msg91/Msg91.node.ts b/packages/nodes-base/nodes/Msg91/Msg91.node.ts index 240a3623e0..8fb0444de5 100644 --- a/packages/nodes-base/nodes/Msg91/Msg91.node.ts +++ b/packages/nodes-base/nodes/Msg91/Msg91.node.ts @@ -68,7 +68,7 @@ export class Msg91 implements INodeType { description: 'The operation to perform.', }, { - displayName: 'From', + displayName: 'Sender ID', name: 'from', type: 'string', default: '', diff --git a/packages/nodes-base/nodes/NextCloud/GenericFunctions.ts b/packages/nodes-base/nodes/NextCloud/GenericFunctions.ts new file mode 100644 index 0000000000..2198cb5513 --- /dev/null +++ b/packages/nodes-base/nodes/NextCloud/GenericFunctions.ts @@ -0,0 +1,63 @@ +import { + IExecuteFunctions, + IHookFunctions, +} from 'n8n-core'; + +import { + OptionsWithUri, +} from 'request'; + +/** + * Make an API request to NextCloud + * + * @param {IHookFunctions} this + * @param {string} method + * @param {string} url + * @param {object} body + * @returns {Promise} + */ +export async function nextCloudApiRequest(this: IHookFunctions | IExecuteFunctions, method: string, endpoint: string, body: object | string | Buffer, headers?: object, encoding?: null | undefined, query?: object): Promise { // tslint:disable-line:no-any + const options : OptionsWithUri = { + headers, + method, + body, + qs: {}, + uri: '', + json: false, + }; + + if (encoding === null) { + options.encoding = null; + } + + const authenticationMethod = this.getNodeParameter('authentication', 0); + + try { + if (authenticationMethod === 'accessToken') { + const credentials = this.getCredentials('nextCloudApi'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.auth = { + user: credentials.user as string, + pass: credentials.password as string, + }; + + options.uri = `${credentials.webDavUrl}/${encodeURI(endpoint)}`; + + return await this.helpers.request(options); + } else { + const credentials = this.getCredentials('nextCloudOAuth2Api'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.uri = `${credentials.webDavUrl}/${encodeURI(endpoint)}`; + + return await this.helpers.requestOAuth2!.call(this, 'nextCloudOAuth2Api', options); + } + } catch (error) { + throw new Error(`NextCloud Error. Status Code: ${error.statusCode}. Message: ${error.message}`); + } +} diff --git a/packages/nodes-base/nodes/NextCloud/NextCloud.node.ts b/packages/nodes-base/nodes/NextCloud/NextCloud.node.ts index 309f53ceae..a5b3109c6e 100644 --- a/packages/nodes-base/nodes/NextCloud/NextCloud.node.ts +++ b/packages/nodes-base/nodes/NextCloud/NextCloud.node.ts @@ -2,6 +2,7 @@ import { BINARY_ENCODING, IExecuteFunctions, } from 'n8n-core'; + import { IDataObject, INodeTypeDescription, @@ -9,9 +10,13 @@ import { INodeType, } from 'n8n-workflow'; -import { parseString } from 'xml2js'; -import { OptionsWithUri } from 'request'; +import { + parseString, +} from 'xml2js'; +import { + nextCloudApiRequest, +} from './GenericFunctions'; export class NextCloud implements INodeType { description: INodeTypeDescription = { @@ -24,7 +29,7 @@ export class NextCloud implements INodeType { description: 'Access data on NextCloud', defaults: { name: 'NextCloud', - color: '#22BB44', + color: '#1cafff', }, inputs: ['main'], outputs: ['main'], @@ -32,9 +37,44 @@ export class NextCloud implements INodeType { { name: 'nextCloudApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'nextCloudOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'The resource to operate on.', + }, { displayName: 'Resource', name: 'resource', @@ -446,7 +486,14 @@ export class NextCloud implements INodeType { const items = this.getInputData().slice(); const returnData: IDataObject[] = []; - const credentials = this.getCredentials('nextCloudApi'); + const authenticationMethod = this.getNodeParameter('authentication', 0); + let credentials; + + if (authenticationMethod === 'accessToken') { + credentials = this.getCredentials('nextCloudApi'); + } else { + credentials = this.getCredentials('nextCloudOAuth2Api'); + } if (credentials === undefined) { throw new Error('No credentials got returned!'); @@ -562,26 +609,14 @@ export class NextCloud implements INodeType { webDavUrl = webDavUrl.slice(0, -1); } - const options: OptionsWithUri = { - auth: { - user: credentials.user as string, - pass: credentials.password as string, - }, - headers, - method: requestMethod, - body, - qs: {}, - uri: `${credentials.webDavUrl}/${encodeURI(endpoint)}`, - json: false, - }; - + let encoding = undefined; if (resource === 'file' && operation === 'download') { // Return the data as a buffer - options.encoding = null; + encoding = null; } try { - responseData = await this.helpers.request(options); + responseData = await nextCloudApiRequest.call(this, requestMethod, endpoint, body, headers, encoding); } catch (error) { if (this.continueOnFail() === true) { returnData.push({ error }); diff --git a/packages/nodes-base/nodes/OpenWeatherMap.node.ts b/packages/nodes-base/nodes/OpenWeatherMap.node.ts index e12e384094..38e883e53f 100644 --- a/packages/nodes-base/nodes/OpenWeatherMap.node.ts +++ b/packages/nodes-base/nodes/OpenWeatherMap.node.ts @@ -213,20 +213,20 @@ export class OpenWeatherMap implements INodeType { // Set base data qs = { APPID: credentials.accessToken, - units: this.getNodeParameter('format', 0) as string + units: this.getNodeParameter('format', i) as string }; // Get the location - locationSelection = this.getNodeParameter('locationSelection', 0) as string; + locationSelection = this.getNodeParameter('locationSelection', i) as string; if (locationSelection === 'cityName') { - qs.q = this.getNodeParameter('cityName', 0) as string; + qs.q = this.getNodeParameter('cityName', i) as string; } else if (locationSelection === 'cityId') { - qs.id = this.getNodeParameter('cityId', 0) as number; + qs.id = this.getNodeParameter('cityId', i) as number; } else if (locationSelection === 'coordinates') { - qs.lat = this.getNodeParameter('latitude', 0) as string; - qs.lon = this.getNodeParameter('longitude', 0) as string; + qs.lat = this.getNodeParameter('latitude', i) as string; + qs.lon = this.getNodeParameter('longitude', i) as string; } else if (locationSelection === 'zipCode') { - qs.zip = this.getNodeParameter('zipCode', 0) as string; + qs.zip = this.getNodeParameter('zipCode', i) as string; } else { throw new Error(`The locationSelection "${locationSelection}" is not known!`); } diff --git a/packages/nodes-base/nodes/PagerDuty/GenericFunctions.ts b/packages/nodes-base/nodes/PagerDuty/GenericFunctions.ts index c360114144..f4832b923c 100644 --- a/packages/nodes-base/nodes/PagerDuty/GenericFunctions.ts +++ b/packages/nodes-base/nodes/PagerDuty/GenericFunctions.ts @@ -19,16 +19,11 @@ import { export async function pagerDutyApiRequest(this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, query: IDataObject = {}, uri?: string, headers: IDataObject = {}): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('pagerDutyApi'); - - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } + const authenticationMethod = this.getNodeParameter('authentication', 0); const options: OptionsWithUri = { headers: { - Accept: 'application/vnd.pagerduty+json;version=2', - Authorization: `Token token=${credentials.apiToken}`, + Accept: 'application/vnd.pagerduty+json;version=2' }, method, body, @@ -39,15 +34,30 @@ export async function pagerDutyApiRequest(this: IExecuteFunctions | IWebhookFunc arrayFormat: 'brackets', }, }; + if (!Object.keys(body).length) { delete options.form; } if (!Object.keys(query).length) { delete options.qs; } + options.headers = Object.assign({}, options.headers, headers); + try { - return await this.helpers.request!(options); + if (authenticationMethod === 'apiToken') { + const credentials = this.getCredentials('pagerDutyApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.headers!['Authorization'] = `Token token=${credentials.apiToken}`; + + return await this.helpers.request!(options); + } else { + return await this.helpers.requestOAuth2!.call(this, 'pagerDutyOAuth2Api', options); + } } catch (error) { if (error.response && error.response.body && error.response.body.error && error.response.body.error.errors) { // Try to return the error prettier diff --git a/packages/nodes-base/nodes/PagerDuty/PagerDuty.node.ts b/packages/nodes-base/nodes/PagerDuty/PagerDuty.node.ts index d53e5921b8..8d62b8fc6f 100644 --- a/packages/nodes-base/nodes/PagerDuty/PagerDuty.node.ts +++ b/packages/nodes-base/nodes/PagerDuty/PagerDuty.node.ts @@ -66,9 +66,43 @@ export class PagerDuty implements INodeType { { name: 'pagerDutyApi', required: true, + displayOptions: { + show: { + authentication: [ + 'apiToken', + ], + }, + }, + }, + { + name: 'pagerDutyOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'API Token', + value: 'apiToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'apiToken', + }, { displayName: 'Resource', name: 'resource', diff --git a/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts b/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts index 59ba514acf..23ef841bee 100644 --- a/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts @@ -5,10 +5,16 @@ import { import { IDataObject, + ILoadOptionsFunctions, } from 'n8n-workflow'; -import { OptionsWithUri } from 'request'; +import { + OptionsWithUri, +} from 'request'; +<<<<<<< HEAD +======= +>>>>>>> master export interface ICustomInterface { name: string; @@ -32,10 +38,27 @@ export interface ICustomProperties { * @param {object} body * @returns {Promise} */ +<<<<<<< HEAD export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctions, method: string, endpoint: string, body: IDataObject, query?: IDataObject, formData?: IDataObject, downloadFile?: boolean): Promise { // tslint:disable-line:no-any const authenticationMethod = this.getNodeParameter('authentication', 0); +======= +export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: IDataObject, query?: IDataObject, formData?: IDataObject, downloadFile?: boolean): Promise { // tslint:disable-line:no-any + const credentials = this.getCredentials('pipedriveApi'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + if (query === undefined) { + query = {}; + } + + query.api_token = credentials.apiToken; +>>>>>>> master const options: OptionsWithUri = { + headers: { + Accept: 'application/json', + }, method, qs: query, uri: `https://api.pipedrive.com/v1${endpoint}`, @@ -62,7 +85,8 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio let responseData; try { - if (authenticationMethod === 'basicAuth') { +<<<<<<< HEAD + if (authenticationMethod === 'basicAuth' || authenticationMethod === 'apiToken') { const credentials = this.getCredentials('pipedriveApi'); if (credentials === undefined) { @@ -76,6 +100,10 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio } else { responseData = await this.helpers.requestOAuth2!.call(this, 'pipedriveOAuth2Api', options); } +======= + //@ts-ignore + const responseData = await this.helpers.request(options); +>>>>>>> master if (downloadFile === true) { return { @@ -99,7 +127,7 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio if (error.response && error.response.body && error.response.body.error) { // Try to return the error prettier - let errorMessage = `Pipedrive error response [${error.statusCode}]: ${error.response.body.error}`; + let errorMessage = `Pipedrive error response [${error.statusCode}]: ${error.response.body.error.message}`; if (error.response.body.error_info) { errorMessage += ` - ${error.response.body.error_info}`; } @@ -128,7 +156,7 @@ export async function pipedriveApiRequestAllItems(this: IHookFunctions | IExecut if (query === undefined) { query = {}; } - query.limit = 500; + query.limit = 100; query.start = 0; const returnData: IDataObject[] = []; @@ -137,7 +165,12 @@ export async function pipedriveApiRequestAllItems(this: IHookFunctions | IExecut do { responseData = await pipedriveApiRequest.call(this, method, endpoint, body, query); - returnData.push.apply(returnData, responseData.data); + // the search path returns data diferently + if (responseData.data.items) { + returnData.push.apply(returnData, responseData.data.items); + } else { + returnData.push.apply(returnData, responseData.data); + } query.start = responseData.additionalData.pagination.next_start; } while ( diff --git a/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts b/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts index 48a619a331..9a0da8d25f 100644 --- a/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts +++ b/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts @@ -1,12 +1,14 @@ import { BINARY_ENCODING, IExecuteFunctions, + ILoadOptionsFunctions, } from 'n8n-core'; import { IDataObject, INodeTypeDescription, INodeExecutionData, INodeType, + INodePropertyOptions, } from 'n8n-workflow'; import { @@ -23,7 +25,6 @@ interface CustomProperty { value: string; } - /** * Add the additional fields to the body * @@ -64,7 +65,7 @@ export class Pipedrive implements INodeType { displayOptions: { show: { authentication: [ - 'basicAuth', + 'apiToken', ], }, }, @@ -88,19 +89,15 @@ export class Pipedrive implements INodeType { type: 'options', options: [ { - name: 'Basic Auth', - value: 'basicAuth' + name: 'API Token', + value: 'apiToken' }, { name: 'OAuth2', value: 'oAuth2', }, - { - name: 'None', - value: 'none', - }, ], - default: 'basicAuth', + default: 'apiToken', description: 'Method of authentication.', }, { @@ -399,6 +396,11 @@ export class Pipedrive implements INodeType { value: 'getAll', description: 'Get data of all persons', }, + { + name: 'Search', + value: 'search', + description: 'Search all persons', + }, { name: 'Update', value: 'update', @@ -2058,6 +2060,7 @@ export class Pipedrive implements INodeType { show: { operation: [ 'getAll', + 'search', ], }, }, @@ -2072,6 +2075,7 @@ export class Pipedrive implements INodeType { show: { operation: [ 'getAll', + 'search', ], returnAll: [ false, @@ -2086,9 +2090,143 @@ export class Pipedrive implements INodeType { description: 'How many results to return.', }, + // ---------------------------------- + // person:getAll + // ---------------------------------- + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'person', + ], + }, + }, + default: {}, + options: [ + { + displayName: 'Filter ID', + name: 'filterId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getFilters', + }, + default: '', + description: 'ID of the filter to use.', + }, + { + displayName: 'First Char', + name: 'firstChar', + type: 'string', + default: '', + description: 'If supplied, only persons whose name starts with the specified letter will be returned ', + }, + ], + }, + + // ---------------------------------- + // person:search + // ---------------------------------- + { + displayName: 'Term', + name: 'term', + type: 'string', + displayOptions: { + show: { + operation: [ + 'search', + ], + resource: [ + 'person', + ], + }, + }, + default: '', + description: 'The search term to look for. Minimum 2 characters (or 1 if using exact_match).', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + displayOptions: { + show: { + operation: [ + 'search', + ], + resource: [ + 'person', + ], + }, + }, + default: {}, + options: [ + { + displayName: 'Exact Match', + name: 'exactMatch', + type: 'boolean', + default: false, + description: 'When enabled, only full exact matches against the given term are returned. It is not case sensitive.', + }, + { + displayName: 'Fields', + name: 'fields', + type: 'string', + default: '', + description: 'A comma-separated string array. The fields to perform the search from. Defaults to all of them.', + }, + { + displayName: 'Include Fields', + name: 'includeFields', + type: 'string', + default: '', + description: 'Supports including optional fields in the results which are not provided by default.', + }, + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'string', + default: '', + description: 'Will filter Deals by the provided Organization ID.', + }, + { + displayName: 'RAW Data', + name: 'rawData', + type: 'boolean', + default: false, + description: `Returns the data exactly in the way it got received from the API.`, + }, + ], + }, ], }; + methods = { + loadOptions: { + // Get all the filters to display them to user so that he can + // select them easily + async getFilters(this: ILoadOptionsFunctions): Promise { + const returnData: INodePropertyOptions[] = []; + const { data } = await pipedriveApiRequest.call(this, 'GET', '/filters', {}, { type: 'people' }); + for (const filter of data) { + const filterName = filter.name; + const filterId = filter.id; + returnData.push({ + name: filterName, + value: filterId, + }); + } + return returnData; + }, + } + }; + async execute(this: IExecuteFunctions): Promise { const items = this.getInputData(); @@ -2492,8 +2630,51 @@ export class Pipedrive implements INodeType { qs.limit = this.getNodeParameter('limit', i) as number; } + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + + if (additionalFields.filterId) { + qs.filter_id = additionalFields.filterId as string; + } + + if (additionalFields.firstChar) { + qs.first_char = additionalFields.firstChar as string; + } + endpoint = `/persons`; + } else if (operation === 'search') { + // ---------------------------------- + // persons:search + // ---------------------------------- + + requestMethod = 'GET'; + + qs.term = this.getNodeParameter('term', i) as string; + returnAll = this.getNodeParameter('returnAll', i) as boolean; + if (returnAll === false) { + qs.limit = this.getNodeParameter('limit', i) as number; + } + + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + + if (additionalFields.fields) { + qs.fields = additionalFields.fields as string; + } + + if (additionalFields.exactMatch) { + qs.exact_match = additionalFields.exactMatch as boolean; + } + + if (additionalFields.organizationId) { + qs.organization_id = parseInt(additionalFields.organizationId as string, 10); + } + + if (additionalFields.includeFields) { + qs.include_fields = additionalFields.includeFields as string; + } + + endpoint = `/persons/search`; + } else if (operation === 'update') { // ---------------------------------- // person:update @@ -2530,7 +2711,9 @@ export class Pipedrive implements INodeType { let responseData; if (returnAll === true) { + responseData = await pipedriveApiRequestAllItems.call(this, requestMethod, endpoint, body, qs); + } else { if (customProperties !== undefined) { @@ -2538,6 +2721,13 @@ export class Pipedrive implements INodeType { } responseData = await pipedriveApiRequest.call(this, requestMethod, endpoint, body, qs, formData, downloadFile); + +<<<<<<< HEAD + if (responseData.data === null) { + responseData.data = []; + } +======= +>>>>>>> master } if (resource === 'file' && operation === 'download') { @@ -2559,6 +2749,24 @@ export class Pipedrive implements INodeType { items[i].binary![binaryPropertyName] = await this.helpers.prepareBinaryData(responseData.data); } else { + + if (responseData.data === null) { + responseData.data = []; + } + + if (operation === 'search' && responseData.data && responseData.data.items) { + responseData.data = responseData.data.items; + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + if (additionalFields.rawData !== true) { + responseData.data = responseData.data.map((item: { result_score: number, item: object }) => { + return { + result_score: item.result_score, + ...item.item, + }; + }); + } + } + if (Array.isArray(responseData.data)) { returnData.push.apply(returnData, responseData.data as IDataObject[]); } else { diff --git a/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts b/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts index ca4a1a7ec8..06aa9c9234 100644 --- a/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts +++ b/packages/nodes-base/nodes/Pipedrive/PipedriveTrigger.node.ts @@ -14,8 +14,10 @@ import { } from './GenericFunctions'; import * as basicAuth from 'basic-auth'; -import { Response } from 'express'; +import { + Response, +} from 'express'; function authorizationError(resp: Response, realm: string, responseCode: number, message?: string) { if (message === undefined) { @@ -52,6 +54,10 @@ export class PipedriveTrigger implements INodeType { { name: 'pipedriveApi', required: true, + }, + { + name: 'httpBasicAuth', + required: true, displayOptions: { show: { authentication: [ @@ -60,18 +66,6 @@ export class PipedriveTrigger implements INodeType { }, }, }, - { - name: 'pipedriveOAuth2Api', - required: true, - displayOptions: { - show: { - authentication: [ - 'oAuth2', - ], - }, - }, - }, - ], ], webhooks: [ { @@ -91,17 +85,13 @@ export class PipedriveTrigger implements INodeType { name: 'Basic Auth', value: 'basicAuth' }, - { - name: 'OAuth2', - value: 'oAuth2', - }, { name: 'None', - value: 'none', + value: 'none' }, ], - default: 'basicAuth', - description: 'Method of authentication.', + default: 'none', + description: 'If authentication should be activated for the webhook (makes it more scure).', }, { displayName: 'Action', @@ -191,7 +181,6 @@ export class PipedriveTrigger implements INodeType { description: 'Type of object to receive notifications about.', }, ], - }; // @ts-ignore (because of request) @@ -288,8 +277,6 @@ export class PipedriveTrigger implements INodeType { }, }; - - async webhook(this: IWebhookFunctions): Promise { const req = this.getRequestObject(); const resp = this.getResponseObject(); diff --git a/packages/nodes-base/nodes/Postgres/Postgres.node.functions.ts b/packages/nodes-base/nodes/Postgres/Postgres.node.functions.ts new file mode 100644 index 0000000000..4dae3a64c1 --- /dev/null +++ b/packages/nodes-base/nodes/Postgres/Postgres.node.functions.ts @@ -0,0 +1,129 @@ +import { IDataObject, INodeExecutionData } from 'n8n-workflow'; +import pgPromise = require('pg-promise'); +import pg = require('pg-promise/typescript/pg-subset'); + +/** + * Returns of copy of the items which only contains the json data and + * of that only the define properties + * + * @param {INodeExecutionData[]} items The items to copy + * @param {string[]} properties The properties it should include + * @returns + */ +function getItemCopy(items: INodeExecutionData[], properties: string[]): IDataObject[] { + // Prepare the data to insert and copy it to be returned + let newItem: IDataObject; + return items.map(item => { + newItem = {}; + for (const property of properties) { + if (item.json[property] === undefined) { + newItem[property] = null; + } else { + newItem[property] = JSON.parse(JSON.stringify(item.json[property])); + } + } + return newItem; + }); +} + +/** + * Executes the given SQL query on the database. + * + * @param {Function} getNodeParam The getter for the Node's parameters + * @param {pgPromise.IMain<{}, pg.IClient>} pgp The pgPromise instance + * @param {pgPromise.IDatabase<{}, pg.IClient>} db The pgPromise database connection + * @param {input[]} input The Node's input data + * @returns Promise> + */ +export function pgQuery( + getNodeParam: Function, + pgp: pgPromise.IMain<{}, pg.IClient>, + db: pgPromise.IDatabase<{}, pg.IClient>, + input: INodeExecutionData[], +): Promise { + const queries: string[] = []; + for (let i = 0; i < input.length; i++) { + queries.push(getNodeParam('query', i) as string); + } + + return db.any(pgp.helpers.concat(queries)); +} + +/** + * Inserts the given items into the database. + * + * @param {Function} getNodeParam The getter for the Node's parameters + * @param {pgPromise.IMain<{}, pg.IClient>} pgp The pgPromise instance + * @param {pgPromise.IDatabase<{}, pg.IClient>} db The pgPromise database connection + * @param {INodeExecutionData[]} items The items to be inserted + * @returns Promise> + */ +export async function pgInsert( + getNodeParam: Function, + pgp: pgPromise.IMain<{}, pg.IClient>, + db: pgPromise.IDatabase<{}, pg.IClient>, + items: INodeExecutionData[], +): Promise { + const table = getNodeParam('table', 0) as string; + const schema = getNodeParam('schema', 0) as string; + let returnFields = (getNodeParam('returnFields', 0) as string).split(',') as string[]; + const columnString = getNodeParam('columns', 0) as string; + const columns = columnString.split(',').map(column => column.trim()); + + const cs = new pgp.helpers.ColumnSet(columns); + + const te = new pgp.helpers.TableName({ table, schema }); + + // Prepare the data to insert and copy it to be returned + const insertItems = getItemCopy(items, columns); + + // Generate the multi-row insert query and return the id of new row + returnFields = returnFields.map(value => value.trim()).filter(value => !!value); + const query = + pgp.helpers.insert(insertItems, cs, te) + + (returnFields.length ? ` RETURNING ${returnFields.join(',')}` : ''); + + // Executing the query to insert the data + const insertData = await db.manyOrNone(query); + + return [insertData, insertItems]; +} + +/** + * Updates the given items in the database. + * + * @param {Function} getNodeParam The getter for the Node's parameters + * @param {pgPromise.IMain<{}, pg.IClient>} pgp The pgPromise instance + * @param {pgPromise.IDatabase<{}, pg.IClient>} db The pgPromise database connection + * @param {INodeExecutionData[]} items The items to be updated + * @returns Promise> + */ +export async function pgUpdate( + getNodeParam: Function, + pgp: pgPromise.IMain<{}, pg.IClient>, + db: pgPromise.IDatabase<{}, pg.IClient>, + items: INodeExecutionData[], +): Promise { + const table = getNodeParam('table', 0) as string; + const updateKey = getNodeParam('updateKey', 0) as string; + const columnString = getNodeParam('columns', 0) as string; + + const columns = columnString.split(',').map(column => column.trim()); + + // Make sure that the updateKey does also get queried + if (!columns.includes(updateKey)) { + columns.unshift(updateKey); + } + + // Prepare the data to update and copy it to be returned + const updateItems = getItemCopy(items, columns); + + // Generate the multi-row update query + const query = + pgp.helpers.update(updateItems, columns, table) + ' WHERE v.' + updateKey + ' = t.' + updateKey; + + // Executing the query to update the data + await db.none(query); + + return updateItems; +} diff --git a/packages/nodes-base/nodes/Postgres/Postgres.node.ts b/packages/nodes-base/nodes/Postgres/Postgres.node.ts index 2fa010576b..f92234eb06 100644 --- a/packages/nodes-base/nodes/Postgres/Postgres.node.ts +++ b/packages/nodes-base/nodes/Postgres/Postgres.node.ts @@ -3,36 +3,12 @@ import { IDataObject, INodeExecutionData, INodeType, - INodeTypeDescription, + INodeTypeDescription } from 'n8n-workflow'; import * as pgPromise from 'pg-promise'; - -/** - * Returns of copy of the items which only contains the json data and - * of that only the define properties - * - * @param {INodeExecutionData[]} items The items to copy - * @param {string[]} properties The properties it should include - * @returns - */ -function getItemCopy(items: INodeExecutionData[], properties: string[]): IDataObject[] { - // Prepare the data to insert and copy it to be returned - let newItem: IDataObject; - return items.map((item) => { - newItem = {}; - for (const property of properties) { - if (item.json[property] === undefined) { - newItem[property] = null; - } else { - newItem[property] = JSON.parse(JSON.stringify(item.json[property])); - } - } - return newItem; - }); -} - +import { pgInsert, pgQuery, pgUpdate } from './Postgres.node.functions'; export class Postgres implements INodeType { description: INodeTypeDescription = { @@ -52,7 +28,7 @@ export class Postgres implements INodeType { { name: 'postgres', required: true, - } + }, ], properties: [ { @@ -63,17 +39,17 @@ export class Postgres implements INodeType { { name: 'Execute Query', value: 'executeQuery', - description: 'Executes a SQL query.', + description: 'Execute an SQL query', }, { name: 'Insert', value: 'insert', - description: 'Insert rows in database.', + description: 'Insert rows in database', }, { name: 'Update', value: 'update', - description: 'Updates rows in database.', + description: 'Update rows in database', }, ], default: 'insert', @@ -92,9 +68,7 @@ export class Postgres implements INodeType { }, displayOptions: { show: { - operation: [ - 'executeQuery' - ], + operation: ['executeQuery'], }, }, default: '', @@ -103,7 +77,6 @@ export class Postgres implements INodeType { description: 'The SQL query to execute.', }, - // ---------------------------------- // insert // ---------------------------------- @@ -113,9 +86,7 @@ export class Postgres implements INodeType { type: 'string', displayOptions: { show: { - operation: [ - 'insert' - ], + operation: ['insert'], }, }, default: 'public', @@ -128,9 +99,7 @@ export class Postgres implements INodeType { type: 'string', displayOptions: { show: { - operation: [ - 'insert' - ], + operation: ['insert'], }, }, default: '', @@ -143,14 +112,13 @@ export class Postgres implements INodeType { type: 'string', displayOptions: { show: { - operation: [ - 'insert' - ], + operation: ['insert'], }, }, default: '', placeholder: 'id,name,description', - description: 'Comma separated list of the properties which should used as columns for the new rows.', + description: + 'Comma separated list of the properties which should used as columns for the new rows.', }, { displayName: 'Return Fields', @@ -158,16 +126,13 @@ export class Postgres implements INodeType { type: 'string', displayOptions: { show: { - operation: [ - 'insert' - ], + operation: ['insert'], }, }, default: '*', description: 'Comma separated list of the fields that the operation will return', }, - // ---------------------------------- // update // ---------------------------------- @@ -177,9 +142,7 @@ export class Postgres implements INodeType { type: 'string', displayOptions: { show: { - operation: [ - 'update' - ], + operation: ['update'], }, }, default: '', @@ -192,14 +155,13 @@ export class Postgres implements INodeType { type: 'string', displayOptions: { show: { - operation: [ - 'update' - ], + operation: ['update'], }, }, default: 'id', required: true, - description: 'Name of the property which decides which rows in the database should be updated. Normally that would be "id".', + description: + 'Name of the property which decides which rows in the database should be updated. Normally that would be "id".', }, { displayName: 'Columns', @@ -207,22 +169,18 @@ export class Postgres implements INodeType { type: 'string', displayOptions: { show: { - operation: [ - 'update' - ], + operation: ['update'], }, }, default: '', placeholder: 'name,description', - description: 'Comma separated list of the properties which should used as columns for rows to update.', + description: + 'Comma separated list of the properties which should used as columns for rows to update.', }, - - ] + ], }; - async execute(this: IExecuteFunctions): Promise { - const credentials = this.getCredentials('postgres'); if (credentials === undefined) { @@ -238,7 +196,7 @@ export class Postgres implements INodeType { user: credentials.user as string, password: credentials.password as string, ssl: !['disable', undefined].includes(credentials.ssl as string | undefined), - sslmode: credentials.ssl as string || 'disable', + sslmode: (credentials.ssl as string) || 'disable', }; const db = pgp(config); @@ -253,39 +211,15 @@ export class Postgres implements INodeType { // executeQuery // ---------------------------------- - const queries: string[] = []; - for (let i = 0; i < items.length; i++) { - queries.push(this.getNodeParameter('query', i) as string); - } - - const queryResult = await db.any(pgp.helpers.concat(queries)); + const queryResult = await pgQuery(this.getNodeParameter, pgp, db, items); returnItems = this.helpers.returnJsonArray(queryResult as IDataObject[]); - } else if (operation === 'insert') { // ---------------------------------- // insert // ---------------------------------- - const table = this.getNodeParameter('table', 0) as string; - const schema = this.getNodeParameter('schema', 0) as string; - let returnFields = (this.getNodeParameter('returnFields', 0) as string).split(',') as string[]; - const columnString = this.getNodeParameter('columns', 0) as string; - const columns = columnString.split(',').map(column => column.trim()); - - const cs = new pgp.helpers.ColumnSet(columns); - - const te = new pgp.helpers.TableName({ table, schema }); - - // Prepare the data to insert and copy it to be returned - const insertItems = getItemCopy(items, columns); - - // Generate the multi-row insert query and return the id of new row - returnFields = returnFields.map(value => value.trim()).filter(value => !!value); - const query = pgp.helpers.insert(insertItems, cs, te) + (returnFields.length ? ` RETURNING ${returnFields.join(',')}` : ''); - - // Executing the query to insert the data - const insertData = await db.manyOrNone(query); + const [insertData, insertItems] = await pgInsert(this.getNodeParameter, pgp, db, items); // Add the id to the data for (let i = 0; i < insertData.length; i++) { @@ -293,37 +227,17 @@ export class Postgres implements INodeType { json: { ...insertData[i], ...insertItems[i], - } + }, }); } - } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- - const table = this.getNodeParameter('table', 0) as string; - const updateKey = this.getNodeParameter('updateKey', 0) as string; - const columnString = this.getNodeParameter('columns', 0) as string; - - const columns = columnString.split(',').map(column => column.trim()); - - // Make sure that the updateKey does also get queried - if (!columns.includes(updateKey)) { - columns.unshift(updateKey); - } - - // Prepare the data to update and copy it to be returned - const updateItems = getItemCopy(items, columns); - - // Generate the multi-row update query - const query = pgp.helpers.update(updateItems, columns, table) + ' WHERE v.' + updateKey + ' = t.' + updateKey; - - // Executing the query to update the data - await db.none(query); - - returnItems = this.helpers.returnJsonArray(updateItems as IDataObject[]); + const updateItems = await pgUpdate(this.getNodeParameter, pgp, db, items); + returnItems = this.helpers.returnJsonArray(updateItems); } else { await pgp.end(); throw new Error(`The operation "${operation}" is not supported!`); diff --git a/packages/nodes-base/nodes/Postmark/GenericFunctions.ts b/packages/nodes-base/nodes/Postmark/GenericFunctions.ts new file mode 100644 index 0000000000..df1e3a1f09 --- /dev/null +++ b/packages/nodes-base/nodes/Postmark/GenericFunctions.ts @@ -0,0 +1,93 @@ +import { + OptionsWithUri, + } from 'request'; + +import { + IExecuteFunctions, + ILoadOptionsFunctions, +} from 'n8n-core'; + +import { + IDataObject, + IHookFunctions, + IWebhookFunctions +} from 'n8n-workflow'; + + +export async function postmarkApiRequest(this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions, method : string, endpoint : string, body: any = {}, option: IDataObject = {}): Promise { // tslint:disable-line:no-any + const credentials = this.getCredentials('postmarkApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + let options: OptionsWithUri = { + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'X-Postmark-Server-Token' : credentials.serverToken + }, + method, + body, + uri: 'https://api.postmarkapp.com' + endpoint, + json: true + }; + if (body === {}) { + delete options.body; + } + options = Object.assign({}, options, option); + + try { + return await this.helpers.request!(options); + } catch (error) { + throw new Error(`Postmark: ${error.statusCode} Message: ${error.message}`); + } +} + +// tslint:disable-next-line: no-any +export function convertTriggerObjectToStringArray (webhookObject : any) : string[] { + const triggers = webhookObject.Triggers; + const webhookEvents : string[] = []; + + // Translate Webhook trigger settings to string array + if (triggers.Open.Enabled) { + webhookEvents.push('open'); + } + if (triggers.Open.PostFirstOpenOnly) { + webhookEvents.push('firstOpen'); + } + if (triggers.Click.Enabled) { + webhookEvents.push('click'); + } + if (triggers.Delivery.Enabled) { + webhookEvents.push('delivery'); + } + if (triggers.Bounce.Enabled) { + webhookEvents.push('bounce'); + } + if (triggers.Bounce.IncludeContent) { + webhookEvents.push('includeContent'); + } + if (triggers.SpamComplaint.Enabled) { + webhookEvents.push('spamComplaint'); + } + if (triggers.SpamComplaint.IncludeContent) { + if (!webhookEvents.includes('IncludeContent')) { + webhookEvents.push('includeContent'); + } + } + if (triggers.SubscriptionChange.Enabled) { + webhookEvents.push('subscriptionChange'); + } + + return webhookEvents; +} + +export function eventExists (currentEvents : string[], webhookEvents: string[]) { + for (const currentEvent of currentEvents) { + if (!webhookEvents.includes(currentEvent)) { + return false; + } + } + return true; +} diff --git a/packages/nodes-base/nodes/Postmark/PostmarkTrigger.node.ts b/packages/nodes-base/nodes/Postmark/PostmarkTrigger.node.ts new file mode 100644 index 0000000000..4956d647b7 --- /dev/null +++ b/packages/nodes-base/nodes/Postmark/PostmarkTrigger.node.ts @@ -0,0 +1,256 @@ +import { + IHookFunctions, + IWebhookFunctions, +} from 'n8n-core'; + +import { + INodeTypeDescription, + INodeType, + IWebhookResponseData, +} from 'n8n-workflow'; + +import { + convertTriggerObjectToStringArray, + eventExists, + postmarkApiRequest +} from './GenericFunctions'; + +export class PostmarkTrigger implements INodeType { + description: INodeTypeDescription = { + displayName: 'Postmark Trigger', + name: 'postmarkTrigger', + icon: 'file:postmark.png', + group: ['trigger'], + version: 1, + description: 'Starts the workflow when Postmark events occur.', + defaults: { + name: 'Postmark Trigger', + color: '#fedd00', + }, + inputs: [], + outputs: ['main'], + credentials: [ + { + name: 'postmarkApi', + required: true, + }, + ], + webhooks: [ + { + name: 'default', + httpMethod: 'POST', + responseMode: 'onReceived', + path: 'webhook', + }, + ], + properties: [ + { + displayName: 'Events', + name: 'events', + type: 'multiOptions', + options: [ + { + name: 'Bounce', + value: 'bounce', + description: 'Trigger on bounce.', + }, + { + name: 'Click', + value: 'click', + description: 'Trigger on click.', + }, + { + name: 'Delivery', + value: 'delivery', + description: 'Trigger on delivery.', + }, + { + name: 'Open', + value: 'open', + description: 'Trigger webhook on open.', + }, + { + name: 'Spam Complaint', + value: 'spamComplaint', + description: 'Trigger on spam complaint.', + }, + { + name: 'Subscription Change', + value: 'subscriptionChange', + description: 'Trigger on subscription change.', + }, + ], + default: [], + required: true, + description: 'Webhook events that will be enabled for that endpoint.', + }, + { + displayName: 'First Open', + name: 'firstOpen', + description: 'Only fires on first open for event "Open".', + type: 'boolean', + default: false, + displayOptions: { + show: { + events: [ + 'open', + ], + }, + }, + }, + { + displayName: 'Include Content', + name: 'includeContent', + description: 'Includes message content for events "Bounce" and "Spam Complaint".', + type: 'boolean', + default: false, + displayOptions: { + show: { + events: [ + 'bounce', + 'spamComplaint', + ], + }, + }, + }, + ], + + }; + + // @ts-ignore (because of request) + webhookMethods = { + default: { + async checkExists(this: IHookFunctions): Promise { + const webhookData = this.getWorkflowStaticData('node'); + const webhookUrl = this.getNodeWebhookUrl('default'); + const events = this.getNodeParameter('events') as string[]; + if (this.getNodeParameter('includeContent') as boolean) { + events.push('includeContent'); + } + if (this.getNodeParameter('firstOpen') as boolean) { + events.push('firstOpen'); + } + + // Get all webhooks + const endpoint = `/webhooks`; + + const responseData = await postmarkApiRequest.call(this, 'GET', endpoint, {}); + + // No webhooks exist + if (responseData.Webhooks.length === 0) { + return false; + } + + // If webhooks exist, check if any match current settings + for (const webhook of responseData.Webhooks) { + if (webhook.Url === webhookUrl && eventExists(events, convertTriggerObjectToStringArray(webhook))) { + webhookData.webhookId = webhook.ID; + // webhook identical to current settings. re-assign webhook id to found webhook. + return true; + } + } + + return false; + }, + async create(this: IHookFunctions): Promise { + const webhookUrl = this.getNodeWebhookUrl('default'); + + const endpoint = `/webhooks`; + + // tslint:disable-next-line: no-any + const body : any = { + Url: webhookUrl, + Triggers: { + Open:{ + Enabled: false, + PostFirstOpenOnly: false + }, + Click:{ + Enabled: false + }, + Delivery:{ + Enabled: false + }, + Bounce:{ + Enabled: false, + IncludeContent: false + }, + SpamComplaint:{ + Enabled: false, + IncludeContent: false + }, + SubscriptionChange: { + Enabled: false + } + } + }; + + const events = this.getNodeParameter('events') as string[]; + + if (events.includes('open')) { + body.Triggers.Open.Enabled = true; + body.Triggers.Open.PostFirstOpenOnly = this.getNodeParameter('firstOpen') as boolean; + } + if (events.includes('click')) { + body.Triggers.Click.Enabled = true; + } + if (events.includes('delivery')) { + body.Triggers.Delivery.Enabled = true; + } + if (events.includes('bounce')) { + body.Triggers.Bounce.Enabled = true; + body.Triggers.Bounce.IncludeContent = this.getNodeParameter('includeContent') as boolean; + } + if (events.includes('spamComplaint')) { + body.Triggers.SpamComplaint.Enabled = true; + body.Triggers.SpamComplaint.IncludeContent = this.getNodeParameter('includeContent') as boolean; + } + if (events.includes('subscriptionChange')) { + body.Triggers.SubscriptionChange.Enabled = true; + } + + const responseData = await postmarkApiRequest.call(this, 'POST', endpoint, body); + + if (responseData.ID === undefined) { + // Required data is missing so was not successful + return false; + } + + const webhookData = this.getWorkflowStaticData('node'); + webhookData.webhookId = responseData.ID as string; + + return true; + }, + async delete(this: IHookFunctions): Promise { + const webhookData = this.getWorkflowStaticData('node'); + + if (webhookData.webhookId !== undefined) { + const endpoint = `/webhooks/${webhookData.webhookId}`; + const body = {}; + + try { + await postmarkApiRequest.call(this, 'DELETE', endpoint, body); + } catch (e) { + return false; + } + + // Remove from the static workflow data so that it is clear + // that no webhooks are registred anymore + delete webhookData.webhookId; + delete webhookData.webhookEvents; + } + + return true; + }, + }, + }; + + async webhook(this: IWebhookFunctions): Promise { + const req = this.getRequestObject(); + return { + workflowData: [ + this.helpers.returnJsonArray(req.body) + ], + }; + } +} diff --git a/packages/nodes-base/nodes/Postmark/postmark.png b/packages/nodes-base/nodes/Postmark/postmark.png new file mode 100644 index 0000000000000000000000000000000000000000..6298b4ae94bdbd1b930a5bdd870200fa9f8f157a GIT binary patch literal 1297 zcmV+s1@8KZP)GpMpc|zYbfeUQZj@Tk zYlwi><%<$P6JYrvE(Ena8Xy!MunS^D_jD*dWl}+oHR-F7Mm3bno_DTVSD@AZL>0w2}~` zrk0DWFvSwaFL>iqZQuQzdF1}wGY4h{HssYQYdn3ziRcv8!j{v6FjWy(sCD2qBqT@( z6^1K$|M1bC^E2M7&z~ReTZYyaY}URApbAf(>HOr2t|%hO#hm}+u}mo>K~;2jl}2}5 z^8BiNcU&o&v(v#p=Yo7b5UC(K=k`Ci@Y-{e>9!IS@$)1BG?auIE#nBrPG?_yV|Zc7 zC*d5oZ(Vxl^@&Vp@d|^|DRax-v9XR14zK&|c&1WIltB<4eCgbyyXRqRNbV%*K~*4H zz5IkFD%q`YsuVauRlXBKbZ4W7M#GVz(!qE6>sZE!lA14gUw)t6bI(#+5Hfa-)TOyp zpN-cXSsg{^Fg&>O^y70U-fqhmeWi-v&r|8CX@6u>82@~Y?1)MzoZGo=`SzjwA16E^ zNG#;M@yYg);T6QI`e?BCpgI7Vj&OKm`1@a#gJCE$vvKQvSxqoZhMH-&M5VVoMO!x)w%w86JW%w!2oB05OY}NJ zJBKX;`8QuVn@LyvGzk%U2EMPpXCV#>xJvtD?O{gUp%pY9y0fKBM_3g>LJ2CM@vYo- zRQL2yRfPlo)0h>|I&IVdt!=T!=@x>%Zk?jW9hp=~HXs!w2oh8fq^aymLa9O(h=B+c z0O9niS=kh5K=AiO=E%2Qk)r_fi(aAVl|2x}o}csI`>5X!EEIv~9@{%VRHO5}5ztCv zays?lk)ALV03<~!X+UyzA^7<7?()!dDjMB+X=r2fp#gw|F>r3xV^lX17*lr35VN|f zs;3f8LjVLbb^Ahj zxpXwWdO!ht1L|*F-9jC)$!bA2N-gL{sRi9AwV)fNn-cn8xOMsu?|pBW00000NkvXX Hu0mjfX*6rT literal 0 HcmV?d00001 diff --git a/packages/nodes-base/nodes/QuestDb/QuestDb.node.ts b/packages/nodes-base/nodes/QuestDb/QuestDb.node.ts new file mode 100644 index 0000000000..b3ae15efee --- /dev/null +++ b/packages/nodes-base/nodes/QuestDb/QuestDb.node.ts @@ -0,0 +1,246 @@ +import { IExecuteFunctions } from 'n8n-core'; +import { IDataObject, INodeExecutionData, INodeType, INodeTypeDescription } from 'n8n-workflow'; + +import * as pgPromise from 'pg-promise'; + +import { pgInsert, pgQuery, pgUpdate } from '../Postgres/Postgres.node.functions'; +import { table } from 'console'; + +export class QuestDb implements INodeType { + description: INodeTypeDescription = { + displayName: 'QuestDB', + name: 'questDb', + icon: 'file:questdb.png', + group: ['input'], + version: 1, + description: 'Gets, add and update data in QuestDB.', + defaults: { + name: 'QuestDB', + color: '#2C4A79', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'questDb', + required: true, + }, + ], + properties: [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + options: [ + { + name: 'Execute Query', + value: 'executeQuery', + description: 'Executes a SQL query.', + }, + { + name: 'Insert', + value: 'insert', + description: 'Insert rows in database.', + } + ], + default: 'insert', + description: 'The operation to perform.', + }, + + // ---------------------------------- + // executeQuery + // ---------------------------------- + { + displayName: 'Query', + name: 'query', + type: 'string', + typeOptions: { + rows: 5, + }, + displayOptions: { + show: { + operation: ['executeQuery'], + }, + }, + default: '', + placeholder: 'SELECT id, name FROM product WHERE id < 40', + required: true, + description: 'The SQL query to execute.', + }, + + // ---------------------------------- + // insert + // ---------------------------------- + { + displayName: 'Schema', + name: 'schema', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: 'public', + required: true, + description: 'Name of the schema the table belongs to', + }, + { + displayName: 'Table', + name: 'table', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: '', + required: true, + description: 'Name of the table in which to insert data to.', + }, + { + displayName: 'Columns', + name: 'columns', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: '', + placeholder: 'id,name,description', + description: + 'Comma separated list of the properties which should used as columns for the new rows.', + }, + { + displayName: 'Return Fields', + name: 'returnFields', + type: 'string', + displayOptions: { + show: { + operation: ['insert'], + }, + }, + default: '*', + description: 'Comma separated list of the fields that the operation will return', + }, + + // ---------------------------------- + // update + // ---------------------------------- + // { + // displayName: 'Table', + // name: 'table', + // type: 'string', + // displayOptions: { + // show: { + // operation: ['update'], + // }, + // }, + // default: '', + // required: true, + // description: 'Name of the table in which to update data in', + // }, + // { + // displayName: 'Update Key', + // name: 'updateKey', + // type: 'string', + // displayOptions: { + // show: { + // operation: ['update'], + // }, + // }, + // default: 'id', + // required: true, + // description: + // 'Name of the property which decides which rows in the database should be updated. Normally that would be "id".', + // }, + // { + // displayName: 'Columns', + // name: 'columns', + // type: 'string', + // displayOptions: { + // show: { + // operation: ['update'], + // }, + // }, + // default: '', + // placeholder: 'name,description', + // description: + // 'Comma separated list of the properties which should used as columns for rows to update.', + // }, + ], + }; + + async execute(this: IExecuteFunctions): Promise { + const credentials = this.getCredentials('questDb'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + const pgp = pgPromise(); + + const config = { + host: credentials.host as string, + port: credentials.port as number, + database: credentials.database as string, + user: credentials.user as string, + password: credentials.password as string, + ssl: !['disable', undefined].includes(credentials.ssl as string | undefined), + sslmode: (credentials.ssl as string) || 'disable', + }; + + const db = pgp(config); + + let returnItems = []; + + const items = this.getInputData(); + const operation = this.getNodeParameter('operation', 0) as string; + + if (operation === 'executeQuery') { + // ---------------------------------- + // executeQuery + // ---------------------------------- + + const queryResult = await pgQuery(this.getNodeParameter, pgp, db, items); + + returnItems = this.helpers.returnJsonArray(queryResult as IDataObject[]); + } else if (operation === 'insert') { + // ---------------------------------- + // insert + // ---------------------------------- + const tableName = this.getNodeParameter('table', 0) as string; + const returnFields = this.getNodeParameter('returnFields', 0) as string; + + let queries : string[] = []; + items.map(item => { + let columns = Object.keys(item.json); + + let values : string = columns.map((col : string) => { + if (typeof item.json[col] === 'string') { + return `\'${item.json[col]}\'`; + } else { + return item.json[col]; + } + }).join(','); + + let query = `INSERT INTO ${tableName} (${columns.join(',')}) VALUES (${values});`; + queries.push(query); + }); + + await db.any(pgp.helpers.concat(queries)); + + let returnedItems = await db.any(`SELECT ${returnFields} from ${tableName}`); + + returnItems = this.helpers.returnJsonArray(returnedItems as IDataObject[]); + } else { + await pgp.end(); + throw new Error(`The operation "${operation}" is not supported!`); + } + + // Close the connection + await pgp.end(); + + return this.prepareOutputData(returnItems); + } +} diff --git a/packages/nodes-base/nodes/QuestDb/questdb.png b/packages/nodes-base/nodes/QuestDb/questdb.png new file mode 100644 index 0000000000000000000000000000000000000000..5be1906e5d9d408257f4d2831489dc310126ecaf GIT binary patch literal 2835 zcmV+u3+(iXP)WmlwQHt2?&Hm}E*bBRV0G7q!a1QW~002>n0CA_HQ;Pte%+=%0+hY^xeFa~dI{<2- z0E4^TWe@6l1$?Vx)>jbz=+>&yllszj{n%Mqt=0g7wg8R7_`Y%gl*a&et>SSDUz
e!5NWn-uMq6!fwT0E)wXyHWw6(*U5(0CTkfZ?KolQIN+`0G!PLkH@dt zSn7@z0GZ2z!c>UCPw=7>@um@l$5^1zREfk>@~jR3wcG%;*8+mP0eZTU%2Rr`OXYqT z_rMSUl*gylR*uS6o6lA4eirku3--JO|Ns7z(OZ_ySNOvL0I%BsrqlqG%Z$TK;cyxN z%jf{A*Z_vW0Arzxz-oTHR`QS(0KVS%cjBr2tlr|GiCWv@ZI$DEFQaAbzlsG9Ib`005J8QchC<0s{mC0{#g8{{H^` z{tW*9{3QPVfJFV+7#05geE$8ftY=zMJt`m){{8&%*v-bVdQvq0{{8xVSvUUu{qx?k ztcZVQME?H%{{H^{{rvRt@$Ki+&8D4|hihL&C;t8Y{OID)&BDODv7MZnmxF3TJ1+kI z{{8gr?9$A}z`mWFeraJTB>nT<*wxj?#>B6mYDSJr*%<%;2RKPYK~z}7)z@b{RdE;x z@c+5zlGP=nP&Oe-T0+{|d+)vX-h1z*G$mOjg`%h^4Xc65$V!sX-t$Gz^S@5_TsIuO z>-VBhiSPYA&;OirFY-TyVOX)472_Wa^Un$(<^Ihw|EjRoBb*(F4s~>N9${UBK*VCE zdJHPo&NBuqt$CZ~SxWB#GuF*x@fDbAF*eSoOK%rvgoK3D!#q(_1FiP}$9dROpu+;= z*bo#A4ULmD8XDk%bqy@j5ilSlXgP!(*04v0My*;tK1a&p;{#dZLb$gy;o%nm1FD|dHKeB55SFRZajXf<5kMj%<9wxwi;MII3#lhiDkWtA z%*Ryj*qHV>S<43*U*G+__@YHAkZPv9aIADZmRL6|hM~f}9IXhW-v0j2bFA4q9w=~ENeZa+%mP~xT|iW2>j zX))(qZw~VSW3p@Q`Z*&ZbN24pYGUI0s{4MBxIMjCN7%nXLyJ%T{P^L+J4kceF|S^_ zZd<#7$Wmj@>dmgNy1k)NJvD@!0aA3VCl7=)qFJ$g`Gg7U;eJ<=1-@y+>d`2LAE9e{ zW?I3HYRE?nUsB?~6k7WxbnA{1uBrDt*sG8rBOjn_c7N+$6p6##9tsYlc&qZm&{S{> zt@%bPWi+%Q@I40QHzYJD{lH2+VACR^J;^}cF|@R_tj)!ptwd5H;uRl!y?;)Izl+F_ zvlc|ehxD{)jvrT6j>#KTSwp-5G<+k~=3=3y_Ja9R?^m>2Sx&9r#~yBQ+Z$77>fUW1g{1h=@Pgapjm3htbJh zCPAo*O2csLlJSp^c^+-gho(TG6Nk@VicabktylHC1RYC6THZZy%=6GBB8wrc2n(G_ zx~03MzOah{j@~}!AV9n&!HRG)ER?Iek`W4-WqKg=&`LI&r4ya(OwcXei?fK5FvsGk z>H&me&1FzWErgPzgD&0(>If?mBu&hgLczRk>(R;1MBlo2F4wa zlbve~yB4(ReyJSPSOJ2`1Vb&e>!<>B+4CqsgyA5%qUu5(2pvL*`3scnLX?C+LjZ!w z01D(m9c56ErLab3+=>DNd81is0VLhgjakA@ZDMNKiUNaqkc-xzWuI$H7-5G7E25Ky z!tu-QHUF3sc>K6+d>U1KSx0e`1;@%DCDQh_@`>}w(YJ&x30IWOO&02B^ao(bc-O?CjEAxDElubA^7_q23eQZ${-1*IykqQ{zCq1fk5c#z>1S}7WDk{eK|$|sQ~ z-mqAR51}-@D?nHYhD)}r^Z~%YhH_N@6gn#pxpz&=gGVGBT&}L}5;(X@kL(^gv{39> zKY57VIjZcT4N~q(wqgn2%v4pmYbe&w?>U~DOd4(nm2fzef(8Ly(OgZ(d+-MHdw6xG z932LtDn3NDE!)weTF z%L6G4B%l(*^bkSl=W?AMTU!Ybu3B)U8`LG0}kN?Nt)ar>pFrZ#{elleI6?t^;)G6x_P6&3m6aN!C0UBCMyg;K;6f>QfT zR5VpRa)6;uaH!P5LKISWFeu+CA;B(7IX#`0s;f*tDjAH+rV7VM9m;Ty`XhZS0Qgde z`~>4PC?y@QjUiSt56*@%QU)Dh{Lc35+_~qXMQ~{7fYjH#oHV?DLcU#07E)dj1@saS zO}dN9-3Je(%>ABYn>Bm?zOe91t5)jLLXfFMPEsNpS0yBL8WodOknR=cpM6&==c5V=Jp5+>6=RwKK_!~{eiN3ot0JKI1NS!i_qGZ?ssV)oC3i6z4)6eB9I+z8p7*w(8{3(Ax$IU|A6YJVudXT{^7l z|H;_6%WV7+iT-J~zWP&*IE5d;cvC6<9t7FwK6`q*=@Pnc^CnFJ;S|BY$zUsrK{b~D l+T@>t7-v);Q7r!d<~Qs#0@pWKjv4>}002ovPDHLkV1jqrjhFxc literal 0 HcmV?d00001 diff --git a/packages/nodes-base/nodes/Redis/Redis.node.ts b/packages/nodes-base/nodes/Redis/Redis.node.ts index 68b7401205..12263b1d64 100644 --- a/packages/nodes-base/nodes/Redis/Redis.node.ts +++ b/packages/nodes-base/nodes/Redis/Redis.node.ts @@ -402,6 +402,7 @@ export class Redis implements INodeType { } else if (type === 'hash') { const clientHset = util.promisify(client.hset).bind(client); for (const key of Object.keys(value)) { + // @ts-ignore await clientHset(keyName, key, (value as IDataObject)[key]!.toString()); } } else if (type === 'list') { diff --git a/packages/nodes-base/nodes/Rocketchat/Rocketchat.node.ts b/packages/nodes-base/nodes/Rocketchat/Rocketchat.node.ts index e83a3afbfe..65dd1a6820 100644 --- a/packages/nodes-base/nodes/Rocketchat/Rocketchat.node.ts +++ b/packages/nodes-base/nodes/Rocketchat/Rocketchat.node.ts @@ -48,15 +48,15 @@ interface IPostMessageBody { export class Rocketchat implements INodeType { description: INodeTypeDescription = { - displayName: 'Rocketchat', + displayName: 'RocketChat', name: 'rocketchat', icon: 'file:rocketchat.png', group: ['output'], version: 1, subtitle: '={{$parameter["resource"] + ": " + $parameter["operation"]}}', - description: 'Consume Rocketchat API', + description: 'Consume RocketChat API', defaults: { - name: 'Rocketchat', + name: 'RocketChat', color: '#c02428', }, inputs: ['main'], diff --git a/packages/nodes-base/nodes/Salesforce/GenericFunctions.ts b/packages/nodes-base/nodes/Salesforce/GenericFunctions.ts index 648735feb2..4c81432238 100644 --- a/packages/nodes-base/nodes/Salesforce/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Salesforce/GenericFunctions.ts @@ -30,7 +30,7 @@ export async function salesforceApiRequest(this: IExecuteFunctions | IExecuteSin } } -export async function salesforceApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, propertyName: string ,method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise { // tslint:disable-line:no-any +export async function salesforceApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, propertyName: string, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise { // tslint:disable-line:no-any const returnData: IDataObject[] = []; diff --git a/packages/nodes-base/nodes/Signl4/GenericFunctions.ts b/packages/nodes-base/nodes/Signl4/GenericFunctions.ts new file mode 100644 index 0000000000..5281ae8c25 --- /dev/null +++ b/packages/nodes-base/nodes/Signl4/GenericFunctions.ts @@ -0,0 +1,52 @@ +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + IDataObject, +} from 'n8n-workflow'; + +import { + OptionsWithUri, + } from 'request'; + +/** + * Make an API request to SIGNL4 + * + * @param {IHookFunctions | IExecuteFunctions} this + * @param {object} message + * @returns {Promise} + */ + +export async function SIGNL4ApiRequest(this: IExecuteFunctions, method: string, resource: string, body: any = {}, query: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise { // tslint:disable-line:no-any + + let options: OptionsWithUri = { + headers: { + 'Accept': '*/*', + }, + method, + body, + qs: query, + uri: uri || ``, + json: true, + }; + + if (!Object.keys(body).length) { + delete options.body; + } + if (!Object.keys(query).length) { + delete options.qs; + } + options = Object.assign({}, options, option); + + try { + return await this.helpers.request!(options); + } catch (error) { + + if (error.response && error.response.body && error.response.body.details) { + throw new Error(`SIGNL4 error response [${error.statusCode}]: ${error.response.body.details}`); + } + + throw error; + } +} diff --git a/packages/nodes-base/nodes/Signl4/Signl4.node.ts b/packages/nodes-base/nodes/Signl4/Signl4.node.ts new file mode 100644 index 0000000000..29d3917cf6 --- /dev/null +++ b/packages/nodes-base/nodes/Signl4/Signl4.node.ts @@ -0,0 +1,325 @@ +import { + IExecuteFunctions, + BINARY_ENCODING, +} from 'n8n-core'; + +import { + IDataObject, + INodeExecutionData, + INodeType, + INodeTypeDescription, + IBinaryKeyData, +} from 'n8n-workflow'; + +import { + SIGNL4ApiRequest, +} from './GenericFunctions'; + +export class Signl4 implements INodeType { + description: INodeTypeDescription = { + displayName: 'SIGNL4', + name: 'signl4', + icon: 'file:signl4.png', + group: ['transform'], + version: 1, + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + description: 'Consume SIGNL4 API.', + defaults: { + name: 'SIGNL4', + color: '#53afe8', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'signl4Api', + required: true, + }, + ], + properties: [ + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: 'Alert', + value: 'alert', + }, + ], + default: 'alert', + description: 'The resource to operate on.', + }, + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'alert', + ], + }, + }, + options: [ + { + name: 'Send', + value: 'send', + description: 'Send an alert.', + }, + ], + default: 'send', + description: 'The operation to perform.', + }, + { + displayName: 'Message', + name: 'message', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', + required: false, + displayOptions: { + show: { + operation: [ + 'send', + ], + resource: [ + 'alert', + ], + }, + }, + description: 'A more detailed description for the alert.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + displayOptions: { + show: { + operation: [ + 'send', + ], + resource: [ + 'alert', + ], + }, + }, + default: {}, + options: [ + { + displayName: 'Alerting Scenario', + name: 'alertingScenario', + type: 'options', + options: [ + { + name: 'Single ACK', + value: 'single_ack', + description: 'In case only one person needs to confirm this Signl.' + }, + { + name: 'Multi ACK', + value: 'multi_ack', + description: 'in case this alert must be confirmed by the number of people who are on duty at the time this Singl is raised', + }, + ], + default: 'single_ack', + required: false, + }, + { + displayName: 'Attachments', + name: 'attachmentsUi', + placeholder: 'Add Attachments', + type: 'fixedCollection', + typeOptions: { + multipleValues: false, + }, + options: [ + { + name: 'attachmentsBinary', + displayName: 'Attachments Binary', + values: [ + { + displayName: 'Property Name', + name: 'property', + type: 'string', + placeholder: 'data', + default: '', + description: 'Name of the binary properties which contain data which should be added as attachment', + }, + ], + }, + ], + default: {}, + }, + { + displayName: 'External ID', + name: 'externalId', + type: 'string', + default: '', + description: `If the event originates from a record in a 3rd party system, use this parameter to pass
+ the unique ID of that record. That ID will be communicated in outbound webhook notifications from SIGNL4,
+ which is great for correlation/synchronization of that record with the alert.`, + }, + { + displayName: 'Filtering', + name: 'filtering', + type: 'boolean', + default: 'false', + description: `Specify a boolean value of true or false to apply event filtering for this event, or not.
+ If set to true, the event will only trigger a notification to the team, if it contains at least one keyword
+ from one of your services and system categories (i.e. it is whitelisted)`, + }, + { + displayName: 'Location', + name: 'locationFieldsUi', + type: 'fixedCollection', + placeholder: 'Add Location', + default: {}, + description: 'Transmit location information (\'latitude, longitude\') with your event and display a map in the mobile app.', + options: [ + { + name: 'locationFieldsValues', + displayName: 'Location', + values: [ + { + displayName: 'Latitude', + name: 'latitude', + type: 'string', + required: true, + description: 'The location latitude.', + default: '', + }, + { + displayName: 'Longitude', + name: 'longitude', + type: 'string', + required: true, + description: 'The location longitude.', + default: '', + }, + ], + } + ], + }, + { + displayName: 'Service', + name: 'service', + type: 'string', + default: '', + description: 'Assigns the alert to the service/system category with the specified name.', + }, + { + displayName: 'Title', + name: 'title', + type: 'string', + default: '', + }, + ], + }, + ], + }; + + async execute(this: IExecuteFunctions): Promise { + const items = this.getInputData(); + const returnData: IDataObject[] = []; + const length = (items.length as unknown) as number; + const qs: IDataObject = {}; + let responseData; + const resource = this.getNodeParameter('resource', 0) as string; + const operation = this.getNodeParameter('operation', 0) as string; + for (let i = 0; i < length; i++) { + if (resource === 'alert') { + //https://connect.signl4.com/webhook/docs/index.html + if (operation === 'send') { + const message = this.getNodeParameter('message', i) as string; + const additionalFields = this.getNodeParameter('additionalFields',i) as IDataObject; + + const data: IDataObject = { + message, + }; + + if (additionalFields.alertingScenario) { + data['X-S4-AlertingScenario'] = additionalFields.alertingScenario as string; + } + if (additionalFields.externalId) { + data['X-S4-ExternalID'] = additionalFields.externalId as string; + } + if (additionalFields.filtering) { + data['X-S4-Filtering'] = (additionalFields.filtering as boolean).toString(); + } + if (additionalFields.locationFieldsUi) { + const locationUi = (additionalFields.locationFieldsUi as IDataObject).locationFieldsValues as IDataObject; + if (locationUi) { + data['X-S4-Location'] = `${locationUi.latitude},${locationUi.longitude}`; + } + } + if (additionalFields.service) { + data['X-S4-Service'] = additionalFields.service as string; + } + if (additionalFields.title) { + data['title'] = additionalFields.title as string; + } + + const attachments = additionalFields.attachmentsUi as IDataObject; + + if (attachments) { + if (attachments.attachmentsBinary && items[i].binary) { + + const propertyName = (attachments.attachmentsBinary as IDataObject).property as string; + + const binaryProperty = (items[i].binary as IBinaryKeyData)[propertyName]; + + if (binaryProperty) { + + const supportedFileExtension = ['png', 'jpg', 'txt']; + + if (!supportedFileExtension.includes(binaryProperty.fileExtension as string)) { + + throw new Error(`Invalid extension, just ${supportedFileExtension.join(',')} are supported}`); + } + + data['file'] = { + value: Buffer.from(binaryProperty.data, BINARY_ENCODING), + options: { + filename: binaryProperty.fileName, + contentType: binaryProperty.mimeType, + }, + }; + + } else { + throw new Error(`Binary property ${propertyName} does not exist on input`); + } + } + } + + const credentials = this.getCredentials('signl4Api'); + + const endpoint = `https://connect.signl4.com/webhook/${credentials?.teamSecret}`; + + responseData = await SIGNL4ApiRequest.call( + this, + 'POST', + '', + {}, + {}, + endpoint, + { + formData: { + ...data, + }, + }, + ); + } + } + } + if (Array.isArray(responseData)) { + returnData.push.apply(returnData, responseData as IDataObject[]); + } else if (responseData !== undefined) { + returnData.push(responseData as IDataObject); + } + return [this.helpers.returnJsonArray(returnData)]; + } +} diff --git a/packages/nodes-base/nodes/Signl4/signl4.png b/packages/nodes-base/nodes/Signl4/signl4.png new file mode 100644 index 0000000000000000000000000000000000000000..205c94a5d2ba0e8d25d7b792050e341a8c8ab29b GIT binary patch literal 3045 zcmVPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!~g&e!~vBn4jTXf00v@9M??Vs0RI60 zpuMM)00007bV*G`2jK|@3RSOzj|T*UUHjarW6~ukZWz-rwG>1;C@6 zG_Zs8q`^r?*s`pX%cV)!S{7kV{zl9%H+K5}q|r!(MT#Ebr;U02QR*kN1U+VypG_O` z?-kl2+(^#mABhvBS_G7u=K*t%tU_XS{&53QUiGeN^WG3|Nmzu$BP1z_u`uM`#~+(=er;sMzdNv2{z2hEyhs&bN|=T6|#E^Sv8K{6@TD9jgV z=3mMkT~j7X&^nK;lHw%18JJ)?!Bl0D7wHlk%H6}c&E&Yla-4;PHEt&$E6Zg_CQEW6yDACvr7W!J@bjyf zmjcv=kBzoOV1^c)q(#Td9!845NXf%+(I-F7I+2z_W=V_if|301(Uh>UE=6vvxhk@< zPLlZO!X&K8NVYcA;<6In3lxFHU3h?blJ7p5l{Z)5-$EGLi^uB~CMwrMt?4 zp;b@MSXkc)Y|Jw4%3#wMzKQG=pNEz1;G679y>apKDisv=JdVNp@5JDdVGQPh19_63 z@rjSp;&O4{z5Uf(R!)=Xwi|B+K5;$9<2ly*J3yv7h4NDm;_dtHL?u6=p)L#LYwZ-t zMzI5T*4*tdge~;Sm1)tnB)z`V!lv#tHs5>~vR8f?R)S9 zd+AT8R?B9gl9-j+wft?0B*Qt}*}EFsfADJ@+V(l*y#(s2&%YL{&pyj2PFq=;ik#iM zDf-qLkvQ+u#tNgqz zRQA2Z71?Tts{FoT#6|JIn++Omjmm-7=+YWxw4bIfZS=;JV*?jdvvp{n^bY}ypa%EB z8~T@8wTFp=n0)DJ^R8BDe|7eWOKsv@eDe3yp}y7{o)q-#Bb*9+F&J~ZvcRQ7D9n@8 zI3gVcM0SQj!W7w$PL(nJ&>eip$e|V7I*O0pjo~9BnA8D+qBvXOq!ekkS~jaOGAlg2 zi-Xe0mH?m6JoON2`(F+!qQQxAAD*X#*)7Se(kz5WLv#LRrA|-I=peF%!-${DebdoC z+yt~(<jyH;su(NYc6*Xv66o4=aBWVUAB1p2~Er;sWx;pp@Qv04md|)%|Tt79%Mq1Y0 z8r;Ksk-z_2IPlodF*xHgoP>#~kCuGG(^U)knq^#E3s#-tR*IN;_F>eP#gJQn77`ST5mV*xKI8{q#b~i&4hu(URgqN;t%Jib_#?diRXI_!k!Cw~uIz>rDR^g)DUC@12iRQ|a^c2a7-~>r4Ras;U!9u93 zpgGn(&al!=2n(T=McNN7{aX)_HWvbPb93Ee$oh&=TS0@@Hm3RMU-3xZz3C{hzRX4< zE6c8wbp;YmH2svuK1-T}8?7yCDkc_DrK*?vhttb!XS7;)i6@e>W|7QFs%PFZcbQ`hjL+_wX}()DgM=uQh&>m==m&RimYthm8te|k(2_Yh%nlcsO?HwSFk#k zAS{T3h=kS-#aLZrRc6XxqZ~nDwjnKY%$tyusmdZ3lI8D;k`-DK7Q{njLQ+aY1t?V= ze<^-fif{#ynU$~{q*4lhmxTVw#xyeD@cTSgSREb7R^K)73F*TPd5Zq@44jUED?S5f z-Fb|SZB+iV7h}&nhVlKctHmriBSBsW)A@)elGt?74y3kS2DhUZ_2Lxr|9lcd|9ArR zGB@;NfR$;J@O+4@6Hj2vP2Wa+#|;?qGKP$K#)oNC;61ksL%;k!Y7--ilADjyw_k$3 z8}Go#nyqHun-|%i)``@}n>c#k_b~b5-_19cgXI%u82ORg?!nMUuVd)9NEaNG{nllNnyxh+tMi7l73-@XARR){KgwvYR26kSoXU8@%KGb=oMx_tx8wGTVn z%NPA)Y7|-Y)^aJSmI|DnQMBu!K0Vg7FC#qfmL~P@M(x8@f94{dg$S}Nm#*==Tc6|y z+eAG-j_Uqbg3>}Ls3^YroH9X83$R`3m1oR*Q9+lE{)0*Zg}?o_y#cb#%o7j5E=)G` zFz<(L%Fpcbt=0zInF*Bl{1LV-2aWc#ESJ``OW~m(qx{-#7F4-7%6s=<`hg$9Q5@RP z$9(a|hcNl8+qoVsJykrnhSB@J1AF?Y|LKV0B$M%-%tnUgR#AN6am3E}5Muow2x=Q3 ztG%%Yqd&SCvEsO~#!`@#>+k#;B&W>$JozqMRoTs#A1%&5EWJ~ zn~uJ=hv1tvImuZUAbrU-h;R5Hd$dtK_y&rMgsLw;iG<}wx`)zMQ}14j4Cs=qJksLoshdtS$CfcL_2Ig% zf1G5W7W4YQHxAFC$9##G>*_dW!tW<6Yg>9h!|FcCENpe>PPz06jgxN<_vA9CT>3} + */ +export async function spotifyApiRequest(this: IHookFunctions | IExecuteFunctions, + method: string, endpoint: string, body: object, query?: object, uri?: string): Promise { // tslint:disable-line:no-any + + const options: OptionsWithUri = { + method, + headers: { + 'User-Agent': 'n8n', + 'Content-Type': 'text/plain', + 'Accept': ' application/json', + }, + body, + qs: query, + uri: uri || `https://api.spotify.com/v1${endpoint}`, + json: true + }; + + try { + const credentials = this.getCredentials('spotifyOAuth2Api'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + if (Object.keys(body).length === 0) { + delete options.body; + } + + return await this.helpers.requestOAuth2.call(this, 'spotifyOAuth2Api', options); + } catch (error) { + if (error.statusCode === 401) { + // Return a clear error + throw new Error('The Spotify credentials are not valid!'); + } + + if (error.error && error.error.error && error.error.error.message) { + // Try to return the error prettier + throw new Error(`Spotify error response [${error.error.error.status}]: ${error.error.error.message}`); + } + + // If that data does not exist for some reason return the actual error + throw error; + } +} + +export async function spotifyApiRequestAllItems(this: IHookFunctions | IExecuteFunctions, + propertyName: string, method: string, endpoint: string, body: object, query?: object): Promise { // tslint:disable-line:no-any + + const returnData: IDataObject[] = []; + + let responseData; + + let uri: string | undefined; + + do { + responseData = await spotifyApiRequest.call(this, method, endpoint, body, query, uri); + returnData.push.apply(returnData, responseData[propertyName]); + uri = responseData.next; + + } while ( + responseData['next'] !== null + ); + + return returnData; +} diff --git a/packages/nodes-base/nodes/Spotify/Spotify.node.ts b/packages/nodes-base/nodes/Spotify/Spotify.node.ts new file mode 100644 index 0000000000..797020c392 --- /dev/null +++ b/packages/nodes-base/nodes/Spotify/Spotify.node.ts @@ -0,0 +1,816 @@ +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + IDataObject, + INodeExecutionData, + INodeType, + INodeTypeDescription, +} from 'n8n-workflow'; + +import { + spotifyApiRequest, + spotifyApiRequestAllItems, +} from './GenericFunctions'; + +export class Spotify implements INodeType { + description: INodeTypeDescription = { + displayName: 'Spotify', + name: 'spotify', + icon: 'file:spotify.png', + group: ['input'], + version: 1, + description: 'Access public song data via the Spotify API.', + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + defaults: { + name: 'Spotify', + color: '#1DB954', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'spotifyOAuth2Api', + required: true, + }, + ], + properties: [ + // ---------------------------------------------------------- + // Resource to Operate on + // Player, Album, Artisits, Playlists, Tracks + // ---------------------------------------------------------- + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: 'Album', + value: 'album', + }, + { + name: 'Artist', + value: 'artist', + }, + { + name: 'Player', + value: 'player', + }, + { + name: 'Playlist', + value: 'playlist', + }, + { + name: 'Track', + value: 'track', + }, + ], + default: 'player', + description: 'The resource to operate on.', + }, + // -------------------------------------------------------------------------------------------------------- + // Player Operations + // Pause, Play, Get Recently Played, Get Currently Playing, Next Song, Previous Song, Add to Queue + // -------------------------------------------------------------------------------------------------------- + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'player', + ], + }, + }, + options: [ + { + name: 'Add Song to Queue', + value: 'addSongToQueue', + description: 'Add a song to your queue.' + }, + { + name: 'Currently Playing', + value: 'currentlyPlaying', + description: 'Get your currently playing track.' + }, + { + name: 'Next Song', + value: 'nextSong', + description: 'Skip to your next track.' + }, + { + name: 'Pause', + value: 'pause', + description: 'Pause your music.', + }, + { + name: 'Previous Song', + value: 'previousSong', + description: 'Skip to your previous song.' + }, + { + name: 'Recently Played', + value: 'recentlyPlayed', + description: 'Get your recently played tracks.' + }, + { + name: 'Start Music', + value: 'startMusic', + description: 'Start playing a playlist, artist, or album.' + }, + ], + default: 'addSongToQueue', + description: 'The operation to perform.', + }, + { + displayName: 'Resource ID', + name: 'id', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'player' + ], + operation: [ + 'startMusic', + ], + }, + }, + placeholder: 'spotify:album:1YZ3k65Mqw3G8FzYlW1mmp', + description: `Enter a playlist, artist, or album URI or ID.`, + }, + { + displayName: 'Track ID', + name: 'id', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'player' + ], + operation: [ + 'addSongToQueue', + ], + }, + }, + placeholder: 'spotify:track:0xE4LEFzSNGsz1F6kvXsHU', + description: `Enter a track URI or ID.`, + }, + // ----------------------------------------------- + // Album Operations + // Get an Album, Get an Album's Tracks + // ----------------------------------------------- + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'album', + ], + }, + }, + options: [ + { + name: 'Get', + value: 'get', + description: 'Get an album by URI or ID.', + }, + { + name: `Get Tracks`, + value: 'getTracks', + description: `Get an album's tracks by URI or ID.`, + }, + ], + default: 'get', + description: 'The operation to perform.', + }, + { + displayName: 'Album ID', + name: 'id', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'album', + ], + }, + }, + placeholder: 'spotify:album:1YZ3k65Mqw3G8FzYlW1mmp', + description: `The album's Spotify URI or ID.`, + }, + // ------------------------------------------------------------------------------------------------------------- + // Artist Operations + // Get an Artist, Get an Artist's Related Artists, Get an Artist's Top Tracks, Get an Artist's Albums + // ------------------------------------------------------------------------------------------------------------- + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'artist', + ], + }, + }, + options: [ + { + name: 'Get', + value: 'get', + description: 'Get an artist by URI or ID.', + }, + { + name: `Get Albums`, + value: 'getAlbums', + description: `Get an artist's albums by URI or ID.`, + }, + { + name: `Get Related Artists`, + value: 'getRelatedArtists', + description: `Get an artist's related artists by URI or ID.`, + }, + { + name: `Get Top Tracks`, + value: 'getTopTracks', + description: `Get an artist's top tracks by URI or ID.`, + }, + ], + default: 'get', + description: 'The operation to perform.', + }, + { + displayName: 'Artist ID', + name: 'id', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'artist', + ], + }, + }, + placeholder: 'spotify:artist:4LLpKhyESsyAXpc4laK94U', + description: `The artist's Spotify URI or ID.`, + }, + { + displayName: 'Country', + name: 'country', + type: 'string', + default: 'US', + required: true, + displayOptions: { + show: { + resource: [ + 'artist' + ], + operation: [ + 'getTopTracks', + ], + }, + }, + placeholder: 'US', + description: `Top tracks in which country? Enter the postal abbriviation.`, + }, + // ------------------------------------------------------------------------------------------------------------- + // Playlist Operations + // Get a Playlist, Get a Playlist's Tracks, Add/Remove a Song from a Playlist, Get a User's Playlists + // ------------------------------------------------------------------------------------------------------------- + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'playlist', + ], + }, + }, + options: [ + { + name: 'Add an Item', + value: 'add', + description: 'Add tracks from a playlist by track and playlist URI or ID.', + }, + { + name: 'Get', + value: 'get', + description: 'Get a playlist by URI or ID.', + }, + { + name: 'Get Tracks', + value: 'getTracks', + description: `Get a playlist's tracks by URI or ID.`, + }, + { + name: `Get the User's Playlists`, + value: 'getUserPlaylists', + description: `Get a user's playlists.`, + }, + { + name: 'Remove an Item', + value: 'delete', + description: 'Remove tracks from a playlist by track and playlist URI or ID.', + }, + ], + default: 'add', + description: 'The operation to perform.', + }, + { + displayName: 'Playlist ID', + name: 'id', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'playlist', + ], + operation: [ + 'add', + 'delete', + 'get', + 'getTracks', + ], + }, + }, + placeholder: 'spotify:playlist:37i9dQZF1DWUhI3iC1khPH', + description: `The playlist's Spotify URI or its ID.`, + }, + { + displayName: 'Track ID', + name: 'trackID', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'playlist', + ], + operation: [ + 'add', + 'delete', + ], + }, + }, + placeholder: 'spotify:track:0xE4LEFzSNGsz1F6kvXsHU', + description: `The track's Spotify URI or its ID. The track to add/delete from the playlist.`, + }, + // ----------------------------------------------------- + // Track Operations + // Get a Track, Get a Track's Audio Features + // ----------------------------------------------------- + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'track', + ], + }, + }, + options: [ + { + name: 'Get', + value: 'get', + description: 'Get a track by its URI or ID.', + }, + { + name: 'Get Audio Features', + value: 'getAudioFeatures', + description: 'Get audio features for a track by URI or ID.', + }, + ], + default: 'track', + description: 'The operation to perform.', + }, + { + displayName: 'Track ID', + name: 'id', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'track', + ], + }, + }, + placeholder: 'spotify:track:0xE4LEFzSNGsz1F6kvXsHU', + description: `The track's Spotify URI or ID.`, + }, + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + default: false, + required: true, + displayOptions: { + show: { + resource: [ + 'album', + 'artist', + 'playlist', + ], + operation: [ + 'getTracks', + 'getAlbums', + 'getUserPlaylists', + ], + }, + }, + description: `The number of items to return.`, + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + default: 50, + required: true, + displayOptions: { + show: { + resource: [ + 'album', + 'artist', + 'playlist' + ], + operation: [ + 'getTracks', + 'getAlbums', + 'getUserPlaylists', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 100, + }, + description: `The number of items to return.`, + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + default: 50, + required: true, + displayOptions: { + show: { + resource: [ + 'player', + ], + operation: [ + 'recentlyPlayed', + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 50, + }, + description: `The number of items to return.`, + }, + ] + }; + + + async execute(this: IExecuteFunctions): Promise { + // Get all of the incoming input data to loop through + const items = this.getInputData(); + const returnData: IDataObject[] = []; + + // For Post + let body: IDataObject; + // For Query string + let qs: IDataObject; + + let requestMethod: string; + let endpoint: string; + let returnAll: boolean; + let propertyName = ''; + let responseData; + + const operation = this.getNodeParameter('operation', 0) as string; + const resource = this.getNodeParameter('resource', 0) as string; + + // Set initial values + requestMethod = 'GET'; + endpoint = ''; + body = {}; + qs = {}; + returnAll = false; + + for(let i = 0; i < items.length; i++) { + // ----------------------------- + // Player Operations + // ----------------------------- + if( resource === 'player' ) { + if(operation === 'pause') { + requestMethod = 'PUT'; + + endpoint = `/me/player/pause`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = { success: true }; + + } else if(operation === 'recentlyPlayed') { + requestMethod = 'GET'; + + endpoint = `/me/player/recently-played`; + + const limit = this.getNodeParameter('limit', i) as number; + + qs = { + limit, + }; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = responseData.items; + + } else if(operation === 'currentlyPlaying') { + requestMethod = 'GET'; + + endpoint = `/me/player/currently-playing`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + } else if(operation === 'nextSong') { + requestMethod = 'POST'; + + endpoint = `/me/player/next`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = { success: true }; + + } else if(operation === 'previousSong') { + requestMethod = 'POST'; + + endpoint = `/me/player/previous`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = { success: true }; + + } else if(operation === 'startMusic') { + requestMethod = 'PUT'; + + endpoint = `/me/player/play`; + + const id = this.getNodeParameter('id', i) as string; + + body.context_uri = id; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = { success: true }; + + } else if(operation === 'addSongToQueue') { + requestMethod = 'POST'; + + endpoint = `/me/player/queue`; + + const id = this.getNodeParameter('id', i) as string; + + qs = { + uri: id + }; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = { success: true }; + } + // ----------------------------- + // Album Operations + // ----------------------------- + } else if( resource === 'album') { + const uri = this.getNodeParameter('id', i) as string; + + const id = uri.replace('spotify:album:', ''); + + requestMethod = 'GET'; + + if(operation === 'get') { + endpoint = `/albums/${id}`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + } else if(operation === 'getTracks') { + endpoint = `/albums/${id}/tracks`; + + propertyName = 'tracks'; + + returnAll = this.getNodeParameter('returnAll', i) as boolean; + + propertyName = 'items'; + + if(!returnAll) { + const limit = this.getNodeParameter('limit', i) as number; + + qs = { + limit, + }; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = responseData.items; + } + } + // ----------------------------- + // Artist Operations + // ----------------------------- + } else if( resource === 'artist') { + const uri = this.getNodeParameter('id', i) as string; + + const id = uri.replace('spotify:artist:', ''); + + if(operation === 'getAlbums') { + + endpoint = `/artists/${id}/albums`; + + returnAll = this.getNodeParameter('returnAll', i) as boolean; + + propertyName = 'items'; + + if(!returnAll) { + const limit = this.getNodeParameter('limit', i) as number; + + qs = { + limit, + }; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = responseData.items; + } + } else if(operation === 'getRelatedArtists') { + + endpoint = `/artists/${id}/related-artists`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = responseData.artists; + + } else if(operation === 'getTopTracks'){ + const country = this.getNodeParameter('country', i) as string; + + qs = { + country, + }; + + endpoint = `/artists/${id}/top-tracks`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = responseData.tracks; + + } else if (operation === 'get') { + + requestMethod = 'GET'; + + endpoint = `/artists/${id}`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + } + // ----------------------------- + // Playlist Operations + // ----------------------------- + } else if( resource === 'playlist') { + if(['delete', 'get', 'getTracks', 'add'].includes(operation)) { + const uri = this.getNodeParameter('id', i) as string; + + const id = uri.replace('spotify:playlist:', ''); + + if(operation === 'delete') { + requestMethod = 'DELETE'; + const trackId = this.getNodeParameter('trackID', i) as string; + + body.tracks = [ + { + uri: `${trackId}`, + positions: [ 0 ], + }, + ]; + + endpoint = `/playlists/${id}/tracks`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = { success: true }; + + } else if(operation === 'get') { + requestMethod = 'GET'; + + endpoint = `/playlists/${id}`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + } else if(operation === 'getTracks') { + requestMethod = 'GET'; + + endpoint = `/playlists/${id}/tracks`; + + returnAll = this.getNodeParameter('returnAll', i) as boolean; + + propertyName = 'items'; + + if(!returnAll) { + const limit = this.getNodeParameter('limit', i) as number; + + qs = { + 'limit': limit + }; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = responseData.items; + } + } else if(operation === 'add') { + requestMethod = 'POST'; + + const trackId = this.getNodeParameter('trackID', i) as string; + + qs = { + uris: trackId + }; + + endpoint = `/playlists/${id}/tracks`; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + } + } else if(operation === 'getUserPlaylists') { + requestMethod = 'GET'; + + endpoint = '/me/playlists'; + + returnAll = this.getNodeParameter('returnAll', i) as boolean; + + propertyName = 'items'; + + if(!returnAll) { + const limit = this.getNodeParameter('limit', i) as number; + + qs = { + limit, + }; + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + + responseData = responseData.items; + } + } + // ----------------------------- + // Track Operations + // ----------------------------- + } else if( resource === 'track') { + const uri = this.getNodeParameter('id', i) as string; + + const id = uri.replace('spotify:track:', ''); + + requestMethod = 'GET'; + + if(operation === 'getAudioFeatures') { + endpoint = `/audio-features/${id}`; + } else if(operation === 'get') { + endpoint = `/tracks/${id}`; + } + + responseData = await spotifyApiRequest.call(this, requestMethod, endpoint, body, qs); + } + + if(returnAll) { + responseData = await spotifyApiRequestAllItems.call(this, propertyName, requestMethod, endpoint, body, qs); + } + + if (Array.isArray(responseData)) { + returnData.push.apply(returnData, responseData as IDataObject[]); + } else { + returnData.push(responseData as IDataObject); + } + } + + return [this.helpers.returnJsonArray(returnData)]; + } +} diff --git a/packages/nodes-base/nodes/Spotify/spotify.png b/packages/nodes-base/nodes/Spotify/spotify.png new file mode 100644 index 0000000000000000000000000000000000000000..2feeb78bbf25c43b2e1ceab5ee5f382eb790b207 GIT binary patch literal 6664 zcmZu$WmptI*CiyRL^`EQVp+PoySsa-1$OC%1*994E|HM#5D;mkTe`bbsSn@ydY)(M z&bjB_bLZboq?(E>CK?GE92^{`yquKA%PjP_qaweI0uKvrFB3dOLskN=a+GZUW%Jra zP9FjXhmQNV!^34{5xoG0L0WoHJ!K^UORy80xfR&Ln$63}aPByTcEda>R&ktbd0B~@yz93j3-p){SFIHy=%|A*0%_C(E zv2+8uKtW(<%D=qk7GQU%Fg5kxK>ykPm8X--e+F`f{7cn~K7g0G3joN*4*36^pdg$7 zO7DMo{XO}o+dowOGnmjzX#^zQtj(cdH!U#OQAGT2?I`7)%x$eTtj(>wg#iB>@n4w= z{iPI8bpu(yX#J~51SkafKem72g#dr${x|vmtnELnFU1u>dx`Y#ixNR&VjB^LgCm@k zmlD^qLmDxB{ZVTsRRmnB>#KW>#bsEdAbr9e!^mj5hB0*X(czp;Dj45vlFq^fMYr?QT}eS{?isA9gzel-;K=F;!xkydKkh zPg`t7cXMtN_AGf88$U19%ax{EgrlR4r9{NDRV}6qa<$AHkmc6ZZYnKSDkYhu)W^#G zn$(V`wMMA@qFlGFBUyWUC%;Un^B@>5zrFYbx#IOuOtNY@vvXJatdFjoMBBEz;B6we z%OC$ytu!D}qE7X#&vW8xfCqTzOqn63C(A>SyK>6bL4T$=1*A61KIni`N-6ohfJcW1 zKT=7bT3LI5X1HjN=l7%s8|}S^jMb{)4`Dih5dWVJcVWKD9Hj0;alUNc^!rWaVAF3o> zvSaT>2z-V_N0IVdMMKlC;S|pv*Z9L#$(6$wOApto-$|CVS2k>O*W|QAwB$=pJIU_i zkpv+qC!m`z%$?8eFojsBzdB6hHy3cY+G(Lj-uq&_oHldF$hxX#pgEGabRCMJ5)Mpej&&8WP#x6<0H>eKRddXDj(Bv z_8PhO^=08Hm<(eAk@^_tzApLM_||^0mAlQ)SW<$C8HIFaRFK|J>HWP5$^}1Xp8Zq3 zKQzR)=c}kzzejGYT?+uaBcAH0nxxLk6uhd|X{?Cx`pXen(VtSPv~#N+W_ii6JG;Hv zrTjmD)8~Cg9fwBH$!S$K{W?*%Jcj3T5^`iz8xSnO+>G&%q;M+YwUE9jL-WU!Q8?j$ku?dGv4XmDE{F$#csxo zp~{|*?0oADr*FrjCCcp4RJV0JY`E!GxySc$7D7FOV4$0sqHi>r_S0P+S9zA%pC;4HhnOKy{KN}Sc!Si0$V=)fz*yc3 za(|qyQDnnKB>(g3HG;~|xKg0w>C^E*EugBtNywLL#r%#I|DG&D>4_9BF<{^;IgGrz zO-u_%RsSjAL*0i;9R<6OIG=Go2ce~6OK(#m(PGkgHE6P$e`a$2jJhae&y54^I?D5` z&^aq6XZHpNO=u)26v1Jp`blU`CK&2qpRPgB44!qn784{h4APnI`n4N6y~2<5)w+BV zpUaoy(3BdsGjAUEBHFfJr4E<%7}-eaBmGzlK*XkP%f@qmwY>ceMt@&cGHEFOqk$vJ zs~ZnKQG~cQ-70_RvC!>+sg{mITyAnmEj_Uat1uaBS7ki^2>2_*serrX@hUL@+rg$Q z2%#($oe{Odth)`igF2gq@X<5uTfG$}g`kc53VLhKrr~!_#)P3v&lqlkcitC`p&dPU zF5Mg~RvJny<;jwcDE>2|VJD2OY4#5^CDWRysUjm3Tdezg$OJ#?{C?|WdtW>1-j$D6DHbk2oFNt+3ccOsy zvAD)ktuncSK8$oaa;eN)R|}?C_FPhz zjN3p&E67L+9irJHIDuhWMhSi%XVB)I@od1vL*f@x^zdL&tj(?<5lwPT@ol(Cs38{L zkqYmG1Nq@zPS1O}Z>fFEl9V8MKGiskWo0Szc-C$D`*5Q>iR}&KyZ8EXZk{*egz>Oi zt?6L$gzR*6_c3>?^&oTFyOmT4Q)+z@ewW-&KVa3_Zg3iA2tx6Rx~>)C91lIe=R%93 zncu_dp>+N37uaO)?-L56e^u7&YIttslkddsU$rS6bEZa4W`}mOtXvNpX>q0|2AxEi z#=~O*%REsyHN?`2aQ^uBXF~O%9QXsl&ai~pu7F=LeB{FoldfbD zYc2*c9sJtoB0@Gy#8HBp`K)E{M9aKdHd(E`=hnesI%J`4#<<6YyK zWzkD$jaht^`I+e~Ur0v%5jZIb>kz#1Xr*^!T82Phe@k*em=IS8wX>nB`^mGu<>=4m z94H=rzzXvB+1<+}5Af+P@1uHVTtsa7P-DTmpu13_OiPKe$OLFOg&NjG%jaz-2rZKqCg8$zkfy5{_F_sYic zG6-6OWbX4qy)||mnrQXHIvnare1ts{?DKwQ)tga8Vhqm;yUEj#SN`DWpBZ)ZyD;aM zew$JlgjTg$4xDr(w0w*5O^%1y*i+q;67mffXK^*zsphKn^StD{rLcq)2wT`lsu(F( zKK>rUh51r^-TABhh+{#_I(=jrfTc`R%J{eMW8;K{ocjgiL~_du?dQLaC~(*Zn__Ue zNZ99D+DLujr!IyRc#<ug7E$C3CQZ2quc+^5Qbf*P;kK>^JVIS(0%f4AZW>;8|Wv=hq70d_6}{s7%%ncGR;y}MK8pzF=R)Pyv`9Jw2csGG#F##Y-U1lmC<5X zy@Wtb3lp7Gmr8y;_+AWW7ENM4l!3oj%FUHyPDOcvre1hT>eT9XoWx&Li6jP=(l1`l zC6^O9CSkuRjM zdo$P%Nm}O?K^XT!i+s!TZL6}2`xQ@$S`zoUq?q&JGzNo7k95w)%&8-Yc-{~n^y_Ds z&X!2Usx^T5Mkr@_3izgLKWPqcnUtwI=YQT;rW6TIX&~xB$)}@7t#vU*4gYmzH%B6e zoe_S2?)LT%AMG_r37dv`aC@n+z-`ld%G%(bCT${C%wjRd@@lwy5hTuUYp-JIyW=$| znseC9N*{Hvnw>o{YRW5V+5G!*9w3#+|F&ly-DSzZ2j5@R|KqH?^JfN}a*)#vO%O{# zv>98r#DZ-0Yf0hl69@Rr(e0Z4kWojWALjZ$wUq;Mh3tY zEXCqe2ngI{Z{ux$5G=+nhb+-@+Y&Qvk?Q@-7Yxkv&Bj%slOoj=1bIL+sx_Mc=EWt_ zvfaU3n;%v}>~Ovil$dAE&^e~g-~sxjZ17>PQ>Yfq40kaHuxZKY3{s-Zo{!x5-P&Tm z0W5ozECx-D`9j&^m5Qr+Mf2_r)28Sjv8iPfU5Xw-#pn@ZUt7&eDAk-A+EfV2=bMW2 z_a1+4$&y7MVuMd(J7ZV|6gko9rzVWhos>?Bu3fmQ_D8CddBm)ndN8RZVU#%|QfCmd zf>mXn@dz(|1J*+QoJ6h>Q(0W8S|Hj}KGCmDJFLyYeI`kZTvz3FYp!o*)Q|V;U-s84 zeM;O@lGJvCNyav35+6Pgx{fQE3Kf(TDK1Qfy1c_1O|dUx_b)%zr$y>SxoAg4P5$8( zSFc_P$3T8DDV;k9!3)qH4T z@xQr?>ohA}oL33oKe;g6U!N9$4{caeA{l~F@rOvc$s=qSIn8!3SP{ zAD!F(-a`Qj=Se$>`kCJ{LCnaNf)<_;GVuzT=0Bsnh83}3qgsZ*LkkwWCK9-;#e053?3`aahr?<*++O+8GBjq2S?JL7?7 zzQtde{BoqN9^;UKY~Dj(s^8cO{9$VP(+=1LY+B5qZviPQ&c^ihA<1u4+>Mj>!Jv~( zRcr+Q76*y%1KC0{F@bC2r;SThox-I&yWHwjS}@F;U~CxLiPVa(rL$uOjZ+t`4^h&i!z-vgp{*qRyVk=*MJORAFQ6 zwTuh1HX#nHrM^dK0k8^m^F{8XSoE0<`F>7v0=GHM?+Jo!q`UQ2{h*|(NvhfJv&RG< zI3<|mSP&a#%ny&uG)ffQlrZ1lsh}iXh~Yj&5jI8?fC1<1h>q{ir9diII2ria3g}6^ z;}?xhYdt1?0#sW=RQADRW>w1$_HPKj0rZ$_)FoI)pG}u=7dyIXcAS*CjsFbK+Rh2j zwDgvxN^qo0-1DgX5)_w0I=U=fU(FYIW=wP;8|fxUeCFAXo1l7pMIKZLg2nQh>889@ ziP~g~#?i*`+In50HftfP9d>89S|lRZs)iZI5!I*Z({7y3a8 zL#TlWGJn4lL#0!f9@NK-wajgYlS3`=*`Z1Rx2pz1?A;Bx-TmaJ(#>`Vz?3(U0yQ#C z_B8v}kL=dUm0m7Nw(*BvHdf7eFfM(ZpNvoYdhxfV?U$gp+A=ps?eMSODG>Y52&y<< z*}@pqKZA*E@-mIFMzdfp6Hjr7(dvEtl#L1Fq*qz_>zFXS^O8ii-=A3BJ6i;m`)K#( zow;qQbSx(wE!|umHgm_0Ol}n1I*lWV`VT&>62Y$&xN-;AtvnAN6;BZ9Qog}Q1p?a> zv2Be6Mb!u1&SjCglthNS?KO+(#s|wKJR*tc6f#T&<}+wkFU(r}QFo#DuW?C}6KbY_ zDQN=yDPU9)t&{7Xeh!!X4AdJ?#urmT3G3c>s{cw+& zZcZIP>Upuoy1nK1ZpjB5pvu0~eLy>ZW3+Auk{-n6QQE9+wi>-!!02^gl99T( zyRC9F-1|}exs4tLgDfN2Cf~!omLn02=~A>`@X4eu(tRi*17Fbz1~k8B$bOnn_0{oV zW@cUpNJGzW*62g@xf|d-T`sK3FiF;m{c07d%l7b)?D!MT`K{L#25ko+R<%LO2fD-+ ztRi`#HyO4^x5NidIx~&CWdthl-`Cy*BGQoDgxRrJbFG&+v$Py!dQS3b@ow0QY4F|o zZN$Fb2sO=jd8Zxi(!fYMAM`@n8?HkWD4 z0|qQigHo)A0!B$dVJ_H(|8$XCVPk7C{LM{M+vr~d`Ltv0ND zMGND7p9r-f+O(fRrw{y6r~<`c|?? zovSNbkel?0S=Z#w!M3b3Qzm3PHlMhE;m!IcnPdAs_z~x)B%zXV9-xNTyFF<-q2^ez z{zs0sC_v9Nb#HI7e*hjIy!T`iA`|66BRFN)UFK0IV*i}|1DpY=2y{!nZ?SqV5>Q2< z)x&00o=JE7wRJ8(8Ne459UU*56WDR}Sbku5GvA;wEoM;Q)_5(iKFT3YV13k}d2v^O zb3E&KoqJmGFp83B;lTknYb!d00Q^rgd!()y6aY5?fZ9x09gt?IQUPCQ~ zNG#rYBi3Um!d|7w0H>|#S*1<)>~UJq*8me@6=?i=88sOOIV@IH!DZu zM0S=Z^H+q1s{xJ`OD==CtvA?TB)MyIY1(4+_H4LA^#i+rF+`}_9Bm8cyG2;JUzN@Y zCVG8(iw_IamwhF#IKh`&e(lJw(&m76A>LU1`!7$p!3U@yn%j=cvB)>4i$y#$9ZAA4 zC)Esv0SCOiO1MZyHShC4*FPuiOV{46yse&!iIOxD9ZuG3M2obV+K42|T7_Knx~={e zc{};1>0^O1KO=O^Wy9aZjmCEFN>xYObwnZZA2-C^cGlB19OgFJX0okrg9~H%@$NVV zW|SA+Q}s%*VuWlIu=M+!zkzM^6LG3Nj8H0f4Rg>%^75JI%Fqalm&yJ9nP{*7*xWTh zx61tOSQ?vw>&QrJzIQ=5m+BEi8&hZpsKX=HhiQQZ_5%xZ*iSVpEBLG>5uo7;gj-${7^}Y;i7QprJkQAcgKPq0L&{$gOsEb^rtDK z&fO0oIW__>(659{IQ(Gi#{T&%{Jf(z-Ue2tCbRDhOtM6`ypS-k%PIfUO8I1O>p@BO yuDUBI#tL~Id;c)#1LY@6KIaUBA^!o!Zi|xu literal 0 HcmV?d00001 diff --git a/packages/nodes-base/nodes/SurveyMonkey/GenericFunctions.ts b/packages/nodes-base/nodes/SurveyMonkey/GenericFunctions.ts index 86f999b578..bfca4dde1b 100644 --- a/packages/nodes-base/nodes/SurveyMonkey/GenericFunctions.ts +++ b/packages/nodes-base/nodes/SurveyMonkey/GenericFunctions.ts @@ -14,19 +14,13 @@ import { } from 'n8n-workflow'; export async function surveyMonkeyApiRequest(this: IExecuteFunctions | IWebhookFunctions | IHookFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, query: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise { // tslint:disable-line:no-any - - const credentials = this.getCredentials('surveyMonkeyApi'); - - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } + const authenticationMethod = this.getNodeParameter('authentication', 0); const endpoint = 'https://api.surveymonkey.com/v3'; let options: OptionsWithUri = { headers: { 'Content-Type': 'application/json', - 'Authorization': `bearer ${credentials.accessToken}`, }, method, body, @@ -34,6 +28,7 @@ export async function surveyMonkeyApiRequest(this: IExecuteFunctions | IWebhookF uri: uri || `${endpoint}${resource}`, json: true }; + if (!Object.keys(body).length) { delete options.body; } @@ -41,8 +36,22 @@ export async function surveyMonkeyApiRequest(this: IExecuteFunctions | IWebhookF delete options.qs; } options = Object.assign({}, options, option); + try { - return await this.helpers.request!(options); + if ( authenticationMethod === 'accessToken') { + const credentials = this.getCredentials('surveyMonkeyApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + // @ts-ignore + options.headers['Authorization'] = `bearer ${credentials.accessToken}`; + + return await this.helpers.request!(options); + + } else { + return await this.helpers.requestOAuth2?.call(this, 'surveyMonkeyOAuth2Api', options); + } } catch (error) { const errorMessage = error.response.body.error.message; if (errorMessage !== undefined) { diff --git a/packages/nodes-base/nodes/SurveyMonkey/SurveyMonkeyTrigger.node.ts b/packages/nodes-base/nodes/SurveyMonkey/SurveyMonkeyTrigger.node.ts index efdc8dba5a..c0f722dd8c 100644 --- a/packages/nodes-base/nodes/SurveyMonkey/SurveyMonkeyTrigger.node.ts +++ b/packages/nodes-base/nodes/SurveyMonkey/SurveyMonkeyTrigger.node.ts @@ -49,6 +49,24 @@ export class SurveyMonkeyTrigger implements INodeType { { name: 'surveyMonkeyApi', required: true, + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'surveyMonkeyOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, }, ], webhooks: [ @@ -66,6 +84,23 @@ export class SurveyMonkeyTrigger implements INodeType { }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'Method of authentication.', + }, { displayName: 'Type', name: 'objectType', @@ -453,11 +488,18 @@ export class SurveyMonkeyTrigger implements INodeType { async webhook(this: IWebhookFunctions): Promise { const event = this.getNodeParameter('event') as string; const objectType = this.getNodeParameter('objectType') as string; - const credentials = this.getCredentials('surveyMonkeyApi') as IDataObject; + const authenticationMethod = this.getNodeParameter('authentication') as string; + let credentials : IDataObject; const headerData = this.getHeaderData() as IDataObject; const req = this.getRequestObject(); const webhookName = this.getWebhookName(); + if (authenticationMethod === 'accessToken') { + credentials = this.getCredentials('surveyMonkeyApi') as IDataObject; + } else { + credentials = this.getCredentials('surveyMonkeyOAuth2Api') as IDataObject; + } + if (webhookName === 'setup') { // It is a create webhook confirmation request return {}; diff --git a/packages/nodes-base/nodes/Trello/AttachmentDescription.ts b/packages/nodes-base/nodes/Trello/AttachmentDescription.ts index a04f507518..4306b2ed11 100644 --- a/packages/nodes-base/nodes/Trello/AttachmentDescription.ts +++ b/packages/nodes-base/nodes/Trello/AttachmentDescription.ts @@ -29,7 +29,7 @@ export const attachmentOperations = [ { name: 'Get', value: 'get', - description: 'Get the data of an attachments', + description: 'Get the data of an attachment', }, { name: 'Get All', diff --git a/packages/nodes-base/nodes/Trello/ChecklistDescription.ts b/packages/nodes-base/nodes/Trello/ChecklistDescription.ts index 34036f83e2..be11ba6f17 100644 --- a/packages/nodes-base/nodes/Trello/ChecklistDescription.ts +++ b/packages/nodes-base/nodes/Trello/ChecklistDescription.ts @@ -44,17 +44,17 @@ export const checklistOperations = [ { name: 'Get Checklist Items', value: 'getCheckItem', - description: 'Get a specific Checklist on a card', + description: 'Get a specific checklist on a card', }, { name: 'Get Completed Checklist Items', value: 'completedCheckItems', - description: 'Get the completed Checklist items on a card', + description: 'Get the completed checklist items on a card', }, { name: 'Update Checklist Item', value: 'updateCheckItem', - description: 'Update an item in a checklist on a card.', + description: 'Update an item in a checklist on a card', }, ], default: 'getAll', diff --git a/packages/nodes-base/nodes/Trello/LabelDescription.ts b/packages/nodes-base/nodes/Trello/LabelDescription.ts index 9c23053282..2b938ae5de 100644 --- a/packages/nodes-base/nodes/Trello/LabelDescription.ts +++ b/packages/nodes-base/nodes/Trello/LabelDescription.ts @@ -39,7 +39,7 @@ export const labelOperations = [ { name: 'Get All', value: 'getAll', - description: 'Returns all label for the board', + description: 'Returns all labels for the board', }, { name: 'Remove From Card', diff --git a/packages/nodes-base/nodes/Twitter/TweetDescription.ts b/packages/nodes-base/nodes/Twitter/TweetDescription.ts index edd12bbf5e..12cb87ebfe 100644 --- a/packages/nodes-base/nodes/Twitter/TweetDescription.ts +++ b/packages/nodes-base/nodes/Twitter/TweetDescription.ts @@ -219,7 +219,7 @@ export const tweetFields = [ description: 'The entities node will not be included when set to false', }, { - displayName: 'Lang', + displayName: 'Language', name: 'lang', type: 'options', typeOptions: { diff --git a/packages/nodes-base/nodes/Twitter/Twitter.node.ts b/packages/nodes-base/nodes/Twitter/Twitter.node.ts index 60f95e3798..a62f9fd95b 100644 --- a/packages/nodes-base/nodes/Twitter/Twitter.node.ts +++ b/packages/nodes-base/nodes/Twitter/Twitter.node.ts @@ -133,7 +133,15 @@ export class Twitter implements INodeType { let attachmentBody = {}; let response: IDataObject = {}; - if (binaryData[binaryPropertyName].mimeType.includes('image')) { + const isAnimatedWebp = (Buffer.from(binaryData[binaryPropertyName].data, 'base64').toString().indexOf('ANMF') !== -1); + + const isImage = binaryData[binaryPropertyName].mimeType.includes('image'); + + if (isImage && isAnimatedWebp) { + throw new Error('Animated .webp images are not supported use .gif instead'); + } + + if (isImage) { const attachmentBody = { media_data: binaryData[binaryPropertyName].data, diff --git a/packages/nodes-base/nodes/Typeform/GenericFunctions.ts b/packages/nodes-base/nodes/Typeform/GenericFunctions.ts index c5e9242465..83ca713afe 100644 --- a/packages/nodes-base/nodes/Typeform/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Typeform/GenericFunctions.ts @@ -45,18 +45,10 @@ export interface ITypeformAnswerField { * @returns {Promise} */ export async function apiRequest(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: object, query?: IDataObject): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('typeformApi'); - - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - - query = query || {}; + const authenticationMethod = this.getNodeParameter('authentication', 0); const options: OptionsWithUri = { - headers: { - 'Authorization': `bearer ${credentials.accessToken}`, - }, + headers: {}, method, body, qs: query, @@ -64,8 +56,23 @@ export async function apiRequest(this: IHookFunctions | IExecuteFunctions | ILoa json: true, }; + query = query || {}; + try { - return await this.helpers.request!(options); + if (authenticationMethod === 'accessToken') { + + const credentials = this.getCredentials('typeformApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.headers!['Authorization'] = `bearer ${credentials.accessToken}`; + + return await this.helpers.request!(options); + } else { + return await this.helpers.requestOAuth2!.call(this, 'typeformOAuth2Api', options); + } } catch (error) { if (error.statusCode === 401) { // Return a clear error diff --git a/packages/nodes-base/nodes/Typeform/TypeformTrigger.node.ts b/packages/nodes-base/nodes/Typeform/TypeformTrigger.node.ts index b127a1f594..9c8f6e16ff 100644 --- a/packages/nodes-base/nodes/Typeform/TypeformTrigger.node.ts +++ b/packages/nodes-base/nodes/Typeform/TypeformTrigger.node.ts @@ -37,7 +37,25 @@ export class TypeformTrigger implements INodeType { { name: 'typeformApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'typeformOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], webhooks: [ { @@ -48,6 +66,23 @@ export class TypeformTrigger implements INodeType { }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'The resource to operate on.', + }, { displayName: 'Form', name: 'formId', diff --git a/packages/nodes-base/nodes/Uplead/Uplead.node.ts b/packages/nodes-base/nodes/Uplead/Uplead.node.ts index e47bdbe71c..93350e99d9 100644 --- a/packages/nodes-base/nodes/Uplead/Uplead.node.ts +++ b/packages/nodes-base/nodes/Uplead/Uplead.node.ts @@ -113,7 +113,9 @@ export class Uplead implements INodeType { if (Array.isArray(responseData.data)) { returnData.push.apply(returnData, responseData.data as IDataObject[]); } else { - returnData.push(responseData.data as IDataObject); + if (responseData.data !== null) { + returnData.push(responseData.data as IDataObject); + } } } return [this.helpers.returnJsonArray(returnData)]; diff --git a/packages/nodes-base/nodes/Webflow/GenericFunctions.ts b/packages/nodes-base/nodes/Webflow/GenericFunctions.ts index 030e47f903..783b674808 100644 --- a/packages/nodes-base/nodes/Webflow/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Webflow/GenericFunctions.ts @@ -1,4 +1,7 @@ -import { OptionsWithUri } from 'request'; +import { + OptionsWithUri, +} from 'request'; + import { IExecuteFunctions, IExecuteSingleFunctions, @@ -6,17 +9,16 @@ import { ILoadOptionsFunctions, IWebhookFunctions, } from 'n8n-core'; -import { IDataObject } from 'n8n-workflow'; + +import { + IDataObject, + } from 'n8n-workflow'; export async function webflowApiRequest(this: IHookFunctions | IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions | IWebhookFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('webflowApi'); - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } + const authenticationMethod = this.getNodeParameter('authentication', 0); let options: OptionsWithUri = { headers: { - authorization: `Bearer ${credentials.accessToken}`, 'accept-version': '1.0.0', }, method, @@ -31,14 +33,22 @@ export async function webflowApiRequest(this: IHookFunctions | IExecuteFunctions } try { - return await this.helpers.request!(options); - } catch (error) { + if (authenticationMethod === 'accessToken') { + const credentials = this.getCredentials('webflowApi'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } - let errorMessage = error.message; - if (error.response.body && error.response.body.err) { - errorMessage = error.response.body.err; + options.headers!['authorization'] = `Bearer ${credentials.accessToken}`; + + return await this.helpers.request!(options); + } else { + return await this.helpers.requestOAuth2!.call(this, 'webflowOAuth2Api', options); } - - throw new Error('Webflow Error: ' + errorMessage); + } catch (error) { + if (error.response.body.err) { + throw new Error(`Webflow Error: [${error.statusCode}]: ${error.response.body.err}`); + } + return error; } } diff --git a/packages/nodes-base/nodes/Webflow/WebflowTrigger.node.ts b/packages/nodes-base/nodes/Webflow/WebflowTrigger.node.ts index 709b9858cd..73b2efef61 100644 --- a/packages/nodes-base/nodes/Webflow/WebflowTrigger.node.ts +++ b/packages/nodes-base/nodes/Webflow/WebflowTrigger.node.ts @@ -34,7 +34,25 @@ export class WebflowTrigger implements INodeType { { name: 'webflowApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + name: 'webflowOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], webhooks: [ { @@ -45,6 +63,23 @@ export class WebflowTrigger implements INodeType { }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'Method of authentication.', + }, { displayName: 'Site', name: 'site', diff --git a/packages/nodes-base/nodes/Webhook.node.ts b/packages/nodes-base/nodes/Webhook.node.ts index 135960ea4e..1778d44290 100644 --- a/packages/nodes-base/nodes/Webhook.node.ts +++ b/packages/nodes-base/nodes/Webhook.node.ts @@ -77,6 +77,7 @@ export class Webhook implements INodeType { { name: 'default', httpMethod: '={{$parameter["httpMethod"]}}', + isFullPath: true, responseCode: '={{$parameter["responseCode"]}}', responseMode: '={{$parameter["responseMode"]}}', responseData: '={{$parameter["responseData"]}}', @@ -133,7 +134,7 @@ export class Webhook implements INodeType { default: '', placeholder: 'webhook', required: true, - description: 'The path to listen to. Slashes("/") in the path are not allowed.', + description: 'The path to listen to.', }, { displayName: 'Response Code', diff --git a/packages/nodes-base/nodes/Xero/ContactDescription.ts b/packages/nodes-base/nodes/Xero/ContactDescription.ts new file mode 100644 index 0000000000..418aef44ac --- /dev/null +++ b/packages/nodes-base/nodes/Xero/ContactDescription.ts @@ -0,0 +1,838 @@ +import { + INodeProperties, + } from 'n8n-workflow'; + +export const contactOperations = [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'contact', + ], + }, + }, + options: [ + { + name: 'Create', + value: 'create', + description: 'create a contact', + }, + { + name: 'Get', + value: 'get', + description: 'Get a contact', + }, + { + name: 'Get All', + value: 'getAll', + description: 'Get all contacts', + }, + { + name: 'Update', + value: 'update', + description: 'Update a contact', + }, + ], + default: 'create', + description: 'The operation to perform.', + }, +] as INodeProperties[]; + +export const contactFields = [ + +/* -------------------------------------------------------------------------- */ +/* contact:create */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTenants', + }, + default: '', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'create', + ], + }, + }, + required: true, + }, + { + displayName: 'Name', + name: 'name', + type: 'string', + default: '', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'create', + ], + }, + }, + description: 'Full name of contact/organisation', + required: true, + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'create', + ], + }, + }, + options: [ + { + displayName: 'Account Number', + name: 'accountNumber', + type: 'string', + default: '', + description: 'A user defined account number', + }, + // { + // displayName: 'Addresses', + // name: 'addressesUi', + // type: 'fixedCollection', + // typeOptions: { + // multipleValues: true, + // }, + // default: '', + // placeholder: 'Add Address', + // options: [ + // { + // name: 'addressesValues', + // displayName: 'Address', + // values: [ + // { + // displayName: 'Type', + // name: 'type', + // type: 'options', + // options: [ + // { + // name: 'PO Box', + // value: 'POBOX', + // }, + // { + // name: 'Street', + // value: 'STREET', + // }, + // ], + // default: '', + // }, + // { + // displayName: 'Line 1', + // name: 'line1', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Line 2', + // name: 'line2', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'City', + // name: 'city', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Region', + // name: 'region', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Postal Code', + // name: 'postalCode', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Country', + // name: 'country', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Attention To', + // name: 'attentionTo', + // type: 'string', + // default: '', + // }, + // ], + // }, + // ], + // }, + { + displayName: 'Bank Account Details', + name: 'bankAccountDetails', + type: 'string', + default: '', + description: 'Bank account number of contact', + }, + { + displayName: 'Contact Number', + name: 'contactNumber', + type: 'string', + default: '', + description: 'This field is read only on the Xero contact screen, used to identify contacts in external systems', + }, + { + displayName: 'Contact Status', + name: 'contactStatus', + type: 'options', + options: [ + { + name: 'Active', + value: 'ACTIVE', + description: 'The Contact is active and can be used in transactions', + }, + { + name: 'Archived', + value: 'ARCHIVED', + description: 'The Contact is archived and can no longer be used in transactions', + }, + { + name: 'GDPR Request', + value: 'GDPRREQUEST', + description: 'The Contact is the subject of a GDPR erasure request', + }, + ], + default: '', + description: 'Current status of a contact - see contact status types', + }, + { + displayName: 'Default Currency', + name: 'defaultCurrency', + type: 'string', + default: '', + description: 'Default currency for raising invoices against contact', + }, + { + displayName: 'Email', + name: 'emailAddress', + type: 'string', + default: '', + description: 'Email address of contact person (umlauts not supported) (max length = 255)', + }, + { + displayName: 'First Name', + name: 'firstName', + type: 'string', + default: '', + description: 'First name of contact person (max length = 255)', + }, + { + displayName: 'Last Name', + name: 'lastName', + type: 'string', + default: '', + description: 'Last name of contact person (max length = 255)', + }, + // { + // displayName: 'Phones', + // name: 'phonesUi', + // type: 'fixedCollection', + // typeOptions: { + // multipleValues: true, + // }, + // default: '', + // placeholder: 'Add Phone', + // options: [ + // { + // name: 'phonesValues', + // displayName: 'Phones', + // values: [ + // { + // displayName: 'Type', + // name: 'type', + // type: 'options', + // options: [ + // { + // name: 'Default', + // value: 'DEFAULT', + // }, + // { + // name: 'DDI', + // value: 'DDI', + // }, + // { + // name: 'Mobile', + // value: 'MOBILE', + // }, + // { + // name: 'Fax', + // value: 'FAX', + // }, + // ], + // default: '', + // }, + // { + // displayName: 'Number', + // name: 'phoneNumber', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Area Code', + // name: 'phoneAreaCode', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Country Code', + // name: 'phoneCountryCode', + // type: 'string', + // default: '', + // }, + // ], + // }, + // ], + // }, + { + displayName: 'Purchase Default Account Code', + name: 'purchasesDefaultAccountCode', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getAccountCodes', + }, + default: '', + description: 'The default purchases account code for contacts', + }, + { + displayName: 'Sales Default Account Code', + name: 'salesDefaultAccountCode', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getAccountCodes', + }, + default: '', + description: 'The default sales account code for contacts', + }, + { + displayName: 'Skype', + name: 'skypeUserName', + type: 'string', + default: '', + description: 'Skype user name of contact', + }, + { + displayName: 'Tax Number', + name: 'taxNumber', + type: 'string', + default: '', + description: 'Tax number of contact', + }, + { + displayName: 'Xero Network Key', + name: 'xeroNetworkKey', + type: 'string', + default: '', + description: 'Store XeroNetworkKey for contacts', + }, + ], + }, +/* -------------------------------------------------------------------------- */ +/* contact:get */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTenants', + }, + default: '', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'get', + ], + }, + }, + required: true, + }, + { + displayName: 'Contact ID', + name: 'contactId', + type: 'string', + default: '', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'get', + ], + }, + }, + required: true, + }, +/* -------------------------------------------------------------------------- */ +/* contact:getAll */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTenants', + }, + default: '', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'getAll', + ], + }, + }, + required: true, + }, + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'getAll', + ], + }, + }, + default: false, + description: 'If all results should be returned or only up to a given limit.', + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'getAll', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 100, + }, + default: 100, + description: 'How many results to return.', + }, + { + displayName: 'Options', + name: 'options', + type: 'collection', + placeholder: 'Add Option', + default: {}, + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'getAll', + ], + }, + }, + options: [ + { + displayName: 'Include Archived', + name: 'includeArchived', + type: 'boolean', + default: false, + description: `Contacts with a status of ARCHIVED will be included in the response`, + }, + { + displayName: 'Order By', + name: 'orderBy', + type: 'string', + placeholder: 'contactID', + default: '', + description: 'Order by any element returned', + }, + { + displayName: 'Sort Order', + name: 'sortOrder', + type: 'options', + options: [ + { + name: 'Asc', + value: 'ASC', + }, + { + name: 'Desc', + value: 'DESC', + }, + ], + default: '', + description: 'Sort order', + }, + { + displayName: 'Where', + name: 'where', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + placeholder: 'EmailAddress!=null&&EmailAddress.StartsWith("boom")', + default: '', + description: `The where parameter allows you to filter on endpoints and elements that don't have explicit parameters. Examples Here`, + }, + ], + }, +/* -------------------------------------------------------------------------- */ +/* contact:update */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTenants', + }, + default: '', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'update', + ], + }, + }, + required: true, + }, + { + displayName: 'Contact ID', + name: 'contactId', + type: 'string', + default: '', + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'update', + ], + }, + }, + required: true, + }, + { + displayName: 'Update Fields', + name: 'updateFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + resource: [ + 'contact', + ], + operation: [ + 'update', + ], + }, + }, + options: [ + { + displayName: 'Account Number', + name: 'accountNumber', + type: 'string', + default: '', + description: 'A user defined account number', + }, + // { + // displayName: 'Addresses', + // name: 'addressesUi', + // type: 'fixedCollection', + // typeOptions: { + // multipleValues: true, + // }, + // default: '', + // placeholder: 'Add Address', + // options: [ + // { + // name: 'addressesValues', + // displayName: 'Address', + // values: [ + // { + // displayName: 'Type', + // name: 'type', + // type: 'options', + // options: [ + // { + // name: 'PO Box', + // value: 'POBOX', + // }, + // { + // name: 'Street', + // value: 'STREET', + // }, + // ], + // default: '', + // }, + // { + // displayName: 'Line 1', + // name: 'line1', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Line 2', + // name: 'line2', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'City', + // name: 'city', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Region', + // name: 'region', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Postal Code', + // name: 'postalCode', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Country', + // name: 'country', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Attention To', + // name: 'attentionTo', + // type: 'string', + // default: '', + // }, + // ], + // }, + // ], + // }, + { + displayName: 'Bank Account Details', + name: 'bankAccountDetails', + type: 'string', + default: '', + description: 'Bank account number of contact', + }, + { + displayName: 'Contact Number', + name: 'contactNumber', + type: 'string', + default: '', + description: 'This field is read only on the Xero contact screen, used to identify contacts in external systems', + }, + { + displayName: 'Contact Status', + name: 'contactStatus', + type: 'options', + options: [ + { + name: 'Active', + value: 'ACTIVE', + description: 'The Contact is active and can be used in transactions', + }, + { + name: 'Archived', + value: 'ARCHIVED', + description: 'The Contact is archived and can no longer be used in transactions', + }, + { + name: 'GDPR Request', + value: 'GDPRREQUEST', + description: 'The Contact is the subject of a GDPR erasure request', + }, + ], + default: '', + description: 'Current status of a contact - see contact status types', + }, + { + displayName: 'Default Currency', + name: 'defaultCurrency', + type: 'string', + default: '', + description: 'Default currency for raising invoices against contact', + }, + { + displayName: 'Email', + name: 'emailAddress', + type: 'string', + default: '', + description: 'Email address of contact person (umlauts not supported) (max length = 255)', + }, + { + displayName: 'First Name', + name: 'firstName', + type: 'string', + default: '', + description: 'First name of contact person (max length = 255)', + }, + { + displayName: 'Last Name', + name: 'lastName', + type: 'string', + default: '', + description: 'Last name of contact person (max length = 255)', + }, + { + displayName: 'Name', + name: 'name', + type: 'string', + default: '', + description: 'Full name of contact/organisation', + }, + // { + // displayName: 'Phones', + // name: 'phonesUi', + // type: 'fixedCollection', + // typeOptions: { + // multipleValues: true, + // }, + // default: '', + // placeholder: 'Add Phone', + // options: [ + // { + // name: 'phonesValues', + // displayName: 'Phones', + // values: [ + // { + // displayName: 'Type', + // name: 'type', + // type: 'options', + // options: [ + // { + // name: 'Default', + // value: 'DEFAULT', + // }, + // { + // name: 'DDI', + // value: 'DDI', + // }, + // { + // name: 'Mobile', + // value: 'MOBILE', + // }, + // { + // name: 'Fax', + // value: 'FAX', + // }, + // ], + // default: '', + // }, + // { + // displayName: 'Number', + // name: 'phoneNumber', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Area Code', + // name: 'phoneAreaCode', + // type: 'string', + // default: '', + // }, + // { + // displayName: 'Country Code', + // name: 'phoneCountryCode', + // type: 'string', + // default: '', + // }, + // ], + // }, + // ], + // }, + { + displayName: 'Purchase Default Account Code', + name: 'purchasesDefaultAccountCode', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getAccountCodes', + }, + default: '', + description: 'The default purchases account code for contacts', + }, + { + displayName: 'Sales Default Account Code', + name: 'salesDefaultAccountCode', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getAccountCodes', + }, + default: '', + description: 'The default sales account code for contacts', + }, + { + displayName: 'Skype', + name: 'skypeUserName', + type: 'string', + default: '', + description: 'Skype user name of contact', + }, + { + displayName: 'Tax Number', + name: 'taxNumber', + type: 'string', + default: '', + description: 'Tax number of contact', + }, + { + displayName: 'Xero Network Key', + name: 'xeroNetworkKey', + type: 'string', + default: '', + description: 'Store XeroNetworkKey for contacts', + }, + ], + }, +] as INodeProperties[]; diff --git a/packages/nodes-base/nodes/Xero/GenericFunctions.ts b/packages/nodes-base/nodes/Xero/GenericFunctions.ts new file mode 100644 index 0000000000..840579bf2f --- /dev/null +++ b/packages/nodes-base/nodes/Xero/GenericFunctions.ts @@ -0,0 +1,76 @@ +import { + OptionsWithUri, + } from 'request'; + +import { + IExecuteFunctions, + IExecuteSingleFunctions, + ILoadOptionsFunctions, +} from 'n8n-core'; + +import { + IDataObject, +} from 'n8n-workflow'; + +export async function xeroApiRequest(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, headers: IDataObject = {}): Promise { // tslint:disable-line:no-any + const options: OptionsWithUri = { + headers: { + 'Content-Type': 'application/json', + }, + method, + body, + qs, + uri: uri || `https://api.xero.com/api.xro/2.0${resource}`, + json: true + }; + try { + if (body.organizationId) { + options.headers = { ...options.headers, 'Xero-tenant-id': body.organizationId }; + delete body.organizationId; + } + if (Object.keys(headers).length !== 0) { + options.headers = Object.assign({}, options.headers, headers); + } + if (Object.keys(body).length === 0) { + delete options.body; + } + //@ts-ignore + return await this.helpers.requestOAuth2.call(this, 'xeroOAuth2Api', options); + } catch (error) { + let errorMessage; + + if (error.response && error.response.body && error.response.body.Message) { + + errorMessage = error.response.body.Message; + + if (error.response.body.Elements) { + const elementErrors = []; + for (const element of error.response.body.Elements) { + elementErrors.push(element.ValidationErrors.map((error: IDataObject) => error.Message).join('|')); + } + errorMessage = elementErrors.join('-'); + } + // Try to return the error prettier + throw new Error(`Xero error response [${error.statusCode}]: ${errorMessage}`); + } + throw error; + } +} + +export async function xeroApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, propertyName: string ,method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise { // tslint:disable-line:no-any + + const returnData: IDataObject[] = []; + + let responseData; + query.page = 1; + + do { + responseData = await xeroApiRequest.call(this, method, endpoint, body, query); + query.page++; + returnData.push.apply(returnData, responseData[propertyName]); + } while ( + responseData[propertyName].length !== 0 + ); + + return returnData; +} diff --git a/packages/nodes-base/nodes/Xero/IContactInterface.ts b/packages/nodes-base/nodes/Xero/IContactInterface.ts new file mode 100644 index 0000000000..1fc5eebe6a --- /dev/null +++ b/packages/nodes-base/nodes/Xero/IContactInterface.ts @@ -0,0 +1,44 @@ + +export interface IAddress { + Type?: string; + AddressLine1?: string; + AddressLine2?: string; + City?: string; + Region?: string; + PostalCode?: string; + Country?: string; + AttentionTo?: string; +} + +export interface IPhone { + Type?: string; + PhoneNumber?: string; + PhoneAreaCode?: string; + PhoneCountryCode?: string; +} + +export interface IContact extends ITenantId { + AccountNumber?: string; + Addresses?: IAddress[]; + BankAccountDetails?: string; + ContactId?: string; + ContactNumber?: string; + ContactStatus?: string; + DefaultCurrency?: string; + EmailAddress?: string; + FirstName?: string; + LastName?: string; + Name?: string; + Phones?: IPhone[]; + PurchaseTrackingCategory?: string; + PurchasesDefaultAccountCode?: string; + SalesDefaultAccountCode?: string; + SalesTrackingCategory?: string; + SkypeUserName?: string; + taxNumber?: string; + xeroNetworkKey?: string; +} + +export interface ITenantId { + organizationId?: string; +} diff --git a/packages/nodes-base/nodes/Xero/InvoiceDescription.ts b/packages/nodes-base/nodes/Xero/InvoiceDescription.ts new file mode 100644 index 0000000000..6591adc24c --- /dev/null +++ b/packages/nodes-base/nodes/Xero/InvoiceDescription.ts @@ -0,0 +1,983 @@ +import { + INodeProperties, + } from 'n8n-workflow'; + +export const invoiceOperations = [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + }, + }, + options: [ + { + name: 'Create', + value: 'create', + description: 'Create a invoice', + }, + { + name: 'Get', + value: 'get', + description: 'Get a invoice', + }, + { + name: 'Get All', + value: 'getAll', + description: 'Get all invoices', + }, + { + name: 'Update', + value: 'update', + description: 'Update a invoice', + }, + ], + default: 'create', + description: 'The operation to perform.', + }, +] as INodeProperties[]; + +export const invoiceFields = [ + +/* -------------------------------------------------------------------------- */ +/* invoice:create */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTenants', + }, + default: '', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'create', + ], + }, + }, + required: true, + }, + { + displayName: 'Type', + name: 'type', + type: 'options', + options: [ + { + name: 'Bill', + value: 'ACCPAY', + description: 'Accounts Payable or supplier invoice' + }, + { + name: 'Sales Invoice', + value: 'ACCREC', + description: ' Accounts Receivable or customer invoice' + }, + ], + default: '', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'create', + ], + }, + }, + required: true, + description: 'Invoice Type', + }, + { + displayName: 'Contact ID', + name: 'contactId', + type: 'string', + default: '', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'create', + ], + }, + }, + required: true, + description: 'Contact ID', + }, + { + displayName: 'Line Items', + name: 'lineItemsUi', + placeholder: 'Add Line Item', + type: 'fixedCollection', + default: '', + typeOptions: { + multipleValues: true, + }, + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'create', + ] + }, + }, + description: 'Line item data', + options: [ + { + name: 'lineItemsValues', + displayName: 'Line Item', + values: [ + { + displayName: 'Description', + name: 'description', + type: 'string', + default: '', + description: 'A line item with just a description', + }, + { + displayName: 'Quantity', + name: 'quantity', + type: 'number', + default: 1, + typeOptions: { + minValue: 1, + }, + description: 'LineItem Quantity', + }, + { + displayName: 'Unit Amount', + name: 'unitAmount', + type: 'string', + default: '', + description: 'Lineitem unit amount. By default, unit amount will be rounded to two decimal places.', + }, + { + displayName: 'Item Code', + name: 'itemCode', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getItemCodes', + loadOptionsDependsOn: [ + 'organizationId', + ], + }, + default: '', + }, + { + displayName: 'Account Code', + name: 'accountCode', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getAccountCodes', + loadOptionsDependsOn: [ + 'organizationId', + ], + }, + default: '', + }, + { + displayName: 'Tax Type', + name: 'taxType', + type: 'options', + options: [ + { + name: 'Tax on Purchases', + value: 'INPUT', + }, + { + name: 'Tax Exempt', + value: 'NONE', + }, + { + name: 'Tax on Sales', + value: 'OUTPUT', + }, + { + name: 'Sales Tax on Imports ', + value: 'GSTONIMPORTS', + }, + ], + default: '', + required: true, + description: 'Tax Type', + }, + { + displayName: 'Tax Amount', + name: 'taxAmount', + type: 'string', + default: '', + description: 'The tax amount is auto calculated as a percentage of the line amount based on the tax rate.', + }, + { + displayName: 'Line Amount', + name: 'lineAmount', + type: 'string', + default: '', + description: 'The line amount reflects the discounted price if a DiscountRate has been used', + }, + { + displayName: 'Discount Rate', + name: 'discountRate', + type: 'string', + default: '', + description: 'Percentage discount or discount amount being applied to a line item. Only supported on ACCREC invoices - ACCPAY invoices and credit notes in Xero do not support discounts', + }, + // { + // displayName: 'Tracking', + // name: 'trackingUi', + // placeholder: 'Add Tracking', + // description: 'Any LineItem can have a maximum of 2 TrackingCategory elements.', + // type: 'fixedCollection', + // typeOptions: { + // multipleValues: true, + // }, + // default: {}, + // options: [ + // { + // name: 'trackingValues', + // displayName: 'Tracking', + // values: [ + // { + // displayName: 'Name', + // name: 'name', + // type: 'options', + // typeOptions: { + // loadOptionsMethod: 'getTrakingCategories', + // loadOptionsDependsOn: [ + // 'organizationId', + // ], + // }, + // default: '', + // description: 'Name of the tracking category', + // }, + // { + // displayName: 'Option', + // name: 'option', + // type: 'options', + // typeOptions: { + // loadOptionsMethod: 'getTrakingOptions', + // loadOptionsDependsOn: [ + // '/name', + // ], + // }, + // default: '', + // description: 'Name of the option', + // }, + // ], + // }, + // ], + // }, + ], + }, + ], + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'create', + ], + }, + }, + options: [ + { + displayName: 'Branding Theme ID', + name: 'brandingThemeId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getBrandingThemes', + loadOptionsDependsOn: [ + 'organizationId', + ], + }, + default: '', + }, + { + displayName: 'Currency', + name: 'currency', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getCurrencies', + loadOptionsDependsOn: [ + 'organizationId', + ], + }, + default: '', + }, + { + displayName: 'Currency Rate', + name: 'currencyRate', + type: 'string', + default: '', + description: 'The currency rate for a multicurrency invoice. If no rate is specified, the XE.com day rate is used.', + }, + { + displayName: 'Date', + name: 'date', + type: 'dateTime', + default: '', + description: 'Date invoice was issued - YYYY-MM-DD. If the Date element is not specified it will default to the current date based on the timezone setting of the organisation', + }, + { + displayName: 'Due Date', + name: 'dueDate', + type: 'dateTime', + default: '', + description: 'Date invoice is due - YYYY-MM-DD', + }, + { + displayName: 'Expected Payment Date', + name: 'expectedPaymentDate', + type: 'dateTime', + default: '', + description: 'Shown on sales invoices (Accounts Receivable) when this has been set', + }, + { + displayName: 'Invoice Number', + name: 'invoiceNumber', + type: 'string', + default: '', + }, + { + displayName: 'Line Amount Type', + name: 'lineAmountType', + type: 'options', + options: [ + { + name: 'Exclusive', + value: 'Exclusive', + description: 'Line items are exclusive of tax', + }, + { + name: 'Inclusive', + value: 'Inclusive', + description: 'Line items are inclusive tax', + }, + { + name: 'NoTax', + value: 'NoTax', + description: 'Line have no tax', + }, + ], + default: 'Exclusive', + }, + { + displayName: 'Planned Payment Date ', + name: 'plannedPaymentDate', + type: 'dateTime', + default: '', + description: 'Shown on bills (Accounts Payable) when this has been set', + }, + { + displayName: 'Reference', + name: 'reference', + type: 'string', + default: '', + description: 'ACCREC only - additional reference number (max length = 255)', + }, + { + displayName: 'Send To Contact', + name: 'sendToContact', + type: 'boolean', + default: false, + description: 'Whether the invoice in the Xero app should be marked as "sent". This can be set only on invoices that have been approved', + }, + { + displayName: 'Status', + name: 'status', + type: 'options', + options: [ + { + name: 'Draft', + value: 'DRAFT', + }, + { + name: 'Submitted', + value: 'SUBMITTED', + }, + { + name: 'Authorised', + value: 'AUTHORISED', + }, + ], + default: 'DRAFT', + }, + { + displayName: 'URL', + name: 'url', + type: 'string', + default: '', + description: 'URL link to a source document - shown as "Go to [appName]" in the Xero app', + }, + ], + }, +/* -------------------------------------------------------------------------- */ +/* invoice:update */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTenants', + }, + default: '', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'update', + ], + }, + }, + required: true, + }, + { + displayName: 'Invoice ID', + name: 'invoiceId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'update', + ], + }, + }, + description: 'Invoice ID', + }, + { + displayName: 'Update Fields', + name: 'updateFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'update', + ], + }, + }, + options: [ + { + displayName: 'Branding Theme ID', + name: 'brandingThemeId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getBrandingThemes', + loadOptionsDependsOn: [ + 'organizationId', + ], + }, + default: '', + }, + { + displayName: 'Contact ID', + name: 'contactId', + type: 'string', + default: '', + description: 'Contact ID', + }, + { + displayName: 'Currency', + name: 'currency', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getCurrencies', + loadOptionsDependsOn: [ + 'organizationId', + ], + }, + default: '', + }, + { + displayName: 'Currency Rate', + name: 'currencyRate', + type: 'string', + default: '', + description: 'The currency rate for a multicurrency invoice. If no rate is specified, the XE.com day rate is used.', + }, + { + displayName: 'Date', + name: 'date', + type: 'dateTime', + default: '', + description: 'Date invoice was issued - YYYY-MM-DD. If the Date element is not specified it will default to the current date based on the timezone setting of the organisation', + }, + { + displayName: 'Due Date', + name: 'dueDate', + type: 'dateTime', + default: '', + description: 'Date invoice is due - YYYY-MM-DD', + }, + { + displayName: 'Expected Payment Date', + name: 'expectedPaymentDate', + type: 'dateTime', + default: '', + description: 'Shown on sales invoices (Accounts Receivable) when this has been set', + }, + { + displayName: 'Invoice Number', + name: 'invoiceNumber', + type: 'string', + default: '', + }, + { + displayName: 'Line Amount Type', + name: 'lineAmountType', + type: 'options', + options: [ + { + name: 'Exclusive', + value: 'Exclusive', + description: 'Line items are exclusive of tax', + }, + { + name: 'Inclusive', + value: 'Inclusive', + description: 'Line items are inclusive tax', + }, + { + name: 'NoTax', + value: 'NoTax', + description: 'Line have no tax', + }, + ], + default: 'Exclusive', + }, + { + displayName: 'Line Items', + name: 'lineItemsUi', + placeholder: 'Add Line Item', + type: 'fixedCollection', + default: '', + typeOptions: { + multipleValues: true, + }, + description: 'Line item data', + options: [ + { + name: 'lineItemsValues', + displayName: 'Line Item', + values: [ + { + displayName: 'Line Item ID', + name: 'lineItemId', + type: 'string', + default: '', + description: 'The Xero generated identifier for a LineItem', + }, + { + displayName: 'Description', + name: 'description', + type: 'string', + default: '', + description: 'A line item with just a description', + }, + { + displayName: 'Quantity', + name: 'quantity', + type: 'number', + default: 1, + typeOptions: { + minValue: 1, + }, + description: 'LineItem Quantity', + }, + { + displayName: 'Unit Amount', + name: 'unitAmount', + type: 'string', + default: '', + description: 'Lineitem unit amount. By default, unit amount will be rounded to two decimal places.', + }, + { + displayName: 'Item Code', + name: 'itemCode', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getItemCodes', + loadOptionsDependsOn: [ + 'organizationId', + ], + }, + default: '', + }, + { + displayName: 'Account Code', + name: 'accountCode', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getAccountCodes', + loadOptionsDependsOn: [ + 'organizationId', + ], + }, + default: '', + }, + { + displayName: 'Tax Type', + name: 'taxType', + type: 'options', + options: [ + { + name: 'Tax on Purchases', + value: 'INPUT', + }, + { + name: 'Tax Exempt', + value: 'NONE', + }, + { + name: 'Tax on Sales', + value: 'OUTPUT', + }, + { + name: 'Sales Tax on Imports ', + value: 'GSTONIMPORTS', + }, + ], + default: '', + required: true, + description: 'Tax Type', + }, + { + displayName: 'Tax Amount', + name: 'taxAmount', + type: 'string', + default: '', + description: 'The tax amount is auto calculated as a percentage of the line amount based on the tax rate.', + }, + { + displayName: 'Line Amount', + name: 'lineAmount', + type: 'string', + default: '', + description: 'The line amount reflects the discounted price if a DiscountRate has been used', + }, + { + displayName: 'Discount Rate', + name: 'discountRate', + type: 'string', + default: '', + description: 'Percentage discount or discount amount being applied to a line item. Only supported on ACCREC invoices - ACCPAY invoices and credit notes in Xero do not support discounts', + }, + // { + // displayName: 'Tracking', + // name: 'trackingUi', + // placeholder: 'Add Tracking', + // description: 'Any LineItem can have a maximum of 2 TrackingCategory elements.', + // type: 'fixedCollection', + // typeOptions: { + // multipleValues: true, + // }, + // default: {}, + // options: [ + // { + // name: 'trackingValues', + // displayName: 'Tracking', + // values: [ + // { + // displayName: 'Name', + // name: 'name', + // type: 'options', + // typeOptions: { + // loadOptionsMethod: 'getTrakingCategories', + // loadOptionsDependsOn: [ + // 'organizationId', + // ], + // }, + // default: '', + // description: 'Name of the tracking category', + // }, + // { + // displayName: 'Option', + // name: 'option', + // type: 'options', + // typeOptions: { + // loadOptionsMethod: 'getTrakingOptions', + // loadOptionsDependsOn: [ + // '/name', + // ], + // }, + // default: '', + // description: 'Name of the option', + // }, + // ], + // }, + // ], + // }, + ], + }, + ], + }, + { + displayName: 'Planned Payment Date ', + name: 'plannedPaymentDate', + type: 'dateTime', + default: '', + description: 'Shown on bills (Accounts Payable) when this has been set', + }, + { + displayName: 'Reference', + name: 'reference', + type: 'string', + default: '', + description: 'ACCREC only - additional reference number (max length = 255)', + }, + { + displayName: 'Send To Contact', + name: 'sendToContact', + type: 'boolean', + default: false, + description: 'Whether the invoice in the Xero app should be marked as "sent". This can be set only on invoices that have been approved', + }, + { + displayName: 'Status', + name: 'status', + type: 'options', + options: [ + { + name: 'Draft', + value: 'DRAFT', + }, + { + name: 'Submitted', + value: 'SUBMITTED', + }, + { + name: 'Authorised', + value: 'AUTHORISED', + }, + ], + default: 'DRAFT', + }, + { + displayName: 'URL', + name: 'url', + type: 'string', + default: '', + description: 'URL link to a source document - shown as "Go to [appName]" in the Xero app', + }, + ], + }, +/* -------------------------------------------------------------------------- */ +/* invoice:get */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTenants', + }, + default: '', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'get', + ], + }, + }, + required: true, + }, + { + displayName: 'Invoice ID', + name: 'invoiceId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'get', + ], + }, + }, + description: 'Invoice ID', + }, +/* -------------------------------------------------------------------------- */ +/* invoice:getAll */ +/* -------------------------------------------------------------------------- */ + { + displayName: 'Organization ID', + name: 'organizationId', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTenants', + }, + default: '', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'getAll', + ], + }, + }, + required: true, + }, + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'getAll', + ], + }, + }, + default: false, + description: 'If all results should be returned or only up to a given limit.', + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'getAll', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 100, + }, + default: 100, + description: 'How many results to return.', + }, + { + displayName: 'Options', + name: 'options', + type: 'collection', + placeholder: 'Add Option', + default: {}, + displayOptions: { + show: { + resource: [ + 'invoice', + ], + operation: [ + 'getAll', + ], + }, + }, + options: [ + { + displayName: 'Created By My App', + name: 'createdByMyApp', + type: 'boolean', + default: false, + description: `When set to true you'll only retrieve Invoices created by your app`, + }, + { + displayName: 'Order By', + name: 'orderBy', + type: 'string', + placeholder: 'InvoiceID', + default: '', + description: 'Order by any element returned', + }, + { + displayName: 'Sort Order', + name: 'sortOrder', + type: 'options', + options: [ + { + name: 'Asc', + value: 'ASC', + }, + { + name: 'Desc', + value: 'DESC', + }, + ], + default: '', + description: 'Sort order', + }, + { + displayName: 'Statuses', + name: 'statuses', + type: 'multiOptions', + options: [ + { + name: 'Draft', + value: 'DRAFT', + }, + { + name: 'Submitted', + value: 'SUBMITTED', + }, + { + name: 'Authorised', + value: 'AUTHORISED', + }, + ], + default: [], + }, + { + displayName: 'Where', + name: 'where', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + placeholder: 'EmailAddress!=null&&EmailAddress.StartsWith("boom")', + default: '', + description: `The where parameter allows you to filter on endpoints and elements that don't have explicit parameters. Examples Here`, + }, + ], + }, +] as INodeProperties[]; diff --git a/packages/nodes-base/nodes/Xero/InvoiceInterface.ts b/packages/nodes-base/nodes/Xero/InvoiceInterface.ts new file mode 100644 index 0000000000..6d6da63fb9 --- /dev/null +++ b/packages/nodes-base/nodes/Xero/InvoiceInterface.ts @@ -0,0 +1,40 @@ +import { + IDataObject, + } from 'n8n-workflow'; + + export interface ILineItem { + Description?: string; + Quantity?: string; + UnitAmount?: string; + ItemCode?: string; + AccountCode?: string; + LineItemID?: string; + TaxType?: string; + TaxAmount?: string; + LineAmount?: string; + DiscountRate?: string; + Tracking?: IDataObject[]; +} + +export interface IInvoice extends ITenantId { + Type?: string; + LineItems?: ILineItem[]; + Contact?: IDataObject; + Date?: string; + DueDate?: string; + LineAmountType?: string; + InvoiceNumber?: string; + Reference?: string; + BrandingThemeID?: string; + Url?: string; + CurrencyCode?: string; + CurrencyRate?: string; + Status?: string; + SentToContact?: boolean; + ExpectedPaymentDate?: string; + PlannedPaymentDate?: string; +} + +export interface ITenantId { + organizationId?: string; +} diff --git a/packages/nodes-base/nodes/Xero/Xero.node.ts b/packages/nodes-base/nodes/Xero/Xero.node.ts new file mode 100644 index 0000000000..31a1df36e8 --- /dev/null +++ b/packages/nodes-base/nodes/Xero/Xero.node.ts @@ -0,0 +1,681 @@ +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + IDataObject, + INodeTypeDescription, + INodeExecutionData, + INodeType, + ILoadOptionsFunctions, + INodePropertyOptions, +} from 'n8n-workflow'; + +import { + xeroApiRequest, + xeroApiRequestAllItems, +} from './GenericFunctions'; + +import { + invoiceFields, + invoiceOperations +} from './InvoiceDescription'; + +import { + contactFields, + contactOperations, +} from './ContactDescription'; + +import { + IInvoice, + ILineItem, +} from './InvoiceInterface'; + +import { + IContact, + // IPhone, + // IAddress, +} from './IContactInterface'; + +export class Xero implements INodeType { + description: INodeTypeDescription = { + displayName: 'Xero', + name: 'xero', + icon: 'file:xero.png', + group: ['output'], + version: 1, + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + description: 'Consume Xero API', + defaults: { + name: 'Xero', + color: '#13b5ea', + }, + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + name: 'xeroOAuth2Api', + required: true, + } + ], + properties: [ + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: 'Contact', + value: 'contact', + }, + { + name: 'Invoice', + value: 'invoice', + }, + ], + default: 'invoice', + description: 'Resource to consume.', + }, + // CONTACT + ...contactOperations, + ...contactFields, + // INVOICE + ...invoiceOperations, + ...invoiceFields, + ], + }; + + methods = { + loadOptions: { + // Get all the item codes to display them to user so that he can + // select them easily + async getItemCodes(this: ILoadOptionsFunctions): Promise { + const organizationId = this.getCurrentNodeParameter('organizationId'); + const returnData: INodePropertyOptions[] = []; + const { Items: items } = await xeroApiRequest.call(this, 'GET', '/items', { organizationId }); + for (const item of items) { + const itemName = item.Description; + const itemId = item.Code; + returnData.push({ + name: itemName, + value: itemId, + }); + } + return returnData; + }, + // Get all the account codes to display them to user so that he can + // select them easily + async getAccountCodes(this: ILoadOptionsFunctions): Promise { + const organizationId = this.getCurrentNodeParameter('organizationId'); + const returnData: INodePropertyOptions[] = []; + const { Accounts: accounts } = await xeroApiRequest.call(this, 'GET', '/Accounts', { organizationId }); + for (const account of accounts) { + const accountName = account.Name; + const accountId = account.Code; + returnData.push({ + name: accountName, + value: accountId, + }); + } + return returnData; + }, + // Get all the tenants to display them to user so that he can + // select them easily + async getTenants(this: ILoadOptionsFunctions): Promise { + const returnData: INodePropertyOptions[] = []; + const tenants = await xeroApiRequest.call(this, 'GET', '', {}, {}, 'https://api.xero.com/connections'); + for (const tenant of tenants) { + const tenantName = tenant.tenantName; + const tenantId = tenant.tenantId; + returnData.push({ + name: tenantName, + value: tenantId, + }); + } + return returnData; + }, + // Get all the brading themes to display them to user so that he can + // select them easily + async getBrandingThemes(this: ILoadOptionsFunctions): Promise { + const organizationId = this.getCurrentNodeParameter('organizationId'); + const returnData: INodePropertyOptions[] = []; + const { BrandingThemes: themes } = await xeroApiRequest.call(this, 'GET', '/BrandingThemes', { organizationId }); + for (const theme of themes) { + const themeName = theme.Name; + const themeId = theme.BrandingThemeID; + returnData.push({ + name: themeName, + value: themeId, + }); + } + return returnData; + }, + // Get all the brading themes to display them to user so that he can + // select them easily + async getCurrencies(this: ILoadOptionsFunctions): Promise { + const organizationId = this.getCurrentNodeParameter('organizationId'); + const returnData: INodePropertyOptions[] = []; + const { Currencies: currencies } = await xeroApiRequest.call(this, 'GET', '/Currencies', { organizationId }); + for (const currency of currencies) { + const currencyName = currency.Code; + const currencyId = currency.Description; + returnData.push({ + name: currencyName, + value: currencyId, + }); + } + return returnData; + }, + // Get all the tracking categories to display them to user so that he can + // select them easily + async getTrakingCategories(this: ILoadOptionsFunctions): Promise { + const organizationId = this.getCurrentNodeParameter('organizationId'); + const returnData: INodePropertyOptions[] = []; + const { TrackingCategories: categories } = await xeroApiRequest.call(this, 'GET', '/TrackingCategories', { organizationId }); + for (const category of categories) { + const categoryName = category.Name; + const categoryId = category.TrackingCategoryID; + returnData.push({ + name: categoryName, + value: categoryId, + }); + } + return returnData; + }, + // // Get all the tracking categories to display them to user so that he can + // // select them easily + // async getTrakingOptions(this: ILoadOptionsFunctions): Promise { + // const organizationId = this.getCurrentNodeParameter('organizationId'); + // const name = this.getCurrentNodeParameter('name'); + // const returnData: INodePropertyOptions[] = []; + // const { TrackingCategories: categories } = await xeroApiRequest.call(this, 'GET', '/TrackingCategories', { organizationId }); + // const { Options: options } = categories.filter((category: IDataObject) => category.Name === name)[0]; + // for (const option of options) { + // const optionName = option.Name; + // const optionId = option.TrackingOptionID; + // returnData.push({ + // name: optionName, + // value: optionId, + // }); + // } + // return returnData; + // }, + }, + }; + + async execute(this: IExecuteFunctions): Promise { + const items = this.getInputData(); + const returnData: IDataObject[] = []; + const length = items.length as unknown as number; + const qs: IDataObject = {}; + let responseData; + for (let i = 0; i < length; i++) { + const resource = this.getNodeParameter('resource', 0) as string; + const operation = this.getNodeParameter('operation', 0) as string; + //https://developer.xero.com/documentation/api/invoices + if (resource === 'invoice') { + if (operation === 'create') { + const organizationId = this.getNodeParameter('organizationId', i) as string; + const type = this.getNodeParameter('type', i) as string; + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + const contactId = this.getNodeParameter('contactId', i) as string; + const lineItemsValues = ((this.getNodeParameter('lineItemsUi', i) as IDataObject).lineItemsValues as IDataObject[]); + + const body: IInvoice = { + organizationId, + Type: type, + Contact: { ContactID: contactId }, + }; + + if (lineItemsValues) { + const lineItems: ILineItem[] = []; + for (const lineItemValue of lineItemsValues) { + const lineItem: ILineItem = { + Tracking: [], + }; + lineItem.AccountCode = lineItemValue.accountCode as string; + lineItem.Description = lineItemValue.description as string; + lineItem.DiscountRate = lineItemValue.discountRate as string; + lineItem.ItemCode = lineItemValue.itemCode as string; + lineItem.LineAmount = lineItemValue.lineAmount as string; + lineItem.Quantity = (lineItemValue.quantity as number).toString(); + lineItem.TaxAmount = lineItemValue.taxAmount as string; + lineItem.TaxType = lineItemValue.taxType as string; + lineItem.UnitAmount = lineItemValue.unitAmount as string; + // if (lineItemValue.trackingUi) { + // //@ts-ignore + // const { trackingValues } = lineItemValue.trackingUi as IDataObject[]; + // if (trackingValues) { + // for (const trackingValue of trackingValues) { + // const tracking: IDataObject = {}; + // tracking.Name = trackingValue.name as string; + // tracking.Option = trackingValue.option as string; + // lineItem.Tracking!.push(tracking); + // } + // } + // } + lineItems.push(lineItem); + } + body.LineItems = lineItems; + } + + if (additionalFields.brandingThemeId) { + body.BrandingThemeID = additionalFields.brandingThemeId as string; + } + if (additionalFields.currency) { + body.CurrencyCode = additionalFields.currency as string; + } + if (additionalFields.currencyRate) { + body.CurrencyRate = additionalFields.currencyRate as string; + } + if (additionalFields.date) { + body.Date = additionalFields.date as string; + } + if (additionalFields.dueDate) { + body.DueDate = additionalFields.dueDate as string; + } + if (additionalFields.dueDate) { + body.DueDate = additionalFields.dueDate as string; + } + if (additionalFields.expectedPaymentDate) { + body.ExpectedPaymentDate = additionalFields.expectedPaymentDate as string; + } + if (additionalFields.invoiceNumber) { + body.InvoiceNumber = additionalFields.invoiceNumber as string; + } + if (additionalFields.lineAmountType) { + body.LineAmountType = additionalFields.lineAmountType as string; + } + if (additionalFields.plannedPaymentDate) { + body.PlannedPaymentDate = additionalFields.plannedPaymentDate as string; + } + if (additionalFields.reference) { + body.Reference = additionalFields.reference as string; + } + if (additionalFields.sendToContact) { + body.SentToContact = additionalFields.sendToContact as boolean; + } + if (additionalFields.status) { + body.Status = additionalFields.status as string; + } + if (additionalFields.url) { + body.Url = additionalFields.url as string; + } + + responseData = await xeroApiRequest.call(this, 'POST', '/Invoices', body); + responseData = responseData.Invoices; + } + if (operation === 'update') { + const invoiceId = this.getNodeParameter('invoiceId', i) as string; + const organizationId = this.getNodeParameter('organizationId', i) as string; + const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; + + const body: IInvoice = { + organizationId, + }; + + if (updateFields.lineItemsUi) { + const lineItemsValues = (updateFields.lineItemsUi as IDataObject).lineItemsValues as IDataObject[]; + if (lineItemsValues) { + const lineItems: ILineItem[] = []; + for (const lineItemValue of lineItemsValues) { + const lineItem: ILineItem = { + Tracking: [], + }; + lineItem.AccountCode = lineItemValue.accountCode as string; + lineItem.Description = lineItemValue.description as string; + lineItem.DiscountRate = lineItemValue.discountRate as string; + lineItem.ItemCode = lineItemValue.itemCode as string; + lineItem.LineAmount = lineItemValue.lineAmount as string; + lineItem.Quantity = (lineItemValue.quantity as number).toString(); + lineItem.TaxAmount = lineItemValue.taxAmount as string; + lineItem.TaxType = lineItemValue.taxType as string; + lineItem.UnitAmount = lineItemValue.unitAmount as string; + // if (lineItemValue.trackingUi) { + // //@ts-ignore + // const { trackingValues } = lineItemValue.trackingUi as IDataObject[]; + // if (trackingValues) { + // for (const trackingValue of trackingValues) { + // const tracking: IDataObject = {}; + // tracking.Name = trackingValue.name as string; + // tracking.Option = trackingValue.option as string; + // lineItem.Tracking!.push(tracking); + // } + // } + // } + lineItems.push(lineItem); + } + body.LineItems = lineItems; + } + } + + if (updateFields.type) { + body.Type = updateFields.type as string; + } + if (updateFields.Contact) { + body.Contact = { ContactID: updateFields.contactId as string }; + } + if (updateFields.brandingThemeId) { + body.BrandingThemeID = updateFields.brandingThemeId as string; + } + if (updateFields.currency) { + body.CurrencyCode = updateFields.currency as string; + } + if (updateFields.currencyRate) { + body.CurrencyRate = updateFields.currencyRate as string; + } + if (updateFields.date) { + body.Date = updateFields.date as string; + } + if (updateFields.dueDate) { + body.DueDate = updateFields.dueDate as string; + } + if (updateFields.dueDate) { + body.DueDate = updateFields.dueDate as string; + } + if (updateFields.expectedPaymentDate) { + body.ExpectedPaymentDate = updateFields.expectedPaymentDate as string; + } + if (updateFields.invoiceNumber) { + body.InvoiceNumber = updateFields.invoiceNumber as string; + } + if (updateFields.lineAmountType) { + body.LineAmountType = updateFields.lineAmountType as string; + } + if (updateFields.plannedPaymentDate) { + body.PlannedPaymentDate = updateFields.plannedPaymentDate as string; + } + if (updateFields.reference) { + body.Reference = updateFields.reference as string; + } + if (updateFields.sendToContact) { + body.SentToContact = updateFields.sendToContact as boolean; + } + if (updateFields.status) { + body.Status = updateFields.status as string; + } + if (updateFields.url) { + body.Url = updateFields.url as string; + } + + responseData = await xeroApiRequest.call(this, 'POST', `/Invoices/${invoiceId}`, body); + responseData = responseData.Invoices; + } + if (operation === 'get') { + const organizationId = this.getNodeParameter('organizationId', i) as string; + const invoiceId = this.getNodeParameter('invoiceId', i) as string; + responseData = await xeroApiRequest.call(this, 'GET', `/Invoices/${invoiceId}`, { organizationId }); + responseData = responseData.Invoices; + } + if (operation === 'getAll') { + const organizationId = this.getNodeParameter('organizationId', i) as string; + const returnAll = this.getNodeParameter('returnAll', i) as boolean; + const options = this.getNodeParameter('options', i) as IDataObject; + if (options.statuses) { + qs.statuses = (options.statuses as string[]).join(','); + } + if (options.orderBy) { + qs.order = `${options.orderBy} ${(options.sortOrder === undefined) ? 'DESC' : options.sortOrder}`; + } + if (options.where) { + qs.where = options.where; + } + if (options.createdByMyApp) { + qs.createdByMyApp = options.createdByMyApp as boolean; + } + if (returnAll) { + responseData = await xeroApiRequestAllItems.call(this, 'Invoices', 'GET', '/Invoices', { organizationId }, qs); + } else { + const limit = this.getNodeParameter('limit', i) as number; + responseData = await xeroApiRequest.call(this, 'GET', `/Invoices`, { organizationId }, qs); + responseData = responseData.Invoices; + responseData = responseData.splice(0, limit); + } + } + } + if (resource === 'contact') { + } + if (operation === 'create') { + const organizationId = this.getNodeParameter('organizationId', i) as string; + const name = this.getNodeParameter('name', i) as string; + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + // const addressesUi = additionalFields.addressesUi as IDataObject; + // const phonesUi = additionalFields.phonesUi as IDataObject; + + const body: IContact = { + Name: name, + }; + + if (additionalFields.accountNumber) { + body.AccountNumber = additionalFields.accountNumber as string; + } + + if (additionalFields.bankAccountDetails) { + body.BankAccountDetails = additionalFields.bankAccountDetails as string; + } + + if (additionalFields.contactNumber) { + body.ContactNumber = additionalFields.contactNumber as string; + } + + if (additionalFields.contactStatus) { + body.ContactStatus = additionalFields.contactStatus as string; + } + + if (additionalFields.defaultCurrency) { + body.DefaultCurrency = additionalFields.defaultCurrency as string; + } + + if (additionalFields.emailAddress) { + body.EmailAddress = additionalFields.emailAddress as string; + } + + if (additionalFields.firstName) { + body.FirstName = additionalFields.firstName as string; + } + + if (additionalFields.lastName) { + body.LastName = additionalFields.lastName as string; + } + + if (additionalFields.purchasesDefaultAccountCode) { + body.PurchasesDefaultAccountCode = additionalFields.purchasesDefaultAccountCode as string; + } + + if (additionalFields.salesDefaultAccountCode) { + body.SalesDefaultAccountCode = additionalFields.salesDefaultAccountCode as string; + } + + if (additionalFields.skypeUserName) { + body.SkypeUserName = additionalFields.skypeUserName as string; + } + + if (additionalFields.taxNumber) { + body.taxNumber = additionalFields.taxNumber as string; + } + + if (additionalFields.xeroNetworkKey) { + body.xeroNetworkKey = additionalFields.xeroNetworkKey as string; + } + + // if (phonesUi) { + // const phoneValues = phonesUi?.phonesValues as IDataObject[]; + // if (phoneValues) { + // const phones: IPhone[] = []; + // for (const phoneValue of phoneValues) { + // const phone: IPhone = {}; + // phone.Type = phoneValue.type as string; + // phone.PhoneNumber = phoneValue.PhoneNumber as string; + // phone.PhoneAreaCode = phoneValue.phoneAreaCode as string; + // phone.PhoneCountryCode = phoneValue.phoneCountryCode as string; + // phones.push(phone); + // } + // body.Phones = phones; + // } + // } + + // if (addressesUi) { + // const addressValues = addressesUi?.addressesValues as IDataObject[]; + // if (addressValues) { + // const addresses: IAddress[] = []; + // for (const addressValue of addressValues) { + // const address: IAddress = {}; + // address.Type = addressValue.type as string; + // address.AddressLine1 = addressValue.line1 as string; + // address.AddressLine2 = addressValue.line2 as string; + // address.City = addressValue.city as string; + // address.Region = addressValue.region as string; + // address.PostalCode = addressValue.postalCode as string; + // address.Country = addressValue.country as string; + // address.AttentionTo = addressValue.attentionTo as string; + // addresses.push(address); + // } + // body.Addresses = addresses; + // } + // } + + responseData = await xeroApiRequest.call(this, 'POST', '/Contacts', { organizationId, Contacts: [body] }); + responseData = responseData.Contacts; + } + if (operation === 'get') { + const organizationId = this.getNodeParameter('organizationId', i) as string; + const contactId = this.getNodeParameter('contactId', i) as string; + responseData = await xeroApiRequest.call(this, 'GET', `/Contacts/${contactId}`, { organizationId }); + responseData = responseData.Contacts; + } + if (operation === 'getAll') { + const organizationId = this.getNodeParameter('organizationId', i) as string; + const returnAll = this.getNodeParameter('returnAll', i) as boolean; + const options = this.getNodeParameter('options', i) as IDataObject; + if (options.includeArchived) { + qs.includeArchived = options.includeArchived as boolean; + } + if (options.orderBy) { + qs.order = `${options.orderBy} ${(options.sortOrder === undefined) ? 'DESC' : options.sortOrder}`; + } + if (options.where) { + qs.where = options.where; + } + if (returnAll) { + responseData = await xeroApiRequestAllItems.call(this, 'Contacts', 'GET', '/Contacts', { organizationId }, qs); + } else { + const limit = this.getNodeParameter('limit', i) as number; + responseData = await xeroApiRequest.call(this, 'GET', `/Contacts`, { organizationId }, qs); + responseData = responseData.Contacts; + responseData = responseData.splice(0, limit); + } + + } + if (operation === 'update') { + const organizationId = this.getNodeParameter('organizationId', i) as string; + const contactId = this.getNodeParameter('contactId', i) as string; + const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; + // const addressesUi = updateFields.addressesUi as IDataObject; + // const phonesUi = updateFields.phonesUi as IDataObject; + + const body: IContact = {}; + + if (updateFields.accountNumber) { + body.AccountNumber = updateFields.accountNumber as string; + } + + if (updateFields.name) { + body.Name = updateFields.name as string; + } + + if (updateFields.bankAccountDetails) { + body.BankAccountDetails = updateFields.bankAccountDetails as string; + } + + if (updateFields.contactNumber) { + body.ContactNumber = updateFields.contactNumber as string; + } + + if (updateFields.contactStatus) { + body.ContactStatus = updateFields.contactStatus as string; + } + + if (updateFields.defaultCurrency) { + body.DefaultCurrency = updateFields.defaultCurrency as string; + } + + if (updateFields.emailAddress) { + body.EmailAddress = updateFields.emailAddress as string; + } + + if (updateFields.firstName) { + body.FirstName = updateFields.firstName as string; + } + + if (updateFields.lastName) { + body.LastName = updateFields.lastName as string; + } + + if (updateFields.purchasesDefaultAccountCode) { + body.PurchasesDefaultAccountCode = updateFields.purchasesDefaultAccountCode as string; + } + + if (updateFields.salesDefaultAccountCode) { + body.SalesDefaultAccountCode = updateFields.salesDefaultAccountCode as string; + } + + if (updateFields.skypeUserName) { + body.SkypeUserName = updateFields.skypeUserName as string; + } + + if (updateFields.taxNumber) { + body.taxNumber = updateFields.taxNumber as string; + } + + if (updateFields.xeroNetworkKey) { + body.xeroNetworkKey = updateFields.xeroNetworkKey as string; + } + + // if (phonesUi) { + // const phoneValues = phonesUi?.phonesValues as IDataObject[]; + // if (phoneValues) { + // const phones: IPhone[] = []; + // for (const phoneValue of phoneValues) { + // const phone: IPhone = {}; + // phone.Type = phoneValue.type as string; + // phone.PhoneNumber = phoneValue.PhoneNumber as string; + // phone.PhoneAreaCode = phoneValue.phoneAreaCode as string; + // phone.PhoneCountryCode = phoneValue.phoneCountryCode as string; + // phones.push(phone); + // } + // body.Phones = phones; + // } + // } + + // if (addressesUi) { + // const addressValues = addressesUi?.addressesValues as IDataObject[]; + // if (addressValues) { + // const addresses: IAddress[] = []; + // for (const addressValue of addressValues) { + // const address: IAddress = {}; + // address.Type = addressValue.type as string; + // address.AddressLine1 = addressValue.line1 as string; + // address.AddressLine2 = addressValue.line2 as string; + // address.City = addressValue.city as string; + // address.Region = addressValue.region as string; + // address.PostalCode = addressValue.postalCode as string; + // address.Country = addressValue.country as string; + // address.AttentionTo = addressValue.attentionTo as string; + // addresses.push(address); + // } + // body.Addresses = addresses; + // } + // } + + responseData = await xeroApiRequest.call(this, 'POST', `/Contacts/${contactId}`, { organizationId, Contacts: [body] }); + responseData = responseData.Contacts; + } + if (Array.isArray(responseData)) { + returnData.push.apply(returnData, responseData as IDataObject[]); + } else { + returnData.push(responseData as IDataObject); + } + } + return [this.helpers.returnJsonArray(returnData)]; + } +} diff --git a/packages/nodes-base/nodes/Xero/xero.png b/packages/nodes-base/nodes/Xero/xero.png new file mode 100644 index 0000000000000000000000000000000000000000..a9d46c10aacd655047a0039b75024aebcab3cf84 GIT binary patch literal 9587 zcmZ`hB^UV9qhyM&TDM*<}0RRAnww9Xlz5VaLy(YoG?{n69 zckc~>i;BJq08pPycH=;JKjv`MGS&wGf_MOch<5j|wQ%^w-CFehMTKNCf;CS~Y_;ZU z20*AJ>D_nsdVp+ocl^Xpc-n=bjINUL8jW2S9s%7gSvQcC>&@Ustq0%5Z0yDs+h$tY z4Zk1^zxaM<0ynWGX%^trjnY9DIb}ITbu)sKqZey-RQLa+K`nX(3T{8-K3=zSQeL1 zziFW}7cvM0%K<(a`;6y4(vv|DCK#y#9gRT%b55!H`CnHsMn^!p@sK%xDdKzshd>v+ z5OLJwhw2dXbF(UiS?kQ%yNYKwSqiUQl+U=DnB0b~P{;Nc3FiB^=i^{3sC)wybm=It z3c*HBWVy5Ey#=$aoYk3;)Sn^J?O&rBI={X})@Y{Hueh~$WtqZ%4xO+9V4(MW=}tn& z!%Z8(kx$C8+9nKSWMuU2v87iq-jaGWvRic0QY1OH0Eg(KgDc32Odech7?(`(kwl4- zr#&4$=~y}N9p_JS-AsehLiZm;%0V&epUUilPuQ}aTkUcB8Eu=+bP-# zKN@w?IL+f{o$=O{SC2FO{uVSk_OB1(Jj@TKuJFcP4kLCiKV%*ticRwdEK)>H%{J*& z{n~FEgiu&W`_g%6xOnz!6Dc4$KuAPHK51s#?^xlBLAk_KVS2HoJ|5L$0C;cL;SO}7 zr$!+%*4dQ#8PWW-=4+*_kNtsKIQZaBGnpkkEd5!eOP_G->pmlEpr~kZ8lZ&nBjZ>R zt4TZjc;}6BkR~tEd114%*>jGb3-GPk*z8eHg6Afoy|7fgEcOS^On$|If-)I}H7Lgh zEj!6oj7S`qmSdo-0g`O4)fftTQWFtFYWc0iND+4aeOSnZuWs7Uc^$1MPGhA!&hK5x z^hc=yqkw{cywQ&VaUcy}8(j}48v>_iD-B2b3nHx{`7OG|#83O{P0sq(<*Lt)kBg7<$-n4HR>CdB*OV2hW?M#2>^M(XwK?efgRkDx-c$3YZnPa{XHW$ zeqgcr31VXgwlT@T%H*98QDLBX=^$;jnjL}CKS)nG$<_B7O#0G<2lPsmOm`uTBL~mRou4w-=?6T0^ zo@a8z)9{Ys-dFhgN0U9o87D!!958~AhH`#Thq9_q17Fd`U}cPdC`?qsN&BhnXI$51 zRCOxS1wQtjDDZ=F%5?ad5;gKpM9FuM;|-%H3K-~#f|*W?0||#V^*D@HUERn@eV;G| zlK=2fH8T0d>_SeZYR;lOdrZF$E^FuT!gPXyAPS zZs{}9CV+a%lhVT*u5;t)M&!u|186O{8bn12{@(TE|3h+yIRp59Egl&h#u&0Qy*U0r zyc|A)Xc18}v1OvFL;6r9Aim~`#G69R}{%Ze)r=3O-K-DMSF5CkqQ=*IOWWSu8=6wt!AW{v1LENn$98JZ_>=VHaoNO zC(7oOKV}{b%v8Yd@z>>H$<%j9UaUacQ`eS-B&=TftI~8)w?QALLZV7l5=Xs~9Xvh| zc~we-&l2}4<{#^Cs@Zf@Ob7yd=e*~ulOG&WrRn+0Ofx>VA4G(czn=sOhOk{$w|95RH>Z8G zlVS;`uRjgN3o+;iI&%smw~uofq9~UkP!ay;t>UR6tsQ!5w_)9I_~t4EZt12sLR2{x zSyVrgD5gpRsA&FiVfW@T`9k4u;)V>FoU9|!=rq&0`O9gSCkMVf*E1%VoPXR=_2ffw zk5ad1Suf0%!^R#(S)ujJC}NpSK?zdjSwt*D!1&_t(4}Fg;`EQj-+>Zr$))K=wA>bQ zV?K}nYBGl1da+#&`N(-t81p#u3^6O3x7_Vdf|E;;61>1#e0lbT=@_H`t z!{zcbL5%8;A19))8Y919FS7Ocw5hq=o;D&f#nAtCN5*`T`t?xrChPjkbzkHY$WOx$ z-ADnP$uIoR-?v2BmLPZQah@=bmeJDZkFaP<#~vV)w{u~=h9;~4CF`~8HgUp~@6O5# z9nfT(zb*|GNwgy4FFCLy>i#np1sW*dgWA3D-gPu&V`;lwC!?xPgEjif&!f4kWq_pDQ z!CmiOz@yf@1XfNP%stT5>=5Ov8vz~7vFUHeTdYX{_prn%u)QmIh`I>HzQc^ilz1P% zJ&r~T^+tfKAN4PP*$q1cQ2EwM{?w}2e7E?%23a%rR`N%KyC_hLU$f-ldy!M(lHwPD zo7t8xunI{8jeuyx?LP)1k(KYyTe%zR2ncCCTa_yB{4Qpozd1?nuOcz$B_vehK(iKO z)t^qG75kZ@^E%ndE^uFYzlHSE(8vGou49kLJz|OUtD4fUt3~z{PkU&kG(9E?f0@@} z$fE3Fu(o^Z(p{^psaZmBd5R5Ax?YNs&tyWp?b(`LUpFIu?G`pl4gTcdK(?Pp(jMM* zz2>MKFxfI-m?y*eZtE<_A~R9ri77@9XT@b~X#!wA^*>-%3=2sOHoA)D%`}W&z&Dqz zr!uk6W_}@|!}hD4_JPz?2aT!D@DLVKfXg?~BoVW=L?=n(?T6iDTL{MaiN(a4~(JkyllS84X0vFFKRCf4-XrEBYKBb`3P4MKb4~YOi01wJ$lt3NX;U)|&P8cOc5H!#D1QvJ&>b zj@fN1g8JcQCaHwEVhb!v6TaAC7jQ0aMobU=Nil}>bl9ZYACpP$Sl`=1$udsTR_|Ky zkkc9iTJn@8iQ0BD#@AS{??<_9OO|)16{I-x*AApP;W=V@CR?L~f#i*u_9UCTs$gi% z?5)gT^io3quy_N3#6rGAB0eF!^rZS$gpKI?3H{&b&87ioXK`9V0wsBM z3lZx_O)=CdHjj4%6%##JYDR(69~t|r>FV6iu!uzxz*u%{m9uCiRl4It`gUO%_dqwRe+e`=YSZ?Q*Y<{T%(rnUQw4(=!uE5~wZP z>@Lvtkd?^1zr)HlJ`wQ2gh-ZM&~cjxyTbE_NGjXeK&>j9-nRPKqjdS;q`XP8_{xF@ z)Jq0t%$*$ydYEeYRA)vSCZ}qTDso*~opQpPtwCn8?SBW|xBk;?dYq^5##AtCHatxz ze6?A+VG2Gus8N%snt#(kl9|@U}3No2JeSlI5@^je=T^+Zo^`pXnWAeNDLC}MXVykDNp+4K}VRv`Y zrLoMJ=%`Eb;UC56`voPaQBeGCFY^9Dk^UF~PZTqtDkIVys`m-;z{3}+BtggD{kiL2 z3fh4NxO<1aacQx!IVGl4dKEyg6VF7h?6fmD{NW4oES9~CW4Z@LnGv9L{2I`)U7X+T zJx2KKkgG1(?s%*BWm+)_%hkO8j#uzlpYy6+M_ISJ?a>0I!gJS$pu{>$d~&UbiM=l& zxWSURhByDFy)}Q|;^e(#C_m%3J1W$<{9Bt!f8TuCE^XViASMJWgGggRer{ZB_@P~B9s0Rji|y-6yW|5_*&=5rv!{5jZ}RG0zJ$EF zjXeoa55c_Az1r&xzOX=nlnX08@_9*;uSV%FG~FRE2#YIoi#1?+I!thVuo zoxHNUUSED0OzKvD+MC68Ppkh9>bG;XA#mNVVZ1Ttz;+)O<%{5Q8B$Cghok}mVP5|=Ejc)FD~e=PX?oQS-73>S|3 zpqPO*p@=n8la_dw`NM0WLrf^ml^U5M&9sXK0A%EROC?>cGak(b4+l6}z ziukf9b-7&`fLM3Xq}$=u4ByIfSNGBQidsf`&v8o{nLEYfoM_5{*YNdCxB4(x89)} zzOTVgEicxB_fb|}Na)n9i~O}0a|aZ>Vi=js{_Nl3otI&8U{w@)GLbFt{4mkXbG~g0YK?21O89J{ZY8lKIs7rE=OQ$V zu$WKai8bD5iR`mR`2}jdwxXuL6EAM((0kHdCw+rsp(_BpFrO7owh;em+b@u9bMIzuK^V5%tm_}X%REBgc52I#DEk~rl5$YTenG4h~v)3V&X$jF-}%G{R#ce3REE#ZnoGq6yiZa`8b)qigtx z#Q{ofn6d0(ak4SxXB+?u89@2aC)+FE*k{GBCiapT)Y#&&Rg*g222R@G{tshDy%py< zj!j-}N{qMP_gcDKtz1ZcbN_v|95OaYTr!xfc+>hJDCe`ov6}cSNi5`SEjcu33qc1N z1B@8h;#&^s?^&i)XFYKKztfx<=hR*Fod}SS2Cqv2;v$+&}f7FRzTFBbUvhRWCR|A>SMpd~gR6 z(d#__qU3w%EAkBdt5j%YskwH?GsU*sv69Hvyk-cd?@{B>Yhc-}76ET;@C*)H^&SG! zkdu?J$oB8tv?Val8pC+mZhwzqI>Es!_;w01f1`sBlxT(T_7&}xLOU{hY-$&LFeX_D zo{_G?P|d7@&&7ac*p8HNWnrTK?czgY-qCzzS+>XZNaRkE^uHg;OI@&&GGpeE!05!b zSBfH^TMybE5PHw>;L1+uZ?-3&SZUniC>C4->HHNMdi_o_S*>hWR7e*u7VlEYqSMyl zDXpVirwZBtMi0pye`FE+Q^5Q~340B#U@B-5Mx4QO)0;wEL zEwm1CnQPa2FoFV;g{-ba586XCKMzS^!*3@`#Jm%u?U2|_VH0Y-xQ1t1CdC4`fenz5 z-Dt1Yo0`ON!k!_~h*_soh1d^TRk^Xh989in=76uaJ+8P6~U5SJ{Ksn-hIj*HurW=8MYd_+4l0K zk1{}vs#PipQSE+nCv6SGowE_|hl<_h*D8o6{N)c2Gt0eV z+zUTCoEm-&%f|@6v$8y1A8C=-s8iVc7ScF?$YoISMnS#I$qDMN|2sY+W*6-IZr(oZ z5U~HNFd|v$Vp^8cPMa=uF9$UZP4xDcF2=3uH1l36TGH0gJhdu7z z`6IZ}*tr4tq5!{JUG~zCGI+-F!1E#6nDaKPFJ=Xa1D`fa+qCzDudfs4yLSgqM0N*W zRv6ozF6*MZi2|4Ca?j{;$qG~IN#92rveo=M1yd$W?FYv_Z6G&6HpYQHMDIZzgMrkLeWtDN)&r=AU9)xX< zum@sT&Cb@;j06-|3BqslUCwvq5BCK{x{f>E0@NZ1%X(&B-byDc9L@G)wI_$$z<5KK zQ%xa{zDLrOPA_uyP?3^cR>utu$G!NAVDECr<@$Tf3$5V+#8;IggTKIzUKuI|=v`*7 z@PEi(ciccD;qyPYHQ(_a-am%nZrtBMR|Bcbt!q!>;#aPINT-@Aak`pmF%?xm+ij*~ zm!)o3>CMkcDShR2#99(9M`{0DScuKimI-1fcAQ9UvR2`IGt*>Vhz*7->DADEZdkKtb8>G>;1#Jc{^S5@q4R!#20s}x zM~fymxgs0!@o1i+Y>17Wn@WX->yvlf)qeVD!*no;keM#$^G1P3T+ZigiAM>bwnN*= zd1@i7zkxNF=z)d!@S=C|Y>M6!eSjlST4h4ivncY_5^LgbtYwP{>>vKoVP5KUY(xEr^`{&64Y;U`?WlXZ1Y zm>ktiW%}47*san;BA`i1jT~PM-$}SoxUtT~*N-OQr(3XmU^Vfp>;_YZc*xM4y(me) zw?zM!Og^u8lWTZt$Q62ebv$Wl=dEEKGRZk#_t74ge1pY|EsdUaC!c2G>`K6 z220794C!kc+D@MicC*1!W_s%$P6;4+gAlXfkiKNC*pSS8bL4$u*C)|gVq zq~$4#DMoihSB2{II+Ula|ATAw2d&g?fY&0#p;Ai$JWldikxY0jWPdF5<|Bhc>}ZC( z+5_sH$HxhZ|Mr!r?+A z<}4`vXGQ5g;@RHg#L;-uA@)a+(zciyp9;E`at~aL6lO?vg`RH$mju@HlWuV>Hr;sM zO`(iIPW?xGV~sotVcP@Zyi*4k@x{PIjZV{_3?cPHB8y?S1{nmPA=_BU1V1&nOR3*Y zVLYI>rF{622D);l`f6*X8#|<{n2vRo%|8!P#GGYi#)?XAo$VlP@5={-d$DWo>jj>N z)!GN2jNMGcYzWnZY_k6Cw5%X2^87#kl5i1~wJTL#@Fj`2oXNEY&#MR7X58E?tegh1 zCy7UL@SCREpno!RZS^hA63T+OyU_pT_Vv8nZ z6H$&}4`4G~M?dY?iNeH5s;jjroZ&Le$Y!l^CGbMni~RB66NUj{182g~_`J>6O+(Id zRtXqER9OC_YO;^hM--~J%MM!WVSv z5S=02G$%?8q$%Jj1Cd~Yjc>O6I>(_>SN#Q9@FS-%`7BRuy?VrZj~dG{ZQ`-Y$tpTD z5`76LIr)9g$`EoG>%ojyuz~l|x6dQtJHqFi!#diA)Bo=#yk_cOv$K( zdJd8t`+HF)m$C`1LIwEVkl@Qkpz@#_M`-j3u$_KI|_a&3f|){zd=0ACXjo%brv!&DfEQv6C~j%-mfTcvDJ00hS~EMUCMV8 zl3v+(6VN-9EM8gB+H3>81__#~*^hNdmb^lzG2$WTw@Be6M--%(Piv-$4{lmHE2?PW zCzr320b#km)4@xD!{w@r+Z|bh*E78b5xe9PLY{ z>ttr*O%Jw#>0{9(J)Hm9kecY)_!ruR-@%kZ&T0e|2}-vmWSrJzc*c=?1{RsxsRSyk z*I_Ius7-(zYmXie4QJlH8cqkx1XYW=3BdVE2SPF;G|nW5z=%kWar>%B?h%;}L|)_r z%3~6|y#PvoquiFWe0k6LGvm%3u;IbK&ATTPhOv&DU;7YA#5_H%co43cKqp)g_ZxzH z0L)?Dm@T#2P_)_mqj7%}{0B2BZm+sHJyKC_zW_VaBm@Mc2+L}3~Fn)>xI z!}C%6V;wF+<*zDy6xfJWXo(!;>{^}V@}HmK<>2ER>u{>2)oj8F5Y0lmL+`LMIwnvX zUCde@Wp@VjGcKpe$vqvWNm4=o_7({d4#qg=VTx|n?X@EjA@IW!{b7i-=rOUJIw zmDTy5oual9;$=Y_jgJJ~7t`ZOqawtf=Nm9{o0^!UJ{2qjrB-FeE5H1wLPe`SW$sO5_`qrmIj%A_$^5yi3#cd8a=Y;E>P?-jUE=2Ajz3_vORII1Q(f;qTlt zk3vjl@57->DOZ{VpUVyIIl6f^@xrSBCo$tAm(S!F#qsv%ryZmU)qfV5E|oJU;xQpC zD7?aSeDCHy^~8y{Wo(8AlYHkEabzf?qbGS{n=%Hkh)Ts=nbT?_tNA{f zL6+zCM<=Xk2O0HrF;M22pyj61(0fg@K`0l_JEmH~H*G0RUv+S;ZuHt@<2uYS&k9_^ z2j4-89VtwJ^%i48rzI5`($255rANduP#kU}uMt_3n@Xwn8gnM3*i}>-OYJPhne!-- zb>8V@tb;o--A&669Vzx)uuH0var)Di5WDwtFURSwk0;O5SNuNbf4O6qAzhN;bz=*^ z|CPk;r*7`& { // tslint:disable-line:no-any - const credentials = this.getCredentials('zendeskApi'); - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - const base64Key = Buffer.from(`${credentials.email}/token:${credentials.apiToken}`).toString('base64'); + const authenticationMethod = this.getNodeParameter('authentication', 0); + let options: OptionsWithUri = { - headers: { 'Authorization': `Basic ${base64Key}`}, + headers: {}, method, qs, body, - uri: uri ||`${credentials.url}/api/v2${resource}.json`, + //@ts-ignore + uri, json: true }; + options = Object.assign({}, options, option); if (Object.keys(options.body).length === 0) { delete options.body; } + try { - return await this.helpers.request!(options); - } catch (err) { + if (authenticationMethod === 'apiToken') { + const credentials = this.getCredentials('zendeskApi'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + const base64Key = Buffer.from(`${credentials.email}/token:${credentials.apiToken}`).toString('base64'); + options.uri = `https://${credentials.subdomain}.zendesk.com/api/v2${resource}.json`; + options.headers!['Authorization'] = `Basic ${base64Key}`; + + return await this.helpers.request!(options); + } else { + const credentials = this.getCredentials('zendeskOAuth2Api'); + + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + + options.uri = `https://${credentials.subdomain}.zendesk.com/api/v2${resource}.json`; + + return await this.helpers.requestOAuth2!.call(this, 'zendeskOAuth2Api', options); + } + } catch(err) { let errorMessage = err.message; if (err.response && err.response.body && err.response.body.error) { errorMessage = err.response.body.error; diff --git a/packages/nodes-base/nodes/Zendesk/Zendesk.node.ts b/packages/nodes-base/nodes/Zendesk/Zendesk.node.ts index 8a2586d8d8..d0c72c335f 100644 --- a/packages/nodes-base/nodes/Zendesk/Zendesk.node.ts +++ b/packages/nodes-base/nodes/Zendesk/Zendesk.node.ts @@ -52,9 +52,44 @@ export class Zendesk implements INodeType { { name: 'zendeskApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'apiToken', + ], + }, + }, + }, + { + name: 'zendeskOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'API Token', + value: 'apiToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'apiToken', + description: 'The resource to operate on.', + }, { displayName: 'Resource', name: 'resource', diff --git a/packages/nodes-base/nodes/Zendesk/ZendeskTrigger.node.ts b/packages/nodes-base/nodes/Zendesk/ZendeskTrigger.node.ts index cc4e26dbd4..421d9e4b32 100644 --- a/packages/nodes-base/nodes/Zendesk/ZendeskTrigger.node.ts +++ b/packages/nodes-base/nodes/Zendesk/ZendeskTrigger.node.ts @@ -42,7 +42,25 @@ export class ZendeskTrigger implements INodeType { { name: 'zendeskApi', required: true, - } + displayOptions: { + show: { + authentication: [ + 'apiToken', + ], + }, + }, + }, + { + name: 'zendeskOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, ], webhooks: [ { @@ -53,6 +71,23 @@ export class ZendeskTrigger implements INodeType { }, ], properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'API Token', + value: 'apiToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'apiToken', + description: 'The resource to operate on.', + }, { displayName: 'Service', name: 'service', diff --git a/packages/nodes-base/nodes/Zoom/GenericFunctions.ts b/packages/nodes-base/nodes/Zoom/GenericFunctions.ts new file mode 100644 index 0000000000..3d036f5f39 --- /dev/null +++ b/packages/nodes-base/nodes/Zoom/GenericFunctions.ts @@ -0,0 +1,104 @@ +import { + OptionsWithUri, +} from 'request'; + +import { + IExecuteFunctions, + IExecuteSingleFunctions, + ILoadOptionsFunctions, +} from 'n8n-core'; + +import { + IDataObject, +} from 'n8n-workflow'; + +export async function zoomApiRequest(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string, resource: string, body: object = {}, query: object = {}, headers: {} | undefined = undefined, option: {} = {}): Promise { // tslint:disable-line:no-any + + const authenticationMethod = this.getNodeParameter('authentication', 0, 'accessToken') as string; + + let options: OptionsWithUri = { + method, + headers: headers || { + 'Content-Type': 'application/json' + }, + body, + qs: query, + uri: `https://api.zoom.us/v2${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; + } + + try { + if (authenticationMethod === 'accessToken') { + const credentials = this.getCredentials('zoomApi'); + if (credentials === undefined) { + throw new Error('No credentials got returned!'); + } + options.headers!.Authorization = `Bearer ${credentials.accessToken}`; + + //@ts-ignore + return await this.helpers.request(options); + } else { + //@ts-ignore + return await this.helpers.requestOAuth2.call(this, 'zoomOAuth2Api', options); + } + } catch (error) { + if (error.statusCode === 401) { + // Return a clear error + throw new Error('The Zoom credentials are not valid!'); + } + + if (error.response && error.response.body && error.response.body.message) { + // Try to return the error prettier + throw new Error(`Zoom error response [${error.statusCode}]: ${error.response.body.message}`); + } + + // If that data does not exist for some reason return the actual error + throw error; + } +} + + +export async function zoomApiRequestAllItems( + this: IExecuteFunctions | ILoadOptionsFunctions, + propertyName: string, + method: string, + endpoint: string, + body: IDataObject = {}, + query: IDataObject = {} +): Promise { // tslint:disable-line:no-any + const returnData: IDataObject[] = []; + let responseData; + query.page_number = 0; + do { + responseData = await zoomApiRequest.call( + this, + method, + endpoint, + body, + query + ); + query.page_number++; + returnData.push.apply(returnData, responseData[propertyName]); + // zoom free plan rate limit is 1 request/second + // TODO just wait when the plan is free + await wait(); + } while ( + responseData.page_count !== responseData.page_number + ); + + return returnData; +} +function wait() { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(true); + }, 1000); + }); +} diff --git a/packages/nodes-base/nodes/Zoom/MeetingDescription.ts b/packages/nodes-base/nodes/Zoom/MeetingDescription.ts new file mode 100644 index 0000000000..f412235396 --- /dev/null +++ b/packages/nodes-base/nodes/Zoom/MeetingDescription.ts @@ -0,0 +1,751 @@ +import { + INodeProperties, +} from 'n8n-workflow'; + +export const meetingOperations = [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'meeting', + ], + }, + }, + options: [ + { + name: 'Create', + value: 'create', + description: 'Create a meeting', + }, + { + name: 'Delete', + value: 'delete', + description: 'Delete a meeting', + }, + { + name: 'Get', + value: 'get', + description: 'Retrieve a meeting', + }, + { + name: 'Get All', + value: 'getAll', + description: 'Retrieve all meetings', + }, + { + name: 'Update', + value: 'update', + description: 'Update a meeting', + }, + ], + default: 'create', + description: 'The operation to perform.', + }, +] as INodeProperties[]; + +export const meetingFields = [ + /* -------------------------------------------------------------------------- */ + /* meeting:create */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'Topic', + name: 'topic', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', + displayOptions: { + show: { + operation: [ + 'create', + + ], + resource: [ + 'meeting', + ], + }, + }, + description: `Topic of the meeting.`, + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'create', + + ], + resource: [ + 'meeting', + ], + }, + }, + options: [ + { + displayName: 'Agenda', + name: 'agenda', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', + description: 'Meeting agenda.', + }, + { + displayName: 'Duration', + name: 'duration', + type: 'number', + typeOptions: { + minValue: 0, + }, + default: 0, + description: 'Meeting duration (minutes).', + }, + { + displayName: 'Password', + name: 'password', + type: 'string', + default: '', + description: 'Password to join the meeting with maximum 10 characters.', + }, + { + displayName: 'Schedule For', + name: 'scheduleFor', + type: 'string', + default: '', + description: 'Schedule meeting for someone else from your account, provide their email ID.', + }, + { + displayName: 'Settings', + name: 'settings', + type: 'collection', + placeholder: 'Add Setting', + default: {}, + options: [ + { + displayName: 'Audio', + name: 'audio', + type: 'options', + options: [ + { + name: 'Both Telephony and VoiP', + value: 'both', + }, + { + name: 'Telephony', + value: 'telephony', + }, + { + name: 'VOIP', + value: 'voip', + }, + + ], + default: 'both', + description: 'Determine how participants can join audio portion of the meeting.', + }, + { + displayName: 'Alternative Hosts', + name: 'alternativeHosts', + type: 'string', + default: '', + description: 'Alternative hosts email IDs.', + }, + { + displayName: 'Auto Recording', + name: 'autoRecording', + type: 'options', + options: [ + { + name: 'Record on Local', + value: 'local', + }, + { + name: 'Record on Cloud', + value: 'cloud', + }, + { + name: 'Disabled', + value: 'none', + }, + ], + default: 'none', + description: 'Auto recording.', + }, + { + displayName: 'Host Meeting in China', + name: 'cnMeeting', + type: 'boolean', + default: false, + description: 'Host Meeting in China.', + }, + { + displayName: 'Host Meeting in India', + name: 'inMeeting', + type: 'boolean', + default: false, + description: 'Host Meeting in India.', + }, + { + displayName: 'Host Video', + name: 'hostVideo', + type: 'boolean', + default: false, + description: 'Start video when host joins the meeting.', + }, + { + displayName: 'Join Before Host', + name: 'joinBeforeHost', + type: 'boolean', + default: false, + description: 'Allow participants to join the meeting before host starts it.', + }, + { + displayName: 'Muting Upon Entry', + name: 'muteUponEntry', + type: 'boolean', + default: false, + description: 'Mute participants upon entry.', + }, + { + displayName: 'Participant Video', + name: 'participantVideo', + type: 'boolean', + default: false, + description: 'Start video when participant joins the meeting.', + }, + { + displayName: 'Registration Type', + name: 'registrationType', + type: 'options', + options: [ + { + name: 'Attendees register once and can attend any of the occurences', + value: 1, + }, + { + name: 'Attendees need to register for every occurrence', + value: 2, + }, + { + name: 'Attendees register once and can choose one or more occurrences to attend', + value: 3, + }, + ], + default: 1, + description: 'Registration type. Used for recurring meetings with fixed time only', + }, + { + displayName: 'Watermark', + name: 'watermark', + type: 'boolean', + default: false, + description: 'Adds watermark when viewing a shared screen.', + }, + ], + }, + { + displayName: 'Start Time', + name: 'startTime', + type: 'dateTime', + default: '', + description: 'Start time should be used only for scheduled or recurring meetings with fixed time', + }, + { + displayName: 'Timezone', + name: 'timeZone', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTimezones', + }, + default: '', + description: `Time zone used in the response. The default is the time zone of the calendar.`, + }, + { + displayName: 'Type', + name: 'type', + type: 'options', + options: [ + { + name: 'Instant Meeting', + value: 1, + }, + { + name: 'Scheduled Meeting', + value: 2, + }, + { + name: 'Recurring Meeting with no fixed time', + value: 3, + }, + { + name: 'Recurring Meeting with fixed time', + value: 8, + }, + + ], + default: 2, + description: 'Meeting type.', + }, + ], + }, + /* -------------------------------------------------------------------------- */ + /* meeting:get */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'ID', + name: 'meetingId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'get', + ], + resource: [ + 'meeting', + ], + }, + }, + description: 'Meeting ID.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'get', + + ], + resource: [ + 'meeting', + ], + }, + }, + options: [ + { + displayName: 'Occurrence ID', + name: 'occurrenceId', + type: 'string', + default: '', + description: 'To view meeting details of a particular occurrence of the recurring meeting.', + }, + { + displayName: 'Show Previous Occurrences', + name: 'showPreviousOccurrences', + type: 'boolean', + default: '', + description: 'To view meeting details of all previous occurrences of the recurring meeting.', + }, + ], + }, + /* -------------------------------------------------------------------------- */ + /* meeting:getAll */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'meeting', + ], + }, + }, + default: false, + description: 'If all results should be returned or only up to a given limit.', + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'meeting', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 300, + }, + default: 30, + description: 'How many results to return.', + }, + { + displayName: 'Filters', + name: 'filters', + type: 'collection', + placeholder: 'Add Filter', + default: {}, + displayOptions: { + show: { + operation: [ + 'getAll', + + ], + resource: [ + 'meeting', + ], + }, + }, + options: [ + { + displayName: 'Type', + name: 'type', + type: 'options', + options: [ + { + name: 'Scheduled', + value: 'scheduled', + description: 'This includes all valid past meetings, live meetings and upcoming scheduled meetings' + }, + { + name: 'Live', + value: 'live', + description: 'All ongoing meetings', + }, + { + name: 'Upcoming', + value: 'upcoming', + description: 'All upcoming meetings including live meetings', + }, + ], + default: 'live', + description: `Meeting type.`, + }, + ], + }, + /* -------------------------------------------------------------------------- */ + /* meeting:delete */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'ID', + name: 'meetingId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'delete', + ], + resource: [ + 'meeting', + ], + }, + }, + description: 'Meeting ID.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'delete', + ], + resource: [ + 'meeting', + ], + }, + }, + options: [ + { + displayName: 'Occurence ID', + name: 'occurrenceId', + type: 'string', + default: '', + description: 'Meeting occurrence ID.', + }, + { + displayName: 'Schedule Reminder', + name: 'scheduleForReminder', + type: 'boolean', + default: false, + description: 'Notify hosts and alternative hosts about meeting cancellation via email', + }, + ], + + }, + /* -------------------------------------------------------------------------- */ + /* meeting:update */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'ID', + name: 'meetingId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'meeting', + ], + }, + }, + description: 'Meeting ID.', + }, + { + displayName: 'Update Fields', + name: 'updateFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'meeting', + ], + }, + }, + options: [ + { + displayName: 'Agenda', + name: 'agenda', + type: 'string', + typeOptions: { + alwaysOpenEditWindow: true, + }, + default: '', + description: 'Meeting agenda.', + }, + { + displayName: 'Duration', + name: 'duration', + type: 'number', + typeOptions: { + minValue: 0, + }, + default: 0, + description: 'Meeting duration (minutes).', + }, + { + displayName: 'Password', + name: 'password', + type: 'string', + default: '', + description: 'Password to join the meeting with maximum 10 characters.', + }, + { + displayName: 'Schedule For', + name: 'scheduleFor', + type: 'string', + default: '', + description: 'Schedule meeting for someone else from your account, provide their email ID.', + }, + { + displayName: 'Settings', + name: 'settings', + type: 'collection', + placeholder: 'Add Setting', + default: {}, + options: [ + { + displayName: 'Audio', + name: 'audio', + type: 'options', + options: [ + { + name: 'Both Telephony and VoiP', + value: 'both', + }, + { + name: 'Telephony', + value: 'telephony', + }, + { + name: 'VOIP', + value: 'voip', + }, + + ], + default: 'both', + description: 'Determine how participants can join audio portion of the meeting.', + }, + { + displayName: 'Alternative Hosts', + name: 'alternativeHosts', + type: 'string', + default: '', + description: 'Alternative hosts email IDs.', + }, + { + displayName: 'Auto Recording', + name: 'autoRecording', + type: 'options', + options: [ + { + name: 'Record on Local', + value: 'local', + }, + { + name: 'Record on Cloud', + value: 'cloud', + }, + { + name: 'Disabled', + value: 'none', + }, + ], + default: 'none', + description: 'Auto recording.', + }, + { + displayName: 'Host Meeting in China', + name: 'cnMeeting', + type: 'boolean', + default: false, + description: 'Host Meeting in China.', + }, + { + displayName: 'Host Meeting in India', + name: 'inMeeting', + type: 'boolean', + default: false, + description: 'Host Meeting in India.', + }, + { + displayName: 'Host Video', + name: 'hostVideo', + type: 'boolean', + default: false, + description: 'Start video when host joins the meeting.', + }, + { + displayName: 'Join Before Host', + name: 'joinBeforeHost', + type: 'boolean', + default: false, + description: 'Allow participants to join the meeting before host starts it.', + }, + { + displayName: 'Muting Upon Entry', + name: 'muteUponEntry', + type: 'boolean', + default: false, + description: 'Mute participants upon entry.', + }, + { + displayName: 'Participant Video', + name: 'participantVideo', + type: 'boolean', + default: false, + description: 'Start video when participant joins the meeting.', + }, + { + displayName: 'Registration Type', + name: 'registrationType', + type: 'options', + options: [ + { + name: 'Attendees register once and can attend any of the occurences', + value: 1, + }, + { + name: 'Attendees need to register for every occurrence', + value: 2, + }, + { + name: 'Attendees register once and can choose one or more occurrences to attend', + value: 3, + }, + ], + default: 1, + description: 'Registration type. Used for recurring meetings with fixed time only', + }, + { + displayName: 'Watermark', + name: 'watermark', + type: 'boolean', + default: false, + description: 'Adds watermark when viewing a shared screen.', + }, + ], + }, + { + displayName: 'Start Time', + name: 'startTime', + type: 'dateTime', + default: '', + description: 'Start time should be used only for scheduled or recurring meetings with fixed time', + }, + { + displayName: 'Timezone', + name: 'timeZone', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTimezones', + }, + default: '', + description: `Time zone used in the response. The default is the time zone of the calendar.`, + }, + { + displayName: 'Topic', + name: 'topic', + type: 'string', + default: '', + description: `Meeting topic.`, + }, + { + displayName: 'Type', + name: 'type', + type: 'options', + options: [ + { + name: 'Instant Meeting', + value: 1, + }, + { + name: 'Scheduled Meeting', + value: 2, + }, + { + name: 'Recurring Meeting with no fixed time', + value: 3, + }, + { + name: 'Recurring Meeting with fixed time', + value: 8, + }, + + ], + default: 2, + description: 'Meeting type.', + }, + ], + }, +] as INodeProperties[]; diff --git a/packages/nodes-base/nodes/Zoom/MeetingRegistrantDescription.ts b/packages/nodes-base/nodes/Zoom/MeetingRegistrantDescription.ts new file mode 100644 index 0000000000..5438f18fa3 --- /dev/null +++ b/packages/nodes-base/nodes/Zoom/MeetingRegistrantDescription.ts @@ -0,0 +1,443 @@ +import { + INodeProperties, +} from 'n8n-workflow'; + +export const meetingRegistrantOperations = [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'meetingRegistrant', + ], + }, + }, + options: [ + { + name: 'Create', + value: 'create', + description: 'Create Meeting Registrants', + }, + { + name: 'Update', + value: 'update', + description: 'Update Meeting Registrant Status', + }, + { + name: 'Get All', + value: 'getAll', + description: 'Retrieve all Meeting Registrants', + }, + + ], + default: 'create', + description: 'The operation to perform.', + } +] as INodeProperties[]; + +export const meetingRegistrantFields = [ + /* -------------------------------------------------------------------------- */ + /* meetingRegistrant:create */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'Meeting Id', + name: 'meetingId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'create', + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + description: 'Meeting ID.', + }, + { + displayName: 'Email', + name: 'email', + type: 'string', + required: true, + default: '', + displayOptions: { + show: { + operation: [ + 'create', + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + description: 'Valid Email-ID.', + }, + { + displayName: 'First Name', + name: 'firstName', + required: true, + type: 'string', + default: '', + displayOptions: { + show: { + operation: [ + 'create', + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + description: 'First Name.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'create', + + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + options: [ + { + displayName: 'Address', + name: 'address', + type: 'string', + default: '', + description: 'Valid address of registrant.', + }, + { + displayName: 'City', + name: 'city', + type: 'string', + default: '', + description: 'Valid city of registrant.', + }, + { + displayName: 'Comments', + name: 'comments', + type: 'string', + default: '', + description: 'Allows registrants to provide any questions they have.', + }, + { + displayName: 'Country', + name: 'country', + type: 'string', + default: '', + description: 'Valid country of registrant.', + }, + { + displayName: 'Job Title', + name: 'jobTitle', + type: 'string', + default: '', + description: 'Job title of registrant.', + }, + { + displayName: 'Last Name', + name: 'lastName', + type: 'string', + default: '', + description: 'Last Name.', + }, + { + displayName: 'Occurrence IDs', + name: 'occurrenceId', + type: 'string', + default: '', + description: 'Occurrence IDs separated by comma.', + }, + { + displayName: 'Organization', + name: 'org', + type: 'string', + default: '', + description: 'Organization of registrant.', + }, + { + displayName: 'Phone Number', + name: 'phone', + type: 'string', + default: '', + description: 'Valid phone number of registrant.', + }, + { + displayName: 'Purchasing Time Frame', + name: 'purchasingTimeFrame', + type: 'options', + options: [ + { + name: 'Within a month', + value: 'Within a month', + }, + { + name: '1-3 months', + value: '1-3 months', + }, + { + name: '4-6 months', + value: '4-6 months', + }, + { + name: 'More than 6 months', + value: 'More than 6 months', + }, + { + name: 'No timeframe', + value: 'No timeframe', + }, + ], + default: '', + description: 'Meeting type.', + }, + { + displayName: 'Role in Purchase Process', + name: 'roleInPurchaseProcess', + type: 'options', + options: [ + { + name: 'Decision Maker', + value: 'Decision Maker', + }, + { + name: 'Evaluator/Recommender', + value: 'Evaluator/Recommender', + }, + { + name: 'Influener', + value: 'Influener', + }, + { + name: 'Not Involved', + value: 'Not Involved', + }, + + ], + default: '', + description: 'Role in purchase process.', + }, + { + displayName: 'State', + name: 'state', + type: 'string', + default: '', + description: 'Valid state of registrant.', + }, + { + displayName: 'Zip Code', + name: 'zip', + type: 'string', + default: '', + description: 'Valid zip-code of registrant.', + }, + + ], + }, + /* -------------------------------------------------------------------------- */ + /* meetingRegistrant:getAll */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'Meeting ID', + name: 'meetingId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + description: 'Meeting ID.', + }, + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + default: false, + description: 'If all results should be returned or only up to a given limit.', + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'meetingRegistrant', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 300, + }, + default: 30, + description: 'How many results to return.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'getAll', + + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + options: [ + { + displayName: 'Occurrence ID', + name: 'occurrenceId', + type: 'string', + default: '', + description: `Occurrence ID.`, + }, + { + displayName: 'Status', + name: 'status', + type: 'options', + options: [ + { + name: 'Pending', + value: 'pending', + }, + { + name: 'Approved', + value: 'approved', + }, + { + name: 'Denied', + value: 'denied', + }, + ], + default: 'approved', + description: `Registrant Status.`, + }, + + ] + }, + /* -------------------------------------------------------------------------- */ + /* meetingRegistrant:update */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'Meeting ID', + name: 'meetingId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + description: 'Meeting ID.', + }, + { + displayName: 'Action', + name: 'action', + type: 'options', + required: true, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + options: [ + { + name: 'Cancel', + value: 'cancel', + }, + { + name: 'Approved', + value: 'approve', + }, + { + name: 'Deny', + value: 'deny', + }, + ], + default: '', + description: `Registrant Status.`, + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'meetingRegistrant', + ], + }, + }, + options: [ + { + displayName: 'Occurrence ID', + name: 'occurrenceId', + type: 'string', + default: '', + description: 'Occurrence ID.', + }, + + ], + } + +] as INodeProperties[]; diff --git a/packages/nodes-base/nodes/Zoom/WebinarDescription.ts b/packages/nodes-base/nodes/Zoom/WebinarDescription.ts new file mode 100644 index 0000000000..421eb2cf50 --- /dev/null +++ b/packages/nodes-base/nodes/Zoom/WebinarDescription.ts @@ -0,0 +1,665 @@ +import { + INodeProperties, +} from 'n8n-workflow'; + +export const webinarOperations = [ + { + displayName: 'Operation', + name: 'operation', + type: 'options', + displayOptions: { + show: { + resource: [ + 'webinar', + ], + }, + }, + options: [ + { + name: 'Create', + value: 'create', + description: 'Create a webinar', + }, + { + name: 'Delete', + value: 'delete', + description: 'Delete a webinar', + }, + { + name: 'Get', + value: 'get', + description: 'Retrieve a webinar', + }, + { + name: 'Get All', + value: 'getAll', + description: 'Retrieve all webinars', + }, + { + name: 'Update', + value: 'update', + description: 'Update a webinar', + } + ], + default: 'create', + description: 'The operation to perform.', + } +] as INodeProperties[]; + +export const webinarFields = [ + /* -------------------------------------------------------------------------- */ + /* webinar:create */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'User ID', + name: 'userId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'create', + ], + resource: [ + 'webinar', + ], + }, + }, + description: 'User ID or email ID.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'create', + + ], + resource: [ + 'webinar', + ], + } + }, + options: [ + { + displayName: 'Agenda', + name: 'agenda', + type: 'string', + default: '', + description: 'Webinar agenda.', + }, + { + displayName: 'Alternative Hosts', + name: 'alternativeHosts', + type: 'string', + default: '', + description: 'Alternative hosts email IDs.', + }, + { + displayName: 'Approval Type', + name: 'approvalType', + type: 'options', + options: [ + { + name: 'Automatically Approve', + value: 0, + }, + { + name: 'Manually Approve', + value: 1, + }, + { + name: 'No Registration Required', + value: 2, + }, + ], + default: 2, + description: 'Approval type.', + }, + { + displayName: 'Audio', + name: 'audio', + type: 'options', + options: [ + { + name: 'Both Telephony and VoiP', + value: 'both', + }, + { + name: 'Telephony', + value: 'telephony', + }, + { + name: 'VOIP', + value: 'voip', + }, + + ], + default: 'both', + description: 'Determine how participants can join audio portion of the webinar.', + }, + { + displayName: 'Auto Recording', + name: 'autoRecording', + type: 'options', + options: [ + { + name: 'Record on Local', + value: 'local', + }, + { + name: 'Record on Cloud', + value: 'cloud', + }, + { + name: 'Disabled', + value: 'none', + }, + ], + default: 'none', + description: 'Auto recording.', + }, + { + displayName: 'Duration', + name: 'duration', + type: 'string', + default: '', + description: 'Duration.', + }, + { + displayName: 'Host Video', + name: 'hostVideo', + type: 'boolean', + default: false, + description: 'Start video when host joins the webinar.', + }, + { + displayName: 'Panelists Video', + name: 'panelistsVideo', + type: 'boolean', + default: false, + description: 'Start video when panelists joins the webinar.', + }, + { + displayName: 'Password', + name: 'password', + type: 'string', + default: '', + description: 'Password to join the webinar with maximum 10 characters.', + }, + { + displayName: 'Practice Session', + name: 'practiceSession', + type: 'boolean', + default: false, + description: 'Enable Practice session.', + }, + { + displayName: 'Registration Type', + name: 'registrationType', + type: 'options', + options: [ + { + name: 'Attendees register once and can attend any of the occurences', + value: 1, + }, + { + name: 'Attendees need to register for every occurrence', + value: 2, + }, + { + name: 'Attendees register once and can choose one or more occurrences to attend', + value: 3, + }, + ], + default: 1, + description: 'Registration type. Used for recurring webinar with fixed time only', + }, + { + displayName: 'Start Time', + name: 'startTime', + type: 'dateTime', + default: '', + description: 'Start time should be used only for scheduled or recurring webinar with fixed time', + }, + { + displayName: 'Timezone', + name: 'timeZone', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTimezones', + }, + default: '', + description: `Time zone used in the response. The default is the time zone of the calendar.`, + }, + { + displayName: 'Webinar Topic', + name: 'topic', + type: 'string', + default: '', + description: `Webinar topic.`, + }, + { + displayName: 'Webinar Type', + name: 'type', + type: 'options', + options: [ + { + name: 'Webinar', + value: 5, + }, + { + name: 'Recurring webinar with no fixed time', + value: 6, + }, + { + name: 'Recurring webinar with fixed time', + value: 9, + }, + ], + default: 5, + description: 'Webinar type.', + }, + + ], + }, + /* -------------------------------------------------------------------------- */ + /* webinar:get */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'Webinar ID', + name: 'webinarId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'get', + ], + resource: [ + 'webinar', + ], + }, + }, + description: 'Webinar ID.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'get', + + ], + resource: [ + 'webinar', + ], + }, + }, + options: [ + { + displayName: 'Occurence ID', + name: 'occurenceId', + type: 'string', + default: '', + description: 'To view webinar details of a particular occurrence of the recurring webinar.', + }, + { + displayName: 'Show Previous Occurrences', + name: 'showPreviousOccurrences', + type: 'boolean', + default: '', + description: 'To view webinar details of all previous occurrences of the recurring webinar.', + }, + ], + }, + /* -------------------------------------------------------------------------- */ + /* webinar:getAll */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'User ID', + name: 'userId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'webinar', + ], + }, + }, + description: 'User ID or email-ID.', + }, + { + displayName: 'Return All', + name: 'returnAll', + type: 'boolean', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'webinar', + ], + }, + }, + default: false, + description: 'If all results should be returned or only up to a given limit.', + }, + { + displayName: 'Limit', + name: 'limit', + type: 'number', + displayOptions: { + show: { + operation: [ + 'getAll', + ], + resource: [ + 'webinar', + ], + returnAll: [ + false, + ], + }, + }, + typeOptions: { + minValue: 1, + maxValue: 300, + }, + default: 30, + description: 'How many results to return.', + }, + /* -------------------------------------------------------------------------- */ + /* webinar:delete */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'Webinar ID', + name: 'webinarId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'delete', + ], + resource: [ + 'webinarId', + ], + }, + }, + description: 'Webinar ID.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'delete', + ], + resource: [ + 'webinar', + ], + }, + }, + options: [ + { + displayName: 'Occurrence ID', + name: 'occurrenceId', + type: 'string', + default: '', + description: 'Webinar occurrence ID.', + }, + + ], + + }, + /* -------------------------------------------------------------------------- */ + /* webinar:update */ + /* -------------------------------------------------------------------------- */ + { + displayName: 'Webinar ID', + name: 'webinarId', + type: 'string', + default: '', + required: true, + displayOptions: { + show: { + operation: [ + 'update', + ], + resource: [ + 'webinar', + ], + }, + }, + description: 'User ID or email address of user.', + }, + { + displayName: 'Additional Fields', + name: 'additionalFields', + type: 'collection', + placeholder: 'Add Field', + default: {}, + displayOptions: { + show: { + operation: [ + 'update', + + ], + resource: [ + 'webinar', + ], + }, + }, + options: [ + { + displayName: 'Agenda', + name: 'agenda', + type: 'string', + default: '', + description: 'Webinar agenda.', + }, + { + displayName: 'Alternative Hosts', + name: 'alternativeHosts', + type: 'string', + default: '', + description: 'Alternative hosts email IDs.', + }, + { + displayName: 'Approval Type', + name: 'approvalType', + type: 'options', + options: [ + { + name: 'Automatically Approve', + value: 0, + }, + { + name: 'Manually Approve', + value: 1, + }, + { + name: 'No Registration Required', + value: 2, + }, + ], + default: 2, + description: 'Approval type.', + }, + { + displayName: 'Auto Recording', + name: 'autoRecording', + type: 'options', + options: [ + { + name: 'Record on Local', + value: 'local', + }, + { + name: 'Record on Cloud', + value: 'cloud', + }, + { + name: 'Disabled', + value: 'none', + }, + ], + default: 'none', + description: 'Auto recording.', + }, + { + displayName: 'Audio', + name: 'audio', + type: 'options', + options: [ + { + name: 'Both Telephony and VoiP', + value: 'both', + }, + { + name: 'Telephony', + value: 'telephony', + }, + { + name: 'VOIP', + value: 'voip', + }, + + ], + default: 'both', + description: 'Determine how participants can join audio portion of the webinar.', + }, + { + displayName: 'Duration', + name: 'duration', + type: 'string', + default: '', + description: 'Duration.', + }, + { + displayName: 'Host Video', + name: 'hostVideo', + type: 'boolean', + default: false, + description: 'Start video when host joins the webinar.', + }, + { + displayName: 'Occurrence ID', + name: 'occurrenceId', + type: 'string', + default: '', + description: `Webinar occurrence ID.`, + }, + { + displayName: 'Password', + name: 'password', + type: 'string', + default: '', + description: 'Password to join the webinar with maximum 10 characters.', + }, + { + displayName: 'Panelists Video', + name: 'panelistsVideo', + type: 'boolean', + default: false, + description: 'Start video when panelists joins the webinar.', + }, + { + displayName: 'Practice Session', + name: 'practiceSession', + type: 'boolean', + default: false, + description: 'Enable Practice session.', + }, + { + displayName: 'Registration Type', + name: 'registrationType', + type: 'options', + options: [ + { + name: 'Attendees register once and can attend any of the occurrences', + value: 1, + }, + { + name: 'Attendees need to register for every occurrence', + value: 2, + }, + { + name: 'Attendees register once and can choose one or more occurrences to attend', + value: 3, + }, + ], + default: 1, + description: 'Registration type. Used for recurring webinars with fixed time only.', + }, + { + displayName: 'Start Time', + name: 'startTime', + type: 'dateTime', + default: '', + description: 'Start time should be used only for scheduled or recurring webinar with fixed time.', + }, + { + displayName: 'Timezone', + name: 'timeZone', + type: 'options', + typeOptions: { + loadOptionsMethod: 'getTimezones', + }, + default: '', + description: `Time zone used in the response. The default is the time zone of the calendar.`, + }, + { + displayName: 'Webinar Topic', + name: 'topic', + type: 'string', + default: '', + description: `Webinar topic.`, + }, + { + displayName: 'Webinar Type', + name: 'type', + type: 'options', + options: [ + { + name: 'Webinar', + value: 5, + }, + { + name: 'Recurring webinar with no fixed time', + value: 6, + }, + { + name: 'Recurring webinar with fixed time', + value: 9, + }, + ], + default: 5, + description: 'Webinar type.' + }, + ], + }, + +] as INodeProperties[]; diff --git a/packages/nodes-base/nodes/Zoom/Zoom.node.ts b/packages/nodes-base/nodes/Zoom/Zoom.node.ts new file mode 100644 index 0000000000..f7ecff0de8 --- /dev/null +++ b/packages/nodes-base/nodes/Zoom/Zoom.node.ts @@ -0,0 +1,821 @@ +import { + IExecuteFunctions, +} from 'n8n-core'; + +import { + IDataObject, + ILoadOptionsFunctions, + INodeExecutionData, + INodePropertyOptions, + INodeType, + INodeTypeDescription, +} from 'n8n-workflow'; + +import { + zoomApiRequest, + zoomApiRequestAllItems, +} from './GenericFunctions'; + +import { + meetingOperations, + meetingFields, +} from './MeetingDescription'; + +// import { +// meetingRegistrantOperations, +// meetingRegistrantFields, +// } from './MeetingRegistrantDescription'; + +// import { +// webinarOperations, +// webinarFields, +// } from './WebinarDescription'; + +import * as moment from 'moment-timezone'; + +interface Settings { + host_video?: boolean; + participant_video?: boolean; + panelists_video?: boolean; + cn_meeting?: boolean; + in_meeting?: boolean; + join_before_host?: boolean; + mute_upon_entry?: boolean; + watermark?: boolean; + waiting_room?: boolean; + audio?: string; + alternative_hosts?: string; + auto_recording?: string; + registration_type?: number; + approval_type?: number; + practice_session?: boolean; +} + +export class Zoom implements INodeType { + description: INodeTypeDescription = { + displayName: 'Zoom', + name: 'zoom', + group: ['input'], + version: 1, + description: 'Consume Zoom API', + subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', + defaults: { + name: 'Zoom', + color: '#0B6CF9' + }, + icon: 'file:zoom.png', + inputs: ['main'], + outputs: ['main'], + credentials: [ + { + // create a JWT app on Zoom Marketplace + //https://marketplace.zoom.us/develop/create + //get the JWT token as access token + name: 'zoomApi', + required: true, + displayOptions: { + show: { + authentication: [ + 'accessToken', + ], + }, + }, + }, + { + //create a account level OAuth app + //https://marketplace.zoom.us/develop/create + name: 'zoomOAuth2Api', + required: true, + displayOptions: { + show: { + authentication: [ + 'oAuth2', + ], + }, + }, + }, + ], + properties: [ + { + displayName: 'Authentication', + name: 'authentication', + type: 'options', + options: [ + { + name: 'Access Token', + value: 'accessToken', + }, + { + name: 'OAuth2', + value: 'oAuth2', + }, + ], + default: 'accessToken', + description: 'The resource to operate on.', + }, + { + displayName: 'Resource', + name: 'resource', + type: 'options', + options: [ + { + name: 'Meeting', + value: 'meeting' + }, + // { + // name: 'Meeting Registrant', + // value: 'meetingRegistrant' + // }, + // { + // name: 'Webinar', + // value: 'webinar' + // } + ], + default: 'meeting', + description: 'The resource to operate on.' + }, + //MEETINGS + ...meetingOperations, + ...meetingFields, + + // //MEETING REGISTRANTS + // ...meetingRegistrantOperations, + // ...meetingRegistrantFields, + + // //WEBINARS + // ...webinarOperations, + // ...webinarFields, + ] + + }; + methods = { + loadOptions: { + // Get all the timezones to display them to user so that he can select them easily + async getTimezones( + this: ILoadOptionsFunctions + ): Promise { + const returnData: INodePropertyOptions[] = []; + for (const timezone of moment.tz.names()) { + const timezoneName = timezone; + const timezoneId = timezone; + returnData.push({ + name: timezoneName, + value: timezoneId + }); + } + return returnData; + } + } + }; + + async execute(this: IExecuteFunctions): Promise { + const items = this.getInputData(); + const returnData: IDataObject[] = []; + let qs: IDataObject = {}; + let responseData; + const resource = this.getNodeParameter('resource', 0) as string; + const operation = this.getNodeParameter('operation', 0) as string; + + for (let i = 0; i < items.length; i++) { + qs = {}; + //https://marketplace.zoom.us/docs/api-reference/zoom-api/ + if (resource === 'meeting') { + + if (operation === 'get') { + //https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meeting + const meetingId = this.getNodeParameter('meetingId', i) as string; + const additionalFields = this.getNodeParameter( + 'additionalFields', + i + ) as IDataObject; + + if (additionalFields.showPreviousOccurrences) { + qs.show_previous_occurrences = additionalFields.showPreviousOccurrences as boolean; + } + + if (additionalFields.occurrenceId) { + qs.occurrence_id = additionalFields.occurrenceId as string; + } + + responseData = await zoomApiRequest.call( + this, + 'GET', + `/meetings/${meetingId}`, + {}, + qs + ); + } + if (operation === 'getAll') { + //https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetings + const returnAll = this.getNodeParameter('returnAll', i) as boolean; + + const filters = this.getNodeParameter( + 'filters', + i + ) as IDataObject; + if (filters.type) { + qs.type = filters.type as string; + } + + if (returnAll) { + responseData = await zoomApiRequestAllItems.call(this, 'meetings', 'GET', '/users/me/meetings', {}, qs); + } else { + qs.page_size = this.getNodeParameter('limit', i) as number; + responseData = await zoomApiRequest.call(this, 'GET', '/users/me/meetings', {}, qs); + responseData = responseData.meetings; + } + + } + if (operation === 'delete') { + //https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingdelete + const meetingId = this.getNodeParameter('meetingId', i) as string; + const additionalFields = this.getNodeParameter( + 'additionalFields', + i + ) as IDataObject; + if (additionalFields.scheduleForReminder) { + qs.schedule_for_reminder = additionalFields.scheduleForReminder as boolean; + } + + if (additionalFields.occurrenceId) { + qs.occurrence_id = additionalFields.occurrenceId; + } + + responseData = await zoomApiRequest.call( + this, + 'DELETE', + `/meetings/${meetingId}`, + {}, + qs + ); + responseData = { success: true }; + } + if (operation === 'create') { + //https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate + const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; + + const body: IDataObject = {}; + + if (additionalFields.settings) { + const settingValues: Settings = {}; + const settings = additionalFields.settings as IDataObject; + + if (settings.cnMeeting) { + settingValues.cn_meeting = settings.cnMeeting as boolean; + } + + if (settings.inMeeting) { + settingValues.in_meeting = settings.inMeeting as boolean; + } + + if (settings.joinBeforeHost) { + settingValues.join_before_host = settings.joinBeforeHost as boolean; + } + + if (settings.muteUponEntry) { + settingValues.mute_upon_entry = settings.muteUponEntry as boolean; + } + + if (settings.watermark) { + settingValues.watermark = settings.watermark as boolean; + } + + if (settings.audio) { + settingValues.audio = settings.audio as string; + } + + if (settings.alternativeHosts) { + settingValues.alternative_hosts = settings.alternativeHosts as string; + } + + if (settings.participantVideo) { + settingValues.participant_video = settings.participantVideo as boolean; + } + + if (settings.hostVideo) { + settingValues.host_video = settings.hostVideo as boolean; + } + + if (settings.autoRecording) { + settingValues.auto_recording = settings.autoRecording as string; + } + + if (settings.registrationType) { + settingValues.registration_type = settings.registrationType as number; + } + + body.settings = settingValues; + } + + body.topic = this.getNodeParameter('topic', i) as string; + + if (additionalFields.type) { + body.type = additionalFields.type as string; + } + + if (additionalFields.startTime) { + if (additionalFields.timeZone) { + body.start_time = moment(additionalFields.startTime as string).format('YYYY-MM-DDTHH:mm:ss'); + } else { + // if none timezone it's defined used n8n timezone + body.start_time = moment.tz(additionalFields.startTime as string, this.getTimezone()).format(); + } + } + + if (additionalFields.duration) { + body.duration = additionalFields.duration as number; + } + + if (additionalFields.scheduleFor) { + body.schedule_for = additionalFields.scheduleFor as string; + } + + if (additionalFields.timeZone) { + body.timezone = additionalFields.timeZone as string; + } + + if (additionalFields.password) { + body.password = additionalFields.password as string; + } + + if (additionalFields.agenda) { + body.agenda = additionalFields.agenda as string; + } + + responseData = await zoomApiRequest.call( + this, + 'POST', + `/users/me/meetings`, + body, + qs + ); + } + if (operation === 'update') { + //https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingupdate + const meetingId = this.getNodeParameter('meetingId', i) as string; + const updateFields = this.getNodeParameter( + 'updateFields', + i + ) as IDataObject; + + const body: IDataObject = {}; + + if (updateFields.settings) { + const settingValues: Settings = {}; + const settings = updateFields.settings as IDataObject; + + if (settings.cnMeeting) { + settingValues.cn_meeting = settings.cnMeeting as boolean; + } + + if (settings.inMeeting) { + settingValues.in_meeting = settings.inMeeting as boolean; + } + + if (settings.joinBeforeHost) { + settingValues.join_before_host = settings.joinBeforeHost as boolean; + } + + if (settings.muteUponEntry) { + settingValues.mute_upon_entry = settings.muteUponEntry as boolean; + } + + if (settings.watermark) { + settingValues.watermark = settings.watermark as boolean; + } + + if (settings.audio) { + settingValues.audio = settings.audio as string; + } + + if (settings.alternativeHosts) { + settingValues.alternative_hosts = settings.alternativeHosts as string; + } + + if (settings.participantVideo) { + settingValues.participant_video = settings.participantVideo as boolean; + } + + if (settings.hostVideo) { + settingValues.host_video = settings.hostVideo as boolean; + } + + if (settings.autoRecording) { + settingValues.auto_recording = settings.autoRecording as string; + } + + if (settings.registrationType) { + settingValues.registration_type = settings.registrationType as number; + } + + body.settings = settingValues; + } + + if (updateFields.topic) { + body.topic = updateFields.topic as string; + } + + if (updateFields.type) { + body.type = updateFields.type as string; + } + + if (updateFields.startTime) { + body.start_time = updateFields.startTime as string; + } + + if (updateFields.duration) { + body.duration = updateFields.duration as number; + } + + if (updateFields.scheduleFor) { + body.schedule_for = updateFields.scheduleFor as string; + } + + if (updateFields.timeZone) { + body.timezone = updateFields.timeZone as string; + } + + if (updateFields.password) { + body.password = updateFields.password as string; + } + + if (updateFields.agenda) { + body.agenda = updateFields.agenda as string; + } + + responseData = await zoomApiRequest.call( + this, + 'PATCH', + `/meetings/${meetingId}`, + body, + qs + ); + + responseData = { success: true }; + + } + } + // if (resource === 'meetingRegistrant') { + // if (operation === 'create') { + // //https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingregistrantcreate + // const meetingId = this.getNodeParameter('meetingId', i) as string; + // const emailId = this.getNodeParameter('email', i) as string; + // body.email = emailId; + // const firstName = this.getNodeParameter('firstName', i) as string; + // body.first_name = firstName; + // const additionalFields = this.getNodeParameter( + // 'additionalFields', + // i + // ) as IDataObject; + // if (additionalFields.occurrenceId) { + // qs.occurrence_ids = additionalFields.occurrenceId as string; + // } + // if (additionalFields.lastName) { + // body.last_name = additionalFields.lastName as string; + // } + // if (additionalFields.address) { + // body.address = additionalFields.address as string; + // } + // if (additionalFields.city) { + // body.city = additionalFields.city as string; + // } + // if (additionalFields.state) { + // body.state = additionalFields.state as string; + // } + // if (additionalFields.country) { + // body.country = additionalFields.country as string; + // } + // if (additionalFields.zip) { + // body.zip = additionalFields.zip as string; + // } + // if (additionalFields.phone) { + // body.phone = additionalFields.phone as string; + // } + // if (additionalFields.comments) { + // body.comments = additionalFields.comments as string; + // } + // if (additionalFields.org) { + // body.org = additionalFields.org as string; + // } + // if (additionalFields.jobTitle) { + // body.job_title = additionalFields.jobTitle as string; + // } + // if (additionalFields.purchasingTimeFrame) { + // body.purchasing_time_frame = additionalFields.purchasingTimeFrame as string; + // } + // if (additionalFields.roleInPurchaseProcess) { + // body.role_in_purchase_process = additionalFields.roleInPurchaseProcess as string; + // } + // responseData = await zoomApiRequest.call( + // this, + // 'POST', + // `/meetings/${meetingId}/registrants`, + // body, + // qs + // ); + // } + // if (operation === 'getAll') { + // //https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingregistrants + // const meetingId = this.getNodeParameter('meetingId', i) as string; + // const additionalFields = this.getNodeParameter( + // 'additionalFields', + // i + // ) as IDataObject; + // if (additionalFields.occurrenceId) { + // qs.occurrence_id = additionalFields.occurrenceId as string; + // } + // if (additionalFields.status) { + // qs.status = additionalFields.status as string; + // } + // const returnAll = this.getNodeParameter('returnAll', i) as boolean; + // if (returnAll) { + // responseData = await zoomApiRequestAllItems.call(this, 'results', 'GET', `/meetings/${meetingId}/registrants`, {}, qs); + // } else { + // qs.page_size = this.getNodeParameter('limit', i) as number; + // responseData = await zoomApiRequest.call(this, 'GET', `/meetings/${meetingId}/registrants`, {}, qs); + + // } + + // } + // if (operation === 'update') { + // //https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingregistrantstatus + // const meetingId = this.getNodeParameter('meetingId', i) as string; + // const additionalFields = this.getNodeParameter( + // 'additionalFields', + // i + // ) as IDataObject; + // if (additionalFields.occurenceId) { + // qs.occurrence_id = additionalFields.occurrenceId as string; + // } + // if (additionalFields.action) { + // body.action = additionalFields.action as string; + // } + // responseData = await zoomApiRequest.call( + // this, + // 'PUT', + // `/meetings/${meetingId}/registrants/status`, + // body, + // qs + // ); + // } + // } + // if (resource === 'webinar') { + // if (operation === 'create') { + // //https://marketplace.zoom.us/docs/api-reference/zoom-api/webinars/webinarcreate + // const userId = this.getNodeParameter('userId', i) as string; + // const additionalFields = this.getNodeParameter( + // 'additionalFields', + // i + // ) as IDataObject; + // const settings: Settings = {}; + + + // if (additionalFields.audio) { + // settings.audio = additionalFields.audio as string; + + // } + + // if (additionalFields.alternativeHosts) { + // settings.alternative_hosts = additionalFields.alternativeHosts as string; + + // } + + // if (additionalFields.panelistsVideo) { + // settings.panelists_video = additionalFields.panelistsVideo as boolean; + + // } + // if (additionalFields.hostVideo) { + // settings.host_video = additionalFields.hostVideo as boolean; + + // } + // if (additionalFields.practiceSession) { + // settings.practice_session = additionalFields.practiceSession as boolean; + + // } + // if (additionalFields.autoRecording) { + // settings.auto_recording = additionalFields.autoRecording as string; + + // } + + // if (additionalFields.registrationType) { + // settings.registration_type = additionalFields.registrationType as number; + + // } + // if (additionalFields.approvalType) { + // settings.approval_type = additionalFields.approvalType as number; + + // } + + // body = { + // settings, + // }; + + // if (additionalFields.topic) { + // body.topic = additionalFields.topic as string; + + // } + + // if (additionalFields.type) { + // body.type = additionalFields.type as string; + + // } + + // if (additionalFields.startTime) { + // body.start_time = additionalFields.startTime as string; + + // } + + // if (additionalFields.duration) { + // body.duration = additionalFields.duration as number; + + // } + + + // if (additionalFields.timeZone) { + // body.timezone = additionalFields.timeZone as string; + + // } + + // if (additionalFields.password) { + // body.password = additionalFields.password as string; + + // } + + // if (additionalFields.agenda) { + // body.agenda = additionalFields.agenda as string; + + // } + // responseData = await zoomApiRequest.call( + // this, + // 'POST', + // `/users/${userId}/webinars`, + // body, + // qs + // ); + // } + // if (operation === 'get') { + // //https://marketplace.zoom.us/docs/api-reference/zoom-api/webinars/webinar + // const webinarId = this.getNodeParameter('webinarId', i) as string; + + // const additionalFields = this.getNodeParameter( + // 'additionalFields', + // i + // ) as IDataObject; + // if (additionalFields.showPreviousOccurrences) { + // qs.show_previous_occurrences = additionalFields.showPreviousOccurrences as boolean; + + // } + + // if (additionalFields.occurrenceId) { + // qs.occurrence_id = additionalFields.occurrenceId as string; + + // } + + // responseData = await zoomApiRequest.call( + // this, + // 'GET', + // `/webinars/${webinarId}`, + // {}, + // qs + // ); + // } + // if (operation === 'getAll') { + // //https://marketplace.zoom.us/docs/api-reference/zoom-api/webinars/webinars + // const userId = this.getNodeParameter('userId', i) as string; + // const returnAll = this.getNodeParameter('returnAll', i) as boolean; + // if (returnAll) { + // responseData = await zoomApiRequestAllItems.call(this, 'results', 'GET', `/users/${userId}/webinars`, {}, qs); + // } else { + // qs.page_size = this.getNodeParameter('limit', i) as number; + // responseData = await zoomApiRequest.call(this, 'GET', `/users/${userId}/webinars`, {}, qs); + + // } + // } + // if (operation === 'delete') { + // //https://marketplace.zoom.us/docs/api-reference/zoom-api/webinars/webinardelete + // const webinarId = this.getNodeParameter('webinarId', i) as string; + // const additionalFields = this.getNodeParameter( + // 'additionalFields', + // i + // ) as IDataObject; + + + // if (additionalFields.occurrenceId) { + // qs.occurrence_id = additionalFields.occurrenceId; + + // } + + // responseData = await zoomApiRequest.call( + // this, + // 'DELETE', + // `/webinars/${webinarId}`, + // {}, + // qs + // ); + // responseData = { success: true }; + // } + // if (operation === 'update') { + // //https://marketplace.zoom.us/docs/api-reference/zoom-api/webinars/webinarupdate + // const webinarId = this.getNodeParameter('webinarId', i) as string; + // const additionalFields = this.getNodeParameter( + // 'additionalFields', + // i + // ) as IDataObject; + // if (additionalFields.occurrenceId) { + // qs.occurrence_id = additionalFields.occurrenceId as string; + + // } + // const settings: Settings = {}; + // if (additionalFields.audio) { + // settings.audio = additionalFields.audio as string; + + // } + // if (additionalFields.alternativeHosts) { + // settings.alternative_hosts = additionalFields.alternativeHosts as string; + + // } + + // if (additionalFields.panelistsVideo) { + // settings.panelists_video = additionalFields.panelistsVideo as boolean; + + // } + // if (additionalFields.hostVideo) { + // settings.host_video = additionalFields.hostVideo as boolean; + + // } + // if (additionalFields.practiceSession) { + // settings.practice_session = additionalFields.practiceSession as boolean; + + // } + // if (additionalFields.autoRecording) { + // settings.auto_recording = additionalFields.autoRecording as string; + + // } + + // if (additionalFields.registrationType) { + // settings.registration_type = additionalFields.registrationType as number; + + // } + // if (additionalFields.approvalType) { + // settings.approval_type = additionalFields.approvalType as number; + + // } + + // body = { + // settings, + // }; + + // if (additionalFields.topic) { + // body.topic = additionalFields.topic as string; + + // } + + // if (additionalFields.type) { + // body.type = additionalFields.type as string; + + // } + + // if (additionalFields.startTime) { + // body.start_time = additionalFields.startTime as string; + + // } + + // if (additionalFields.duration) { + // body.duration = additionalFields.duration as number; + + // } + + + // if (additionalFields.timeZone) { + // body.timezone = additionalFields.timeZone as string; + + // } + + // if (additionalFields.password) { + // body.password = additionalFields.password as string; + + // } + + // if (additionalFields.agenda) { + // body.agenda = additionalFields.agenda as string; + + // } + // responseData = await zoomApiRequest.call( + // this, + // 'PATCH', + // `webinars/${webinarId}`, + // body, + // qs + // ); + // } + // } + } + if (Array.isArray(responseData)) { + returnData.push.apply(returnData, responseData as IDataObject[]); + } else { + returnData.push(responseData as IDataObject); + } + + return [this.helpers.returnJsonArray(returnData)]; + } +} diff --git a/packages/nodes-base/nodes/Zoom/zoom.png b/packages/nodes-base/nodes/Zoom/zoom.png new file mode 100644 index 0000000000000000000000000000000000000000..dfc72331ebddb8f4f2bfded903500be639581567 GIT binary patch literal 1848 zcmV-82gmq{P)Px%JbF}EbW&k=AaHVTW@&6?Aar?fWgvKMZ~y=}jg?hP zvfLmH+;fT?0ZT$M$MFnim#Qpt{B*;7-uQVkiCtx5B-E{z!0GqTU+D+0SS9IId#sUt zarKLrFv%`nJiPj@O=Rzv%cYB8zPfRygcfU>twlD4@9H(#8e3pt(b#M+=6EBZDi(=o z*Ilw+W7REI$3kxe^F=bh{px!tZHWkAW8TR_w`q8|4<^qrn7eR=Jyu9AtF@AokX(;3 zrA2mCY2cG}QJ^aF#oVH%g=5TJF)PC^((#^8Ptu0lHXJv&gyh35xAX)o;8VoR{E(WY zVPtx181Aea(&;fS*#lm(55@uHMJw+I6T!1h05A#-)Q5_oij4@gzp?-YlnR9quS2N{ zh2U|w`;s774+u+EQ`oPypupex4zT@MB8)X**pSK!KAGepZNAs)7}6TL=S|r38uvUb z0=ARj8dli4L*w+B^m%YLcR(-rbcRczLnFb0GUHR~iOujvfeV5dYgY)+{rasbGZ?{v zPC7=J4O$d!m<1g>cHpe(@R0fh8H#O2E0Ux}q+hJssN8fyN_A|}O?d@c5S@;VSkb)I zgnf^1Y*1UUE^AISVpxZ{D*QlbK|V)hrlC=|3(4>Z%+5YRw&fl2JK*%_;aBuBdf0)E z4~$v4{H5TV-?X_)lm1bg_{1=sYV#HOgEn_*(gAt>Uu}e^0K~zWE&cC%d}{dgn&;7D z_I7%v=P5i*C%*!uG!K2k^At~i0DWd{JA-D?0ssI232;bRa{vGU0RR910RT@W#MS@+ z0Kia8R7L;)|0#0+DY^eCYXATL{V96?D7OFq{{Q{{|0uBkDyjb|ZvQB%|0{t1D5d`> zp#LbW|0{FUP>}zY$o^Hp|AxN*aHamW+Wp(+{&2?rNUr}pa{YDmg%SV&1Gz~= zK~zY`)t75ysxS#S=h0`rOkJY$Xx#LekY=iKf8|ErU$BL)MyWD&~x4T#m6|#L%aLQ;3GC zb4sdyc&(v7JRu(z95Jor$4Ro@{W+`MI^mp`L-X~`>ZXQPH*2ok8Y*u7*Xp8%ZeUq` z@%(`^Tsd9WVx?AVo<(MIyqA}k7qAX4&*=hp$sunDOd#+e2M5|Ex8b&0t3}IptHCdH zwNoB18@^s&{YJ08@`!ze1z+nT*RMXy%Z>otxdyebype25SWH1kAd~(DUe*H?zIxn8ifElSQGzW)pxRvbF(oHlIxF4}vWOU~rxJ z2S))5X<$mBGe(o|1TzHq$p*ifpS4eVgr9Vg(Vl$8!UAbOO$1zue0QgXvAwh84LHsi zrvTq6ktKX5q#ZN(0gUaMV%q3eiX7lMU1We5z*Mwb&VL8XF~4E2qWGu~4)U}qCWCMg z1W$9SsW6hIjgb)!5LP2kgFwLYT=C~ujG4wn!XY|NBYK1*3BMpLNv8ZHz?k>=s9*pz zgGWS#UtHIfaCJVwNaSu4DvIPj48U(1RpAhZ#*TA{V|hl?(EVWep4^Av=xSj1Wh)D* zG&|vRG)5cRm{a(K)JlV=E(xtx~ z9oi5BxY0kYu6ocYMD~}BZVffEU1RCAETcdei;A0q@R7`!d62lVRZ<=*z&}I(|JN63T z<8-_k*U)C1#)r8lHfB7C$!EI#xjmzwZTg8n97>lFb9`uh%paXm#Ico8{I^01|5Z3Y m^XEj^W09%Wm7f*)|MeG&CZon#`=kW`0000 [['a', 'b'], ['c', 'd']] + * + * chunk(['a', 'b', 'c', 'd'], 3) + * // => [['a', 'b', 'c'], ['d']] + */ +export function chunk(array: any[], size = 1) { // tslint:disable-line:no-any + const length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + let index = 0; + let resIndex = 0; + const result = new Array(Math.ceil(length / size)); + + while (index < length) { + result[resIndex++] = array.slice(index, (index += size)); + } + return result; +} + +/** + * Takes a multidimensional array and converts it to a one-dimensional array. + * + * @param {Array} nestedArray The array to be flattened. + * @returns {Array} Returns the new flattened array. + * @example + * + * flatten([['a', 'b'], ['c', 'd']]) + * // => ['a', 'b', 'c', 'd'] + * + */ +export function flatten(nestedArray: any[][]) { // tslint:disable-line:no-any + const result = []; + + (function loop(array: any[]) { // tslint:disable-line:no-any + for (let i = 0; i < array.length; i++) { + if (Array.isArray(array[i])) { + loop(array[i]); + } else { + result.push(array[i]); + } + } + })(nestedArray); + + return result; +} diff --git a/packages/nodes-base/package.json b/packages/nodes-base/package.json index 57332957ee..5513c78130 100644 --- a/packages/nodes-base/package.json +++ b/packages/nodes-base/package.json @@ -1,29 +1,160 @@ { - "name": "n8n-nodes-base", - "version": "0.63.1", - "description": "Base nodes of n8n", - "license": "SEE LICENSE IN LICENSE.md", - "homepage": "https://n8n.io", - "author": { - "name": "Jan Oberhauser", - "email": "jan@n8n.io" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/n8n-io/n8n.git" - }, - "main": "dist/src/index", - "types": "dist/src/index.d.ts", - "scripts": { - "dev": "npm run watch", - "build": "tsc && gulp", - "tslint": "tslint -p tsconfig.json -c tslint.json", - "watch": "tsc --watch", - "test": "jest" - }, - "files": [ - "dist" + "name": "n8n-nodes-base", + "version": "0.69.0", + "description": "Base nodes of n8n", + "license": "SEE LICENSE IN LICENSE.md", + "homepage": "https://n8n.io", + "author": { + "name": "Jan Oberhauser", + "email": "jan@n8n.io" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/n8n-io/n8n.git" + }, + "main": "dist/src/index", + "types": "dist/src/index.d.ts", + "scripts": { + "dev": "npm run watch", + "build": "tsc && gulp", + "tslint": "tslint -p tsconfig.json -c tslint.json", + "watch": "tsc --watch", + "test": "jest" + }, + "files": [ + "dist" + ], + "n8n": { + "credentials": [ + "dist/credentials/ActiveCampaignApi.credentials.js", + "dist/credentials/AgileCrmApi.credentials.js", + "dist/credentials/AcuitySchedulingApi.credentials.js", + "dist/credentials/AirtableApi.credentials.js", + "dist/credentials/Amqp.credentials.js", + "dist/credentials/AsanaApi.credentials.js", + "dist/credentials/Aws.credentials.js", + "dist/credentials/AffinityApi.credentials.js", + "dist/credentials/BannerbearApi.credentials.js", + "dist/credentials/BitbucketApi.credentials.js", + "dist/credentials/BitlyApi.credentials.js", + "dist/credentials/ChargebeeApi.credentials.js", + "dist/credentials/CircleCiApi.credentials.js", + "dist/credentials/ClearbitApi.credentials.js", + "dist/credentials/ClickUpApi.credentials.js", + "dist/credentials/ClockifyApi.credentials.js", + "dist/credentials/CockpitApi.credentials.js", + "dist/credentials/CodaApi.credentials.js", + "dist/credentials/CopperApi.credentials.js", + "dist/credentials/CalendlyApi.credentials.js", + "dist/credentials/CrateDb.credentials.js", + "dist/credentials/DisqusApi.credentials.js", + "dist/credentials/DriftApi.credentials.js", + "dist/credentials/DriftOAuth2Api.credentials.js", + "dist/credentials/DropboxApi.credentials.js", + "dist/credentials/EventbriteApi.credentials.js", + "dist/credentials/EventbriteOAuth2Api.credentials.js", + "dist/credentials/FacebookGraphApi.credentials.js", + "dist/credentials/FreshdeskApi.credentials.js", + "dist/credentials/FileMaker.credentials.js", + "dist/credentials/FlowApi.credentials.js", + "dist/credentials/GithubApi.credentials.js", + "dist/credentials/GithubOAuth2Api.credentials.js", + "dist/credentials/GitlabApi.credentials.js", + "dist/credentials/GitlabOAuth2Api.credentials.js", + "dist/credentials/GoogleApi.credentials.js", + "dist/credentials/GoogleCalendarOAuth2Api.credentials.js", + "dist/credentials/GoogleDriveOAuth2Api.credentials.js", + "dist/credentials/GoogleOAuth2Api.credentials.js", + "dist/credentials/GoogleSheetsOAuth2Api.credentials.js", + "dist/credentials/GoogleTasksOAuth2Api.credentials.js", + "dist/credentials/GumroadApi.credentials.js", + "dist/credentials/HarvestApi.credentials.js", + "dist/credentials/HelpScoutOAuth2Api.credentials.js", + "dist/credentials/HttpBasicAuth.credentials.js", + "dist/credentials/HttpDigestAuth.credentials.js", + "dist/credentials/HttpHeaderAuth.credentials.js", + "dist/credentials/HubspotApi.credentials.js", + "dist/credentials/HubspotDeveloperApi.credentials.js", + "dist/credentials/HubspotOAuth2Api.credentials.js", + "dist/credentials/HunterApi.credentials.js", + "dist/credentials/Imap.credentials.js", + "dist/credentials/IntercomApi.credentials.js", + "dist/credentials/InvoiceNinjaApi.credentials.js", + "dist/credentials/JiraSoftwareCloudApi.credentials.js", + "dist/credentials/JiraSoftwareServerApi.credentials.js", + "dist/credentials/JotFormApi.credentials.js", + "dist/credentials/KeapOAuth2Api.credentials.js", + "dist/credentials/LinkFishApi.credentials.js", + "dist/credentials/MailchimpApi.credentials.js", + "dist/credentials/MailchimpOAuth2Api.credentials.js", + "dist/credentials/MailgunApi.credentials.js", + "dist/credentials/MailjetEmailApi.credentials.js", + "dist/credentials/MailjetSmsApi.credentials.js", + "dist/credentials/MandrillApi.credentials.js", + "dist/credentials/MattermostApi.credentials.js", + "dist/credentials/MauticApi.credentials.js", + "dist/credentials/MauticOAuth2Api.credentials.js", + "dist/credentials/MessageBirdApi.credentials.js", + "dist/credentials/MicrosoftExcelOAuth2Api.credentials.js", + "dist/credentials/MicrosoftOAuth2Api.credentials.js", + "dist/credentials/MicrosoftOneDriveOAuth2Api.credentials.js", + "dist/credentials/MicrosoftSql.credentials.js", + "dist/credentials/MoceanApi.credentials.js", + "dist/credentials/MondayComApi.credentials.js", + "dist/credentials/MongoDb.credentials.js", + "dist/credentials/Msg91Api.credentials.js", + "dist/credentials/MySql.credentials.js", + "dist/credentials/NextCloudApi.credentials.js", + "dist/credentials/NextCloudOAuth2Api.credentials.js", + "dist/credentials/OAuth1Api.credentials.js", + "dist/credentials/OAuth2Api.credentials.js", + "dist/credentials/OpenWeatherMapApi.credentials.js", + "dist/credentials/PagerDutyApi.credentials.js", + "dist/credentials/PagerDutyOAuth2Api.credentials.js", + "dist/credentials/PayPalApi.credentials.js", + "dist/credentials/PipedriveApi.credentials.js", + "dist/credentials/Postgres.credentials.js", + "dist/credentials/PostmarkApi.credentials.js", + "dist/credentials/QuestDb.credentials.js", + "dist/credentials/Redis.credentials.js", + "dist/credentials/RocketchatApi.credentials.js", + "dist/credentials/RundeckApi.credentials.js", + "dist/credentials/ShopifyApi.credentials.js", + "dist/credentials/SalesforceOAuth2Api.credentials.js", + "dist/credentials/SlackApi.credentials.js", + "dist/credentials/SlackOAuth2Api.credentials.js", + "dist/credentials/Sms77Api.credentials.js", + "dist/credentials/Smtp.credentials.js", + "dist/credentials/StripeApi.credentials.js", + "dist/credentials/SalesmateApi.credentials.js", + "dist/credentials/SegmentApi.credentials.js", + "dist/credentials/Signl4Api.credentials.js", + "dist/credentials/SpotifyOAuth2Api.credentials.js", + "dist/credentials/SurveyMonkeyApi.credentials.js", + "dist/credentials/SurveyMonkeyOAuth2Api.credentials.js", + "dist/credentials/TelegramApi.credentials.js", + "dist/credentials/TodoistApi.credentials.js", + "dist/credentials/TrelloApi.credentials.js", + "dist/credentials/TwilioApi.credentials.js", + "dist/credentials/TwitterOAuth1Api.credentials.js", + "dist/credentials/TypeformApi.credentials.js", + "dist/credentials/TypeformOAuth2Api.credentials.js", + "dist/credentials/TogglApi.credentials.js", + "dist/credentials/UpleadApi.credentials.js", + "dist/credentials/VeroApi.credentials.js", + "dist/credentials/WebflowApi.credentials.js", + "dist/credentials/WebflowOAuth2Api.credentials.js", + "dist/credentials/WooCommerceApi.credentials.js", + "dist/credentials/WordpressApi.credentials.js", + "dist/credentials/XeroOAuth2Api.credentials.js", + "dist/credentials/ZendeskApi.credentials.js", + "dist/credentials/ZendeskOAuth2Api.credentials.js", + "dist/credentials/ZohoOAuth2Api.credentials.js", + "dist/credentials/ZoomApi.credentials.js", + "dist/credentials/ZoomOAuth2Api.credentials.js", + "dist/credentials/ZulipApi.credentials.js" ], +<<<<<<< HEAD "n8n": { "credentials": [ "dist/credentials/ActiveCampaignApi.credentials.js", @@ -282,83 +413,250 @@ "dist/nodes/Zoho/ZohoCrm.node.js", "dist/nodes/Zulip/Zulip.node.js" ] +======= + "nodes": [ + "dist/nodes/ActiveCampaign/ActiveCampaign.node.js", + "dist/nodes/ActiveCampaign/ActiveCampaignTrigger.node.js", + "dist/nodes/AgileCrm/AgileCrm.node.js", + "dist/nodes/Airtable/Airtable.node.js", + "dist/nodes/AcuityScheduling/AcuitySchedulingTrigger.node.js", + "dist/nodes/Amqp/Amqp.node.js", + "dist/nodes/Amqp/AmqpTrigger.node.js", + "dist/nodes/Asana/Asana.node.js", + "dist/nodes/Asana/AsanaTrigger.node.js", + "dist/nodes/Affinity/Affinity.node.js", + "dist/nodes/Affinity/AffinityTrigger.node.js", + "dist/nodes/Aws/AwsLambda.node.js", + "dist/nodes/Aws/S3/AwsS3.node.js", + "dist/nodes/Aws/AwsSes.node.js", + "dist/nodes/Aws/AwsSns.node.js", + "dist/nodes/Aws/AwsSnsTrigger.node.js", + "dist/nodes/Bannerbear/Bannerbear.node.js", + "dist/nodes/Bitbucket/BitbucketTrigger.node.js", + "dist/nodes/Bitly/Bitly.node.js", + "dist/nodes/Calendly/CalendlyTrigger.node.js", + "dist/nodes/Chargebee/Chargebee.node.js", + "dist/nodes/Chargebee/ChargebeeTrigger.node.js", + "dist/nodes/CircleCi/CircleCi.node.js", + "dist/nodes/Clearbit/Clearbit.node.js", + "dist/nodes/ClickUp/ClickUp.node.js", + "dist/nodes/ClickUp/ClickUpTrigger.node.js", + "dist/nodes/Clockify/ClockifyTrigger.node.js", + "dist/nodes/Cockpit/Cockpit.node.js", + "dist/nodes/Coda/Coda.node.js", + "dist/nodes/Copper/CopperTrigger.node.js", + "dist/nodes/CrateDb/CrateDb.node.js", + "dist/nodes/Cron.node.js", + "dist/nodes/Crypto.node.js", + "dist/nodes/DateTime.node.js", + "dist/nodes/Discord/Discord.node.js", + "dist/nodes/Disqus/Disqus.node.js", + "dist/nodes/Drift/Drift.node.js", + "dist/nodes/Dropbox/Dropbox.node.js", + "dist/nodes/EditImage.node.js", + "dist/nodes/EmailReadImap.node.js", + "dist/nodes/EmailSend.node.js", + "dist/nodes/ErrorTrigger.node.js", + "dist/nodes/Eventbrite/EventbriteTrigger.node.js", + "dist/nodes/ExecuteCommand.node.js", + "dist/nodes/ExecuteWorkflow.node.js", + "dist/nodes/Facebook/FacebookGraphApi.node.js", + "dist/nodes/FileMaker/FileMaker.node.js", + "dist/nodes/Freshdesk/Freshdesk.node.js", + "dist/nodes/Flow/Flow.node.js", + "dist/nodes/Flow/FlowTrigger.node.js", + "dist/nodes/Function.node.js", + "dist/nodes/FunctionItem.node.js", + "dist/nodes/Github/Github.node.js", + "dist/nodes/Github/GithubTrigger.node.js", + "dist/nodes/Gitlab/Gitlab.node.js", + "dist/nodes/Gitlab/GitlabTrigger.node.js", + "dist/nodes/Google/Calendar/GoogleCalendar.node.js", + "dist/nodes/Google/Drive/GoogleDrive.node.js", + "dist/nodes/Google/Sheet/GoogleSheets.node.js", + "dist/nodes/Google/Task/GoogleTasks.node.js", + "dist/nodes/GraphQL/GraphQL.node.js", + "dist/nodes/Gumroad/GumroadTrigger.node.js", + "dist/nodes/HackerNews/HackerNews.node.js", + "dist/nodes/Harvest/Harvest.node.js", + "dist/nodes/HelpScout/HelpScout.node.js", + "dist/nodes/HelpScout/HelpScoutTrigger.node.js", + "dist/nodes/HtmlExtract/HtmlExtract.node.js", + "dist/nodes/HttpRequest.node.js", + "dist/nodes/Hubspot/Hubspot.node.js", + "dist/nodes/Hubspot/HubspotTrigger.node.js", + "dist/nodes/Hunter/Hunter.node.js", + "dist/nodes/If.node.js", + "dist/nodes/Intercom/Intercom.node.js", + "dist/nodes/Interval.node.js", + "dist/nodes/InvoiceNinja/InvoiceNinja.node.js", + "dist/nodes/InvoiceNinja/InvoiceNinjaTrigger.node.js", + "dist/nodes/Jira/Jira.node.js", + "dist/nodes/JotForm/JotFormTrigger.node.js", + "dist/nodes/Keap/Keap.node.js", + "dist/nodes/Keap/KeapTrigger.node.js", + "dist/nodes/LinkFish/LinkFish.node.js", + "dist/nodes/Mailchimp/Mailchimp.node.js", + "dist/nodes/Mailchimp/MailchimpTrigger.node.js", + "dist/nodes/Mailgun/Mailgun.node.js", + "dist/nodes/Mailjet/Mailjet.node.js", + "dist/nodes/Mailjet/MailjetTrigger.node.js", + "dist/nodes/Mandrill/Mandrill.node.js", + "dist/nodes/Mattermost/Mattermost.node.js", + "dist/nodes/Mautic/Mautic.node.js", + "dist/nodes/Mautic/MauticTrigger.node.js", + "dist/nodes/Merge.node.js", + "dist/nodes/MessageBird/MessageBird.node.js", + "dist/nodes/Microsoft/Excel/MicrosoftExcel.node.js", + "dist/nodes/Microsoft/OneDrive/MicrosoftOneDrive.node.js", + "dist/nodes/Microsoft/Sql/MicrosoftSql.node.js", + "dist/nodes/MoveBinaryData.node.js", + "dist/nodes/Mocean/Mocean.node.js", + "dist/nodes/MondayCom/MondayCom.node.js", + "dist/nodes/MongoDb/MongoDb.node.js", + "dist/nodes/MoveBinaryData.node.js", + "dist/nodes/Msg91/Msg91.node.js", + "dist/nodes/MySql/MySql.node.js", + "dist/nodes/NextCloud/NextCloud.node.js", + "dist/nodes/NoOp.node.js", + "dist/nodes/OpenWeatherMap.node.js", + "dist/nodes/PagerDuty/PagerDuty.node.js", + "dist/nodes/PayPal/PayPal.node.js", + "dist/nodes/PayPal/PayPalTrigger.node.js", + "dist/nodes/Pipedrive/Pipedrive.node.js", + "dist/nodes/Pipedrive/PipedriveTrigger.node.js", + "dist/nodes/Postgres/Postgres.node.js", + "dist/nodes/Postmark/PostmarkTrigger.node.js", + "dist/nodes/QuestDb/QuestDb.node.js", + "dist/nodes/ReadBinaryFile.node.js", + "dist/nodes/ReadBinaryFiles.node.js", + "dist/nodes/ReadPdf.node.js", + "dist/nodes/Redis/Redis.node.js", + "dist/nodes/RenameKeys.node.js", + "dist/nodes/Rocketchat/Rocketchat.node.js", + "dist/nodes/RssFeedRead.node.js", + "dist/nodes/Rundeck/Rundeck.node.js", + "dist/nodes/Salesforce/Salesforce.node.js", + "dist/nodes/Set.node.js", + "dist/nodes/Shopify/Shopify.node.js", + "dist/nodes/Shopify/ShopifyTrigger.node.js", + "dist/nodes/Signl4/Signl4.node.js", + "dist/nodes/Slack/Slack.node.js", + "dist/nodes/Sms77/Sms77.node.js", + "dist/nodes/SplitInBatches.node.js", + "dist/nodes/Spotify/Spotify.node.js", + "dist/nodes/SpreadsheetFile.node.js", + "dist/nodes/SseTrigger.node.js", + "dist/nodes/Start.node.js", + "dist/nodes/Stripe/StripeTrigger.node.js", + "dist/nodes/Switch.node.js", + "dist/nodes/Salesmate/Salesmate.node.js", + "dist/nodes/Segment/Segment.node.js", + "dist/nodes/SurveyMonkey/SurveyMonkeyTrigger.node.js", + "dist/nodes/Telegram/Telegram.node.js", + "dist/nodes/Telegram/TelegramTrigger.node.js", + "dist/nodes/Todoist/Todoist.node.js", + "dist/nodes/Toggl/TogglTrigger.node.js", + "dist/nodes/Trello/Trello.node.js", + "dist/nodes/Trello/TrelloTrigger.node.js", + "dist/nodes/Twilio/Twilio.node.js", + "dist/nodes/Twitter/Twitter.node.js", + "dist/nodes/Typeform/TypeformTrigger.node.js", + "dist/nodes/Uplead/Uplead.node.js", + "dist/nodes/Vero/Vero.node.js", + "dist/nodes/Webflow/WebflowTrigger.node.js", + "dist/nodes/Webhook.node.js", + "dist/nodes/Wordpress/Wordpress.node.js", + "dist/nodes/WooCommerce/WooCommerce.node.js", + "dist/nodes/WooCommerce/WooCommerceTrigger.node.js", + "dist/nodes/WriteBinaryFile.node.js", + "dist/nodes/Xero/Xero.node.js", + "dist/nodes/Xml.node.js", + "dist/nodes/Zendesk/Zendesk.node.js", + "dist/nodes/Zendesk/ZendeskTrigger.node.js", + "dist/nodes/Zoho/ZohoCrm.node.js", + "dist/nodes/Zoom/Zoom.node.js", + "dist/nodes/Zulip/Zulip.node.js" + ] + }, + "devDependencies": { + "@types/aws4": "^1.5.1", + "@types/basic-auth": "^1.1.2", + "@types/cheerio": "^0.22.15", + "@types/cron": "^1.6.1", + "@types/eventsource": "^1.1.2", + "@types/express": "^4.16.1", + "@types/formidable": "^1.0.31", + "@types/gm": "^1.18.2", + "@types/imap-simple": "^4.2.0", + "@types/jest": "^24.0.18", + "@types/lodash.set": "^4.3.6", + "@types/moment-timezone": "^0.5.12", + "@types/mongodb": "^3.5.4", + "@types/mssql": "^6.0.2", + "@types/node": "^10.10.1", + "@types/nodemailer": "^6.4.0", + "@types/redis": "^2.8.11", + "@types/request-promise-native": "~1.0.15", + "@types/uuid": "^3.4.6", + "@types/xml2js": "^0.4.3", + "gulp": "^4.0.0", + "jest": "^24.9.0", + "n8n-workflow": "~0.35.0", + "ts-jest": "^24.0.2", + "tslint": "^5.17.0", + "typescript": "~3.7.4" + }, + "dependencies": { + "aws4": "^1.8.0", + "basic-auth": "^2.0.1", + "change-case": "^4.1.1", + "cheerio": "^1.0.0-rc.3", + "cron": "^1.7.2", + "eventsource": "^1.0.7", + "formidable": "^1.2.1", + "glob-promise": "^3.4.0", + "gm": "^1.23.1", + "imap-simple": "^4.3.0", + "iso-639-1": "^2.1.3", + "jsonwebtoken": "^8.5.1", + "lodash.get": "^4.4.2", + "lodash.set": "^4.3.2", + "lodash.unset": "^4.5.2", + "moment": "2.24.0", + "moment-timezone": "^0.5.28", + "mongodb": "^3.5.5", + "mssql": "^6.2.0", + "mysql2": "^2.0.1", + "n8n-core": "~0.39.0", + "nodemailer": "^6.4.6", + "pdf-parse": "^1.1.1", + "pg-promise": "^9.0.3", + "redis": "^2.8.0", + "request": "^2.88.2", + "rhea": "^1.0.11", + "rss-parser": "^3.7.0", + "uuid": "^3.4.0", + "vm2": "^3.6.10", + "xlsx": "^0.14.3", + "xml2js": "^0.4.22" + }, + "jest": { + "transform": { + "^.+\\.tsx?$": "ts-jest" +>>>>>>> master }, - "devDependencies": { - "@types/aws4": "^1.5.1", - "@types/basic-auth": "^1.1.2", - "@types/cheerio": "^0.22.15", - "@types/cron": "^1.6.1", - "@types/eventsource": "^1.1.2", - "@types/express": "^4.16.1", - "@types/formidable": "^1.0.31", - "@types/gm": "^1.18.2", - "@types/imap-simple": "^4.2.0", - "@types/jest": "^24.0.18", - "@types/lodash.set": "^4.3.6", - "@types/moment-timezone": "^0.5.12", - "@types/mongodb": "^3.5.4", - "@types/node": "^10.10.1", - "@types/nodemailer": "^6.4.0", - "@types/redis": "^2.8.11", - "@types/request-promise-native": "~1.0.15", - "@types/uuid": "^3.4.6", - "@types/xml2js": "^0.4.3", - "gulp": "^4.0.0", - "jest": "^24.9.0", - "n8n-workflow": "~0.32.0", - "ts-jest": "^24.0.2", - "tslint": "^5.17.0", - "typescript": "~3.7.4" - }, - "dependencies": { - "aws4": "^1.8.0", - "basic-auth": "^2.0.1", - "change-case": "^4.1.1", - "cheerio": "^1.0.0-rc.3", - "cron": "^1.7.2", - "eventsource": "^1.0.7", - "formidable": "^1.2.1", - "glob-promise": "^3.4.0", - "gm": "^1.23.1", - "googleapis": "~50.0.0", - "imap-simple": "^4.3.0", - "iso-639-1": "^2.1.3", - "jsonwebtoken": "^8.5.1", - "lodash.get": "^4.4.2", - "lodash.set": "^4.3.2", - "lodash.unset": "^4.5.2", - "moment": "2.24.0", - "moment-timezone": "^0.5.28", - "mongodb": "^3.5.5", - "mysql2": "^2.0.1", - "n8n-core": "~0.35.0", - "nodemailer": "^6.4.6", - "pdf-parse": "^1.1.1", - "pg-promise": "^9.0.3", - "redis": "^2.8.0", - "request": "^2.88.2", - "rhea": "^1.0.11", - "rss-parser": "^3.7.0", - "uuid": "^3.4.0", - "vm2": "^3.6.10", - "xlsx": "^0.14.3", - "xml2js": "^0.4.22" - }, - "jest": { - "transform": { - "^.+\\.tsx?$": "ts-jest" - }, - "testURL": "http://localhost/", - "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", - "testPathIgnorePatterns": [ - "/dist/", - "/node_modules/" - ], - "moduleFileExtensions": [ - "ts", - "tsx", - "js", - "json" - ] - } + "testURL": "http://localhost/", + "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", + "testPathIgnorePatterns": [ + "/dist/", + "/node_modules/" + ], + "moduleFileExtensions": [ + "ts", + "tsx", + "js", + "json" + ] + } } diff --git a/packages/workflow/LICENSE.md b/packages/workflow/LICENSE.md index aac54547eb..24a7d38fc9 100644 --- a/packages/workflow/LICENSE.md +++ b/packages/workflow/LICENSE.md @@ -215,7 +215,7 @@ Licensor: n8n GmbH same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2020 n8n GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/packages/workflow/README.md b/packages/workflow/README.md index 40a74b1116..4f3ef155a3 100644 --- a/packages/workflow/README.md +++ b/packages/workflow/README.md @@ -1,6 +1,6 @@ # n8n-workflow -![n8n.io - Workflow Automation](https://n8n.io/n8n-logo.png) +![n8n.io - Workflow Automation](https://raw.githubusercontent.com/n8n-io/n8n/master/assets/n8n-logo.png) Workflow base code for n8n diff --git a/packages/workflow/package.json b/packages/workflow/package.json index 969270199b..aed6e160ba 100644 --- a/packages/workflow/package.json +++ b/packages/workflow/package.json @@ -1,6 +1,6 @@ { "name": "n8n-workflow", - "version": "0.32.0", + "version": "0.35.0", "description": "Workflow base code of n8n", "license": "SEE LICENSE IN LICENSE.md", "homepage": "https://n8n.io", diff --git a/packages/workflow/src/Interfaces.ts b/packages/workflow/src/Interfaces.ts index f8a6cc5e82..fa3628e379 100644 --- a/packages/workflow/src/Interfaces.ts +++ b/packages/workflow/src/Interfaces.ts @@ -336,6 +336,7 @@ export interface INode { continueOnFail?: boolean; parameters: INodeParameters; credentials?: INodeCredentials; + webhookId?: string; } @@ -558,8 +559,9 @@ export interface IWebhookData { } export interface IWebhookDescription { - [key: string]: WebhookHttpMethod | WebhookResponseMode | string | undefined; + [key: string]: WebhookHttpMethod | WebhookResponseMode | boolean | string | undefined; httpMethod: WebhookHttpMethod | string; + isFullPath?: boolean; name: string; path: string; responseBinaryPropertyName?: string; diff --git a/packages/workflow/src/NodeHelpers.ts b/packages/workflow/src/NodeHelpers.ts index fcaca55a0a..3e38931ae8 100644 --- a/packages/workflow/src/NodeHelpers.ts +++ b/packages/workflow/src/NodeHelpers.ts @@ -755,7 +755,7 @@ export function getNodeWebhooks(workflow: Workflow, node: INode, additionalData: const returnData: IWebhookData[] = []; for (const webhookDescription of nodeType.description.webhooks) { - let nodeWebhookPath = workflow.getSimpleParameterValue(node, webhookDescription['path'], 'GET'); + let nodeWebhookPath = workflow.getSimpleParameterValue(node, webhookDescription['path']); if (nodeWebhookPath === undefined) { // TODO: Use a proper logger console.error(`No webhook path could be found for node "${node.name}" in workflow "${workflowId}".`); @@ -768,7 +768,8 @@ export function getNodeWebhooks(workflow: Workflow, node: INode, additionalData: nodeWebhookPath = nodeWebhookPath.slice(1); } - const path = getNodeWebhookPath(workflowId, node, nodeWebhookPath); + const isFullPath: boolean = workflow.getSimpleParameterValue(node, webhookDescription['isFullPath'], false) as boolean; + const path = getNodeWebhookPath(workflowId, node, nodeWebhookPath, isFullPath); const httpMethod = workflow.getSimpleParameterValue(node, webhookDescription['httpMethod'], 'GET'); @@ -791,6 +792,61 @@ export function getNodeWebhooks(workflow: Workflow, node: INode, additionalData: return returnData; } +export function getNodeWebhooksBasic(workflow: Workflow, node: INode): IWebhookData[] { + if (node.disabled === true) { + // Node is disabled so webhooks will also not be enabled + return []; + } + + const nodeType = workflow.nodeTypes.getByName(node.type) as INodeType; + + if (nodeType.description.webhooks === undefined) { + // Node does not have any webhooks so return + return []; + } + + const workflowId = workflow.id || '__UNSAVED__'; + + const returnData: IWebhookData[] = []; + for (const webhookDescription of nodeType.description.webhooks) { + let nodeWebhookPath = workflow.getSimpleParameterValue(node, webhookDescription['path']); + if (nodeWebhookPath === undefined) { + // TODO: Use a proper logger + console.error(`No webhook path could be found for node "${node.name}" in workflow "${workflowId}".`); + continue; + } + + nodeWebhookPath = nodeWebhookPath.toString(); + + if (nodeWebhookPath.charAt(0) === '/') { + nodeWebhookPath = nodeWebhookPath.slice(1); + } + + const isFullPath: boolean = workflow.getSimpleParameterValue(node, webhookDescription['isFullPath'], false) as boolean; + + const path = getNodeWebhookPath(workflowId, node, nodeWebhookPath, isFullPath); + + const httpMethod = workflow.getSimpleParameterValue(node, webhookDescription['httpMethod']); + + if (httpMethod === undefined) { + // TODO: Use a proper logger + console.error(`The webhook "${path}" for node "${node.name}" in workflow "${workflowId}" could not be added because the httpMethod is not defined.`); + continue; + } + + //@ts-ignore + returnData.push({ + httpMethod: httpMethod.toString() as WebhookHttpMethod, + node: node.name, + path, + webhookDescription, + workflowId, + }); + } + + return returnData; +} + /** * Returns the webhook path @@ -801,8 +857,17 @@ export function getNodeWebhooks(workflow: Workflow, node: INode, additionalData: * @param {string} path * @returns {string} */ -export function getNodeWebhookPath(workflowId: string, node: INode, path: string): string { - return `${workflowId}/${encodeURIComponent(node.name.toLowerCase())}/${path}`; +export function getNodeWebhookPath(workflowId: string, node: INode, path: string, isFullPath?: boolean): string { + let webhookPath = ''; + if (node.webhookId === undefined) { + webhookPath = `${workflowId}/${encodeURIComponent(node.name.toLowerCase())}/${path}`; + } else { + if (isFullPath === true) { + return path; + } + webhookPath = `${node.webhookId}/${path}`; + } + return webhookPath; } @@ -814,11 +879,11 @@ export function getNodeWebhookPath(workflowId: string, node: INode, path: string * @param {string} workflowId * @param {string} nodeTypeName * @param {string} path + * @param {boolean} isFullPath * @returns {string} */ -export function getNodeWebhookUrl(baseUrl: string, workflowId: string, node: INode, path: string): string { - // return `${baseUrl}/${workflowId}/${nodeTypeName}/${path}`; - return `${baseUrl}/${getNodeWebhookPath(workflowId, node, path)}`; +export function getNodeWebhookUrl(baseUrl: string, workflowId: string, node: INode, path: string, isFullPath?: boolean): string { + return `${baseUrl}/${getNodeWebhookPath(workflowId, node, path, isFullPath)}`; } diff --git a/packages/workflow/src/Workflow.ts b/packages/workflow/src/Workflow.ts index 9a7d3ef1eb..9306b68492 100644 --- a/packages/workflow/src/Workflow.ts +++ b/packages/workflow/src/Workflow.ts @@ -715,7 +715,7 @@ export class Workflow { * @returns {(string | undefined)} * @memberof Workflow */ - getSimpleParameterValue(node: INode, parameterValue: string | undefined, defaultValue?: boolean | number | string): boolean | number | string | undefined { + getSimpleParameterValue(node: INode, parameterValue: string | boolean | undefined, defaultValue?: boolean | number | string): boolean | number | string | undefined { if (parameterValue === undefined) { // Value is not set so return the default return defaultValue; @@ -1085,18 +1085,18 @@ export class Workflow { * @returns {(Promise)} * @memberof Workflow */ - async runNode(node: INode, inputData: ITaskDataConnections, runExecutionData: IRunExecutionData, runIndex: number, additionalData: IWorkflowExecuteAdditionalData, nodeExecuteFunctions: INodeExecuteFunctions, mode: WorkflowExecuteMode): Promise { + async runNode(node: INode, inputData: ITaskDataConnections, runExecutionData: IRunExecutionData, runIndex: number, additionalData: IWorkflowExecuteAdditionalData, nodeExecuteFunctions: INodeExecuteFunctions, mode: WorkflowExecuteMode): Promise { if (node.disabled === true) { // If node is disabled simply pass the data through // return NodeRunHelpers. if (inputData.hasOwnProperty('main') && inputData.main.length > 0) { // If the node is disabled simply return the data from the first main input if (inputData.main[0] === null) { - return null; + return undefined; } return [(inputData.main[0] as INodeExecutionData[])]; } - return null; + return undefined; } const nodeType = this.nodeTypes.getByName(node.type); @@ -1112,7 +1112,7 @@ export class Workflow { if (connectionInputData.length === 0) { // No data for node so return - return null; + return undefined; } if (runExecutionData.resultData.lastNodeExecuted === node.name && runExecutionData.resultData.error !== undefined) { From 28fcaf79ae266571a6fc837241998117ca7f0aa8 Mon Sep 17 00:00:00 2001 From: ricardo Date: Thu, 23 Jul 2020 17:10:20 -0400 Subject: [PATCH 4/4] :bug: Fix merge issues --- .../nodes/Pipedrive/GenericFunctions.ts | 26 +- .../nodes/Pipedrive/Pipedrive.node.ts | 7 +- packages/nodes-base/package.json | 262 +----------------- 3 files changed, 4 insertions(+), 291 deletions(-) diff --git a/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts b/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts index 23ef841bee..17033eaf76 100644 --- a/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts +++ b/packages/nodes-base/nodes/Pipedrive/GenericFunctions.ts @@ -11,10 +11,6 @@ import { import { OptionsWithUri, } from 'request'; -<<<<<<< HEAD - -======= ->>>>>>> master export interface ICustomInterface { name: string; @@ -38,22 +34,8 @@ export interface ICustomProperties { * @param {object} body * @returns {Promise} */ -<<<<<<< HEAD -export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctions, method: string, endpoint: string, body: IDataObject, query?: IDataObject, formData?: IDataObject, downloadFile?: boolean): Promise { // tslint:disable-line:no-any - const authenticationMethod = this.getNodeParameter('authentication', 0); -======= export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, body: IDataObject, query?: IDataObject, formData?: IDataObject, downloadFile?: boolean): Promise { // tslint:disable-line:no-any - const credentials = this.getCredentials('pipedriveApi'); - if (credentials === undefined) { - throw new Error('No credentials got returned!'); - } - - if (query === undefined) { - query = {}; - } - - query.api_token = credentials.apiToken; ->>>>>>> master + const authenticationMethod = this.getNodeParameter('authentication', 0); const options: OptionsWithUri = { headers: { @@ -85,7 +67,6 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio let responseData; try { -<<<<<<< HEAD if (authenticationMethod === 'basicAuth' || authenticationMethod === 'apiToken') { const credentials = this.getCredentials('pipedriveApi'); @@ -95,15 +76,12 @@ export async function pipedriveApiRequest(this: IHookFunctions | IExecuteFunctio query.api_token = credentials.apiToken; + //@ts-ignore responseData = await this.helpers.request(options); } else { responseData = await this.helpers.requestOAuth2!.call(this, 'pipedriveOAuth2Api', options); } -======= - //@ts-ignore - const responseData = await this.helpers.request(options); ->>>>>>> master if (downloadFile === true) { return { diff --git a/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts b/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts index 9a0da8d25f..a1f48305aa 100644 --- a/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts +++ b/packages/nodes-base/nodes/Pipedrive/Pipedrive.node.ts @@ -2137,6 +2137,7 @@ export class Pipedrive implements INodeType { displayName: 'Term', name: 'term', type: 'string', + required: true, displayOptions: { show: { operation: [ @@ -2722,12 +2723,6 @@ export class Pipedrive implements INodeType { responseData = await pipedriveApiRequest.call(this, requestMethod, endpoint, body, qs, formData, downloadFile); -<<<<<<< HEAD - if (responseData.data === null) { - responseData.data = []; - } -======= ->>>>>>> master } if (resource === 'file' && operation === 'download') { diff --git a/packages/nodes-base/package.json b/packages/nodes-base/package.json index 5513c78130..e9d965aa21 100644 --- a/packages/nodes-base/package.json +++ b/packages/nodes-base/package.json @@ -113,6 +113,7 @@ "dist/credentials/PagerDutyOAuth2Api.credentials.js", "dist/credentials/PayPalApi.credentials.js", "dist/credentials/PipedriveApi.credentials.js", + "dist/credentials/PipedriveOAuth2Api.credentials.js", "dist/credentials/Postgres.credentials.js", "dist/credentials/PostmarkApi.credentials.js", "dist/credentials/QuestDb.credentials.js", @@ -154,266 +155,6 @@ "dist/credentials/ZoomOAuth2Api.credentials.js", "dist/credentials/ZulipApi.credentials.js" ], -<<<<<<< HEAD - "n8n": { - "credentials": [ - "dist/credentials/ActiveCampaignApi.credentials.js", - "dist/credentials/AgileCrmApi.credentials.js", - "dist/credentials/AcuitySchedulingApi.credentials.js", - "dist/credentials/AirtableApi.credentials.js", - "dist/credentials/Amqp.credentials.js", - "dist/credentials/AsanaApi.credentials.js", - "dist/credentials/Aws.credentials.js", - "dist/credentials/AffinityApi.credentials.js", - "dist/credentials/BannerbearApi.credentials.js", - "dist/credentials/BitbucketApi.credentials.js", - "dist/credentials/BitlyApi.credentials.js", - "dist/credentials/ChargebeeApi.credentials.js", - "dist/credentials/ClearbitApi.credentials.js", - "dist/credentials/ClickUpApi.credentials.js", - "dist/credentials/ClockifyApi.credentials.js", - "dist/credentials/CockpitApi.credentials.js", - "dist/credentials/CodaApi.credentials.js", - "dist/credentials/CopperApi.credentials.js", - "dist/credentials/CalendlyApi.credentials.js", - "dist/credentials/DisqusApi.credentials.js", - "dist/credentials/DriftApi.credentials.js", - "dist/credentials/DropboxApi.credentials.js", - "dist/credentials/EventbriteApi.credentials.js", - "dist/credentials/FacebookGraphApi.credentials.js", - "dist/credentials/FreshdeskApi.credentials.js", - "dist/credentials/FileMaker.credentials.js", - "dist/credentials/FlowApi.credentials.js", - "dist/credentials/GithubApi.credentials.js", - "dist/credentials/GithubOAuth2Api.credentials.js", - "dist/credentials/GitlabApi.credentials.js", - "dist/credentials/GoogleApi.credentials.js", - "dist/credentials/GoogleCalendarOAuth2Api.credentials.js", - "dist/credentials/GoogleOAuth2Api.credentials.js", - "dist/credentials/GoogleSheetsOAuth2Api.credentials.js", - "dist/credentials/GumroadApi.credentials.js", - "dist/credentials/HarvestApi.credentials.js", - "dist/credentials/HelpScoutOAuth2Api.credentials.js", - "dist/credentials/HttpBasicAuth.credentials.js", - "dist/credentials/HttpDigestAuth.credentials.js", - "dist/credentials/HttpHeaderAuth.credentials.js", - "dist/credentials/HubspotApi.credentials.js", - "dist/credentials/HubspotDeveloperApi.credentials.js", - "dist/credentials/HunterApi.credentials.js", - "dist/credentials/Imap.credentials.js", - "dist/credentials/IntercomApi.credentials.js", - "dist/credentials/InvoiceNinjaApi.credentials.js", - "dist/credentials/JiraSoftwareCloudApi.credentials.js", - "dist/credentials/JiraSoftwareServerApi.credentials.js", - "dist/credentials/JotFormApi.credentials.js", - "dist/credentials/KeapOAuth2Api.credentials.js", - "dist/credentials/LinkFishApi.credentials.js", - "dist/credentials/MailchimpApi.credentials.js", - "dist/credentials/MailgunApi.credentials.js", - "dist/credentials/MailjetEmailApi.credentials.js", - "dist/credentials/MailjetSmsApi.credentials.js", - "dist/credentials/MandrillApi.credentials.js", - "dist/credentials/MattermostApi.credentials.js", - "dist/credentials/MauticApi.credentials.js", - "dist/credentials/MicrosoftExcelOAuth2Api.credentials.js", - "dist/credentials/MicrosoftOAuth2Api.credentials.js", - "dist/credentials/MicrosoftOneDriveOAuth2Api.credentials.js", - "dist/credentials/MoceanApi.credentials.js", - "dist/credentials/MondayComApi.credentials.js", - "dist/credentials/MongoDb.credentials.js", - "dist/credentials/Msg91Api.credentials.js", - "dist/credentials/MySql.credentials.js", - "dist/credentials/NextCloudApi.credentials.js", - "dist/credentials/OAuth1Api.credentials.js", - "dist/credentials/OAuth2Api.credentials.js", - "dist/credentials/OpenWeatherMapApi.credentials.js", - "dist/credentials/PagerDutyApi.credentials.js", - "dist/credentials/PayPalApi.credentials.js", - "dist/credentials/PipedriveApi.credentials.js", - "dist/credentials/PipedriveOAuth2Api.credentials.js", - "dist/credentials/Postgres.credentials.js", - "dist/credentials/Redis.credentials.js", - "dist/credentials/RocketchatApi.credentials.js", - "dist/credentials/RundeckApi.credentials.js", - "dist/credentials/ShopifyApi.credentials.js", - "dist/credentials/SalesforceOAuth2Api.credentials.js", - "dist/credentials/SlackApi.credentials.js", - "dist/credentials/SlackOAuth2Api.credentials.js", - "dist/credentials/Sms77Api.credentials.js", - "dist/credentials/Smtp.credentials.js", - "dist/credentials/StripeApi.credentials.js", - "dist/credentials/SalesmateApi.credentials.js", - "dist/credentials/SegmentApi.credentials.js", - "dist/credentials/SurveyMonkeyApi.credentials.js", - "dist/credentials/TelegramApi.credentials.js", - "dist/credentials/TodoistApi.credentials.js", - "dist/credentials/TrelloApi.credentials.js", - "dist/credentials/TwilioApi.credentials.js", - "dist/credentials/TwitterOAuth1Api.credentials.js", - "dist/credentials/TypeformApi.credentials.js", - "dist/credentials/TogglApi.credentials.js", - "dist/credentials/UpleadApi.credentials.js", - "dist/credentials/VeroApi.credentials.js", - "dist/credentials/WebflowApi.credentials.js", - "dist/credentials/WooCommerceApi.credentials.js", - "dist/credentials/WordpressApi.credentials.js", - "dist/credentials/ZendeskApi.credentials.js", - "dist/credentials/ZohoOAuth2Api.credentials.js", - "dist/credentials/ZulipApi.credentials.js" - ], - "nodes": [ - "dist/nodes/ActiveCampaign/ActiveCampaign.node.js", - "dist/nodes/ActiveCampaign/ActiveCampaignTrigger.node.js", - "dist/nodes/AgileCrm/AgileCrm.node.js", - "dist/nodes/Airtable/Airtable.node.js", - "dist/nodes/AcuityScheduling/AcuitySchedulingTrigger.node.js", - "dist/nodes/Amqp/Amqp.node.js", - "dist/nodes/Amqp/AmqpTrigger.node.js", - "dist/nodes/Asana/Asana.node.js", - "dist/nodes/Asana/AsanaTrigger.node.js", - "dist/nodes/Affinity/Affinity.node.js", - "dist/nodes/Affinity/AffinityTrigger.node.js", - "dist/nodes/Aws/AwsLambda.node.js", - "dist/nodes/Aws/S3/AwsS3.node.js", - "dist/nodes/Aws/AwsSes.node.js", - "dist/nodes/Aws/AwsSns.node.js", - "dist/nodes/Aws/AwsSnsTrigger.node.js", - "dist/nodes/Bannerbear/Bannerbear.node.js", - "dist/nodes/Bitbucket/BitbucketTrigger.node.js", - "dist/nodes/Bitly/Bitly.node.js", - "dist/nodes/Calendly/CalendlyTrigger.node.js", - "dist/nodes/Chargebee/Chargebee.node.js", - "dist/nodes/Chargebee/ChargebeeTrigger.node.js", - "dist/nodes/Clearbit/Clearbit.node.js", - "dist/nodes/ClickUp/ClickUp.node.js", - "dist/nodes/ClickUp/ClickUpTrigger.node.js", - "dist/nodes/Clockify/ClockifyTrigger.node.js", - "dist/nodes/Cockpit/Cockpit.node.js", - "dist/nodes/Coda/Coda.node.js", - "dist/nodes/Copper/CopperTrigger.node.js", - "dist/nodes/Cron.node.js", - "dist/nodes/Crypto.node.js", - "dist/nodes/DateTime.node.js", - "dist/nodes/Discord/Discord.node.js", - "dist/nodes/Disqus/Disqus.node.js", - "dist/nodes/Drift/Drift.node.js", - "dist/nodes/Dropbox/Dropbox.node.js", - "dist/nodes/EditImage.node.js", - "dist/nodes/EmailReadImap.node.js", - "dist/nodes/EmailSend.node.js", - "dist/nodes/ErrorTrigger.node.js", - "dist/nodes/Eventbrite/EventbriteTrigger.node.js", - "dist/nodes/ExecuteCommand.node.js", - "dist/nodes/ExecuteWorkflow.node.js", - "dist/nodes/Facebook/FacebookGraphApi.node.js", - "dist/nodes/FileMaker/FileMaker.node.js", - "dist/nodes/Freshdesk/Freshdesk.node.js", - "dist/nodes/Flow/Flow.node.js", - "dist/nodes/Flow/FlowTrigger.node.js", - "dist/nodes/Function.node.js", - "dist/nodes/FunctionItem.node.js", - "dist/nodes/Github/Github.node.js", - "dist/nodes/Github/GithubTrigger.node.js", - "dist/nodes/Gitlab/Gitlab.node.js", - "dist/nodes/Gitlab/GitlabTrigger.node.js", - "dist/nodes/Google/Calendar/GoogleCalendar.node.js", - "dist/nodes/Google/Drive/GoogleDrive.node.js", - "dist/nodes/Google/Sheet/GoogleSheets.node.js", - "dist/nodes/GraphQL/GraphQL.node.js", - "dist/nodes/Gumroad/GumroadTrigger.node.js", - "dist/nodes/Harvest/Harvest.node.js", - "dist/nodes/HelpScout/HelpScout.node.js", - "dist/nodes/HelpScout/HelpScoutTrigger.node.js", - "dist/nodes/HtmlExtract/HtmlExtract.node.js", - "dist/nodes/HttpRequest.node.js", - "dist/nodes/Hubspot/Hubspot.node.js", - "dist/nodes/Hubspot/HubspotTrigger.node.js", - "dist/nodes/Hunter/Hunter.node.js", - "dist/nodes/If.node.js", - "dist/nodes/Intercom/Intercom.node.js", - "dist/nodes/Interval.node.js", - "dist/nodes/InvoiceNinja/InvoiceNinja.node.js", - "dist/nodes/InvoiceNinja/InvoiceNinjaTrigger.node.js", - "dist/nodes/Jira/Jira.node.js", - "dist/nodes/JotForm/JotFormTrigger.node.js", - "dist/nodes/Keap/Keap.node.js", - "dist/nodes/Keap/KeapTrigger.node.js", - "dist/nodes/LinkFish/LinkFish.node.js", - "dist/nodes/Mailchimp/Mailchimp.node.js", - "dist/nodes/Mailchimp/MailchimpTrigger.node.js", - "dist/nodes/Mailgun/Mailgun.node.js", - "dist/nodes/Mailjet/Mailjet.node.js", - "dist/nodes/Mailjet/MailjetTrigger.node.js", - "dist/nodes/Mandrill/Mandrill.node.js", - "dist/nodes/Mattermost/Mattermost.node.js", - "dist/nodes/Mautic/Mautic.node.js", - "dist/nodes/Mautic/MauticTrigger.node.js", - "dist/nodes/Merge.node.js", - "dist/nodes/Microsoft/Excel/MicrosoftExcel.node.js", - "dist/nodes/Microsoft/OneDrive/MicrosoftOneDrive.node.js", - "dist/nodes/MoveBinaryData.node.js", - "dist/nodes/Mocean/Mocean.node.js", - "dist/nodes/MondayCom/MondayCom.node.js", - "dist/nodes/MongoDb/MongoDb.node.js", - "dist/nodes/MoveBinaryData.node.js", - "dist/nodes/Msg91/Msg91.node.js", - "dist/nodes/MySql/MySql.node.js", - "dist/nodes/NextCloud/NextCloud.node.js", - "dist/nodes/NoOp.node.js", - "dist/nodes/OpenWeatherMap.node.js", - "dist/nodes/PagerDuty/PagerDuty.node.js", - "dist/nodes/PayPal/PayPal.node.js", - "dist/nodes/PayPal/PayPalTrigger.node.js", - "dist/nodes/Pipedrive/Pipedrive.node.js", - "dist/nodes/Pipedrive/PipedriveTrigger.node.js", - "dist/nodes/Postgres/Postgres.node.js", - "dist/nodes/ReadBinaryFile.node.js", - "dist/nodes/ReadBinaryFiles.node.js", - "dist/nodes/ReadPdf.node.js", - "dist/nodes/Redis/Redis.node.js", - "dist/nodes/RenameKeys.node.js", - "dist/nodes/Rocketchat/Rocketchat.node.js", - "dist/nodes/RssFeedRead.node.js", - "dist/nodes/Rundeck/Rundeck.node.js", - "dist/nodes/Salesforce/Salesforce.node.js", - "dist/nodes/Set.node.js", - "dist/nodes/Shopify/Shopify.node.js", - "dist/nodes/Shopify/ShopifyTrigger.node.js", - "dist/nodes/Slack/Slack.node.js", - "dist/nodes/Sms77/Sms77.node.js", - "dist/nodes/SplitInBatches.node.js", - "dist/nodes/SpreadsheetFile.node.js", - "dist/nodes/SseTrigger.node.js", - "dist/nodes/Start.node.js", - "dist/nodes/Stripe/StripeTrigger.node.js", - "dist/nodes/Switch.node.js", - "dist/nodes/Salesmate/Salesmate.node.js", - "dist/nodes/Segment/Segment.node.js", - "dist/nodes/SurveyMonkey/SurveyMonkeyTrigger.node.js", - "dist/nodes/Telegram/Telegram.node.js", - "dist/nodes/Telegram/TelegramTrigger.node.js", - "dist/nodes/Todoist/Todoist.node.js", - "dist/nodes/Toggl/TogglTrigger.node.js", - "dist/nodes/Trello/Trello.node.js", - "dist/nodes/Trello/TrelloTrigger.node.js", - "dist/nodes/Twilio/Twilio.node.js", - "dist/nodes/Twitter/Twitter.node.js", - "dist/nodes/Typeform/TypeformTrigger.node.js", - "dist/nodes/Uplead/Uplead.node.js", - "dist/nodes/Vero/Vero.node.js", - "dist/nodes/Webflow/WebflowTrigger.node.js", - "dist/nodes/Webhook.node.js", - "dist/nodes/Wordpress/Wordpress.node.js", - "dist/nodes/WooCommerce/WooCommerce.node.js", - "dist/nodes/WooCommerce/WooCommerceTrigger.node.js", - "dist/nodes/WriteBinaryFile.node.js", - "dist/nodes/Xml.node.js", - "dist/nodes/Zendesk/Zendesk.node.js", - "dist/nodes/Zendesk/ZendeskTrigger.node.js", - "dist/nodes/Zoho/ZohoCrm.node.js", - "dist/nodes/Zulip/Zulip.node.js" - ] -======= "nodes": [ "dist/nodes/ActiveCampaign/ActiveCampaign.node.js", "dist/nodes/ActiveCampaign/ActiveCampaignTrigger.node.js", @@ -644,7 +385,6 @@ "jest": { "transform": { "^.+\\.tsx?$": "ts-jest" ->>>>>>> master }, "testURL": "http://localhost/", "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",