SignalingMessageReceiver.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Daniel Calviño Sánchez
  5. * Copyright (C) 2022 Daniel Calviño Sánchez <danxuliu@gmail.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * 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 General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.nextcloud.talk.signaling;
  21. import com.nextcloud.talk.models.json.converters.EnumParticipantTypeConverter;
  22. import com.nextcloud.talk.models.json.participants.Participant;
  23. import com.nextcloud.talk.models.json.signaling.NCIceCandidate;
  24. import com.nextcloud.talk.models.json.signaling.NCMessagePayload;
  25. import com.nextcloud.talk.models.json.signaling.NCSignalingMessage;
  26. import java.util.ArrayList;
  27. import java.util.List;
  28. import java.util.Map;
  29. /**
  30. * Hub to register listeners for signaling messages of different kinds.
  31. *
  32. * In general, if a listener is added while an event is being handled the new listener will not receive that event.
  33. * An exception to that is adding a WebRtcMessageListener when handling an offer in an OfferMessageListener; in that
  34. * case the "onOffer()" method of the WebRtcMessageListener will be called for that same offer.
  35. *
  36. * Similarly, if a listener is removed while an event is being handled the removed listener will still receive that
  37. * event. Again the exception is removing a WebRtcMessageListener when handling an offer in an OfferMessageListener; in
  38. * that case the "onOffer()" method of the WebRtcMessageListener will not be called for that offer.
  39. *
  40. * Adding and removing listeners, as well as notifying them is internally synchronized. This should be kept in mind
  41. * if listeners are added or removed when handling an event to prevent deadlocks (nevertheless, just adding or
  42. * removing a listener in the same thread handling the event is fine, and in most cases it will be fine too if done
  43. * in a different thread, as long as the notifier thread is not forced to wait until the listener is added or removed).
  44. *
  45. * SignalingMessageReceiver does not fetch the signaling messages itself; subclasses must fetch them and then call
  46. * the appropriate protected methods to process the messages and notify the listeners.
  47. */
  48. public abstract class SignalingMessageReceiver {
  49. /**
  50. * Listener for participant list messages.
  51. *
  52. * The messages are implicitly bound to the room currently joined in the signaling server; listeners are expected
  53. * to know the current room.
  54. */
  55. public interface ParticipantListMessageListener {
  56. /**
  57. * List of all the participants in the room.
  58. *
  59. * This message is received only when the internal signaling server is used.
  60. *
  61. * The message is received periodically, and the participants may not have been modified since the last message.
  62. *
  63. * Only the following participant properties are set:
  64. * - inCall
  65. * - lastPing
  66. * - sessionId
  67. * - userId (if the participant is not a guest)
  68. *
  69. * "participantPermissions" is provided in the message (since Talk 13), but not currently set in the
  70. * participant. "publishingPermissions" was provided instead in Talk 12, but it was not used anywhere, so it is
  71. * ignored.
  72. *
  73. * @param participants all the participants (users and guests) in the room
  74. */
  75. void onUsersInRoom(List<Participant> participants);
  76. /**
  77. * List of all the participants in the call or the room (depending on what triggered the event).
  78. *
  79. * This message is received only when the external signaling server is used.
  80. *
  81. * The message is received when any participant changed, although what changed is not provided and should be
  82. * derived from the difference with previous messages. The list of participants may include only the
  83. * participants in the call (including those that just left it and thus triggered the event) or all the
  84. * participants currently in the room (participants in the room but not currently active, that is, without a
  85. * session, are not included).
  86. *
  87. * Only the following participant properties are set:
  88. * - inCall
  89. * - lastPing
  90. * - sessionId
  91. * - type
  92. * - userId (if the participant is not a guest)
  93. *
  94. * "nextcloudSessionId" is provided in the message (when the "inCall" property of any participant changed), but
  95. * not currently set in the participant.
  96. *
  97. * "participantPermissions" is provided in the message (since Talk 13), but not currently set in the
  98. * participant. "publishingPermissions" was provided instead in Talk 12, but it was not used anywhere, so it is
  99. * ignored.
  100. *
  101. * @param participants all the participants (users and guests) in the room
  102. */
  103. void onParticipantsUpdate(List<Participant> participants);
  104. /**
  105. * Update of the properties of all the participants in the room.
  106. *
  107. * This message is received only when the external signaling server is used.
  108. *
  109. * @param inCall the new value of the inCall property
  110. */
  111. void onAllParticipantsUpdate(long inCall);
  112. }
  113. /**
  114. * Listener for call participant messages.
  115. *
  116. * The messages are bound to a specific call participant (or, rather, session), so each listener is expected to
  117. * handle messages only for a single call participant.
  118. *
  119. * Although "unshareScreen" is technically bound to a specific peer connection it is instead treated as a general
  120. * message on the call participant.
  121. */
  122. public interface CallParticipantMessageListener {
  123. void onRaiseHand(boolean state, long timestamp);
  124. void onUnshareScreen();
  125. }
  126. /**
  127. * Listener for WebRTC offers.
  128. *
  129. * Unlike the WebRtcMessageListener, which is bound to a specific peer connection, an OfferMessageListener listens
  130. * to all offer messages, no matter which peer connection they are bound to. This can be used, for example, to
  131. * create a new peer connection when a remote offer for which there is no previous connection is received.
  132. *
  133. * When an offer is received all OfferMessageListeners are notified before any WebRtcMessageListener is notified.
  134. */
  135. public interface OfferMessageListener {
  136. void onOffer(String sessionId, String roomType, String sdp, String nick);
  137. }
  138. /**
  139. * Listener for WebRTC messages.
  140. *
  141. * The messages are bound to a specific peer connection, so each listener is expected to handle messages only for
  142. * a single peer connection.
  143. */
  144. public interface WebRtcMessageListener {
  145. void onOffer(String sdp, String nick);
  146. void onAnswer(String sdp, String nick);
  147. void onCandidate(String sdpMid, int sdpMLineIndex, String sdp);
  148. void onEndOfCandidates();
  149. }
  150. private final ParticipantListMessageNotifier participantListMessageNotifier = new ParticipantListMessageNotifier();
  151. private final CallParticipantMessageNotifier callParticipantMessageNotifier = new CallParticipantMessageNotifier();
  152. private final OfferMessageNotifier offerMessageNotifier = new OfferMessageNotifier();
  153. private final WebRtcMessageNotifier webRtcMessageNotifier = new WebRtcMessageNotifier();
  154. /**
  155. * Adds a listener for participant list messages.
  156. *
  157. * A listener is expected to be added only once. If the same listener is added again it will be notified just once.
  158. *
  159. * @param listener the ParticipantListMessageListener
  160. */
  161. public void addListener(ParticipantListMessageListener listener) {
  162. participantListMessageNotifier.addListener(listener);
  163. }
  164. public void removeListener(ParticipantListMessageListener listener) {
  165. participantListMessageNotifier.removeListener(listener);
  166. }
  167. /**
  168. * Adds a listener for call participant messages.
  169. *
  170. * A listener is expected to be added only once. If the same listener is added again it will no longer be notified
  171. * for the messages from the previous session ID.
  172. *
  173. * @param listener the CallParticipantMessageListener
  174. * @param sessionId the ID of the session that messages come from
  175. */
  176. public void addListener(CallParticipantMessageListener listener, String sessionId) {
  177. callParticipantMessageNotifier.addListener(listener, sessionId);
  178. }
  179. public void removeListener(CallParticipantMessageListener listener) {
  180. callParticipantMessageNotifier.removeListener(listener);
  181. }
  182. /**
  183. * Adds a listener for all offer messages.
  184. *
  185. * A listener is expected to be added only once. If the same listener is added again it will be notified just once.
  186. *
  187. * @param listener the OfferMessageListener
  188. */
  189. public void addListener(OfferMessageListener listener) {
  190. offerMessageNotifier.addListener(listener);
  191. }
  192. public void removeListener(OfferMessageListener listener) {
  193. offerMessageNotifier.removeListener(listener);
  194. }
  195. /**
  196. * Adds a listener for WebRTC messages from the given session ID and room type.
  197. *
  198. * A listener is expected to be added only once. If the same listener is added again it will no longer be notified
  199. * for the messages from the previous session ID or room type.
  200. *
  201. * @param listener the WebRtcMessageListener
  202. * @param sessionId the ID of the session that messages come from
  203. * @param roomType the room type that messages come from
  204. */
  205. public void addListener(WebRtcMessageListener listener, String sessionId, String roomType) {
  206. webRtcMessageNotifier.addListener(listener, sessionId, roomType);
  207. }
  208. public void removeListener(WebRtcMessageListener listener) {
  209. webRtcMessageNotifier.removeListener(listener);
  210. }
  211. protected void processEvent(Map<String, Object> eventMap) {
  212. if (!"update".equals(eventMap.get("type")) || !"participants".equals(eventMap.get("target"))) {
  213. return;
  214. }
  215. Map<String, Object> updateMap;
  216. try {
  217. updateMap = (Map<String, Object>) eventMap.get("update");
  218. } catch (RuntimeException e) {
  219. // Broken message, this should not happen.
  220. return;
  221. }
  222. if (updateMap == null) {
  223. // Broken message, this should not happen.
  224. return;
  225. }
  226. if (updateMap.get("all") != null && Boolean.parseBoolean(updateMap.get("all").toString())) {
  227. processAllParticipantsUpdate(updateMap);
  228. return;
  229. }
  230. if (updateMap.get("users") != null) {
  231. processParticipantsUpdate(updateMap);
  232. return;
  233. }
  234. }
  235. private void processAllParticipantsUpdate(Map<String, Object> updateMap) {
  236. // Message schema:
  237. // {
  238. // "type": "event",
  239. // "event": {
  240. // "target": "participants",
  241. // "type": "update",
  242. // "update": {
  243. // "roomid": #STRING#,
  244. // "incall": 0,
  245. // "all": true,
  246. // },
  247. // },
  248. // }
  249. long inCall;
  250. try {
  251. inCall = Long.parseLong(updateMap.get("inCall").toString());
  252. } catch (RuntimeException e) {
  253. // Broken message, this should not happen.
  254. return;
  255. }
  256. participantListMessageNotifier.notifyAllParticipantsUpdate(inCall);
  257. }
  258. private void processParticipantsUpdate(Map<String, Object> updateMap) {
  259. // Message schema:
  260. // {
  261. // "type": "event",
  262. // "event": {
  263. // "target": "participants",
  264. // "type": "update",
  265. // "update": {
  266. // "roomid": #INTEGER#,
  267. // "users": [
  268. // {
  269. // "inCall": #INTEGER#,
  270. // "lastPing": #INTEGER#,
  271. // "sessionId": #STRING#,
  272. // "participantType": #INTEGER#,
  273. // "userId": #STRING#, // Optional
  274. // "nextcloudSessionId": #STRING#, // Optional
  275. // "participantPermissions": #INTEGER#, // Talk >= 13
  276. // },
  277. // ...
  278. // ],
  279. // },
  280. // },
  281. // }
  282. //
  283. // Note that "userId" in participants->update comes from the Nextcloud server, so it is "userId"; in other
  284. // messages, like room->join, it comes directly from the external signaling server, so it is "userid" instead.
  285. List<Map<String, Object>> users;
  286. try {
  287. users = (List<Map<String, Object>>) updateMap.get("users");
  288. } catch (RuntimeException e) {
  289. // Broken message, this should not happen.
  290. return;
  291. }
  292. if (users == null) {
  293. // Broken message, this should not happen.
  294. return;
  295. }
  296. List<Participant> participants = new ArrayList<>(users.size());
  297. for (Map<String, Object> user: users) {
  298. try {
  299. participants.add(getParticipantFromMessageMap(user));
  300. } catch (RuntimeException e) {
  301. // Broken message, this should not happen.
  302. return;
  303. }
  304. }
  305. participantListMessageNotifier.notifyParticipantsUpdate(participants);
  306. }
  307. protected void processUsersInRoom(List<Map<String, Object>> users) {
  308. // Message schema:
  309. // {
  310. // "type": "usersInRoom",
  311. // "data": [
  312. // {
  313. // "inCall": #INTEGER#,
  314. // "lastPing": #INTEGER#,
  315. // "roomId": #INTEGER#,
  316. // "sessionId": #STRING#,
  317. // "userId": #STRING#, // Always included, although it can be empty
  318. // "participantPermissions": #INTEGER#, // Talk >= 13
  319. // },
  320. // ...
  321. // ],
  322. // }
  323. List<Participant> participants = new ArrayList<>(users.size());
  324. for (Map<String, Object> user: users) {
  325. try {
  326. participants.add(getParticipantFromMessageMap(user));
  327. } catch (RuntimeException e) {
  328. // Broken message, this should not happen.
  329. return;
  330. }
  331. }
  332. participantListMessageNotifier.notifyUsersInRoom(participants);
  333. }
  334. /**
  335. * Creates and initializes a Participant from the data in the given map.
  336. *
  337. * Maps from internal and external signaling server messages can be used. Nevertheless, besides the differences
  338. * between the messages and the optional properties, it is expected that the message is correct and the given data
  339. * is parseable. Broken messages (for example, a string instead of an integer for "inCall" or a missing
  340. * "sessionId") may cause a RuntimeException to be thrown.
  341. *
  342. * @param participantMap the map with the participant data
  343. * @return the Participant
  344. */
  345. private Participant getParticipantFromMessageMap(Map<String, Object> participantMap) {
  346. Participant participant = new Participant();
  347. participant.setInCall(Long.parseLong(participantMap.get("inCall").toString()));
  348. participant.setLastPing(Long.parseLong(participantMap.get("lastPing").toString()));
  349. participant.setSessionId(participantMap.get("sessionId").toString());
  350. if (participantMap.get("userId") != null && !participantMap.get("userId").toString().isEmpty()) {
  351. participant.setUserId(participantMap.get("userId").toString());
  352. }
  353. // Only in external signaling messages
  354. if (participantMap.get("participantType") != null) {
  355. int participantTypeInt = Integer.parseInt(participantMap.get("participantType").toString());
  356. EnumParticipantTypeConverter converter = new EnumParticipantTypeConverter();
  357. participant.setType(converter.getFromInt(participantTypeInt));
  358. }
  359. return participant;
  360. }
  361. protected void processSignalingMessage(NCSignalingMessage signalingMessage) {
  362. // Note that in the internal signaling server message "data" is the String representation of a JSON
  363. // object, although it is already decoded when used here.
  364. String type = signalingMessage.getType();
  365. String sessionId = signalingMessage.getFrom();
  366. String roomType = signalingMessage.getRoomType();
  367. if ("raiseHand".equals(type)) {
  368. // Message schema (external signaling server):
  369. // {
  370. // "type": "message",
  371. // "message": {
  372. // "sender": {
  373. // ...
  374. // },
  375. // "data": {
  376. // "to": #STRING#,
  377. // "sid": #STRING#,
  378. // "roomType": "video",
  379. // "type": "raiseHand",
  380. // "payload": {
  381. // "state": #BOOLEAN#,
  382. // "timestamp": #LONG#,
  383. // },
  384. // "from": #STRING#,
  385. // },
  386. // },
  387. // }
  388. //
  389. // Message schema (internal signaling server):
  390. // {
  391. // "type": "message",
  392. // "data": {
  393. // "to": #STRING#,
  394. // "sid": #STRING#,
  395. // "roomType": "video",
  396. // "type": "raiseHand",
  397. // "payload": {
  398. // "state": #BOOLEAN#,
  399. // "timestamp": #LONG#,
  400. // },
  401. // "from": #STRING#,
  402. // },
  403. // }
  404. NCMessagePayload payload = signalingMessage.getPayload();
  405. if (payload == null) {
  406. // Broken message, this should not happen.
  407. return;
  408. }
  409. Boolean state = payload.getState();
  410. Long timestamp = payload.getTimestamp();
  411. if (state == null || timestamp == null) {
  412. // Broken message, this should not happen.
  413. return;
  414. }
  415. callParticipantMessageNotifier.notifyRaiseHand(sessionId, state, timestamp);
  416. return;
  417. }
  418. // "unshareScreen" messages are directly sent to the screen peer connection when the internal signaling
  419. // server is used, and to the room when the external signaling server is used. However, the (relevant) data
  420. // of the received message ("from" and "type") is the same in both cases.
  421. if ("unshareScreen".equals(type)) {
  422. // Message schema (external signaling server):
  423. // {
  424. // "type": "message",
  425. // "message": {
  426. // "sender": {
  427. // ...
  428. // },
  429. // "data": {
  430. // "roomType": "screen",
  431. // "type": "unshareScreen",
  432. // "from": #STRING#,
  433. // },
  434. // },
  435. // }
  436. //
  437. // Message schema (internal signaling server):
  438. // {
  439. // "type": "message",
  440. // "data": {
  441. // "to": #STRING#,
  442. // "sid": #STRING#,
  443. // "broadcaster": #STRING#,
  444. // "roomType": "screen",
  445. // "type": "unshareScreen",
  446. // "from": #STRING#,
  447. // },
  448. // }
  449. callParticipantMessageNotifier.notifyUnshareScreen(sessionId);
  450. return;
  451. }
  452. if ("offer".equals(type)) {
  453. // Message schema (external signaling server):
  454. // {
  455. // "type": "message",
  456. // "message": {
  457. // "sender": {
  458. // ...
  459. // },
  460. // "data": {
  461. // "to": #STRING#,
  462. // "from": #STRING#,
  463. // "type": "offer",
  464. // "roomType": #STRING#, // "video" or "screen"
  465. // "payload": {
  466. // "type": "offer",
  467. // "sdp": #STRING#,
  468. // },
  469. // "sid": #STRING#, // external signaling server >= 0.5.0
  470. // },
  471. // },
  472. // }
  473. //
  474. // Message schema (internal signaling server):
  475. // {
  476. // "type": "message",
  477. // "data": {
  478. // "to": #STRING#,
  479. // "sid": #STRING#,
  480. // "roomType": #STRING#, // "video" or "screen"
  481. // "type": "offer",
  482. // "payload": {
  483. // "type": "offer",
  484. // "sdp": #STRING#,
  485. // "nick": #STRING#, // Optional
  486. // },
  487. // "from": #STRING#,
  488. // },
  489. // }
  490. NCMessagePayload payload = signalingMessage.getPayload();
  491. if (payload == null) {
  492. // Broken message, this should not happen.
  493. return;
  494. }
  495. String sdp = payload.getSdp();
  496. String nick = payload.getNick();
  497. // If "processSignalingMessage" is called with two offers from two different threads it is possible,
  498. // although extremely unlikely, that the WebRtcMessageListeners for the second offer are notified before the
  499. // WebRtcMessageListeners for the first offer. This should not be a problem, though, so for simplicity
  500. // the statements are not synchronized.
  501. offerMessageNotifier.notifyOffer(sessionId, roomType, sdp, nick);
  502. webRtcMessageNotifier.notifyOffer(sessionId, roomType, sdp, nick);
  503. return;
  504. }
  505. if ("answer".equals(type)) {
  506. // Message schema: same as offers, but with type "answer".
  507. NCMessagePayload payload = signalingMessage.getPayload();
  508. if (payload == null) {
  509. // Broken message, this should not happen.
  510. return;
  511. }
  512. String sdp = payload.getSdp();
  513. String nick = payload.getNick();
  514. webRtcMessageNotifier.notifyAnswer(sessionId, roomType, sdp, nick);
  515. return;
  516. }
  517. if ("candidate".equals(type)) {
  518. // Message schema (external signaling server):
  519. // {
  520. // "type": "message",
  521. // "message": {
  522. // "sender": {
  523. // ...
  524. // },
  525. // "data": {
  526. // "to": #STRING#,
  527. // "from": #STRING#,
  528. // "type": "candidate",
  529. // "roomType": #STRING#, // "video" or "screen"
  530. // "payload": {
  531. // "candidate": {
  532. // "candidate": #STRING#,
  533. // "sdpMid": #STRING#,
  534. // "sdpMLineIndex": #INTEGER#,
  535. // },
  536. // },
  537. // "sid": #STRING#, // external signaling server >= 0.5.0
  538. // },
  539. // },
  540. // }
  541. //
  542. // Message schema (internal signaling server):
  543. // {
  544. // "type": "message",
  545. // "data": {
  546. // "to": #STRING#,
  547. // "sid": #STRING#,
  548. // "roomType": #STRING#, // "video" or "screen"
  549. // "type": "candidate",
  550. // "payload": {
  551. // "candidate": {
  552. // "candidate": #STRING#,
  553. // "sdpMid": #STRING#,
  554. // "sdpMLineIndex": #INTEGER#,
  555. // },
  556. // },
  557. // "from": #STRING#,
  558. // },
  559. // }
  560. NCMessagePayload payload = signalingMessage.getPayload();
  561. if (payload == null) {
  562. // Broken message, this should not happen.
  563. return;
  564. }
  565. NCIceCandidate ncIceCandidate = payload.getIceCandidate();
  566. if (ncIceCandidate == null) {
  567. // Broken message, this should not happen.
  568. return;
  569. }
  570. webRtcMessageNotifier.notifyCandidate(sessionId,
  571. roomType,
  572. ncIceCandidate.getSdpMid(),
  573. ncIceCandidate.getSdpMLineIndex(),
  574. ncIceCandidate.getCandidate());
  575. return;
  576. }
  577. if ("endOfCandidates".equals(type)) {
  578. webRtcMessageNotifier.notifyEndOfCandidates(sessionId, roomType);
  579. return;
  580. }
  581. }
  582. }