-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgmail-label-counts.js
More file actions
291 lines (241 loc) · 9.13 KB
/
gmail-label-counts.js
File metadata and controls
291 lines (241 loc) · 9.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const { google } = require('googleapis');
const pLimit = require('p-limit').default;
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
const TOKEN_PATH = 'token.json';
const CACHE_DIR = path.join(__dirname, '.cache');
if (!fs.existsSync(CACHE_DIR)) {
fs.mkdirSync(CACHE_DIR);
console.log('Created cache dir:', CACHE_DIR);
} else {
console.log('Using cache dir:', CACHE_DIR);
}
function authorize(callback) {
const credentials = JSON.parse(fs.readFileSync('credentials.json'));
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
if (fs.existsSync(TOKEN_PATH)) {
oAuth2Client.setCredentials(JSON.parse(fs.readFileSync(TOKEN_PATH)));
callback(oAuth2Client);
} else {
const authUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES });
console.log('Authorize this app by visiting:', authUrl);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question('Enter the code from that page: ', (code) => {
rl.close();
oAuth2Client.getToken(code).then(({ tokens }) => {
oAuth2Client.setCredentials(tokens);
fs.writeFileSync(TOKEN_PATH, JSON.stringify(tokens));
callback(oAuth2Client);
});
});
}
}
function getCachedInboxThreadIds() {
const path = `${CACHE_DIR}/inbox-thread-ids.json`;
if (fs.existsSync(path)) {
try {
return JSON.parse(fs.readFileSync(path, 'utf8'));
} catch (e) {
console.warn('Warning: failed to load inbox thread ID cache. Refetching...');
}
}
return null;
}
function saveCachedInboxThreadIds(ids) {
const path = `${CACHE_DIR}/inbox-thread-ids.json`;
fs.writeFileSync(path, JSON.stringify(ids, null, 2));
}
function getCachedThread(threadId) {
const path = `${CACHE_DIR}/thread-${threadId}.json`;
if (fs.existsSync(path)) {
return JSON.parse(fs.readFileSync(path, 'utf8'));
}
return null;
}
function saveCachedThread(threadId, data) {
if (!Array.isArray(data.labelIds)) {
console.warn(`Skipping cache save for ${threadId} — no valid labels.`);
return;
}
const path = `${CACHE_DIR}/thread-${threadId}.json`;
fs.writeFileSync(path, JSON.stringify(data, null, 2));
}
/* eventual version
function isStableThread(labels) {
return labels.includes('=P') || labels.includes('=Q') || labels.includes('=IT');
}
*/
/* test version */
function isStableThread(labelIds) {
return (labelIds.length > 0);
}
async function safeGetThread(gmail, id, retries = 3) {
try {
const res = await gmail.users.threads.get({ userId: 'me', id, format: 'minimal' });
const labelIds = res.data.messages[0].labelIds;
if (!Array.isArray(labelIds) || labelIds.length === 0) {
console.warn(`Thread ${id} returned with missing or empty labels.`);
}
return res;
} catch (err) {
if (retries > 0 && err?.response?.status === 429) {
const delay = 1000 * (4 - retries);
console.warn(`Rate limit hit. Retrying in ${delay}ms...`);
await new Promise(res => setTimeout(res, delay));
return safeGetThread(gmail, id, retries - 1);
}
throw err;
}
}
async function loadLabelMaps(gmail) {
const res = await gmail.users.labels.list({ userId: 'me' });
const labels = res.data.labels || [];
const labelIdToName = {};
const labelNameToId = {};
for (const label of labels) {
if (label.id && label.name) {
labelIdToName[label.id] = label.name;
labelNameToId[label.name] = label.id;
}
}
return { labelIdToName, labelNameToId };
}
async function getInboxThreads(gmail) {
let threadIds = getCachedInboxThreadIds();
if (threadIds) {
console.log(`Loaded ${threadIds.length} inbox thread IDs from cache.`);
return threadIds.map(id => ({ id }));
}
const threads = [];
let nextPageToken = null;
do {
const res = await gmail.users.threads.list({
userId: 'me', q: 'label:inbox', maxResults: 100, pageToken: nextPageToken
});
threads.push(...(res.data.threads || []));
nextPageToken = res.data.nextPageToken;
process.stdout.write(`\rFetched ${threads.length} inbox thread IDs...`);
} while (nextPageToken);
console.log();
saveCachedInboxThreadIds(threads.map(t => t.id));
return threads;
}
async function listInboxLabelCounts(auth) {
const gmail = google.gmail({ version: 'v1', auth });
const { labelIdToName, labelNameToId } = await loadLabelMaps(gmail);
const threads = await getInboxThreads(gmail);
// Convert the array of thread objects to a Set for fast lookups.
const inboxThreadIds = new Set(threads.map(t => t.id));
const labelResults = [];
// Phase 1: Scan cache
let validCached = 0;
let invalidOrMissing = 0;
const toFetch = [];
await Promise.all(threads.map(async thread => {
const threadId = thread.id;
try {
const cache = getCachedThread(threadId);
const labelIds = cache?.labelIds;
if (Array.isArray(labelIds)) {
if (!inboxThreadIds.has(threadId)) {
fs.unlinkSync(`${CACHE_DIR}/thread-${threadId}.json`);
} else if (isStableThread(labelIds)) {
labelResults.push({ id: threadId, labelIds, fromCache: true });
validCached++;
} else {
toFetch.push(threadId);
}
} else {
toFetch.push(threadId);
invalidOrMissing++;
}
} catch (e) {
toFetch.push(threadId);
invalidOrMissing++;
}
const scanned = validCached + invalidOrMissing;
process.stdout.write(`\rScanned ${scanned} threads from cache (${validCached} valid, ${invalidOrMissing} invalid)...`);
}));
console.log();
// Phase 2: Fetch missing/unstable threads
const limit = pLimit(3);
let fetched = 0;
await Promise.all(toFetch.map(threadId =>
limit(async () => {
const full = await safeGetThread(gmail, threadId);
const labelIds = full.data.messages[0].labelIds || [];
saveCachedThread(threadId, {
labelIds: labelIds,
cachedAt: new Date().toISOString()
});
const labelNames = labelIds.map(id => labelIdToName[id]);
labelResults.push({ id: threadId, labelNames, fromCache: false });
fetched++;
process.stdout.write(`\rFetched ${fetched}/${toFetch.length} threads from API...`);
})
));
console.log();
// Phase 3: Count labels
const labelCounts = {};
let usedCache = 0;
let usedApi = 0;
for (const t of labelResults) {
if (!inboxThreadIds.has(t.id)) continue;
const labels = t.labelIds || t.labelNames || [];
for (const label of labels) {
if (label !== 'INBOX') {
labelCounts[label] = (labelCounts[label] || 0) + 1;
}
}
if (t.fromCache) usedCache++;
else usedApi++;
}
console.log(`\nUsed ${usedCache} threads from cache, ${usedApi} from API.\n`);
// Final output
console.log('Label Name'.padEnd(30) + 'Inbox Threads');
console.log('='.repeat(40));
Object.entries(labelCounts)
.sort(([a], [b]) => {
const nameA = labelIdToName[a] || '';
const nameB = labelIdToName[b] || '';
if (!labelIdToName[a]) console.warn(`Warning: missing label name for ID '${a}'`);
if (!labelIdToName[b]) console.warn(`Warning: missing label name for ID '${b}'`);
return nameA.localeCompare(nameB);
})
.forEach(([labelId, count]) => {
const name = labelIdToName[labelId] || `(missing name: ${labelId})`;
console.log(name.padEnd(30) + count);
});
const unreadCount = await countThreadsMatchingQuery('in:inbox is:unread', gmail);
console.log('Inbox unread threads:'.padEnd(30) + unreadCount);
const untaggedCount = await countThreadsMatchingQuery('in:inbox -label:=it -label:=p -label:=q', gmail);
console.log('Inbox untagged threads:'.padEnd(30) + untaggedCount);
}
async function countThreadsMatchingQuery(query, gmail) {
let count = 0;
let nextPageToken = null;
do {
const res = await gmail.users.threads.list({
userId: 'me',
q: query,
maxResults: 100,
pageToken: nextPageToken,
});
count += res.data.threads?.length || 0;
nextPageToken = res.data.nextPageToken;
} while (nextPageToken);
return count;
}
async function countInboxUnreadThreads(gmail) {
const res = await gmail.users.threads.list({
userId: 'me',
q: 'in:inbox is:unread',
});
return res.data.resultSizeEstimate || 0;
}
authorize(async (auth) => {
await listInboxLabelCounts(auth);
});