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.

app.js 47KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  1. /* jshint -W117 */
  2. /* application specific logic */
  3. var connection = null;
  4. var authenticatedUser = false;
  5. var focus = null;
  6. var activecall = null;
  7. var RTC = null;
  8. var nickname = null;
  9. var sharedKey = '';
  10. var recordingToken ='';
  11. var roomUrl = null;
  12. var roomName = null;
  13. var ssrc2jid = {};
  14. var mediaStreams = [];
  15. /**
  16. * The stats collector that process stats data and triggers updates to app.js.
  17. * @type {StatsCollector}
  18. */
  19. var statsCollector = null;
  20. /**
  21. * The stats collector for the local stream.
  22. * @type {LocalStatsCollector}
  23. */
  24. var localStatsCollector = null;
  25. /**
  26. * Indicates whether ssrc is camera video or desktop stream.
  27. * FIXME: remove those maps
  28. */
  29. var ssrc2videoType = {};
  30. var videoSrcToSsrc = {};
  31. /**
  32. * Currently focused video "src"(displayed in large video).
  33. * @type {String}
  34. */
  35. var focusedVideoSrc = null;
  36. var mutedAudios = {};
  37. var localVideoSrc = null;
  38. var flipXLocalVideo = true;
  39. var isFullScreen = false;
  40. var toolbarTimeout = null;
  41. var currentVideoWidth = null;
  42. var currentVideoHeight = null;
  43. /**
  44. * Method used to calculate large video size.
  45. * @type {function ()}
  46. */
  47. var getVideoSize;
  48. /**
  49. * Method used to get large video position.
  50. * @type {function ()}
  51. */
  52. var getVideoPosition;
  53. /* window.onbeforeunload = closePageWarning; */
  54. var sessionTerminated = false;
  55. function init() {
  56. RTC = setupRTC();
  57. if (RTC === null) {
  58. window.location.href = 'webrtcrequired.html';
  59. return;
  60. } else if (RTC.browser !== 'chrome') {
  61. window.location.href = 'chromeonly.html';
  62. return;
  63. }
  64. obtainAudioAndVideoPermissions(function (stream) {
  65. var audioStream = new webkitMediaStream();
  66. var videoStream = new webkitMediaStream();
  67. var audioTracks = stream.getAudioTracks();
  68. var videoTracks = stream.getVideoTracks();
  69. for (var i = 0; i < audioTracks.length; i++) {
  70. audioStream.addTrack(audioTracks[i]);
  71. }
  72. VideoLayout.changeLocalAudio(audioStream);
  73. startLocalRtpStatsCollector(audioStream);
  74. for (i = 0; i < videoTracks.length; i++) {
  75. videoStream.addTrack(videoTracks[i]);
  76. }
  77. VideoLayout.changeLocalVideo(videoStream, true);
  78. maybeDoJoin();
  79. });
  80. var jid = document.getElementById('jid').value || config.hosts.anonymousdomain || config.hosts.domain || window.location.hostname;
  81. connect(jid);
  82. }
  83. function connect(jid, password) {
  84. var localAudio, localVideo;
  85. if (connection && connection.jingle) {
  86. localAudio = connection.jingle.localAudio;
  87. localVideo = connection.jingle.localVideo;
  88. }
  89. connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');
  90. if (nickname) {
  91. connection.emuc.addDisplayNameToPresence(nickname);
  92. }
  93. if (connection.disco) {
  94. // for chrome, add multistream cap
  95. }
  96. connection.jingle.pc_constraints = RTC.pc_constraints;
  97. if (config.useIPv6) {
  98. // https://code.google.com/p/webrtc/issues/detail?id=2828
  99. if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];
  100. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  101. }
  102. if (localAudio) connection.jingle.localAudio = localAudio;
  103. if (localVideo) connection.jingle.localVideo = localVideo;
  104. if(!password)
  105. password = document.getElementById('password').value;
  106. var anonymousConnectionFailed = false;
  107. connection.connect(jid, password, function (status, msg) {
  108. if (status === Strophe.Status.CONNECTED) {
  109. console.log('connected');
  110. if (config.useStunTurn) {
  111. connection.jingle.getStunAndTurnCredentials();
  112. }
  113. document.getElementById('connect').disabled = true;
  114. if(password)
  115. authenticatedUser = true;
  116. maybeDoJoin();
  117. } else if (status === Strophe.Status.CONNFAIL) {
  118. if(msg === 'x-strophe-bad-non-anon-jid') {
  119. anonymousConnectionFailed = true;
  120. }
  121. console.log('status', status);
  122. } else if (status === Strophe.Status.DISCONNECTED) {
  123. if(anonymousConnectionFailed) {
  124. // prompt user for username and password
  125. $(document).trigger('passwordrequired.main');
  126. }
  127. } else if (status === Strophe.Status.AUTHFAIL) {
  128. // wrong password or username, prompt user
  129. $(document).trigger('passwordrequired.main');
  130. } else {
  131. console.log('status', status);
  132. }
  133. });
  134. }
  135. /**
  136. * We ask for audio and video combined stream in order to get permissions and
  137. * not to ask twice.
  138. */
  139. function obtainAudioAndVideoPermissions(callback) {
  140. // Get AV
  141. getUserMediaWithConstraints(
  142. ['audio', 'video'],
  143. function (avStream) {
  144. callback(avStream);
  145. trackUsage('localMedia', {
  146. audio: avStream.getAudioTracks().length,
  147. video: avStream.getVideoTracks().length
  148. });
  149. },
  150. function (error) {
  151. console.error('failed to obtain audio/video stream - stop', error);
  152. trackUsage('localMediaError', {
  153. media: error.media || 'video',
  154. name : error.name
  155. });
  156. },
  157. config.resolution || '360');
  158. }
  159. function maybeDoJoin() {
  160. if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?
  161. && (connection.jingle.localAudio || connection.jingle.localVideo)) {
  162. doJoin();
  163. }
  164. }
  165. function doJoin() {
  166. var roomnode = null;
  167. var path = window.location.pathname;
  168. var roomjid;
  169. // determinde the room node from the url
  170. // TODO: just the roomnode or the whole bare jid?
  171. if (config.getroomnode && typeof config.getroomnode === 'function') {
  172. // custom function might be responsible for doing the pushstate
  173. roomnode = config.getroomnode(path);
  174. } else {
  175. /* fall back to default strategy
  176. * this is making assumptions about how the URL->room mapping happens.
  177. * It currently assumes deployment at root, with a rewrite like the
  178. * following one (for nginx):
  179. location ~ ^/([a-zA-Z0-9]+)$ {
  180. rewrite ^/(.*)$ / break;
  181. }
  182. */
  183. if (path.length > 1) {
  184. roomnode = path.substr(1).toLowerCase();
  185. } else {
  186. var word = RoomNameGenerator.generateRoomWithoutSeparator(3);
  187. roomnode = word.toLowerCase();
  188. window.history.pushState('VideoChat',
  189. 'Room: ' + word, window.location.pathname + word);
  190. }
  191. }
  192. roomName = roomnode + '@' + config.hosts.muc;
  193. roomjid = roomName;
  194. if (config.useNicks) {
  195. var nick = window.prompt('Your nickname (optional)');
  196. if (nick) {
  197. roomjid += '/' + nick;
  198. } else {
  199. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  200. }
  201. } else {
  202. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  203. if(!authenticatedUser)
  204. tmpJid = tmpJid.substr(0, 8);
  205. roomjid += '/' + tmpJid;
  206. }
  207. connection.emuc.doJoin(roomjid);
  208. }
  209. function waitForRemoteVideo(selector, ssrc, stream) {
  210. if (selector.removed || !selector.parent().is(":visible")) {
  211. console.warn("Media removed before had started", selector);
  212. return;
  213. }
  214. if (stream.id === 'mixedmslabel') return;
  215. if (selector[0].currentTime > 0) {
  216. var simulcast = new Simulcast();
  217. var videoStream = simulcast.getReceivingVideoStream(stream);
  218. RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  219. // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type
  220. // in order to get rid of too many maps
  221. if (ssrc && selector.attr('src')) {
  222. videoSrcToSsrc[selector.attr('src')] = ssrc;
  223. } else {
  224. console.warn("No ssrc given for video", selector);
  225. }
  226. $(document).trigger('videoactive.jingle', [selector]);
  227. } else {
  228. setTimeout(function () {
  229. waitForRemoteVideo(selector, ssrc, stream);
  230. }, 250);
  231. }
  232. }
  233. $(document).bind('remotestreamadded.jingle', function (event, data, sid) {
  234. waitForPresence(data, sid);
  235. });
  236. function waitForPresence(data, sid) {
  237. var sess = connection.jingle.sessions[sid];
  238. var thessrc;
  239. // look up an associated JID for a stream id
  240. if (data.stream.id.indexOf('mixedmslabel') === -1) {
  241. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  242. var ssrclines
  243. = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  244. ssrclines = ssrclines.filter(function (line) {
  245. // NOTE(gp) previously we filtered on the mslabel, but that property
  246. // is not always present.
  247. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  248. return line.indexOf('msid:' + data.stream.id) !== -1;
  249. });
  250. if (ssrclines.length) {
  251. thessrc = ssrclines[0].substring(7).split(' ')[0];
  252. // We signal our streams (through Jingle to the focus) before we set
  253. // our presence (through which peers associate remote streams to
  254. // jids). So, it might arrive that a remote stream is added but
  255. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  256. // successfully set. Here we wait for up to a second for the
  257. // presence to arrive.
  258. if (!ssrc2jid[thessrc]) {
  259. // TODO(gp) limit wait duration to 1 sec.
  260. setTimeout(function(d, s) {
  261. return function() {
  262. waitForPresence(d, s);
  263. }
  264. }(data, sid), 250);
  265. return;
  266. }
  267. // ok to overwrite the one from focus? might save work in colibri.js
  268. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  269. if (ssrc2jid[thessrc]) {
  270. data.peerjid = ssrc2jid[thessrc];
  271. }
  272. }
  273. }
  274. // NOTE(gp) now that we have simulcast, a media stream can have more than 1
  275. // ssrc. We should probably take that into account in our MediaStream
  276. // wrapper.
  277. mediaStreams.push(new MediaStream(data, sid, thessrc));
  278. var container;
  279. var remotes = document.getElementById('remoteVideos');
  280. if (data.peerjid) {
  281. VideoLayout.ensurePeerContainerExists(data.peerjid);
  282. container = document.getElementById(
  283. 'participant_' + Strophe.getResourceFromJid(data.peerjid));
  284. } else {
  285. if (data.stream.id !== 'mixedmslabel') {
  286. console.error( 'can not associate stream',
  287. data.stream.id,
  288. 'with a participant');
  289. // We don't want to add it here since it will cause troubles
  290. return;
  291. }
  292. // FIXME: for the mixed ms we dont need a video -- currently
  293. container = document.createElement('span');
  294. container.id = 'mixedstream';
  295. container.className = 'videocontainer';
  296. remotes.appendChild(container);
  297. Util.playSoundNotification('userJoined');
  298. }
  299. var isVideo = data.stream.getVideoTracks().length > 0;
  300. if (container) {
  301. VideoLayout.addRemoteStreamElement( container,
  302. sid,
  303. data.stream,
  304. data.peerjid,
  305. thessrc);
  306. }
  307. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  308. if (isVideo &&
  309. data.peerjid && sess.peerjid === data.peerjid &&
  310. data.stream.getVideoTracks().length === 0 &&
  311. connection.jingle.localVideo.getVideoTracks().length > 0) {
  312. //
  313. window.setTimeout(function () {
  314. sendKeyframe(sess.peerconnection);
  315. }, 3000);
  316. }
  317. }
  318. /**
  319. * Returns the JID of the user to whom given <tt>videoSrc</tt> belongs.
  320. * @param videoSrc the video "src" identifier.
  321. * @returns {null | String} the JID of the user to whom given <tt>videoSrc</tt>
  322. * belongs.
  323. */
  324. function getJidFromVideoSrc(videoSrc)
  325. {
  326. if (videoSrc === localVideoSrc)
  327. return connection.emuc.myroomjid;
  328. var ssrc = videoSrcToSsrc[videoSrc];
  329. if (!ssrc)
  330. {
  331. return null;
  332. }
  333. return ssrc2jid[ssrc];
  334. }
  335. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  336. function sendKeyframe(pc) {
  337. console.log('sendkeyframe', pc.iceConnectionState);
  338. if (pc.iceConnectionState !== 'connected') return; // safe...
  339. pc.setRemoteDescription(
  340. pc.remoteDescription,
  341. function () {
  342. pc.createAnswer(
  343. function (modifiedAnswer) {
  344. pc.setLocalDescription(
  345. modifiedAnswer,
  346. function () {
  347. // noop
  348. },
  349. function (error) {
  350. console.log('triggerKeyframe setLocalDescription failed', error);
  351. }
  352. );
  353. },
  354. function (error) {
  355. console.log('triggerKeyframe createAnswer failed', error);
  356. }
  357. );
  358. },
  359. function (error) {
  360. console.log('triggerKeyframe setRemoteDescription failed', error);
  361. }
  362. );
  363. }
  364. // Really mute video, i.e. dont even send black frames
  365. function muteVideo(pc, unmute) {
  366. // FIXME: this probably needs another of those lovely state safeguards...
  367. // which checks for iceconn == connected and sigstate == stable
  368. pc.setRemoteDescription(pc.remoteDescription,
  369. function () {
  370. pc.createAnswer(
  371. function (answer) {
  372. var sdp = new SDP(answer.sdp);
  373. if (sdp.media.length > 1) {
  374. if (unmute)
  375. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  376. else
  377. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  378. sdp.raw = sdp.session + sdp.media.join('');
  379. answer.sdp = sdp.raw;
  380. }
  381. pc.setLocalDescription(answer,
  382. function () {
  383. console.log('mute SLD ok');
  384. },
  385. function (error) {
  386. console.log('mute SLD error');
  387. }
  388. );
  389. },
  390. function (error) {
  391. console.log(error);
  392. }
  393. );
  394. },
  395. function (error) {
  396. console.log('muteVideo SRD error');
  397. }
  398. );
  399. }
  400. /**
  401. * Callback for audio levels changed.
  402. * @param jid JID of the user
  403. * @param audioLevel the audio level value
  404. */
  405. function audioLevelUpdated(jid, audioLevel)
  406. {
  407. var resourceJid;
  408. if(jid === LocalStatsCollector.LOCAL_JID)
  409. {
  410. resourceJid = AudioLevels.LOCAL_LEVEL;
  411. if(isAudioMuted())
  412. return;
  413. }
  414. else
  415. {
  416. resourceJid = Strophe.getResourceFromJid(jid);
  417. }
  418. AudioLevels.updateAudioLevel(resourceJid, audioLevel);
  419. }
  420. /**
  421. * Starts the {@link StatsCollector} if the feature is enabled in config.js.
  422. */
  423. function startRtpStatsCollector()
  424. {
  425. stopRTPStatsCollector();
  426. if (config.enableRtpStats)
  427. {
  428. statsCollector = new StatsCollector(
  429. getConferenceHandler().peerconnection, 200, audioLevelUpdated);
  430. statsCollector.start();
  431. }
  432. }
  433. /**
  434. * Stops the {@link StatsCollector}.
  435. */
  436. function stopRTPStatsCollector()
  437. {
  438. if (statsCollector)
  439. {
  440. statsCollector.stop();
  441. statsCollector = null;
  442. }
  443. }
  444. /**
  445. * Starts the {@link LocalStatsCollector} if the feature is enabled in config.js
  446. * @param stream the stream that will be used for collecting statistics.
  447. */
  448. function startLocalRtpStatsCollector(stream)
  449. {
  450. if(config.enableRtpStats)
  451. {
  452. localStatsCollector = new LocalStatsCollector(stream, 100, audioLevelUpdated);
  453. localStatsCollector.start();
  454. }
  455. }
  456. /**
  457. * Stops the {@link LocalStatsCollector}.
  458. */
  459. function stopLocalRtpStatsCollector()
  460. {
  461. if(localStatsCollector)
  462. {
  463. localStatsCollector.stop();
  464. localStatsCollector = null;
  465. }
  466. }
  467. $(document).bind('callincoming.jingle', function (event, sid) {
  468. var sess = connection.jingle.sessions[sid];
  469. // TODO: do we check activecall == null?
  470. activecall = sess;
  471. startRtpStatsCollector();
  472. // Bind data channel listener in case we're a regular participant
  473. if (config.openSctp)
  474. {
  475. bindDataChannelListener(sess.peerconnection);
  476. }
  477. // TODO: check affiliation and/or role
  478. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  479. sess.usedrip = true; // not-so-naive trickle ice
  480. sess.sendAnswer();
  481. sess.accept();
  482. });
  483. $(document).bind('conferenceCreated.jingle', function (event, focus)
  484. {
  485. startRtpStatsCollector();
  486. });
  487. $(document).bind('conferenceCreated.jingle', function (event, focus)
  488. {
  489. // Bind data channel listener in case we're the focus
  490. if (config.openSctp)
  491. {
  492. bindDataChannelListener(focus.peerconnection);
  493. }
  494. });
  495. $(document).bind('callterminated.jingle', function (event, sid, jid, reason) {
  496. // Leave the room if my call has been remotely terminated.
  497. if (connection.emuc.joined && focus == null && reason === 'kick') {
  498. sessionTerminated = true;
  499. connection.emuc.doLeave();
  500. openMessageDialog( "Session Terminated",
  501. "Ouch! You have been kicked out of the meet!");
  502. }
  503. });
  504. $(document).bind('setLocalDescription.jingle', function (event, sid) {
  505. // put our ssrcs into presence so other clients can identify our stream
  506. var sess = connection.jingle.sessions[sid];
  507. var newssrcs = [];
  508. var simulcast = new Simulcast();
  509. var media = simulcast.parseMedia(sess.peerconnection.localDescription);
  510. media.forEach(function (media) {
  511. // TODO(gp) maybe exclude FID streams?
  512. Object.keys(media.sources).forEach(function(ssrc) {
  513. newssrcs.push({
  514. 'ssrc': ssrc,
  515. 'type': media.type,
  516. 'direction': media.direction
  517. });
  518. });
  519. });
  520. console.log('new ssrcs', newssrcs);
  521. // Have to clear presence map to get rid of removed streams
  522. connection.emuc.clearPresenceMedia();
  523. if (newssrcs.length > 0) {
  524. for (var i = 1; i <= newssrcs.length; i ++) {
  525. // Change video type to screen
  526. if (newssrcs[i-1].type === 'video' && isUsingScreenStream) {
  527. newssrcs[i-1].type = 'screen';
  528. }
  529. connection.emuc.addMediaToPresence(i,
  530. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  531. }
  532. connection.emuc.sendPresence();
  533. }
  534. });
  535. $(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {
  536. switch (session.peerconnection.iceConnectionState) {
  537. case 'checking':
  538. session.timeChecking = (new Date()).getTime();
  539. session.firstconnect = true;
  540. break;
  541. case 'completed': // on caller side
  542. case 'connected':
  543. if (session.firstconnect) {
  544. session.firstconnect = false;
  545. var metadata = {};
  546. metadata.setupTime = (new Date()).getTime() - session.timeChecking;
  547. session.peerconnection.getStats(function (res) {
  548. res.result().forEach(function (report) {
  549. if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {
  550. metadata.localCandidateType = report.stat('googLocalCandidateType');
  551. metadata.remoteCandidateType = report.stat('googRemoteCandidateType');
  552. // log pair as well so we can get nice pie charts
  553. metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');
  554. if (report.stat('googRemoteAddress').indexOf('[') === 0) {
  555. metadata.ipv6 = true;
  556. }
  557. }
  558. });
  559. trackUsage('iceConnected', metadata);
  560. });
  561. }
  562. break;
  563. }
  564. });
  565. $(document).bind('joined.muc', function (event, jid, info) {
  566. updateRoomUrl(window.location.href);
  567. document.getElementById('localNick').appendChild(
  568. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  569. );
  570. if (Object.keys(connection.emuc.members).length < 1) {
  571. focus = new ColibriFocus(connection, config.hosts.bridge);
  572. if (nickname !== null) {
  573. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  574. nickname);
  575. }
  576. Toolbar.showSipCallButton(true);
  577. Toolbar.showRecordingButton(false);
  578. }
  579. if (!focus)
  580. {
  581. Toolbar.showSipCallButton(false);
  582. }
  583. if (focus && config.etherpad_base) {
  584. Etherpad.init();
  585. }
  586. VideoLayout.showFocusIndicator();
  587. // Add myself to the contact list.
  588. ContactList.addContact(jid);
  589. // Once we've joined the muc show the toolbar
  590. ToolbarToggler.showToolbar();
  591. if (info.displayName)
  592. $(document).trigger('displaynamechanged',
  593. ['localVideoContainer', info.displayName + ' (me)']);
  594. });
  595. $(document).bind('entered.muc', function (event, jid, info, pres) {
  596. console.log('entered', jid, info);
  597. console.log('is focus? ' + (focus ? 'true' : 'false'));
  598. // Add Peer's container
  599. VideoLayout.ensurePeerContainerExists(jid);
  600. if (focus !== null) {
  601. // FIXME: this should prepare the video
  602. if (focus.confid === null) {
  603. console.log('make new conference with', jid);
  604. focus.makeConference(Object.keys(connection.emuc.members));
  605. Toolbar.showRecordingButton(true);
  606. } else {
  607. console.log('invite', jid, 'into conference');
  608. focus.addNewParticipant(jid);
  609. }
  610. }
  611. else if (sharedKey) {
  612. Toolbar.updateLockButton();
  613. }
  614. });
  615. $(document).bind('left.muc', function (event, jid) {
  616. console.log('left.muc', jid);
  617. // Need to call this with a slight delay, otherwise the element couldn't be
  618. // found for some reason.
  619. window.setTimeout(function () {
  620. var container = document.getElementById(
  621. 'participant_' + Strophe.getResourceFromJid(jid));
  622. if (container) {
  623. // hide here, wait for video to close before removing
  624. $(container).hide();
  625. VideoLayout.resizeThumbnails();
  626. }
  627. }, 10);
  628. // Unlock large video
  629. if (focusedVideoSrc)
  630. {
  631. if (getJidFromVideoSrc(focusedVideoSrc) === jid)
  632. {
  633. console.info("Focused video owner has left the conference");
  634. focusedVideoSrc = null;
  635. }
  636. }
  637. connection.jingle.terminateByJid(jid);
  638. if (focus == null
  639. // I shouldn't be the one that left to enter here.
  640. && jid !== connection.emuc.myroomjid
  641. && connection.emuc.myroomjid === connection.emuc.list_members[0]
  642. // If our session has been terminated for some reason
  643. // (kicked, hangup), don't try to become the focus
  644. && !sessionTerminated) {
  645. console.log('welcome to our new focus... myself');
  646. focus = new ColibriFocus(connection, config.hosts.bridge);
  647. if (nickname !== null) {
  648. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  649. nickname);
  650. }
  651. Toolbar.showSipCallButton(true);
  652. if (Object.keys(connection.emuc.members).length > 0) {
  653. focus.makeConference(Object.keys(connection.emuc.members));
  654. Toolbar.showRecordingButton(true);
  655. }
  656. $(document).trigger('focusechanged.muc', [focus]);
  657. }
  658. else if (focus && Object.keys(connection.emuc.members).length === 0) {
  659. console.log('everyone left');
  660. // FIXME: closing the connection is a hack to avoid some
  661. // problems with reinit
  662. disposeConference();
  663. focus = new ColibriFocus(connection, config.hosts.bridge);
  664. if (nickname !== null) {
  665. focus.setEndpointDisplayName(connection.emuc.myroomjid,
  666. nickname);
  667. }
  668. Toolbar.showSipCallButton(true);
  669. Toolbar.showRecordingButton(false);
  670. }
  671. if (connection.emuc.getPrezi(jid)) {
  672. $(document).trigger('presentationremoved.muc',
  673. [jid, connection.emuc.getPrezi(jid)]);
  674. }
  675. });
  676. $(document).bind('presence.muc', function (event, jid, info, pres) {
  677. // Remove old ssrcs coming from the jid
  678. Object.keys(ssrc2jid).forEach(function (ssrc) {
  679. if (ssrc2jid[ssrc] == jid) {
  680. delete ssrc2jid[ssrc];
  681. }
  682. if (ssrc2videoType[ssrc] == jid) {
  683. delete ssrc2videoType[ssrc];
  684. }
  685. });
  686. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  687. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  688. var ssrcV = ssrc.getAttribute('ssrc');
  689. ssrc2jid[ssrcV] = jid;
  690. var type = ssrc.getAttribute('type');
  691. ssrc2videoType[ssrcV] = type;
  692. // might need to update the direction if participant just went from sendrecv to recvonly
  693. if (type === 'video' || type === 'screen') {
  694. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  695. switch (ssrc.getAttribute('direction')) {
  696. case 'sendrecv':
  697. el.show();
  698. break;
  699. case 'recvonly':
  700. el.hide();
  701. // FIXME: Check if we have to change large video
  702. //VideoLayout.updateLargeVideo(el);
  703. break;
  704. }
  705. }
  706. });
  707. if (info.displayName && info.displayName.length > 0)
  708. $(document).trigger('displaynamechanged',
  709. [jid, info.displayName]);
  710. if (focus !== null && info.displayName !== null) {
  711. focus.setEndpointDisplayName(jid, info.displayName);
  712. }
  713. });
  714. $(document).bind('presence.status.muc', function (event, jid, info, pres) {
  715. VideoLayout.setPresenceStatus(
  716. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  717. });
  718. $(document).bind('passwordrequired.muc', function (event, jid) {
  719. console.log('on password required', jid);
  720. $.prompt('<h2>Password required</h2>' +
  721. '<input id="lockKey" type="text" placeholder="shared key" autofocus>', {
  722. persistent: true,
  723. buttons: { "Ok": true, "Cancel": false},
  724. defaultButton: 1,
  725. loaded: function (event) {
  726. document.getElementById('lockKey').focus();
  727. },
  728. submit: function (e, v, m, f) {
  729. if (v) {
  730. var lockKey = document.getElementById('lockKey');
  731. if (lockKey.value !== null) {
  732. setSharedKey(lockKey.value);
  733. connection.emuc.doJoin(jid, lockKey.value);
  734. }
  735. }
  736. }
  737. });
  738. });
  739. $(document).bind('passwordrequired.main', function (event) {
  740. console.log('password is required');
  741. $.prompt('<h2>Password required</h2>' +
  742. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  743. '<input id="passwordrequired.password" type="password" placeholder="user password">', {
  744. persistent: true,
  745. buttons: { "Ok": true, "Cancel": false},
  746. defaultButton: 1,
  747. loaded: function (event) {
  748. document.getElementById('passwordrequired.username').focus();
  749. },
  750. submit: function (e, v, m, f) {
  751. if (v) {
  752. var username = document.getElementById('passwordrequired.username');
  753. var password = document.getElementById('passwordrequired.password');
  754. if (username.value !== null && password.value != null) {
  755. connect(username.value, password.value);
  756. }
  757. }
  758. }
  759. });
  760. });
  761. /**
  762. * Checks if video identified by given src is desktop stream.
  763. * @param videoSrc eg.
  764. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  765. * @returns {boolean}
  766. */
  767. function isVideoSrcDesktop(videoSrc) {
  768. // FIXME: fix this mapping mess...
  769. // figure out if large video is desktop stream or just a camera
  770. var isDesktop = false;
  771. if (localVideoSrc === videoSrc) {
  772. // local video
  773. isDesktop = isUsingScreenStream;
  774. } else {
  775. // Do we have associations...
  776. var videoSsrc = videoSrcToSsrc[videoSrc];
  777. if (videoSsrc) {
  778. var videoType = ssrc2videoType[videoSsrc];
  779. if (videoType) {
  780. // Finally there...
  781. isDesktop = videoType === 'screen';
  782. } else {
  783. console.error("No video type for ssrc: " + videoSsrc);
  784. }
  785. } else {
  786. console.error("No ssrc for src: " + videoSrc);
  787. }
  788. }
  789. return isDesktop;
  790. }
  791. function getConferenceHandler() {
  792. return focus ? focus : activecall;
  793. }
  794. function toggleVideo() {
  795. buttonClick("#video", "icon-camera icon-camera-disabled");
  796. if (!(connection && connection.jingle.localVideo))
  797. return;
  798. var sess = getConferenceHandler();
  799. if (sess) {
  800. sess.toggleVideoMute(
  801. function (isMuted) {
  802. if (isMuted) {
  803. $('#video').removeClass("icon-camera");
  804. $('#video').addClass("icon-camera icon-camera-disabled");
  805. } else {
  806. $('#video').removeClass("icon-camera icon-camera-disabled");
  807. $('#video').addClass("icon-camera");
  808. }
  809. }
  810. );
  811. }
  812. sess = focus || activecall;
  813. if (!sess) {
  814. return;
  815. }
  816. sess.pendingop = ismuted ? 'unmute' : 'mute';
  817. // connection.emuc.addVideoInfoToPresence(!ismuted);
  818. // connection.emuc.sendPresence();
  819. sess.modifySources();
  820. }
  821. /**
  822. * Mutes / unmutes audio for the local participant.
  823. */
  824. function toggleAudio() {
  825. if (!(connection && connection.jingle.localAudio)) {
  826. preMuted = true;
  827. // We still click the button.
  828. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  829. return;
  830. }
  831. var localAudio = connection.jingle.localAudio;
  832. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  833. var audioEnabled = localAudio.getAudioTracks()[idx].enabled;
  834. localAudio.getAudioTracks()[idx].enabled = !audioEnabled;
  835. // isMuted is the opposite of audioEnabled
  836. connection.emuc.addAudioInfoToPresence(audioEnabled);
  837. connection.emuc.sendPresence();
  838. }
  839. buttonClick("#mute", "icon-microphone icon-mic-disabled");
  840. }
  841. /**
  842. * Checks whether the audio is muted or not.
  843. * @returns {boolean} true if audio is muted and false if not.
  844. */
  845. function isAudioMuted()
  846. {
  847. var localAudio = connection.jingle.localAudio;
  848. for (var idx = 0; idx < localAudio.getAudioTracks().length; idx++) {
  849. if(localAudio.getAudioTracks()[idx].enabled === true)
  850. return false;
  851. }
  852. return true;
  853. }
  854. // Starts or stops the recording for the conference.
  855. function toggleRecording() {
  856. if (focus === null || focus.confid === null) {
  857. console.log('non-focus, or conference not yet organized: not enabling recording');
  858. return;
  859. }
  860. if (!recordingToken)
  861. {
  862. $.prompt('<h2>Enter recording token</h2>' +
  863. '<input id="recordingToken" type="text" placeholder="token" autofocus>',
  864. {
  865. persistent: false,
  866. buttons: { "Save": true, "Cancel": false},
  867. defaultButton: 1,
  868. loaded: function (event) {
  869. document.getElementById('recordingToken').focus();
  870. },
  871. submit: function (e, v, m, f) {
  872. if (v) {
  873. var token = document.getElementById('recordingToken');
  874. if (token.value) {
  875. setRecordingToken(Util.escapeHtml(token.value));
  876. toggleRecording();
  877. }
  878. }
  879. }
  880. }
  881. );
  882. return;
  883. }
  884. var oldState = focus.recordingEnabled;
  885. Toolbar.toggleRecordingButtonState();
  886. focus.setRecording(!oldState,
  887. recordingToken,
  888. function (state) {
  889. console.log("New recording state: ", state);
  890. if (state == oldState) //failed to change, reset the token because it might have been wrong
  891. {
  892. Toolbar.toggleRecordingButtonState();
  893. setRecordingToken(null);
  894. }
  895. }
  896. );
  897. }
  898. /**
  899. * Returns an array of the video horizontal and vertical indents,
  900. * so that if fits its parent.
  901. *
  902. * @return an array with 2 elements, the horizontal indent and the vertical
  903. * indent
  904. */
  905. function getCameraVideoPosition(videoWidth,
  906. videoHeight,
  907. videoSpaceWidth,
  908. videoSpaceHeight) {
  909. // Parent height isn't completely calculated when we position the video in
  910. // full screen mode and this is why we use the screen height in this case.
  911. // Need to think it further at some point and implement it properly.
  912. var isFullScreen = document.fullScreen ||
  913. document.mozFullScreen ||
  914. document.webkitIsFullScreen;
  915. if (isFullScreen)
  916. videoSpaceHeight = window.innerHeight;
  917. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  918. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  919. return [horizontalIndent, verticalIndent];
  920. }
  921. /**
  922. * Returns an array of the video horizontal and vertical indents.
  923. * Centers horizontally and top aligns vertically.
  924. *
  925. * @return an array with 2 elements, the horizontal indent and the vertical
  926. * indent
  927. */
  928. function getDesktopVideoPosition(videoWidth,
  929. videoHeight,
  930. videoSpaceWidth,
  931. videoSpaceHeight) {
  932. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  933. var verticalIndent = 0;// Top aligned
  934. return [horizontalIndent, verticalIndent];
  935. }
  936. /**
  937. * Returns an array of the video dimensions, so that it covers the screen.
  938. * It leaves no empty areas, but some parts of the video might not be visible.
  939. *
  940. * @return an array with 2 elements, the video width and the video height
  941. */
  942. function getCameraVideoSize(videoWidth,
  943. videoHeight,
  944. videoSpaceWidth,
  945. videoSpaceHeight) {
  946. if (!videoWidth)
  947. videoWidth = currentVideoWidth;
  948. if (!videoHeight)
  949. videoHeight = currentVideoHeight;
  950. var aspectRatio = videoWidth / videoHeight;
  951. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  952. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  953. if (availableWidth / aspectRatio < videoSpaceHeight) {
  954. availableHeight = videoSpaceHeight;
  955. availableWidth = availableHeight * aspectRatio;
  956. }
  957. if (availableHeight * aspectRatio < videoSpaceWidth) {
  958. availableWidth = videoSpaceWidth;
  959. availableHeight = availableWidth / aspectRatio;
  960. }
  961. return [availableWidth, availableHeight];
  962. }
  963. $(document).ready(function () {
  964. document.title = brand.appName;
  965. if(config.enableWelcomePage && window.location.pathname == "/" &&
  966. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  967. {
  968. $("#videoconference_page").hide();
  969. $("#domain_name").text(window.location.protocol + "//" + window.location.host + "/");
  970. $("span[name='appName']").text(brand.appName);
  971. function enter_room()
  972. {
  973. var val = $("#enter_room_field").val();
  974. if(!val)
  975. val = $("#enter_room_field").attr("room_name");
  976. window.location.pathname = "/" + val;
  977. }
  978. $("#enter_room_button").click(function()
  979. {
  980. enter_room();
  981. });
  982. $("#enter_room_field").keydown(function (event) {
  983. if (event.keyCode === 13) {
  984. enter_room();
  985. }
  986. });
  987. var updateTimeout;
  988. var animateTimeout;
  989. $("#reload_roomname").click(function () {
  990. clearTimeout(updateTimeout);
  991. clearTimeout(animateTimeout);
  992. update_roomname();
  993. });
  994. function animate(word) {
  995. var currentVal = $("#enter_room_field").attr("placeholder");
  996. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  997. animateTimeout = setTimeout(function() {
  998. animate(word.substring(1, word.length))
  999. }, 70);
  1000. }
  1001. function update_roomname()
  1002. {
  1003. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1004. $("#enter_room_field").attr("room_name", word);
  1005. $("#enter_room_field").attr("placeholder", "");
  1006. animate(word);
  1007. updateTimeout = setTimeout(update_roomname, 10000);
  1008. }
  1009. update_roomname();
  1010. $("#disable_welcome").click(function () {
  1011. window.localStorage.welcomePageDisabled = $("#disable_welcome").is(":checked");
  1012. });
  1013. return;
  1014. }
  1015. $("#welcome_page").hide();
  1016. Chat.init();
  1017. $('body').popover({ selector: '[data-toggle=popover]',
  1018. trigger: 'click hover',
  1019. content: function() {
  1020. return this.getAttribute("content") +
  1021. KeyboardShortcut.getShortcut(this.getAttribute("shortcut"));
  1022. }
  1023. });
  1024. // Set the defaults for prompt dialogs.
  1025. jQuery.prompt.setDefaults({persistent: false});
  1026. // Set default desktop sharing method
  1027. setDesktopSharing(config.desktopSharing);
  1028. // Initialize Chrome extension inline installs
  1029. if (config.chromeExtensionId) {
  1030. initInlineInstalls();
  1031. }
  1032. // By default we use camera
  1033. getVideoSize = getCameraVideoSize;
  1034. getVideoPosition = getCameraVideoPosition;
  1035. VideoLayout.resizeLargeVideoContainer();
  1036. $(window).resize(function () {
  1037. VideoLayout.resizeLargeVideoContainer();
  1038. VideoLayout.positionLarge();
  1039. });
  1040. // Listen for large video size updates
  1041. document.getElementById('largeVideo')
  1042. .addEventListener('loadedmetadata', function (e) {
  1043. currentVideoWidth = this.videoWidth;
  1044. currentVideoHeight = this.videoHeight;
  1045. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  1046. });
  1047. if (!$('#settings').is(':visible')) {
  1048. console.log('init');
  1049. init();
  1050. } else {
  1051. loginInfo.onsubmit = function (e) {
  1052. if (e.preventDefault) e.preventDefault();
  1053. $('#settings').hide();
  1054. init();
  1055. };
  1056. }
  1057. });
  1058. $(window).bind('beforeunload', function () {
  1059. if (connection && connection.connected) {
  1060. // ensure signout
  1061. $.ajax({
  1062. type: 'POST',
  1063. url: config.bosh,
  1064. async: false,
  1065. cache: false,
  1066. contentType: 'application/xml',
  1067. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1068. success: function (data) {
  1069. console.log('signed out');
  1070. console.log(data);
  1071. },
  1072. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1073. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1074. }
  1075. });
  1076. }
  1077. disposeConference(true);
  1078. });
  1079. function disposeConference(onUnload) {
  1080. var handler = getConferenceHandler();
  1081. if (handler && handler.peerconnection) {
  1082. // FIXME: probably removing streams is not required and close() should be enough
  1083. if (connection.jingle.localAudio) {
  1084. handler.peerconnection.removeStream(connection.jingle.localAudio);
  1085. }
  1086. if (connection.jingle.localVideo) {
  1087. handler.peerconnection.removeStream(connection.jingle.localVideo);
  1088. }
  1089. handler.peerconnection.close();
  1090. }
  1091. stopRTPStatsCollector();
  1092. if(onUnload) {
  1093. stopLocalRtpStatsCollector();
  1094. }
  1095. focus = null;
  1096. activecall = null;
  1097. }
  1098. function dump(elem, filename) {
  1099. elem = elem.parentNode;
  1100. elem.download = filename || 'meetlog.json';
  1101. elem.href = 'data:application/json;charset=utf-8,\n';
  1102. var data = {};
  1103. if (connection.jingle) {
  1104. Object.keys(connection.jingle.sessions).forEach(function (sid) {
  1105. var session = connection.jingle.sessions[sid];
  1106. if (session.peerconnection && session.peerconnection.updateLog) {
  1107. // FIXME: should probably be a .dump call
  1108. data["jingle_" + session.sid] = {
  1109. updateLog: session.peerconnection.updateLog,
  1110. stats: session.peerconnection.stats,
  1111. url: window.location.href
  1112. };
  1113. }
  1114. });
  1115. }
  1116. metadata = {};
  1117. metadata.time = new Date();
  1118. metadata.url = window.location.href;
  1119. metadata.ua = navigator.userAgent;
  1120. if (connection.logger) {
  1121. metadata.xmpp = connection.logger.log;
  1122. }
  1123. data.metadata = metadata;
  1124. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1125. return false;
  1126. }
  1127. /**
  1128. * Changes the style class of the element given by id.
  1129. */
  1130. function buttonClick(id, classname) {
  1131. $(id).toggleClass(classname); // add the class to the clicked element
  1132. }
  1133. /**
  1134. * Shows a message to the user.
  1135. *
  1136. * @param titleString the title of the message
  1137. * @param messageString the text of the message
  1138. */
  1139. function openMessageDialog(titleString, messageString) {
  1140. $.prompt(messageString,
  1141. {
  1142. title: titleString,
  1143. persistent: false
  1144. }
  1145. );
  1146. }
  1147. /**
  1148. * Locks / unlocks the room.
  1149. */
  1150. function lockRoom(lock) {
  1151. if (lock)
  1152. connection.emuc.lockRoom(sharedKey);
  1153. else
  1154. connection.emuc.lockRoom('');
  1155. Toolbar.updateLockButton();
  1156. }
  1157. /**
  1158. * Sets the shared key.
  1159. */
  1160. function setSharedKey(sKey) {
  1161. sharedKey = sKey;
  1162. }
  1163. function setRecordingToken(token) {
  1164. recordingToken = token;
  1165. }
  1166. /**
  1167. * Updates the room invite url.
  1168. */
  1169. function updateRoomUrl(newRoomUrl) {
  1170. roomUrl = newRoomUrl;
  1171. // If the invite dialog has been already opened we update the information.
  1172. var inviteLink = document.getElementById('inviteLinkRef');
  1173. if (inviteLink) {
  1174. inviteLink.value = roomUrl;
  1175. inviteLink.select();
  1176. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  1177. }
  1178. }
  1179. /**
  1180. * Warning to the user that the conference window is about to be closed.
  1181. */
  1182. function closePageWarning() {
  1183. if (focus !== null)
  1184. return "You are the owner of this conference call and"
  1185. + " you are about to end it.";
  1186. else
  1187. return "You are about to leave this conversation.";
  1188. }
  1189. /**
  1190. * Resizes and repositions videos in full screen mode.
  1191. */
  1192. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1193. function () {
  1194. VideoLayout.resizeLargeVideoContainer();
  1195. VideoLayout.positionLarge();
  1196. isFullScreen = document.fullScreen ||
  1197. document.mozFullScreen ||
  1198. document.webkitIsFullScreen;
  1199. if (isFullScreen) {
  1200. setView("fullscreen");
  1201. }
  1202. else {
  1203. setView("default");
  1204. }
  1205. }
  1206. );
  1207. /**
  1208. * Sets the current view.
  1209. */
  1210. function setView(viewName) {
  1211. // if (viewName == "fullscreen") {
  1212. // document.getElementById('videolayout_fullscreen').disabled = false;
  1213. // document.getElementById('videolayout_default').disabled = true;
  1214. // }
  1215. // else {
  1216. // document.getElementById('videolayout_default').disabled = false;
  1217. // document.getElementById('videolayout_fullscreen').disabled = true;
  1218. // }
  1219. }
  1220. function hangUp() {
  1221. if (connection && connection.connected) {
  1222. // ensure signout
  1223. $.ajax({
  1224. type: 'POST',
  1225. url: config.bosh,
  1226. async: false,
  1227. cache: false,
  1228. contentType: 'application/xml',
  1229. data: "<body rid='" + (connection.rid || connection._proto.rid) + "' xmlns='http://jabber.org/protocol/httpbind' sid='" + (connection.sid || connection._proto.sid) + "' type='terminate'><presence xmlns='jabber:client' type='unavailable'/></body>",
  1230. success: function (data) {
  1231. console.log('signed out');
  1232. console.log(data);
  1233. },
  1234. error: function (XMLHttpRequest, textStatus, errorThrown) {
  1235. console.log('signout error', textStatus + ' (' + errorThrown + ')');
  1236. }
  1237. });
  1238. }
  1239. disposeConference(true);
  1240. }
  1241. $(document).bind('fatalError.jingle',
  1242. function (event, session, error)
  1243. {
  1244. sessionTerminated = true;
  1245. connection.emuc.doLeave();
  1246. openMessageDialog( "Sorry",
  1247. "Your browser version is too old. Please update and try again...");
  1248. }
  1249. );
  1250. $(document).bind("video.selected", function(event, isPresentation, userJid) {
  1251. if (!isPresentation && _dataChannels && _dataChannels.length != 0) {
  1252. _dataChannels[0].send(JSON.stringify({
  1253. 'colibriClass': 'SelectedEndpointChangedEvent',
  1254. 'selectedEndpoint': (isPresentation || !userJid)
  1255. // TODO(gp) hmm.. I wonder which one of the Strophe methods to use..
  1256. ? null : userJid.split('/')[1]
  1257. }));
  1258. }
  1259. });
  1260. function callSipButtonClicked()
  1261. {
  1262. $.prompt('<h2>Enter SIP number</h2>' +
  1263. '<input id="sipNumber" type="text" value="" autofocus>',
  1264. {
  1265. persistent: false,
  1266. buttons: { "Dial": true, "Cancel": false},
  1267. defaultButton: 2,
  1268. loaded: function (event)
  1269. {
  1270. document.getElementById('sipNumber').focus();
  1271. },
  1272. submit: function (e, v, m, f)
  1273. {
  1274. if (v)
  1275. {
  1276. var numberInput = document.getElementById('sipNumber');
  1277. if (numberInput.value && numberInput.value.length)
  1278. {
  1279. connection.rayo.dial(
  1280. numberInput.value, 'fromnumber', roomName);
  1281. }
  1282. }
  1283. }
  1284. }
  1285. );
  1286. }
  1287. function hangup() {
  1288. disposeConference();
  1289. sessionTerminated = true;
  1290. connection.emuc.doLeave();
  1291. var buttons = {};
  1292. if(config.enableWelcomePage)
  1293. {
  1294. setTimeout(function()
  1295. {
  1296. window.localStorage.welcomePageDisabled = false;
  1297. window.location.pathname = "/";
  1298. }, 10000);
  1299. }
  1300. $.prompt("Session Terminated",
  1301. {
  1302. title: "You hung up the call",
  1303. persistent: true,
  1304. buttons: {
  1305. "Join again": true
  1306. },
  1307. closeText: '',
  1308. submit: function(event, value, message, formVals)
  1309. {
  1310. window.location.reload();
  1311. return false;
  1312. }
  1313. }
  1314. );
  1315. }