|
| 1 | +import browser from 'webextension-polyfill' |
| 2 | + |
| 3 | + |
| 4 | +function getComposeMetadata(form: HTMLElement) { |
| 5 | + const getRecipients = (name: string) => |
| 6 | + Array.from( |
| 7 | + form.querySelectorAll(`div[name="${name}"] [data-hovercard-id]`), |
| 8 | + ).map((el) => el.getAttribute('data-hovercard-id')) |
| 9 | + .filter(Boolean) as string[] |
| 10 | + |
| 11 | + return { |
| 12 | + subject: (form.querySelector('input[name="subjectbox"]') as HTMLInputElement)?.value || '', |
| 13 | + to: getRecipients('to'), |
| 14 | + cc: getRecipients('cc'), |
| 15 | + bcc: getRecipients('bcc'), |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +function sendGmailHeartbeat() { |
| 20 | + if (document.visibilityState === 'hidden') { |
| 21 | + return |
| 22 | + } |
| 23 | + |
| 24 | + const hash = window.location.hash |
| 25 | + const form = document.querySelector('div[role="dialog"] form') as HTMLElement | null |
| 26 | + |
| 27 | + let activity = 'reading_inbox' |
| 28 | + let meta: any = {} |
| 29 | + |
| 30 | + if (form) { |
| 31 | + // for simplity in MVP: |
| 32 | + // - if many emails forms are open, we only track the first one |
| 33 | + // - if subject, to, cc, bcc changes when composing the email, we send a new heartbeat |
| 34 | + activity = 'composing_email' |
| 35 | + meta = getComposeMetadata(form) |
| 36 | + } else if ( |
| 37 | + hash.includes('inbox/') || |
| 38 | + hash.includes('sent/') || |
| 39 | + hash.includes('all/') |
| 40 | + ) { |
| 41 | + const fromEl = document.querySelector('span.gD') |
| 42 | + const from = |
| 43 | + fromEl?.getAttribute('email') || |
| 44 | + fromEl?.getAttribute('data-hovercard-id') || |
| 45 | + (fromEl as HTMLElement)?.innerText || |
| 46 | + '' |
| 47 | + const to = Array.from( |
| 48 | + document.querySelectorAll('.gE [email], .gE [data-hovercard-id]'), |
| 49 | + ) |
| 50 | + .map( |
| 51 | + (el) => el.getAttribute('email') || el.getAttribute('data-hovercard-id'), |
| 52 | + ) |
| 53 | + .filter((e) => e && e !== from) as string[] |
| 54 | + |
| 55 | + activity = 'reading_email' |
| 56 | + meta = { |
| 57 | + subject: (document.querySelector('h2.hP') as HTMLElement)?.innerText || '', |
| 58 | + from, |
| 59 | + to, |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + const data = { |
| 64 | + gmail_activity: activity, |
| 65 | + ...meta, |
| 66 | + url: window.location.href, |
| 67 | + title: document.title, |
| 68 | + } |
| 69 | + |
| 70 | + browser.runtime.sendMessage({ type: 'AW_GMAIL_HEARTBEAT', data }).catch(() => {}) |
| 71 | +} |
| 72 | + |
| 73 | +browser.storage.local.get('gmailEnabled').then((settings) => { |
| 74 | + if (!settings.gmailEnabled) { |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + setInterval(sendGmailHeartbeat, 1000) |
| 79 | + sendGmailHeartbeat() |
| 80 | +}) |
0 commit comments