diff --git a/.gitignore b/.gitignore index 9af5408..8b58756 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ plugins sftp-config.json .project .vscode +data/ +__pycache__/ diff --git a/core/ajax/mail.ajax.php b/core/ajax/mail.ajax.php new file mode 100644 index 0000000..ddeea8e --- /dev/null +++ b/core/ajax/mail.ajax.php @@ -0,0 +1,54 @@ +. +*/ + +try { + require_once dirname(__FILE__) . '/../../../../core/php/core.inc.php'; + include_file('core', 'authentification', 'php'); + + if (!isConnect('admin')) { + throw new Exception(__('401 - Accès non autorisé', __FILE__)); + } + + ajax::init(); + + $eqLogic = mail::byId(init('id')); + if (!is_object($eqLogic)) { + throw new Exception(__('Equipement introuvable, sauvegardez-le avant de connecter le compte', __FILE__) . ' : ' . init('id')); + } + + if (init('action') == 'oauthStart') { + ajax::success($eqLogic->oauthStart(init('provider'))); + } + + if (init('action') == 'oauthFinish') { + ajax::success($eqLogic->oauthFinish(init('url'))); + } + + if (init('action') == 'oauthPoll') { + ajax::success($eqLogic->oauthPoll()); + } + + if (init('action') == 'oauthDisconnect') { + $eqLogic->oauthDisconnect(); + ajax::success(); + } + + throw new Exception(__('Aucune méthode correspondante à', __FILE__) . ' : ' . init('action')); +} catch (Exception $e) { + ajax::error(displayException($e), $e->getCode()); +} diff --git a/core/class/mail.class.php b/core/class/mail.class.php index 7891012..d5e8e4e 100644 --- a/core/class/mail.class.php +++ b/core/class/mail.class.php @@ -31,6 +31,477 @@ class mail extends eqLogic { + /* * ***********************Methode static*************************** */ + + public static function cronDaily() { + foreach (eqLogic::byType(__CLASS__) as $eqLogic) { + $path = self::getAttachmentsPath($eqLogic->getId()); + if (!is_dir($path)) { + continue; + } + $days = max(1, intval($eqLogic->getConfiguration('imap::attachments::retention', 7))); + exec('find ' . escapeshellarg($path) . ' -type f -mtime +' . $days . ' -delete'); + exec('find ' . escapeshellarg($path) . ' -mindepth 1 -type d -empty -delete'); + } + } + + public static function getDataPath() { + $path = __DIR__ . '/../../data'; + if (!is_dir($path)) { + mkdir($path, 0775, true); + } + if (!file_exists($path . '/.htaccess')) { + // Received attachments must not be reachable from the web + file_put_contents($path . '/.htaccess', "Order allow,deny\nDeny from all\n"); + } + return realpath($path); + } + + public static function getAttachmentsPath($_eqLogic_id) { + return self::getDataPath() . '/attachments/' . $_eqLogic_id; + } + + public static function getReceptionCommands() { + // Ordered: values are updated in this order when a mail is received, subject last + return array( + 'receive::date' => __('Date de réception', __FILE__), + 'receive::from' => __('Expéditeur', __FILE__), + 'receive::fromName' => __('Nom expéditeur', __FILE__), + 'receive::to' => __('Destinataire', __FILE__), + 'receive::html' => __('HTML', __FILE__), + 'receive::body' => __('Texte', __FILE__), + 'receive::attachments' => __('Pièces jointes', __FILE__), + 'receive::subject' => __('Sujet', __FILE__), + ); + } + + public static function getListeners() { + $return = array(); + foreach (eqLogic::byType(__CLASS__, true) as $eqLogic) { + if ($eqLogic->getConfiguration('imap::enable', 0) == 1 && $eqLogic->getConfiguration('imap::server') != '') { + $return[] = $eqLogic; + } + } + return $return; + } + + public static function deamon_info() { + $return = array(); + $return['log'] = __CLASS__ . '_daemon'; + $return['launchable'] = 'ok'; + $return['state'] = self::isDaemonRunning() ? 'ok' : 'nok'; + if (count(self::getListeners()) == 0) { + // The daemon is only needed for mail reception + $return['state'] = 'ok'; + $return['launchable_message'] = __('Aucun équipement en réception', __FILE__); + } + return $return; + } + + public static function isDaemonRunning() { + $pid_file = jeedom::getTmpFolder(__CLASS__) . '/deamon.pid'; + if (!file_exists($pid_file)) { + return false; + } + if (@posix_getsid(intval(trim(file_get_contents($pid_file))))) { + return true; + } + shell_exec(system::getCmdSudo() . 'rm -rf ' . $pid_file . ' 2>&1 > /dev/null'); + return false; + } + + public static function deamon_start() { + self::deamon_stop(); + if (count(self::getListeners()) == 0) { + log::add(__CLASS__, 'info', __('Aucun équipement en réception, le démon n\'est pas lancé', __FILE__)); + return true; + } + $deamon_info = self::deamon_info(); + if ($deamon_info['launchable'] != 'ok') { + throw new Exception(__('Veuillez vérifier la configuration', __FILE__)); + } + $python = method_exists('system', 'getCmdPython3') ? trim(system::getCmdPython3(__CLASS__)) : 'python3'; + $cmd = $python . ' ' . realpath(__DIR__ . '/../../resources/maild') . '/maild.py'; + $cmd .= ' --loglevel ' . log::convertLogLevel(log::getLogLevel(__CLASS__)); + $cmd .= ' --socketport ' . intval(config::byKey('socketport', __CLASS__, 55072)); + $cmd .= ' --callback ' . escapeshellarg(network::getNetworkAccess('internal', 'http:127.0.0.1:port:comp') . '/plugins/mail/core/php/jeeMail.php'); + $cmd .= ' --apikey ' . escapeshellarg(jeedom::getApiKey(__CLASS__)); + $cmd .= ' --pid ' . escapeshellarg(jeedom::getTmpFolder(__CLASS__) . '/deamon.pid'); + $cmd .= ' --state ' . escapeshellarg(self::getDataPath() . '/state.json'); + log::add(__CLASS__, 'info', __('Lancement du démon de réception', __FILE__)); + exec($cmd . ' >> ' . log::getPathToLog(__CLASS__ . '_daemon') . ' 2>&1 &'); + $i = 0; + while ($i < 30) { + if (self::isDaemonRunning() && self::sendSync()) { + break; + } + sleep(1); + $i++; + } + if ($i >= 30) { + log::add(__CLASS__, 'error', __('Impossible de lancer le démon de réception, vérifiez le log', __FILE__), 'unableStartDeamon'); + return false; + } + message::removeAll(__CLASS__, 'unableStartDeamon'); + return true; + } + + public static function deamon_stop() { + $pid_file = jeedom::getTmpFolder(__CLASS__) . '/deamon.pid'; + if (file_exists($pid_file)) { + system::kill(intval(trim(file_get_contents($pid_file)))); + } + system::kill('maild.py'); + sleep(1); + } + + public static function sendToDaemon($_params) { + $_params['apikey'] = jeedom::getApiKey(__CLASS__); + $socket = @stream_socket_client('tcp://127.0.0.1:' . intval(config::byKey('socketport', __CLASS__, 55072)), $errno, $errstr, 5); + if ($socket === false) { + return false; + } + fwrite($socket, json_encode($_params) . "\n"); + fclose($socket); + return true; + } + + public static function sendSync() { + $accounts = array(); + foreach (self::getListeners() as $eqLogic) { + $accounts[] = $eqLogic->getDaemonConfig(); + } + return self::sendToDaemon(array('action' => 'sync', 'accounts' => $accounts)); + } + + public static function syncDaemon() { + if (count(self::getListeners()) == 0) { + if (self::isDaemonRunning()) { + self::deamon_stop(); + } + return; + } + if (!self::isDaemonRunning()) { + if (config::byKey('deamonAutoMode', __CLASS__, 1) == 1) { + self::deamon_start(); + } + return; + } + if (!self::sendSync()) { + log::add(__CLASS__, 'error', __('Impossible de transmettre la configuration au démon de réception', __FILE__)); + } + } + + public static function receive($_mail) { + $eqLogic = self::byId($_mail['eqLogic_id']); + if (!is_object($eqLogic) || $eqLogic->getEqType_name() != __CLASS__) { + return; + } + log::add(__CLASS__, 'info', $eqLogic->getHumanName() . ' ' . __('Mail reçu de', __FILE__) . ' ' . $_mail['from'] . ' : ' . $_mail['subject']); + $_mail['date'] = date('Y-m-d H:i:s', isset($_mail['timestamp']) ? intval($_mail['timestamp']) : time()); + foreach (array_keys(self::getReceptionCommands()) as $logicalId) { + $cmd = $eqLogic->getCmd('info', $logicalId); + if (!is_object($cmd)) { + continue; + } + $key = substr($logicalId, strlen('receive::')); + $value = $_mail[$key] ?? ''; + if (is_array($value)) { + $value = implode(',', $value); + } + $cmd->event($value); + } + } + + public static function receiveStatus($_status) { + $eqLogic = self::byId($_status['eqLogic_id']); + if (!is_object($eqLogic) || $eqLogic->getEqType_name() != __CLASS__) { + return; + } + $previous = $eqLogic->getCache('imap::status'); + $eqLogic->setCache(array('imap::status' => $_status['state'], 'imap::message' => $_status['message'])); + if ($_status['state'] == 'error' && $previous != 'error') { + log::add(__CLASS__, 'error', $eqLogic->getHumanName() . ' ' . __('Erreur de réception', __FILE__) . ' : ' . $_status['message']); + } elseif ($_status['state'] == 'ok' && $previous != 'ok') { + log::add(__CLASS__, 'info', $eqLogic->getHumanName() . ' ' . __('Connecté au serveur de réception', __FILE__)); + } + } + + public static function getOAuthProvider($_provider) { + switch ($_provider) { + case 'google': + $provider = array( + 'name' => 'Google', + 'auth_url' => 'https://accounts.google.com/o/oauth2/v2/auth', + 'token_url' => 'https://oauth2.googleapis.com/token', + // Desktop application client: Google accepts any loopback redirect without registration + 'redirect_uri' => 'http://127.0.0.1:47823/', + 'scope' => 'openid email https://mail.google.com/', + 'client_id' => trim(config::byKey('oauth::google::client_id', __CLASS__)), + 'client_secret' => trim(config::byKey('oauth::google::client_secret', __CLASS__)), + ); + break; + case 'microsoft': + $tenant = trim(config::byKey('oauth::microsoft::tenant', __CLASS__, 'common')); + if ($tenant == '') { + $tenant = 'common'; + } + $provider = array( + 'name' => 'Microsoft', + 'device_url' => 'https://login.microsoftonline.com/' . rawurlencode($tenant) . '/oauth2/v2.0/devicecode', + 'token_url' => 'https://login.microsoftonline.com/' . rawurlencode($tenant) . '/oauth2/v2.0/token', + 'scope' => 'openid email offline_access https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send', + 'client_id' => trim(config::byKey('oauth::microsoft::client_id', __CLASS__)), + 'client_secret' => '', + ); + break; + default: + throw new Exception(__('Fournisseur OAuth inconnu', __FILE__) . ' : ' . $_provider); + } + if ($provider['client_id'] == '') { + throw new Exception(__('Veuillez renseigner l\'identifiant client OAuth', __FILE__) . ' ' . $provider['name'] . ' ' . __('dans la configuration du plugin', __FILE__)); + } + return $provider; + } + + private static function oauthRequest($_url, $_params) { + $ch = curl_init($_url); + curl_setopt_array($ch, array( + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => http_build_query($_params), + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTPHEADER => array('Accept: application/json'), + )); + $response = curl_exec($ch); + if ($response === false) { + $error = curl_error($ch); + curl_close($ch); + throw new Exception(__('Erreur de connexion au serveur OAuth', __FILE__) . ' : ' . $error); + } + curl_close($ch); + $data = json_decode($response, true); + return is_array($data) ? $data : array(); + } + + private static function oauthError($_data) { + if (isset($_data['error_description'])) { + return $_data['error_description']; + } + return isset($_data['error']) ? $_data['error'] : __('réponse invalide', __FILE__); + } + + private static function base64url($_data) { + return rtrim(strtr(base64_encode($_data), '+/', '-_'), '='); + } + + /* * *********************Methode d'instance************************* */ + + public function decrypt() { + $this->setConfiguration('imap::password', utils::decrypt($this->getConfiguration('imap::password'))); + $this->setConfiguration('oauth::refresh_token', utils::decrypt($this->getConfiguration('oauth::refresh_token'))); + } + + public function encrypt() { + $this->setConfiguration('imap::password', utils::encrypt($this->getConfiguration('imap::password'))); + $this->setConfiguration('oauth::refresh_token', utils::encrypt($this->getConfiguration('oauth::refresh_token'))); + } + + public function getOAuthUser() { + if ($this->getConfiguration('oauth::account') != '') { + return $this->getConfiguration('oauth::account'); + } + if ($this->getConfiguration('imap::username') != '') { + return $this->getConfiguration('imap::username'); + } + return $this->getConfiguration('smtp::username'); + } + + /** + * Return a valid access token, refreshing it if needed. + * Shared by SMTP sending and by the reception daemon. + */ + public function getOAuthToken() { + $provider = self::getOAuthProvider($this->getConfiguration('oauth::provider')); + if ($this->getCache('oauth::expires', 0) > time() + 300) { + $token = utils::decrypt($this->getCache('oauth::access_token')); + if ($token != '') { + return array('user' => $this->getOAuthUser(), 'access_token' => $token); + } + } + if ($this->getConfiguration('oauth::refresh_token') == '') { + throw new Exception(__('Le compte', __FILE__) . ' ' . $provider['name'] . ' ' . __('n\'est pas connecté', __FILE__)); + } + $params = array( + 'client_id' => $provider['client_id'], + 'grant_type' => 'refresh_token', + 'refresh_token' => $this->getConfiguration('oauth::refresh_token'), + ); + if ($this->getConfiguration('oauth::provider') == 'microsoft') { + $params['scope'] = $provider['scope']; + } + if ($provider['client_secret'] != '') { + $params['client_secret'] = $provider['client_secret']; + } + $data = self::oauthRequest($provider['token_url'], $params); + if (!isset($data['access_token'])) { + throw new Exception(__('Impossible de renouveler le jeton', __FILE__) . ' ' . $provider['name'] . ' : ' . self::oauthError($data)); + } + $this->storeOAuthToken($data); + if (isset($data['refresh_token']) && $data['refresh_token'] != $this->getConfiguration('oauth::refresh_token')) { + // Microsoft rotates refresh tokens + $this->setConfiguration('oauth::refresh_token', $data['refresh_token']); + $this->save(true); + } + return array('user' => $this->getOAuthUser(), 'access_token' => $data['access_token']); + } + + private function storeOAuthToken($_data) { + $this->setCache(array( + 'oauth::access_token' => utils::encrypt($_data['access_token']), + 'oauth::expires' => time() + (isset($_data['expires_in']) ? intval($_data['expires_in']) : 3600), + )); + } + + public function oauthStart($_provider) { + $provider = self::getOAuthProvider($_provider); + if ($_provider == 'google') { + $verifier = self::base64url(random_bytes(32)); + $state = bin2hex(random_bytes(16)); + $this->setCache('oauth::pending', json_encode(array('provider' => $_provider, 'verifier' => $verifier, 'state' => $state, 'expires' => time() + 900))); + $url = $provider['auth_url'] . '?' . http_build_query(array( + 'client_id' => $provider['client_id'], + 'redirect_uri' => $provider['redirect_uri'], + 'response_type' => 'code', + 'scope' => $provider['scope'], + 'access_type' => 'offline', + 'prompt' => 'consent', + 'state' => $state, + 'code_challenge' => self::base64url(hash('sha256', $verifier, true)), + 'code_challenge_method' => 'S256', + )); + return array('type' => 'redirect', 'url' => $url); + } + $data = self::oauthRequest($provider['device_url'], array('client_id' => $provider['client_id'], 'scope' => $provider['scope'])); + if (!isset($data['device_code'])) { + throw new Exception(__('Erreur OAuth', __FILE__) . ' ' . $provider['name'] . ' : ' . self::oauthError($data)); + } + $interval = isset($data['interval']) ? intval($data['interval']) : 5; + $this->setCache('oauth::pending', json_encode(array('provider' => $_provider, 'device_code' => $data['device_code'], 'interval' => $interval, 'expires' => time() + intval($data['expires_in'])))); + return array('type' => 'device', 'user_code' => $data['user_code'], 'verification_uri' => $data['verification_uri'], 'interval' => $interval); + } + + private function getOAuthPending($_provider) { + $pending = json_decode($this->getCache('oauth::pending', ''), true); + if (!is_array($pending) || $pending['provider'] != $_provider || $pending['expires'] < time()) { + throw new Exception(__('Aucune connexion en cours ou délai dépassé, veuillez recommencer', __FILE__)); + } + return $pending; + } + + /** + * Google: the user pastes the address of the page Google redirected to (http://127.0.0.1:47823/?code=...) + */ + public function oauthFinish($_url) { + $pending = $this->getOAuthPending('google'); + $provider = self::getOAuthProvider('google'); + parse_str((string) parse_url(trim($_url), PHP_URL_QUERY), $query); + if (isset($query['error'])) { + throw new Exception(__('Autorisation refusée', __FILE__) . ' : ' . $query['error']); + } + if (!isset($query['code']) || !isset($query['state']) || !hash_equals($pending['state'], $query['state'])) { + throw new Exception(__('Adresse invalide, copiez l\'adresse complète de la page affichée après l\'autorisation', __FILE__)); + } + $data = self::oauthRequest($provider['token_url'], array( + 'client_id' => $provider['client_id'], + 'client_secret' => $provider['client_secret'], + 'grant_type' => 'authorization_code', + 'code' => $query['code'], + 'redirect_uri' => $provider['redirect_uri'], + 'code_verifier' => $pending['verifier'], + )); + return $this->oauthConnected('google', $data); + } + + /** + * Microsoft: called periodically while the user enters the code on microsoft.com/devicelogin + */ + public function oauthPoll() { + $pending = $this->getOAuthPending('microsoft'); + $provider = self::getOAuthProvider('microsoft'); + $data = self::oauthRequest($provider['token_url'], array( + 'client_id' => $provider['client_id'], + 'grant_type' => 'urn:ietf:params:oauth:grant-type:device_code', + 'device_code' => $pending['device_code'], + )); + if (isset($data['error']) && in_array($data['error'], array('authorization_pending', 'slow_down'))) { + return array('state' => 'pending'); + } + return $this->oauthConnected('microsoft', $data); + } + + private function oauthConnected($_provider, $_data) { + $this->setCache('oauth::pending', ''); + if (!isset($_data['refresh_token'])) { + throw new Exception(__('Erreur OAuth', __FILE__) . ' : ' . self::oauthError($_data)); + } + $account = ''; + if (isset($_data['id_token'])) { + $parts = explode('.', $_data['id_token']); + $claims = json_decode(base64_decode(strtr($parts[1], '-_', '+/')), true); + if (isset($claims['email'])) { + $account = $claims['email']; + } elseif (isset($claims['preferred_username'])) { + $account = $claims['preferred_username']; + } + } + $this->setConfiguration('oauth::provider', $_provider); + $this->setConfiguration('oauth::refresh_token', $_data['refresh_token']); + $this->setConfiguration('oauth::account', $account); + // Changes the daemon configuration so that the reception reconnects with the new token + $this->setConfiguration('oauth::connectedAt', time()); + $this->storeOAuthToken($_data); + $this->save(); + log::add(__CLASS__, 'info', $this->getHumanName() . ' ' . __('Compte OAuth connecté', __FILE__) . ' : ' . $account); + return array('state' => 'ok', 'account' => $account); + } + + public function oauthDisconnect() { + $this->setConfiguration('oauth::refresh_token', ''); + $this->setConfiguration('oauth::account', ''); + $this->setConfiguration('oauth::connectedAt', time()); + $this->setCache(array('oauth::access_token' => '', 'oauth::expires' => 0, 'oauth::pending' => '')); + $this->save(); + } + + public function getDaemonConfig() { + return array( + 'id' => $this->getId(), + 'name' => $this->getHumanName(), + 'server' => $this->getConfiguration('imap::server'), + 'port' => $this->getConfiguration('imap::port'), + 'security' => $this->getConfiguration('imap::security', 'ssl'), + 'username' => $this->getConfiguration('imap::username'), + 'password' => $this->getConfiguration('imap::password'), + 'oauth' => ($this->getConfiguration('oauth::provider', '') != ''), + 'oauthVersion' => $this->getConfiguration('oauth::connectedAt'), + 'dontcheckssl' => ($this->getConfiguration('imap::dontcheckssl', 0) == 1), + 'folder' => $this->getConfiguration('imap::folder', 'INBOX'), + 'markSeen' => ($this->getConfiguration('imap::markSeen', 0) == 1), + 'filterFrom' => $this->getConfiguration('imap::filter::from'), + 'filterSubject' => $this->getConfiguration('imap::filter::subject'), + 'attachments' => ($this->getConfiguration('imap::attachments', 0) == 1), + 'attachmentsPath' => self::getAttachmentsPath($this->getId()), + ); + } + + public function postRemove() { + $path = self::getAttachmentsPath($this->getId()); + if (is_dir($path)) { + exec('rm -rf ' . escapeshellarg($path)); + } + self::syncDaemon(); + } public function postSave() { $customEmail = $this->getCmd(null, 'send_to_custom_email'); @@ -45,6 +516,26 @@ public function postSave() { $customEmail->setDisplay('cmd_with_recipient', '1'); $customEmail->save(); } + if ($this->getConfiguration('imap::enable', 0) == 1) { + $visible = array('receive::date', 'receive::from', 'receive::subject'); + foreach (self::getReceptionCommands() as $logicalId => $name) { + $cmd = $this->getCmd('info', $logicalId); + if (is_object($cmd)) { + continue; + } + $cmd = new mailCmd(); + $cmd->setEqLogic_id($this->getId()); + $cmd->setLogicalId($logicalId); + $cmd->setName($name); + $cmd->setType('info'); + $cmd->setSubType('string'); + $cmd->setIsVisible(in_array($logicalId, $visible) ? 1 : 0); + // Two identical mails in a row must trigger scenarios twice + $cmd->setConfiguration('repeatEventManagement', 'always'); + $cmd->save(); + } + } + self::syncDaemon(); } } @@ -56,6 +547,9 @@ class mailCmd extends cmd { /* * *********************Methode d'instance************************* */ public function preSave() { + if ($this->getType() == 'info') { + return; + } if ($this->getLogicalId() == 'send_to_custom_email'){ $this->setConfiguration('recipient',''); return; @@ -93,6 +587,9 @@ public function getWidgetTemplateCode($_version = 'dashboard', $_clean = true, $ } public function execute($_options = null) { + if ($this->getType() == 'info') { + return; + } $eqLogic = $this->getEqLogic(); if ($_options === null) { throw new Exception(__('[Mail] Les options de la fonction ne peuvent être null', __FILE__)); @@ -144,7 +641,24 @@ public function execute($_options = null) { if ($eqLogic->getConfiguration('smtp::security', '') != '' && $eqLogic->getConfiguration('smtp::security', '') != 'none') { $mail->SMTPSecure = $eqLogic->getConfiguration('smtp::security', ''); } - if ($eqLogic->getConfiguration('smtp::username') != '') { + if ($eqLogic->getConfiguration('oauth::provider', '') != '') { + $token = $eqLogic->getOAuthToken(); + $mail->SMTPAuth = true; + $mail->AuthType = 'XOAUTH2'; + $mail->setOAuth(new class($token['user'], $token['access_token']) implements \PHPMailer\PHPMailer\OAuthTokenProvider { + private $user; + private $token; + + public function __construct($_user, $_token) { + $this->user = $_user; + $this->token = $_token; + } + + public function getOauth64() { + return base64_encode('user=' . $this->user . "\001auth=Bearer " . $this->token . "\001\001"); + } + }); + } elseif ($eqLogic->getConfiguration('smtp::username') != '') { $mail->SMTPAuth = true; $mail->Username = $eqLogic->getConfiguration('smtp::username'); // SMTP account username $mail->Password = $eqLogic->getConfiguration('smtp::password'); // SMTP account password diff --git a/core/php/jeeMail.php b/core/php/jeeMail.php new file mode 100644 index 0000000..0187991 --- /dev/null +++ b/core/php/jeeMail.php @@ -0,0 +1,50 @@ +. +*/ + +require_once dirname(__FILE__) . '/../../../../core/php/core.inc.php'; + +if (!jeedom::apiAccess(init('apikey'), 'mail')) { + echo __('Vous n\'êtes pas autorisé à effectuer cette action', __FILE__); + die(); +} + +$result = json_decode(file_get_contents('php://input'), true); +if (!is_array($result)) { + die(); +} + +if (isset($result['token'])) { + // Synchronous request from the daemon: answer with an OAuth access token + $eqLogic = mail::byId($result['token']['eqLogic_id']); + if (!is_object($eqLogic) || $eqLogic->getEqType_name() != 'mail') { + echo json_encode(array('error' => 'Unknown equipment')); + die(); + } + try { + echo json_encode($eqLogic->getOAuthToken()); + } catch (Exception $e) { + echo json_encode(array('error' => $e->getMessage())); + } + die(); +} +if (isset($result['status'])) { + mail::receiveStatus($result['status']); +} +if (isset($result['mail'])) { + mail::receive($result['mail']); +} diff --git a/desktop/js/mail.js b/desktop/js/mail.js index 8c8553d..99fad81 100644 --- a/desktop/js/mail.js +++ b/desktop/js/mail.js @@ -20,10 +20,150 @@ $('.eqLogicAttr[data-l1key=configuration][data-l2key=sendMode]').on('change', fu $('.sendMode.' + $(this).value()).show(); }); +$('.eqLogicAttr[data-l1key=configuration][data-l2key="imap::enable"]').on('change', function () { + $('.imapConfig').toggle($(this).value() == 1); +}); + +$('.eqLogicAttr[data-l1key=configuration][data-l2key="imap::security"]').on('change', function () { + $('.eqLogicAttr[data-l1key=configuration][data-l2key="imap::port"]').attr('placeholder', $(this).value() == 'ssl' ? '993' : '143'); +}); + +var mailOAuthPresets = { + google: {'smtp::server': 'smtp.gmail.com', 'smtp::port': '587', 'smtp::security': 'tls', 'imap::server': 'imap.gmail.com', 'imap::port': '993', 'imap::security': 'ssl'}, + microsoft: {'smtp::server': 'smtp.office365.com', 'smtp::port': '587', 'smtp::security': 'tls', 'imap::server': 'outlook.office365.com', 'imap::port': '993', 'imap::security': 'ssl'} +}; +var mailOAuthPollTimer = null; + +$('.eqLogicAttr[data-l1key=configuration][data-l2key="oauth::provider"]').on('change', function () { + var provider = $(this).value(); + $('.oauthConfig').toggle(provider != ''); + $('.passwordAuth').toggle(provider == ''); + mailOAuthReset(); + if (mailOAuthPresets[provider]) { + $.each(mailOAuthPresets[provider], function (key, value) { + var field = $('.eqLogicAttr[data-l1key=configuration][data-l2key="' + key + '"]'); + if (field.value() == '') { + field.value(value); + } + }); + } +}); + +function printEqLogic(_eqLogic) { + mailOAuthSetAccount(_eqLogic.configuration ? _eqLogic.configuration['oauth::account'] : ''); +} + +function mailOAuthSetAccount(_account) { + if (_account) { + $('#span_oauthAccount').removeClass('label-default').addClass('label-success').text(_account); + $('#bt_oauthDisconnect').show(); + } else { + $('#span_oauthAccount').removeClass('label-success').addClass('label-default').text('{{Non connecté}}'); + $('#bt_oauthDisconnect').hide(); + } +} + +function mailOAuthReset() { + clearTimeout(mailOAuthPollTimer); + $('#div_oauthGoogle, #div_oauthMicrosoft').hide(); + $('#in_oauthGoogleUrl').value(''); +} + +function mailAjax(_action, _data, _success) { + _data.action = _action; + _data.id = $('.eqLogicAttr[data-l1key=id]').value(); + $.ajax({ + type: 'POST', + url: 'plugins/mail/core/ajax/mail.ajax.php', + data: _data, + dataType: 'json', + error: function (request, status, error) { + handleAjaxError(request, status, error); + }, + success: function (data) { + if (data.state != 'ok') { + mailOAuthReset(); + jeedomUtils.showAlert({message: data.result, level: 'danger'}); + return; + } + _success(data.result); + } + }); +} + +function mailOAuthConnected(_result) { + mailOAuthReset(); + mailOAuthSetAccount(_result.account); + jeedomUtils.showAlert({message: '{{Compte connecté}} : ' + _result.account, level: 'success'}); +} + +function mailOAuthPoll(_interval) { + mailOAuthPollTimer = setTimeout(function () { + mailAjax('oauthPoll', {}, function (result) { + if (result.state == 'pending') { + mailOAuthPoll(_interval); + return; + } + mailOAuthConnected(result); + }); + }, _interval * 1000); +} + +$('#bt_oauthConnect').on('click', function () { + if ($('.eqLogicAttr[data-l1key=id]').value() == '') { + jeedomUtils.showAlert({message: '{{Sauvegardez l\'équipement avant de connecter le compte}}', level: 'warning'}); + return; + } + mailOAuthReset(); + var provider = $('.eqLogicAttr[data-l1key=configuration][data-l2key="oauth::provider"]').value(); + mailAjax('oauthStart', {provider: provider}, function (result) { + if (result.type == 'redirect') { + window.open(result.url, '_blank'); + $('#div_oauthGoogle').show(); + return; + } + $('#a_oauthMicrosoftUri').attr('href', result.verification_uri).text(result.verification_uri); + $('#span_oauthMicrosoftCode').text(result.user_code); + $('#div_oauthMicrosoft').show(); + window.open(result.verification_uri, '_blank'); + mailOAuthPoll(result.interval); + }); +}); + +$('#bt_oauthGoogleFinish').on('click', function () { + mailAjax('oauthFinish', {url: $('#in_oauthGoogleUrl').value()}, mailOAuthConnected); +}); + +$('#bt_oauthDisconnect').on('click', function () { + mailAjax('oauthDisconnect', {}, function () { + mailOAuthSetAccount(''); + }); +}); + function addCmdToTable(_cmd) { if (!isset(_cmd)) { var _cmd = {configuration: {}}; } + if (init(_cmd.type) == 'info') { + var tr = ''; + tr += ''; + tr += ''; + tr += ''; + tr += '{{Réception}} '; + tr += ''; + tr += ''; + tr += ''; + tr += ''; + tr += ''; + if (is_numeric(_cmd.id)) { + tr += ' '; + } + tr += ''; + tr += ''; + $('#table_cmd tbody').append(tr); + $('#table_cmd tbody tr:last').setValues(_cmd, '.cmdAttr'); + return; + } var tr = ''; tr += ''; tr += ''; diff --git a/desktop/php/mail.php b/desktop/php/mail.php index 8b97c72..a892f51 100644 --- a/desktop/php/mail.php +++ b/desktop/php/mail.php @@ -16,6 +16,11 @@
{{Ajouter}} +
+ +
+ {{Configuration}} +
{{Mes mails}}
  • +
  • {{Réception}}
  • {{Commandes}}
  • @@ -122,6 +128,45 @@
    +
    + +
    + +
    +
    + + +
    @@ -173,13 +218,13 @@
    -
    +
    -
    +
    @@ -197,6 +242,111 @@
    +
    +
    +
    +
    + {{Réception des mails (IMAP)}} +
    + +
    + +
    +
    +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    +
    +
    + {{Filtres}} +
    + +
    + +
    +
    +
    + +
    + +
    +
    + {{Pièces jointes}} +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    +
    +
    +
    {{Ajouter une commande mail}}

    diff --git a/docs/fr_FR/changelog.md b/docs/fr_FR/changelog.md index 4cba24e..f3330eb 100644 --- a/docs/fr_FR/changelog.md +++ b/docs/fr_FR/changelog.md @@ -4,6 +4,20 @@ > >Pour rappel s'il n'y a pas d'information sur la mise à jour, c'est que celle-ci concerne uniquement de la mise à jour de documentation, de traduction ou de texte +- Réception des mails (IMAP) : un équipement peut surveiller une boîte mail et déclencher des scénarios à chaque nouveau mail + - Nouvel onglet « Réception » : serveur, sécurité (SSL/TLS, STARTTLS), dossier surveillé, marquage des mails comme lus + - Filtres sur l'expéditeur et sur le sujet + - Nouvelles commandes info : date de réception, expéditeur, nom de l'expéditeur, destinataire, texte, HTML, pièces jointes et sujet. La commande « Sujet » est mise à jour en dernier pour servir de déclencheur, y compris pour deux mails consécutifs de même sujet + - Enregistrement optionnel des pièces jointes, avec suppression automatique après un nombre de jours configurable + - Réception instantanée (IMAP IDLE) avec reconnexion automatique ; les mails reçus pendant un arrêt de Jeedom sont traités au redémarrage + - Nouveau démon de réception, lancé uniquement si au moins un équipement a la réception activée (aucune dépendance supplémentaire) +- Authentification OAuth2 pour Google (Gmail, Google Workspace) et Microsoft (Microsoft 365, Outlook.com, Hotmail), en envoi (SMTP) comme en réception (IMAP) + - Nouveau champ « Authentification » sur les équipements, avec pré-remplissage des serveurs + - Connexion du compte depuis l'équipement, renouvellement automatique de l'accès + - Identifiants des applications OAuth2 à renseigner dans la configuration du plugin +- Ajout d'une page de configuration du plugin et d'un bouton « Configuration » sur la page du plugin +- Les mots de passe IMAP et les accès OAuth2 sont chiffrés en base +- Mise à jour de la documentation - Support des images d'équipement personnalisées (Jeedom 4.5) - Passage en mode dépendances diff --git a/docs/fr_FR/index.md b/docs/fr_FR/index.md index 8c0c6bc..b79d6f5 100644 --- a/docs/fr_FR/index.md +++ b/docs/fr_FR/index.md @@ -1,20 +1,35 @@ # Plugin Mail -Plugin permettant d’envoyer des mails. +Plugin permettant d’envoyer et de recevoir des mails : + +- **Envoi** : depuis un scénario, une interaction ou tout autre élément de Jeedom, par SMTP, Sendmail, Qmail, la fonction mail() de PHP ou le service Jeedom Cloud +- **Réception** : surveillance d’une boîte mail en IMAP, chaque nouveau mail met à jour des commandes info qui peuvent déclencher des scénarios +- **Authentification OAuth2** pour Google (Gmail, Google Workspace) et Microsoft (Microsoft 365, Outlook.com, Hotmail), en envoi comme en réception # Configuration du plugin -Après avoir installé le plugin, il vous suffit de l’activer. Ce plugin n’a aucune configuration particulière : +Après avoir installé le plugin, activez-le puis lancez l’installation des dépendances si Jeedom le demande. ![mail1](../images/mail1.PNG) +La page de configuration est accessible depuis **Plugins → Gestion des plugins → Mail**, ou avec le bouton **Configuration** de la page du plugin. Pour un simple envoi par mot de passe, aucun réglage n’est nécessaire. Elle contient : + +- **Démon** : état du démon de réception des mails. Il n’est lancé que si au moins un équipement a la réception activée ; sinon il apparaît comme OK avec le message « Aucun équipement en réception » +- **Port socket interne** : port local utilisé par Jeedom pour communiquer avec le démon (55072 par défaut). À ne modifier qu’en cas de conflit avec un autre plugin +- **Application OAuth2 Google** : ID client et code secret de l’application Google, nécessaires uniquement pour l’authentification Google OAuth2 +- **Application OAuth2 Microsoft** : ID d’application et locataire de l’application Microsoft, nécessaires uniquement pour l’authentification Microsoft OAuth2 + +La création de ces applications est détaillée dans le chapitre « Authentification OAuth2 » ci-dessous. + +Le démon a son propre log, `mail_daemon`, en plus du log `mail` du plugin. + # Configuration des équipements La configuration des équipements Mail est accessible à partir du menu plugin : ![mail2](../images/mail2.PNG) -Voilà à quoi ressemble la page du plugin Mail (ici avec déjà 1 mail, vous pouvez en mettre autant que vous voulez avec le bouton "Ajouter") : +Voilà à quoi ressemble la page du plugin Mail (ici avec déjà 1 mail, vous pouvez en mettre autant que vous voulez avec le bouton "Ajouter"). Le bouton "Configuration" ouvre la page de configuration du plugin : ![mail3](../images/mail3.PNG) @@ -30,6 +45,7 @@ Vous retrouvez ici toute la configuration de votre équipement : - **Visible** : rend votre équipement visible sur le dashboard - **Nom expéditeur** : nom de l’expéditeur du mail (ex : Jeedom) - **Mail expéditeur** : mail de l’expéditeur (ex : ) +- **Authentification** : mot de passe, Google (OAuth2) ou Microsoft 365 / Outlook (OAuth2). Elle sert à l’envoi SMTP comme à la réception IMAP, voir le chapitre « Authentification OAuth2 » ci-dessous - **Mode d’envoi** : mode d’envoi du mail : - Jeedom cloud : aucune configuration à faire, envoi des mails par le service Cloud Jeedom, en phase beta pour le moment, limité à 5 mails par jour - SMTP : mode le plus courant pour l’envoi de mails @@ -63,9 +79,9 @@ Voici quelques exemples pour les principaux fournisseurs de services email : > **Important** > -> Attention Google semble avoir changé sa politique au niveau de gmail et il n'est plus possible d'utiliser gmail avec le plugin (meme en utilisant une clef d'application). Cela ne semble en revanche pas impacter tous les comptes gmail (sans que nous aillons la regle de chez qui ca marche ou pas et pourquoi) +> Google et Microsoft restreignent de plus en plus l’accès par mot de passe. Pour Gmail, Google Workspace, Microsoft 365, Outlook.com et Hotmail, utilisez l’authentification OAuth2. -Les champs « Utilisateur SMTP » et « Mot de passe SMTP » correspondent aux identifiants de votre compte email. +Les champs « Utilisateur SMTP » et « Mot de passe SMTP » correspondent aux identifiants de votre compte email. Ils sont masqués en authentification OAuth2 : l’identité du compte connecté est alors utilisée. A partir de l’onglet "Commandes", vous pouvez ajouter des commandes qui correspondent aux adresses email auxquelles vous souhaitez pouvoir envoyer des emails avec Jeedom : @@ -77,6 +93,97 @@ A partir de l’onglet "Commandes", vous pouvez ajouter des commandes qui corres - **tester** : permet de tester la commande, - **supprimer** (signe -) : permet de supprimer la commande. +# Réception des mails + +Chaque équipement peut aussi surveiller une boîte mail en IMAP. Dès qu’un nouveau mail arrive, les commandes info de l’équipement sont mises à jour et peuvent déclencher un scénario. + +La configuration se fait dans l’onglet **Réception** de l’équipement : + +- **Activer la réception** : active la surveillance de la boîte mail +- **Serveur IMAP**, **Sécurité IMAP** et **Port IMAP** : paramètres de connexion au serveur (993 en SSL/TLS, 143 en STARTTLS ou sans sécurité) +- **Utilisateur IMAP** et **Mot de passe IMAP** : identifiants du compte (le mot de passe est chiffré en base). Ils sont masqués en authentification OAuth2 +- **Ne pas vérifier le certificat SSL** : à n’utiliser que pour un serveur local avec un certificat auto-signé +- **Dossier surveillé** : dossier IMAP à surveiller, `INBOX` par défaut +- **Marquer comme lu** : marque les mails traités comme lus sur le serveur. Sans cette option la boîte mail n’est pas modifiée +- **Expéditeurs** : ne traite que les mails dont l’adresse de l’expéditeur contient l’une des valeurs indiquées (séparées par des virgules), par exemple `alarme@exemple.com, @mondomaine.fr` +- **Sujet contient** : ne traite que les mails dont le sujet contient ce texte +- **Enregistrer les pièces jointes** : enregistre les pièces jointes sur Jeedom. Elles sont supprimées automatiquement après le nombre de jours indiqué dans **Conservation** (7 par défaut) + +La réception utilise un démon, visible sur la page de configuration du plugin. Il n’est lancé que si au moins un équipement a la réception activée. Il est prévenu instantanément par le serveur (IMAP IDLE) ; si le serveur ne le permet pas, la boîte est vérifiée toutes les minutes. + +Au premier lancement, seuls les mails arrivés après l’activation sont traités. Si le démon est arrêté puis relancé, les mails reçus entre-temps sont traités à son redémarrage. + +Une fois la réception activée et l’équipement sauvegardé, les commandes info suivantes sont créées : + +- **Date de réception** +- **Expéditeur** : adresse mail de l’expéditeur +- **Nom expéditeur** +- **Destinataire** +- **HTML** : contenu HTML du mail +- **Texte** : contenu texte du mail (calculé à partir du HTML si le mail n’a pas de version texte) +- **Pièces jointes** : chemins des pièces jointes enregistrées, séparés par des virgules. Ils peuvent être réutilisés tels quels dans l’option « fichiers » d’une commande d’envoi de mail +- **Sujet** + +Les commandes sont mises à jour dans cet ordre, la commande **Sujet** en dernier. Pour déclencher un scénario à la réception d’un mail, utilisez donc la commande **Sujet** comme déclencheur : toutes les autres informations du mail sont déjà à jour. Le scénario est déclenché même si deux mails consécutifs ont le même sujet. + +> **Important** +> +> Microsoft (Outlook, Hotmail, Microsoft 365) n’autorise plus la connexion IMAP ni SMTP par mot de passe : utilisez l’authentification OAuth2 décrite ci-dessous. Pour Gmail, vous pouvez utiliser OAuth2 ou un mot de passe d’application. + +Quelques exemples de serveurs IMAP : + +- **Gmail** : imap.gmail.com, port 993, SSL/TLS +- **iCloud** : imap.mail.me.com, port 993, SSL/TLS +- **Yahoo.com** : imap.mail.yahoo.com, port 993, SSL/TLS +- **Orange** : imap.orange.fr, port 993, SSL/TLS +- **Free** : imap.free.fr, port 993, SSL/TLS + +# Authentification OAuth2 (Google et Microsoft 365) + +Le champ **Authentification** de l’équipement permet de choisir entre un mot de passe et une connexion OAuth2 à un compte Google ou Microsoft (Microsoft 365, Outlook.com, Hotmail). L’authentification choisie sert à la fois à l’envoi (SMTP) et à la réception (IMAP). En OAuth2, aucun mot de passe n’est enregistré dans Jeedom. + +En choisissant Google ou Microsoft, les serveurs et ports SMTP et IMAP sont pré-remplis s’ils sont vides. + +## Prérequis : déclarer une application OAuth2 + +Google et Microsoft n’autorisent l’accès aux mails qu’à une application déclarée chez eux. Ses identifiants se renseignent une seule fois, dans la page de configuration du plugin (bouton **Configuration** de la page du plugin) ; une même application sert pour tous les équipements. + +### Google + +1. Dans la [console Google Cloud](https://console.cloud.google.com/), créez un projet +2. Dans **API et services → Écran de consentement OAuth**, configurez l’écran de consentement (type « Externe » pour un compte Gmail, « Interne » pour Google Workspace), puis ajoutez votre adresse comme utilisateur test +3. Dans **API et services → Identifiants**, créez un **ID client OAuth** de type **Application de bureau** +4. Recopiez l’**ID client** et le **Code secret du client** dans la configuration du plugin + +> **Important** +> +> Avec Google Workspace, choisissez le type « Interne » : aucune validation Google n’est nécessaire et la connexion n’expire pas. Si IMAP est désactivé, l’administrateur doit l’autoriser dans la console d’administration (**Applications → Google Workspace → Gmail → Accès des utilisateurs finaux**). +> +> Tant que l’application est en mode « Test » chez Google, la connexion expire au bout de 7 jours. Pour un compte Gmail personnel, passez l’application en « Production » dans l’écran de consentement (Google affichera un avertissement « application non validée » lors de la connexion, il suffit de continuer). Ce n’est pas nécessaire pour une application « Interne » Google Workspace. + +### Microsoft + +1. Dans le [portail Microsoft Entra](https://entra.microsoft.com/), ouvrez **Inscriptions d’applications → Nouvelle inscription** +2. Choisissez « Comptes dans un annuaire d’organisation et comptes Microsoft personnels » (ou seulement votre organisation), sans URI de redirection +3. Dans **Authentification**, activez **Autoriser les flux de clients publics** +4. Dans **Autorisations de l’API → Ajouter une autorisation → API utilisées par mon organisation → Office 365 Exchange Online**, ajoutez les autorisations déléguées **IMAP.AccessAsUser.All** et **SMTP.Send** +5. Recopiez l’**ID d’application (client)** dans la configuration du plugin. Si l’application n’accepte que les comptes de votre organisation, indiquez aussi l’ID du locataire (sinon laissez `common`) + +Sur Microsoft 365, l’administrateur doit aussi autoriser IMAP et « SMTP authentifié » pour la boîte mail concernée. + +## Connecter le compte + +Sauvegardez l’équipement après avoir choisi Google ou Microsoft, puis cliquez sur **Connecter le compte** : + +- **Google** : une fenêtre Google s’ouvre pour autoriser l’accès. Google redirige ensuite vers une page qui ne s’affiche pas (adresse `http://127.0.0.1:47823/...`) : c’est normal. Copiez l’adresse complète de cette page, collez-la dans le champ affiché par Jeedom et cliquez sur **Valider** +- **Microsoft** : Jeedom affiche un code. Saisissez-le sur la page Microsoft qui s’ouvre, puis connectez-vous ; Jeedom détecte automatiquement la fin de l’autorisation + +Le compte connecté s’affiche ensuite à côté du bouton. La connexion est renouvelée automatiquement. Le bouton **Déconnecter** supprime les accès enregistrés dans Jeedom. + +En cas de problème (application supprimée, accès révoqué depuis le compte Google ou Microsoft, mot de passe du compte changé…), l’erreur est indiquée dans les logs `mail` et `mail_daemon` : cliquez à nouveau sur **Connecter le compte**. + +# Utilisation + Ce plugin fonctionne comme un module, c’est-à-dire qu’une fois sauvegardé, il apparaît dans la liste des actions ou commandes. Il est ainsi très simple de l’utiliser lors de la création de scénarios par exemple. Dans un scénario, une fois sélectionné dans une action, il faudra saisir le titre et le message. @@ -85,7 +192,7 @@ Dans un scénario, une fois sélectionné dans une action, il faudra saisir le t > **Important** > -> Si vous êtes en double authentification avec Gmail il faut donner un mot de passe spécifique pour l’application : Mon compte ⇒ connexion et sécurité ⇒ Se connecter à Google ⇒ Mots de passe d’application, si ce n'est pas le cas vous devez renseigner votre mot de passe Gmail habituel. +> En authentification par mot de passe avec Gmail, il faut utiliser un mot de passe d’application : Mon compte ⇒ Sécurité ⇒ Validation en deux étapes ⇒ Mots de passe des applications. L’authentification OAuth2 évite cette manipulation. > **Tip** > diff --git a/plugin_info/configuration.php b/plugin_info/configuration.php new file mode 100644 index 0000000..b383e21 --- /dev/null +++ b/plugin_info/configuration.php @@ -0,0 +1,69 @@ +. +*/ + +require_once dirname(__FILE__) . '/../../../core/php/core.inc.php'; +include_file('core', 'authentification', 'php'); +if (!isConnect()) { + include_file('desktop', '404', 'php'); + die(); +} +?> +
    +
    + {{Démon de réception}} +
    + +
    + +
    +
    + {{Application OAuth2 Google}} +
    + +
    + +
    +
    +
    + +
    + +
    +
    + {{Application OAuth2 Microsoft}} +
    + +
    + +
    +
    +
    + +
    + +
    +
    +
    +
    diff --git a/plugin_info/info.json b/plugin_info/info.json index 70ed47b..46d07f2 100644 --- a/plugin_info/info.json +++ b/plugin_info/info.json @@ -17,6 +17,7 @@ "author": "Loïc", "require": "4.4", "hasDependency": true, + "hasOwnDeamon": true, "category": "communication", "changelog": "https:\/\/doc.jeedom.com\/#language#\/plugins\/communication\/mail\/changelog", "documentation": "https:\/\/doc.jeedom.com\/#language#\/plugins\/communication\/mail\/", diff --git a/resources/maild/.htaccess b/resources/maild/.htaccess new file mode 100644 index 0000000..7d3aaf1 --- /dev/null +++ b/resources/maild/.htaccess @@ -0,0 +1,2 @@ +Order allow,deny +Deny from all \ No newline at end of file diff --git a/resources/maild/maild.py b/resources/maild/maild.py new file mode 100644 index 0000000..8003cac --- /dev/null +++ b/resources/maild/maild.py @@ -0,0 +1,600 @@ +# This file is part of Jeedom. +# +# Jeedom is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Jeedom is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Jeedom. If not, see . + +# Mail reception daemon (IMAP IDLE). +# Only uses the Python standard library so that the plugin keeps working without +# any pip dependency (python >= 3.9). + +import argparse +import email +import email.policy +import email.utils +import hashlib +import html +import imaplib +import json +import logging +import os +import queue +import re +import select +import signal +import socket +import socketserver +import ssl +import sys +import threading +import time +import traceback +import urllib.request + +IDLE_TIMEOUT = 25 * 60 # RFC 2177: re-issue IDLE before the 29 minutes server timeout +POLL_INTERVAL = 60 # used when the server does not support IDLE +SOCKET_TIMEOUT = 120 +RECONNECT_MIN = 10 +RECONNECT_MAX = 300 +MAX_TEXT_LENGTH = 100000 + + +def convert_log_level(level='error'): + levels = { + 'debug': logging.DEBUG, + 'info': logging.INFO, + 'notice': logging.WARNING, + 'warning': logging.WARNING, + 'error': logging.ERROR, + 'critical': logging.CRITICAL, + 'none': logging.CRITICAL + } + return levels.get(level, logging.CRITICAL) + + +class JeedomCallback(): + """Send events to Jeedom, one after the other to keep their order.""" + + def __init__(self, url, apikey, retry=3): + self._url = url + ('&' if '?' in url else '?') + 'apikey=' + apikey + self._retry = retry + self._queue = queue.Queue() + threading.Thread(target=self._loop, daemon=True).start() + + def test(self): + try: + with urllib.request.urlopen(self._url, timeout=10) as response: + return response.status == 200 + except Exception as e: + logging.error('Callback error: %s. Please check your network configuration page', e) + return False + + def send(self, data): + self._queue.put(data) + + def request(self, data): + """Synchronous call, returns the JSON answered by Jeedom.""" + request = urllib.request.Request(self._url, data=json.dumps(data).encode('utf-8'), headers={'Content-Type': 'application/json'}, method='POST') + with urllib.request.urlopen(request, timeout=60) as response: + return json.loads(response.read().decode('utf-8')) + + def _loop(self): + while True: + data = self._queue.get() + payload = json.dumps(data).encode('utf-8') + for i in range(self._retry): + try: + request = urllib.request.Request(self._url, data=payload, headers={'Content-Type': 'application/json'}, method='POST') + with urllib.request.urlopen(request, timeout=60) as response: + if response.status == 200: + break + logging.warning('Error on send request to jeedom, return code %s', response.status) + except Exception as e: + logging.error('Error on send request to jeedom "%s" retry: %i/%i', e, i + 1, self._retry) + time.sleep(1) + + +class IMAPBufferMixin(): + """Replace imaplib buffered file by our own buffer. + + imaplib reads through sock.makefile() whose internal buffer can't be inspected + without blocking, which makes it impossible to wait for IDLE notifications with + select(). Reading the socket ourselves lets us know when data is pending. + """ + + def open(self, host='', port=None, timeout=None): + self._rbuf = bytearray() + super().open(host, port, timeout) + + def _fill(self): + data = self.sock.recv(65536) + if not data: + raise imaplib.IMAP4.abort('socket error: EOF') + self._rbuf += data + + def read(self, size): + while len(self._rbuf) < size: + self._fill() + data = bytes(self._rbuf[:size]) + del self._rbuf[:size] + return data + + def readline(self): + while True: + pos = self._rbuf.find(b'\n') + if pos != -1: + break + if len(self._rbuf) > imaplib._MAXLINE: + raise self.error('got more than %d bytes' % imaplib._MAXLINE) + self._fill() + data = bytes(self._rbuf[:pos + 1]) + del self._rbuf[:pos + 1] + return data + + def has_pending_data(self): + if len(self._rbuf) > 0: + return True + return isinstance(self.sock, ssl.SSLSocket) and self.sock.pending() > 0 + + def idle(self, stop_event, timeout): + """Run IDLE until the mailbox changes, timeout expires or stop is requested.""" + tag = self._new_tag() + self.send(tag + b' IDLE\r\n') + changed = False + while True: + # Untagged responses may arrive before the continuation + line = self.readline() + if line.startswith(b'+'): + break + if line.startswith(tag): + raise self.error('IDLE refused: %r' % line) + if re.match(rb'^\* \d+ (EXISTS|RECENT)', line): + changed = True + end = time.monotonic() + timeout + while not changed and not stop_event.is_set(): + remaining = end - time.monotonic() + if remaining <= 0: + break + if not self.has_pending_data(): + readable, _, _ = select.select([self.sock], [], [], min(remaining, 5)) + if not readable: + continue + line = self.readline() + logging.debug('IDLE: %r', line) + if line.startswith(b'* BYE'): + raise self.abort('server closed connection: %r' % line) + if re.match(rb'^\* \d+ (EXISTS|RECENT)', line): + changed = True + break + self.send(b'DONE\r\n') + while True: + line = self.readline() + if line.startswith(tag): + if not line.startswith(tag + b' OK'): + raise self.error('IDLE failed: %r' % line) + break + if re.match(rb'^\* \d+ (EXISTS|RECENT)', line): + changed = True + return changed + + +class IMAP4(IMAPBufferMixin, imaplib.IMAP4): + pass + + +class IMAP4_SSL(IMAPBufferMixin, imaplib.IMAP4_SSL): + pass + + +def quote_mailbox(name): + return '"' + name.replace('\\', '\\\\').replace('"', '\\"') + '"' + + +def safe_filename(name): + name = os.path.basename(name or '').strip() + name = re.sub(r'[^\w.\- ]', '_', name) + name = name.lstrip('.') + return name[:150] or 'attachment' + + +def error_message(e): + if e.args and isinstance(e.args[0], bytes): + return e.args[0].decode('utf-8', errors='replace') + return str(e) + + +def part_content(part): + try: + return part.get_content() + except Exception: + payload = part.get_payload(decode=True) or b'' + try: + return payload.decode(part.get_content_charset() or 'utf-8', errors='replace') + except LookupError: + return payload.decode('utf-8', errors='replace') + + +def html_to_text(content): + content = re.sub(r'(?is)<(script|style).*?', '', content) + content = re.sub(r'(?i)|

    |
    |', '\n', content) + content = re.sub(r'<[^>]+>', '', content) + content = html.unescape(content).replace('\xa0', ' ') + content = re.sub(r'[ \t]+', ' ', content) + return re.sub(r'\n\s*\n+', '\n\n', content).strip() + + +class Account(threading.Thread): + + def __init__(self, config, callback, state): + super().__init__(daemon=True) + self.config = config + self.id = str(config['id']) + self.name = config.get('name', self.id) + self.callback = callback + self.state = state + self.stop_event = threading.Event() + self.imap = None + + def stop(self): + self.stop_event.set() + imap = self.imap + if imap is not None: + try: + imap.sock.shutdown(socket.SHUT_RDWR) + except Exception: + pass + + def status(self, state, message=''): + self.callback.send({'status': {'eqLogic_id': self.id, 'state': state, 'message': message}}) + + def run(self): + delay = RECONNECT_MIN + while not self.stop_event.is_set(): + try: + self.connect() + delay = RECONNECT_MIN + self.status('ok') + self.listen() + except Exception as e: + if self.stop_event.is_set(): + break + message = error_message(e) + logging.error('[%s] %s', self.name, message) + logging.debug(traceback.format_exc()) + self.status('error', message) + finally: + self.disconnect() + if self.stop_event.wait(delay): + break + delay = min(delay * 2, RECONNECT_MAX) + logging.info('[%s] Stopped', self.name) + + def connect(self): + config = self.config + context = ssl.create_default_context() + if config.get('dontcheckssl'): + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + host = config['server'] + security = config.get('security', 'ssl') + port = int(config.get('port') or (993 if security == 'ssl' else 143)) + logging.info('[%s] Connecting to %s:%s (%s)', self.name, host, port, security) + if security == 'ssl': + self.imap = IMAP4_SSL(host, port, ssl_context=context, timeout=SOCKET_TIMEOUT) + else: + self.imap = IMAP4(host, port, timeout=SOCKET_TIMEOUT) + if security == 'starttls': + self.imap.starttls(ssl_context=context) + self.imap.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + if config.get('oauth'): + self.login_oauth() + else: + self.imap.login(config['username'], config['password']) + typ, data = self.imap.select(quote_mailbox(config.get('folder') or 'INBOX')) + if typ != 'OK': + raise Exception('Unable to open folder %s: %s' % (config.get('folder'), data)) + logging.info('[%s] Connected, capabilities: %s', self.name, ' '.join(self.imap.capabilities)) + + def login_oauth(self): + token = self.callback.request({'token': {'eqLogic_id': self.id}}) + if 'error' in token: + raise Exception(token['error']) + auth_string = 'user=%s\x01auth=Bearer %s\x01\x01' % (token['user'], token['access_token']) + sent = [] + + def authobject(challenge): + # On failure the server sends an error challenge, answer it with an empty line + if sent: + return b'' + sent.append(True) + return auth_string.encode('utf-8') + self.imap.authenticate('XOAUTH2', authobject) + + def disconnect(self): + imap, self.imap = self.imap, None + if imap is None: + return + try: + imap.logout() + except Exception: + pass + + def response_value(self, name): + typ, data = self.imap.response(name) + if data and data[0] is not None: + return int(data[0]) + return None + + def listen(self): + uidvalidity = self.response_value('UIDVALIDITY') + uidnext = self.response_value('UIDNEXT') + saved = self.state.get(self.id) + if saved is None or saved.get('uidvalidity') != uidvalidity: + # First start (or mailbox recreated): don't flood Jeedom with old mails + if uidnext is None: + typ, data = self.imap.uid('SEARCH', None, 'ALL') + uids = [int(u) for u in data[0].split()] if typ == 'OK' and data[0] else [] + uidnext = max(uids) + 1 if uids else 1 + self.state.set(self.id, {'uidvalidity': uidvalidity, 'last_uid': uidnext - 1}) + use_idle = 'IDLE' in self.imap.capabilities + if not use_idle: + logging.warning('[%s] Server does not support IDLE, polling every %ss', self.name, POLL_INTERVAL) + while not self.stop_event.is_set(): + self.fetch_new(uidvalidity) + if use_idle: + self.imap.idle(self.stop_event, IDLE_TIMEOUT) + else: + if self.stop_event.wait(POLL_INTERVAL): + break + self.imap.noop() + + def fetch_new(self, uidvalidity): + last_uid = self.state.get(self.id)['last_uid'] + typ, data = self.imap.uid('SEARCH', None, 'UID %d:*' % (last_uid + 1)) + if typ != 'OK' or not data[0]: + return + # "n:*" always returns the last message, even if its uid is lower than n + uids = sorted(int(u) for u in data[0].split() if int(u) > last_uid) + for uid in uids: + if self.stop_event.is_set(): + return + typ, data = self.imap.uid('FETCH', str(uid), '(BODY.PEEK[])') + raw = None + if typ == 'OK': + for part in data: + if isinstance(part, tuple): + raw = part[1] + break + if raw is None: + logging.warning('[%s] Unable to fetch mail uid %s', self.name, uid) + else: + try: + self.process(uid, raw) + except Exception as e: + logging.error('[%s] Error processing mail uid %s: %s', self.name, uid, e) + logging.debug(traceback.format_exc()) + self.state.set(self.id, {'uidvalidity': uidvalidity, 'last_uid': uid}) + + def match_filters(self, from_addr, subject): + filter_from = [f.strip().lower() for f in (self.config.get('filterFrom') or '').split(',') if f.strip()] + if filter_from and not any(f in from_addr.lower() for f in filter_from): + return False + filter_subject = (self.config.get('filterSubject') or '').strip().lower() + if filter_subject and filter_subject not in subject.lower(): + return False + return True + + def process(self, uid, raw): + msg = email.message_from_bytes(raw, policy=email.policy.default) + from_name, from_addr = email.utils.parseaddr(str(msg.get('From', ''))) + subject = str(msg.get('Subject', '') or '').strip() + if not self.match_filters(from_addr, subject): + logging.info('[%s] Mail uid %s from %s ignored by filters', self.name, uid, from_addr) + return + logging.info('[%s] New mail uid %s from %s: %s', self.name, uid, from_addr, subject) + + body = '' + html_body = '' + part = msg.get_body(preferencelist=('plain',)) + if part is not None: + body = part_content(part) + part = msg.get_body(preferencelist=('html',)) + if part is not None: + html_body = part_content(part) + if body == '' and html_body != '': + body = html_to_text(html_body) + + # Sent as a timestamp: Jeedom formats it with its own timezone + try: + timestamp = int(email.utils.parsedate_to_datetime(str(msg.get('Date'))).timestamp()) + except Exception: + timestamp = int(time.time()) + + attachments = [] + if self.config.get('attachments') and self.config.get('attachmentsPath'): + attachments = self.save_attachments(msg, uid) + + self.callback.send({'mail': { + 'eqLogic_id': self.id, + 'uid': uid, + 'from': from_addr, + 'fromName': from_name, + 'to': ', '.join(addr for _, addr in email.utils.getaddresses([str(v) for v in msg.get_all('To', [])])), + 'subject': subject, + 'body': body.strip()[:MAX_TEXT_LENGTH], + 'html': html_body[:MAX_TEXT_LENGTH], + 'timestamp': timestamp, + 'attachments': attachments + }}) + + if self.config.get('markSeen'): + self.imap.uid('STORE', str(uid), '+FLAGS', '(\\Seen)') + + def save_attachments(self, msg, uid): + folder = os.path.join(self.config['attachmentsPath'], str(uid)) + files = [] + for part in msg.iter_attachments(): + content = part.get_payload(decode=True) + if content is None: + continue + os.makedirs(folder, exist_ok=True) + name = safe_filename(part.get_filename()) + path = os.path.join(folder, name) + index = 1 + while path in files or os.path.exists(path): + base, ext = os.path.splitext(name) + path = os.path.join(folder, '%s_%d%s' % (base, index, ext)) + index += 1 + with open(path, 'wb') as f: + f.write(content) + files.append(path) + logging.debug('[%s] Attachment saved: %s', self.name, path) + return files + + +class State(): + """Last processed uid of each account, kept on disk to catch up after a restart.""" + + def __init__(self, path): + self._path = path + self._lock = threading.Lock() + self._data = {} + try: + with open(path) as f: + self._data = json.load(f) + except Exception: + pass + + def get(self, key): + with self._lock: + return self._data.get(key) + + def set(self, key, value): + with self._lock: + self._data[key] = value + tmp = self._path + '.tmp' + with open(tmp, 'w') as f: + json.dump(self._data, f) + os.replace(tmp, self._path) + + +class Daemon(): + + def __init__(self, apikey, callback, state): + self.apikey = apikey + self.callback = callback + self.state = state + self.accounts = {} + self.hashes = {} + self.lock = threading.Lock() + + def handle(self, message): + if message.get('apikey') != self.apikey: + logging.error('Invalid apikey from socket') + return + if message.get('action') == 'sync': + self.sync(message.get('accounts', [])) + + def sync(self, configs): + with self.lock: + wanted = {} + for config in configs: + key = str(config['id']) + wanted[key] = config + for key in list(self.accounts): + new_hash = self.config_hash(wanted[key]) if key in wanted else None + if new_hash != self.hashes[key]: + logging.info('[%s] Configuration removed or changed, stopping', self.accounts[key].name) + self.accounts[key].stop() + self.accounts[key].join(10) + del self.accounts[key] + del self.hashes[key] + for key, config in wanted.items(): + if key in self.accounts: + continue + account = Account(config, self.callback, self.state) + self.accounts[key] = account + self.hashes[key] = self.config_hash(config) + account.start() + logging.info('%d account(s) listened', len(self.accounts)) + + def stop(self): + with self.lock: + for account in self.accounts.values(): + account.stop() + for account in self.accounts.values(): + account.join(5) + + @staticmethod + def config_hash(config): + return hashlib.sha256(json.dumps(config, sort_keys=True).encode('utf-8')).hexdigest() + + +class SocketHandler(socketserver.StreamRequestHandler): + + def handle(self): + line = self.rfile.readline().strip() + if not line: + return + try: + message = json.loads(line.decode('utf-8')) + except Exception as e: + logging.error('Invalid message from socket: %s', e) + return + self.server.daemon_instance.handle(message) + + +def shutdown(signum=None, frame=None): + logging.info('Shutdown') + try: + daemon.stop() + except Exception: + pass + try: + os.remove(args.pid) + except Exception: + pass + sys.stdout.flush() + os._exit(0) + + +parser = argparse.ArgumentParser(description='Mail reception daemon for Jeedom') +parser.add_argument('--loglevel', type=str, default='error') +parser.add_argument('--socketport', type=int, default=55072) +parser.add_argument('--callback', type=str, required=True) +parser.add_argument('--apikey', type=str, required=True) +parser.add_argument('--pid', type=str, required=True) +parser.add_argument('--state', type=str, required=True) +args = parser.parse_args() + +logging.basicConfig(level=convert_log_level(args.loglevel), format='[%(asctime)-15s][%(levelname)s] : %(message)s', datefmt='%Y-%m-%d %H:%M:%S') +logging.info('Start maild, log level: %s, socket port: %s', args.loglevel, args.socketport) + +signal.signal(signal.SIGINT, shutdown) +signal.signal(signal.SIGTERM, shutdown) + +try: + with open(args.pid, 'w') as f: + f.write(str(os.getpid())) + callback = JeedomCallback(args.callback, args.apikey) + if not callback.test(): + logging.error('Network communication issues. Please fix your Jeedom network configuration.') + shutdown() + daemon = Daemon(args.apikey, callback, State(args.state)) + socketserver.TCPServer.allow_reuse_address = True + server = socketserver.TCPServer(('127.0.0.1', args.socketport), SocketHandler) + server.daemon_instance = daemon + server.serve_forever() +except Exception as e: + logging.error('Fatal error: %s', e) + logging.info(traceback.format_exc()) + shutdown()