import logging import secrets import string from backend.ws.agent_ws import ws_manager logger = logging.getLogger(__name__) async def dpm_command(device_id: str, command: str, **kwargs) -> bool: """ Sends an MDM command (lock, wipe, password reset, locate) to the Android device via the active WebSocket connection. The FamilyDeviceManagerService parses this. """ payload = { "event": "mdm:command", "payload": { "command": command, "args": kwargs } } try: # Assuming ws_manager can broadcast or target specific device names. # For this scope, we use send_to_device if implemented, otherwise broadcast # and let the device filter by device_name/id. await ws_manager.send_to_device(device_id, payload) return True except Exception as e: logger.error(f"Failed to send DPM command to {device_id}: {e}") return False def generate_secure_temp_password(length=12) -> str: alphabet = string.ascii_letters + string.digits + "!@#$%^&*" return "".join(secrets.choice(alphabet) for _ in range(length)) class FamilyDeviceController: async def remote_lock(self, device_id: str): await dpm_command(device_id, "lockNow") async def remote_wipe_sensitive_data(self, device_id: str): # Wipes app-specific data (payment apps, etc.) without full factory reset await dpm_command(device_id, "wipeData", flags=["WIPE_EXTERNAL_STORAGE"]) async def remote_wipe_full(self, device_id: str): # Full factory reset — for confirmed theft, not casual use await dpm_command(device_id, "wipeData", flags=["WIPE_RESET_PROTECTION_DATA"]) async def force_password_reset(self, device_id: str): new_pass = generate_secure_temp_password() await dpm_command(device_id, "resetPassword", new_password=new_pass) return new_pass async def locate_device(self, device_id: str) -> dict: # Request location update via WS, device will respond with location telemetry await dpm_command(device_id, "queryLocation") return {"status": "request_sent"}