pro-call.blade.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. @extends('layouts.meeting')
  2. @section('content')
  3. <div id="proCallComponent">
  4. <div class="d-flex align-items-center justify-content-center py-3 border-bottom">
  5. <span class="mr-3">
  6. {{ $pro->name_display }} | PRO
  7. </span>
  8. <button class="btn btn-sm btn-primary px-4 font-weight-bold"
  9. v-on:click.prevent="nextPatient()"
  10. :disabled="client || checkingForNextPatient || started">Next Patient</button>
  11. <span v-if="patientInQueue && !started" class="patient-in-q-alert text-warning text-sm ml-2 small">
  12. <i class="fa fa-circle"></i>
  13. </span>
  14. <span v-if="!patientInQueue && !started" class="text-success text-sm ml-2 small">
  15. <i class="fa fa-circle"></i>
  16. </span>
  17. </div>
  18. <div v-if="!started && noNextPatient" class="bg-light rounded text-center py-1 font-weight-bold text-sm my-3 mx-3">@{{ noNextPatient }}</div>
  19. <div class="" v-show="videoActive">
  20. <div class="py-3 text-center" v-if="started">
  21. <h6 class="text-black font-weight-bold m-0">Call in progress: @{{ timeDisplay() }}</h6>
  22. </div>
  23. <div class="main-view mx-auto">
  24. <div id="self-view" class="full-view" data-name="{{ $pro->name_display }}" data-type="PRO"></div>
  25. <div class="thumbs">
  26. </div>
  27. <button class="btn btn-danger rounded-circle hang-up"
  28. v-if="started"
  29. title="Leave Call"
  30. v-on:click.prevent="hangUp()">
  31. <i class="fa fa-phone"></i>
  32. </button>
  33. </div>
  34. </div>
  35. </div>
  36. <script>
  37. new Vue({
  38. el: '#proCallComponent',
  39. delimiters: ['@{{', '}}'],
  40. data: {
  41. time: 0,
  42. startTime: 0,
  43. started: false,
  44. client: false,
  45. pro: false,
  46. selfName: '',
  47. selfToken: '',
  48. clientUid: '',
  49. otSessionId: '',
  50. checkingForNextPatient: false,
  51. noNextPatient: false,
  52. otSession: false,
  53. selfUserType: 'PRO',
  54. selfStreamId: '',
  55. patientInQueue: false,
  56. videoActive: false,
  57. heartbeatTimer: false,
  58. },
  59. methods: {
  60. pollForNextPatient: function() {
  61. if(!this.started) {
  62. this.nextPatient(true);
  63. }
  64. },
  65. nextPatient: function(_pollOnly = false) {
  66. var self = this;
  67. if(!_pollOnly) this.checkingForNextPatient = true;
  68. $.post('/api/client/getNextClientForVideoVisit', {}, function(_data) {
  69. if(_pollOnly) {
  70. self.patientInQueue = _data.success;
  71. }
  72. else {
  73. self.checkingForNextPatient = false;
  74. if(!_data.success) {
  75. self.noNextPatient = _data.message;
  76. window.setTimeout(function() {
  77. self.noNextPatient = false;
  78. }, 2000);
  79. }
  80. else {
  81. // get ot session key from client record
  82. self.client = true;
  83. self.clientUid = _data.data;
  84. self.videoActive = true;
  85. self.startOpenTokSession();
  86. }
  87. }
  88. }, 'json');
  89. },
  90. startOpenTokSession: function() {
  91. var self = this;
  92. self.getOpenTokSessionId(function() {
  93. self.selfName = '{{ $pro->name_display }}';
  94. $.post('/api/openTok/getClientToken', {
  95. opentokSessionId: self.otSessionId,
  96. data: JSON.stringify({
  97. uid: '{{ $pro->uid }}',
  98. name: self.selfName,
  99. type: 'PRO'
  100. })
  101. }, function (_data) {
  102. console.log(_data);
  103. self.selfToken = _data.data;
  104. self.initOpenTok();
  105. });
  106. });
  107. },
  108. timeDisplay: function() {
  109. var seconds = this.time / 1000,
  110. minutes = parseInt(seconds / 60, 10);
  111. seconds = parseInt(seconds % 60, 10);
  112. return minutes + " min, " + seconds + " sec";
  113. },
  114. hangUp: function() {
  115. if(this.otSession) {
  116. try {
  117. this.otSession.disconnect();
  118. }
  119. catch (e) {
  120. console.log('Was already disconnected.');
  121. }
  122. this.otSession = false;
  123. this.otSessionId = '';
  124. this.started = false;
  125. this.startTime = false;
  126. this.videoActive = false;
  127. // this.client = false;
  128. }
  129. },
  130. initOpenTok: function() {
  131. /* fake video feed (temp) */
  132. const randomColour = () => {
  133. return Math.round(Math.random() * 255);
  134. };
  135. const canvas = document.createElement('canvas');
  136. canvas.width = 640;
  137. canvas.height = 480;
  138. const ctx = canvas.getContext('2d');
  139. var pos = 100;
  140. window.setInterval(function() {
  141. ctx.clearRect(0, 0, canvas.width, canvas.height);
  142. ctx.font = "20px Georgia";
  143. ctx.fillStyle = `rgb(220, 220, 220)`;
  144. ctx.fillText("Video feed from {{ $pro->name_display }}", 20, pos);
  145. pos += 5;
  146. if(pos > canvas.height) pos = 100;
  147. }, 1000);
  148. var self = this;
  149. var apiKey = '<?= env('TOKBOX_API_KEY', '46678902') ?>';
  150. var sessionId = this.otSessionId;
  151. var token = this.selfToken;
  152. // destroy if existing
  153. // self.hangUp();
  154. self.otSession = OT.initSession(apiKey, sessionId);
  155. // peer connected
  156. self.otSession.on('streamCreated', function streamCreated(event) {
  157. console.log('streamCreated', arguments);
  158. var subscriberOptions = {
  159. insertMode: 'append',
  160. width: '100%',
  161. height: '100%'
  162. };
  163. var connectionData = JSON.parse(event.stream.connection.data);
  164. // add a div for remove view
  165. var remoteViewID = 'remote-view-' + event.stream.id;
  166. var remoteElem = $('<div id="' + remoteViewID + '" class="remote-view thumb-view" ' +
  167. 'data-stream="' + event.stream.id + '" ' +
  168. 'data-connection-data="' + event.stream.connection.data + '" ' +
  169. 'data-name="' + connectionData.name + '" ' +
  170. 'data-type="' + connectionData.type + '"></div>');
  171. remoteElem.appendTo('.thumbs');
  172. self.otSession.subscribe(event.stream, remoteViewID, subscriberOptions, self.handleOpenTokError);
  173. if (connectionData.type === 'CLIENT') {
  174. self.client = true;
  175. }
  176. if(!self.startTime) {
  177. self.startTime = new Date().getTime();
  178. window.setInterval(function() {
  179. self.time = new Date().getTime() - self.startTime;
  180. }, 1000);
  181. self.started = true;
  182. }
  183. self.activateParty(event.stream.id);
  184. });
  185. // peer disconnected
  186. self.otSession.on("streamDestroyed", function(event) {
  187. onPeerDisconnection(event, event.stream.connection.data);
  188. });
  189. // self.otSession.on("connectionDestroyed", function(event) {
  190. // debugger;
  191. // console.log('connectionDestroyed from ' + event.connection.data);
  192. // onPeerDisconnection(event, event.connection.data);
  193. // });
  194. self.otSession.on("connectionCreated", function(event) {
  195. console.log('connectionCreated');
  196. console.log(event);
  197. });
  198. function onPeerDisconnection(event, data) {
  199. if(event.stream && $('.full-view[data-stream="' + event.stream.id + '"]').length) {
  200. var allThumbs = $('.thumbs [data-stream]:not([data-stream=""]):not(.disconnected-view):visible');
  201. if(allThumbs.length) {
  202. $('.thumbs [data-stream]:not([data-stream=""])').each(function() {
  203. if($(this).attr('data-stream') !== event.stream.id) {
  204. self.activateParty($(this).attr('data-stream'));
  205. return false;
  206. }
  207. });
  208. }
  209. else {
  210. self.hangUp();
  211. }
  212. }
  213. if(event.stream) {
  214. var remoteViewElem = $('[data-stream="' + event.stream.id + '"]');
  215. remoteViewElem.remove();
  216. // if(remoteViewElem.length) {
  217. // remoteViewElem.attr('data-stream', '');
  218. // remoteViewElem.attr('data-connection-data', '');
  219. // remoteViewElem.attr('data-type', '');
  220. // remoteViewElem.attr('data-name', '');
  221. // }
  222. // remoteViewElem.addClass('disconnected-view')
  223. }
  224. var connectionData = JSON.parse(data);
  225. if(connectionData.type === 'CLIENT') {
  226. self.client = false;
  227. }
  228. // if no other parties in call, hang up
  229. if(!$('[data-stream]:not([data-stream="' + self.selfStreamId + '"])').length) {
  230. // self.hangUp();
  231. console.warn('No other parties in the call!');
  232. new Noty({
  233. theme: 'mint',
  234. type: 'info',
  235. text: 'All other participants have left the call',
  236. progressBar: false,
  237. timeout: 2500,
  238. }).show();
  239. self.startTime = 0;
  240. self.started = false;
  241. self.hangUp();
  242. }
  243. }
  244. // self connected
  245. self.otSession.on("sessionConnected", function(event) {
  246. self.joinMeetingAsPro(self.selfUserType);
  247. });
  248. // self disconnected
  249. self.otSession.on('sessionDisconnected', function sessionDisconnected(event) {
  250. console.log('You were disconnected from the session.', event.reason);
  251. // turn pro video off
  252. $.post('/api/clientVideoVisit/turnProVideoOff', {}, function(_data) {
  253. console.log(_data);
  254. // stop heart beat
  255. if(self.heartbeatTimer) {
  256. window.clearInterval(self.heartbeatTimer);
  257. self.heartbeatTimer = false;
  258. }
  259. });
  260. });
  261. // initialize the publisher
  262. var publisherOptions = {
  263. videoSource: canvas.captureStream(1).getVideoTracks()[0], // TODO: Comment this line to use webcam
  264. insertMode: 'append',
  265. width: '100%',
  266. height: '100%',
  267. };
  268. var publisher = OT.initPublisher('self-view', publisherOptions, self.handleOpenTokError);
  269. publisher.on('streamCreated', function(event) {
  270. var selfView = $('#self-view');
  271. selfView.attr('data-stream', event.stream.id);
  272. selfView.attr('data-connection-data', event.stream.connection.data);
  273. self.selfStreamId = event.stream.id;
  274. });
  275. publisher.on('streamCreated', function(event) {
  276. console.log('publisher->streamCreated');
  277. var selfView = $('#self-view');
  278. selfView.attr('data-stream', event.stream.id);
  279. selfView.attr('data-connection-data', event.stream.connection.data);
  280. selfView.attr('data-type', 'PRO');
  281. self.activateParty('self');
  282. $('#self-view').show();
  283. // turn pro video on
  284. $.post('/api/clientVideoVisit/turnProVideoOn', {}, function(_data) {
  285. console.log(_data);
  286. // start heart beat
  287. self.heartbeatTimer = window.setInterval(function() {
  288. $.post('/api/clientVideoVisit/registerProMeetingHeartbeat', {}, function(_data) {
  289. console.log(_data);
  290. });
  291. }, 5000);
  292. });
  293. });
  294. publisher.on('streamDestroyed', function(event) {
  295. event.preventDefault();
  296. console.log('publisher->streamDestroyed');
  297. $('#self-view').hide();
  298. var allThumbs = $('.thumbs [data-stream]:not([data-stream=""]):not(.disconnected-view):visible');
  299. if(allThumbs.length) {
  300. $('.thumbs [data-stream]:not([data-stream=""])').each(function() {
  301. if($(this).attr('data-stream') !== $('#self-view').attr('data-stream')) {
  302. self.activateParty($(this).attr('data-stream'));
  303. return false;
  304. }
  305. });
  306. }
  307. else {
  308. self.hangUp();
  309. }
  310. // turn pro video off
  311. $.post('/api/clientVideoVisit/turnProVideoOff', {}, function(_data) {
  312. console.log(_data);
  313. // stop heart beat
  314. if(self.heartbeatTimer) {
  315. window.clearInterval(self.heartbeatTimer);
  316. self.heartbeatTimer = false;
  317. }
  318. });
  319. });
  320. // Connect to the session
  321. self.otSession.connect(token, function callback(error) {
  322. if (error) {
  323. self.handleOpenTokError(error);
  324. } else {
  325. // If the connection is successful, publish the publisher to the session
  326. self.otSession.publish(publisher, self.handleOpenTokError);
  327. }
  328. });
  329. },
  330. handleOpenTokError: function(e) {
  331. },
  332. getOpenTokSessionId: function(_done) {
  333. var self = this;
  334. $.get('/pro/get-opentok-session-key/' + self.clientUid, function(_data) {
  335. self.otSessionId = _data.data;
  336. console.log(_data);
  337. _done();
  338. }, 'json');
  339. },
  340. joinMeetingAsPro: function(_type) {
  341. var self = this;
  342. $.ajax({
  343. type: 'post',
  344. url: '/api/clientVideoVisit/joinVideoVisitAsPro',
  345. headers: {
  346. 'sessionKey': '{{ request()->cookie('sessionKey') }}'
  347. },
  348. data: {uid: self.clientUid},
  349. dataType: 'json'
  350. })
  351. .done(function (_data) {
  352. console.log(_data);
  353. })
  354. .fail(function (_data) {
  355. console.warn(_data);
  356. alert(_data.message);
  357. });
  358. },
  359. activateParty: function(_stream = 'self') {
  360. var current = $('.full-view');
  361. if(current.attr('data-stream') === _stream) return;
  362. current.removeClass('full-view').addClass('thumb-view');
  363. if(current.attr('data-type') === 'CLIENT') {
  364. current.prependTo('.thumbs');
  365. }
  366. else {
  367. current.appendTo('.thumbs');
  368. }
  369. if(_stream === 'self') {
  370. $('#self-view')
  371. .removeClass('thumb-view')
  372. .removeClass('disconnected-view')
  373. .addClass('full-view')
  374. .prependTo('.main-view');
  375. }
  376. else {
  377. $('div[data-stream="' + _stream + '"]')
  378. .removeClass('thumb-view')
  379. .removeClass('disconnected-view')
  380. .addClass('full-view')
  381. .prependTo('.main-view');
  382. }
  383. }
  384. },
  385. mounted: function() {
  386. var self = this;
  387. $(document).on('click', '.thumbs>div[data-stream]', function() {
  388. self.activateParty($(this).attr('data-stream'));
  389. return false;
  390. });
  391. // poll for new patients and alert
  392. window.setInterval(function() {
  393. self.pollForNextPatient();
  394. }, 5000);
  395. window.onbeforeunload = function() {
  396. if(self.started) {
  397. return "A call is in progress";
  398. }
  399. };
  400. @if(isset($client))
  401. self.client = true;
  402. self.clientUid = '{{ $client->uid }}';
  403. self.videoActive = true;
  404. self.startOpenTokSession();
  405. @endif
  406. }
  407. });
  408. </script>
  409. @endsection