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 = '