Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added port #135

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 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, token, options = {}) {
async function _get_recent_email(credentials, token, options = {}, port = 32019) {
const emails = [];

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

async function __check_inbox(credentials, token, options = {}) {
async function __check_inbox(credentials, token, options = {}, port = 32019) {
const { subject, from, to, wait_time_sec, max_wait_time_sec } = options;
try {
console.log(
Expand All @@ -108,7 +108,8 @@ async function __check_inbox(credentials, token, options = {}) {
const emails = await _get_recent_email(
credentials,
token,
options
options,
port
);
if (emails.length > 0) {
console.log(`[gmail] Found!`);
Expand Down Expand Up @@ -147,6 +148,7 @@ async function __check_inbox(credentials, token, options = {}) {
* @param {number} [options.wait_time_sec] - Interval between inbox checks (in seconds). Default: 30 seconds.
* @param {number} [options.max_wait_time_sec] - Maximum wait time (in seconds). When reached and the email was not found, the script exits. Default: 60 seconds.
* @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
* @param {number} [port] - Optional port option, in case the default port (32019) is unavailable.
*/
async function check_inbox(
credentials,
Expand All @@ -159,15 +161,16 @@ async function check_inbox(
max_wait_time_sec: 30,
include_body: false,
label: "INBOX"
}
},
port = 32019
) {
if (typeof options !== "object") {
console.error(
"[gmail-tester] This functionality is obsolete! Please pass all params of check_inbox() in options object."
);
process.exit(1);
}
return __check_inbox(credentials, token, options);
return __check_inbox(credentials, token, options, port);
}

/**
Expand All @@ -182,10 +185,11 @@ async function check_inbox(
* @param {string} options.subject - Filter on the subject of the email.
* @param {Object} options.before - Date. Filter messages received _after_ the specified date.
* @param {Object} options.after - Date. Filter messages received _before_ the specified date.
* @param {number} [port] - Optional port option, in case the default port (32019) is unavailable.
*/
async function get_messages(credentials, token, options) {
async function get_messages(credentials, token, options, port = 32019) {
try {
return await _get_recent_email(credentials, token, options);
return await _get_recent_email(credentials, token, options, port = 32019);
} catch (err) {
console.log("[gmail] Error:", err);
}
Expand All @@ -196,9 +200,10 @@ async function get_messages(credentials, token, options) {
*
* @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 {number} [port] - Optional port option, in case the default port (32019) is unavailable.
*/
async function refresh_access_token(credentials, token) {
const oAuth2Client = await gmail.authorize(credentials, token);
async function refresh_access_token(credentials, token, port = 32019) {
const oAuth2Client = await gmail.authorize(credentials, token, port = 32019);
const refresh_token_result = await oAuth2Client.refreshToken(
oAuth2Client.credentials.refresh_token
);
Expand Down
11 changes: 7 additions & 4 deletions gmail.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ const SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"];
* given callback function.
* @param {string | Object} credentials The authorization client credentials.
* @param {string | Object} token Token.
* @param {number} [port] - Optional port option, in case the default port (32019) is unavailable.
* @return {google.auth.OAuth2} The OAuth2Client.
*/
async function authorize(credentials, token) {
async function authorize(credentials, token, port = 32019) {
const { client_secret, client_id, redirect_uris } =
_get_credentials_object(credentials).installed;
const oAuth2Client = new google.auth.OAuth2(
Expand All @@ -27,7 +28,7 @@ async function authorize(credentials, token) {
oAuth2Client.setCredentials(_get_token_object(token));
return oAuth2Client;
} catch (error) {
const newOAuth2Client = await get_new_token(oAuth2Client, token);
const newOAuth2Client = await get_new_token(oAuth2Client, token, port = 32019);
if (token instanceof Object) {
tokenStore.store(newOAuth2Client.credentials);
} else {
Expand All @@ -41,10 +42,12 @@ async function authorize(credentials, token) {
* Get a new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {string | Object} token Token.
* @param {number} [port] - Optional port option, in case the default port (32019) is unavailable.
* @return {Promise<google.auth.OAuth2>} The promise for the authorized client.
*/
async function get_new_token(oAuth2Client, token) {
return authenticate(oAuth2Client, SCOPES, token);
async function get_new_token(oAuth2Client, token, port = 32019) {
return authenticate(oAuth2Client, SCOPES, token, port);
}

/**
Expand Down
14 changes: 9 additions & 5 deletions libs/oauth2.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,27 @@ if (fs.existsSync(keyPath)) {
/**
* Open an http server to accept the oauth callback. In this simple example, the only request to our webserver is to /callback?code=<code>
*/
async function authenticate(oauth2Client, scopes, tokensFile) {
async function authenticate(oauth2Client, scopes, tokensFile, port = 80) {
return new Promise((resolve, reject) => {
// grab the url that will be used for authorization
if (!fs.existsSync(tokensFile)) {
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: scopes.join(" ")
scope: scopes.join(" "),
redirect_uri: `http://localhost:${port}`
});
console.log(`Authorize this app by visiting this url: ${authorizeUrl}`);
const server = http
.createServer(async (req, res) => {
try {
if (req.url.indexOf("/") > -1) {
const qs = new url.URL(req.url, "http://localhost:80").searchParams;
const qs = new url.URL(req.url, `http://localhost:${port}`).searchParams;
res.end("Authentication successful! Please return to the console.");
server.destroy();
const { tokens } = await oauth2Client.getToken(qs.get("code"));
const { tokens } = await oauth2Client.getToken({
code: qs.get("code"),
redirect_uri: `http://localhost:${port}`
});
fs.writeFileSync(tokensFile, JSON.stringify(tokens, null, 2));
oauth2Client.credentials = tokens; // eslint-disable-line require-atomic-updates
resolve(oauth2Client);
Expand All @@ -57,7 +61,7 @@ async function authenticate(oauth2Client, scopes, tokensFile) {
reject(e);
}
})
.listen(80, () => {
.listen(port, () => {
// open the browser to the authorize url to start the workflow
opn(authorizeUrl, { wait: false }).then(cp => cp.unref());
});
Expand Down