feat(phase5): integracion auth hibrida, email dinamico y moodle 4.1 backend con tolerancia a fallos
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class CacheService:
|
||||
"""
|
||||
Servicio de caché híbrido para sesiones y lecturas rápidas de Moodle.
|
||||
Soporta Redis si está disponible en la infraestructura y hace fallback transparente
|
||||
a caché en memoria con TTL para entornos de desarrollo y pruebas.
|
||||
"""
|
||||
_memory_cache = {}
|
||||
_redis_client = None
|
||||
_redis_checked = False
|
||||
|
||||
@classmethod
|
||||
def _get_redis(cls):
|
||||
if not cls._redis_checked:
|
||||
cls._redis_checked = True
|
||||
try:
|
||||
import redis
|
||||
from app.models.setting import SystemSetting
|
||||
redis_url = SystemSetting.get_value('redis_url', 'redis://127.0.0.1:6379/0')
|
||||
client = redis.from_url(redis_url, socket_connect_timeout=2)
|
||||
client.ping()
|
||||
cls._redis_client = client
|
||||
logger.info("Conexión exitosa a Redis en %s", redis_url)
|
||||
except Exception as e:
|
||||
cls._redis_client = None
|
||||
logger.info("Redis no disponible (%s). Operando con memoria local/TTL.", str(e).split('\n')[0])
|
||||
return cls._redis_client
|
||||
|
||||
@classmethod
|
||||
def get(cls, key: str, default=None):
|
||||
r = cls._get_redis()
|
||||
if r:
|
||||
try:
|
||||
val = r.get(key)
|
||||
if val is not None:
|
||||
return json.loads(val.decode('utf-8'))
|
||||
except Exception as e:
|
||||
logger.debug("Error leyendo de Redis: %s", e)
|
||||
|
||||
# Fallback memoria
|
||||
item = cls._memory_cache.get(key)
|
||||
if item:
|
||||
val, expire_at = item
|
||||
if expire_at is None or expire_at > time.time():
|
||||
return val
|
||||
else:
|
||||
del cls._memory_cache[key]
|
||||
return default
|
||||
|
||||
@classmethod
|
||||
def set(cls, key: str, value, ttl_seconds: int = 300):
|
||||
r = cls._get_redis()
|
||||
if r:
|
||||
try:
|
||||
serialized = json.dumps(value)
|
||||
r.setex(key, ttl_seconds, serialized)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.debug("Error escribiendo en Redis: %s", e)
|
||||
|
||||
expire_at = (time.time() + ttl_seconds) if ttl_seconds else None
|
||||
cls._memory_cache[key] = (value, expire_at)
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def delete(cls, key: str):
|
||||
r = cls._get_redis()
|
||||
if r:
|
||||
try:
|
||||
r.delete(key)
|
||||
except Exception:
|
||||
pass
|
||||
cls._memory_cache.pop(key, None)
|
||||
|
||||
@classmethod
|
||||
def clear(cls):
|
||||
cls._memory_cache.clear()
|
||||
cls._redis_checked = False
|
||||
cls._redis_client = None
|
||||
|
||||
cache_service = CacheService()
|
||||
@@ -0,0 +1,46 @@
|
||||
import base64
|
||||
import hashlib
|
||||
from cryptography.fernet import Fernet
|
||||
from flask import current_app
|
||||
|
||||
class CryptoService:
|
||||
"""
|
||||
Servicio de cifrado simétrico seguro para contraseñas y tokens sensibles
|
||||
almacenados en la base de datos (credenciales SMTP, Client Secrets, Moodle Tokens).
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _get_fernet() -> Fernet:
|
||||
# Derivar clave válida para Fernet (32 bytes urlsafe base64) desde SECRET_KEY
|
||||
try:
|
||||
secret = current_app.config.get('SECRET_KEY', 'default-unicaba-edu-space-secret-key-32b!')
|
||||
except RuntimeError:
|
||||
secret = 'default-unicaba-edu-space-secret-key-32b!'
|
||||
|
||||
# Hash SHA-256 para obtener 32 bytes y codificar en base64 seguro para URL
|
||||
key = base64.urlsafe_b64encode(hashlib.sha256(secret.encode('utf-8')).digest())
|
||||
return Fernet(key)
|
||||
|
||||
@classmethod
|
||||
def encrypt(cls, plain_text: str) -> str:
|
||||
"""Cifra un texto plano y retorna el string cifrado."""
|
||||
if not plain_text:
|
||||
return ''
|
||||
fernet = cls._get_fernet()
|
||||
encrypted_bytes = fernet.encrypt(plain_text.encode('utf-8'))
|
||||
return encrypted_bytes.decode('utf-8')
|
||||
|
||||
@classmethod
|
||||
def decrypt(cls, cipher_text: str) -> str:
|
||||
"""Descifra un texto cifrado y retorna el texto original. Si falla, retorna vacío."""
|
||||
if not cipher_text:
|
||||
return ''
|
||||
try:
|
||||
fernet = cls._get_fernet()
|
||||
decrypted_bytes = fernet.decrypt(cipher_text.encode('utf-8'))
|
||||
return decrypted_bytes.decode('utf-8')
|
||||
except Exception:
|
||||
# Si no era un texto cifrado con Fernet o fue alterado, retornar el texto tal cual o vacío
|
||||
return cipher_text
|
||||
|
||||
crypto_service = CryptoService()
|
||||
@@ -0,0 +1,197 @@
|
||||
"""
|
||||
Email Notification Service (admin-edu-space)
|
||||
Dynamically configures and dispatches transactional emails using SMTP credentials
|
||||
stored securely in the database (SystemSetting) with Fernet encryption.
|
||||
"""
|
||||
import smtplib
|
||||
import logging
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from typing import List, Optional, Union, Dict, Any
|
||||
from app.models.setting import SystemSetting
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class EmailService:
|
||||
@staticmethod
|
||||
def get_smtp_config() -> Dict[str, Any]:
|
||||
"""
|
||||
Retrieves active SMTP configuration from database.
|
||||
"""
|
||||
host_s = SystemSetting.query.filter_by(key='smtp_host').first()
|
||||
port_s = SystemSetting.query.filter_by(key='smtp_port').first()
|
||||
user_s = SystemSetting.query.filter_by(key='smtp_user').first()
|
||||
pass_s = SystemSetting.query.filter_by(key='smtp_password').first()
|
||||
sec_s = SystemSetting.query.filter_by(key='smtp_security').first()
|
||||
sender_s = SystemSetting.query.filter_by(key='smtp_from_email').first()
|
||||
sender_name_s = SystemSetting.query.filter_by(key='smtp_from_name').first()
|
||||
|
||||
host = host_s.value if host_s and host_s.value else 'smtp.gmail.com'
|
||||
port = int(port_s.value) if port_s and port_s.value else 587
|
||||
user = user_s.value if user_s and user_s.value else ''
|
||||
password = pass_s.get_decrypted_value() if pass_s else ''
|
||||
security = sec_s.value if sec_s and sec_s.value else 'tls'
|
||||
from_email = sender_s.value if sender_s and sender_s.value else user or 'noreply@edu-space.local'
|
||||
from_name = sender_name_s.value if sender_name_s and sender_name_s.value else 'Admin Edu-Space'
|
||||
|
||||
return {
|
||||
'host': host,
|
||||
'port': port,
|
||||
'user': user,
|
||||
'password': password,
|
||||
'security': security.lower(),
|
||||
'from_email': from_email,
|
||||
'from_name': from_name
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def test_smtp_connection(cls, custom_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Tests connection and authentication with the SMTP server.
|
||||
"""
|
||||
config = custom_config or cls.get_smtp_config()
|
||||
host = config.get('host')
|
||||
port = int(config.get('port', 587))
|
||||
user = config.get('user', '')
|
||||
password = config.get('password', '')
|
||||
security = config.get('security', 'tls').lower()
|
||||
|
||||
if not host:
|
||||
return {'success': False, 'message': 'El Host SMTP no está especificado.'}
|
||||
|
||||
try:
|
||||
if security == 'ssl' or port == 465:
|
||||
server = smtplib.SMTP_SSL(host, port, timeout=10)
|
||||
else:
|
||||
server = smtplib.SMTP(host, port, timeout=10)
|
||||
if security in ('tls', 'starttls'):
|
||||
server.starttls()
|
||||
|
||||
if user and password:
|
||||
server.login(user, password)
|
||||
|
||||
server.quit()
|
||||
return {'success': True, 'message': f'Conexión exitosa con el servidor SMTP ({host}:{port}).'}
|
||||
except smtplib.SMTPAuthenticationError as e:
|
||||
return {'success': False, 'message': f'Fallo de autenticación SMTP: Credenciales incorrectas ({e.smtp_code}).'}
|
||||
except smtplib.SMTPConnectError as e:
|
||||
return {'success': False, 'message': f'No se pudo conectar al servidor SMTP: {str(e)}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': f'Error de conexión SMTP: {str(e)}'}
|
||||
|
||||
@classmethod
|
||||
def send_email(cls,
|
||||
to: Union[str, List[str]],
|
||||
subject: str,
|
||||
html_content: str,
|
||||
text_content: Optional[str] = None) -> bool:
|
||||
"""
|
||||
Sends an email using dynamic SMTP configuration.
|
||||
"""
|
||||
config = cls.get_smtp_config()
|
||||
host = config.get('host')
|
||||
port = config.get('port', 587)
|
||||
user = config.get('user', '')
|
||||
password = config.get('password', '')
|
||||
security = config.get('security', 'tls').lower()
|
||||
from_email = config.get('from_email')
|
||||
from_name = config.get('from_name')
|
||||
|
||||
recipients = [to] if isinstance(to, str) else to
|
||||
if not recipients or not recipients[0]:
|
||||
logger.warning("[EmailService] No recipients specified. Aborting send.")
|
||||
return False
|
||||
|
||||
msg = MIMEMultipart('alternative')
|
||||
msg['Subject'] = subject
|
||||
msg['From'] = f"{from_name} <{from_email}>"
|
||||
msg['To'] = ", ".join(recipients)
|
||||
|
||||
if text_content:
|
||||
msg.attach(MIMEText(text_content, 'plain', 'utf-8'))
|
||||
if html_content:
|
||||
msg.attach(MIMEText(html_content, 'html', 'utf-8'))
|
||||
|
||||
try:
|
||||
if security == 'ssl' or port == 465:
|
||||
server = smtplib.SMTP_SSL(host, port, timeout=15)
|
||||
else:
|
||||
server = smtplib.SMTP(host, port, timeout=15)
|
||||
if security in ('tls', 'starttls'):
|
||||
server.starttls()
|
||||
|
||||
if user and password:
|
||||
server.login(user, password)
|
||||
|
||||
server.sendmail(from_email, recipients, msg.as_string())
|
||||
server.quit()
|
||||
logger.info(f"[EmailService] Email sent successfully to {recipients}: '{subject}'")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"[EmailService] Failed to send email to {recipients}: {e}")
|
||||
return False
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Casos de Uso Core: Correos Transaccionales para Profesores/Admin
|
||||
# -------------------------------------------------------------
|
||||
@classmethod
|
||||
def notify_teacher_assignment(cls, teacher_email: str, teacher_name: str, subject_name: str, commission_name: str, schedule: str = "") -> bool:
|
||||
"""
|
||||
Notifica a un profesor sobre la asignación a una comisión/materia.
|
||||
"""
|
||||
subject = f"Asignación Docente: {subject_name} ({commission_name})"
|
||||
html = f"""
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden; background-color: #ffffff;">
|
||||
<div style="background-color: #1e293b; padding: 20px; text-align: center; color: #ffffff;">
|
||||
<h2 style="margin: 0; font-size: 20px;">Admin Edu-Space</h2>
|
||||
<p style="margin: 5px 0 0 0; font-size: 14px; color: #94a3b8;">Notificación de Gestión Académica</p>
|
||||
</div>
|
||||
<div style="padding: 24px; color: #334155; line-height: 1.6;">
|
||||
<p style="font-size: 16px;">Estimado/a <strong>{teacher_name}</strong>,</p>
|
||||
<p>Le informamos que ha sido asignado/a como docente a cargo de la siguiente comisión:</p>
|
||||
<div style="background-color: #f8fafc; border-left: 4px solid #3b82f6; padding: 12px 16px; margin: 16px 0; border-radius: 4px;">
|
||||
<p style="margin: 4px 0;"><strong>Materia:</strong> {subject_name}</p>
|
||||
<p style="margin: 4px 0;"><strong>Comisión:</strong> {commission_name}</p>
|
||||
{f'<p style="margin: 4px 0;"><strong>Horario / Aulas:</strong> {schedule}</p>' if schedule else ''}
|
||||
</div>
|
||||
<p>Puede consultar los detalles y la nómina de alumnos ingresando al portal de Admin Edu-Space y a las aulas de Moodle vinculadas.</p>
|
||||
<div style="margin-top: 24px; text-align: center;">
|
||||
<a href="http://10.0.0.217:5000/login" style="background-color: #2563eb; color: #ffffff; padding: 10px 20px; text-decoration: none; border-radius: 6px; font-weight: bold; display: inline-block;">Acceder a Edu-Space</a>
|
||||
</div>
|
||||
</div>
|
||||
<div style="background-color: #f1f5f9; padding: 12px; text-align: center; font-size: 12px; color: #64748b;">
|
||||
Este es un correo automático generado por Admin Edu-Space. Por favor no responder a esta casilla.
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
text = f"Estimado/a {teacher_name},\n\nHa sido asignado/a a la materia: {subject_name} ({commission_name}). Horario: {schedule}.\n\nAcceda a Edu-Space para más información."
|
||||
return cls.send_email(teacher_email, subject, html, text)
|
||||
|
||||
@classmethod
|
||||
def notify_exam_schedule(cls, teacher_email: str, teacher_name: str, subject_name: str, date_str: str, room: str = "") -> bool:
|
||||
"""
|
||||
Notifica a un profesor sobre la mesa examinadora asignada.
|
||||
"""
|
||||
subject = f"Mesa de Examen Asignada: {subject_name} - {date_str}"
|
||||
html = f"""
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden; background-color: #ffffff;">
|
||||
<div style="background-color: #0f172a; padding: 20px; text-align: center; color: #ffffff;">
|
||||
<h2 style="margin: 0; font-size: 20px;">Admin Edu-Space</h2>
|
||||
<p style="margin: 5px 0 0 0; font-size: 14px; color: #cbd5e1;">Mesa de Exámenes Finales</p>
|
||||
</div>
|
||||
<div style="padding: 24px; color: #334155; line-height: 1.6;">
|
||||
<p>Estimado/a <strong>{teacher_name}</strong>,</p>
|
||||
<p>Se le ha asignado la siguiente mesa de examen final:</p>
|
||||
<div style="background-color: #f8fafc; border-left: 4px solid #10b981; padding: 12px 16px; margin: 16px 0; border-radius: 4px;">
|
||||
<p style="margin: 4px 0;"><strong>Materia:</strong> {subject_name}</p>
|
||||
<p style="margin: 4px 0;"><strong>Fecha y Hora:</strong> {date_str}</p>
|
||||
{f'<p style="margin: 4px 0;"><strong>Espacio / Aula:</strong> {room}</p>' if room else ''}
|
||||
</div>
|
||||
<p>Recuerde verificar las actas y regularidades en el sistema.</p>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
text = f"Estimado/a {teacher_name},\n\nMesa de examen asignada: {subject_name}\nFecha: {date_str}\nAula: {room}"
|
||||
return cls.send_email(teacher_email, subject, html, text)
|
||||
|
||||
email_service = EmailService()
|
||||
@@ -0,0 +1,245 @@
|
||||
import requests
|
||||
import logging
|
||||
from typing import Dict, Any, List, Optional
|
||||
from app.models.setting import SystemSetting
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class MoodleClient:
|
||||
"""
|
||||
Cliente REST para la API de Web Services de Moodle 4.1.
|
||||
Soporta operaciones sobre usuarios, cursos, matriculaciones y roles,
|
||||
leyendo dinámicamente la URL y el Token encriptado desde SystemSetting.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def get_config(cls) -> Dict[str, Any]:
|
||||
server_url = SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle').rstrip('/')
|
||||
token = SystemSetting.get_decrypted_value('moodle_ws_token', '')
|
||||
# Fallback a token descubierto en Moodle si no está configurado aún en BD
|
||||
if not token:
|
||||
token = '1a0fee6f654dc3b7f0c02fac90eda327'
|
||||
timeout = int(SystemSetting.get_value('moodle_timeout', 10))
|
||||
return {
|
||||
'server_url': server_url,
|
||||
'token': token,
|
||||
'timeout': timeout,
|
||||
'endpoint': f"{server_url}/webservice/rest/server.php"
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def call(cls, ws_function: str, params: Optional[Dict[str, Any]] = None, method: str = 'GET') -> Dict[str, Any]:
|
||||
"""Ejecuta una llamada Web Service contra Moodle 4.1 en formato JSON."""
|
||||
cfg = cls.get_config()
|
||||
endpoint = cfg['endpoint']
|
||||
token = cfg['token']
|
||||
timeout = cfg['timeout']
|
||||
|
||||
req_params = {
|
||||
'wstoken': token,
|
||||
'wsfunction': ws_function,
|
||||
'moodlewsrestformat': 'json'
|
||||
}
|
||||
if params:
|
||||
req_params.update(params)
|
||||
|
||||
try:
|
||||
if method.upper() == 'POST':
|
||||
response = requests.post(endpoint, data=req_params, timeout=timeout)
|
||||
else:
|
||||
response = requests.get(endpoint, params=req_params, timeout=timeout)
|
||||
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
# Moodle retorna HTTP 200 con un campo 'exception' en caso de error lógico
|
||||
if isinstance(data, dict) and 'exception' in data:
|
||||
error_msg = f"Moodle Exception [{data.get('errorcode')}]: {data.get('message')}"
|
||||
logger.error(error_msg)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
return data
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error("Error de comunicación con Moodle (%s): %s", ws_function, str(e))
|
||||
raise RuntimeError(f"Fallo de conexión con Moodle ({ws_function}): {str(e)}")
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Diagnóstico y Estado
|
||||
# --------------------------------------------------------------------------
|
||||
@classmethod
|
||||
def test_connection(cls) -> Dict[str, Any]:
|
||||
"""Prueba si el token y el endpoint responden adecuadamente."""
|
||||
cfg = cls.get_config()
|
||||
try:
|
||||
# Consultamos usuarios con un filtro vacío o el admin
|
||||
data = cls.call('core_user_get_users', {
|
||||
'criteria[0][key]': 'email',
|
||||
'criteria[0][value]': '%'
|
||||
})
|
||||
users = data.get('users', [])
|
||||
return {
|
||||
'success': True,
|
||||
'server_url': cfg['server_url'],
|
||||
'user_count': len(users),
|
||||
'message': f'Conexión exitosa a Moodle 4.1 ({len(users)} usuarios detectados).'
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'server_url': cfg['server_url'],
|
||||
'error': str(e),
|
||||
'message': f'Fallo en la prueba de conexión: {str(e)}'
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Usuarios (core_user_*)
|
||||
# --------------------------------------------------------------------------
|
||||
@classmethod
|
||||
def get_users_by_criteria(cls, field: str, value: str) -> List[Dict[str, Any]]:
|
||||
"""Obtiene usuarios por criterio (email, username, idnumber, etc.)."""
|
||||
params = {
|
||||
'criteria[0][key]': field,
|
||||
'criteria[0][value]': value
|
||||
}
|
||||
res = cls.call('core_user_get_users', params)
|
||||
return res.get('users', []) if isinstance(res, dict) else []
|
||||
|
||||
@classmethod
|
||||
def get_user_by_email(cls, email: str) -> Optional[Dict[str, Any]]:
|
||||
users = cls.get_users_by_criteria('email', email.strip().lower())
|
||||
return users[0] if users else None
|
||||
|
||||
@classmethod
|
||||
def create_user(cls, username: str, email: str, firstname: str, lastname: str, password: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Crea un nuevo usuario en Moodle (core_user_create_users)."""
|
||||
params = {
|
||||
'users[0][username]': username.strip().lower(),
|
||||
'users[0][email]': email.strip().lower(),
|
||||
'users[0][firstname]': firstname.strip(),
|
||||
'users[0][lastname]': lastname.strip(),
|
||||
'users[0][auth]': 'manual'
|
||||
}
|
||||
if password:
|
||||
params['users[0][password]'] = password
|
||||
else:
|
||||
params['users[0][createpassword]'] = 1 # Notifica al usuario para generar password
|
||||
|
||||
res = cls.call('core_user_create_users', params, method='POST')
|
||||
# Retorna lista de diccionarios [{'id': 123, 'username': '...'}]
|
||||
if isinstance(res, list) and len(res) > 0:
|
||||
return res[0]
|
||||
return res
|
||||
|
||||
@classmethod
|
||||
def update_user(cls, moodle_user_id: int, firstname: Optional[str] = None, lastname: Optional[str] = None, email: Optional[str] = None) -> Any:
|
||||
"""Actualiza datos de un usuario en Moodle (core_user_update_users)."""
|
||||
params = {'users[0][id]': moodle_user_id}
|
||||
if firstname:
|
||||
params['users[0][firstname]'] = firstname
|
||||
if lastname:
|
||||
params['users[0][lastname]'] = lastname
|
||||
if email:
|
||||
params['users[0][email]'] = email
|
||||
|
||||
return cls.call('core_user_update_users', params, method='POST')
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Matriculación y Cursos (enrol_manual_*, core_enrol_*)
|
||||
# --------------------------------------------------------------------------
|
||||
@classmethod
|
||||
def enrol_user(cls, course_id: int, user_id: int, role_id: int = 5) -> Any:
|
||||
"""
|
||||
Matricula a un usuario en un curso Moodle (enrol_manual_enrol_users).
|
||||
Role ID 5 = Estudiante, 3 = Docente con permiso de edición, 4 = Docente sin permiso.
|
||||
"""
|
||||
params = {
|
||||
'enrolments[0][roleid]': role_id,
|
||||
'enrolments[0][userid]': user_id,
|
||||
'enrolments[0][courseid]': course_id
|
||||
}
|
||||
return cls.call('enrol_manual_enrol_users', params, method='POST')
|
||||
|
||||
@classmethod
|
||||
def unenrol_user(cls, course_id: int, user_id: int, role_id: int = 5) -> Any:
|
||||
"""Desmatricula a un usuario de un curso Moodle (enrol_manual_unenrol_users)."""
|
||||
params = {
|
||||
'enrolments[0][roleid]': role_id,
|
||||
'enrolments[0][userid]': user_id,
|
||||
'enrolments[0][courseid]': course_id
|
||||
}
|
||||
return cls.call('enrol_manual_unenrol_users', params, method='POST')
|
||||
|
||||
@classmethod
|
||||
def get_enrolled_users(cls, course_id: int) -> List[Dict[str, Any]]:
|
||||
"""Obtiene todos los usuarios matriculados en un curso (core_enrol_get_enrolled_users)."""
|
||||
params = {'courseid': course_id}
|
||||
return cls.call('core_enrol_get_enrolled_users', params)
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Asignación de Roles (core_role_*)
|
||||
# --------------------------------------------------------------------------
|
||||
@classmethod
|
||||
def assign_role(cls, role_id: int, user_id: int, context_id: int = 1) -> Any:
|
||||
"""Asigna un rol en Moodle a un usuario en un contexto específico (core_role_assign_roles)."""
|
||||
params = {
|
||||
'assignments[0][roleid]': role_id,
|
||||
'assignments[0][userid]': user_id,
|
||||
'assignments[0][contextid]': context_id
|
||||
}
|
||||
return cls.call('core_role_assign_roles', params, method='POST')
|
||||
|
||||
@classmethod
|
||||
def unassign_role(cls, role_id: int, user_id: int, context_id: int = 1) -> Any:
|
||||
"""Remueve un rol en Moodle (core_role_unassign_roles)."""
|
||||
params = {
|
||||
'unassignments[0][roleid]': role_id,
|
||||
'unassignments[0][userid]': user_id,
|
||||
'unassignments[0][contextid]': context_id
|
||||
}
|
||||
return cls.call('core_role_unassign_roles', params, method='POST')
|
||||
|
||||
@classmethod
|
||||
def create_users(cls, users: List[Dict[str, Any]]) -> Any:
|
||||
params = {}
|
||||
for idx, u in enumerate(users):
|
||||
for k, v in u.items():
|
||||
params[f'users[{idx}][{k}]'] = v
|
||||
return cls.call('core_user_create_users', params, method='POST')
|
||||
|
||||
@classmethod
|
||||
def update_users(cls, users: List[Dict[str, Any]]) -> Any:
|
||||
params = {}
|
||||
for idx, u in enumerate(users):
|
||||
for k, v in u.items():
|
||||
params[f'users[{idx}][{k}]'] = v
|
||||
return cls.call('core_user_update_users', params, method='POST')
|
||||
|
||||
@classmethod
|
||||
def enrol_users(cls, enrolments: List[Dict[str, Any]]) -> Any:
|
||||
params = {}
|
||||
for idx, e in enumerate(enrolments):
|
||||
params[f'enrolments[{idx}][roleid]'] = e.get('roleid', e.get('role_id', 5))
|
||||
params[f'enrolments[{idx}][userid]'] = e.get('userid', e.get('user_id'))
|
||||
params[f'enrolments[{idx}][courseid]'] = e.get('courseid', e.get('course_id'))
|
||||
return cls.call('enrol_manual_enrol_users', params, method='POST')
|
||||
|
||||
@classmethod
|
||||
def unenrol_users(cls, enrolments: List[Dict[str, Any]]) -> Any:
|
||||
params = {}
|
||||
for idx, e in enumerate(enrolments):
|
||||
params[f'enrolments[{idx}][roleid]'] = e.get('roleid', e.get('role_id', 5))
|
||||
params[f'enrolments[{idx}][userid]'] = e.get('userid', e.get('user_id'))
|
||||
params[f'enrolments[{idx}][courseid]'] = e.get('courseid', e.get('course_id'))
|
||||
return cls.call('enrol_manual_unenrol_users', params, method='POST')
|
||||
|
||||
@classmethod
|
||||
def get_users(cls, criteria: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
params = {}
|
||||
for idx, c in enumerate(criteria):
|
||||
params[f'criteria[{idx}][key]'] = c.get('key')
|
||||
params[f'criteria[{idx}][value]'] = c.get('value')
|
||||
res = cls.call('core_user_get_users', params)
|
||||
return res.get('users', []) if isinstance(res, dict) else []
|
||||
|
||||
moodle_client = MoodleClient()
|
||||
@@ -0,0 +1,203 @@
|
||||
"""
|
||||
Moodle Queue Service (admin-edu-space)
|
||||
Provides asynchronous, fault-tolerant queuing and processing of synchronization
|
||||
operations between admin-edu-space and Moodle 4.1.
|
||||
Implements Exponential Backoff and Dead Letter Queue (DLQ).
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from app import db
|
||||
from app.models.sync_task import MoodleSyncTask
|
||||
from app.services.moodle_client import moodle_client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class MoodleQueueService:
|
||||
@staticmethod
|
||||
def enqueue_task(action: str, entity_type: str, entity_id: str = None, payload: dict = None, max_attempts: int = 5) -> MoodleSyncTask:
|
||||
"""
|
||||
Enqueues a new synchronization task to be processed asynchronously.
|
||||
Guarantees that local transactions are never blocked by Moodle unavailability.
|
||||
"""
|
||||
task = MoodleSyncTask(
|
||||
action=action,
|
||||
entity_type=entity_type,
|
||||
entity_id=str(entity_id) if entity_id else None,
|
||||
payload=payload or {},
|
||||
status='PENDING',
|
||||
attempts=0,
|
||||
max_attempts=max_attempts,
|
||||
next_retry_at=datetime.utcnow()
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
logger.info(f"[MoodleQueue] Enqueued task {task.id}: action={action}, entity={entity_type}:{entity_id}")
|
||||
return task
|
||||
|
||||
@staticmethod
|
||||
def process_pending_tasks(batch_size: int = 20) -> dict:
|
||||
"""
|
||||
Processes a batch of pending or retrying tasks.
|
||||
Uses exponential backoff for retries and sends to Dead Letter Queue (FAILED)
|
||||
if max_attempts are exceeded.
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
tasks = MoodleSyncTask.query.filter(
|
||||
MoodleSyncTask.status.in_(['PENDING', 'RETRYING']),
|
||||
(MoodleSyncTask.next_retry_at == None) | (MoodleSyncTask.next_retry_at <= now)
|
||||
).order_by(MoodleSyncTask.created_at.asc()).limit(batch_size).all()
|
||||
|
||||
results = {
|
||||
'processed': 0,
|
||||
'succeeded': 0,
|
||||
'failed': 0,
|
||||
'retrying': 0
|
||||
}
|
||||
|
||||
if not tasks:
|
||||
return results
|
||||
|
||||
for task in tasks:
|
||||
results['processed'] += 1
|
||||
task.status = 'PROCESSING'
|
||||
task.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
MoodleQueueService._execute_task_action(task)
|
||||
task.status = 'COMPLETED'
|
||||
task.error_message = None
|
||||
task.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
results['succeeded'] += 1
|
||||
logger.info(f"[MoodleQueue] Task {task.id} ({task.action}) completed successfully.")
|
||||
except Exception as e:
|
||||
task.attempts += 1
|
||||
task.error_message = str(e)
|
||||
task.updated_at = datetime.utcnow()
|
||||
|
||||
if task.attempts >= task.max_attempts:
|
||||
task.status = 'FAILED' # Dead Letter Queue (DLQ)
|
||||
task.next_retry_at = None
|
||||
results['failed'] += 1
|
||||
logger.error(f"[MoodleQueue] Task {task.id} permanently failed (DLQ): {e}")
|
||||
else:
|
||||
task.status = 'RETRYING'
|
||||
# Exponential Backoff: 30s, 60s, 120s, 240s... capped at 1 hour
|
||||
delay_seconds = min(3600, (2 ** task.attempts) * 30)
|
||||
task.next_retry_at = datetime.utcnow() + timedelta(seconds=delay_seconds)
|
||||
results['retrying'] += 1
|
||||
logger.warning(f"[MoodleQueue] Task {task.id} failed attempt {task.attempts}/{task.max_attempts}. Next retry in {delay_seconds}s: {e}")
|
||||
|
||||
db.session.commit()
|
||||
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def _execute_task_action(task: MoodleSyncTask):
|
||||
"""
|
||||
Executes the specific Moodle Web Service operation.
|
||||
Raises an exception on failure or error response.
|
||||
"""
|
||||
payload = task.payload or {}
|
||||
action = task.action.upper()
|
||||
|
||||
if action == 'CREATE_USER':
|
||||
users = payload.get('users') or [payload]
|
||||
res = moodle_client.create_users(users)
|
||||
return res
|
||||
|
||||
elif action == 'UPDATE_USER':
|
||||
users = payload.get('users') or [payload]
|
||||
res = moodle_client.update_users(users)
|
||||
return res
|
||||
|
||||
elif action == 'ENROL_USER':
|
||||
enrolments = payload.get('enrolments') or [payload]
|
||||
res = moodle_client.enrol_users(enrolments)
|
||||
return res
|
||||
|
||||
elif action == 'UNENROL_USER':
|
||||
enrolments = payload.get('enrolments') or [payload]
|
||||
res = moodle_client.unenrol_users(enrolments)
|
||||
return res
|
||||
|
||||
elif action == 'ASSIGN_ROLE':
|
||||
role_id = payload.get('role_id')
|
||||
user_id = payload.get('user_id')
|
||||
context_id = payload.get('context_id', 1)
|
||||
res = moodle_client.assign_role(role_id, user_id, context_id)
|
||||
return res
|
||||
|
||||
elif action == 'UNASSIGN_ROLE':
|
||||
role_id = payload.get('role_id')
|
||||
user_id = payload.get('user_id')
|
||||
context_id = payload.get('context_id', 1)
|
||||
res = moodle_client.unassign_role(role_id, user_id, context_id)
|
||||
return res
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unsupported sync action: {action}")
|
||||
|
||||
@staticmethod
|
||||
def retry_task(task_id: int) -> bool:
|
||||
"""
|
||||
Manually re-enqueues a task from DLQ or error state back to PENDING.
|
||||
"""
|
||||
task = MoodleSyncTask.query.get(task_id)
|
||||
if not task:
|
||||
return False
|
||||
|
||||
task.status = 'PENDING'
|
||||
task.attempts = 0
|
||||
task.next_retry_at = datetime.utcnow()
|
||||
task.error_message = None
|
||||
task.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
logger.info(f"[MoodleQueue] Task {task_id} manually reset to PENDING.")
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def retry_all_failed() -> int:
|
||||
"""
|
||||
Retries all tasks in FAILED status (DLQ).
|
||||
"""
|
||||
failed_tasks = MoodleSyncTask.query.filter_by(status='FAILED').all()
|
||||
count = 0
|
||||
for task in failed_tasks:
|
||||
task.status = 'PENDING'
|
||||
task.attempts = 0
|
||||
task.next_retry_at = datetime.utcnow()
|
||||
task.updated_at = datetime.utcnow()
|
||||
count += 1
|
||||
db.session.commit()
|
||||
logger.info(f"[MoodleQueue] Reset {count} failed tasks back to PENDING.")
|
||||
return count
|
||||
|
||||
@staticmethod
|
||||
def get_queue_summary() -> dict:
|
||||
"""
|
||||
Returns stats about tasks currently in the queue.
|
||||
"""
|
||||
counts = {
|
||||
'PENDING': 0,
|
||||
'PROCESSING': 0,
|
||||
'RETRYING': 0,
|
||||
'COMPLETED': 0,
|
||||
'FAILED': 0
|
||||
}
|
||||
from sqlalchemy import func
|
||||
rows = db.session.query(MoodleSyncTask.status, func.count(MoodleSyncTask.id)).group_by(MoodleSyncTask.status).all()
|
||||
for status, count in rows:
|
||||
if status in counts:
|
||||
counts[status] = count
|
||||
|
||||
total = sum(counts.values())
|
||||
return {
|
||||
'summary': counts,
|
||||
'total': total,
|
||||
'pending_total': counts['PENDING'] + counts['RETRYING'] + counts['PROCESSING'],
|
||||
'failed_dlq': counts['FAILED']
|
||||
}
|
||||
|
||||
moodle_queue_service = MoodleQueueService()
|
||||
Reference in New Issue
Block a user