415 lines
17 KiB
JavaScript
415 lines
17 KiB
JavaScript
#!/usr/bin/env node
|
|
// Lê mensagens do Teams (o novo, WebView2) direto do cache local (IndexedDB), e as atas de reunião de uma
|
|
// pasta local. Sem Graph API e sem dependência fora do Node. Uso e receitas: ../SKILL.md.
|
|
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import crypto from 'node:crypto';
|
|
import { parseArgs } from 'node:util';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { openIndexedDb } from './chromium-indexeddb.mjs';
|
|
|
|
// Caminho do perfil WebView2 do Teams a partir de %LOCALAPPDATA%.
|
|
const TEAMS_PROFILE_SUFFIX = ['Packages', 'MSTeams_8wekyb3d8bbwe', 'LocalCache', 'Microsoft', 'MSTeams', 'EBWebView', 'WV2Profile_tfw'];
|
|
|
|
// TEAMS_PROFILE_DIR > Windows nativo (%LOCALAPPDATA%) > WSL (/mnt/c/Users/*, primeiro em ordem alfabética).
|
|
export function defaultTeamsProfile(env = process.env, platform = process.platform) {
|
|
if (env.TEAMS_PROFILE_DIR) return env.TEAMS_PROFILE_DIR;
|
|
if (platform === 'win32') {
|
|
const base = env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
|
return path.join(base, ...TEAMS_PROFILE_SUFFIX);
|
|
}
|
|
let users = [];
|
|
try {
|
|
users = fs.readdirSync('/mnt/c/Users').filter((u) => !u.startsWith('.')).sort();
|
|
} catch {
|
|
// sem /mnt/c
|
|
}
|
|
for (const u of users) {
|
|
const candidate = path.posix.join('/mnt/c/Users', u, 'AppData', 'Local', ...TEAMS_PROFILE_SUFFIX);
|
|
if (fs.existsSync(candidate)) return candidate;
|
|
}
|
|
return path.posix.join('/mnt/c/Users/<usuario>/AppData/Local', ...TEAMS_PROFILE_SUFFIX);
|
|
}
|
|
|
|
// Cópia de trabalho do LevelDB no temporário do sistema (/tmp no Linux/WSL, %TEMP% no Windows).
|
|
const CACHE_DIR = path.join(os.tmpdir(), 'teams_indexeddb_sync');
|
|
|
|
function warn(msg) {
|
|
process.stderr.write(`[aviso] ${msg}\n`);
|
|
}
|
|
|
|
// O Teams aberto segura o arquivo LOCK do LevelDB; por isso a leitura é feita numa cópia, sem o LOCK.
|
|
// A cópia não apaga arquivos de cópias anteriores.
|
|
function syncDb(profileDir) {
|
|
const src = path.join(profileDir, 'IndexedDB', 'https_teams.microsoft.com_0.indexeddb.leveldb');
|
|
if (!fs.existsSync(src)) {
|
|
throw new Error(`Caminho do banco LevelDB do Teams não encontrado: ${src}`);
|
|
}
|
|
let failed = 0;
|
|
const copyDir = (from, to) => {
|
|
fs.mkdirSync(to, { recursive: true });
|
|
for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
|
|
if (entry.name === 'LOCK') continue;
|
|
const s = path.join(from, entry.name);
|
|
const d = path.join(to, entry.name);
|
|
try {
|
|
if (entry.isDirectory()) copyDir(s, d);
|
|
else fs.copyFileSync(s, d);
|
|
} catch {
|
|
failed += 1;
|
|
}
|
|
}
|
|
};
|
|
try {
|
|
copyDir(src, CACHE_DIR);
|
|
} catch (e) {
|
|
warn(`falha ao copiar o cache do Teams: ${e.message}; a leitura segue com o que já estiver em ${CACHE_DIR}.`);
|
|
}
|
|
if (failed) {
|
|
warn(`${failed} arquivo(s) do cache do Teams não puderam ser copiados (bloqueados?); a leitura segue com o que foi copiado.`);
|
|
}
|
|
return CACHE_DIR;
|
|
}
|
|
|
|
export function cleanHtml(raw) {
|
|
if (raw instanceof Uint8Array) raw = Buffer.from(raw).toString('utf8');
|
|
if (typeof raw !== 'string') return '';
|
|
let text = raw.replace(/<blockquote[\s\S]*?<\/blockquote>/g, ' [Citação] ');
|
|
text = text.replace(/<img.*?src=["'](.*?)["'].*?>/g, ' [Imagem: $1] ');
|
|
text = text.replace(/<.*?>/g, '');
|
|
text = text.replaceAll(' ', ' ').replaceAll(' ', ' ').replaceAll('&', '&')
|
|
.replaceAll('<', '<').replaceAll('>', '>');
|
|
return text.replace(/\s+/g, ' ').trim();
|
|
}
|
|
|
|
const pad = (n) => String(n).padStart(2, '0');
|
|
|
|
// Data local em dd/mm/aaaa hh:mm:ss; aceita segundos ou milissegundos (número ou texto numérico).
|
|
export function parseTs(ts) {
|
|
if (!ts) return [0, 'N/A'];
|
|
let val = NaN;
|
|
if (typeof ts === 'number') val = ts;
|
|
else if (typeof ts === 'string' && /^\s*[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?\s*$/.test(ts)) val = parseFloat(ts);
|
|
const d = new Date(val > 1e11 ? val : val * 1000);
|
|
if (!Number.isFinite(val) || Number.isNaN(d.getTime())) return [0, String(ts)];
|
|
const fmt = `${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
return [val, fmt];
|
|
}
|
|
|
|
// Texto de um valor qualquer do cache (objeto, Map, Buffer, BigInt), para busca de termos e links.
|
|
function toText(value) {
|
|
const seen = new WeakSet();
|
|
return JSON.stringify(value, (_k, v) => {
|
|
if (typeof v === 'bigint') return v.toString();
|
|
if (v instanceof Map) return Object.fromEntries(v);
|
|
if (v instanceof Set) return [...v];
|
|
if (ArrayBuffer.isView(v)) return `<${v.byteLength} bytes>`;
|
|
if (v && typeof v === 'object') {
|
|
if (seen.has(v)) return '[circular]';
|
|
seen.add(v);
|
|
}
|
|
return v;
|
|
}) ?? String(value);
|
|
}
|
|
|
|
const get = (obj, key) => (obj instanceof Map ? obj.get(key) : obj?.[key]);
|
|
const isRecord = (v) => v instanceof Map || (v !== null && typeof v === 'object' && !Array.isArray(v) && !ArrayBuffer.isView(v));
|
|
const entriesOf = (v) => (v instanceof Map ? [...v.entries()] : isRecord(v) ? Object.entries(v) : []);
|
|
|
|
function detectMediaAssets(msg, rawContent) {
|
|
const media = [];
|
|
const msgType = String(get(msg, 'messageType') ?? '');
|
|
const msgText = toText(msg);
|
|
if (msgType.includes('Media_CallRecording') || msgText.includes('CallRecording')) {
|
|
media.push({ type: 'recording', desc: 'Gravação de Reunião do Teams' });
|
|
} else if (msgType.toLowerCase().includes('audio')) {
|
|
media.push({ type: 'audio', desc: 'Mensagem de Áudio / Chamada de Voz' });
|
|
} else if (msgType.toLowerCase().includes('video')) {
|
|
media.push({ type: 'video', desc: 'Vídeo / Clipe de Vídeo' });
|
|
}
|
|
const links = `${typeof rawContent === 'string' ? rawContent : toText(rawContent)} ${msgText}`.match(/https?:\/\/[^\s<>"']+/g) || [];
|
|
for (const link of links) {
|
|
if (['stream.aspx', 'iqcok', 'recording', '.mp4', '.m4a', '.mp3', '.wav'].some((t) => link.toLowerCase().includes(t))) {
|
|
media.push({ type: 'media_link', url: link, desc: 'Link de Gravação/Mídia' });
|
|
}
|
|
}
|
|
return media;
|
|
}
|
|
|
|
// Percorre as mensagens do cache com texto não vazio depois do cleanHtml: o mesmo critério para a busca e
|
|
// para o --list-chats, para que as contagens batam com o que a busca consegue achar.
|
|
function* iterMessages(profileDir) {
|
|
const idb = openIndexedDb(syncDb(profileDir));
|
|
for (const db of idb.databases) {
|
|
if (!db.name.includes('replychain-manager') || db.name.includes('metadata') || db.name.includes('streams')) continue;
|
|
for (let storeId = 1; storeId <= db.maxStoreId; storeId++) {
|
|
for (const { value: chain } of idb.iterateRecords(db.id, storeId)) {
|
|
if (!isRecord(chain)) continue;
|
|
const convId = get(chain, 'conversationId') || 'geral';
|
|
for (const [mId, data] of entriesOf(get(chain, 'messageMap'))) {
|
|
if (!isRecord(data)) continue;
|
|
const rawContent = get(data, 'content') ?? '';
|
|
const text = cleanHtml(rawContent);
|
|
if (!text) continue;
|
|
yield { convId, mId, data, rawContent, text };
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Diagnóstico: só contagens. O id de conversa de chat 1:1 contém os ids AAD dos participantes; por isso cada
|
|
// conversa sai como os 12 primeiros hex do SHA-256 do id (estável entre execuções).
|
|
function listChats(profileDir) {
|
|
const counts = new Map();
|
|
for (const { convId } of iterMessages(profileDir)) counts.set(convId, (counts.get(convId) || 0) + 1);
|
|
const chats = [...counts].map(([c, n]) => ({
|
|
chat: crypto.createHash('sha256').update(String(c), 'utf8').digest('hex').slice(0, 12),
|
|
mensagens: n,
|
|
}));
|
|
chats.sort((a, b) => b.mensagens - a.mensagens);
|
|
return {
|
|
perfil: profileDir,
|
|
conversas: chats.length,
|
|
mensagens: chats.reduce((s, c) => s + c.mensagens, 0),
|
|
por_conversa: chats,
|
|
};
|
|
}
|
|
|
|
function getContextualizedConversations({ query, senderFilter, limit, contextDepth, profileDir }) {
|
|
const all = new Map();
|
|
for (const { convId, mId, data, rawContent, text } of iterMessages(profileDir)) {
|
|
try {
|
|
const sender = get(data, 'imDisplayName') || get(data, 'fromDisplayNameInToken') || get(data, 'imdisplayname')
|
|
|| get(data, 'from') || get(data, 'creator') || 'Desconhecido';
|
|
const tsVal = get(data, 'clientArrivalTime') || get(data, 'originalArrivalTime') || get(data, 'composeTime');
|
|
const [tsRaw, tsFmt] = parseTs(tsVal);
|
|
const attachments = [];
|
|
const atts = get(data, 'attachments');
|
|
for (const att of Array.isArray(atts) ? atts : []) {
|
|
const name = isRecord(att) ? get(att, 'name') : undefined;
|
|
if (name !== undefined) attachments.push(name);
|
|
}
|
|
const senderText = typeof sender === 'string' ? sender : toText(sender);
|
|
const item = {
|
|
id: String(mId),
|
|
conversation_id: convId,
|
|
sender: senderText,
|
|
text,
|
|
ts_raw: tsRaw,
|
|
ts_fmt: tsFmt,
|
|
media: detectMediaAssets(data, rawContent),
|
|
attachments,
|
|
raw_str: `${text} ${senderText}`.toLowerCase(),
|
|
};
|
|
if (!all.has(convId)) all.set(convId, []);
|
|
all.get(convId).push(item);
|
|
} catch {
|
|
// mensagem com formato inesperado: segue
|
|
}
|
|
}
|
|
|
|
const q = query?.toLowerCase();
|
|
const p = senderFilter?.toLowerCase();
|
|
const results = [];
|
|
for (const [convId, msgs] of all) {
|
|
msgs.sort((a, b) => a.ts_raw - b.ts_raw);
|
|
const included = new Set();
|
|
msgs.forEach((m, idx) => {
|
|
const hit = p ? m.sender.toLowerCase().includes(p) && (!q || m.raw_str.includes(q)) : Boolean(q && m.raw_str.includes(q));
|
|
if (!hit) return;
|
|
for (let i = Math.max(0, idx - contextDepth); i < Math.min(msgs.length, idx + contextDepth + 1); i++) included.add(i);
|
|
});
|
|
if (!included.size) continue;
|
|
const block = [...included].sort((a, b) => a - b).map((i) => msgs[i]);
|
|
results.push({
|
|
conversation_id: convId,
|
|
messages: block,
|
|
has_media: block.some((m) => m.media.length > 0),
|
|
last_timestamp: block.at(-1).ts_raw,
|
|
});
|
|
}
|
|
results.sort((a, b) => b.last_timestamp - a.last_timestamp);
|
|
return results.slice(0, limit);
|
|
}
|
|
|
|
// Pasta de atas: só via TEAMS_MEETINGS_DIR; sem ela, a busca de atas é pulada com aviso.
|
|
function getMeetingMinutes({ meetingsDir, query, dateFilter, limit }) {
|
|
if (!meetingsDir) {
|
|
warn('TEAMS_MEETINGS_DIR não definida; a busca de atas foi pulada.');
|
|
return [];
|
|
}
|
|
if (!fs.existsSync(meetingsDir)) {
|
|
warn(`pasta de atas não encontrada (${meetingsDir}); a busca de atas foi pulada.`);
|
|
return [];
|
|
}
|
|
const readOr = (file, fallback) => {
|
|
try { return fs.readFileSync(file, 'utf8'); } catch { return fallback; }
|
|
};
|
|
const meetings = [];
|
|
const folders = fs.readdirSync(meetingsDir).filter((n) => !n.startsWith('.')).sort().reverse();
|
|
for (const folderName of folders) {
|
|
const folderPath = path.join(meetingsDir, folderName);
|
|
if (!fs.statSync(folderPath, { throwIfNoEntry: false })?.isDirectory()) continue;
|
|
if (dateFilter && !folderName.includes(dateFilter)) continue;
|
|
|
|
const ataFile = path.join(folderPath, 'ata_reuniao.md');
|
|
const transcricaoFile = path.join(folderPath, 'transcricao.md');
|
|
const ataContent = readOr(ataFile, '');
|
|
const firstLine = ataContent.trim().split('\n')[0].replaceAll('#', '').trim();
|
|
const title = firstLine || folderName;
|
|
const transcricaoSnippet = readOr(transcricaoFile, '').slice(0, 2000);
|
|
|
|
if (query && !`${title} ${ataContent} ${transcricaoSnippet}`.toLowerCase().includes(query.toLowerCase())) continue;
|
|
|
|
let screenshots = 0;
|
|
try {
|
|
screenshots = fs.readdirSync(path.join(folderPath, 'screenshots')).filter((n) => !n.startsWith('.') && n.endsWith('.jpg')).length;
|
|
} catch {
|
|
// sem pasta de screenshots
|
|
}
|
|
meetings.push({
|
|
folder_name: folderName,
|
|
folder_path: folderPath,
|
|
date: folderName.includes('_') ? folderName.split('_')[0] : '',
|
|
title,
|
|
has_ata: Boolean(ataContent),
|
|
ata_content: ataContent,
|
|
transcricao_file: fs.existsSync(transcricaoFile) ? transcricaoFile : null,
|
|
screenshots_count: screenshots,
|
|
});
|
|
if (meetings.length >= limit) break;
|
|
}
|
|
return meetings;
|
|
}
|
|
|
|
const HELP = `Uso: node teams-reader.mjs [opções]
|
|
|
|
Lê mensagens do Teams no cache local e atas de reunião.
|
|
|
|
-q, --query <termo> termo de busca nas mensagens ou atas
|
|
-p, --person <nome> nome da pessoa / remetente para filtrar no chat
|
|
-d, --date <data> filtrar atas por data (ex.: 2026-09-02)
|
|
-a, --atas buscar e exibir as Atas Executivas de reuniões
|
|
-c, --context <n> quantas mensagens antes e depois trazer na conversa (padrão 15)
|
|
-l, --limit <n> quantidade máxima de resultados (padrão 3)
|
|
--json saída em JSON
|
|
--list-chats diagnóstico: perfil detectado e contagens (conversas, mensagens e, por conversa,
|
|
um hash do id + contagem); não imprime texto, remetente, participante nem id
|
|
-h, --help esta ajuda
|
|
`;
|
|
|
|
function toInt(name, value) {
|
|
if (!/^\s*[+-]?\d+\s*$/.test(value)) {
|
|
process.stderr.write(`erro: --${name} precisa ser um número inteiro (recebido: ${value})\n`);
|
|
process.exit(2);
|
|
}
|
|
return parseInt(value, 10);
|
|
}
|
|
|
|
function main() {
|
|
let values;
|
|
try {
|
|
({ values } = parseArgs({
|
|
options: {
|
|
query: { type: 'string', short: 'q' },
|
|
person: { type: 'string', short: 'p' },
|
|
date: { type: 'string', short: 'd' },
|
|
atas: { type: 'boolean', short: 'a' },
|
|
context: { type: 'string', short: 'c', default: '15' },
|
|
limit: { type: 'string', short: 'l', default: '3' },
|
|
json: { type: 'boolean' },
|
|
'list-chats': { type: 'boolean' },
|
|
help: { type: 'boolean', short: 'h' },
|
|
},
|
|
}));
|
|
} catch (e) {
|
|
process.stderr.write(`erro: ${e.message}\n\n${HELP}`);
|
|
process.exit(2);
|
|
}
|
|
if (values.help) {
|
|
process.stdout.write(HELP);
|
|
return;
|
|
}
|
|
const context = toInt('context', values.context);
|
|
const limit = toInt('limit', values.limit);
|
|
const { query, person, date } = values;
|
|
const print = (s = '') => process.stdout.write(`${s}\n`);
|
|
const printJson = (v) => print(JSON.stringify(v, null, 2));
|
|
|
|
// 0. Diagnóstico: só contagens, nenhum conteúdo de mensagem.
|
|
if (values['list-chats']) {
|
|
const summary = listChats(defaultTeamsProfile());
|
|
if (values.json) return printJson(summary);
|
|
print(`Perfil: ${summary.perfil}`);
|
|
print(`Conversas: ${summary.conversas}`);
|
|
print(`Mensagens (com texto): ${summary.mensagens}`);
|
|
for (const c of summary.por_conversa) print(` ${c.chat} ${c.mensagens}`);
|
|
return;
|
|
}
|
|
|
|
// 1. Atas de reuniões.
|
|
if (values.atas) {
|
|
const meetingsDir = process.env.TEAMS_MEETINGS_DIR || null;
|
|
const meetings = getMeetingMinutes({ meetingsDir, query, dateFilter: date, limit });
|
|
if (values.json) return printJson(meetings);
|
|
print('\n=======================================================');
|
|
print(` 📋 ATAS EXECUTIVAS DE REUNIÕES (${meetings.length})`);
|
|
if (query) print(` Filtro de Assunto/Termo: ${query}`);
|
|
if (date) print(` Filtro de Data: ${date}`);
|
|
print(` Diretório: ${meetingsDir || '(TEAMS_MEETINGS_DIR não definida)'}`);
|
|
print('=======================================================\n');
|
|
if (!meetings.length) return print('Nenhuma ata de reunião encontrada com os critérios informados.');
|
|
meetings.forEach((m, i) => {
|
|
print(`${'#'.repeat(25)} REUNIÃO #${i + 1} ${'#'.repeat(25)}`);
|
|
print(`📁 Pasta: ${m.folder_name}`);
|
|
print(`🏷️ Título: ${m.title}`);
|
|
print(`🖼️ Screenshots anexos: ${m.screenshots_count}`);
|
|
print('\n--- CONTEÚDO DA ATA ---\n');
|
|
print(m.has_ata ? m.ata_content : '[Ata ainda em processamento ou áudio transcrito apenas]');
|
|
print(`\n${'='.repeat(70)}\n`);
|
|
});
|
|
return;
|
|
}
|
|
|
|
// 2. Mensagens e conversas do chat.
|
|
const results = getContextualizedConversations({
|
|
query, senderFilter: person, limit, contextDepth: context, profileDir: defaultTeamsProfile(),
|
|
});
|
|
if (values.json) return printJson(results);
|
|
print('\n=======================================================');
|
|
print(` CONVERSAS CONTEXTUALIZADAS (${results.length})`);
|
|
if (person) print(` Filtro Pessoa: ${person}`);
|
|
if (query) print(` Filtro Busca: ${query}`);
|
|
print(` Contexto: ±${context} mensagens dentro da mesma conversa`);
|
|
print('=======================================================\n');
|
|
const q = query?.toLowerCase();
|
|
const p = person?.toLowerCase();
|
|
results.forEach((item, i) => {
|
|
print(`\n${'#'.repeat(20)} CONVERSA #${i + 1} ${'#'.repeat(20)}`);
|
|
print(`Conversation ID: ${item.conversation_id}`);
|
|
print(`Total de mensagens carregadas: ${item.messages.length}`);
|
|
if (item.has_media) print('🔔 [MÍDIA/VÍDEO DETECTADO NESTA CONVERSA]');
|
|
print();
|
|
for (const m of item.messages) {
|
|
const hit = (q && m.raw_str.includes(q)) || (p && m.sender.toLowerCase().includes(p) && (!q || m.raw_str.includes(q)));
|
|
print(`${hit ? '>>> [MATCH]' : ' [CTX] '} ${m.ts_fmt} | ${m.sender}:`);
|
|
print(` ${m.text}`);
|
|
if (m.media.length) print(` 🎥 Mídia: ${JSON.stringify(m.media)}`);
|
|
if (m.attachments.length) print(` Anexos: ${m.attachments.join(', ')}`);
|
|
}
|
|
print(`\n${'='.repeat(70)}`);
|
|
});
|
|
}
|
|
|
|
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
|
try {
|
|
main();
|
|
} catch (e) {
|
|
process.stderr.write(`erro: ${e.message}\n`);
|
|
process.exit(1);
|
|
}
|
|
}
|