You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

497 lines
13 KiB

  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
  4. *
  5. * @license GNU AGPL version 3 or any later version
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License as
  9. * published by the Free Software Foundation, either version 3 of the
  10. * License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. namespace OCA\Spreed;
  22. use OCA\Spreed\Exceptions\RoomNotFoundException;
  23. use OCP\DB\QueryBuilder\IQueryBuilder;
  24. use OCP\IConfig;
  25. use OCP\IDBConnection;
  26. use OCP\Security\IHasher;
  27. use OCP\Security\ISecureRandom;
  28. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  29. class Manager {
  30. /** @var IDBConnection */
  31. private $db;
  32. /** @var IConfig */
  33. private $config;
  34. /** @var ISecureRandom */
  35. private $secureRandom;
  36. /** @var EventDispatcherInterface */
  37. private $dispatcher;
  38. /** @var IHasher */
  39. private $hasher;
  40. /**
  41. * Manager constructor.
  42. *
  43. * @param IDBConnection $db
  44. * @param IConfig $config
  45. * @param ISecureRandom $secureRandom
  46. * @param EventDispatcherInterface $dispatcher
  47. * @param IHasher $hasher
  48. */
  49. public function __construct(IDBConnection $db, IConfig $config, ISecureRandom $secureRandom, EventDispatcherInterface $dispatcher, IHasher $hasher) {
  50. $this->db = $db;
  51. $this->config = $config;
  52. $this->secureRandom = $secureRandom;
  53. $this->dispatcher = $dispatcher;
  54. $this->hasher = $hasher;
  55. }
  56. /**
  57. * @param array $row
  58. * @return Room
  59. */
  60. protected function createRoomObject(array $row) {
  61. return new Room($this->db, $this->secureRandom, $this->dispatcher, $this->hasher, (int) $row['id'], (int) $row['type'], $row['token'], $row['name'], $row['password']);
  62. }
  63. /**
  64. * @param Room $room
  65. * @param array $row
  66. * @return Participant
  67. */
  68. protected function createParticipantObject(Room $room, array $row) {
  69. return new Participant($this->db, $room, $row['userId'], (int) $row['participantType'], (int) $row['lastPing'], $row['sessionId']);
  70. }
  71. /**
  72. * @param string $participant
  73. * @return Room[]
  74. */
  75. public function getRoomsForParticipant($participant) {
  76. $query = $this->db->getQueryBuilder();
  77. $query->select('*')
  78. ->from('spreedme_rooms', 'r')
  79. ->leftJoin('r', 'spreedme_room_participants', 'p', $query->expr()->andX(
  80. $query->expr()->eq('p.userId', $query->createNamedParameter($participant)),
  81. $query->expr()->eq('p.roomId', 'r.id')
  82. ))
  83. ->where($query->expr()->isNotNull('p.userId'));
  84. $result = $query->execute();
  85. $rooms = [];
  86. while ($row = $result->fetch()) {
  87. $room = $this->createRoomObject($row);
  88. if ($participant !== null && isset($row['userId'])) {
  89. $room->setParticipant($row['userId'], $this->createParticipantObject($room, $row));
  90. }
  91. $rooms[] = $room;
  92. }
  93. $result->closeCursor();
  94. return $rooms;
  95. }
  96. /**
  97. * Does *not* return public rooms for participants that have not been invited
  98. *
  99. * @param int $roomId
  100. * @param string $participant
  101. * @return Room
  102. * @throws RoomNotFoundException
  103. */
  104. public function getRoomForParticipant($roomId, $participant) {
  105. $query = $this->db->getQueryBuilder();
  106. $query->select('*')
  107. ->from('spreedme_rooms', 'r')
  108. ->where($query->expr()->eq('id', $query->createNamedParameter($roomId, IQueryBuilder::PARAM_INT)));
  109. if ($participant !== null) {
  110. // Non guest user
  111. $query->leftJoin('r', 'spreedme_room_participants', 'p', $query->expr()->andX(
  112. $query->expr()->eq('p.userId', $query->createNamedParameter($participant)),
  113. $query->expr()->eq('p.roomId', 'r.id')
  114. ))
  115. ->andWhere($query->expr()->isNotNull('p.userId'));
  116. }
  117. $result = $query->execute();
  118. $row = $result->fetch();
  119. $result->closeCursor();
  120. if ($row === false) {
  121. throw new RoomNotFoundException();
  122. }
  123. $room = $this->createRoomObject($row);
  124. if ($participant !== null && isset($row['userId'])) {
  125. $room->setParticipant($row['userId'], $this->createParticipantObject($room, $row));
  126. }
  127. if ($participant === null && $room->getType() !== Room::PUBLIC_CALL) {
  128. throw new RoomNotFoundException();
  129. }
  130. return $room;
  131. }
  132. /**
  133. * Also returns public rooms for participants that have not been invited,
  134. * so they can join.
  135. *
  136. * @param string $token
  137. * @param string $participant
  138. * @return Room
  139. * @throws RoomNotFoundException
  140. */
  141. public function getRoomForParticipantByToken($token, $participant) {
  142. $query = $this->db->getQueryBuilder();
  143. $query->select('*')
  144. ->from('spreedme_rooms', 'r')
  145. ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
  146. ->setMaxResults(1);
  147. if ($participant !== null) {
  148. // Non guest user
  149. $query->leftJoin('r', 'spreedme_room_participants', 'p', $query->expr()->andX(
  150. $query->expr()->eq('p.userId', $query->createNamedParameter($participant)),
  151. $query->expr()->eq('p.roomId', 'r.id')
  152. ));
  153. }
  154. $result = $query->execute();
  155. $row = $result->fetch();
  156. $result->closeCursor();
  157. if ($row === false) {
  158. throw new RoomNotFoundException();
  159. }
  160. $room = $this->createRoomObject($row);
  161. if ($participant !== null && isset($row['userId'])) {
  162. $room->setParticipant($row['userId'], $this->createParticipantObject($room, $row));
  163. }
  164. if ($room->getType() === Room::PUBLIC_CALL) {
  165. return $room;
  166. }
  167. if ($participant !== null && $row['userId'] === $participant) {
  168. return $room;
  169. }
  170. throw new RoomNotFoundException();
  171. }
  172. /**
  173. * @param int $roomId
  174. * @return Room
  175. * @throws RoomNotFoundException
  176. */
  177. public function getRoomById($roomId) {
  178. $query = $this->db->getQueryBuilder();
  179. $query->select('*')
  180. ->from('spreedme_rooms')
  181. ->where($query->expr()->eq('id', $query->createNamedParameter($roomId, IQueryBuilder::PARAM_INT)));
  182. $result = $query->execute();
  183. $row = $result->fetch();
  184. $result->closeCursor();
  185. if ($row === false) {
  186. throw new RoomNotFoundException();
  187. }
  188. return $this->createRoomObject($row);
  189. }
  190. /**
  191. * @param string $token
  192. * @return Room
  193. * @throws RoomNotFoundException
  194. */
  195. public function getRoomByToken($token) {
  196. $query = $this->db->getQueryBuilder();
  197. $query->select('*')
  198. ->from('spreedme_rooms')
  199. ->where($query->expr()->eq('token', $query->createNamedParameter($token)));
  200. $result = $query->execute();
  201. $row = $result->fetch();
  202. $result->closeCursor();
  203. if ($row === false) {
  204. throw new RoomNotFoundException();
  205. }
  206. return $this->createRoomObject($row);
  207. }
  208. /**
  209. * @param string $userId
  210. * @param string $sessionId
  211. * @return Room
  212. * @throws RoomNotFoundException
  213. */
  214. public function getRoomForSession($userId, $sessionId) {
  215. if ($sessionId === '' || $sessionId === '0') {
  216. throw new RoomNotFoundException();
  217. }
  218. $query = $this->db->getQueryBuilder();
  219. $query->select('*')
  220. ->from('spreedme_rooms', 'r')
  221. ->leftJoin('r', 'spreedme_room_participants', 'p', $query->expr()->andX(
  222. $query->expr()->eq('p.sessionId', $query->createNamedParameter($sessionId)),
  223. $query->expr()->eq('p.roomId', 'r.id')
  224. ))
  225. ->setMaxResults(1);
  226. $result = $query->execute();
  227. $row = $result->fetch();
  228. $result->closeCursor();
  229. if ($row === false) {
  230. throw new RoomNotFoundException();
  231. }
  232. if ((string) $userId !== $row['userId']) {
  233. throw new RoomNotFoundException();
  234. }
  235. $room = $this->createRoomObject($row);
  236. $participant = $this->createParticipantObject($room, $row);
  237. $room->setParticipant($row['userId'], $participant);
  238. if ($room->getType() === Room::PUBLIC_CALL || !in_array($participant->getParticipantType(), [Participant::GUEST, Participant::USER_SELF_JOINED], true)) {
  239. return $room;
  240. }
  241. throw new RoomNotFoundException();
  242. }
  243. /**
  244. * @param string $participant1
  245. * @param string $participant2
  246. * @return Room
  247. * @throws RoomNotFoundException
  248. */
  249. public function getOne2OneRoom($participant1, $participant2) {
  250. $query = $this->db->getQueryBuilder();
  251. $query->select('*')
  252. ->from('spreedme_rooms', 'r1')
  253. ->leftJoin('r1', 'spreedme_room_participants', 'p1', $query->expr()->andX(
  254. $query->expr()->eq('p1.userId', $query->createNamedParameter($participant1)),
  255. $query->expr()->eq('p1.roomId', 'r1.id')
  256. ))
  257. ->leftJoin('r1', 'spreedme_room_participants', 'p2', $query->expr()->andX(
  258. $query->expr()->eq('p2.userId', $query->createNamedParameter($participant2)),
  259. $query->expr()->eq('p2.roomId', 'r1.id')
  260. ))
  261. ->where($query->expr()->eq('r1.type', $query->createNamedParameter(Room::ONE_TO_ONE_CALL, IQueryBuilder::PARAM_INT)))
  262. ->andWhere($query->expr()->isNotNull('p1.userId'))
  263. ->andWhere($query->expr()->isNotNull('p2.userId'));
  264. $result = $query->execute();
  265. $row = $result->fetch();
  266. $result->closeCursor();
  267. if ($row === false) {
  268. throw new RoomNotFoundException();
  269. }
  270. return $this->createRoomObject($row);
  271. }
  272. /**
  273. * @return Room
  274. */
  275. public function createOne2OneRoom() {
  276. return $this->createRoom(Room::ONE_TO_ONE_CALL);
  277. }
  278. /**
  279. * @param string $name
  280. * @return Room
  281. */
  282. public function createGroupRoom($name = '') {
  283. return $this->createRoom(Room::GROUP_CALL, $name);
  284. }
  285. /**
  286. * @return Room
  287. */
  288. public function createPublicRoom() {
  289. return $this->createRoom(Room::PUBLIC_CALL);
  290. }
  291. /**
  292. * @param int $type
  293. * @param string $name
  294. * @return Room
  295. */
  296. private function createRoom($type, $name = '') {
  297. $token = $this->getNewToken();
  298. $query = $this->db->getQueryBuilder();
  299. $query->insert('spreedme_rooms')
  300. ->values(
  301. [
  302. 'name' => $query->createNamedParameter($name),
  303. 'type' => $query->createNamedParameter($type, IQueryBuilder::PARAM_INT),
  304. 'token' => $query->createNamedParameter($token),
  305. ]
  306. );
  307. $query->execute();
  308. $roomId = $query->getLastInsertId();
  309. return $this->createRoomObject([
  310. 'id' => $roomId,
  311. 'type' => $type,
  312. 'token' => $token,
  313. 'name' => $name,
  314. 'password' => '',
  315. ]);
  316. }
  317. /**
  318. * @param string $userId
  319. * @return string
  320. */
  321. public function getCurrentSessionId($userId) {
  322. if (empty($userId)) {
  323. return null;
  324. }
  325. $query = $this->db->getQueryBuilder();
  326. $query->select('*')
  327. ->from('spreedme_room_participants')
  328. ->where($query->expr()->eq('userId', $query->createNamedParameter($userId)))
  329. ->andWhere($query->expr()->neq('sessionId', $query->createNamedParameter('0')))
  330. ->orderBy('lastPing', 'DESC')
  331. ->setMaxResults(1);
  332. $result = $query->execute();
  333. $row = $result->fetch();
  334. $result->closeCursor();
  335. if ($row === false) {
  336. return null;
  337. }
  338. return $row['sessionId'];
  339. }
  340. /**
  341. * @param string $userId
  342. */
  343. public function disconnectUserFromAllRooms($userId) {
  344. $query = $this->db->getQueryBuilder();
  345. $query->update('spreedme_room_participants')
  346. ->set('sessionId', $query->createNamedParameter('0'))
  347. ->where($query->expr()->eq('userId', $query->createNamedParameter($userId)));
  348. $query->execute();
  349. }
  350. /**
  351. * @param string $sessionId
  352. */
  353. public function removeSessionFromAllRooms($sessionId) {
  354. $query = $this->db->getQueryBuilder();
  355. $query->delete('spreedme_room_participants')
  356. ->where($query->expr()->eq('sessionId', $query->createNamedParameter($sessionId)));
  357. $query->execute();
  358. }
  359. /**
  360. * @param string $userId
  361. * @return string[]
  362. */
  363. public function getSessionIdsForUser($userId) {
  364. if (!is_string($userId) || $userId === '') {
  365. // No deleting messages for guests
  366. return [];
  367. }
  368. // Delete all messages from or to the current user
  369. $query = $this->db->getQueryBuilder();
  370. $query->select('sessionId')
  371. ->from('spreedme_room_participants')
  372. ->where($query->expr()->eq('userId', $query->createNamedParameter($userId)));
  373. $result = $query->execute();
  374. $sessionIds = [];
  375. while ($row = $result->fetch()) {
  376. if ($row['sessionId'] !== '0') {
  377. $sessionIds[] = $row['sessionId'];
  378. }
  379. }
  380. $result->closeCursor();
  381. return $sessionIds;
  382. }
  383. /**
  384. * @return string
  385. */
  386. protected function getNewToken() {
  387. $chars = str_replace(['l', '0', '1'], '', ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
  388. $entropy = (int) $this->config->getAppValue('spreed', 'token_entropy', 8);
  389. $entropy = min(8, $entropy); // For update cases
  390. $query = $this->db->getQueryBuilder();
  391. $query->select('id')
  392. ->from('spreedme_rooms')
  393. ->where($query->expr()->eq('token', $query->createParameter('token')));
  394. $i = 0;
  395. while ($i < 1000) {
  396. try {
  397. return $this->generateNewToken($query, $entropy, $chars);
  398. } catch (\OutOfBoundsException $e) {
  399. $i++;
  400. if ($entropy >= 30 || $i >= 999) {
  401. // Max entropy of 30
  402. $i = 0;
  403. }
  404. }
  405. }
  406. $entropy++;
  407. $this->config->setAppValue('spreed', 'token_entropy', $entropy);
  408. return $this->generateNewToken($query, $entropy, $chars);
  409. }
  410. /**
  411. * @param IQueryBuilder $query
  412. * @param int $entropy
  413. * @param string $chars
  414. * @return string
  415. * @throws \OutOfBoundsException
  416. */
  417. protected function generateNewToken(IQueryBuilder $query, $entropy, $chars) {
  418. $token = $this->secureRandom->generate($entropy, $chars);
  419. $query->setParameter('token', $token);
  420. $result = $query->execute();
  421. $row = $result->fetch();
  422. $result->closeCursor();
  423. if (is_array($row)) {
  424. // Token already in use
  425. throw new \OutOfBoundsException();
  426. }
  427. return $token;
  428. }
  429. }