pro-call.blade.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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="py-3 text-center" v-if="noOneElseInCall">
  24. <h6 class="text-black font-weight-bold m-0">No other participants in the call.
  25. <a href="#" class="text-danger font-weight-bold" v-on:click.prevent="hangUp()">Hang up</a>
  26. </h6>
  27. </div>
  28. <div class="main-view mx-auto">
  29. <div id="self-view" class="full-view" data-name="{{ $pro->name_display }}" data-type="PRO"></div>
  30. <div class="thumbs">
  31. </div>
  32. <button class="btn btn-danger rounded-circle hang-up"
  33. v-if="started"
  34. title="Leave Call"
  35. v-on:click.prevent="hangUp()">
  36. <i class="fa fa-phone"></i>
  37. </button>
  38. </div>
  39. </div>
  40. </div>
  41. <script>
  42. new Vue({
  43. el: '#proCallComponent',
  44. delimiters: ['@{{', '}}'],
  45. data: {
  46. time: 0,
  47. startTime: 0,
  48. started: false,
  49. client: false,
  50. pro: false,
  51. selfName: '',
  52. selfToken: '',
  53. clientUid: '',
  54. otSessionId: '',
  55. checkingForNextPatient: false,
  56. noNextPatient: false,
  57. otSession: false,
  58. selfUserType: 'PRO',
  59. selfStreamId: '',
  60. noOneElseInCall: true,
  61. patientInQueue: false,
  62. videoActive: false,
  63. heartbeatTimer: false,
  64. },
  65. methods: {
  66. pollForNextPatient: function() {
  67. if(!this.started) {
  68. this.nextPatient(true);
  69. }
  70. },
  71. nextPatient: function(_pollOnly = false) {
  72. var self = this;
  73. if(!_pollOnly) this.checkingForNextPatient = true;
  74. $.post('/api/client/getNextClientForVideoVisit', {}, function(_data) {
  75. if(_pollOnly) {
  76. self.patientInQueue = _data.success;
  77. }
  78. else {
  79. self.checkingForNextPatient = false;
  80. if(!_data.success) {
  81. self.noNextPatient = _data.message;
  82. window.setTimeout(function() {
  83. self.noNextPatient = false;
  84. }, 2000);
  85. }
  86. else {
  87. // get ot session key from client record
  88. self.client = true;
  89. self.clientUid = _data.data;
  90. self.videoActive = true;
  91. self.startOpenTokSession();
  92. }
  93. }
  94. }, 'json');
  95. },
  96. startOpenTokSession: function() {
  97. var self = this;
  98. self.getOpenTokSessionId(function() {
  99. self.selfName = '{{ $pro->name_display }}';
  100. $.post('/api/openTok/getClientToken', {
  101. opentokSessionId: self.otSessionId,
  102. data: JSON.stringify({
  103. uid: '{{ $pro->uid }}',
  104. name: self.selfName,
  105. type: 'PRO'
  106. })
  107. }, function (_data) {
  108. console.log(_data);
  109. self.selfToken = _data.data;
  110. self.initOpenTok();
  111. });
  112. });
  113. },
  114. timeDisplay: function() {
  115. var seconds = this.time / 1000,
  116. minutes = parseInt(seconds / 60, 10);
  117. seconds = parseInt(seconds % 60, 10);
  118. return minutes + " min, " + seconds + " sec";
  119. },
  120. hangUp: function() {
  121. if(this.otSession) {
  122. try {
  123. this.otSession.disconnect();
  124. }
  125. catch (e) {
  126. console.log('Was already disconnected.');
  127. }
  128. this.otSession = false;
  129. this.otSessionId = '';
  130. this.started = false;
  131. this.startTime = false;
  132. this.videoActive = false;
  133. // this.client = false;
  134. // call leaveVideoVisitAsPro
  135. $.post('/api/clientVideoVisit/leaveVideoVisitAsPro', {}, function(_data) {
  136. console.log(_data);
  137. });
  138. }
  139. },
  140. initOpenTok: function() {
  141. /* fake video feed (temp) */
  142. const randomColour = () => {
  143. return Math.round(Math.random() * 255);
  144. };
  145. const canvas = document.createElement('canvas');
  146. canvas.width = 640;
  147. canvas.height = 480;
  148. const ctx = canvas.getContext('2d');
  149. var pos = 100;
  150. window.setInterval(function() {
  151. ctx.clearRect(0, 0, canvas.width, canvas.height);
  152. ctx.font = "20px Georgia";
  153. ctx.fillStyle = `rgb(220, 220, 220)`;
  154. ctx.fillText("Video feed from {{ $pro->name_display }}", 20, pos);
  155. pos += 5;
  156. if(pos > canvas.height) pos = 100;
  157. }, 1000);
  158. var self = this;
  159. var apiKey = '<?= config('stag.tokboxApiKey') ?>';
  160. var sessionId = this.otSessionId;
  161. var token = this.selfToken;
  162. self.otSession = OT.initSession(apiKey, sessionId);
  163. // peer connected
  164. self.otSession.on('streamCreated', function streamCreated(event) {
  165. console.log('streamCreated', arguments);
  166. var subscriberOptions = {
  167. insertMode: 'append',
  168. width: '100%',
  169. height: '100%'
  170. };
  171. var connectionData = JSON.parse(event.stream.connection.data);
  172. // add a div for remove view
  173. var remoteViewID = 'remote-view-' + event.stream.id;
  174. var remoteElem = $('<div id="' + remoteViewID + '" class="remote-view thumb-view" ' +
  175. 'data-stream="' + event.stream.id + '" ' +
  176. 'data-connection-data="' + event.stream.connection.data + '" ' +
  177. 'data-name="' + connectionData.name + '" ' +
  178. 'data-type="' + connectionData.type + '"></div>');
  179. remoteElem.appendTo('.thumbs');
  180. self.otSession.subscribe(event.stream, remoteViewID, subscriberOptions, self.handleOpenTokError);
  181. if (connectionData.type === 'CLIENT') {
  182. self.client = true;
  183. }
  184. if(!self.startTime) {
  185. self.startTime = new Date().getTime();
  186. window.setInterval(function() {
  187. self.time = new Date().getTime() - self.startTime;
  188. }, 1000);
  189. self.started = true;
  190. }
  191. self.activateParty(event.stream.id);
  192. self.noOneElseInCall = false;
  193. });
  194. // peer disconnected
  195. self.otSession.on("streamDestroyed", function(event) {
  196. onPeerDisconnection(event, event.stream.connection.data);
  197. });
  198. // self.otSession.on("connectionDestroyed", function(event) {
  199. // debugger;
  200. // console.log('connectionDestroyed from ' + event.connection.data);
  201. // onPeerDisconnection(event, event.connection.data);
  202. // });
  203. self.otSession.on("connectionCreated", function(event) {
  204. console.log('connectionCreated');
  205. console.log(event);
  206. });
  207. function onPeerDisconnection(event, data) {
  208. if(event.stream && $('.full-view[data-stream="' + event.stream.id + '"]').length) {
  209. var allThumbs = $('.thumbs [data-stream]:not([data-stream=""]):not(.disconnected-view):visible');
  210. if(allThumbs.length) {
  211. $('.thumbs [data-stream]:not([data-stream=""])').each(function() {
  212. if($(this).attr('data-stream') !== event.stream.id) {
  213. self.activateParty($(this).attr('data-stream'));
  214. return false;
  215. }
  216. });
  217. }
  218. else {
  219. self.noOneElseInCall = true;
  220. }
  221. }
  222. if(event.stream) {
  223. var remoteViewElem = $('[data-stream="' + event.stream.id + '"]');
  224. remoteViewElem.remove();
  225. // if(remoteViewElem.length) {
  226. // remoteViewElem.attr('data-stream', '');
  227. // remoteViewElem.attr('data-connection-data', '');
  228. // remoteViewElem.attr('data-type', '');
  229. // remoteViewElem.attr('data-name', '');
  230. // }
  231. // remoteViewElem.addClass('disconnected-view')
  232. }
  233. var connectionData = JSON.parse(data);
  234. if(connectionData.type === 'CLIENT') {
  235. self.client = false;
  236. }
  237. // if no other parties in call, hang up
  238. if(!$('[data-stream]:not([data-stream="' + self.selfStreamId + '"])').length) {
  239. self.startTime = 0;
  240. self.started = false;
  241. self.noOneElseInCall = true;
  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.startTime = 0;
  309. self.started = false;
  310. self.noOneElseInCall = true;
  311. }
  312. // turn pro video off
  313. $.post('/api/clientVideoVisit/turnProVideoOff', {}, function(_data) {
  314. console.log(_data);
  315. // stop heart beat
  316. if(self.heartbeatTimer) {
  317. window.clearInterval(self.heartbeatTimer);
  318. self.heartbeatTimer = false;
  319. }
  320. });
  321. });
  322. // Connect to the session
  323. self.otSession.connect(token, function callback(error) {
  324. if (error) {
  325. self.handleOpenTokError(error);
  326. } else {
  327. // If the connection is successful, publish the publisher to the session
  328. self.otSession.publish(publisher, self.handleOpenTokError);
  329. }
  330. });
  331. },
  332. handleOpenTokError: function(e) {
  333. },
  334. getOpenTokSessionId: function(_done) {
  335. var self = this;
  336. $.get('/pro/get-opentok-session-key/' + self.clientUid, function(_data) {
  337. self.otSessionId = _data.data;
  338. console.log(_data);
  339. _done();
  340. }, 'json');
  341. },
  342. joinMeetingAsPro: function(_type) {
  343. var self = this;
  344. $.ajax({
  345. type: 'post',
  346. url: '/api/clientVideoVisit/joinVideoVisitAsPro',
  347. headers: {
  348. 'sessionKey': '{{ request()->cookie('sessionKey') }}'
  349. },
  350. data: {uid: self.clientUid},
  351. dataType: 'json'
  352. })
  353. .done(function (_data) {
  354. console.log(_data);
  355. })
  356. .fail(function (_data) {
  357. console.warn(_data);
  358. alert(_data.message);
  359. });
  360. },
  361. activateParty: function(_stream = 'self') {
  362. var current = $('.full-view');
  363. if(current.attr('data-stream') === _stream) return;
  364. current.removeClass('full-view').addClass('thumb-view');
  365. if(current.attr('data-type') === 'CLIENT') {
  366. current.prependTo('.thumbs');
  367. }
  368. else {
  369. current.appendTo('.thumbs');
  370. }
  371. if(_stream === 'self') {
  372. $('#self-view')
  373. .removeClass('thumb-view')
  374. .removeClass('disconnected-view')
  375. .addClass('full-view')
  376. .prependTo('.main-view');
  377. }
  378. else {
  379. $('div[data-stream="' + _stream + '"]')
  380. .removeClass('thumb-view')
  381. .removeClass('disconnected-view')
  382. .addClass('full-view')
  383. .prependTo('.main-view');
  384. }
  385. }
  386. },
  387. mounted: function() {
  388. var self = this;
  389. $(document).on('click', '.thumbs>div[data-stream]', function() {
  390. self.activateParty($(this).attr('data-stream'));
  391. return false;
  392. });
  393. // poll for new patients and alert
  394. window.setInterval(function() {
  395. self.pollForNextPatient();
  396. }, 5000);
  397. window.onbeforeunload = function() {
  398. if(self.started) {
  399. return "A call is in progress";
  400. }
  401. };
  402. @if(isset($client))
  403. self.client = true;
  404. self.clientUid = '{{ $client->uid }}';
  405. self.videoActive = true;
  406. self.startOpenTokSession();
  407. @endif
  408. }
  409. });
  410. </script>
  411. @endsection