| 1 | #!/usr/bin/env python3 |
| 2 | """Cliente Gmail genérico para skills de email-triage creadas por ClonAgent. |
| 3 | |
| 4 | Lee la lista de remitentes autorizados desde `config.json` (mismo directorio), |
| 5 | así puede ser editada en caliente sin tocar este archivo. |
| 6 | |
| 7 | Subcomandos: |
| 8 | auth Flujo OAuth (1ª vez) |
| 9 | list-unread [--days N] Threads no leídos de remitentes autorizados |
| 10 | get-thread <thread_id> Thread completo (JSON) |
| 11 | reply <thread_id> --body-file FILE Responder en el thread con CC a todos |
| 12 | mark-read <thread_id> Quitar UNREAD |
| 13 | add-label <thread_id> <label> Añadir etiqueta (la crea si no existe) |
| 14 | remove-label <thread_id> <label> Quitar etiqueta |
| 15 | """ |
| 16 | from __future__ import annotations |
| 17 | |
| 18 | import argparse |
| 19 | import base64 |
| 20 | import json |
| 21 | import os |
| 22 | import sys |
| 23 | from email.mime.text import MIMEText |
| 24 | from pathlib import Path |
| 25 | |
| 26 | from google.auth.transport.requests import Request |
| 27 | from google.oauth2.credentials import Credentials |
| 28 | from google_auth_oauthlib.flow import InstalledAppFlow |
| 29 | from googleapiclient.discovery import build |
| 30 | from googleapiclient.errors import HttpError |
| 31 | |
| 32 | SKILL_DIR = Path(__file__).parent |
| 33 | CREDENTIALS_FILE = SKILL_DIR / 'credentials.json' |
| 34 | TOKEN_FILE = SKILL_DIR / 'token.json' |
| 35 | CONFIG_FILE = SKILL_DIR / 'config.json' |
| 36 | |
| 37 | SCOPES = [ |
| 38 | 'https://www.googleapis.com/auth/gmail.readonly', |
| 39 | 'https://www.googleapis.com/auth/gmail.send', |
| 40 | 'https://www.googleapis.com/auth/gmail.modify', |
| 41 | 'https://www.googleapis.com/auth/gmail.labels', |
| 42 | ] |
| 43 | |
| 44 | |
| 45 | def load_config() -> dict: |
| 46 | if not CONFIG_FILE.exists(): |
| 47 | print(f"❌ falta {CONFIG_FILE}", file=sys.stderr) |
| 48 | sys.exit(1) |
| 49 | return json.loads(CONFIG_FILE.read_text()) |
| 50 | |
| 51 | |
| 52 | def authorized_senders(): |
| 53 | """Devuelve [{email, role}, ...] (acepta strings legacy).""" |
| 54 | cfg = load_config() |
| 55 | raw = cfg.get('authorizedSenders') or [] |
| 56 | out = [] |
| 57 | for i, s in enumerate(raw): |
| 58 | if isinstance(s, str): |
| 59 | out.append({'email': s.lower(), 'role': 'owner' if i == 0 else 'reader'}) |
| 60 | elif isinstance(s, dict) and s.get('email'): |
| 61 | role = s.get('role') if s.get('role') in ('owner', 'cocreator', 'reader') else 'reader' |
| 62 | out.append({'email': s['email'].lower(), 'role': role}) |
| 63 | if not out: sys.exit("config.json sin authorizedSenders") |
| 64 | return out |
| 65 | |
| 66 | |
| 67 | def authorized_emails(): |
| 68 | return [s['email'] for s in authorized_senders()] |
| 69 | |
| 70 | |
| 71 | def role_for(email: str): |
| 72 | e = (email or '').lower() |
| 73 | if '<' in e and '>' in e: |
| 74 | e = e.split('<', 1)[1].split('>', 1)[0] |
| 75 | for s in authorized_senders(): |
| 76 | if s['email'] == e: return s['role'] |
| 77 | return None |
| 78 | |
| 79 | |
| 80 | def get_service(): |
| 81 | creds = None |
| 82 | if TOKEN_FILE.exists(): |
| 83 | creds = Credentials.from_authorized_user_file(str(TOKEN_FILE), SCOPES) |
| 84 | if creds and creds.valid: |
| 85 | return build('gmail', 'v1', credentials=creds, cache_discovery=False) |
| 86 | if creds and creds.expired and creds.refresh_token: |
| 87 | try: |
| 88 | creds.refresh(Request()) |
| 89 | TOKEN_FILE.write_text(creds.to_json()) |
| 90 | return build('gmail', 'v1', credentials=creds, cache_discovery=False) |
| 91 | except Exception as e: |
| 92 | print(f"⚠️ No pude refrescar el token: {e}", file=sys.stderr) |
| 93 | print(" Ejecuta: python3 gmail_client.py auth", file=sys.stderr) |
| 94 | sys.exit(1) |
| 95 | print("❌ No hay token válido. Ejecuta: python3 gmail_client.py auth", file=sys.stderr) |
| 96 | sys.exit(1) |
| 97 | |
| 98 | |
| 99 | def cmd_auth(_): |
| 100 | if not CREDENTIALS_FILE.exists(): |
| 101 | print(f"❌ Falta {CREDENTIALS_FILE}", file=sys.stderr) |
| 102 | print(" Sube las credenciales OAuth de Google Cloud aquí.", file=sys.stderr) |
| 103 | sys.exit(1) |
| 104 | flow = InstalledAppFlow.from_client_secrets_file(str(CREDENTIALS_FILE), SCOPES) |
| 105 | creds = flow.run_local_server(port=8765, open_browser=True, |
| 106 | success_message='OK. Vuelve al terminal.') |
| 107 | TOKEN_FILE.write_text(creds.to_json()) |
| 108 | os.chmod(TOKEN_FILE, 0o600) |
| 109 | profile = build('gmail', 'v1', credentials=creds).users().getProfile(userId='me').execute() |
| 110 | print(json.dumps({'ok': True, 'authenticated_as': profile.get('emailAddress')})) |
| 111 | |
| 112 | |
| 113 | def _header(headers, name): |
| 114 | for h in headers: |
| 115 | if h['name'].lower() == name.lower(): return h['value'] |
| 116 | return '' |
| 117 | |
| 118 | |
| 119 | def cmd_list_unread(args): |
| 120 | service = get_service() |
| 121 | senders_query = ' OR '.join(f'from:{s["email"]}' for s in authorized_senders()) |
| 122 | skip = '-label:en-progreso-bot -label:procesado-bot -label:pendiente-revision-humana' |
| 123 | query = f'in:inbox is:unread {skip} ({senders_query})' |
| 124 | if args.days: query += f' newer_than:{args.days}d' |
| 125 | result = service.users().threads().list(userId='me', q=query, maxResults=20).execute() |
| 126 | out = [] |
| 127 | for t in result.get('threads', []): |
| 128 | full = service.users().threads().get(userId='me', id=t['id'], format='metadata', |
| 129 | metadataHeaders=['Subject','From','Date']).execute() |
| 130 | msgs = full.get('messages', []) |
| 131 | if not msgs: continue |
| 132 | last = msgs[-1] |
| 133 | headers = last.get('payload', {}).get('headers', []) |
| 134 | from_ = _header(headers, 'From') |
| 135 | out.append({ |
| 136 | 'thread_id': t['id'], |
| 137 | 'last_message_id': last['id'], |
| 138 | 'subject': _header(headers,'Subject'), |
| 139 | 'from': from_, |
| 140 | 'sender_role': role_for(from_), |
| 141 | 'date': _header(headers,'Date'), |
| 142 | 'snippet': last.get('snippet',''), |
| 143 | 'message_count': len(msgs), |
| 144 | }) |
| 145 | print(json.dumps(out, ensure_ascii=False, indent=2)) |
| 146 | |
| 147 | |
| 148 | def _decode(part): |
| 149 | body = part.get('body', {}); data = body.get('data') |
| 150 | return base64.urlsafe_b64decode(data).decode('utf-8','replace') if data else '' |
| 151 | |
| 152 | |
| 153 | def _extract_body(payload): |
| 154 | if payload.get('mimeType','').startswith('text/plain'): return _decode(payload) |
| 155 | parts = payload.get('parts', []) |
| 156 | for p in parts: |
| 157 | if p.get('mimeType','').startswith('text/plain'): return _decode(p) |
| 158 | for p in parts: |
| 159 | if p.get('mimeType','').startswith('text/html'): return _decode(p) |
| 160 | for p in parts: |
| 161 | if p.get('parts'): |
| 162 | sub = _extract_body(p) |
| 163 | if sub: return sub |
| 164 | return '' |
| 165 | |
| 166 | |
| 167 | def cmd_get_thread(args): |
| 168 | service = get_service() |
| 169 | thread = service.users().threads().get(userId='me', id=args.thread_id, format='full').execute() |
| 170 | out = {'thread_id': thread['id'], 'messages': []} |
| 171 | for msg in thread.get('messages', []): |
| 172 | headers = msg.get('payload', {}).get('headers', []) |
| 173 | out['messages'].append({ |
| 174 | 'message_id': msg['id'], |
| 175 | 'subject': _header(headers,'Subject'), |
| 176 | 'from': _header(headers,'From'), |
| 177 | 'to': _header(headers,'To'), |
| 178 | 'cc': _header(headers,'Cc'), |
| 179 | 'date': _header(headers,'Date'), |
| 180 | 'message_id_header': _header(headers,'Message-ID'), |
| 181 | 'in_reply_to': _header(headers,'In-Reply-To'), |
| 182 | 'references': _header(headers,'References'), |
| 183 | 'body': _extract_body(msg.get('payload', {})), |
| 184 | 'snippet': msg.get('snippet',''), |
| 185 | 'labels': msg.get('labelIds', []), |
| 186 | }) |
| 187 | print(json.dumps(out, ensure_ascii=False, indent=2)) |
| 188 | |
| 189 | |
| 190 | def _email(field): |
| 191 | if not field: return '' |
| 192 | if '<' in field and '>' in field: |
| 193 | return field.split('<',1)[1].split('>',1)[0].strip().lower() |
| 194 | return field.strip().lower() |
| 195 | |
| 196 | |
| 197 | def cmd_reply(args): |
| 198 | service = get_service() |
| 199 | thread = service.users().threads().get(userId='me', id=args.thread_id, format='metadata', |
| 200 | metadataHeaders=['Subject','From','Message-ID','References']).execute() |
| 201 | msgs = thread.get('messages', []) |
| 202 | if not msgs: |
| 203 | print("❌ Thread vacío", file=sys.stderr); sys.exit(1) |
| 204 | last = msgs[-1]; headers = last.get('payload',{}).get('headers',[]) |
| 205 | from_ = _email(_header(headers,'From')) |
| 206 | subj = _header(headers,'Subject') |
| 207 | msgid = _header(headers,'Message-ID') |
| 208 | refs = _header(headers,'References') |
| 209 | |
| 210 | to = args.to or from_ |
| 211 | cc = args.cc.split(',') if args.cc else [e for e in authorized_emails() if e != to] |
| 212 | |
| 213 | if args.body_file: body = Path(args.body_file).read_text('utf-8') |
| 214 | elif args.body: body = args.body |
| 215 | else: body = sys.stdin.read() |
| 216 | subject = args.subject or subj |
| 217 | if subject and not subject.lower().startswith('re:'): subject = f'Re: {subject}' |
| 218 | |
| 219 | msg = MIMEText(body, 'plain', 'utf-8') |
| 220 | msg['To'] = to |
| 221 | if cc: msg['Cc'] = ', '.join(cc) |
| 222 | msg['Subject'] = subject |
| 223 | if msgid: |
| 224 | msg['In-Reply-To'] = msgid |
| 225 | msg['References'] = f'{refs} {msgid}' if refs else msgid |
| 226 | |
| 227 | raw = base64.urlsafe_b64encode(msg.as_bytes()).decode('utf-8') |
| 228 | sent = service.users().messages().send(userId='me', |
| 229 | body={'raw': raw, 'threadId': args.thread_id}).execute() |
| 230 | print(json.dumps({'sent':True,'message_id':sent.get('id'),'thread_id':sent.get('threadId'), |
| 231 | 'to':to,'cc':cc,'subject':subject}, ensure_ascii=False, indent=2)) |
| 232 | |
| 233 | |
| 234 | def cmd_mark_read(args): |
| 235 | get_service().users().threads().modify(userId='me', id=args.thread_id, |
| 236 | body={'removeLabelIds': ['UNREAD']}).execute() |
| 237 | print(json.dumps({'thread_id': args.thread_id, 'marked_read': True})) |
| 238 | |
| 239 | |
| 240 | def _label_id(service, name): |
| 241 | for l in service.users().labels().list(userId='me').execute().get('labels', []): |
| 242 | if l['name'].lower() == name.lower(): return l['id'] |
| 243 | created = service.users().labels().create(userId='me', body={ |
| 244 | 'name': name, 'labelListVisibility': 'labelShow', 'messageListVisibility': 'show', |
| 245 | }).execute() |
| 246 | return created['id'] |
| 247 | |
| 248 | |
| 249 | def cmd_add_label(args): |
| 250 | service = get_service() |
| 251 | lid = _label_id(service, args.label) |
| 252 | service.users().threads().modify(userId='me', id=args.thread_id, |
| 253 | body={'addLabelIds': [lid]}).execute() |
| 254 | print(json.dumps({'thread_id': args.thread_id, 'label_added': args.label})) |
| 255 | |
| 256 | |
| 257 | def cmd_remove_label(args): |
| 258 | service = get_service() |
| 259 | lid = None |
| 260 | for l in service.users().labels().list(userId='me').execute().get('labels', []): |
| 261 | if l['name'].lower() == args.label.lower(): lid = l['id']; break |
| 262 | if not lid: |
| 263 | print(json.dumps({'thread_id': args.thread_id, 'label_removed': args.label, 'noop': True})); return |
| 264 | service.users().threads().modify(userId='me', id=args.thread_id, |
| 265 | body={'removeLabelIds': [lid]}).execute() |
| 266 | print(json.dumps({'thread_id': args.thread_id, 'label_removed': args.label})) |
| 267 | |
| 268 | |
| 269 | def main(): |
| 270 | p = argparse.ArgumentParser(description='Gmail client (ClonAgent template)') |
| 271 | sub = p.add_subparsers(dest='cmd', required=True) |
| 272 | sub.add_parser('auth') |
| 273 | pl = sub.add_parser('list-unread'); pl.add_argument('--days', type=int, default=7) |
| 274 | pg = sub.add_parser('get-thread'); pg.add_argument('thread_id') |
| 275 | pr = sub.add_parser('reply'); pr.add_argument('thread_id') |
| 276 | pr.add_argument('--body'); pr.add_argument('--body-file'); pr.add_argument('--subject') |
| 277 | pr.add_argument('--to'); pr.add_argument('--cc') |
| 278 | pm = sub.add_parser('mark-read'); pm.add_argument('thread_id') |
| 279 | pa = sub.add_parser('add-label'); pa.add_argument('thread_id'); pa.add_argument('label') |
| 280 | px = sub.add_parser('remove-label'); px.add_argument('thread_id'); px.add_argument('label') |
| 281 | args = p.parse_args() |
| 282 | handlers = {'auth':cmd_auth,'list-unread':cmd_list_unread,'get-thread':cmd_get_thread, |
| 283 | 'reply':cmd_reply,'mark-read':cmd_mark_read, |
| 284 | 'add-label':cmd_add_label,'remove-label':cmd_remove_label} |
| 285 | try: handlers[args.cmd](args) |
| 286 | except HttpError as e: |
| 287 | print(f"❌ Error API Gmail: {e}", file=sys.stderr); sys.exit(2) |
| 288 | |
| 289 | |
| 290 | if __name__ == '__main__': |
| 291 | main() |