This code fetches contacts from Google Contacts using the Google People API and provides a way to search for specific contacts by name or email address.
npm run import -- "list google contact"
var google = require('googleapis');
var people = google.people('v1');
var importer = require('../Core');
var getOauthClient = importer.import("import google calendar api");
var options = {
scopes: [
'https://www.googleapis.com/auth/contacts'
]
};
function findMatch(arr, contact) {
return arr.filter(c => (
typeof c.names !== 'undefined'
&& typeof contact.displayName !== 'undefined'
&& c.names.filter(n => n.displayName.match(new RegExp(contact.displayName, 'ig'))).length > 0)
|| (
typeof c.emailAddresses !== 'undefined'
&& typeof contact.emailAddress !== 'undefined'
&& c.emailAddresses.filter(e => e.value.match(new RegExp(contact.emailAddress, 'ig'))).length > 0)
);
}
function googlePromise(func) {
return new Promise((resolve, reject) => func((err, response) => {
if (err) reject(err);
try {
} catch (e) {
reject(e);
}
setTimeout(() => resolve(response), 100);
})).catch(e => console.log(e));
};
var contactCache = [];
function listContacts(contact, done = false) {
// return matching contacts or empty if there are no more pages
return googlePromise(
people.people.connections.list.bind(people.people.connections, {
resourceName: 'people/me',
personFields: 'emailAddresses,names,birthdays,phoneNumbers,memberships',
auth: options.auth,
pageToken: options.pageToken
}))
.then(r => {
options.pageToken = r.nextPageToken;
done = !options.pageToken;
return r.connections;
})
.then(r => {
for (var c of r) {
contactCache.push(c);
}
if (done) {
return findMatch(contactCache, contact);
}
return listContacts(contact, done);
})
.catch(e => console.log(e))
};
function getContacts(contact) {
return getOauthClient(options)
.then(() => {
if (contactCache.length > 0) {
return findMatch(contactCache, contact);
}
options.nextPageToken = null;
contactCache = [];
return listContacts(contact);
})
.catch(e => console.log(e))
};
module.exports = getContacts;
const { google } = require('googleapis');
const people = google.people('v1');
const { importOauthClient } = require('../Core');
/**
* Function to find matching contacts in the cache or in the Google People API.
* @param {Object} contact - Contact data to search for in the API.
* @returns {Promise<Array>} - Array of matching contacts.
*/
async function findMatch(contact) {
const matches = contactCache.filter(c => (
c.names.some(n => n.displayName.match(new RegExp(contact.displayName, 'ig')))
|| c.emailAddresses.some(e => e.value.match(new RegExp(contact.emailAddress, 'ig')))
));
return matches;
}
/**
* Google API promise helper to delay and catch errors.
* @param {Function} func - Function to be executed and wrapped in a promise.
* @param {Number} delay - Time to delay the resolution of the promise.
* @returns {Promise} - Wrapped promise with error catching and delay.
*/
function googlePromise(func, delay = 100) {
return new Promise((resolve, reject) => {
func((err, response) => {
if (err) reject(err);
resolve(response);
});
}).catch(e => console.log(e));
};
let contactCache = [];
/**
* Recursively list contacts in the Google People API.
* @param {Object} options - Options object containing auth and pageToken.
* @returns {Promise<Array>} - Array of matching contacts.
*/
async function listContacts(options) {
try {
const response = await people.people.connections.list({
resourceName: 'people/me',
personFields: 'emailAddresses,names,birthdays,phoneNumbers,memberships',
auth: options.auth,
pageToken: options.pageToken
});
if (response.data.connections.length === 0) {
return [];
}
contactCache.push(...response.data.connections);
options.pageToken = response.data.nextPageToken;
if (!options.pageToken) {
// If no more pages, clear the cache and return the matches
contactCache = [];
return await findMatch(contactCache);
}
// Otherwise, recursively list the next page
return await listContacts(options);
} catch (e) {
console.log(e);
return [];
}
};
/**
* Get contacts for a given contact.
* @param {Object} contact - Contact data to search for in the API.
* @returns {Promise<Array>} - Array of matching contacts.
*/
async function getContacts(contact) {
try {
const oauthClient = await importOauthClient();
const options = {
auth: oauthClient,
nextPageToken: null
};
contactCache = []; // Clear cache on each call
return await listContacts(options);
} catch (e) {
console.log(e);
return [];
}
};
module.exports = getContacts;
This code snippet fetches and processes contacts from Google Contacts using the Google People API.
Here's a breakdown:
Dependencies:
googleapis
library for interacting with Google APIs.getOauthClient
from ../Core
to handle OAuth 2.0 authentication.findMatch
Function:
googlePromise
Function:
contactCache
:
listContacts
Function:
people.people.connections.list
method to retrieve contacts.contactCache
.findMatch
to find matching contacts based on the provided search criteria.getContacts
Function:
getOauthClient
to obtain an authenticated API client and then listContacts
to retrieve the contacts.Purpose:
This code snippet provides a way to search for contacts in Google Contacts based on their display name or email address. It uses the Google People API, handles authentication, and caches results for efficiency.