Skip to content

Commit

Permalink
Merge pull request #89 from MatteoMolinari93/feature/accept_objects_a…
Browse files Browse the repository at this point in the history
…nd_paths_to_files

Feature/accept objects and paths to files
  • Loading branch information
levz0r authored Jun 3, 2022
2 parents 01a2951 + 037079e commit ca5de7c
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 26 deletions.
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ Congratulations! `gmail-tester` is ready to use.

# API

### `get_messages(credentials_path, token_path, options)`
### `get_messages(credentials, token, options)`

`credentials_path`: Path to credentials JSON file.<br>
`token_path`: Path to OAuth2 token file.<br>
`credentials`: Path to credentials JSON file or JSON Object.<br>
`token`: Path to OAuth2 token file or JSON Object.<br>
`options`: <br>

- `from`: String. Filter on the email address of the receiver.
Expand Down Expand Up @@ -111,10 +111,10 @@ An array of `email` objects with the following fields:<br>

_Some senders will send you `text/html` content, the others will send you `plain/text`, and some will send you both. Make sure you are looking for the content in the right body field._

### `check_inbox(credentials_path, token_path, options = {})`
### `check_inbox(credentials, token, options = {})`

`credentials_path`: Path to credentials JSON file.<br>
`token_path`: Path to OAuth2 token file.<br>
`credentials`: Path to credentials JSON file or JSON Object.<br>
`token`: Path to OAuth2 token file or JSON Object.<br>
`options`: <br>

- `from`: String. Filter on the email address of the receiver.
Expand Down
28 changes: 14 additions & 14 deletions gmail-tester.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ function _init_query(options) {
return query;
}

async function _get_recent_email(credentials_path, token_path, options = {}) {
async function _get_recent_email(credentials, token, options = {}) {
const emails = [];

const query = _init_query(options);
// Load client secrets from a local file.
const oAuth2Client = await gmail.authorize(credentials_path, token_path);
const oAuth2Client = await gmail.authorize(credentials, token);
const gmail_emails = await gmail.get_recent_email(
oAuth2Client,
query,
Expand Down Expand Up @@ -96,7 +96,7 @@ async function _get_recent_email(credentials_path, token_path, options = {}) {
return emails;
}

async function __check_inbox(credentials_path, token_path, options = {}) {
async function __check_inbox(credentials, token, options = {}) {
const { subject, from, to, wait_time_sec, max_wait_time_sec } = options;
try {
console.log(
Expand All @@ -106,8 +106,8 @@ async function __check_inbox(credentials_path, token_path, options = {}) {
let done_waiting_time = 0;
do {
const emails = await _get_recent_email(
credentials_path,
token_path,
credentials,
token,
options
);
if (emails.length > 0) {
Expand Down Expand Up @@ -135,8 +135,8 @@ async function __check_inbox(credentials_path, token_path, options = {}) {
/**
* Poll inbox.
*
* @param {string} credentials_path - Path to credentials json file.
* @param {string} token_path - Path to token json file.
* @param {string | Object} credentials - Path to credentials json file or credentials Object.
* @param {string | Object} token - Path to token json file or token Object.
* @param {CheckInboxOptions} [options]
* @param {boolean} [options.include_body] - Set to `true` to fetch decoded email bodies.
* @param {string} [options.from] - Filter on the email address of the receiver.
Expand All @@ -149,8 +149,8 @@ async function __check_inbox(credentials_path, token_path, options = {}) {
* @param {string} [options.label] - String. The default label is 'INBOX', but can be changed to 'SPAM', 'TRASH' or a custom label. For a full list of built-in labels, see https://developers.google.com/gmail/api/guides/labels?hl=en
*/
async function check_inbox(
credentials_path,
token_path,
credentials,
token,
options = {
subject: undefined,
from: undefined,
Expand All @@ -167,14 +167,14 @@ async function check_inbox(
);
process.exit(1);
}
return __check_inbox(credentials_path, token_path, options);
return __check_inbox(credentials, token, options);
}

/**
* Get an array of messages
*
* @param {string} credentials_path - Path to credentials json file.
* @param {string} token_path - Path to token json file.
* @param {string | Object} credentials - Path to credentials json file or credentials Object.
* @param {string | Object} token - Path to token json file or token Object.
* @param {GetMessagesOptions} options
* @param {boolean} options.include_body - Return message body string.
* @param {string} options.from - Filter on the email address of the receiver.
Expand All @@ -183,9 +183,9 @@ async function check_inbox(
* @param {Object} options.before - Date. Filter messages received _after_ the specified date.
* @param {Object} options.after - Date. Filter messages received _before_ the specified date.
*/
async function get_messages(credentials_path, token_path, options) {
async function get_messages(credentials, token, options) {
try {
return await _get_recent_email(credentials_path, token_path, options);
return await _get_recent_email(credentials, token, options);
} catch (err) {
console.log("[gmail] Error:", err);
}
Expand Down
26 changes: 20 additions & 6 deletions gmail.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,28 @@ const SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"];
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {string} credentials_path The authorization client credentials.
* @param {string} token_path Path to token json file.
* @param {string | Object} credentials The authorization client credentials.
* @param {string | Object} token Token.
* @return {google.auth.OAuth2} The OAuth2Client.
*/
async function authorize(credentials_path, token_path) {
const { client_secret, client_id, redirect_uris } = _get_credentials_object(credentials_path).installed;
async function authorize(credentials, token) {
const { client_secret, client_id, redirect_uris } = _get_credentials_object(credentials).installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
// Check if we have previously stored a token.
try {
oAuth2Client.setCredentials(tokenStore.get(token_path));
oAuth2Client.setCredentials(_get_token_object(token));
return oAuth2Client;
} catch (error) {
const newOAuth2Client = await get_new_token(oAuth2Client);
tokenStore.store(newOAuth2Client.credentials, token_path);
if(token instanceof Object) {
tokenStore.store(newOAuth2Client.credentials);
} else {
tokenStore.store(newOAuth2Client.credentials, token);
}
return newOAuth2Client;
}
}
Expand Down Expand Up @@ -223,9 +227,19 @@ function _gmail_client(oAuth2Client) {
}

function _get_credentials_object(credentials) {
if(credentials instanceof Object){
return credentials;
}
return JSON.parse(fs.readFileSync(credentials));
}

function _get_token_object(token) {
if(token instanceof Object){
return token;
}
return tokenStore.get(token)
}

module.exports = {
authorize,
get_recent_email,
Expand Down
42 changes: 42 additions & 0 deletions spec/gmail.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const gmail = require('../gmail');
const tokenStore = require('../token-store');

const { google } = require('googleapis');

const fs = require('fs');

describe('Gmail', () => {

it('authorize works with file paths', () => {
const cred_file = '{"installed":{"client_secret":"client_secret","client_id":"client_id","redirect_uris":["redirect_uris"]}}';
spyOn(fs, 'readFileSync').and.returnValue(Buffer.alloc(cred_file.length, cred_file));
spyOn(tokenStore, 'get').and.returnValue('tokenfile');

const oAuth2Spy = jasmine.createSpyObj('oAuth2', ['setCredentials'])
spyOn(google.auth, 'OAuth2').and.returnValue(oAuth2Spy);

const result = gmail.authorize('cred_path', 'token_path');

expect(fs.readFileSync).toHaveBeenCalledOnceWith('cred_path');
expect(tokenStore.get).toHaveBeenCalledOnceWith('token_path');
expect(result).not.toBeNull();
expect(oAuth2Spy.setCredentials).toHaveBeenCalledOnceWith('tokenfile');
});

it('authorize works with json objects', () => {
const cred_obj = {"installed":{"client_secret":"client_secret","client_id":"client_id","redirect_uris":["redirect_uris"]}};
spyOn(fs, 'readFileSync');
spyOn(tokenStore, 'get');

const oAuth2Spy = jasmine.createSpyObj('oAuth2', ['setCredentials'])
spyOn(google.auth, 'OAuth2').and.returnValue(oAuth2Spy);

const result = gmail.authorize(cred_obj, {myObj: true});

expect(fs.readFileSync).not.toHaveBeenCalled();
expect(tokenStore.get).not.toHaveBeenCalled();
expect(result).not.toBeNull();
expect(oAuth2Spy.setCredentials).toHaveBeenCalledOnceWith({myObj: true});
});

});

0 comments on commit ca5de7c

Please sign in to comment.