plugin.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. <?php
  2. // PLUGIN INFORMATION
  3. $GLOBALS['plugins']['Invites'] = array( // Plugin Name
  4. 'name' => 'Invites', // Plugin Name
  5. 'author' => 'CauseFX', // Who wrote the plugin
  6. 'category' => 'Management', // One to Two Word Description
  7. 'link' => '', // Link to plugin info
  8. 'license' => 'personal', // License Type use , for multiple
  9. 'idPrefix' => 'INVITES', // html element id prefix
  10. 'configPrefix' => 'INVITES', // config file prefix for array items without the hyphen
  11. 'version' => '1.1.0', // SemVer of plugin
  12. 'image' => 'api/plugins/invites/logo.png', // 1:1 non transparent image for plugin
  13. 'settings' => true, // does plugin need a settings modal?
  14. 'bind' => true, // use default bind to make settings page - true or false
  15. 'api' => 'api/v2/plugins/invites/settings', // api route for settings page
  16. 'homepage' => false // Is plugin for use on homepage? true or false
  17. );
  18. class Invites extends Organizr
  19. {
  20. public function __construct()
  21. {
  22. parent::__construct();
  23. $this->_pluginUpgradeCheck();
  24. }
  25. public function _pluginUpgradeCheck()
  26. {
  27. if ($this->hasDB()) {
  28. $compare = new Composer\Semver\Comparator;
  29. $oldVer = $this->config['INVITES-dbVersion'];
  30. // Upgrade check start for version below
  31. $versionCheck = '1.1.0';
  32. if ($compare->lessThan($oldVer, $versionCheck)) {
  33. $oldVer = $versionCheck;
  34. $this->_pluginUpgradeToVersion($versionCheck);
  35. }
  36. // End Upgrade check start for version above
  37. // Update config.php version if different to the installed version
  38. if ($GLOBALS['plugins']['Invites']['version'] !== $this->config['INVITES-dbVersion']) {
  39. $this->updateConfig(array('INVITES-dbVersion' => $oldVer));
  40. $this->setLoggerChannel('Invites Plugin');
  41. $this->logger->debug('Updated INVITES-dbVersion to ' . $oldVer);
  42. }
  43. return true;
  44. }
  45. }
  46. public function _pluginUpgradeToVersion($version = '1.1.0')
  47. {
  48. switch ($version) {
  49. case '1.1.0':
  50. $this->_addInvitedByColumnToDatabase();
  51. break;
  52. }
  53. $this->setResponse(200, 'Ran plugin update function for version: ' . $version);
  54. return true;
  55. }
  56. public function _addInvitedByColumnToDatabase()
  57. {
  58. $addColumn = $this->addColumnToDatabase('invites', 'invitedby', 'TEXT');
  59. $this->setLoggerChannel('Invites Plugin');
  60. if ($addColumn) {
  61. $this->logger->info('Updated Invites Database');
  62. } else {
  63. $this->logger->warning('Could not update Invites Database');
  64. }
  65. }
  66. public function _invitesPluginGetCodes()
  67. {
  68. if ($this->qualifyRequest(1, false)) {
  69. $response = [
  70. array(
  71. 'function' => 'fetchAll',
  72. 'query' => 'SELECT * FROM invites'
  73. )
  74. ];
  75. } else {
  76. $response = [
  77. array(
  78. 'function' => 'fetchAll',
  79. 'query' => array(
  80. 'SELECT * FROM invites WHERE invitedby = ?',
  81. $this->user['username']
  82. )
  83. )
  84. ];
  85. }
  86. return $this->processQueries($response);
  87. }
  88. public function _invitesPluginCreateCode($array)
  89. {
  90. $code = ($array['code']) ?? null;
  91. $username = ($array['username']) ?? null;
  92. $email = ($array['email']) ?? null;
  93. $invites = $this->_invitesPluginGetCodes();
  94. $inviteCount = count($invites);
  95. if (!$this->qualifyRequest(1, false)) {
  96. if ($this->config['INVITES-maximum-invites'] != 0 && $inviteCount >= $this->config['INVITES-maximum-invites']) {
  97. $this->setAPIResponse('error', 'Maximum number of invites reached', 409);
  98. return false;
  99. }
  100. }
  101. if (!$code) {
  102. $this->setAPIResponse('error', 'Code not supplied', 409);
  103. return false;
  104. }
  105. if (!$username) {
  106. $this->setAPIResponse('error', 'Username not supplied', 409);
  107. return false;
  108. }
  109. if (!$email) {
  110. $this->setAPIResponse('error', 'Email not supplied', 409);
  111. return false;
  112. }
  113. $newCode = [
  114. 'code' => $code,
  115. 'email' => $email,
  116. 'username' => $username,
  117. 'valid' => 'Yes',
  118. 'type' => $this->config['INVITES-type-include'],
  119. 'invitedby' => $this->user['username'],
  120. 'date' => gmdate('Y-m-d H:i:s')
  121. ];
  122. $response = [
  123. array(
  124. 'function' => 'query',
  125. 'query' => array(
  126. 'INSERT INTO [invites]',
  127. $newCode
  128. )
  129. )
  130. ];
  131. $query = $this->processQueries($response);
  132. if ($query) {
  133. $this->setLoggerChannel('Invites')->info('Added Invite [' . $code . ']');
  134. if ($this->config['PHPMAILER-enabled']) {
  135. $PhpMailer = new PhpMailer();
  136. $emailTemplate = array(
  137. 'type' => 'invite',
  138. 'body' => $this->config['PHPMAILER-emailTemplateInviteUser'],
  139. 'subject' => $this->config['PHPMAILER-emailTemplateInviteUserSubject'],
  140. 'user' => $username,
  141. 'password' => null,
  142. 'inviteCode' => $code,
  143. );
  144. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  145. $sendEmail = array(
  146. 'to' => $email,
  147. 'subject' => $emailTemplate['subject'],
  148. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  149. );
  150. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  151. }
  152. $this->setAPIResponse('success', 'Invite Code: ' . $code . ' has been created', 200);
  153. return true;
  154. } else {
  155. return false;
  156. }
  157. }
  158. public function _invitesPluginVerifyCode($code)
  159. {
  160. $response = [
  161. array(
  162. 'function' => 'fetchAll',
  163. 'query' => array(
  164. 'SELECT * FROM invites WHERE valid = "Yes" AND code = ? COLLATE NOCASE',
  165. $code
  166. )
  167. )
  168. ];
  169. if ($this->processQueries($response)) {
  170. $this->setAPIResponse('success', 'Code has been verified', 200);
  171. return true;
  172. } else {
  173. $this->setAPIResponse('error', 'Code is invalid', 401);
  174. return false;
  175. }
  176. }
  177. public function _invitesPluginDeleteCode($code)
  178. {
  179. if ($this->qualifyRequest(1, false)) {
  180. $response = [
  181. array(
  182. 'function' => 'fetch',
  183. 'query' => array(
  184. 'SELECT * FROM invites WHERE code = ? COLLATE NOCASE',
  185. $code
  186. )
  187. )
  188. ];
  189. } else {
  190. if ($this->config['INVITES-allow-delete']) {
  191. $response = [
  192. array(
  193. 'function' => 'fetch',
  194. 'query' => array(
  195. 'SELECT * FROM invites WHERE invitedby = ? AND code = ? COLLATE NOCASE',
  196. $this->user['username'],
  197. $code
  198. )
  199. )
  200. ];
  201. } else {
  202. $this->setAPIResponse('error', 'You are not permitted to delete invites.', 409);
  203. return false;
  204. }
  205. }
  206. $info = $this->processQueries($response);
  207. if (!$info) {
  208. $this->setAPIResponse('error', 'Code not found', 404);
  209. return false;
  210. }
  211. $response = [
  212. array(
  213. 'function' => 'query',
  214. 'query' => array(
  215. 'DELETE FROM invites WHERE code = ? COLLATE NOCASE',
  216. $code
  217. )
  218. )
  219. ];
  220. $this->setAPIResponse('success', 'Code has been deleted', 200);
  221. return $this->processQueries($response);
  222. }
  223. public function _invitesPluginUseCode($code, $array)
  224. {
  225. $code = ($code) ?? null;
  226. $usedBy = ($array['usedby']) ?? null;
  227. $now = date("Y-m-d H:i:s");
  228. $currentIP = $this->userIP();
  229. if ($this->_invitesPluginVerifyCode($code)) {
  230. $updateCode = [
  231. 'valid' => 'No',
  232. 'usedby' => $usedBy,
  233. 'dateused' => $now,
  234. 'ip' => $currentIP
  235. ];
  236. $response = [
  237. array(
  238. 'function' => 'query',
  239. 'query' => array(
  240. 'UPDATE invites SET',
  241. $updateCode,
  242. 'WHERE code=? COLLATE NOCASE',
  243. $code
  244. )
  245. )
  246. ];
  247. $query = $this->processQueries($response);
  248. $this->setLoggerChannel('Invites')->info('Invite Used [' . $code . ']');
  249. return $this->_invitesPluginAction($usedBy, 'share', $this->config['INVITES-type-include']);
  250. } else {
  251. return false;
  252. }
  253. }
  254. public function _invitesPluginLibraryList($type = null)
  255. {
  256. switch ($type) {
  257. case 'plex':
  258. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  259. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'];
  260. try {
  261. $headers = array(
  262. "Accept" => "application/json",
  263. "X-Plex-Token" => $this->config['plexToken']
  264. );
  265. $response = Requests::get($url, $headers, array());
  266. libxml_use_internal_errors(true);
  267. if ($response->success) {
  268. $libraryList = array();
  269. $plex = simplexml_load_string($response->body);
  270. foreach ($plex->Server->Section as $child) {
  271. $libraryList['libraries'][(string)$child['title']] = (string)$child['id'];
  272. }
  273. if ($this->config['INVITES-plexLibraries'] !== '') {
  274. $noLongerId = 0;
  275. $libraries = explode(',', $this->config['INVITES-plexLibraries']);
  276. foreach ($libraries as $child) {
  277. if (!$this->search_for_value($child, $libraryList)) {
  278. $libraryList['libraries']['No Longer Exists - ' . $noLongerId] = $child;
  279. $noLongerId++;
  280. }
  281. }
  282. }
  283. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  284. return $libraryList;
  285. }
  286. } catch (Requests_Exception $e) {
  287. $this->setLoggerChannel('Plex')->error($e);
  288. return false;
  289. };
  290. }
  291. break;
  292. default:
  293. # code...
  294. break;
  295. }
  296. return false;
  297. }
  298. public function _invitesPluginGetSettings()
  299. {
  300. if ($this->config['plexID'] !== '' && $this->config['plexToken'] !== '' && $this->config['INVITES-type-include'] == 'plex') {
  301. $loop = $this->_invitesPluginLibraryList($this->config['INVITES-type-include'])['libraries'];
  302. foreach ($loop as $key => $value) {
  303. $libraryList[] = array(
  304. 'name' => $key,
  305. 'value' => $value
  306. );
  307. }
  308. } else {
  309. $libraryList = array(
  310. array(
  311. 'name' => 'Refresh page to update List',
  312. 'value' => '',
  313. 'disabled' => true,
  314. ),
  315. );
  316. }
  317. $komgaRoles = $this->_getKomgaRoles();
  318. $komgalibrary = $this->_getKomgaLibraries();
  319. return array(
  320. 'Backend' => array(
  321. array(
  322. 'type' => 'select',
  323. 'name' => 'INVITES-type-include',
  324. 'label' => 'Media Server',
  325. 'value' => $this->config['INVITES-type-include'],
  326. 'options' => array(
  327. array(
  328. 'name' => 'N/A',
  329. 'value' => 'n/a'
  330. ),
  331. array(
  332. 'name' => 'Plex',
  333. 'value' => 'plex'
  334. ),
  335. array(
  336. 'name' => 'Emby',
  337. 'value' => 'emby'
  338. )
  339. )
  340. ),
  341. array(
  342. 'type' => 'select',
  343. 'name' => 'INVITES-Auth-include',
  344. 'label' => 'Minimum Authentication',
  345. 'value' => $this->config['INVITES-Auth-include'],
  346. 'options' => $this->groupSelect()
  347. ),
  348. array(
  349. 'type' => 'switch',
  350. 'name' => 'INVITES-allow-delete-include',
  351. 'label' => 'Allow users to delete invites',
  352. 'help' => 'This must be disabled to enforce invitation limits.',
  353. 'value' => $this->config['INVITES-allow-delete-include']
  354. ),
  355. array(
  356. 'type' => 'number',
  357. 'name' => 'INVITES-maximum-invites',
  358. 'label' => 'Maximum number of invites permitted for users.',
  359. 'help' => 'Set to 0 to disable the limit.',
  360. 'value' => $this->config['INVITES-maximum-invites'],
  361. 'placeholder' => '0'
  362. ),
  363. ),
  364. 'Plex Settings' => array(
  365. array(
  366. 'type' => 'password-alt',
  367. 'name' => 'plexToken',
  368. 'label' => 'Plex Token',
  369. 'value' => $this->config['plexToken'],
  370. 'placeholder' => 'Use Get Token Button'
  371. ),
  372. array(
  373. 'type' => 'button',
  374. 'label' => 'Get Plex Token',
  375. 'icon' => 'fa fa-ticket',
  376. 'text' => 'Retrieve',
  377. 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, oAuthMaxRetry, null, null, \'#INVITES-settings-items [name=plexToken]\')"'
  378. ),
  379. array(
  380. 'type' => 'password-alt',
  381. 'name' => 'plexID',
  382. 'label' => 'Plex Machine',
  383. 'value' => $this->config['plexID'],
  384. 'placeholder' => 'Use Get Plex Machine Button'
  385. ),
  386. array(
  387. 'type' => 'button',
  388. 'label' => 'Get Plex Machine',
  389. 'icon' => 'fa fa-id-badge',
  390. 'text' => 'Retrieve',
  391. 'attr' => 'onclick="showPlexMachineForm(\'#INVITES-settings-items [name=plexID]\')"'
  392. ),
  393. array(
  394. 'type' => 'select2',
  395. 'class' => 'select2-multiple',
  396. 'id' => 'invite-select-' . $this->random_ascii_string(6),
  397. 'name' => 'INVITES-plexLibraries',
  398. 'label' => 'Libraries',
  399. 'value' => $this->config['INVITES-plexLibraries'],
  400. 'options' => $libraryList
  401. ),
  402. array(
  403. 'type' => 'text',
  404. 'name' => 'INVITES-plex-tv-labels',
  405. 'label' => 'TV Labels (comma separated)',
  406. 'value' => $this->config['INVITES-plex-tv-labels'],
  407. 'placeholder' => 'All'
  408. ),
  409. array(
  410. 'type' => 'text',
  411. 'name' => 'INVITES-plex-movies-labels',
  412. 'label' => 'Movies Labels (comma separated)',
  413. 'value' => $this->config['INVITES-plex-movies-labels'],
  414. 'placeholder' => 'All'
  415. ),
  416. array(
  417. 'type' => 'text',
  418. 'name' => 'INVITES-plex-music-labels',
  419. 'label' => 'Music Labels (comma separated)',
  420. 'value' => $this->config['INVITES-plex-music-labels'],
  421. 'placeholder' => 'All'
  422. ),
  423. ),
  424. 'Komga Settings' => array(
  425. array(
  426. 'type' => 'switch',
  427. 'name' => 'INVITES-komga-enabled',
  428. 'label' => 'Enable Komga for auto create account',
  429. 'value' => $this->config['INVITES-komga-enabled'],
  430. ),
  431. array(
  432. 'type' => 'input',
  433. 'name' => 'INVITES-komga-uri',
  434. 'label' => 'URL',
  435. 'value' => $this->config['INVITES-komga-uri'],
  436. 'placeholder' => 'http(s)://hostname:port'
  437. ),
  438. array(
  439. 'type' => 'password-alt',
  440. 'name' => 'INVITES-komga-api-key',
  441. 'label' => 'Komga Api Key',
  442. 'value' => $this->config['INVITES-komga-api-key']
  443. ),
  444. array(
  445. 'type' => 'password-alt',
  446. 'name' => 'INVITES-komga-default-user-password',
  447. 'label' => 'Default password for new user',
  448. 'value' => $this->config['INVITES-komga-default-user-password']
  449. ),
  450. array(
  451. 'type' => 'select2',
  452. 'class' => 'select2-multiple',
  453. 'id' => 'invites-select-' . $this->random_ascii_string(6),
  454. 'name' => 'INVITES-komga-roles',
  455. 'label' => 'Roles',
  456. 'value' => $this->config['INVITES-komga-roles'],
  457. 'options' => $komgaRoles
  458. ),
  459. array(
  460. 'type' => 'select2',
  461. 'class' => 'select2-multiple',
  462. 'id' => 'invit4es-select-' . $this->random_ascii_string(6),
  463. 'name' => 'INVITES-komga-libraryIds',
  464. 'label' => 'Libraries',
  465. 'value' => $this->config['INVITES-komga-libraryIds'],
  466. 'options' => $komgalibrary
  467. )
  468. ),
  469. 'Emby Settings' => array(
  470. array(
  471. 'type' => 'password-alt',
  472. 'name' => 'embyToken',
  473. 'label' => 'Emby API key',
  474. 'value' => $this->config['embyToken'],
  475. 'placeholder' => 'enter key from emby'
  476. ),
  477. array(
  478. 'type' => 'text',
  479. 'name' => 'embyURL',
  480. 'label' => 'Emby server adress',
  481. 'value' => $this->config['embyURL'],
  482. 'placeholder' => 'localhost:8086'
  483. ),
  484. array(
  485. 'type' => 'text',
  486. 'name' => 'INVITES-EmbyTemplate',
  487. 'label' => 'Emby User to be used as template for new users',
  488. 'value' => $this->config['INVITES-EmbyTemplate'],
  489. 'placeholder' => 'AdamSmith'
  490. )
  491. ),
  492. 'FYI' => array(
  493. array(
  494. 'type' => 'html',
  495. 'label' => 'Note',
  496. 'html' => '<span lang="en">After enabling for the first time, please reload the page - Menu is located under User menu on top right</span>'
  497. )
  498. )
  499. );
  500. }
  501. public function _invitesPluginAction($username, $action = null, $type = null)
  502. {
  503. if ($action == null) {
  504. $this->setAPIResponse('error', 'No Action supplied', 409);
  505. return false;
  506. }
  507. switch ($type) {
  508. case 'plex':
  509. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  510. $url = "https://plex.tv/api/servers/" . $this->config['plexID'] . "/shared_servers/";
  511. if ($this->config['INVITES-plexLibraries'] !== "") {
  512. $libraries = explode(',', $this->config['INVITES-plexLibraries']);
  513. } else {
  514. $libraries = '';
  515. }
  516. if ($this->config['INVITES-plex-tv-labels'] !== "") {
  517. $tv_labels = "label=" . $this->config['INVITES-plex-tv-labels'];
  518. } else {
  519. $tv_labels = "";
  520. }
  521. if ($this->config['INVITES-plex-movies-labels'] !== "") {
  522. $movies_labels = "label=" . $this->config['INVITES-plex-movies-labels'];
  523. } else {
  524. $movies_labels = "";
  525. }
  526. if ($this->config['INVITES-plex-music-labels'] !== "") {
  527. $music_labels = "label=" . $this->config['INVITES-plex-music-labels'];
  528. } else {
  529. $music_labels = "";
  530. }
  531. $headers = array(
  532. "Accept" => "application/json",
  533. "Content-Type" => "application/json",
  534. "X-Plex-Token" => $this->config['plexToken']
  535. );
  536. $data = array(
  537. "server_id" => $this->config['plexID'],
  538. "shared_server" => array(
  539. "library_section_ids" => $libraries,
  540. "invited_email" => $username
  541. ),
  542. "sharing_settings" => array(
  543. "filterTelevision" => $tv_labels,
  544. "filterMovies" => $movies_labels,
  545. "filterMusic" => $music_labels
  546. )
  547. );
  548. try {
  549. switch ($action) {
  550. case 'share':
  551. $response = Requests::post($url, $headers, json_encode($data), array());
  552. if($this->config['INVITES-komga-enabled']) {
  553. $this->_createKomgaAccount($username);
  554. }
  555. break;
  556. case 'unshare':
  557. $id = (is_numeric($username) ? $username : $this->_invitesPluginConvertPlexName($username, "id"));
  558. $url = $url . $id;
  559. $response = Requests::delete($url, $headers, array());
  560. break;
  561. default:
  562. $this->setAPIResponse('error', 'No Action supplied', 409);
  563. return false;
  564. }
  565. if ($response->success) {
  566. $this->setLoggerChannel('Invites')->info('Plex User now has access to system');
  567. $this->setAPIResponse('success', 'Plex User now has access to system', 200);
  568. return true;
  569. } else {
  570. switch ($response->status_code) {
  571. case 400:
  572. $this->setLoggerChannel('Plex')->warning('Plex User already has access');
  573. $this->setAPIResponse('error', 'Plex User already has access', 409);
  574. return false;
  575. case 401:
  576. $this->setLoggerChannel('Plex')->warning('Incorrect Token');
  577. $this->setAPIResponse('error', 'Incorrect Token', 409);
  578. return false;
  579. case 404:
  580. $this->setLoggerChannel('Plex')->warning('Libraries not setup correctly');
  581. $this->setAPIResponse('error', 'Libraries not setup correct', 409);
  582. return false;
  583. default:
  584. $this->setLoggerChannel('Plex')->warning('An error occurred [' . $response->status_code . ']');
  585. $this->setAPIResponse('error', 'An Error Occurred', 409);
  586. return false;
  587. }
  588. }
  589. } catch (Requests_Exception $e) {
  590. $this->setLoggerChannel('Plex')->error($e);
  591. $this->setAPIResponse('error', $e->getMessage(), 409);
  592. return false;
  593. }
  594. } else {
  595. $this->setLoggerChannel('Plex')->warning('Plex Token/ID not set');
  596. $this->setAPIResponse('error', 'Plex Token/ID not set', 409);
  597. return false;
  598. }
  599. break;
  600. case 'emby':
  601. try {
  602. #add emby user to system
  603. $this->setAPIResponse('success', 'User now has access to system', 200);
  604. return true;
  605. } catch (Requests_Exception $e) {
  606. $this->setLoggerChannel('Emby')->error($e);
  607. $this->setAPIResponse('error', $e->getMessage(), 409);
  608. return false;
  609. }
  610. default:
  611. return false;
  612. }
  613. return false;
  614. }
  615. public function _invitesPluginConvertPlexName($user, $type)
  616. {
  617. $array = $this->userList('plex');
  618. switch ($type) {
  619. case "username":
  620. case "u":
  621. $plexUser = array_search($user, $array['users']);
  622. break;
  623. case "id":
  624. if (array_key_exists(strtolower($user), $array['users'])) {
  625. $plexUser = $array['users'][strtolower($user)];
  626. }
  627. break;
  628. default:
  629. $plexUser = false;
  630. }
  631. return (!empty($plexUser) ? $plexUser : null);
  632. }
  633. /**
  634. * Creates a new Komga user account using the provided email address.
  635. *
  636. * This method checks if Komga integration is enabled in the configuration,
  637. * validates the required parameters (endpoint URI, API key, and email),
  638. * and sends a POST request to the Komga API to create a user with the specified
  639. * roles and shared library IDs. Roles and library IDs are parsed from the configuration,
  640. * separated by semicolons. The default user password is also taken from the configuration.
  641. *
  642. * Logs informational, warning, or error messages based on the outcome.
  643. *
  644. * @param string $email The email address for the new Komga user account.
  645. * @return bool True if the account was successfully created, false otherwise.
  646. */
  647. private function _createKomgaAccount($email) {
  648. $this->logger->info('Try to create Komga account for ' . $email);
  649. if (empty($this->config['INVITES-komga-uri'])) {
  650. $this->setLoggerChannel('Invites')->info('Komga uri is missing');
  651. return false;
  652. }
  653. if (empty($this->config['INVITES-komga-api-key'])) {
  654. $this->setLoggerChannel('Invites')->info('Komga api key is missing');
  655. return false;
  656. }
  657. if (empty($this->config['INVITES-komga-roles'])) {
  658. $this->setLoggerChannel('Invites')->info('Komga roles empty');
  659. return false;
  660. }
  661. if (empty($this->config['INVITES-komga-libraryIds'])) {
  662. $this->setLoggerChannel('Invites')->info('Komga library empty');
  663. return false;
  664. }
  665. if (empty($this->config['INVITES-komga-default-user-password'])) {
  666. $this->setLoggerChannel('Invites')->info('Komga default user password empty');
  667. return false;
  668. }
  669. if (empty($email)) {
  670. $this->setLoggerChannel('Invites')->info('User email empty');
  671. return false;
  672. }
  673. $endpoint = rtrim($this->config['INVITES-komga-uri'], '/') . '/api/v2/users';
  674. $apiKey = $this->config['INVITES-komga-api-key'];
  675. $password = $this->decrypt($this->config['INVITES-komga-default-user-password']);
  676. $rolesStr = $this->config['INVITES-komga-roles'] ?? '';
  677. $roles = array_values(array_filter(array_map('trim', explode(';', $rolesStr))));
  678. $libIdsStr = $this->config['INVITES-komga-libraryIds'] ?? '';
  679. $libraryIds = array_values(array_filter(array_map('trim', explode(';', $libIdsStr))));
  680. $headers = array(
  681. 'accept' => 'application/json',
  682. 'X-API-Key' => $apiKey,
  683. 'Content-Type' => 'application/json'
  684. );
  685. $payload = array(
  686. 'email' => $email,
  687. 'password' => $password,
  688. 'roles' => $roles,
  689. 'sharedLibraries' => array(
  690. 'all' => false,
  691. 'libraryIds' => $libraryIds
  692. )
  693. );
  694. try {
  695. $response = Requests::post($endpoint, $headers, json_encode($payload));
  696. if ($response->success) {
  697. $this->setLoggerChannel('Komga')->info('User created ' . $email . ' with roles: ' . implode(',', $roles) . ' and libraries: ' . implode(',', $libraryIds));
  698. return true;
  699. }
  700. $this->setLoggerChannel('Komga')->warning('User not created ' . $email . ' HTTP ' . $response->status_code);
  701. } catch (Requests_Exception $e) {
  702. $this->setLoggerChannel('Komga')->error('User not created ' . $email . ' Requests_Exception: ' . $e->getMessage());
  703. }
  704. return false;
  705. }
  706. /**
  707. * Retrieves a list of Komga roles
  708. *
  709. * @return array An array of associative arrays, each containing 'name' and 'value' for a Komga role.
  710. */
  711. function _getKomgaRoles() {
  712. $komgaRoles = array();
  713. $roleNames = array(
  714. 'ADMIN' => 'Administrator',
  715. 'FILE_DOWNLOAD' => 'File download',
  716. 'PAGE_STREAMING' => 'Page streaming',
  717. 'KOBO_SYNC' => 'Kobo Sync',
  718. 'KOREADER_SYNC' => 'Koreader Sync'
  719. );
  720. foreach ($roleNames as $value => $name) {
  721. $komgaRoles[] = array(
  722. 'name' => $name,
  723. 'value' => $value
  724. );
  725. }
  726. return $komgaRoles;
  727. }
  728. /**
  729. * Fetches the list of Komga libraries from the Komga API.
  730. *
  731. * @return array|false Returns an array of libraries with 'name' and 'id' on success, or false on failure.
  732. */
  733. function _getKomgaLibraries() {
  734. $this->logger->info('Try to fetch Komga libraries');
  735. $endpoint = rtrim($this->config['komgaURL'], '/') . '/api/v1/libraries';
  736. $apiKey = $this->config['INVITES-komga-api-key'];
  737. $libraryListDefault = array(
  738. array(
  739. 'name' => 'Refresh page to update List',
  740. 'value' => '',
  741. 'disabled' => true,
  742. ),
  743. );
  744. $headers = array(
  745. 'accept' => 'application/json',
  746. 'X-API-Key' => $apiKey
  747. );
  748. try {
  749. $response = Requests::get($endpoint, $headers);
  750. if ($response->success) {
  751. $libraries = json_decode($response->body, true);
  752. // Komga retourne un tableau d'objets librairie
  753. $result = array();
  754. foreach ($libraries as $library) {
  755. $result[] = array(
  756. 'name' => $library['name'],
  757. 'id' => $library['id']
  758. );
  759. }
  760. $this->logger->info('Fetched libraries: ' . json_encode($result));
  761. if(!empty($result)) {
  762. return $result;
  763. }
  764. } else {
  765. $this->logger->warning("Error HTTP ".$response->status_code.' body='.$response->body);
  766. }
  767. } catch (Requests_Exception $e) {
  768. $this->logger->warning("Exception: " . $e->getMessage());
  769. }
  770. return $libraryListDefault;
  771. }
  772. }