useOpenVidu.jsx 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import React from "react";
  2. import { OpenVidu } from "openvidu-browser";
  3. import { nanoid } from "nanoid";
  4. export const OpenViduContext = React.createContext({});
  5. class Stream {
  6. constructor({ stream, data, session }) {
  7. this.stream = stream;
  8. this.data = data;
  9. this._session = session;
  10. this.subscribed = false;
  11. this.subscriber = null;
  12. this.audio = true;
  13. this.video = true;
  14. this.uid = nanoid();
  15. this.toggleVideo = this.toggleVideo.bind(this);
  16. this.toggleAudio = this.toggleAudio.bind(this);
  17. this.toggleSubscribe = this.toggleSubscribe.bind(this);
  18. }
  19. subscribe() {
  20. if (this.subscribed) {
  21. return;
  22. }
  23. if (!this.subscriber) {
  24. this.subscriber = this._session.subscribe(this.stream);
  25. } else {
  26. this._session.subscribe(this.subscriber);
  27. }
  28. this.subscribed = true;
  29. }
  30. unsubscribe() {
  31. if (!this.subscribed) {
  32. return;
  33. }
  34. // We already had subscribed
  35. this.subscribed = false;
  36. this._session.unsubscribe(this.subscriber);
  37. }
  38. toggleSubscribe() {
  39. if (this.subscribed) {
  40. this.unsubscribe();
  41. } else {
  42. this.subscribe();
  43. }
  44. }
  45. enableVideo(value = true) {
  46. if (this.video === value) {
  47. return;
  48. }
  49. this._session.subscribeToVideo(value);
  50. this.video = value;
  51. }
  52. toggleVideo() {
  53. this.subscriber.publishVideo(!this.video);
  54. this.video = !this.video;
  55. }
  56. enableAudio(value = true) {
  57. if (this.audio === value) {
  58. return;
  59. }
  60. this._session.subscribeToAudio(value);
  61. this.audio = value;
  62. }
  63. toggleAudio() {
  64. this.subscriber.publishAudio(!this.audio);
  65. this.audio = !this.audio;
  66. }
  67. addVideoElement(elt) {
  68. if (!this.subscriber) {
  69. return;
  70. }
  71. this.subscriber.addVideoElement(elt);
  72. }
  73. }
  74. class LocalStream {
  75. constructor({ session, OV }) {
  76. this._session = session;
  77. this.published = false;
  78. this.publisher = null;
  79. this.audio = true;
  80. this.video = true;
  81. this.uid = nanoid();
  82. this._OV = OV;
  83. this.toggleVideo = this.toggleVideo.bind(this);
  84. this.toggleAudio = this.toggleAudio.bind(this);
  85. this.togglePublish = this.togglePublish.bind(this);
  86. }
  87. publish(config = {}, forceNew = false) {
  88. if (this.published) {
  89. return;
  90. }
  91. if (!this.publisher || forceNew) {
  92. this.publisher = this._OV.initPublisher(undefined, {
  93. audioSource: undefined, // The source of audio. If undefined default microphone
  94. videoSource: undefined, // The source of video. If undefined default webcam
  95. publishAudio: true, // Whether you want to start publishing with your audio unmuted or not
  96. publishVideo: true, // Whether you want to start publishing with your video enabled or not
  97. resolution: "320x240", // The resolution of your video
  98. frameRate: 10, // The frame rate of your video
  99. mirror: false, // Whether to mirror your local video or not
  100. ...config,
  101. });
  102. }
  103. this._session.publish(this.publisher);
  104. this.published = true;
  105. }
  106. unpublish() {
  107. if (!this.published) {
  108. return;
  109. }
  110. // We already had subscribed
  111. this.published = false;
  112. this._session.unpublish(this.publisher);
  113. }
  114. togglePublish() {
  115. if (this.published) {
  116. this.unpublish();
  117. } else {
  118. this.publish();
  119. }
  120. }
  121. enableVideo(value = true) {
  122. if (this.video === value) {
  123. return;
  124. }
  125. try {
  126. this.publisher.publishVideo(value);
  127. } catch (e) {
  128. setTimeout(() => {
  129. try {
  130. this.publisher.publishVideo(value);
  131. } catch (e) {
  132. console.log("Error while trying to change video publishing:", e);
  133. }
  134. }, 2000);
  135. }
  136. this.video = value;
  137. }
  138. toggleVideo() {
  139. this.publisher.publishVideo(!this.video);
  140. this.video = !this.video;
  141. }
  142. enableAudio(value = true) {
  143. if (this.audio === value) {
  144. return;
  145. }
  146. try {
  147. this.publisher.publishAudio(value);
  148. } catch (e) {
  149. setTimeout(() => {
  150. try {
  151. this.publisher.publishVideo(value);
  152. } catch (e) {
  153. console.log("Error while trying change audio publishing:", e);
  154. }
  155. }, 2000);
  156. }
  157. this.audio = value;
  158. }
  159. toggleAudio() {
  160. this.publisher.publishAudio(!this.audio);
  161. this.audio = !this.audio;
  162. }
  163. addVideoElement(elt) {
  164. if (!this.publisher) {
  165. return;
  166. }
  167. this.publisher.addVideoElement(elt);
  168. }
  169. }
  170. const defaultParseData = (d) => d;
  171. const defaultSetData = () => nanoid();
  172. export const OpenViduProvider = ({
  173. children,
  174. room,
  175. getToken,
  176. parseUserData = defaultParseData,
  177. getUserData = defaultSetData,
  178. }) => {
  179. const OVRef = React.useRef(new OpenVidu());
  180. const instanceRef = React.useRef({});
  181. const [connected, setConnected] = React.useState(false);
  182. const [remoteStreams, setRemoteStreams] = React.useState([]);
  183. const [localStream, setLocalStream] = React.useState(null);
  184. const joinSession = React.useCallback(
  185. async ({ room, parseUserData, getUserData }) => {
  186. console.log("Join conf session...");
  187. if (!OVRef.current) {
  188. OVRef.current = new OpenVidu();
  189. }
  190. OVRef.current.enableProdMode();
  191. const newSession = OVRef.current.initSession();
  192. // On every new Stream received...
  193. newSession.on("streamCreated", (event) => {
  194. // Subscribe to the Stream to receive it. Second parameter is undefined
  195. // so OpenVidu doesn't create an HTML video by its own
  196. const newStream = new Stream({
  197. data: parseUserData(event.stream.connection.data),
  198. stream: event.stream,
  199. session: newSession,
  200. });
  201. setRemoteStreams((prev) => [...prev, newStream]);
  202. });
  203. // On every Stream destroyed...
  204. newSession.on("streamDestroyed", (event) => {
  205. setRemoteStreams((prev) =>
  206. prev.filter(({ stream }) => stream !== event.stream)
  207. );
  208. });
  209. newSession.on("streamPropertyChanged", () => {
  210. // Just update the map to trigger the render
  211. setRemoteStreams((prev) => prev.slice());
  212. });
  213. const token = await getToken(room);
  214. await newSession.connect(token, getUserData());
  215. setLocalStream(
  216. new LocalStream({ session: newSession, OV: OVRef.current })
  217. );
  218. setConnected(true);
  219. instanceRef.current.session = newSession;
  220. },
  221. [getToken]
  222. );
  223. const onLeave = React.useCallback(() => {
  224. const { session } = instanceRef.current;
  225. if (session) {
  226. session.disconnect();
  227. instanceRef.current = {};
  228. OVRef.current = null;
  229. }
  230. }, []);
  231. React.useEffect(() => {
  232. window.addEventListener("beforeunload", onLeave);
  233. return () => {
  234. window.removeEventListener("beforeunload", onLeave);
  235. };
  236. }, [onLeave]);
  237. React.useEffect(() => {
  238. joinSession({ room, parseUserData, getUserData });
  239. return onLeave;
  240. }, [getUserData, joinSession, onLeave, parseUserData, room]);
  241. return (
  242. <OpenViduContext.Provider value={{ remoteStreams, localStream }}>
  243. {connected && children}
  244. </OpenViduContext.Provider>
  245. );
  246. };
  247. const useOpenVidu = () => {
  248. return React.useContext(OpenViduContext);
  249. };
  250. export default useOpenVidu;