Merge branch 'google-books' of https://github.com/RicardoE105/n8n into RicardoE105-google-books

This commit is contained in:
Tanay Pant 2020-11-04 13:12:14 +01:00
commit c950aea2c3
5 changed files with 686 additions and 0 deletions

View file

@ -0,0 +1,25 @@
import {
ICredentialType,
NodePropertyTypes,
} from 'n8n-workflow';
const scopes = [
'https://www.googleapis.com/auth/books',
];
export class GoogleBooksOAuth2Api implements ICredentialType {
name = 'googleBooksOAuth2Api';
extends = [
'googleOAuth2Api',
];
displayName = 'Google Books OAuth2 API';
documentationUrl = 'google';
properties = [
{
displayName: 'Scope',
name: 'scope',
type: 'hidden' as NodePropertyTypes,
default: scopes.join(' '),
},
];
}

View file

@ -0,0 +1,140 @@
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, headers: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
const authenticationMethod = this.getNodeParameter('authentication', 0, 'serviceAccount') as string;
const options: OptionsWithUri = {
headers: {
'Content-Type': 'application/json',
},
method,
body,
qs,
uri: uri || `https://www.googleapis.com/books/${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;
}
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}`;
console.log(options);
//@ts-ignore
return await this.helpers.request(options);
} else {
console.log(this.getCredentials('googleBooksOAuth2Api'));
//@ts-ignore
return await this.helpers.requestOAuth2.call(this, 'googleBooksOAuth2Api', options);
}
} catch (error) {
if (error.response && error.response.body && error.response.body.error) {
let errors;
if (error.response.body.error.errors) {
errors = error.response.body.error.errors;
errors = errors.map((e: IDataObject) => e.message).join('|');
} else {
errors = error.response.body.error.message;
}
// Try to return the error prettier
throw new Error(
`Google Books error response [${error.statusCode}]: ${errors}`
);
}
throw error;
}
}
export async function googleApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, propertyName: string, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
const returnData: IDataObject[] = [];
let responseData;
query.maxResults = 40;
do {
responseData = await googleApiRequest.call(this, method, endpoint, body, query);
returnData.push.apply(returnData, responseData[propertyName] || []);
} while (
returnData.length < responseData.totalItems
);
return returnData;
}
function getAccessToken(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, credentials: IDataObject): Promise<IDataObject> {
//https://developers.google.com/identity/protocols/oauth2/service-account#httprest
const scopes = [
'https://www.googleapis.com/auth/books',
];
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);
}

View file

@ -0,0 +1,482 @@
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
INodeExecutionData,
INodeType,
INodeTypeDescription,
} from 'n8n-workflow';
import {
googleApiRequest,
googleApiRequestAllItems,
} from './GenericFunctions';
export interface IGoogleAuthCredentials {
email: string;
privateKey: string;
}
export class GoogleBooks implements INodeType {
description: INodeTypeDescription = {
displayName: 'Google Books',
name: 'googleBooks',
icon: 'file:googlebooks.svg',
group: ['input', 'output'],
version: 1,
description: 'Read data from Google Books',
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
defaults: {
name: 'Google Books',
color: '#4198e6',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'googleApi',
required: true,
displayOptions: {
show: {
authentication: [
'serviceAccount',
],
},
},
},
{
name: 'googleBooksOAuth2Api',
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',
type: 'options',
options: [
{
name: 'Bookshelf',
value: 'bookshelf',
},
{
name: 'Bookshelf Volume',
value: 'bookshelfVolume',
},
{
name: 'Volume',
value: 'volume',
},
],
default: 'bookshelf',
description: 'The resource to operate on',
},
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Get',
value: 'get',
description: 'Retrieve a specific bookshelf resource for the specified user',
},
{
name: 'Get All',
value: 'getAll',
description: 'Get all public bookshelf resource for the specified user',
},
],
displayOptions: {
show: {
resource: [
'bookshelf',
],
},
},
default: 'get',
description: 'The operation to perform',
},
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Add',
value: 'add',
description: 'Add a volume to a bookshelf',
},
{
name: 'Clear',
value: 'clear',
description: 'Clears all volumes from a bookshelf',
},
{
name: 'Get All',
value: 'getAll',
description: 'Get all volumes in a specific bookshelf for the specified user',
},
{
name: 'Move',
value: 'move',
description: 'Moves a volume within a bookshelf',
},
{
name: 'Remove',
value: 'remove',
description: 'Removes a volume from a bookshelf',
},
],
displayOptions: {
show: {
resource: [
'bookshelfVolume',
],
},
},
default: 'getAll',
description: 'The operation to perform',
},
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Get',
value: 'get',
description: 'Get a volume resource based on ID',
},
{
name: 'Get All',
value: 'getAll',
description: 'Get all volumes filtered by query',
},
],
displayOptions: {
show: {
resource: [
'volume',
],
},
},
default: 'get',
description: 'The operation to perform',
},
{
displayName: 'My Library',
name: 'myLibrary',
type: 'boolean',
default: false,
required: true,
displayOptions: {
show: {
operation: [
'get',
'getAll',
],
resource: [
'bookshelf',
'bookshelfVolume'
],
},
},
},
// ----------------------------------
// All
// ----------------------------------
{
displayName: 'Search Query',
name: 'searchQuery',
type: 'string',
description: 'Full-text search query string',
default: '',
required: true,
displayOptions: {
show: {
operation: [
'getAll',
],
resource: [
'volume',
],
},
},
},
{
displayName: 'User ID',
name: 'userId',
type: 'string',
description: 'ID of user',
default: '',
required: true,
displayOptions: {
show: {
operation: [
'get',
'getAll',
],
resource: [
'bookshelf',
'bookshelfVolume',
],
},
hide: {
myLibrary: [
true,
],
},
},
},
{
displayName: 'Bookshelf ID',
name: 'shelfId',
type: 'string',
description: 'ID of the bookshelf',
default: '',
required: true,
displayOptions: {
show: {
operation: [
'get',
'add',
'clear',
'move',
'remove',
],
resource: [
'bookshelf',
'bookshelfVolume'
],
},
},
},
{
displayName: 'Volume ID',
name: 'volumeId',
type: 'string',
description: 'ID of the volume',
default: '',
required: true,
displayOptions: {
show: {
operation: [
'add',
'move',
'remove',
'get',
],
resource: [
'bookshelfVolume',
],
},
},
},
{
displayName: 'Volume Position',
name: 'volumePosition',
type: 'string',
description: 'Position on shelf to move the item (0 puts the item before the current first item, 1 puts it between the first and the second and so on) ',
default: '',
required: true,
displayOptions: {
show: {
operation: [
'move',
],
resource: [
'bookshelfVolume',
],
},
},
},
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
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: {
operation: [
'getAll',
],
returnAll: [
false,
],
},
},
typeOptions: {
minValue: 1,
maxValue: 40,
},
default: 40,
description: 'How many results to return.',
},
],
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const length = items.length as unknown as number;
const returnData: IDataObject[] = [];
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
const qs: IDataObject = {};
let responseData;
for (let i = 0; i < length; i++) {
if (resource === 'volume') {
if (operation === 'get') {
const volumeId = this.getNodeParameter('volumeId', i) as string;
responseData = await googleApiRequest.call(this, 'GET', `v1/volumes/${volumeId}`, {});
} else if (operation === 'getAll') {
const searchQuery = this.getNodeParameter('searchQuery', i) as string;
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
if (returnAll) {
responseData = await googleApiRequestAllItems.call(this, 'items', 'GET', `v1/volumes?q=${searchQuery}`, {});
} else {
qs.maxResults = this.getNodeParameter('limit', i) as number;
responseData = await googleApiRequest.call(this, 'GET', `v1/volumes?q=${searchQuery}`, {}, qs);
responseData = responseData.items || [];
}
}
}
if (resource === 'bookshelf') {
if (operation === 'get') {
const shelfId = this.getNodeParameter('shelfId', i) as string;
const myLibrary = this.getNodeParameter('myLibrary', i) as boolean;
let endpoint;
if (myLibrary === false) {
const userId = this.getNodeParameter('userId', i) as string;
endpoint = `v1/users/${userId}/bookshelves/${shelfId}`;
} else {
endpoint = `v1/mylibrary/bookshelves/${shelfId}`;
}
responseData = await googleApiRequest.call(this, 'GET', endpoint, {});
} else if (operation === 'getAll') {
const myLibrary = this.getNodeParameter('myLibrary', i) as boolean;
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
let endpoint;
if (myLibrary === false) {
const userId = this.getNodeParameter('userId', i) as string;
endpoint = `v1/users/${userId}/bookshelves`;
} else {
endpoint = `v1/mylibrary/bookshelves`;
}
if (returnAll) {
responseData = await googleApiRequestAllItems.call(this, 'items', 'GET', endpoint, {});
} else {
qs.maxResults = this.getNodeParameter('limit', i) as number;
responseData = await googleApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items || [];
}
}
}
if (resource === 'bookshelfVolume') {
if (operation === 'add') {
const shelfId = this.getNodeParameter('shelfId', i) as string;
const volumeId = this.getNodeParameter('volumeId', i) as string;
const body: IDataObject = {
volumeId,
};
responseData = await googleApiRequest.call(this, 'POST', `mylibrary/bookshelves/${shelfId}/addVolume`, body);
}
if (operation === 'clear') {
const shelfId = this.getNodeParameter('shelfId', i) as string;
responseData = await googleApiRequest.call(this, 'POST', `mylibrary/bookshelves/${shelfId}/clearVolumes`);
}
if (operation === 'getAll') {
const shelfId = this.getNodeParameter('shelfId', i) as string;
const returnAll = this.getNodeParameter('returnAll', i) as boolean;
const myLibrary = this.getNodeParameter('myLibrary', i) as boolean;
let endpoint;
if (myLibrary === false) {
const userId = this.getNodeParameter('userId', i) as string;
endpoint = `v1/users/${userId}/bookshelves/${shelfId}/volumes`;
} else {
endpoint = `v1/mylibrary/bookshelves/${shelfId}/volumes`;
}
if (returnAll) {
responseData = await googleApiRequestAllItems.call(this, 'items', 'GET', endpoint, {});
} else {
qs.maxResults = this.getNodeParameter('limit', i) as number;
responseData = await googleApiRequest.call(this, 'GET', endpoint, {}, qs);
responseData = responseData.items || [];
}
}
if (operation === 'move') {
const shelfId = this.getNodeParameter('shelfId', i) as string;
const volumeId = this.getNodeParameter('volumeId', i) as string;
const volumePosition = this.getNodeParameter('volumePosition', i) as number;
const body: IDataObject = {
volumeId,
volumePosition,
};
responseData = await googleApiRequest.call(this, 'POST', `mylibrary/bookshelves/${shelfId}/moveVolume`, body);
}
if (operation === 'move') {
const shelfId = this.getNodeParameter('shelfId', i) as string;
const volumeId = this.getNodeParameter('volumeId', i) as string;
const body: IDataObject = {
volumeId,
};
responseData = await googleApiRequest.call(this, 'POST', `mylibrary/bookshelves/${shelfId}/removeVolume`, body);
}
}
if (Array.isArray(responseData)) {
returnData.push.apply(returnData, responseData as IDataObject[]);
} else {
returnData.push(responseData as IDataObject);
}
}
return [this.helpers.returnJsonArray(responseData)];
}
}

View file

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generator: Adobe Illustrator 23.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="svg61" xmlns:x="http://ns.adobe.com/Extensibility/1.0/" xmlns:i="http://ns.adobe.com/AdobeIllustrator/10.0/" xmlns:graph="http://ns.adobe.com/Graphs/1.0/" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 448.7 500" enable-background="new 0 0 448.7 500" xml:space="preserve">
<metadata id="metadata58">
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
</cc:Work>
</rdf:RDF>
<sfw xmlns="http://ns.adobe.com/SaveForWeb/1.0/">
<slices/>
<sliceSourceBounds bottomLeftOrigin="true" height="500" width="448.7" x="3451.9" y="3846"/>
</sfw>
</metadata>
<g>
<path fill="#0B5E9F" d="M428.2,221.9L49.2,6.5C33-2.6,18.5-1.7,9.7,6.8l0,0C3.4,12.8,0,22.4,0,34.9v429.9C0,477.4,3.7,487,9.7,493 l0,0c9.1,8.8,23.3,9.7,39.5,0.3l379.1-215.4C455.5,262.5,455.5,237.5,428.2,221.9z"/>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="223.1684" y1="7682.2407" x2="223.1684" y2="8182.2686" gradientTransform="matrix(0.9998 0 0 -0.9998 1.2134 8180.7046)">
<stop offset="0" style="stop-color:#FFFFFF;stop-opacity:0"/>
<stop offset="1" style="stop-color:#FFFFFF;stop-opacity:0.1"/>
</linearGradient>
<path fill-rule="evenodd" clip-rule="evenodd" fill="url(#SVGID_1_)" d="M428.3,221.9l-95-54l-1.7-1.1l-0.1,0.1L49.2,6.6 c-15.7-9-29.9-8.3-38.9-0.2L8.8,7.7C3.2,13.7,0,23,0,35.1v429.7c0,12.1,3.2,21.4,9.1,27.2l0,0l-0.2,0.2c8.9,9.5,23.7,10.6,40.4,1.3 l282.2-160.5l0.1,0.1c0,0,1.7-1.1,1.8-1.1l95-54C455.5,262.5,455.5,237.2,428.3,221.9z"/>
<path opacity="0.25" fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" enable-background="new " d="M49.2,9.4l379,215.3 c12.3,6.9,19.2,16,20.3,25.3c0-10.1-6.7-20.3-20.3-28.1L49.2,6.6C22-9,0,4,0,35.1v2.8C0,6.8,22-5.9,49.2,9.4z"/>
<path fill="#40DCFF" d="M358.2,70.2H135.9V444l242.9-138V90.9C378.8,79.5,369.6,70.2,358.2,70.2z"/>
<linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="7121.7529" y1="-324.192" x2="7123.5923" y2="-327.4978" gradientTransform="matrix(38.316 0 0 -36.19 -272599.25 -11433.2002)">
<stop offset="0" style="stop-color:#5B7C8C;stop-opacity:0"/>
<stop offset="1" style="stop-color:#5B7C8C;stop-opacity:0.4"/>
</linearGradient>
<path fill="url(#SVGID_2_)" d="M358.2,70.2H135.9v373.6l242.9-137.9V90.9C378.8,79.5,369.6,70.2,358.2,70.2z"/>
<polygon fill="#009BF0" points="135.9,70.2 70.3,70.2 70.3,481.2 135.9,444 "/>
<path opacity="0.15" fill="#FFFFFF" enable-background="new " d="M358.2,70.2H70.3v2.3h287.9c11.4,0,20.7,6.9,20.7,18.3l0,0 C378.8,79.5,369.6,70.2,358.2,70.2z"/>
<polygon fill="#FAFAFA" points="261.1,173.3 294.9,152.4 329.9,173.3 329.9,70.2 261.1,70.2 "/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

View file

@ -76,6 +76,7 @@
"dist/credentials/GitlabOAuth2Api.credentials.js",
"dist/credentials/GmailOAuth2Api.credentials.js",
"dist/credentials/GoogleApi.credentials.js",
"dist/credentials/GoogleBooksOAuth2Api.credentials.js",
"dist/credentials/GoogleCalendarOAuth2Api.credentials.js",
"dist/credentials/GoogleContactsOAuth2Api.credentials.js",
"dist/credentials/GoogleDriveOAuth2Api.credentials.js",
@ -273,6 +274,7 @@
"dist/nodes/Github/GithubTrigger.node.js",
"dist/nodes/Gitlab/Gitlab.node.js",
"dist/nodes/Gitlab/GitlabTrigger.node.js",
"dist/nodes/Google/Books/GoogleBooks.node.js",
"dist/nodes/Google/Calendar/GoogleCalendar.node.js",
"dist/nodes/Google/Contacts/GoogleContacts.node.js",
"dist/nodes/Google/Drive/GoogleDrive.node.js",