Oauth1 support and Twitter node

This commit is contained in:
ricardo
2020-06-01 20:42:38 -04:00
parent f1f09d4a03
commit af3d799e5c
26 changed files with 822 additions and 43 deletions

View File

@@ -0,0 +1,44 @@
import {
OptionsWithUrl,
} from 'request';
import {
IHookFunctions,
IExecuteFunctions,
IExecuteSingleFunctions,
ILoadOptionsFunctions,
} from 'n8n-core';
import {
IDataObject,
} from 'n8n-workflow';
export async function twitterApiRequest(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions | IHookFunctions, method: string, resource: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
let options: OptionsWithUrl = {
method,
body,
qs,
url: uri || `https://api.twitter.com/1.1${resource}`,
json: true
};
try {
if (Object.keys(option).length !== 0) {
options = Object.assign({}, options, option);
}
if (Object.keys(body).length === 0) {
delete options.body;
}
//@ts-ignore
return await this.helpers.requestOAuth1.call(this, 'twitterOAuth1Api', options);
} catch (error) {
if (error.response && error.response.body && error.response.body.errors) {
// Try to return the error prettier
const errorMessages = error.response.body.errors.map((error: IDataObject) => {
return error.message;
});
throw new Error(`Twitter error response [${error.statusCode}]: ${errorMessages.join(' | ')}`);
}
throw error;
}
}

View File

@@ -0,0 +1,208 @@
import {
INodeProperties,
} from 'n8n-workflow';
export const tweetOperations = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
displayOptions: {
show: {
resource: [
'tweet',
],
},
},
options: [
{
name: 'Create',
value: 'create',
description: 'Create a new tweet',
},
],
default: 'create',
description: 'The operation to perform.',
},
] as INodeProperties[];
export const tweetFields = [
/* -------------------------------------------------------------------------- */
/* tweet:create */
/* -------------------------------------------------------------------------- */
{
displayName: 'Text',
name: 'text',
type: 'string',
typeOptions: {
alwaysOpenEditWindow: true,
},
required: true,
default: '',
displayOptions: {
show: {
operation: [
'create',
],
resource: [
'tweet',
],
},
},
description: 'The text of the status update. URL encode as necessary. t.co link wrapping will affect character counts. ',
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
operation: [
'create',
],
resource: [
'tweet',
],
},
},
options: [
{
displayName: 'Attachments',
name: 'attachmentsUi',
placeholder: 'Add Attachments',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
options: [
{
name: 'attachmentsValues',
displayName: 'Attachments Values',
values: [
{
displayName: 'Data',
name: 'data',
type: 'string',
default: '',
description: 'The base64-encoded file content being uploaded.',
},
{
displayName: 'Category',
name: 'category',
type: 'options',
options: [
{
name: 'Amplify Video',
value: 'amplifyVideo',
},
{
name: 'Gif',
value: 'tweetGif',
},
{
name: 'Image',
value: 'tweetImage',
},
{
name: 'Video',
value: 'tweetVideo',
},
],
default: '',
description: 'The category that represents how the media will be used',
},
],
},
{
name: 'attachmentsBinary',
displayName: 'Attachments Binary',
values: [
{
displayName: 'Property',
name: 'property',
type: 'string',
default: '',
description: 'Name of the binary properties which contain data which should be added to email as attachment',
},
{
displayName: 'Category',
name: 'category',
type: 'options',
options: [
{
name: 'Amplify Video',
value: 'amplifyVideo',
},
{
name: 'Gif',
value: 'tweetGif',
},
{
name: 'Image',
value: 'tweetImage',
},
{
name: 'Video',
value: 'tweetVideo',
},
],
default: '',
description: 'The category that represents how the media will be used',
},
],
},
],
default: '',
description: 'Array of supported attachments to add to the message.',
},
{
displayName: 'Display Coordinates',
name: 'displayCoordinates',
type: 'boolean',
default: false,
description: 'Whether or not to put a pin on the exact coordinates a Tweet has been sent from.',
},
{
displayName: 'Location',
name: 'locationFieldsUi',
type: 'fixedCollection',
placeholder: 'Add Location',
default: {},
description: `Subscriber location information.n`,
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: 'Possibly Sensitive',
name: 'possiblySensitive',
type: 'boolean',
default: false,
description: 'If you upload Tweet media that might be considered sensitive content such as nudity, or medical procedures, you must set this value to true.',
},
]
},
] as INodeProperties[];

View File

@@ -0,0 +1,8 @@
export interface ITweet {
display_coordinates?: boolean;
lat?: number;
long?: number;
media_ids?: string;
possibly_sensitive?: boolean;
status: string;
}

View File

@@ -0,0 +1,151 @@
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IBinaryKeyData,
IDataObject,
INodeExecutionData,
INodeType,
INodeTypeDescription,
} from 'n8n-workflow';
import {
tweetFields,
tweetOperations,
} from './TweetDescription';
import {
twitterApiRequest,
} from './GenericFunctions';
import {
ITweet,
} from './TweetInterface';
import {
snakeCase,
} from 'change-case';
export class Twitter implements INodeType {
description: INodeTypeDescription = {
displayName: 'Twitter ',
name: 'twitter',
icon: 'file:twitter.png',
group: ['input', 'output'],
version: 1,
description: 'Consume Twitter API',
subtitle: '={{$parameter["operation"] + ":" + $parameter["resource"]}}',
defaults: {
name: 'Twitter',
color: '#1DA1F2',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'twitterOAuth1Api',
required: true,
}
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Tweet',
value: 'tweet',
},
],
default: 'tweet',
description: 'The resource to operate on.',
},
// TWEET
...tweetOperations,
...tweetFields,
],
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
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 === 'tweet') {
//https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
if (operation === 'create') {
const text = this.getNodeParameter('text', i) as string;
const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: ITweet = {
status: text,
};
if (additionalFields.attachmentsUi) {
const mediaIds = [];
const attachmentsUi = additionalFields.attachmentsUi as IDataObject;
const uploadUri = 'https://upload.twitter.com/1.1/media/upload.json';
if (attachmentsUi.attachmentsValues) {
const attachtments = attachmentsUi.attachmentsValues as IDataObject[];
for (const attachment of attachtments) {
const body = {
media_data: attachment.data,
media_category: snakeCase(attachment.category as string).toUpperCase(),
};
const response = await twitterApiRequest.call(this, 'POST', '', body, {}, uploadUri);
mediaIds.push(response.media_id);
}
}
if (attachmentsUi.attachmentsBinary) {
const attachtments = attachmentsUi.attachmentsBinary as IDataObject[];
for (const attachment of attachtments) {
const binaryData = items[i].binary as IBinaryKeyData;
const propertyName = attachment.property as string;
if (binaryData === undefined) {
throw new Error('No binary data set. So file can not be written!');
}
if (!binaryData[propertyName]) {
continue;
}
const body = {
media_data: binaryData[propertyName].data,
media_category: snakeCase(attachment.category as string).toUpperCase(),
};
const response = await twitterApiRequest.call(this, 'POST', '', body, {}, uploadUri);
mediaIds.push(response.media_id_string);
}
}
body.media_ids = mediaIds.join(',');
}
if (additionalFields.possiblySensitive) {
body.possibly_sensitive = additionalFields.possibly_sensitive as boolean;
}
if (additionalFields.locationFieldsUi) {
const locationUi = additionalFields.locationFieldsUi as IDataObject;
if (locationUi.locationFieldsValues) {
const values = locationUi.locationFieldsValues as IDataObject;
body.lat = parseFloat(values.lalatitude as string);
body.long = parseFloat(values.lalatitude as string);
}
}
responseData = await twitterApiRequest.call(this, 'POST', '/statuses/update.json', body);
}
}
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)];
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB