Skip to content
Merged
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
1 change: 1 addition & 0 deletions connectors/gmail/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@
"lint": "plot lint"
},
"dependencies": {
"@plotday/connector-google-contacts": "workspace:^",
"@plotday/twister": "workspace:^"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions connectors/gmail/src/gmail-api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,6 +4,7 @@ import type {
NewContact,
} from "@plotday/twister/plot";


export type GmailLabel = {
id: string;
name: string;
Expand Down
54 changes: 51 additions & 3 deletions connectors/gmail/src/gmail.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,10 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network, type WebhookRequest } from "@plotday/twister/tools/network";

import {
GOOGLE_PEOPLE_SCOPES,
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";

import {
GmailApi,
Expand DownExpand Up@@ -58,7 +62,14 @@ export class Gmail extends Connector<Gmail> {
static readonly SCOPES = ["https://www.googleapis.com/auth/gmail.modify"];

readonly provider = AuthProvider.Google;
readonly scopes = Gmail.SCOPES;
// Merge in People API scopes so we can enrich email-only contacts (Gmail
// headers carry name + address but no avatar) with photos from the user's
// Google Contacts and "other contacts" — without requiring the separate
// Google Contacts connector to be installed.
readonly scopes = Integrations.MergeScopes(
Gmail.SCOPES,
GOOGLE_PEOPLE_SCOPES,
);
readonly linkTypes = [
{
type: "email",
Expand DownExpand Up@@ -430,11 +441,48 @@ export class Gmail extends Connector<Gmail> {
channelId: string,
initialSync: boolean
): Promise<void> {
// Pre-build all plot threads, then enrich every contact email across the
// batch in one People API pass. Gmail headers don't carry avatars, so
// without this every email-only contact lands with `avatar = undefined`
// and shows initials forever.
const transformed: { thread: GmailThread; plot: ReturnType<typeof transformGmailThread> }[] = [];
const allEmails = new Set<string>();
for (const thread of threads) {
const plot = transformGmailThread(thread);
if (!plot.notes || plot.notes.length === 0) continue;
transformed.push({ thread, plot });
for (const c of plot.accessContacts ?? []) {
if (c && typeof c === "object" && "email" in c && c.email) allEmails.add(c.email);
}
for (const note of plot.notes) {
const author = (note as { author?: { email?: string } }).author;
if (author?.email) allEmails.add(author.email);
const noteContacts = (note as { accessContacts?: Array<{ email?: string }> }).accessContacts;
for (const c of noteContacts ?? []) {
if (c?.email) allEmails.add(c.email);
}
}
}

if (allEmails.size > 0) {
try {
// Transform Gmail thread to NewLinkWithNotes
const plotThread = transformGmailThread(thread);
const token = await this.tools.integrations.get(channelId);
if (token) {
await enrichLinkContactsFromGoogle(
transformed.map((t) => t.plot),
token.token,
token.scopes,
);
}
} catch (err) {
// Enrichment is best-effort — Gravatar fallback in the client still
// covers anyone the People API doesn't return.
console.warn("Failed to enrich Gmail contacts (non-blocking):", err);
}
}

for (const { thread, plot: plotThread } of transformed) {
try {
if (!plotThread.notes || plotThread.notes.length === 0) continue;

// Filter out notes for messages we sent (dedup)
Expand Down
22 changes: 21 additions & 1 deletion connectors/google-calendar/src/google-calendar.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
import GoogleContacts from "@plotday/connector-google-contacts";
import GoogleContacts, {
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";
import {
type Action,
ActionType,
Expand DownExpand Up@@ -1019,6 +1021,24 @@ export class GoogleCalendar extends Connector<GoogleCalendar> {
// recurring meetings) into a single cross-runtime call.
const batch = Array.from(linksBySource.values());
if (batch.length > 0) {
// Enrich attendee/organizer contacts with names + avatars from the
// user's Google Contacts and "other contacts". Calendar already
// merges GoogleContacts.SCOPES into its scopes, so the People API
// is reachable without a separate connector install.
try {
const token = await this.tools.integrations.get(calendarId);
if (token) {
await enrichLinkContactsFromGoogle(batch, token.token, token.scopes);
}
} catch (err) {
// Best-effort — Gravatar fallback in the client still covers
// anyone the People API doesn't return.
console.warn(
"Failed to enrich Google Calendar contacts (non-blocking):",
err
);
}

await this.tools.integrations.saveLinks(batch);
}
}
Expand Down
244 changes: 7 additions & 237 deletions connectors/google-contacts/src/google-contacts.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,239 +12,12 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network } from "@plotday/twister/tools/network";

type ContactTokens = {
connections?: {
nextPageToken?: string;
nextSyncToken?: string;
};
other?: {
nextPageToken?: string;
nextSyncToken?: string;
};
};

type ContactSyncState = {
more?: boolean;
state?: string;
};

type GoogleContact = {
names?: Array<{
displayName?: string;
}>;
emailAddresses?: Array<{
value?: string;
}>;
photos?: Array<{
url?: string;
default?: boolean;
metadata?: {
primary?: boolean;
};
}>;
};

type ListResponse = {
connections?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

type ListOtherResponse = {
otherContacts?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

class GoogleApi {
constructor(public accessToken: string) {}

public async call(
method: string,
url: string,
params?: { [key: string]: any },
body?: { [key: string]: any }
) {
const query = params ? `?${new URLSearchParams(params)}` : "";
const headers = {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/json",
...(body ? { "Content-Type": "application/json" } : {}),
};
const response = await fetch(url + query, {
method,
headers,
...(body ? { body: JSON.stringify(body) } : {}),
});
switch (response.status) {
case 400:
const responseBody = await response.json();
if (responseBody.status === "FAILED_PRECONDITION") {
return null;
}
throw new Error("Invalid request", { cause: responseBody });
case 401:
throw new Error("Authentication failed - token may be expired");
case 410:
return null;
case 200:
return await response.json();
default:
throw new Error(await response.text());
}
}
}

function parseContact(contact: GoogleContact) {
const name = contact.names?.[0]?.displayName;
const avatar = contact.photos?.filter(
(p: NonNullable<GoogleContact["photos"]>[number]) =>
!p.default && p.metadata?.primary
)?.[0]?.url;
return { name, avatar };
}

async function getGoogleContacts(
api: GoogleApi,
scopes: string[],
state: ContactSyncState
): Promise<{
contacts: NewContact[];
state: ContactSyncState;
}> {
let tokens = JSON.parse(state.state ?? "{}") as ContactTokens;
const contacts = {} as Record<string, NewContact>;
let more = false;

if (!state.more || tokens.connections?.nextPageToken) {
if (
scopes?.some?.(
(scope) => scope === "https://www.googleapis.com/auth/contacts.readonly"
)
) {
let response: ListResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/people/me/connections",
{
requestSyncToken: true,
...(tokens.connections?.nextPageToken
? {
pageToken: tokens.connections?.nextPageToken,
}
: tokens.connections?.nextSyncToken
? {
syncToken: tokens.connections?.nextSyncToken,
}
: {}),
personFields: "names,emailAddresses,photos",
}
)) as ListResponse;
if (response !== null) break;
if (!tokens.connections) break;
tokens.connections = undefined;
continue;
}
if (response) {
for (const c of response.connections ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = true;
tokens = {
...tokens,
connections: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = true;
tokens = {
...tokens,
connections: {},
};
}
} else {
if (
scopes?.some?.(
(scope) =>
scope === "https://www.googleapis.com/auth/contacts.other.readonly"
)
) {
let response: ListOtherResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/otherContacts",
{
requestSyncToken: true,
...(tokens.other?.nextPageToken
? {
pageToken: tokens.other?.nextPageToken,
}
: tokens.other?.nextSyncToken
? {
syncToken: tokens.other?.nextSyncToken,
}
: {}),
readMask: "names,emailAddresses,photos",
}
)) as ListOtherResponse;
if (response !== null) break;
if (!tokens.other) break;
tokens.other = undefined;
continue;
}
if (response) {
for (const c of response.otherContacts ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = !!response.nextPageToken;
tokens = {
...tokens,
other: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = false;
tokens = {
...tokens,
other: {},
};
}
}

return {
contacts: Object.values(contacts),
state: {
more,
state: JSON.stringify(tokens),
},
};
}
import {
type ContactSyncState,
GOOGLE_PEOPLE_SCOPES,
GoogleApi,
getGoogleContacts,
} from "./people-api";

export default class GoogleContacts
extends Connector<GoogleContacts>
Expand All@@ -253,10 +26,7 @@ export default class GoogleContacts

static readonly PROVIDER = AuthProvider.Google;

static readonly SCOPES = [
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/contacts.other.readonly",
];
static readonly SCOPES = GOOGLE_PEOPLE_SCOPES;

readonly provider = AuthProvider.Google;
readonly scopes = GoogleContacts.SCOPES;
Expand Down
6 changes: 6 additions & 0 deletions connectors/google-contacts/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
export * from "./types";
export {
GOOGLE_PEOPLE_SCOPES,
enrichContactsFromGoogle,
enrichLinkContactsFromGoogle,
lookupGooglePeople,
} from "./people-api";
export { default } from "./google-contacts";
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
connectors: shared Google People API enrichment for contacts by KrisBraun · Pull Request #125 · plotday/plot · GitHub
Skip to content
Merged
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
1 change: 1 addition & 0 deletions connectors/gmail/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@
"lint": "plot lint"
},
"dependencies": {
"@plotday/connector-google-contacts": "workspace:^",
"@plotday/twister": "workspace:^"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions connectors/gmail/src/gmail-api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,6 +4,7 @@ import type {
NewContact,
} from "@plotday/twister/plot";


export type GmailLabel = {
id: string;
name: string;
Expand Down
54 changes: 51 additions & 3 deletions connectors/gmail/src/gmail.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,10 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network, type WebhookRequest } from "@plotday/twister/tools/network";

import {
GOOGLE_PEOPLE_SCOPES,
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";

import {
GmailApi,
Expand DownExpand Up@@ -58,7 +62,14 @@ export class Gmail extends Connector<Gmail> {
static readonly SCOPES = ["https://www.googleapis.com/auth/gmail.modify"];

readonly provider = AuthProvider.Google;
readonly scopes = Gmail.SCOPES;
// Merge in People API scopes so we can enrich email-only contacts (Gmail
// headers carry name + address but no avatar) with photos from the user's
// Google Contacts and "other contacts" — without requiring the separate
// Google Contacts connector to be installed.
readonly scopes = Integrations.MergeScopes(
Gmail.SCOPES,
GOOGLE_PEOPLE_SCOPES,
);
readonly linkTypes = [
{
type: "email",
Expand DownExpand Up@@ -430,11 +441,48 @@ export class Gmail extends Connector<Gmail> {
channelId: string,
initialSync: boolean
): Promise<void> {
// Pre-build all plot threads, then enrich every contact email across the
// batch in one People API pass. Gmail headers don't carry avatars, so
// without this every email-only contact lands with `avatar = undefined`
// and shows initials forever.
const transformed: { thread: GmailThread; plot: ReturnType<typeof transformGmailThread> }[] = [];
const allEmails = new Set<string>();
for (const thread of threads) {
const plot = transformGmailThread(thread);
if (!plot.notes || plot.notes.length === 0) continue;
transformed.push({ thread, plot });
for (const c of plot.accessContacts ?? []) {
if (c && typeof c === "object" && "email" in c && c.email) allEmails.add(c.email);
}
for (const note of plot.notes) {
const author = (note as { author?: { email?: string } }).author;
if (author?.email) allEmails.add(author.email);
const noteContacts = (note as { accessContacts?: Array<{ email?: string }> }).accessContacts;
for (const c of noteContacts ?? []) {
if (c?.email) allEmails.add(c.email);
}
}
}

if (allEmails.size > 0) {
try {
// Transform Gmail thread to NewLinkWithNotes
const plotThread = transformGmailThread(thread);
const token = await this.tools.integrations.get(channelId);
if (token) {
await enrichLinkContactsFromGoogle(
transformed.map((t) => t.plot),
token.token,
token.scopes,
);
}
} catch (err) {
// Enrichment is best-effort — Gravatar fallback in the client still
// covers anyone the People API doesn't return.
console.warn("Failed to enrich Gmail contacts (non-blocking):", err);
}
}

for (const { thread, plot: plotThread } of transformed) {
try {
if (!plotThread.notes || plotThread.notes.length === 0) continue;

// Filter out notes for messages we sent (dedup)
Expand Down
22 changes: 21 additions & 1 deletion connectors/google-calendar/src/google-calendar.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
import GoogleContacts from "@plotday/connector-google-contacts";
import GoogleContacts, {
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";
import {
type Action,
ActionType,
Expand DownExpand Up@@ -1019,6 +1021,24 @@ export class GoogleCalendar extends Connector<GoogleCalendar> {
// recurring meetings) into a single cross-runtime call.
const batch = Array.from(linksBySource.values());
if (batch.length > 0) {
// Enrich attendee/organizer contacts with names + avatars from the
// user's Google Contacts and "other contacts". Calendar already
// merges GoogleContacts.SCOPES into its scopes, so the People API
// is reachable without a separate connector install.
try {
const token = await this.tools.integrations.get(calendarId);
if (token) {
await enrichLinkContactsFromGoogle(batch, token.token, token.scopes);
}
} catch (err) {
// Best-effort — Gravatar fallback in the client still covers
// anyone the People API doesn't return.
console.warn(
"Failed to enrich Google Calendar contacts (non-blocking):",
err
);
}

await this.tools.integrations.saveLinks(batch);
}
}
Expand Down
244 changes: 7 additions & 237 deletions connectors/google-contacts/src/google-contacts.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,239 +12,12 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network } from "@plotday/twister/tools/network";

type ContactTokens = {
connections?: {
nextPageToken?: string;
nextSyncToken?: string;
};
other?: {
nextPageToken?: string;
nextSyncToken?: string;
};
};

type ContactSyncState = {
more?: boolean;
state?: string;
};

type GoogleContact = {
names?: Array<{
displayName?: string;
}>;
emailAddresses?: Array<{
value?: string;
}>;
photos?: Array<{
url?: string;
default?: boolean;
metadata?: {
primary?: boolean;
};
}>;
};

type ListResponse = {
connections?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

type ListOtherResponse = {
otherContacts?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

class GoogleApi {
constructor(public accessToken: string) {}

public async call(
method: string,
url: string,
params?: { [key: string]: any },
body?: { [key: string]: any }
) {
const query = params ? `?${new URLSearchParams(params)}` : "";
const headers = {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/json",
...(body ? { "Content-Type": "application/json" } : {}),
};
const response = await fetch(url + query, {
method,
headers,
...(body ? { body: JSON.stringify(body) } : {}),
});
switch (response.status) {
case 400:
const responseBody = await response.json();
if (responseBody.status === "FAILED_PRECONDITION") {
return null;
}
throw new Error("Invalid request", { cause: responseBody });
case 401:
throw new Error("Authentication failed - token may be expired");
case 410:
return null;
case 200:
return await response.json();
default:
throw new Error(await response.text());
}
}
}

function parseContact(contact: GoogleContact) {
const name = contact.names?.[0]?.displayName;
const avatar = contact.photos?.filter(
(p: NonNullable<GoogleContact["photos"]>[number]) =>
!p.default && p.metadata?.primary
)?.[0]?.url;
return { name, avatar };
}

async function getGoogleContacts(
api: GoogleApi,
scopes: string[],
state: ContactSyncState
): Promise<{
contacts: NewContact[];
state: ContactSyncState;
}> {
let tokens = JSON.parse(state.state ?? "{}") as ContactTokens;
const contacts = {} as Record<string, NewContact>;
let more = false;

if (!state.more || tokens.connections?.nextPageToken) {
if (
scopes?.some?.(
(scope) => scope === "https://www.googleapis.com/auth/contacts.readonly"
)
) {
let response: ListResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/people/me/connections",
{
requestSyncToken: true,
...(tokens.connections?.nextPageToken
? {
pageToken: tokens.connections?.nextPageToken,
}
: tokens.connections?.nextSyncToken
? {
syncToken: tokens.connections?.nextSyncToken,
}
: {}),
personFields: "names,emailAddresses,photos",
}
)) as ListResponse;
if (response !== null) break;
if (!tokens.connections) break;
tokens.connections = undefined;
continue;
}
if (response) {
for (const c of response.connections ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = true;
tokens = {
...tokens,
connections: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = true;
tokens = {
...tokens,
connections: {},
};
}
} else {
if (
scopes?.some?.(
(scope) =>
scope === "https://www.googleapis.com/auth/contacts.other.readonly"
)
) {
let response: ListOtherResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/otherContacts",
{
requestSyncToken: true,
...(tokens.other?.nextPageToken
? {
pageToken: tokens.other?.nextPageToken,
}
: tokens.other?.nextSyncToken
? {
syncToken: tokens.other?.nextSyncToken,
}
: {}),
readMask: "names,emailAddresses,photos",
}
)) as ListOtherResponse;
if (response !== null) break;
if (!tokens.other) break;
tokens.other = undefined;
continue;
}
if (response) {
for (const c of response.otherContacts ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = !!response.nextPageToken;
tokens = {
...tokens,
other: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = false;
tokens = {
...tokens,
other: {},
};
}
}

return {
contacts: Object.values(contacts),
state: {
more,
state: JSON.stringify(tokens),
},
};
}
import {
type ContactSyncState,
GOOGLE_PEOPLE_SCOPES,
GoogleApi,
getGoogleContacts,
} from "./people-api";

export default class GoogleContacts
extends Connector<GoogleContacts>
Expand All@@ -253,10 +26,7 @@ export default class GoogleContacts

static readonly PROVIDER = AuthProvider.Google;

static readonly SCOPES = [
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/contacts.other.readonly",
];
static readonly SCOPES = GOOGLE_PEOPLE_SCOPES;

readonly provider = AuthProvider.Google;
readonly scopes = GoogleContacts.SCOPES;
Expand Down
6 changes: 6 additions & 0 deletions connectors/google-contacts/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
export * from "./types";
export {
GOOGLE_PEOPLE_SCOPES,
enrichContactsFromGoogle,
enrichLinkContactsFromGoogle,
lookupGooglePeople,
} from "./people-api";
export { default } from "./google-contacts";
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' connectors: shared Google People API enrichment for contacts by KrisBraun · Pull Request #125 · plotday/plot · GitHub
Skip to content
Merged
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
1 change: 1 addition & 0 deletions connectors/gmail/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@
"lint": "plot lint"
},
"dependencies": {
"@plotday/connector-google-contacts": "workspace:^",
"@plotday/twister": "workspace:^"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions connectors/gmail/src/gmail-api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,6 +4,7 @@ import type {
NewContact,
} from "@plotday/twister/plot";


export type GmailLabel = {
id: string;
name: string;
Expand Down
54 changes: 51 additions & 3 deletions connectors/gmail/src/gmail.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,10 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network, type WebhookRequest } from "@plotday/twister/tools/network";

import {
GOOGLE_PEOPLE_SCOPES,
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";

import {
GmailApi,
Expand DownExpand Up@@ -58,7 +62,14 @@ export class Gmail extends Connector<Gmail> {
static readonly SCOPES = ["https://www.googleapis.com/auth/gmail.modify"];

readonly provider = AuthProvider.Google;
readonly scopes = Gmail.SCOPES;
// Merge in People API scopes so we can enrich email-only contacts (Gmail
// headers carry name + address but no avatar) with photos from the user's
// Google Contacts and "other contacts" — without requiring the separate
// Google Contacts connector to be installed.
readonly scopes = Integrations.MergeScopes(
Gmail.SCOPES,
GOOGLE_PEOPLE_SCOPES,
);
readonly linkTypes = [
{
type: "email",
Expand DownExpand Up@@ -430,11 +441,48 @@ export class Gmail extends Connector<Gmail> {
channelId: string,
initialSync: boolean
): Promise<void> {
// Pre-build all plot threads, then enrich every contact email across the
// batch in one People API pass. Gmail headers don't carry avatars, so
// without this every email-only contact lands with `avatar = undefined`
// and shows initials forever.
const transformed: { thread: GmailThread; plot: ReturnType<typeof transformGmailThread> }[] = [];
const allEmails = new Set<string>();
for (const thread of threads) {
const plot = transformGmailThread(thread);
if (!plot.notes || plot.notes.length === 0) continue;
transformed.push({ thread, plot });
for (const c of plot.accessContacts ?? []) {
if (c && typeof c === "object" && "email" in c && c.email) allEmails.add(c.email);
}
for (const note of plot.notes) {
const author = (note as { author?: { email?: string } }).author;
if (author?.email) allEmails.add(author.email);
const noteContacts = (note as { accessContacts?: Array<{ email?: string }> }).accessContacts;
for (const c of noteContacts ?? []) {
if (c?.email) allEmails.add(c.email);
}
}
}

if (allEmails.size > 0) {
try {
// Transform Gmail thread to NewLinkWithNotes
const plotThread = transformGmailThread(thread);
const token = await this.tools.integrations.get(channelId);
if (token) {
await enrichLinkContactsFromGoogle(
transformed.map((t) => t.plot),
token.token,
token.scopes,
);
}
} catch (err) {
// Enrichment is best-effort — Gravatar fallback in the client still
// covers anyone the People API doesn't return.
console.warn("Failed to enrich Gmail contacts (non-blocking):", err);
}
}

for (const { thread, plot: plotThread } of transformed) {
try {
if (!plotThread.notes || plotThread.notes.length === 0) continue;

// Filter out notes for messages we sent (dedup)
Expand Down
22 changes: 21 additions & 1 deletion connectors/google-calendar/src/google-calendar.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
import GoogleContacts from "@plotday/connector-google-contacts";
import GoogleContacts, {
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";
import {
type Action,
ActionType,
Expand DownExpand Up@@ -1019,6 +1021,24 @@ export class GoogleCalendar extends Connector<GoogleCalendar> {
// recurring meetings) into a single cross-runtime call.
const batch = Array.from(linksBySource.values());
if (batch.length > 0) {
// Enrich attendee/organizer contacts with names + avatars from the
// user's Google Contacts and "other contacts". Calendar already
// merges GoogleContacts.SCOPES into its scopes, so the People API
// is reachable without a separate connector install.
try {
const token = await this.tools.integrations.get(calendarId);
if (token) {
await enrichLinkContactsFromGoogle(batch, token.token, token.scopes);
}
} catch (err) {
// Best-effort — Gravatar fallback in the client still covers
// anyone the People API doesn't return.
console.warn(
"Failed to enrich Google Calendar contacts (non-blocking):",
err
);
}

await this.tools.integrations.saveLinks(batch);
}
}
Expand Down
244 changes: 7 additions & 237 deletions connectors/google-contacts/src/google-contacts.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,239 +12,12 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network } from "@plotday/twister/tools/network";

type ContactTokens = {
connections?: {
nextPageToken?: string;
nextSyncToken?: string;
};
other?: {
nextPageToken?: string;
nextSyncToken?: string;
};
};

type ContactSyncState = {
more?: boolean;
state?: string;
};

type GoogleContact = {
names?: Array<{
displayName?: string;
}>;
emailAddresses?: Array<{
value?: string;
}>;
photos?: Array<{
url?: string;
default?: boolean;
metadata?: {
primary?: boolean;
};
}>;
};

type ListResponse = {
connections?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

type ListOtherResponse = {
otherContacts?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

class GoogleApi {
constructor(public accessToken: string) {}

public async call(
method: string,
url: string,
params?: { [key: string]: any },
body?: { [key: string]: any }
) {
const query = params ? `?${new URLSearchParams(params)}` : "";
const headers = {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/json",
...(body ? { "Content-Type": "application/json" } : {}),
};
const response = await fetch(url + query, {
method,
headers,
...(body ? { body: JSON.stringify(body) } : {}),
});
switch (response.status) {
case 400:
const responseBody = await response.json();
if (responseBody.status === "FAILED_PRECONDITION") {
return null;
}
throw new Error("Invalid request", { cause: responseBody });
case 401:
throw new Error("Authentication failed - token may be expired");
case 410:
return null;
case 200:
return await response.json();
default:
throw new Error(await response.text());
}
}
}

function parseContact(contact: GoogleContact) {
const name = contact.names?.[0]?.displayName;
const avatar = contact.photos?.filter(
(p: NonNullable<GoogleContact["photos"]>[number]) =>
!p.default && p.metadata?.primary
)?.[0]?.url;
return { name, avatar };
}

async function getGoogleContacts(
api: GoogleApi,
scopes: string[],
state: ContactSyncState
): Promise<{
contacts: NewContact[];
state: ContactSyncState;
}> {
let tokens = JSON.parse(state.state ?? "{}") as ContactTokens;
const contacts = {} as Record<string, NewContact>;
let more = false;

if (!state.more || tokens.connections?.nextPageToken) {
if (
scopes?.some?.(
(scope) => scope === "https://www.googleapis.com/auth/contacts.readonly"
)
) {
let response: ListResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/people/me/connections",
{
requestSyncToken: true,
...(tokens.connections?.nextPageToken
? {
pageToken: tokens.connections?.nextPageToken,
}
: tokens.connections?.nextSyncToken
? {
syncToken: tokens.connections?.nextSyncToken,
}
: {}),
personFields: "names,emailAddresses,photos",
}
)) as ListResponse;
if (response !== null) break;
if (!tokens.connections) break;
tokens.connections = undefined;
continue;
}
if (response) {
for (const c of response.connections ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = true;
tokens = {
...tokens,
connections: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = true;
tokens = {
...tokens,
connections: {},
};
}
} else {
if (
scopes?.some?.(
(scope) =>
scope === "https://www.googleapis.com/auth/contacts.other.readonly"
)
) {
let response: ListOtherResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/otherContacts",
{
requestSyncToken: true,
...(tokens.other?.nextPageToken
? {
pageToken: tokens.other?.nextPageToken,
}
: tokens.other?.nextSyncToken
? {
syncToken: tokens.other?.nextSyncToken,
}
: {}),
readMask: "names,emailAddresses,photos",
}
)) as ListOtherResponse;
if (response !== null) break;
if (!tokens.other) break;
tokens.other = undefined;
continue;
}
if (response) {
for (const c of response.otherContacts ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = !!response.nextPageToken;
tokens = {
...tokens,
other: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = false;
tokens = {
...tokens,
other: {},
};
}
}

return {
contacts: Object.values(contacts),
state: {
more,
state: JSON.stringify(tokens),
},
};
}
import {
type ContactSyncState,
GOOGLE_PEOPLE_SCOPES,
GoogleApi,
getGoogleContacts,
} from "./people-api";

export default class GoogleContacts
extends Connector<GoogleContacts>
Expand All@@ -253,10 +26,7 @@ export default class GoogleContacts

static readonly PROVIDER = AuthProvider.Google;

static readonly SCOPES = [
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/contacts.other.readonly",
];
static readonly SCOPES = GOOGLE_PEOPLE_SCOPES;

readonly provider = AuthProvider.Google;
readonly scopes = GoogleContacts.SCOPES;
Expand Down
6 changes: 6 additions & 0 deletions connectors/google-contacts/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
export * from "./types";
export {
GOOGLE_PEOPLE_SCOPES,
enrichContactsFromGoogle,
enrichLinkContactsFromGoogle,
lookupGooglePeople,
} from "./people-api";
export { default } from "./google-contacts";
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' connectors: shared Google People API enrichment for contacts by KrisBraun · Pull Request #125 · plotday/plot · GitHub
Skip to content
Merged
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
1 change: 1 addition & 0 deletions connectors/gmail/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@
"lint": "plot lint"
},
"dependencies": {
"@plotday/connector-google-contacts": "workspace:^",
"@plotday/twister": "workspace:^"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions connectors/gmail/src/gmail-api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,6 +4,7 @@ import type {
NewContact,
} from "@plotday/twister/plot";


export type GmailLabel = {
id: string;
name: string;
Expand Down
54 changes: 51 additions & 3 deletions connectors/gmail/src/gmail.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,10 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network, type WebhookRequest } from "@plotday/twister/tools/network";

import {
GOOGLE_PEOPLE_SCOPES,
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";

import {
GmailApi,
Expand DownExpand Up@@ -58,7 +62,14 @@ export class Gmail extends Connector<Gmail> {
static readonly SCOPES = ["https://www.googleapis.com/auth/gmail.modify"];

readonly provider = AuthProvider.Google;
readonly scopes = Gmail.SCOPES;
// Merge in People API scopes so we can enrich email-only contacts (Gmail
// headers carry name + address but no avatar) with photos from the user's
// Google Contacts and "other contacts" — without requiring the separate
// Google Contacts connector to be installed.
readonly scopes = Integrations.MergeScopes(
Gmail.SCOPES,
GOOGLE_PEOPLE_SCOPES,
);
readonly linkTypes = [
{
type: "email",
Expand DownExpand Up@@ -430,11 +441,48 @@ export class Gmail extends Connector<Gmail> {
channelId: string,
initialSync: boolean
): Promise<void> {
// Pre-build all plot threads, then enrich every contact email across the
// batch in one People API pass. Gmail headers don't carry avatars, so
// without this every email-only contact lands with `avatar = undefined`
// and shows initials forever.
const transformed: { thread: GmailThread; plot: ReturnType<typeof transformGmailThread> }[] = [];
const allEmails = new Set<string>();
for (const thread of threads) {
const plot = transformGmailThread(thread);
if (!plot.notes || plot.notes.length === 0) continue;
transformed.push({ thread, plot });
for (const c of plot.accessContacts ?? []) {
if (c && typeof c === "object" && "email" in c && c.email) allEmails.add(c.email);
}
for (const note of plot.notes) {
const author = (note as { author?: { email?: string } }).author;
if (author?.email) allEmails.add(author.email);
const noteContacts = (note as { accessContacts?: Array<{ email?: string }> }).accessContacts;
for (const c of noteContacts ?? []) {
if (c?.email) allEmails.add(c.email);
}
}
}

if (allEmails.size > 0) {
try {
// Transform Gmail thread to NewLinkWithNotes
const plotThread = transformGmailThread(thread);
const token = await this.tools.integrations.get(channelId);
if (token) {
await enrichLinkContactsFromGoogle(
transformed.map((t) => t.plot),
token.token,
token.scopes,
);
}
} catch (err) {
// Enrichment is best-effort — Gravatar fallback in the client still
// covers anyone the People API doesn't return.
console.warn("Failed to enrich Gmail contacts (non-blocking):", err);
}
}

for (const { thread, plot: plotThread } of transformed) {
try {
if (!plotThread.notes || plotThread.notes.length === 0) continue;

// Filter out notes for messages we sent (dedup)
Expand Down
22 changes: 21 additions & 1 deletion connectors/google-calendar/src/google-calendar.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
import GoogleContacts from "@plotday/connector-google-contacts";
import GoogleContacts, {
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";
import {
type Action,
ActionType,
Expand DownExpand Up@@ -1019,6 +1021,24 @@ export class GoogleCalendar extends Connector<GoogleCalendar> {
// recurring meetings) into a single cross-runtime call.
const batch = Array.from(linksBySource.values());
if (batch.length > 0) {
// Enrich attendee/organizer contacts with names + avatars from the
// user's Google Contacts and "other contacts". Calendar already
// merges GoogleContacts.SCOPES into its scopes, so the People API
// is reachable without a separate connector install.
try {
const token = await this.tools.integrations.get(calendarId);
if (token) {
await enrichLinkContactsFromGoogle(batch, token.token, token.scopes);
}
} catch (err) {
// Best-effort — Gravatar fallback in the client still covers
// anyone the People API doesn't return.
console.warn(
"Failed to enrich Google Calendar contacts (non-blocking):",
err
);
}

await this.tools.integrations.saveLinks(batch);
}
}
Expand Down
244 changes: 7 additions & 237 deletions connectors/google-contacts/src/google-contacts.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,239 +12,12 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network } from "@plotday/twister/tools/network";

type ContactTokens = {
connections?: {
nextPageToken?: string;
nextSyncToken?: string;
};
other?: {
nextPageToken?: string;
nextSyncToken?: string;
};
};

type ContactSyncState = {
more?: boolean;
state?: string;
};

type GoogleContact = {
names?: Array<{
displayName?: string;
}>;
emailAddresses?: Array<{
value?: string;
}>;
photos?: Array<{
url?: string;
default?: boolean;
metadata?: {
primary?: boolean;
};
}>;
};

type ListResponse = {
connections?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

type ListOtherResponse = {
otherContacts?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

class GoogleApi {
constructor(public accessToken: string) {}

public async call(
method: string,
url: string,
params?: { [key: string]: any },
body?: { [key: string]: any }
) {
const query = params ? `?${new URLSearchParams(params)}` : "";
const headers = {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/json",
...(body ? { "Content-Type": "application/json" } : {}),
};
const response = await fetch(url + query, {
method,
headers,
...(body ? { body: JSON.stringify(body) } : {}),
});
switch (response.status) {
case 400:
const responseBody = await response.json();
if (responseBody.status === "FAILED_PRECONDITION") {
return null;
}
throw new Error("Invalid request", { cause: responseBody });
case 401:
throw new Error("Authentication failed - token may be expired");
case 410:
return null;
case 200:
return await response.json();
default:
throw new Error(await response.text());
}
}
}

function parseContact(contact: GoogleContact) {
const name = contact.names?.[0]?.displayName;
const avatar = contact.photos?.filter(
(p: NonNullable<GoogleContact["photos"]>[number]) =>
!p.default && p.metadata?.primary
)?.[0]?.url;
return { name, avatar };
}

async function getGoogleContacts(
api: GoogleApi,
scopes: string[],
state: ContactSyncState
): Promise<{
contacts: NewContact[];
state: ContactSyncState;
}> {
let tokens = JSON.parse(state.state ?? "{}") as ContactTokens;
const contacts = {} as Record<string, NewContact>;
let more = false;

if (!state.more || tokens.connections?.nextPageToken) {
if (
scopes?.some?.(
(scope) => scope === "https://www.googleapis.com/auth/contacts.readonly"
)
) {
let response: ListResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/people/me/connections",
{
requestSyncToken: true,
...(tokens.connections?.nextPageToken
? {
pageToken: tokens.connections?.nextPageToken,
}
: tokens.connections?.nextSyncToken
? {
syncToken: tokens.connections?.nextSyncToken,
}
: {}),
personFields: "names,emailAddresses,photos",
}
)) as ListResponse;
if (response !== null) break;
if (!tokens.connections) break;
tokens.connections = undefined;
continue;
}
if (response) {
for (const c of response.connections ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = true;
tokens = {
...tokens,
connections: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = true;
tokens = {
...tokens,
connections: {},
};
}
} else {
if (
scopes?.some?.(
(scope) =>
scope === "https://www.googleapis.com/auth/contacts.other.readonly"
)
) {
let response: ListOtherResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/otherContacts",
{
requestSyncToken: true,
...(tokens.other?.nextPageToken
? {
pageToken: tokens.other?.nextPageToken,
}
: tokens.other?.nextSyncToken
? {
syncToken: tokens.other?.nextSyncToken,
}
: {}),
readMask: "names,emailAddresses,photos",
}
)) as ListOtherResponse;
if (response !== null) break;
if (!tokens.other) break;
tokens.other = undefined;
continue;
}
if (response) {
for (const c of response.otherContacts ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = !!response.nextPageToken;
tokens = {
...tokens,
other: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = false;
tokens = {
...tokens,
other: {},
};
}
}

return {
contacts: Object.values(contacts),
state: {
more,
state: JSON.stringify(tokens),
},
};
}
import {
type ContactSyncState,
GOOGLE_PEOPLE_SCOPES,
GoogleApi,
getGoogleContacts,
} from "./people-api";

export default class GoogleContacts
extends Connector<GoogleContacts>
Expand All@@ -253,10 +26,7 @@ export default class GoogleContacts

static readonly PROVIDER = AuthProvider.Google;

static readonly SCOPES = [
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/contacts.other.readonly",
];
static readonly SCOPES = GOOGLE_PEOPLE_SCOPES;

readonly provider = AuthProvider.Google;
readonly scopes = GoogleContacts.SCOPES;
Expand Down
6 changes: 6 additions & 0 deletions connectors/google-contacts/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
export * from "./types";
export {
GOOGLE_PEOPLE_SCOPES,
enrichContactsFromGoogle,
enrichLinkContactsFromGoogle,
lookupGooglePeople,
} from "./people-api";
export { default } from "./google-contacts";
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' connectors: shared Google People API enrichment for contacts by KrisBraun · Pull Request #125 · plotday/plot · GitHub
Skip to content
Merged
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
1 change: 1 addition & 0 deletions connectors/gmail/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@
"lint": "plot lint"
},
"dependencies": {
"@plotday/connector-google-contacts": "workspace:^",
"@plotday/twister": "workspace:^"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions connectors/gmail/src/gmail-api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,6 +4,7 @@ import type {
NewContact,
} from "@plotday/twister/plot";


export type GmailLabel = {
id: string;
name: string;
Expand Down
54 changes: 51 additions & 3 deletions connectors/gmail/src/gmail.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,10 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network, type WebhookRequest } from "@plotday/twister/tools/network";

import {
GOOGLE_PEOPLE_SCOPES,
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";

import {
GmailApi,
Expand DownExpand Up@@ -58,7 +62,14 @@ export class Gmail extends Connector<Gmail> {
static readonly SCOPES = ["https://www.googleapis.com/auth/gmail.modify"];

readonly provider = AuthProvider.Google;
readonly scopes = Gmail.SCOPES;
// Merge in People API scopes so we can enrich email-only contacts (Gmail
// headers carry name + address but no avatar) with photos from the user's
// Google Contacts and "other contacts" — without requiring the separate
// Google Contacts connector to be installed.
readonly scopes = Integrations.MergeScopes(
Gmail.SCOPES,
GOOGLE_PEOPLE_SCOPES,
);
readonly linkTypes = [
{
type: "email",
Expand DownExpand Up@@ -430,11 +441,48 @@ export class Gmail extends Connector<Gmail> {
channelId: string,
initialSync: boolean
): Promise<void> {
// Pre-build all plot threads, then enrich every contact email across the
// batch in one People API pass. Gmail headers don't carry avatars, so
// without this every email-only contact lands with `avatar = undefined`
// and shows initials forever.
const transformed: { thread: GmailThread; plot: ReturnType<typeof transformGmailThread> }[] = [];
const allEmails = new Set<string>();
for (const thread of threads) {
const plot = transformGmailThread(thread);
if (!plot.notes || plot.notes.length === 0) continue;
transformed.push({ thread, plot });
for (const c of plot.accessContacts ?? []) {
if (c && typeof c === "object" && "email" in c && c.email) allEmails.add(c.email);
}
for (const note of plot.notes) {
const author = (note as { author?: { email?: string } }).author;
if (author?.email) allEmails.add(author.email);
const noteContacts = (note as { accessContacts?: Array<{ email?: string }> }).accessContacts;
for (const c of noteContacts ?? []) {
if (c?.email) allEmails.add(c.email);
}
}
}

if (allEmails.size > 0) {
try {
// Transform Gmail thread to NewLinkWithNotes
const plotThread = transformGmailThread(thread);
const token = await this.tools.integrations.get(channelId);
if (token) {
await enrichLinkContactsFromGoogle(
transformed.map((t) => t.plot),
token.token,
token.scopes,
);
}
} catch (err) {
// Enrichment is best-effort — Gravatar fallback in the client still
// covers anyone the People API doesn't return.
console.warn("Failed to enrich Gmail contacts (non-blocking):", err);
}
}

for (const { thread, plot: plotThread } of transformed) {
try {
if (!plotThread.notes || plotThread.notes.length === 0) continue;

// Filter out notes for messages we sent (dedup)
Expand Down
22 changes: 21 additions & 1 deletion connectors/google-calendar/src/google-calendar.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
import GoogleContacts from "@plotday/connector-google-contacts";
import GoogleContacts, {
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";
import {
type Action,
ActionType,
Expand DownExpand Up@@ -1019,6 +1021,24 @@ export class GoogleCalendar extends Connector<GoogleCalendar> {
// recurring meetings) into a single cross-runtime call.
const batch = Array.from(linksBySource.values());
if (batch.length > 0) {
// Enrich attendee/organizer contacts with names + avatars from the
// user's Google Contacts and "other contacts". Calendar already
// merges GoogleContacts.SCOPES into its scopes, so the People API
// is reachable without a separate connector install.
try {
const token = await this.tools.integrations.get(calendarId);
if (token) {
await enrichLinkContactsFromGoogle(batch, token.token, token.scopes);
}
} catch (err) {
// Best-effort — Gravatar fallback in the client still covers
// anyone the People API doesn't return.
console.warn(
"Failed to enrich Google Calendar contacts (non-blocking):",
err
);
}

await this.tools.integrations.saveLinks(batch);
}
}
Expand Down
244 changes: 7 additions & 237 deletions connectors/google-contacts/src/google-contacts.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,239 +12,12 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network } from "@plotday/twister/tools/network";

type ContactTokens = {
connections?: {
nextPageToken?: string;
nextSyncToken?: string;
};
other?: {
nextPageToken?: string;
nextSyncToken?: string;
};
};

type ContactSyncState = {
more?: boolean;
state?: string;
};

type GoogleContact = {
names?: Array<{
displayName?: string;
}>;
emailAddresses?: Array<{
value?: string;
}>;
photos?: Array<{
url?: string;
default?: boolean;
metadata?: {
primary?: boolean;
};
}>;
};

type ListResponse = {
connections?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

type ListOtherResponse = {
otherContacts?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

class GoogleApi {
constructor(public accessToken: string) {}

public async call(
method: string,
url: string,
params?: { [key: string]: any },
body?: { [key: string]: any }
) {
const query = params ? `?${new URLSearchParams(params)}` : "";
const headers = {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/json",
...(body ? { "Content-Type": "application/json" } : {}),
};
const response = await fetch(url + query, {
method,
headers,
...(body ? { body: JSON.stringify(body) } : {}),
});
switch (response.status) {
case 400:
const responseBody = await response.json();
if (responseBody.status === "FAILED_PRECONDITION") {
return null;
}
throw new Error("Invalid request", { cause: responseBody });
case 401:
throw new Error("Authentication failed - token may be expired");
case 410:
return null;
case 200:
return await response.json();
default:
throw new Error(await response.text());
}
}
}

function parseContact(contact: GoogleContact) {
const name = contact.names?.[0]?.displayName;
const avatar = contact.photos?.filter(
(p: NonNullable<GoogleContact["photos"]>[number]) =>
!p.default && p.metadata?.primary
)?.[0]?.url;
return { name, avatar };
}

async function getGoogleContacts(
api: GoogleApi,
scopes: string[],
state: ContactSyncState
): Promise<{
contacts: NewContact[];
state: ContactSyncState;
}> {
let tokens = JSON.parse(state.state ?? "{}") as ContactTokens;
const contacts = {} as Record<string, NewContact>;
let more = false;

if (!state.more || tokens.connections?.nextPageToken) {
if (
scopes?.some?.(
(scope) => scope === "https://www.googleapis.com/auth/contacts.readonly"
)
) {
let response: ListResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/people/me/connections",
{
requestSyncToken: true,
...(tokens.connections?.nextPageToken
? {
pageToken: tokens.connections?.nextPageToken,
}
: tokens.connections?.nextSyncToken
? {
syncToken: tokens.connections?.nextSyncToken,
}
: {}),
personFields: "names,emailAddresses,photos",
}
)) as ListResponse;
if (response !== null) break;
if (!tokens.connections) break;
tokens.connections = undefined;
continue;
}
if (response) {
for (const c of response.connections ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = true;
tokens = {
...tokens,
connections: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = true;
tokens = {
...tokens,
connections: {},
};
}
} else {
if (
scopes?.some?.(
(scope) =>
scope === "https://www.googleapis.com/auth/contacts.other.readonly"
)
) {
let response: ListOtherResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/otherContacts",
{
requestSyncToken: true,
...(tokens.other?.nextPageToken
? {
pageToken: tokens.other?.nextPageToken,
}
: tokens.other?.nextSyncToken
? {
syncToken: tokens.other?.nextSyncToken,
}
: {}),
readMask: "names,emailAddresses,photos",
}
)) as ListOtherResponse;
if (response !== null) break;
if (!tokens.other) break;
tokens.other = undefined;
continue;
}
if (response) {
for (const c of response.otherContacts ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = !!response.nextPageToken;
tokens = {
...tokens,
other: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = false;
tokens = {
...tokens,
other: {},
};
}
}

return {
contacts: Object.values(contacts),
state: {
more,
state: JSON.stringify(tokens),
},
};
}
import {
type ContactSyncState,
GOOGLE_PEOPLE_SCOPES,
GoogleApi,
getGoogleContacts,
} from "./people-api";

export default class GoogleContacts
extends Connector<GoogleContacts>
Expand All@@ -253,10 +26,7 @@ export default class GoogleContacts

static readonly PROVIDER = AuthProvider.Google;

static readonly SCOPES = [
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/contacts.other.readonly",
];
static readonly SCOPES = GOOGLE_PEOPLE_SCOPES;

readonly provider = AuthProvider.Google;
readonly scopes = GoogleContacts.SCOPES;
Expand Down
6 changes: 6 additions & 0 deletions connectors/google-contacts/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
export * from "./types";
export {
GOOGLE_PEOPLE_SCOPES,
enrichContactsFromGoogle,
enrichLinkContactsFromGoogle,
lookupGooglePeople,
} from "./people-api";
export { default } from "./google-contacts";
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' connectors: shared Google People API enrichment for contacts by KrisBraun · Pull Request #125 · plotday/plot · GitHub
Skip to content
Merged
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
1 change: 1 addition & 0 deletions connectors/gmail/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@
"lint": "plot lint"
},
"dependencies": {
"@plotday/connector-google-contacts": "workspace:^",
"@plotday/twister": "workspace:^"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions connectors/gmail/src/gmail-api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,6 +4,7 @@ import type {
NewContact,
} from "@plotday/twister/plot";


export type GmailLabel = {
id: string;
name: string;
Expand Down
54 changes: 51 additions & 3 deletions connectors/gmail/src/gmail.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,10 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network, type WebhookRequest } from "@plotday/twister/tools/network";

import {
GOOGLE_PEOPLE_SCOPES,
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";

import {
GmailApi,
Expand DownExpand Up@@ -58,7 +62,14 @@ export class Gmail extends Connector<Gmail> {
static readonly SCOPES = ["https://www.googleapis.com/auth/gmail.modify"];

readonly provider = AuthProvider.Google;
readonly scopes = Gmail.SCOPES;
// Merge in People API scopes so we can enrich email-only contacts (Gmail
// headers carry name + address but no avatar) with photos from the user's
// Google Contacts and "other contacts" — without requiring the separate
// Google Contacts connector to be installed.
readonly scopes = Integrations.MergeScopes(
Gmail.SCOPES,
GOOGLE_PEOPLE_SCOPES,
);
readonly linkTypes = [
{
type: "email",
Expand DownExpand Up@@ -430,11 +441,48 @@ export class Gmail extends Connector<Gmail> {
channelId: string,
initialSync: boolean
): Promise<void> {
// Pre-build all plot threads, then enrich every contact email across the
// batch in one People API pass. Gmail headers don't carry avatars, so
// without this every email-only contact lands with `avatar = undefined`
// and shows initials forever.
const transformed: { thread: GmailThread; plot: ReturnType<typeof transformGmailThread> }[] = [];
const allEmails = new Set<string>();
for (const thread of threads) {
const plot = transformGmailThread(thread);
if (!plot.notes || plot.notes.length === 0) continue;
transformed.push({ thread, plot });
for (const c of plot.accessContacts ?? []) {
if (c && typeof c === "object" && "email" in c && c.email) allEmails.add(c.email);
}
for (const note of plot.notes) {
const author = (note as { author?: { email?: string } }).author;
if (author?.email) allEmails.add(author.email);
const noteContacts = (note as { accessContacts?: Array<{ email?: string }> }).accessContacts;
for (const c of noteContacts ?? []) {
if (c?.email) allEmails.add(c.email);
}
}
}

if (allEmails.size > 0) {
try {
// Transform Gmail thread to NewLinkWithNotes
const plotThread = transformGmailThread(thread);
const token = await this.tools.integrations.get(channelId);
if (token) {
await enrichLinkContactsFromGoogle(
transformed.map((t) => t.plot),
token.token,
token.scopes,
);
}
} catch (err) {
// Enrichment is best-effort — Gravatar fallback in the client still
// covers anyone the People API doesn't return.
console.warn("Failed to enrich Gmail contacts (non-blocking):", err);
}
}

for (const { thread, plot: plotThread } of transformed) {
try {
if (!plotThread.notes || plotThread.notes.length === 0) continue;

// Filter out notes for messages we sent (dedup)
Expand Down
22 changes: 21 additions & 1 deletion connectors/google-calendar/src/google-calendar.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
import GoogleContacts from "@plotday/connector-google-contacts";
import GoogleContacts, {
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";
import {
type Action,
ActionType,
Expand DownExpand Up@@ -1019,6 +1021,24 @@ export class GoogleCalendar extends Connector<GoogleCalendar> {
// recurring meetings) into a single cross-runtime call.
const batch = Array.from(linksBySource.values());
if (batch.length > 0) {
// Enrich attendee/organizer contacts with names + avatars from the
// user's Google Contacts and "other contacts". Calendar already
// merges GoogleContacts.SCOPES into its scopes, so the People API
// is reachable without a separate connector install.
try {
const token = await this.tools.integrations.get(calendarId);
if (token) {
await enrichLinkContactsFromGoogle(batch, token.token, token.scopes);
}
} catch (err) {
// Best-effort — Gravatar fallback in the client still covers
// anyone the People API doesn't return.
console.warn(
"Failed to enrich Google Calendar contacts (non-blocking):",
err
);
}

await this.tools.integrations.saveLinks(batch);
}
}
Expand Down
244 changes: 7 additions & 237 deletions connectors/google-contacts/src/google-contacts.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,239 +12,12 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network } from "@plotday/twister/tools/network";

type ContactTokens = {
connections?: {
nextPageToken?: string;
nextSyncToken?: string;
};
other?: {
nextPageToken?: string;
nextSyncToken?: string;
};
};

type ContactSyncState = {
more?: boolean;
state?: string;
};

type GoogleContact = {
names?: Array<{
displayName?: string;
}>;
emailAddresses?: Array<{
value?: string;
}>;
photos?: Array<{
url?: string;
default?: boolean;
metadata?: {
primary?: boolean;
};
}>;
};

type ListResponse = {
connections?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

type ListOtherResponse = {
otherContacts?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

class GoogleApi {
constructor(public accessToken: string) {}

public async call(
method: string,
url: string,
params?: { [key: string]: any },
body?: { [key: string]: any }
) {
const query = params ? `?${new URLSearchParams(params)}` : "";
const headers = {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/json",
...(body ? { "Content-Type": "application/json" } : {}),
};
const response = await fetch(url + query, {
method,
headers,
...(body ? { body: JSON.stringify(body) } : {}),
});
switch (response.status) {
case 400:
const responseBody = await response.json();
if (responseBody.status === "FAILED_PRECONDITION") {
return null;
}
throw new Error("Invalid request", { cause: responseBody });
case 401:
throw new Error("Authentication failed - token may be expired");
case 410:
return null;
case 200:
return await response.json();
default:
throw new Error(await response.text());
}
}
}

function parseContact(contact: GoogleContact) {
const name = contact.names?.[0]?.displayName;
const avatar = contact.photos?.filter(
(p: NonNullable<GoogleContact["photos"]>[number]) =>
!p.default && p.metadata?.primary
)?.[0]?.url;
return { name, avatar };
}

async function getGoogleContacts(
api: GoogleApi,
scopes: string[],
state: ContactSyncState
): Promise<{
contacts: NewContact[];
state: ContactSyncState;
}> {
let tokens = JSON.parse(state.state ?? "{}") as ContactTokens;
const contacts = {} as Record<string, NewContact>;
let more = false;

if (!state.more || tokens.connections?.nextPageToken) {
if (
scopes?.some?.(
(scope) => scope === "https://www.googleapis.com/auth/contacts.readonly"
)
) {
let response: ListResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/people/me/connections",
{
requestSyncToken: true,
...(tokens.connections?.nextPageToken
? {
pageToken: tokens.connections?.nextPageToken,
}
: tokens.connections?.nextSyncToken
? {
syncToken: tokens.connections?.nextSyncToken,
}
: {}),
personFields: "names,emailAddresses,photos",
}
)) as ListResponse;
if (response !== null) break;
if (!tokens.connections) break;
tokens.connections = undefined;
continue;
}
if (response) {
for (const c of response.connections ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = true;
tokens = {
...tokens,
connections: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = true;
tokens = {
...tokens,
connections: {},
};
}
} else {
if (
scopes?.some?.(
(scope) =>
scope === "https://www.googleapis.com/auth/contacts.other.readonly"
)
) {
let response: ListOtherResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/otherContacts",
{
requestSyncToken: true,
...(tokens.other?.nextPageToken
? {
pageToken: tokens.other?.nextPageToken,
}
: tokens.other?.nextSyncToken
? {
syncToken: tokens.other?.nextSyncToken,
}
: {}),
readMask: "names,emailAddresses,photos",
}
)) as ListOtherResponse;
if (response !== null) break;
if (!tokens.other) break;
tokens.other = undefined;
continue;
}
if (response) {
for (const c of response.otherContacts ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = !!response.nextPageToken;
tokens = {
...tokens,
other: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = false;
tokens = {
...tokens,
other: {},
};
}
}

return {
contacts: Object.values(contacts),
state: {
more,
state: JSON.stringify(tokens),
},
};
}
import {
type ContactSyncState,
GOOGLE_PEOPLE_SCOPES,
GoogleApi,
getGoogleContacts,
} from "./people-api";

export default class GoogleContacts
extends Connector<GoogleContacts>
Expand All@@ -253,10 +26,7 @@ export default class GoogleContacts

static readonly PROVIDER = AuthProvider.Google;

static readonly SCOPES = [
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/contacts.other.readonly",
];
static readonly SCOPES = GOOGLE_PEOPLE_SCOPES;

readonly provider = AuthProvider.Google;
readonly scopes = GoogleContacts.SCOPES;
Expand Down
6 changes: 6 additions & 0 deletions connectors/google-contacts/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
export * from "./types";
export {
GOOGLE_PEOPLE_SCOPES,
enrichContactsFromGoogle,
enrichLinkContactsFromGoogle,
lookupGooglePeople,
} from "./people-api";
export { default } from "./google-contacts";
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); connectors: shared Google People API enrichment for contacts by KrisBraun · Pull Request #125 · plotday/plot · GitHub
Skip to content
Merged
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
1 change: 1 addition & 0 deletions connectors/gmail/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,6 +27,7 @@
"lint": "plot lint"
},
"dependencies": {
"@plotday/connector-google-contacts": "workspace:^",
"@plotday/twister": "workspace:^"
},
"devDependencies": {
Expand Down
1 change: 1 addition & 0 deletions connectors/gmail/src/gmail-api.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,6 +4,7 @@ import type {
NewContact,
} from "@plotday/twister/plot";


export type GmailLabel = {
id: string;
name: string;
Expand Down
54 changes: 51 additions & 3 deletions connectors/gmail/src/gmail.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,6 +15,10 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network, type WebhookRequest } from "@plotday/twister/tools/network";

import {
GOOGLE_PEOPLE_SCOPES,
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";

import {
GmailApi,
Expand DownExpand Up@@ -58,7 +62,14 @@ export class Gmail extends Connector<Gmail> {
static readonly SCOPES = ["https://www.googleapis.com/auth/gmail.modify"];

readonly provider = AuthProvider.Google;
readonly scopes = Gmail.SCOPES;
// Merge in People API scopes so we can enrich email-only contacts (Gmail
// headers carry name + address but no avatar) with photos from the user's
// Google Contacts and "other contacts" — without requiring the separate
// Google Contacts connector to be installed.
readonly scopes = Integrations.MergeScopes(
Gmail.SCOPES,
GOOGLE_PEOPLE_SCOPES,
);
readonly linkTypes = [
{
type: "email",
Expand DownExpand Up@@ -430,11 +441,48 @@ export class Gmail extends Connector<Gmail> {
channelId: string,
initialSync: boolean
): Promise<void> {
// Pre-build all plot threads, then enrich every contact email across the
// batch in one People API pass. Gmail headers don't carry avatars, so
// without this every email-only contact lands with `avatar = undefined`
// and shows initials forever.
const transformed: { thread: GmailThread; plot: ReturnType<typeof transformGmailThread> }[] = [];
const allEmails = new Set<string>();
for (const thread of threads) {
const plot = transformGmailThread(thread);
if (!plot.notes || plot.notes.length === 0) continue;
transformed.push({ thread, plot });
for (const c of plot.accessContacts ?? []) {
if (c && typeof c === "object" && "email" in c && c.email) allEmails.add(c.email);
}
for (const note of plot.notes) {
const author = (note as { author?: { email?: string } }).author;
if (author?.email) allEmails.add(author.email);
const noteContacts = (note as { accessContacts?: Array<{ email?: string }> }).accessContacts;
for (const c of noteContacts ?? []) {
if (c?.email) allEmails.add(c.email);
}
}
}

if (allEmails.size > 0) {
try {
// Transform Gmail thread to NewLinkWithNotes
const plotThread = transformGmailThread(thread);
const token = await this.tools.integrations.get(channelId);
if (token) {
await enrichLinkContactsFromGoogle(
transformed.map((t) => t.plot),
token.token,
token.scopes,
);
}
} catch (err) {
// Enrichment is best-effort — Gravatar fallback in the client still
// covers anyone the People API doesn't return.
console.warn("Failed to enrich Gmail contacts (non-blocking):", err);
}
}

for (const { thread, plot: plotThread } of transformed) {
try {
if (!plotThread.notes || plotThread.notes.length === 0) continue;

// Filter out notes for messages we sent (dedup)
Expand Down
22 changes: 21 additions & 1 deletion connectors/google-calendar/src/google-calendar.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
import GoogleContacts from "@plotday/connector-google-contacts";
import GoogleContacts, {
enrichLinkContactsFromGoogle,
} from "@plotday/connector-google-contacts";
import {
type Action,
ActionType,
Expand DownExpand Up@@ -1019,6 +1021,24 @@ export class GoogleCalendar extends Connector<GoogleCalendar> {
// recurring meetings) into a single cross-runtime call.
const batch = Array.from(linksBySource.values());
if (batch.length > 0) {
// Enrich attendee/organizer contacts with names + avatars from the
// user's Google Contacts and "other contacts". Calendar already
// merges GoogleContacts.SCOPES into its scopes, so the People API
// is reachable without a separate connector install.
try {
const token = await this.tools.integrations.get(calendarId);
if (token) {
await enrichLinkContactsFromGoogle(batch, token.token, token.scopes);
}
} catch (err) {
// Best-effort — Gravatar fallback in the client still covers
// anyone the People API doesn't return.
console.warn(
"Failed to enrich Google Calendar contacts (non-blocking):",
err
);
}

await this.tools.integrations.saveLinks(batch);
}
}
Expand Down
244 changes: 7 additions & 237 deletions connectors/google-contacts/src/google-contacts.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,239 +12,12 @@ import {
} from "@plotday/twister/tools/integrations";
import { Network } from "@plotday/twister/tools/network";

type ContactTokens = {
connections?: {
nextPageToken?: string;
nextSyncToken?: string;
};
other?: {
nextPageToken?: string;
nextSyncToken?: string;
};
};

type ContactSyncState = {
more?: boolean;
state?: string;
};

type GoogleContact = {
names?: Array<{
displayName?: string;
}>;
emailAddresses?: Array<{
value?: string;
}>;
photos?: Array<{
url?: string;
default?: boolean;
metadata?: {
primary?: boolean;
};
}>;
};

type ListResponse = {
connections?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

type ListOtherResponse = {
otherContacts?: GoogleContact[];
nextPageToken?: string;
nextSyncToken?: string;
};

class GoogleApi {
constructor(public accessToken: string) {}

public async call(
method: string,
url: string,
params?: { [key: string]: any },
body?: { [key: string]: any }
) {
const query = params ? `?${new URLSearchParams(params)}` : "";
const headers = {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/json",
...(body ? { "Content-Type": "application/json" } : {}),
};
const response = await fetch(url + query, {
method,
headers,
...(body ? { body: JSON.stringify(body) } : {}),
});
switch (response.status) {
case 400:
const responseBody = await response.json();
if (responseBody.status === "FAILED_PRECONDITION") {
return null;
}
throw new Error("Invalid request", { cause: responseBody });
case 401:
throw new Error("Authentication failed - token may be expired");
case 410:
return null;
case 200:
return await response.json();
default:
throw new Error(await response.text());
}
}
}

function parseContact(contact: GoogleContact) {
const name = contact.names?.[0]?.displayName;
const avatar = contact.photos?.filter(
(p: NonNullable<GoogleContact["photos"]>[number]) =>
!p.default && p.metadata?.primary
)?.[0]?.url;
return { name, avatar };
}

async function getGoogleContacts(
api: GoogleApi,
scopes: string[],
state: ContactSyncState
): Promise<{
contacts: NewContact[];
state: ContactSyncState;
}> {
let tokens = JSON.parse(state.state ?? "{}") as ContactTokens;
const contacts = {} as Record<string, NewContact>;
let more = false;

if (!state.more || tokens.connections?.nextPageToken) {
if (
scopes?.some?.(
(scope) => scope === "https://www.googleapis.com/auth/contacts.readonly"
)
) {
let response: ListResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/people/me/connections",
{
requestSyncToken: true,
...(tokens.connections?.nextPageToken
? {
pageToken: tokens.connections?.nextPageToken,
}
: tokens.connections?.nextSyncToken
? {
syncToken: tokens.connections?.nextSyncToken,
}
: {}),
personFields: "names,emailAddresses,photos",
}
)) as ListResponse;
if (response !== null) break;
if (!tokens.connections) break;
tokens.connections = undefined;
continue;
}
if (response) {
for (const c of response.connections ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = true;
tokens = {
...tokens,
connections: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = true;
tokens = {
...tokens,
connections: {},
};
}
} else {
if (
scopes?.some?.(
(scope) =>
scope === "https://www.googleapis.com/auth/contacts.other.readonly"
)
) {
let response: ListOtherResponse | undefined;
while (true) {
response = (await api.call(
"GET",
"https://people.googleapis.com/v1/otherContacts",
{
requestSyncToken: true,
...(tokens.other?.nextPageToken
? {
pageToken: tokens.other?.nextPageToken,
}
: tokens.other?.nextSyncToken
? {
syncToken: tokens.other?.nextSyncToken,
}
: {}),
readMask: "names,emailAddresses,photos",
}
)) as ListOtherResponse;
if (response !== null) break;
if (!tokens.other) break;
tokens.other = undefined;
continue;
}
if (response) {
for (const c of response.otherContacts ?? []) {
for (const e of c.emailAddresses ?? []) {
if (!e.value) continue;
const { name, avatar } = parseContact(c);
contacts[e.value] = {
...contacts[e.value],
email: e.value,
...(name ? { name } : {}),
...(avatar ? { avatar } : {}),
};
}
}
more = !!response.nextPageToken;
tokens = {
...tokens,
other: {
nextPageToken: response.nextPageToken ?? undefined,
nextSyncToken: response.nextSyncToken ?? undefined,
},
};
}
} else {
more = false;
tokens = {
...tokens,
other: {},
};
}
}

return {
contacts: Object.values(contacts),
state: {
more,
state: JSON.stringify(tokens),
},
};
}
import {
type ContactSyncState,
GOOGLE_PEOPLE_SCOPES,
GoogleApi,
getGoogleContacts,
} from "./people-api";

export default class GoogleContacts
extends Connector<GoogleContacts>
Expand All@@ -253,10 +26,7 @@ export default class GoogleContacts

static readonly PROVIDER = AuthProvider.Google;

static readonly SCOPES = [
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/contacts.other.readonly",
];
static readonly SCOPES = GOOGLE_PEOPLE_SCOPES;

readonly provider = AuthProvider.Google;
readonly scopes = GoogleContacts.SCOPES;
Expand Down
6 changes: 6 additions & 0 deletions connectors/google-contacts/src/index.ts
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
export * from "./types";
export {
GOOGLE_PEOPLE_SCOPES,
enrichContactsFromGoogle,
enrichLinkContactsFromGoogle,
lookupGooglePeople,
} from "./people-api";
export { default } from "./google-contacts";
Loading
Loading