672 lines
28 KiB
Python
672 lines
28 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
Moodle Replicator: Exportación de Datos de Moodle Producción a Entorno Local.
|
|
Replica usuarios, carreras, materias y matriculaciones desde Moodle UniCABA (Producción)
|
|
hacia el Moodle Local (10.0.0.207) para pruebas con Admin Edu Space.
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import re
|
|
import json
|
|
import argparse
|
|
import unicodedata
|
|
from typing import Dict, List, Any, Optional
|
|
import requests
|
|
|
|
# Mapa de correspondencia oficial entre Producción y Local
|
|
COURSE_MAPPING = {
|
|
# Carrera y Escuela
|
|
922: {
|
|
'name': 'Mi carrera - Lic. en Tecnologías Digitales (CCC)',
|
|
'shortname': 'Mi carrera - Lic. en Tecnologías Digitales (CCC)',
|
|
'local_id': 19,
|
|
'type': 'career'
|
|
},
|
|
187: {
|
|
'name': 'Escuela de Tecnología e Industrias Digitales (Sala de estudiantes)',
|
|
'shortname': 'Sala de estudiantes',
|
|
'local_id': 3,
|
|
'type': 'faculty'
|
|
},
|
|
# Cuatrimestre 1/2025
|
|
3218: {
|
|
'name': 'ASIG00120 - Gestión de Sistemas de Información_1/2025',
|
|
'shortname': 'ASIG00120 - Gestión de Sistemas de Información_1/2025',
|
|
'local_id': 4,
|
|
'type': 'subject'
|
|
},
|
|
3220: {
|
|
'name': 'ASIG00121 - Análisis de Datos I - TEC.DIG._1/2025',
|
|
'shortname': 'ASIG00121 - Análisis de Datos I - TEC.DIG._1/2025',
|
|
'local_id': 5,
|
|
'type': 'subject'
|
|
},
|
|
3221: {
|
|
'name': 'ASIG00122 - Taller: Gestión de Proyectos Digitales - E1_1/2025',
|
|
'shortname': 'ASIG00122 - Taller: Gestión de Proyectos Digitales - E1_1/2025',
|
|
'local_id': 6,
|
|
'type': 'subject'
|
|
},
|
|
3665: {
|
|
'name': 'ASIG00215 - Marketing Digital - OPTATIVA -1/2025',
|
|
'shortname': 'ASIG00215 - Marketing Digital - OPTATIVA -1/2025',
|
|
'local_id': 7,
|
|
'type': 'subject'
|
|
},
|
|
# Cuatrimestre 2/2025
|
|
3945: {
|
|
'name': 'ASIG00123 - Administración de Negocios Digitales_2/2025',
|
|
'shortname': 'ASIG00123 - Administración de Negocios Digitales_2/2025',
|
|
'local_id': 8,
|
|
'type': 'subject'
|
|
},
|
|
3944: {
|
|
'name': 'ASIG00124 - Sistemas Digitales_2/2025',
|
|
'shortname': 'ASIG00124 - Sistemas Digitales_2/2025',
|
|
'local_id': 9,
|
|
'type': 'subject'
|
|
},
|
|
3943: {
|
|
'name': 'ASIG00125 - Taller: Emprendedurismo en Innovación Digital_2/2025',
|
|
'shortname': 'ASIG00125 - Taller: Emprendedurismo en Innovación Digital_2/2025',
|
|
'local_id': 10,
|
|
'type': 'subject'
|
|
},
|
|
3933: {
|
|
'name': 'ASIG00205 - Gestión del Talento Humano en la Industria digital-2/2025',
|
|
'shortname': 'ASIG00205 - Gestión del Talento Humano en la Industria digital-2/2025',
|
|
'local_id': 11,
|
|
'type': 'subject'
|
|
},
|
|
# Cuatrimestre 1/2026
|
|
4565: {
|
|
'name': 'ASIG00121 - Análisis de Datos I - TEC.DIG._1/2026',
|
|
'shortname': 'ASIG00121 - Análisis de Datos I - TEC.DIG._1/2026',
|
|
'local_id': 12,
|
|
'type': 'subject'
|
|
},
|
|
4569: {
|
|
'name': 'ASIG00123 - Administración de Negocios Digitales_1/2026',
|
|
'shortname': 'ASIG00123 - Administración de Negocios Digitales_1/2026',
|
|
'local_id': 13,
|
|
'type': 'subject'
|
|
},
|
|
4571: {
|
|
'name': 'ASIG00125 - Taller: Emprendedurismo en Innovación Digital_1/2026',
|
|
'shortname': 'ASIG00125 - Taller: Emprendedurismo en Innovación Digital_1/2026',
|
|
'local_id': 14,
|
|
'type': 'subject'
|
|
},
|
|
4582: {
|
|
'name': 'ASIG00296 - Gestión de Redes Informáticas - Equipo 1_1/2026',
|
|
'shortname': 'ASIG00296 - Gestión de Redes Informáticas - Equipo 1_1/2026',
|
|
'local_id': 15,
|
|
'type': 'subject'
|
|
},
|
|
# Cuatrimestre 2/2026
|
|
5311: {
|
|
'name': 'ASIG00124 - Sistemas Digitales_2/2026',
|
|
'shortname': 'ASIG00124 - Sistemas Digitales_2/2026',
|
|
'local_id': 16,
|
|
'type': 'subject'
|
|
},
|
|
5313: {
|
|
'name': 'ASIG00126 - Seguridad de la Información_2/2026',
|
|
'shortname': 'ASIG00126 - Seguridad de la Información_2/2026',
|
|
'local_id': 17,
|
|
'type': 'subject'
|
|
},
|
|
5314: {
|
|
'name': 'ASIG00127 - Programación de Vanguardia - E1_2/2026',
|
|
'shortname': 'ASIG00127 - Programación de Vanguardia - E1_2/2026',
|
|
'local_id': 18,
|
|
'type': 'subject'
|
|
}
|
|
}
|
|
|
|
|
|
def slugify(text: str) -> str:
|
|
"""Normaliza texto para generar nombres de usuario o correos legibles."""
|
|
if not text:
|
|
return ""
|
|
text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8')
|
|
text = re.sub(r'[^\w\s-]', '', text.lower()).strip()
|
|
return re.sub(r'[-\s]+', '.', text)
|
|
|
|
|
|
def normalize_name(text: str) -> str:
|
|
"""Normaliza nombres eliminando acentos y espacios múltiples para matching robusto."""
|
|
if not text:
|
|
return ""
|
|
text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8')
|
|
return re.sub(r'\s+', ' ', text).strip().upper()
|
|
|
|
|
|
class CredentialsLoader:
|
|
"""Carga credenciales desde el archivo .credenciales."""
|
|
|
|
@staticmethod
|
|
def load(file_path: str = ".credenciales") -> Dict[str, str]:
|
|
creds = {
|
|
'prod_url': 'https://campus.udelaciudad.edu.ar',
|
|
'prod_user': '',
|
|
'prod_pass': '',
|
|
'local_url': 'http://10.0.0.207/moodle',
|
|
'local_token': '810428346d3601c68a37a315fcba8d4391629f46'
|
|
}
|
|
|
|
if not os.path.exists(file_path):
|
|
return creds
|
|
|
|
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
|
|
lines = f.readlines()
|
|
|
|
is_prod = False
|
|
is_token = False
|
|
for line in lines:
|
|
line_str = line.strip()
|
|
if "Login Moodle del Campus UniCABA en producción" in line_str:
|
|
is_prod = True
|
|
continue
|
|
if is_prod:
|
|
if line_str.startswith("user:"):
|
|
creds['prod_user'] = line_str.split(":", 1)[1].strip()
|
|
elif line_str.startswith("pass:"):
|
|
creds['prod_pass'] = line_str.split(":", 1)[1].strip()
|
|
if line_str.startswith("token:"):
|
|
creds['local_token'] = line_str.split(":", 1)[1].strip()
|
|
|
|
return creds
|
|
|
|
|
|
class MoodleProdExtractor:
|
|
"""Extrae participantes de Moodle Producción mediante sesión web y scraping híbrido."""
|
|
|
|
def __init__(self, base_url: str, user: str, password: str):
|
|
self.base_url = base_url.rstrip('/')
|
|
self.user = user
|
|
self.password = password
|
|
self.session = requests.Session()
|
|
self.session.headers.update({
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
|
|
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
'Accept-Language': 'es-AR,es;q=0.9',
|
|
})
|
|
self.authenticated = False
|
|
self.email_cache: Dict[int, str] = {}
|
|
# Pre-cargar correos previamente extraídos si existe participantes_export.json
|
|
if os.path.exists("participantes_export.json"):
|
|
try:
|
|
with open("participantes_export.json", encoding="utf-8") as f:
|
|
cached_data = json.load(f)
|
|
for cid, user_list in cached_data.items():
|
|
for u in user_list:
|
|
dni_str = str(u.get('dni', ''))
|
|
if dni_str.startswith('90') and len(dni_str) == 8 and dni_str[2:].isdigit():
|
|
mid = int(dni_str[2:])
|
|
if u.get('email') and not u['email'].endswith('@unicaba.edu.ar'):
|
|
self.email_cache[mid] = u['email']
|
|
elif str(u.get('dni')) == '34247025':
|
|
self.email_cache[34247025] = "carlostellocba@gmail.com"
|
|
print(f"[+] Precargados {len(self.email_cache)} correos reales desde caché local.")
|
|
except Exception as e:
|
|
print(f"[*] Aviso al cargar caché: {e}")
|
|
|
|
def fetch_real_emails(self, users: List[Dict[str, Any]], course_id: int) -> None:
|
|
"""Descarga de forma concurrente los correos electrónicos REALES desde los perfiles de Moodle Producción."""
|
|
to_fetch = [u for u in users if u.get('moodle_id') and u['moodle_id'] not in self.email_cache]
|
|
if to_fetch:
|
|
print(f"[*] Obteniendo correos electrónicos reales para {len(to_fetch)} participantes faltantes...")
|
|
|
|
def _get_single_email(uid: int):
|
|
url = f"{self.base_url}/user/view.php?id={uid}&course={course_id}"
|
|
try:
|
|
res = self.session.get(url, timeout=5)
|
|
if res.status_code == 200:
|
|
mailtos = [m for m in re.findall(r'mailto:([^"\'>\s]+)', res.text) if m not in ['info@udelaciudad.edu.ar', '.']]
|
|
if mailtos:
|
|
return uid, mailtos[0]
|
|
except Exception:
|
|
pass
|
|
return uid, None
|
|
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
with ThreadPoolExecutor(max_workers=15) as executor:
|
|
future_results = list(executor.map(_get_single_email, [u['moodle_id'] for u in to_fetch]))
|
|
|
|
for uid, email in future_results:
|
|
if email:
|
|
self.email_cache[uid] = email
|
|
|
|
found_count = sum(1 for _, em in future_results if em)
|
|
print(f"[+] Correos reales obtenidos: {found_count}/{len(to_fetch)} perfiles consultados.")
|
|
|
|
# Asignar correos reales a la lista de usuarios
|
|
for u in users:
|
|
uid = u.get('moodle_id')
|
|
if uid and uid in self.email_cache:
|
|
u['real_email'] = self.email_cache[uid]
|
|
|
|
def login(self) -> bool:
|
|
login_url = f"{self.base_url}/login/index.php"
|
|
print(f"[*] Obteniendo token de login de producción en {login_url}...")
|
|
res = self.session.get(login_url, timeout=25)
|
|
if res.status_code != 200:
|
|
print(f"[!] Error al acceder a la página de login: HTTP {res.status_code}")
|
|
return False
|
|
|
|
# Extraer logintoken
|
|
m = re.search(r'name=["\']logintoken["\']\s+value=["\']([^"\']+)["\']', res.text)
|
|
if not m:
|
|
m = re.search(r'value=["\']([^"\']+)["\']\s+name=["\']logintoken["\']', res.text)
|
|
if not m:
|
|
print("[!] No se encontró el 'logintoken' en la respuesta.")
|
|
return False
|
|
|
|
token = m.group(1)
|
|
|
|
payload = {
|
|
'username': self.user,
|
|
'password': self.password,
|
|
'logintoken': token
|
|
}
|
|
print(f"[*] Autenticando usuario '{self.user}' en Producción...")
|
|
post_res = self.session.post(login_url, data=payload, timeout=25, allow_redirects=True)
|
|
if "loginerrormessage" in post_res.text or ("Inicie sesión en su cuenta" in post_res.text and "my/" not in post_res.url):
|
|
print("[!] Falla de autenticación en Moodle de Producción. Verifique usuario/contraseña.")
|
|
return False
|
|
|
|
print("[+] Autenticación exitosa en Moodle Producción.")
|
|
self.authenticated = True
|
|
return True
|
|
|
|
def extract_course_participants(self, course_id: int) -> List[Dict[str, Any]]:
|
|
"""Extrae la lista completa de participantes para un curso de producción."""
|
|
if not self.authenticated:
|
|
raise RuntimeError("Debe autenticarse antes de extraer datos.")
|
|
|
|
# Paso 1: Acceder con perpage=5000 para cargar todos los participantes en una sola vista
|
|
url_all = f"{self.base_url}/user/index.php?page=0&perpage=5000&contextid=0&id={course_id}&newcourse"
|
|
print(f"[*] Descargando vista de participantes para curso Prod ID {course_id}...")
|
|
res = self.session.get(url_all, timeout=30)
|
|
if res.status_code != 200:
|
|
print(f"[!] Error al cargar curso {course_id}: HTTP {res.status_code}")
|
|
return []
|
|
|
|
# Extraer sesskey
|
|
m_sk = re.search(r'name=["\']sesskey["\']\s+value=["\']([^"\']+)["\']', res.text)
|
|
sesskey = m_sk.group(1) if m_sk else ""
|
|
|
|
# Extraer checkboxes de usuarios: id="user12345" name="user12345"
|
|
user_checkboxes = re.findall(r'<input[^>]+id=["\'](user\d+)["\'][^>]*>', res.text)
|
|
print(f"[+] Detectados {len(user_checkboxes)} participantes en la página del curso.")
|
|
|
|
# Paso 2: Intentar descarga estructurada directa JSON mediante /user/action_redir.php
|
|
json_participants = []
|
|
if sesskey and user_checkboxes:
|
|
redir_url = f"{self.base_url}/user/action_redir.php"
|
|
post_data = {
|
|
'id': str(course_id),
|
|
'sesskey': sesskey,
|
|
'formaction': 'bulkchange.php?operation=download_participants&dataformat=json'
|
|
}
|
|
for ucb in user_checkboxes:
|
|
post_data[ucb] = '1'
|
|
|
|
try:
|
|
r_json = self.session.post(redir_url, data=post_data, timeout=30, allow_redirects=True)
|
|
if r_json.status_code == 200 and 'application/json' in r_json.headers.get('Content-Type', ''):
|
|
data = r_json.json()
|
|
# Moodle a veces retorna [[{user1}, {user2}]]
|
|
if isinstance(data, list) and len(data) > 0 and isinstance(data[0], list):
|
|
json_participants = data[0]
|
|
elif isinstance(data, list):
|
|
json_participants = data
|
|
print(f"[+] Descarga nativa JSON exitosa: {len(json_participants)} registros estructurados.")
|
|
except Exception as e:
|
|
print(f"[!] Aviso: No se pudo completar la descarga JSON directa ({e}). Usando scraping HTML.")
|
|
|
|
# Paso 3: Parsear la tabla HTML de manera lineal y rápida por fragmentos <tr>
|
|
html_participants_by_name = {}
|
|
html_participants_by_id = {}
|
|
|
|
# Dividir por filas para evitar backtracking catastrófico en cadenas HTML de 3+ MB
|
|
chunks = res.text.split('<tr')
|
|
for chunk in chunks[1:]:
|
|
if 'user/view.php?id=' not in chunk:
|
|
continue
|
|
|
|
m_uid = re.search(r'user/view\.php\?id=(\d+)', chunk)
|
|
if not m_uid:
|
|
continue
|
|
uid = int(m_uid.group(1))
|
|
|
|
m_name = re.search(r'<a[^>]*user/view\.php[^>]*>(?:<img[^>]*>)?\s*(.*?)\s*</a>', chunk, re.DOTALL)
|
|
raw_name = re.sub(r'<[^>]+>', '', m_name.group(1)).strip() if m_name else ''
|
|
|
|
m_role = re.search(r'<td[^>]*class=["\'][^"\']*c2[^"\']*["\'][^>]*>(.*?)</td>', chunk, re.DOTALL)
|
|
raw_role = re.sub(r'<[^>]+>', '', m_role.group(1)).strip() if m_role else 'Estudiante'
|
|
|
|
is_teacher = any(k in raw_role.lower() for k in ['profesor', 'docente', 'teacher'])
|
|
|
|
entry = {
|
|
'moodle_id': uid,
|
|
'fullname': raw_name,
|
|
'role_text': raw_role,
|
|
'is_teacher': is_teacher
|
|
}
|
|
if raw_name:
|
|
html_participants_by_name[normalize_name(raw_name)] = entry
|
|
html_participants_by_id[uid] = entry
|
|
|
|
# Paso 4: Fusionar datos estructurados (JSON + HTML)
|
|
final_list = []
|
|
if json_participants:
|
|
for item in json_participants:
|
|
fn = item.get('nombre', '').strip()
|
|
ln = item.get('apellidos', '').strip()
|
|
combined = f"{fn} {ln}"
|
|
|
|
matched = html_participants_by_name.get(normalize_name(combined))
|
|
moodle_id = matched['moodle_id'] if matched else None
|
|
is_teacher = matched['is_teacher'] if matched else False
|
|
role_text = matched['role_text'] if matched else 'Estudiante'
|
|
|
|
final_list.append({
|
|
'moodle_id': moodle_id,
|
|
'firstname': fn,
|
|
'lastname': ln,
|
|
'fullname': f"{fn} {ln}".strip(),
|
|
'role_text': role_text,
|
|
'is_teacher': is_teacher,
|
|
'group': item.get('grupos', ''),
|
|
'course_id': course_id
|
|
})
|
|
else:
|
|
# Respaldo exclusivo HTML
|
|
for entry in html_participants_by_id.values():
|
|
name_parts = entry['fullname'].split()
|
|
if len(name_parts) >= 2:
|
|
fn = " ".join(name_parts[:-1])
|
|
ln = name_parts[-1]
|
|
else:
|
|
fn = entry['fullname']
|
|
ln = entry['fullname']
|
|
|
|
final_list.append({
|
|
'moodle_id': entry['moodle_id'],
|
|
'firstname': fn,
|
|
'lastname': ln,
|
|
'fullname': entry['fullname'],
|
|
'role_text': entry['role_text'],
|
|
'is_teacher': entry['is_teacher'],
|
|
'group': '',
|
|
'course_id': course_id
|
|
})
|
|
|
|
# Paso 5: Obtener los correos electrónicos reales desde los perfiles en Moodle Producción
|
|
self.fetch_real_emails(final_list, course_id)
|
|
|
|
print(f"[+] Total procesado para curso {course_id}: {len(final_list)} participantes.")
|
|
return final_list
|
|
|
|
|
|
class MoodleUserTransformer:
|
|
"""Aplica las reglas de negocio y mocking para el entorno local."""
|
|
|
|
@staticmethod
|
|
def transform_user(user: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""Genera credenciales con DNI determinístico y asigna el email REAL de producción."""
|
|
fn = user.get('firstname', '').strip()
|
|
ln = user.get('lastname', '').strip()
|
|
moodle_id = user.get('moodle_id')
|
|
full_upper = f"{fn} {ln}".upper()
|
|
|
|
# Regla RF4: Preservar credenciales reales conocidas (Carlos Tello: 34247025)
|
|
if "CARLOS" in full_upper and "TELLO" in full_upper:
|
|
dni = "34247025"
|
|
else:
|
|
# Regla RF3: DNI de 8 dígitos determinístico: prefijo 90 + ID Moodle a 6 dígitos
|
|
if moodle_id:
|
|
dni = f"90{moodle_id:06d}"
|
|
else:
|
|
import hashlib
|
|
h = int(hashlib.md5(full_upper.encode('utf-8')).hexdigest()[:6], 16) % 1000000
|
|
dni = f"90{h:06d}"
|
|
|
|
# Correo electrónico REAL extraído del perfil de producción
|
|
real_email = user.get('real_email')
|
|
if real_email:
|
|
email = real_email
|
|
elif "CARLOS" in full_upper and "TELLO" in full_upper:
|
|
email = "carlostellocba@gmail.com"
|
|
else:
|
|
slug_fn = slugify(fn)
|
|
slug_ln = slugify(ln)
|
|
email = f"{slug_fn}.{slug_ln}@unicaba.edu.ar"
|
|
|
|
# Rol: editingteacher = 3, student = 5
|
|
role_id = 3 if user.get('is_teacher') else 5
|
|
|
|
return {
|
|
'username': dni,
|
|
'password': dni, # RF3: Documento tanto como username como password
|
|
'firstname': fn if fn else 'Usuario',
|
|
'lastname': ln if ln else 'UniCABA',
|
|
'fullname': f"{fn} {ln}".strip(),
|
|
'email': email,
|
|
'auth': 'manual',
|
|
'dni': dni,
|
|
'role_id': role_id,
|
|
'is_teacher': user.get('is_teacher', False),
|
|
'course_id': user.get('course_id')
|
|
}
|
|
|
|
|
|
class MoodleLocalLoader:
|
|
"""Interactúa con la API REST de Moodle Local (10.0.0.207) para altas y matriculaciones."""
|
|
|
|
def __init__(self, local_url: str, token: str):
|
|
self.endpoint = f"{local_url.rstrip('/')}/webservice/rest/server.php"
|
|
self.token = token
|
|
self.session = requests.Session()
|
|
self.user_cache: Dict[str, int] = {}
|
|
|
|
def call(self, wsfunction: str, params: Dict[str, Any]) -> Any:
|
|
full_params = {
|
|
'wstoken': self.token,
|
|
'wsfunction': wsfunction,
|
|
'moodlewsrestformat': 'json',
|
|
**params
|
|
}
|
|
res = self.session.post(self.endpoint, data=full_params, timeout=25)
|
|
try:
|
|
return res.json()
|
|
except Exception:
|
|
return {'error': res.text, 'status_code': res.status_code}
|
|
|
|
def get_or_create_user(self, user_data: Dict[str, Any]) -> Optional[int]:
|
|
"""Obtiene el ID local de un usuario por username o lo crea si no existe (con caché en memoria)."""
|
|
username = user_data['username']
|
|
if username in self.user_cache:
|
|
return self.user_cache[username]
|
|
|
|
# Buscar si ya existe
|
|
query_res = self.call('core_user_get_users', {
|
|
'criteria[0][key]': 'username',
|
|
'criteria[0][value]': username
|
|
})
|
|
|
|
if isinstance(query_res, dict) and 'users' in query_res and len(query_res['users']) > 0:
|
|
uid = query_res['users'][0]['id']
|
|
self.user_cache[username] = uid
|
|
# Actualizar con el correo real de producción si difiere del actual y asegurar contraseña idéntica al DNI
|
|
current_email = query_res['users'][0].get('email', '')
|
|
target_email = user_data.get('email', '')
|
|
update_payload = {
|
|
'users[0][id]': uid,
|
|
'users[0][password]': user_data['password']
|
|
}
|
|
if target_email and current_email != target_email:
|
|
update_payload['users[0][email]'] = target_email
|
|
self.call('core_user_update_users', update_payload)
|
|
return uid
|
|
|
|
# Crear usuario si no existe
|
|
create_payload = {
|
|
'users[0][username]': username,
|
|
'users[0][password]': user_data['password'],
|
|
'users[0][firstname]': user_data['firstname'],
|
|
'users[0][lastname]': user_data['lastname'],
|
|
'users[0][email]': user_data['email'],
|
|
'users[0][auth]': 'manual'
|
|
}
|
|
|
|
create_res = self.call('core_user_create_users', create_payload)
|
|
if isinstance(create_res, list) and len(create_res) > 0 and 'id' in create_res[0]:
|
|
uid = create_res[0]['id']
|
|
self.user_cache[username] = uid
|
|
return uid
|
|
|
|
print(f"[!] Error al crear usuario {username}: {create_res}")
|
|
return None
|
|
|
|
def enrol_user(self, local_user_id: int, local_course_id: int, role_id: int) -> bool:
|
|
"""Matricula a un usuario en un curso con el rol especificado."""
|
|
payload = {
|
|
'enrolments[0][roleid]': role_id,
|
|
'enrolments[0][userid]': local_user_id,
|
|
'enrolments[0][courseid]': local_course_id
|
|
}
|
|
res = self.call('enrol_manual_enrol_users', payload)
|
|
# Retorna None o vacio en caso de éxito
|
|
if res is None or res == {} or res == []:
|
|
return True
|
|
if isinstance(res, dict) and 'exception' in res:
|
|
print(f"[!] Error al matricular user {local_user_id} en curso {local_course_id}: {res.get('message')}")
|
|
return False
|
|
return True
|
|
|
|
|
|
def run_replication(
|
|
course_ids: Optional[List[int]] = None,
|
|
dry_run: bool = False,
|
|
export_json_path: Optional[str] = None
|
|
):
|
|
print("=" * 75)
|
|
print(" MOODLE REPLICATOR: UniCABA Producción -> Entorno Local (10.0.0.207)")
|
|
print("=" * 75)
|
|
|
|
creds = CredentialsLoader.load()
|
|
if not creds['prod_user'] or not creds['prod_pass']:
|
|
print("[!] No se encontraron credenciales de Moodle Producción en .credenciales.")
|
|
sys.exit(1)
|
|
|
|
extractor = MoodleProdExtractor(creds['prod_url'], creds['prod_user'], creds['prod_pass'])
|
|
if not extractor.login():
|
|
sys.exit(1)
|
|
|
|
loader = None
|
|
if not dry_run:
|
|
loader = MoodleLocalLoader(creds['local_url'], creds['local_token'])
|
|
|
|
target_courses = course_ids if course_ids else list(COURSE_MAPPING.keys())
|
|
all_exported_data = {}
|
|
|
|
total_created = 0
|
|
total_enrolled = 0
|
|
|
|
for cid in target_courses:
|
|
course_meta = COURSE_MAPPING.get(cid, {
|
|
'name': f'Curso Prod {cid}',
|
|
'local_id': cid
|
|
})
|
|
local_course_id = course_meta['local_id']
|
|
|
|
print("\n" + "-" * 70)
|
|
print(f"[*] Procesando: '{course_meta['name']}'")
|
|
print(f" Prod ID: {cid} -> Local ID: {local_course_id}")
|
|
print("-" * 70)
|
|
|
|
raw_participants = extractor.extract_course_participants(cid)
|
|
transformed_users = [MoodleUserTransformer.transform_user(u) for u in raw_participants]
|
|
all_exported_data[cid] = transformed_users
|
|
|
|
if dry_run or not loader:
|
|
print(f"[DRY-RUN] Se habrían procesado {len(transformed_users)} usuarios para curso local {local_course_id}.")
|
|
continue
|
|
|
|
print(f"[*] Replicando {len(transformed_users)} usuarios en Moodle Local (10.0.0.207)...")
|
|
course_enrolled = 0
|
|
for u in transformed_users:
|
|
local_uid = loader.get_or_create_user(u)
|
|
if local_uid:
|
|
total_created += 1
|
|
if loader.enrol_user(local_uid, local_course_id, u['role_id']):
|
|
course_enrolled += 1
|
|
total_enrolled += 1
|
|
|
|
print(f"[+] Curso local {local_course_id}: {course_enrolled}/{len(transformed_users)} usuarios matriculados con éxito.")
|
|
|
|
# Guardar exportación JSON si fue solicitada
|
|
if export_json_path:
|
|
with open(export_json_path, 'w', encoding='utf-8') as f:
|
|
json.dump(all_exported_data, f, indent=2, ensure_ascii=False)
|
|
print(f"\n[+] Datos exportados guardados exitosamente en: {export_json_path}")
|
|
|
|
print("\n" + "=" * 75)
|
|
print(" RESUMEN DE EJECUCIÓN")
|
|
print("=" * 75)
|
|
print(f" Cursos procesados: {len(target_courses)}")
|
|
if not dry_run:
|
|
print(f" Usuarios en local: {total_created} procesados")
|
|
print(f" Matriculaciones OK: {total_enrolled}")
|
|
else:
|
|
print(" Modo: DRY-RUN (Sin escrituras)")
|
|
|
|
print("\n" + "=" * 75)
|
|
print(" PROFESORES Y EQUIPO DOCENTE IDENTIFICADOS POR MATERIA")
|
|
print("=" * 75)
|
|
for cid in target_courses:
|
|
c_name = COURSE_MAPPING.get(cid, {}).get('name', f'Curso {cid}')
|
|
c_users = all_exported_data.get(cid, [])
|
|
c_teachers = [u for u in c_users if u.get('is_teacher') or u.get('role_id') == 3]
|
|
print(f"\n[+] {c_name} (Prod ID: {cid}) - Docentes: {len(c_teachers)}")
|
|
if c_teachers:
|
|
for t in c_teachers:
|
|
print(f" - {t['fullname']:<28} | Email: {t['email']:<36} | DNI: {t['dni']}")
|
|
else:
|
|
print(" (Sin docentes asignados directamente en la vista del curso)")
|
|
print("=" * 75)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Replicador de Moodle Producción a Local para UniCABA.")
|
|
parser.add_argument('--course', type=int, choices=list(COURSE_MAPPING.keys()), help="ID del curso específico a procesar.")
|
|
parser.add_argument('--dry-run', action='store_true', help="Ejecutar en modo simulación sin modificar el Moodle local.")
|
|
parser.add_argument('--export-json', type=str, help="Ruta de archivo JSON donde guardar el volcado de datos.")
|
|
parser.add_argument('--sync-app', action='store_true', help="Sincronizar e importar usuarios con sus roles en la base de datos de Admin Edu Space.")
|
|
args = parser.parse_args()
|
|
|
|
course_ids = [args.course] if args.course else None
|
|
export_path = args.export_json or ('participantes_export.json' if args.sync_app else None)
|
|
run_replication(course_ids=course_ids, dry_run=args.dry_run, export_json_path=export_path)
|
|
|
|
if args.sync_app and export_path:
|
|
try:
|
|
import importlib
|
|
scripts_dir = os.path.dirname(os.path.abspath(__file__))
|
|
if scripts_dir not in sys.path:
|
|
sys.path.insert(0, scripts_dir)
|
|
_imp_mod = importlib.import_module("import_moodle_to_app")
|
|
import_moodle_users = getattr(_imp_mod, "import_moodle_users")
|
|
import_moodle_users(export_path)
|
|
except Exception as e:
|
|
print(f"[!] Error al sincronizar con la base de datos de la App: {e}")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|