I am getting this error "Can't find variable: FBSDKApplicationDelegate" - facebook-javascript-sdk

Can't find variable: FBSDKApplicationDelegate,
app.js
> const application = require("tns-core-modules/application");
>
> if(application.ios){ `
>
> var AppDelegate = UIResponder.extend({
> applicationDidFinishLaunchingWithOptions :function (application,
> launchOptions) { var gglDelegate = false; try { var errorRef = new
> interop.Reference();
> GGLContext.sharedInstance().configureWithError(errorRef); var signIn =
> GIDSignIn.sharedInstance(); gglDelegate = true; } catch (error) {
> console.log(error); } var fcbDelegate =
> FBSDKApplicationDelegate.sharedInstance().applicationDidFinishLaunchingWithOptions(application,
> launchOptions); // facebook login delegate return gglDelegate ||
> fcbDelegate; }, applicationOpenURLSourceApplicationAnnotation :
> function (application, url, sourceApplication, annotation) { var
> fcbDelegate =
> FBSDKApplicationDelegate.sharedInstance().applicationOpenURLSourceApplicationAnnotation(application,
> url, sourceApplication, annotation); // facebook login delegate var
> gglDelegate =
> GIDSignIn.sharedInstance().handleURLSourceApplicationAnnotation(url,
> sourceApplication, annotation); // google login delegate return
> fcbDelegate || gglDelegate; }
>
> },{ name: "AppDelegate", protocols:[UIApplicationDelegate]
>
> }); application.ios.delegate = AppDelegate; } application.run({
> moduleName: "app-root" });
The js code given in https://github.com/mkloubert/nativescript-social-login#javascript . not working , i am working on nativescript( javascript ) without any framework like TS , angular or view.

Related

Vuejs-pdf print

I'm using vuejs-pdf to print some pages of my pdf and the print is not show the characters :
that's the code i'm using :
<button #click="$refs.myPdfComponent.print(100,pages)">Print </button>
<pdf v-for="i in pages" :key="i" ref="newpdf" :src="'pdf/'+src" :page="i" class="rounded border
border-info mb-4" :rotate="rotate" #progress="loadedRatio = $event" #error="error" #num-pages="numPages = $event" #link-clicked="page = $event" > </pdf>
and the pdf i'm printing is myPdfComponent the newpdf is the only the pages i need :
<pdf v-if="show" ref="myPdfComponent" class="rounded border border-info mb-4" :src="'pdf/'+src"
:page="page" :rotate="rotate" #progress="loadedRatio = $event" #error="error" #num-pages="numPages =
$event" #link-clicked="page = $event"></pdf>
Open the vue-pdf plugin directory node_modules/vue-pdf/src/pdfjsWrapper.js
and replace
import { PDFLinkService } from 'pdfjs-dist/es5/web/pdf_viewer';
var pendingOperation = Promise.resolve();
export default function(PDFJS) {
function isPDFDocumentLoadingTask(obj) {
return typeof(obj) === 'object' && obj !== null && obj.__PDFDocumentLoadingTask === true;
// or: return obj.constructor.name === 'PDFDocumentLoadingTask';
}
function createLoadingTask(src, options) {
var source;
if ( typeof(src) === 'string' )
source = { url: src };
else if ( src instanceof Uint8Array )
source = { data: src };
else if ( typeof(src) === 'object' && src !== null )
source = Object.assign({}, src);
else
throw new TypeError('invalid src type');
// source.verbosity = PDFJS.VerbosityLevel.INFOS;
// source.pdfBug = true;
// source.stopAtErrors = true;
if ( options && options.withCredentials )
source.withCredentials = options.withCredentials;
var loadingTask = PDFJS.getDocument(source);
loadingTask.__PDFDocumentLoadingTask = true; // since PDFDocumentLoadingTask is not public
if ( options && options.onPassword )
loadingTask.onPassword = options.onPassword;
if ( options && options.onProgress )
loadingTask.onProgress = options.onProgress;
return loadingTask;
}
function PDFJSWrapper(canvasElt, annotationLayerElt, emitEvent) {
var pdfDoc = null;
var pdfPage = null;
var pdfRender = null;
var canceling = false;
canvasElt.getContext('2d').save();
function clearCanvas() {
canvasElt.getContext('2d').clearRect(0, 0, canvasElt.width, canvasElt.height);
}
function clearAnnotations() {
while ( annotationLayerElt.firstChild )
annotationLayerElt.removeChild(annotationLayerElt.firstChild);
}
this.destroy = function() {
if ( pdfDoc === null )
return;
// Aborts all network requests and destroys worker.
pendingOperation = pdfDoc.destroy();
pdfDoc = null;
}
this.getResolutionScale = function() {
return canvasElt.offsetWidth / canvasElt.width;
}
this.printPage = function(dpi, pageNumberOnly) {
if ( pdfPage === null )
return;
// 1in == 72pt
// 1in == 96px
var PRINT_RESOLUTION = dpi === undefined ? 150 : dpi;
var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
var CSS_UNITS = 96.0 / 72.0;
/*var iframeElt = document.createElement('iframe');
function removeIframe() {
iframeElt.parentNode.removeChild(iframeElt);
}*/
var printContainerElement = document.createElement('div');
printContainerElement.setAttribute('id', 'print-container')
function removePrintContainer() {
printContainerElement.parentNode.removeChild(printContainerElement);
}
new Promise(function(resolve, reject) {
/*
iframeElt.frameBorder = '0';
iframeElt.scrolling = 'no';
iframeElt.width = '0px;'
iframeElt.height = '0px;'
iframeElt.style.cssText = 'position: absolute; top: 0; left: 0';
iframeElt.onload = function() {
resolve(this.contentWindow);
}
window.document.body.appendChild(iframeElt);*/
printContainerElement.frameBorder = '0';
printContainerElement.scrolling = 'no';
printContainerElement.width = '0px;'
printContainerElement.height = '0px;'
printContainerElement.style.cssText = 'position: absolute; top: 0; left: 0';
window.document.body.appendChild(printContainerElement);
resolve(window)
})
.then(function(win) {
win.document.title = '';
return pdfDoc.getPage(1)
.then(function(page) {
var viewport = page.getViewport({ scale: 1 });
//win.document.head.appendChild(win.document.createElement('style')).textContent =
printContainerElement.appendChild(win.document.createElement('style')).textContent =
'#supports ((size:A4) and (size:1pt 1pt)) {' +
'#page { margin: 1pt; size: ' + ((viewport.width * PRINT_UNITS) / CSS_UNITS) + 'pt ' + ((viewport.height * PRINT_UNITS) / CSS_UNITS) + 'pt; }' +
'}' +
'#print-canvas { display: none }' +
'#media print {' +
'body { margin: 0 }' +
'canvas { page-break-before: avoid; page-break-after: always; page-break-inside: avoid }' +
'#print-canvas { page-break-before: avoid; page-break-after: always; page-break-inside: avoid; display: block }' +
'body > *:not(#print-container) { display: none; }' +
'}'+
'#media screen {' +
'body { margin: 0 }' +
'}'+
''
return win;
})
})
.then(function(win) {
var allPages = [];
for ( var pageNumber = 1; pageNumber <= pdfDoc.numPages; ++pageNumber ) {
if ( pageNumberOnly !== undefined && pageNumberOnly.indexOf(pageNumber) === -1 )
continue;
allPages.push(
pdfDoc.getPage(pageNumber)
.then(function(page) {
var viewport = page.getViewport({ scale: 1 });
//var printCanvasElt = win.document.body.appendChild(win.document.createElement('canvas'));
var printCanvasElt = printContainerElement.appendChild(win.document.createElement('canvas'));
printCanvasElt.setAttribute('id', 'print-canvas')
printCanvasElt.width = (viewport.width * PRINT_UNITS);
printCanvasElt.height = (viewport.height * PRINT_UNITS);
return page.render({
canvasContext: printCanvasElt.getContext('2d'),
transform: [ // Additional transform, applied just before viewport transform.
PRINT_UNITS, 0, 0,
PRINT_UNITS, 0, 0
],
viewport: viewport,
intent: 'print'
}).promise;
})
);
}
Promise.all(allPages)
.then(function() {
win.focus(); // Required for IE
if (win.document.queryCommandSupported('print')) {
win.document.execCommand('print', false, null);
} else {
win.print();
}
removePrintContainer();
})
.catch(function(err) {
removePrintContainer();
emitEvent('error', err);
})
})
}
this.renderPage = function(rotate) {
if ( pdfRender !== null ) {
if ( canceling )
return;
canceling = true;
pdfRender.cancel();
return;
}
if ( pdfPage === null )
return;
var pageRotate = (pdfPage.rotate === undefined ? 0 : pdfPage.rotate) + (rotate === undefined ? 0 : rotate);
var scale = canvasElt.offsetWidth / pdfPage.getViewport({ scale: 1 }).width * (window.devicePixelRatio || 1);
var viewport = pdfPage.getViewport({ scale: scale, rotation:pageRotate });
emitEvent('page-size', viewport.width, viewport.height, scale);
canvasElt.width = viewport.width;
canvasElt.height = viewport.height;
pdfRender = pdfPage.render({
canvasContext: canvasElt.getContext('2d'),
viewport: viewport
});
annotationLayerElt.style.visibility = 'hidden';
clearAnnotations();
var viewer = {
scrollPageIntoView: function(params) {
emitEvent('link-clicked', params.pageNumber)
},
};
var linkService = new PDFLinkService();
linkService.setDocument(pdfDoc);
linkService.setViewer(viewer);
pendingOperation = pendingOperation.then(function() {
var getAnnotationsOperation =
pdfPage.getAnnotations({ intent: 'display' })
.then(function(annotations) {
PDFJS.AnnotationLayer.render({
viewport: viewport.clone({ dontFlip: true }),
div: annotationLayerElt,
annotations: annotations,
page: pdfPage,
linkService: linkService,
renderInteractiveForms: false
});
});
var pdfRenderOperation =
pdfRender.promise
.then(function() {
annotationLayerElt.style.visibility = '';
canceling = false;
pdfRender = null;
})
.catch(function(err) {
pdfRender = null;
if ( err instanceof PDFJS.RenderingCancelledException ) {
canceling = false;
this.renderPage(rotate);
return;
}
emitEvent('error', err);
}.bind(this))
return Promise.all([getAnnotationsOperation, pdfRenderOperation]);
}.bind(this));
}
this.forEachPage = function(pageCallback) {
var numPages = pdfDoc.numPages;
(function next(pageNum) {
pdfDoc.getPage(pageNum)
.then(pageCallback)
.then(function() {
if ( ++pageNum <= numPages )
next(pageNum);
})
})(1);
}
this.loadPage = function(pageNumber, rotate) {
pdfPage = null;
if ( pdfDoc === null )
return;
pendingOperation = pendingOperation.then(function() {
return pdfDoc.getPage(pageNumber);
})
.then(function(page) {
pdfPage = page;
this.renderPage(rotate);
emitEvent('page-loaded', page.pageNumber);
}.bind(this))
.catch(function(err) {
clearCanvas();
clearAnnotations();
emitEvent('error', err);
});
}
this.loadDocument = function(src) {
pdfDoc = null;
pdfPage = null;
emitEvent('num-pages', undefined);
if ( !src ) {
canvasElt.removeAttribute('width');
canvasElt.removeAttribute('height');
clearAnnotations();
return;
}
// wait for pending operation ends
pendingOperation = pendingOperation.then(function() {
var loadingTask;
if ( isPDFDocumentLoadingTask(src) ) {
if ( src.destroyed ) {
emitEvent('error', new Error('loadingTask has been destroyed'));
return
}
loadingTask = src;
} else {
loadingTask = createLoadingTask(src, {
onPassword: function(updatePassword, reason) {
var reasonStr;
switch (reason) {
case PDFJS.PasswordResponses.NEED_PASSWORD:
reasonStr = 'NEED_PASSWORD';
break;
case PDFJS.PasswordResponses.INCORRECT_PASSWORD:
reasonStr = 'INCORRECT_PASSWORD';
break;
}
emitEvent('password', updatePassword, reasonStr);
},
onProgress: function(status) {
var ratio = status.loaded / status.total;
emitEvent('progress', Math.min(ratio, 1));
}
});
}
return loadingTask.promise;
})
.then(function(pdf) {
pdfDoc = pdf;
emitEvent('num-pages', pdf.numPages);
emitEvent('loaded');
})
.catch(function(err) {
clearCanvas();
clearAnnotations();
emitEvent('error', err);
})
}
annotationLayerElt.style.transformOrigin = '0 0';
}
return {
createLoadingTask: createLoadingTask,
PDFJSWrapper: PDFJSWrapper,
}
}

angular 8- webrtc-adapter in Firefox not working

I try to run poc which created in angular 8 using webrtc-adpater. Problem is that it is not working in firefox and safari, but working in chrome.
What I observe connection is never connecting or connected in firefox.
I import webrtc in code so anything else we need to handle for firefox and safari.
Basically from Wowza I trying to consume streaming.
Below code sample which working in chrome but not in Firefox and safari:
const ICE_SERVERS: RTCIceServer[] = [
{ urls: ['stun:stun.example.com', 'stun:stun-1.example.com'] },
{ urls: 'stun:stun.l.google.com:19302' }
];
setupSignalingServer(ele) {
const self = this;
window.RTCPeerConnection = window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
let signalingConnection = new WebSocket('wss://local.geofabricdev.com/webrtc-session.json');
signalingConnection.binaryType = 'arraybuffer';
signalingConnection.onopen = function (res) {
console.log('connection open');
signalingConnection.onerror = self.errorHandler;
// window.RTCPeerConnection = self.getRTCPeerConnection();
const peerConnection = new RTCPeerConnection(PEER_CONNECTION_CONFIG);
peerConnection.addEventListener('connectionstatechange', event => {
console.log(event);
if (peerConnection.connectionState === 'connected') {
console.log('connected');
}
});
peerConnection.addEventListener('icecandidate', event => {
console.log('peerconnection state5:' + peerConnection.connectionState);
if (event.candidate) {
// signalingChannel.send({'new-ice-candidate': event.candidate});
}
});
peerConnection.addEventListener('track', async event => {
console.log('gotRemoteTrack: kind:' + event.track.kind + ' stream:' + event.streams[0]);
const video = self.createVideo();
// const remoteVideo1 = document.querySelector('#remoteVideo') as HTMLVideoElement;
try {
video.srcObject = event.streams[0];
// remoteVideo1.srcObject = event.streams[0];
} catch (error) {
video.src = window.URL.createObjectURL(event.streams[0]);
}
});
signalingConnection.addEventListener('message', async message => {
console.dir(message);
// self.getSignalMessageCallback(message);
console.log('wsConnection.onmessage: ' + message.data);
const signal = JSON.parse(message.data);
if(signal.status !== 200) {
const video = self.createVideo();
video.poster = '../assets/streaming-error.png';
}
const streamInfoResponse = signal['streamInfo'];
let g = [];
// self.socketStream.some((f) => {
g = self.streams.filter((str) => signal['streamInfo'].streamName === str.streamName);
// if(g.length > 0) {
// return true;
// }
// });
// });
if (streamInfoResponse !== undefined) {
g[0]['sessionId'] = streamInfoResponse.sessionId;
}
console.log('Received signal');
const msgCommand = signal['command'];
console.log(msgCommand);
if (signal.sdp) {
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp));
if (signal.sdp) {
const description = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(description);
signalingConnection.send('{"direction":"play", "command":"sendResponse", "streamInfo":' +
JSON.stringify(g[0]) + ', "sdp":' + JSON.stringify(description) + ',"userData":' + JSON.stringify(self.userData) + '}');
}
// })
// .catch(self.errorHandler);
} else if (signal.iceCandidates) {
console.log('ice: ' + JSON.stringify(signal.iceCandidates));
peerConnection.addIceCandidate(new RTCIceCandidate(signal.iceCandidates[0])).catch(self.errorHandler);
}
if ('sendResponse'.localeCompare(msgCommand) === 0) {
if (signalingConnection != null) {
signalingConnection.close();
}
signalingConnection = null;
}
// };
});
signalingConnection.send('{"direction":"play", "command":"getOffer", "streamInfo":' +
JSON.stringify(ele) + ', "userData":' + JSON.stringify(self.userData) + '}');
};
signalingConnection.onclose = function (r) {
console.log('close');
};
}
private createVideo() {
const video = document.createElement('video');
video.classList.add('cameraPanel');
video.autoplay = true;
video.preload = 'true';
video.muted = true;
video.width = 300;
const remoteVideo = document.querySelector('#videoContainer') as HTMLElement;
remoteVideo.appendChild(video);
return video;
}

How to get the video ended event in titanium appcelerator

I have load video url at run time using the setInterval() before assign video i am try to clear the setinterval
Also have used onComplete="donextcall" for assingn new video path to videoview but it fire twice so please help me
<VideoPlayer id="videoPlayersinglezone" ns="Ti.Media" autoplay="true" height="100%" width="100%" onComplete="donextcall" url="" backgroundColor="black" />
var f = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory +'SinglezoneData/', singleimgs[tempcall]);
clearInterval(x)
$.videoPlayersinglezone.url = f.nativePath;
$.videoPlayersinglezone.show();
I have using titanium 3.1.1 and alloy 1.2.2 anything missing please tell me.
Full code example
var common = require('common');
var singleimgs = [];
var fistentry = 0;
doFirstClickSingleZone();
function doFirstClickSingleZone() {
var totalads = Titanium.App.Properties.getString('total_files_on_sdcard');
$.videoPlayersinglezone.mediaControlStyle = Titanium.Media.VIDEO_CONTROL_HIDDEN;
LoadData(totalads);
}
function LoadData(adscount) {
var fistcall = 0;
for (var i = 0; i < adscount; i++) {
singleimgs[i] = Titanium.App.Properties.getString('dwnfname' + i);
}
}
var tempcall=0;
function donextcall() {
/*
fistentry++;
if (fistentry % 2 == 0) {
} else {
tempcall++;
RenderAd(tempcall);
}
*/
tempcall++;
RenderAd(tempcall);
}
function RenderAd(imgid) {
if (imgid == singleimgs.length) {
tempcall = 0;
} else {
tempcall= imgid;
}
var t = Titanium.App.Properties.getString('timeInt');
var x = setInterval(function() {
if (tempcall < singleimgs.length) {
var arry = [];
arry = singleimgs[tempcall].split(".");
var exte;
exte = arry[arry.length - 1];
if (exte == 'png' || exte == 'jpg' || exte == 'gif' || exte == 'jpeg' || exte == 'tif') {
common.getnotification();
$.videoPlayersinglezone.url = "";
$.videoPlayersinglezone.hide();
var f = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory +'SinglezoneData/', singleimgs[tempcall]);
$.myImg.image = f.nativePath;
$.myImg.show();
tempcall++;
} else {
//if(exte=='mp4' || exte=='avi' || exte=='3gp' || exte=='mov' || exte == 'flv'){
common.getnotification();
var f = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory +'SinglezoneData/', singleimgs[tempcall]);
//Titanium.App.Properties.setString('videopath', f.nativePath);
//Titanium.App.Properties.setString('imgcount', tempcall++);
$.myImg.image = '';
$.myImg.hide();
clearInterval(x);
$.videoPlayersinglezone.url = f.nativePath;
$.videoPlayersinglezone.show();
}
} else {
common.getnotification();
clearInterval(x);
callAgain();
}
}, 10000);
}
//this callaAgain() I have use to call RenderAd(imgid) to display image or video randomly so u have any solution please help me my application aim to display image or video from sdcard randomly
function callAgain() {
RenderAd(singleimgs.length);
}

WebRTC + JSEP + Google Channel API - cannot receive remoteStream

I've been trying to get this works, but I don't know what's wrong, can you guys help me? I tried WebRTC code with modification like this.
Both caller and callee enter the web
Web will create channel based on their username
Caller clicks the call button and sends message to spesific channel to some user's username. When caller clicks the call button, he then creates peerConnection and adds localStream
Callee will receive message, and the process goes on like WebRTC sample code. When callee receives an offer, he then creates peerConnection and adds localStream, then creates and sends answer
My code goes like this
var my_username = '{{ current_username }}';
var friend;
var localVideo;
var remoteVideo;
var localStream;
var remoteStream;
var channel;
var channelReady = false;
var pc;
var socket;
var started = false;
// Set up audio and video regardless of what devices are present.
var mediaConstraints = {'mandatory': {
'OfferToReceiveAudio':true,
'OfferToReceiveVideo':true }};
var isVideoMuted = false;
var isAudioMuted = false;
function choiceFriendInitialize() {
var choice_visible = false;
$('ul#friendlist > li').click(function(e) {
$(this).css('background-color', '#808080');
friend = $(this).text();
var choice = $('ul#choice');
choice_visible = true;
choice.css('display', 'inline-block');
choice.css('top', e.pageY);
choice.css('left', e.pageX);
});
// trigger call from here
$('li#call').click(function() {
$('ul#friendlist > li').css('background-color', 'transparent');
$('ul#choice').css('display', 'none');
choice_visible = false;
// call
maybeStart();
doCall();
});
$('li#unfriend').click(function() {
$('ul#friendlist > li').css('background-color', 'transparent');
$('ul#choice').css('display', 'none');
choice_visible = false;
});
$("body").mouseup(function(){
if (choice_visible) {
$('ul#friendlist > li').css('background-color', 'transparent');
$('ul#choice').css('display', 'none');
choice_visible = false;
}
});
}
function initialize() {
console.log("Initializing..");
choiceFriendInitialize();
localVideo = document.getElementById("localVideo");
remoteVideo = document.getElementById("remoteVideo");
openChannel();
doGetUserMedia();
}
function openChannel() {
console.log("Opening channel.");
var channel = new goog.appengine.Channel('{{ token }}');
var handler = {
'onopen': onChannelOpened,
'onmessage': onChannelMessage,
'onerror': onChannelError,
'onclose': onChannelClosed
};
socket = channel.open(handler);
}
function doGetUserMedia() {
// Call into getUserMedia via the polyfill (adapter.js).
var constraints = {"mandatory": {}, "optional": []};
try {
getUserMedia({'audio':true, 'video':constraints}, onUserMediaSuccess, onUserMediaError);
console.log("Requested access to local media with mediaConstraints:\n" + " \"" + JSON.stringify(constraints) + "\"");
} catch (e) {
alert("getUserMedia() failed. Is this a WebRTC capable browser?");
console.log("getUserMedia failed with exception: " + e.message);
}
}
function createPeerConnection() {
var pc_config = {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]};
try {
// Create an RTCPeerConnection via the polyfill (adapter.js).
pc = new RTCPeerConnection(pc_config);
pc.onicecandidate = onIceCandidate;
console.log("Created RTCPeerConnnection with config:\n" + " \"" + JSON.stringify(pc_config) + "\".");
} catch (e) {
console.log("Failed to create PeerConnection, exception: " + e.message);
alert("Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.");
return;
}
pc.onconnecting = onSessionConnecting;
pc.onopen = onSessionOpened;
pc.onaddstream = onRemoteStreamAdded;
pc.onremovestream = onRemoteStreamRemoved;
}
function maybeStart() {
if (!started && localStream && channelReady) {
console.log("Creating PeerConnection.");
createPeerConnection();
console.log("Adding local stream.");
pc.addStream(localStream);
started = true;
// Caller initiates offer to peer.
//if (initiator)
//doCall();
}
}
function doCall() {
console.log("Sending offer to peer.");
pc.createOffer(setLocalAndSendMessage, null, mediaConstraints);
}
function doAnswer() {
console.log("Sending answer to peer.");
pc.createAnswer(setLocalAndSendMessage, null, mediaConstraints);
}
function setLocalAndSendMessage(sessionDescription) {
// Set Opus as the preferred codec in SDP if Opus is present.
sessionDescription.sdp = preferOpus(sessionDescription.sdp);
pc.setLocalDescription(sessionDescription);
sendMessage({from: my_username, to: friend}, sessionDescription);
}
function sendMessage(client, message) {
console.log('C->S: ' + JSON.stringify(message));
var xhr = new XMLHttpRequest();
xhr.open('POST', '/send', true);
xhr.setRequestHeader("Content-type","application/json");
var msgString = {send_info: client, data_message: message};
xhr.send(JSON.stringify(msgString));
}
function processSignalingMessage(message) {
var msg = JSON.parse(message);
var data_message = msg.data_message;
var send_info = msg.send_info;
if (data_message.type === 'offer') {
// Callee creates PeerConnection
if (!started)
maybeStart();
pc.setRemoteDescription(new RTCSessionDescription(data_message));
friend = send_info.from;
doAnswer();
} else if (data_message.type === 'answer' && started) {
pc.setRemoteDescription(new RTCSessionDescription(data_message));
} else if (data_message.type === 'candidate' && started) {
var candidate = new RTCIceCandidate({sdpMLineIndex:data_message.label, candidate:data_message.candidate});
pc.addIceCandidate(candidate);
} else if (data_message.type === 'bye' && started) {
onRemoteHangup();
}
}
function onChannelOpened() {
console.log('Channel opened.');
channelReady = true;
}
function onChannelMessage(message) {
console.log('S->C: ' + message.data);
processSignalingMessage(message.data);
}
function onChannelError() {
console.log('Channel error.');
}
function onChannelClosed() {
console.log('Channel closed.');
}
function onUserMediaSuccess(stream) {
console.log("User has granted access to local media.");
// Call the polyfill wrapper to attach the media stream to this element.
attachMediaStream(localVideo, stream);
localVideo.style.opacity = 1;
localStream = stream;
// Caller creates PeerConnection.
//if (initiator) maybeStart();
}
function onUserMediaError(error) {
console.log("Failed to get access to local media. Error code was " + error.code);
alert("Failed to get access to local media. Error code was " + error.code + ".");
}
function onIceCandidate(event) {
if (event.candidate) {
sendMessage({from: my_username, to: friend}, {type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate});
} else {
console.log("End of candidates.");
}
}
function onSessionConnecting(message) {
console.log("Session connecting.");
}
function onSessionOpened(message) {
console.log("Session opened.");
}
function onRemoteStreamAdded(event) {
console.log("Remote stream added.");
attachMediaStream(remoteVideo, event.stream);
remoteStream = event.stream;
waitForRemoteVideo();
}
function onRemoteStreamRemoved(event) {
console.log("Remote stream removed.");
}
function onHangup() {
console.log("Hanging up.");
transitionToDone();
stop();
// will trigger BYE from server
socket.close();
}
function onRemoteHangup() {
console.log('Session terminated.');
transitionToWaiting();
stop();
}
function stop() {
started = false;
isAudioMuted = false;
isVideoMuted = false;
pc.close();
pc = null;
}
function waitForRemoteVideo() {
if (remoteStream.videoTracks.length === 0 || remoteVideo.currentTime > 0) {
console.log('ada remote stream');
transitionToActive();
} else {
console.log('ga ada remote stream');
setTimeout(waitForRemoteVideo, 100);
}
}
function transitionToActive() {
remoteVideo.style.opacity = 1;
}
function transitionToWaiting() {
remoteVideo.style.opacity = 0;
}
function transitionToDone() {
localVideo.style.opacity = 0;
remoteVideo.style.opacity = 0;
}
function toggleVideoMute() {
if (localStream.videoTracks.length === 0) {
console.log("No local video available.");
return;
}
if (isVideoMuted) {
for (i = 0; i < localStream.videoTracks.length; i++) {
localStream.videoTracks[i].enabled = true;
}
console.log("Video unmuted.");
} else {
for (i = 0; i < localStream.videoTracks.length; i++) {
localStream.videoTracks[i].enabled = false;
}
console.log("Video muted.");
}
isVideoMuted = !isVideoMuted;
}
function toggleAudioMute() {
if (localStream.audioTracks.length === 0) {
console.log("No local audio available.");
return;
}
if (isAudioMuted) {
for (i = 0; i < localStream.audioTracks.length; i++) {
localStream.audioTracks[i].enabled = true;
}
console.log("Audio unmuted.");
} else {
for (i = 0; i < localStream.audioTracks.length; i++){
localStream.audioTracks[i].enabled = false;
}
console.log("Audio muted.");
}
isAudioMuted = !isAudioMuted;
}
setTimeout(initialize, 1);
// Send BYE on refreshing(or leaving) a demo page
// to ensure the room is cleaned for next session.
window.onbeforeunload = function() {
sendMessage({from: my_username, to: friend}, {type: 'bye'});
//Delay 100ms to ensure 'bye' arrives first.
setTimeout(function(){}, 100);
}
// Ctrl-D: toggle audio mute; Ctrl-E: toggle video mute.
// On Mac, Command key is instead of Ctrl.
// Return false to screen out original Chrome shortcuts.
document.onkeydown = function() {
if (navigator.appVersion.indexOf("Mac") != -1) {
if (event.metaKey && event.keyCode === 68) {
toggleAudioMute();
return false;
}
if (event.metaKey && event.keyCode === 69) {
toggleVideoMute();
return false;
}
} else {
if (event.ctrlKey && event.keyCode === 68) {
toggleAudioMute();
return false;
}
if (event.ctrlKey && event.keyCode === 69) {
toggleVideoMute();
return false;
}
}
}
// Set Opus as the default audio codec if it's present.
function preferOpus(sdp) {
var sdpLines = sdp.split('\r\n');
// Search for m line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('m=audio') !== -1) {
var mLineIndex = i;
break;
}
}
if (mLineIndex === null)
return sdp;
// If Opus is available, set it as the default in m line.
for (var i = 0; i < sdpLines.length; i++) {
if (sdpLines[i].search('opus/48000') !== -1) {
var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
if (opusPayload)
sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], opusPayload);
break;
}
}
// Remove CN in m line and sdp.
sdpLines = removeCN(sdpLines, mLineIndex);
sdp = sdpLines.join('\r\n');
return sdp;
}
function extractSdp(sdpLine, pattern) {
var result = sdpLine.match(pattern);
return (result && result.length == 2)? result[1]: null;
}
// Set the selected codec to the first in m line.
function setDefaultCodec(mLine, payload) {
var elements = mLine.split(' ');
var newLine = new Array();
var index = 0;
for (var i = 0; i < elements.length; i++) {
if (index === 3) // Format of media starts from the fourth.
newLine[index++] = payload; // Put target payload to the first.
if (elements[i] !== payload)
newLine[index++] = elements[i];
}
return newLine.join(' ');
}
// Strip CN from sdp before CN constraints is ready.
function removeCN(sdpLines, mLineIndex) {
var mLineElements = sdpLines[mLineIndex].split(' ');
// Scan from end for the convenience of removing an item.
for (var i = sdpLines.length-1; i >= 0; i--) {
var payload = extractSdp(sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i);
if (payload) {
var cnPos = mLineElements.indexOf(payload);
if (cnPos !== -1) {
// Remove CN payload from m line.
mLineElements.splice(cnPos, 1);
}
// Remove CN line in sdp
sdpLines.splice(i, 1);
}
}
sdpLines[mLineIndex] = mLineElements.join(' ');
return sdpLines;
}
When it comes to waitForRemoteVideo, the function calls the else condition. But the blob url for remoteVideo exists.
It's funny that I've been searching for the error and re-writing the code for like three times, and suddenly after posted my question here, I realized my mistake.
Here in the function processSignallingMessage..
if (data_message.type === 'offer') {
// Callee creates PeerConnection
if (!started)
maybeStart();
pc.setRemoteDescription(new RTCSessionDescription(data_message));
friend = send_info.from;
doAnswer();
} else ....
Should be like this:
if (data_message.type === 'offer') {
friend = send_info.from;
// Callee creates PeerConnection
if (!started)
maybeStart();
pc.setRemoteDescription(new RTCSessionDescription(data_message));
doAnswer();
} else ....
because callee need variable friend to be filled before sending candidate message.

Corrupt Windows in Titanium

I open windows as follows:
app.js:
var NavigationController = require('NavigationController').NavigationController,
TestWindow = require('main_windows/tmain').TestWindow;
//create NavigationController which will drive our simple application
var controller = new NavigationController();
//open initial window
controller.open(new TestWindow(controller));
function openWindow(name, naController, event) {
var TestWindow2 = require('main_windows/t' + name).TestWindow;
var win = Titanium.UI.currentWindow;
var swin = Titanium.UI.createWindow();
if(event.bid)
swin.bid = event.bid;
if(event.uniq)
swin.uniq = event.uniq;
if (event.zipcode)
swin.zipcode = event.zipcode;
if (event.user_id)
swin.user_id = event.user_id;
if (event.service_id)
swin.service_id = event.service_id;
if (event.service_name)
swin.service_name = event.service_name;
if (event.user_uniqid)
swin.user_uniqid = event.user_uniqid;
if (event.user_name)
swin.user_name = event.user_name;
if (event.user_email)
swin.user_email = event.user_email;
if (event.provider_id)
swin.provider_id = event.provider_id;
if (event.provider_name)
swin.provider_name = event.provider_name;
if (event.total)
swin.total = event.total;
if(event.response)
swin.response = event.response;
swin.backgroundColor = '#f7f7f7';
swin.barImage = 'images/example.gif';
naController.open(new TestWindow2(naController, swin));
}
Here is the NavigationController.js
exports.NavigationController = function() {
this.windowStack = [];
};
exports.NavigationController.prototype.open = function(/*Ti.UI.Window*/windowToOpen) {
//add the window to the stack of windows managed by the controller
this.windowStack.push(windowToOpen);
//alert('open' + this.windowStack.length);
//grab a copy of the current nav controller for use in the callback
var that = this;
windowToOpen.addEventListener('close', function() {
// alert('open' + that.windowStack.length);
if(that.windowStack.length > 1)
{
//alert('pop' + that.windowStack.length);
that.windowStack.pop();
}
});
//hack - setting this property ensures the window is "heavyweight" (associated with an Android activity)
windowToOpen.navBarHidden = windowToOpen.navBarHidden || false;
//This is the first window
if(this.windowStack.length === 1) {
if(Ti.Platform.osname === 'android') {
windowToOpen.exitOnClose = true;
windowToOpen.open();
} else {
//alert('nav' + this.windowStack.length);
this.navGroup = Ti.UI.iPhone.createNavigationGroup({
window : windowToOpen
});
var containerWindow = Ti.UI.createWindow();
containerWindow.add(this.navGroup);
containerWindow.open();
}
}
//All subsequent windows
else {
if(Ti.Platform.osname === 'android') {
windowToOpen.open();
} else {
//alert('nav2' + this.windowStack.length);
this.navGroup.open(windowToOpen);
}
}
};
//go back to the initial window of the NavigationController
exports.NavigationController.prototype.home = function() {
//store a copy of all the current windows on the stack
//alert('reset' + this.windowStack.length);
var windows = this.windowStack.concat([]);
for(var i = 1, l = windows.length; i < l; i++) {
(this.navGroup) ? this.navGroup.close(windows[i]) : windows[i].close();
}
this.windowStack = [this.windowStack[0]]; //reset stack
//alert('n' + this.windowStack.length);
};
Here is tmain.js
exports.TestWindow = function(navController) {
var win = Ti.UI.createWindow({
backButtonTitleImage : 'images/backb.gif',
fullscreen : false,
navBarHidden : true,
});
var t1 = null;
win.backgroundImage = 'images/back.jpg';
var view = Titanium.UI.createView({
width : '100%',
height : '100%',
top : 270,
layout : 'vertical'
});
var b3 = Titanium.UI.createImageView({
url : 'images/login.gif',
height : 80
});
view.add(b3);
var b4 = Titanium.UI.createImageView({
url : 'images/signup.gif',
top : 0,
height : 80
});
view.add(b4);
win.add(view);
var list1 = function(e) {
openWindow('login', navController, e);
};
b3.addEventListener('click', list1);
var list2 = function(e) {
openWindow('register', navController, e);
};
b4.addEventListener('click', list2);
win.addEventListener('close', function (e) {
alert(3);
b3.removeEventListener('click', list1);
b4.removeEventListener('click', list2);
});
return win;
};
So I use the openWindow function to open windows in the app. I have a logout botton, that when people click on it, calls the function navController.home() (see Navigation Controller), but the problem is clicking on the logout link causes corrupt window state - meaning that the application crashes and when you try to open it, windows are mixed together (like buttons in window 3 show up in window 2).
What am I doing wrong?