430 lines
18 KiB
Python
430 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
import sys
|
|
import os
|
|
import pathlib
|
|
import json
|
|
import re
|
|
import glob
|
|
import shutil
|
|
import tempfile
|
|
import argparse
|
|
import hashlib
|
|
from datetime import datetime
|
|
|
|
# Setup imports
|
|
SCRIPT_DIR = pathlib.Path(__file__).resolve().parent
|
|
sys.path.insert(0, str(SCRIPT_DIR / 'ccl_simplesnappy'))
|
|
sys.path.insert(0, str(SCRIPT_DIR / 'ccl_chromium_reader'))
|
|
|
|
from ccl_chromium_reader import ccl_chromium_indexeddb
|
|
|
|
# Caminho do perfil WebView2 do Teams (novo) a partir de %LOCALAPPDATA%.
|
|
TEAMS_PROFILE_SUFFIX = pathlib.PurePosixPath(
|
|
'Packages/MSTeams_8wekyb3d8bbwe/LocalCache/Microsoft/MSTeams/EBWebView/WV2Profile_tfw'
|
|
)
|
|
|
|
|
|
def default_teams_profile() -> pathlib.Path:
|
|
"""Detecta o perfil do Teams: TEAMS_PROFILE_DIR > Windows nativo (%LOCALAPPDATA%) > WSL (/mnt/c/Users/*)."""
|
|
override = os.environ.get('TEAMS_PROFILE_DIR')
|
|
if override:
|
|
return pathlib.Path(override)
|
|
if os.name == 'nt':
|
|
local_appdata = os.environ.get('LOCALAPPDATA')
|
|
base = pathlib.Path(local_appdata) if local_appdata else pathlib.Path.home() / 'AppData' / 'Local'
|
|
return base.joinpath(*TEAMS_PROFILE_SUFFIX.parts)
|
|
found = sorted(pathlib.Path('/mnt/c/Users').glob(str(pathlib.PurePosixPath('*', 'AppData', 'Local') / TEAMS_PROFILE_SUFFIX)))
|
|
if found:
|
|
return found[0]
|
|
return pathlib.Path('/mnt/c/Users/<usuario>/AppData/Local') / TEAMS_PROFILE_SUFFIX
|
|
|
|
|
|
TEAMS_PROFILE_DEFAULT = default_teams_profile()
|
|
# Cópia de trabalho do LevelDB no temporário do sistema (/tmp no Linux/WSL, %TEMP% no Windows).
|
|
CACHE_DIR = pathlib.Path(tempfile.gettempdir()) / 'teams_indexeddb_sync'
|
|
# Pasta de atas: só via TEAMS_MEETINGS_DIR; sem ela, a busca de atas é pulada com aviso.
|
|
MEETINGS_DIR = pathlib.Path(os.environ['TEAMS_MEETINGS_DIR']) if os.environ.get('TEAMS_MEETINGS_DIR') else None
|
|
|
|
|
|
def warn(msg):
|
|
print(f"[aviso] {msg}", file=sys.stderr)
|
|
|
|
|
|
def sync_db(profile_dir: pathlib.Path):
|
|
src_db = profile_dir / 'IndexedDB' / 'https_teams.microsoft.com_0.indexeddb.leveldb'
|
|
if not src_db.exists():
|
|
raise FileNotFoundError(f"Caminho do banco LevelDB do Teams não encontrado: {src_db}")
|
|
|
|
# O Teams aberto segura o arquivo LOCK do LevelDB; por isso a leitura é feita numa cópia,
|
|
# sem o LOCK. Equivale ao antigo `rsync -a --exclude=LOCK` (sem apagar arquivos antigos da cópia).
|
|
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
try:
|
|
shutil.copytree(src_db, CACHE_DIR, ignore=shutil.ignore_patterns('LOCK'), dirs_exist_ok=True)
|
|
except shutil.Error as e:
|
|
failed = e.args[0] if e.args and isinstance(e.args[0], list) else []
|
|
warn(f"{len(failed)} arquivo(s) do cache do Teams não puderam ser copiados (bloqueados?); "
|
|
f"a leitura segue com o que foi copiado.")
|
|
except OSError as e:
|
|
warn(f"falha ao copiar o cache do Teams: {e}; a leitura segue com o que já estiver em {CACHE_DIR}.")
|
|
return CACHE_DIR
|
|
|
|
def clean_html(raw):
|
|
if isinstance(raw, bytes):
|
|
raw = raw.decode('utf-8', errors='ignore')
|
|
if not isinstance(raw, str):
|
|
return ""
|
|
text = re.sub(r'<blockquote.*?</blockquote>', ' [Citação] ', raw, flags=re.DOTALL)
|
|
text = re.sub(r'<img.*?src=["\'](.*?)["\'].*?>', r' [Imagem: \1] ', text)
|
|
text = re.sub(r'<.*?>', '', text)
|
|
text = text.replace(' ', ' ').replace(' ', ' ').replace('&', '&').replace('<', '<').replace('>', '>')
|
|
return re.sub(r'\s+', ' ', text).strip()
|
|
|
|
def parse_ts(ts):
|
|
if not ts:
|
|
return 0, "N/A"
|
|
try:
|
|
val = float(ts)
|
|
val_sec = val / 1000.0 if val > 1e11 else val
|
|
dt = datetime.fromtimestamp(val_sec)
|
|
return val, dt.strftime('%d/%m/%Y %H:%M:%S')
|
|
except:
|
|
return 0, str(ts)
|
|
|
|
def detect_media_assets(msg_dict, raw_content):
|
|
media = []
|
|
msg_type = str(msg_dict.get('messageType', ''))
|
|
|
|
if 'Media_CallRecording' in msg_type or 'CallRecording' in str(msg_dict):
|
|
media.append({'type': 'recording', 'desc': 'Gravação de Reunião do Teams'})
|
|
elif 'Audio' in msg_type or 'audio' in msg_type.lower():
|
|
media.append({'type': 'audio', 'desc': 'Mensagem de Áudio / Chamada de Voz'})
|
|
elif 'Video' in msg_type or 'video' in msg_type.lower():
|
|
media.append({'type': 'video', 'desc': 'Vídeo / Clipe de Vídeo'})
|
|
|
|
links = re.findall(r'(https?://[^\s<>"\']+)', str(raw_content) + " " + str(msg_dict))
|
|
for link in links:
|
|
if any(term in link.lower() for term in ['stream.aspx', 'iqcok', 'recording', '.mp4', '.m4a', '.mp3', '.wav']):
|
|
media.append({'type': 'media_link', 'url': link, 'desc': 'Link de Gravação/Mídia'})
|
|
|
|
return media
|
|
|
|
def iter_messages(profile_dir):
|
|
"""Percorre as mensagens do cache: (conversationId, id da mensagem, dict, conteúdo bruto, texto limpo).
|
|
|
|
Só mensagens com texto não vazio depois do clean_html — o mesmo critério da busca, compartilhado
|
|
pela busca e pelo --list-chats para que as contagens batam com o que a busca consegue achar.
|
|
"""
|
|
db_dir = sync_db(profile_dir)
|
|
wrapper = ccl_chromium_indexeddb.WrappedIndexDB(db_dir)
|
|
for db_id in wrapper.database_ids:
|
|
db = wrapper[db_id]
|
|
if 'replychain-manager' in db.name and 'metadata' not in db.name and 'streams' not in db.name:
|
|
for s in db.object_store_names:
|
|
store = db[s]
|
|
for record in store.iterate_records():
|
|
try:
|
|
chain_data = record.value
|
|
if not isinstance(chain_data, dict):
|
|
continue
|
|
conv_id = chain_data.get('conversationId') or 'geral'
|
|
msg_map = chain_data.get('messageMap', {})
|
|
for m_id, data in msg_map.items():
|
|
if not isinstance(data, dict):
|
|
continue
|
|
raw_content = data.get('content', '')
|
|
text = clean_html(raw_content)
|
|
if not text:
|
|
continue
|
|
yield conv_id, m_id, data, raw_content, text
|
|
except Exception:
|
|
continue
|
|
|
|
|
|
def list_chats(profile_dir=TEAMS_PROFILE_DEFAULT):
|
|
"""Modo de diagnóstico: só contagens. Não devolve texto, remetente, participante nem conversationId.
|
|
|
|
O conversationId 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, não reversível na prática).
|
|
"""
|
|
counts = {}
|
|
for conv_id, _m_id, _data, _raw, _text in iter_messages(profile_dir):
|
|
counts[conv_id] = counts.get(conv_id, 0) + 1
|
|
chats = [
|
|
{'chat': hashlib.sha256(str(c).encode('utf-8')).hexdigest()[:12], 'mensagens': n}
|
|
for c, n in counts.items()
|
|
]
|
|
chats.sort(key=lambda x: x['mensagens'], reverse=True)
|
|
return {
|
|
'perfil': str(profile_dir),
|
|
'conversas': len(chats),
|
|
'mensagens': sum(c['mensagens'] for c in chats),
|
|
'por_conversa': chats,
|
|
}
|
|
|
|
|
|
def get_contextualized_conversations(query=None, sender_filter=None, limit=3, context_depth=15, profile_dir=TEAMS_PROFILE_DEFAULT):
|
|
all_conversations = {}
|
|
|
|
for conv_id, m_id, data, raw_content, text in iter_messages(profile_dir):
|
|
try:
|
|
sender = (
|
|
data.get('imDisplayName') or
|
|
data.get('fromDisplayNameInToken') or
|
|
data.get('imdisplayname') or
|
|
data.get('from') or
|
|
data.get('creator') or
|
|
'Desconhecido'
|
|
)
|
|
|
|
ts_val = data.get('clientArrivalTime') or data.get('originalArrivalTime') or data.get('composeTime')
|
|
ts_raw, ts_fmt = parse_ts(ts_val)
|
|
|
|
media = detect_media_assets(data, raw_content)
|
|
|
|
attachments = []
|
|
for att in data.get('attachments', []):
|
|
if isinstance(att, dict) and 'name' in att:
|
|
attachments.append(att['name'])
|
|
|
|
msg_item = {
|
|
'id': str(m_id),
|
|
'conversation_id': conv_id,
|
|
'sender': str(sender),
|
|
'text': text,
|
|
'ts_raw': ts_raw,
|
|
'ts_fmt': ts_fmt,
|
|
'media': media,
|
|
'attachments': attachments,
|
|
'raw_str': (text + " " + str(sender)).lower()
|
|
}
|
|
|
|
if conv_id not in all_conversations:
|
|
all_conversations[conv_id] = []
|
|
all_conversations[conv_id].append(msg_item)
|
|
except Exception:
|
|
continue
|
|
|
|
for c_id in all_conversations:
|
|
all_conversations[c_id].sort(key=lambda x: x['ts_raw'])
|
|
|
|
matched_conversations = {}
|
|
|
|
for conv_id, msgs in all_conversations.items():
|
|
hit_indices = []
|
|
for idx, m in enumerate(msgs):
|
|
is_match = False
|
|
|
|
if sender_filter and sender_filter.lower() in m['sender'].lower():
|
|
if query and query.lower() in m['raw_str']:
|
|
is_match = True
|
|
elif not query:
|
|
is_match = True
|
|
elif not sender_filter and query and query.lower() in m['raw_str']:
|
|
is_match = True
|
|
|
|
if is_match:
|
|
hit_indices.append(idx)
|
|
|
|
if hit_indices:
|
|
matched_conversations[conv_id] = (msgs, hit_indices)
|
|
|
|
expanded_results = []
|
|
|
|
for conv_id, (conv_msgs, hit_indices) in matched_conversations.items():
|
|
included_indices = set()
|
|
for h_idx in hit_indices:
|
|
start = max(0, h_idx - context_depth)
|
|
end = min(len(conv_msgs), h_idx + context_depth + 1)
|
|
for i in range(start, end):
|
|
included_indices.add(i)
|
|
|
|
convo_block = [conv_msgs[idx] for idx in sorted(included_indices)]
|
|
has_media = any(len(m['media']) > 0 for m in convo_block)
|
|
|
|
expanded_results.append({
|
|
'conversation_id': conv_id,
|
|
'messages': convo_block,
|
|
'has_media': has_media,
|
|
'last_timestamp': convo_block[-1]['ts_raw'] if convo_block else 0
|
|
})
|
|
|
|
expanded_results.sort(key=lambda x: x['last_timestamp'], reverse=True)
|
|
return expanded_results[:limit]
|
|
|
|
def get_meeting_minutes(query=None, date_filter=None, limit=5):
|
|
if MEETINGS_DIR is None:
|
|
warn("TEAMS_MEETINGS_DIR não definida; a busca de atas foi pulada.")
|
|
return []
|
|
if not MEETINGS_DIR.exists():
|
|
warn(f"pasta de atas não encontrada ({MEETINGS_DIR}); a busca de atas foi pulada.")
|
|
return []
|
|
|
|
meetings = []
|
|
meeting_folders = sorted(glob.glob(str(MEETINGS_DIR / "*")), reverse=True)
|
|
|
|
for folder in meeting_folders:
|
|
folder_path = pathlib.Path(folder)
|
|
if not folder_path.is_dir():
|
|
continue
|
|
|
|
folder_name = folder_path.name
|
|
date_part = folder_name.split("_")[0] if "_" in folder_name else ""
|
|
|
|
if date_filter and date_filter not in folder_name:
|
|
continue
|
|
|
|
ata_file = folder_path / "ata_reuniao.md"
|
|
transcricao_file = folder_path / "transcricao.md"
|
|
|
|
ata_content = ""
|
|
transcricao_snippet = ""
|
|
title = folder_name
|
|
|
|
if ata_file.exists():
|
|
try:
|
|
with open(ata_file, "r", encoding="utf-8") as f:
|
|
ata_content = f.read()
|
|
first_line = ata_content.strip().split("\n")[0].replace("#", "").strip()
|
|
if first_line:
|
|
title = first_line
|
|
except Exception:
|
|
pass
|
|
|
|
if transcricao_file.exists():
|
|
try:
|
|
with open(transcricao_file, "r", encoding="utf-8") as f:
|
|
transcricao_snippet = f.read()[:2000]
|
|
except Exception:
|
|
pass
|
|
|
|
combined_text = (title + " " + ata_content + " " + transcricao_snippet).lower()
|
|
if query and query.lower() not in combined_text:
|
|
continue
|
|
|
|
meetings.append({
|
|
"folder_name": folder_name,
|
|
"folder_path": str(folder_path),
|
|
"date": date_part,
|
|
"title": title,
|
|
"has_ata": bool(ata_content),
|
|
"ata_content": ata_content,
|
|
"transcricao_file": str(transcricao_file) if transcricao_file.exists() else None,
|
|
"screenshots_count": len(glob.glob(str(folder_path / "screenshots" / "*.jpg")))
|
|
})
|
|
|
|
if len(meetings) >= limit:
|
|
break
|
|
|
|
return meetings
|
|
|
|
def main():
|
|
# No Windows, com a saída capturada (pipe), o Python usa cp1252 e os emojis abaixo quebrariam.
|
|
for stream in (sys.stdout, sys.stderr):
|
|
if hasattr(stream, 'reconfigure'):
|
|
stream.reconfigure(encoding='utf-8', errors='replace')
|
|
|
|
parser = argparse.ArgumentParser(description="Teams Local Reader with Meeting Minutes (Atas) & Media Support")
|
|
parser.add_argument("--query", "-q", help="Termo de busca nas mensagens ou atas", default=None)
|
|
parser.add_argument("--person", "-p", help="Nome da pessoa / remetente para filtrar no chat", default=None)
|
|
parser.add_argument("--date", "-d", help="Filtrar por data (ex: 2026-09-02)", default=None)
|
|
parser.add_argument("--atas", "-a", action="store_true", help="Buscar e exibir diretamente as Atas Executivas de Reuniões")
|
|
parser.add_argument("--context", "-c", help="Quantas mensagens antes e depois trazer na conversa", type=int, default=15)
|
|
parser.add_argument("--limit", "-l", help="Quantidade máxima de resultados", type=int, default=3)
|
|
parser.add_argument("--json", action="store_true", help="Saída em formato JSON")
|
|
parser.add_argument("--list-chats", action="store_true",
|
|
help="Diagnóstico/teste: só o perfil detectado e contagens (conversas, mensagens e, por conversa, "
|
|
"um hash do id + contagem). Não imprime texto, remetente, participante nem id da conversa")
|
|
|
|
args = parser.parse_args()
|
|
|
|
# 0. Modo de diagnóstico: só contagens, nenhum conteúdo de mensagem.
|
|
if args.list_chats:
|
|
summary = list_chats()
|
|
if args.json:
|
|
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
|
return
|
|
print(f"Perfil: {summary['perfil']}")
|
|
print(f"Conversas: {summary['conversas']}")
|
|
print(f"Mensagens (com texto): {summary['mensagens']}")
|
|
for c in summary['por_conversa']:
|
|
print(f" {c['chat']} {c['mensagens']}")
|
|
return
|
|
|
|
# 1. Modo de Busca de Atas de Reuniões
|
|
if args.atas:
|
|
meetings = get_meeting_minutes(query=args.query, date_filter=args.date, limit=args.limit)
|
|
if args.json:
|
|
print(json.dumps(meetings, ensure_ascii=False, indent=2))
|
|
return
|
|
|
|
print(f"\n=======================================================")
|
|
print(f" 📋 ATAS EXECUTIVAS DE REUNIÕES ({len(meetings)})")
|
|
if args.query:
|
|
print(f" Filtro de Assunto/Termo: {args.query}")
|
|
if args.date:
|
|
print(f" Filtro de Data: {args.date}")
|
|
print(f" Diretório: {MEETINGS_DIR if MEETINGS_DIR else '(TEAMS_MEETINGS_DIR não definida)'}")
|
|
print(f"=======================================================\n")
|
|
|
|
if not meetings:
|
|
print("Nenhuma ata de reunião encontrada com os critérios informados.")
|
|
return
|
|
|
|
for idx, m in enumerate(meetings, 1):
|
|
print(f"{'#' * 25} REUNIÃO #{idx} {'#' * 25}")
|
|
print(f"📁 Pasta: {m['folder_name']}")
|
|
print(f"🏷️ Título: {m['title']}")
|
|
print(f"🖼️ Screenshots anexos: {m['screenshots_count']}")
|
|
print(f"\n--- CONTEÚDO DA ATA ---\n")
|
|
print(m['ata_content'] if m['has_ata'] else "[Ata ainda em processamento ou áudio transcrito apenas]")
|
|
print("\n" + "=" * 70 + "\n")
|
|
return
|
|
|
|
# 2. Modo de Busca de Mensagens e Conversas no Chat
|
|
results = get_contextualized_conversations(
|
|
query=args.query,
|
|
sender_filter=args.person,
|
|
limit=args.limit,
|
|
context_depth=args.context
|
|
)
|
|
|
|
if args.json:
|
|
print(json.dumps(results, ensure_ascii=False, indent=2))
|
|
return
|
|
|
|
print(f"\n=======================================================")
|
|
print(f" CONVERSAS CONTEXTUALIZADAS ({len(results)})")
|
|
if args.person:
|
|
print(f" Filtro Pessoa: {args.person}")
|
|
if args.query:
|
|
print(f" Filtro Busca: {args.query}")
|
|
print(f" Contexto: ±{args.context} mensagens dentro da mesma conversa")
|
|
print(f"=======================================================\n")
|
|
|
|
for t_idx, item in enumerate(results, 1):
|
|
print(f"\n{'#' * 20} CONVERSA #{t_idx} {'#' * 20}")
|
|
print(f"Conversation ID: {item['conversation_id']}")
|
|
print(f"Total de mensagens carregadas: {len(item['messages'])}")
|
|
if item['has_media']:
|
|
print(f"🔔 [MÍDIA/VÍDEO DETECTADO NESTA CONVERSA]")
|
|
print()
|
|
|
|
for m in item['messages']:
|
|
is_hit = False
|
|
if args.query and args.query.lower() in m['raw_str']:
|
|
is_hit = True
|
|
if args.person and args.person.lower() in m['sender'].lower() and (not args.query or args.query.lower() in m['raw_str']):
|
|
is_hit = True
|
|
|
|
prefix = ">>> [MATCH]" if is_hit else " [CTX] "
|
|
print(f"{prefix} {m['ts_fmt']} | {m['sender']}:")
|
|
print(f" {m['text']}")
|
|
if m['media']:
|
|
print(f" 🎥 Mídia: {m['media']}")
|
|
if m['attachments']:
|
|
print(f" Anexos: {', '.join(m['attachments'])}")
|
|
print("\n" + "=" * 70)
|
|
|
|
if __name__ == '__main__':
|
|
main()
|