/** @jsx React.DOM */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/* global loop:true, React, MozActivity */
/* jshint newcap:false, maxlen:false */
var loop = loop || {};
loop.webapp = (function($, _, OT, mozL10n) {
"use strict";
loop.config = loop.config || {};
loop.config.serverUrl = loop.config.serverUrl || "http://localhost:5000";
var sharedMixins = loop.shared.mixins;
var sharedModels = loop.shared.models;
var sharedViews = loop.shared.views;
var sharedUtils = loop.shared.utils;
/**
* Homepage view.
*/
var HomeView = React.createClass({
render: function() {
return (
);
}
});
/**
* The Firefox Marketplace exposes a web page that contains a postMesssage
* based API that wraps a small set of functionality from the WebApps API
* that allow us to request the installation of apps given their manifest
* URL. We will be embedding the content of this web page within an hidden
* iframe in case that we need to request the installation of the FxOS Loop
* client.
*/
var FxOSHiddenMarketplace = React.createClass({
render: function() {
return ;
},
componentDidUpdate: function() {
// This happens only once when we change the 'src' property of the iframe.
if (this.props.onMarketplaceMessage) {
// The reason for listening on the global window instead of on the
// iframe content window is because the Marketplace is doing a
// window.top.postMessage.
window.addEventListener("message", this.props.onMarketplaceMessage);
}
}
});
var FxOSConversationModel = Backbone.Model.extend({
setupOutgoingCall: function() {
// The FxOS Loop client exposes a "loop-call" activity. If we get the
// activity onerror callback it means that there is no "loop-call"
// activity handler available and so no FxOS Loop client installed.
var request = new MozActivity({
name: "loop-call",
data: {
type: "loop/token",
token: this.get("loopToken"),
callerId: this.get("callerId"),
callType: this.get("callType")
}
});
request.onsuccess = function() {};
request.onerror = (function(event) {
if (event.target.error.name !== "NO_PROVIDER") {
console.error ("Unexpected " + event.target.error.name);
this.trigger("session:error", "fxos_app_needed", {
fxosAppName: loop.config.fxosApp.name
});
return;
}
this.trigger("fxos:app-needed");
}).bind(this);
},
onMarketplaceMessage: function(event) {
var message = event.data;
switch (message.name) {
case "loaded":
var marketplace = window.document.getElementById("marketplace");
// Once we have it loaded, we request the installation of the FxOS
// Loop client app. We will be receiving the result of this action
// via postMessage from the child iframe.
marketplace.contentWindow.postMessage({
"name": "install-package",
"data": {
"product": {
"name": loop.config.fxosApp.name,
"manifest_url": loop.config.fxosApp.manifestUrl,
"is_packaged": true
}
}
}, "*");
break;
case "install-package":
window.removeEventListener("message", this.onMarketplaceMessage);
if (message.error) {
console.error(message.error.error);
this.trigger("session:error", "fxos_app_needed", {
fxosAppName: loop.config.fxosApp.name
});
return;
}
// We installed the FxOS app \o/, so we can continue with the call
// process.
this.setupOutgoingCall();
break;
}
}
});
var ConversationHeader = React.createClass({
render: function() {
var cx = React.addons.classSet;
var conversationUrl = location.href;
var urlCreationDateClasses = cx({
"light-color-font": true,
"call-url-date": true, /* Used as a handler in the tests */
/*hidden until date is available*/
"hide": !this.props.urlCreationDateString.length
});
var callUrlCreationDateString = mozL10n.get("call_url_creation_date_label", {
"call_url_creation_date": this.props.urlCreationDateString
});
return (
);
}
});
var StartConversationView = React.createClass({
render: function() {
return this.transferPropsTo(
);
}
});
var FailedConversationView = React.createClass({
render: function() {
return this.transferPropsTo(
);
}
});
/**
* This view manages the outgoing conversation views - from
* call initiation through to the actual conversation and call end.
*
* At the moment, it does more than that, these parts need refactoring out.
*/
var OutgoingConversationView = React.createClass({
propTypes: {
client: React.PropTypes.instanceOf(loop.StandaloneClient).isRequired,
conversation: React.PropTypes.oneOfType([
React.PropTypes.instanceOf(sharedModels.ConversationModel),
React.PropTypes.instanceOf(FxOSConversationModel)
]).isRequired,
helper: React.PropTypes.instanceOf(sharedUtils.Helper).isRequired,
notifications: React.PropTypes.instanceOf(sharedModels.NotificationCollection)
.isRequired,
sdk: React.PropTypes.object.isRequired,
feedbackApiClient: React.PropTypes.object.isRequired
},
getInitialState: function() {
return {
callStatus: "start"
};
},
componentDidMount: function() {
this.props.conversation.on("call:outgoing", this.startCall, this);
this.props.conversation.on("call:outgoing:setup", this.setupOutgoingCall, this);
this.props.conversation.on("change:publishedStream", this._checkConnected, this);
this.props.conversation.on("change:subscribedStream", this._checkConnected, this);
this.props.conversation.on("session:ended", this._endCall, this);
this.props.conversation.on("session:peer-hungup", this._onPeerHungup, this);
this.props.conversation.on("session:network-disconnected", this._onNetworkDisconnected, this);
this.props.conversation.on("session:connection-error", this._notifyError, this);
},
componentDidUnmount: function() {
this.props.conversation.off(null, null, this);
},
shouldComponentUpdate: function(nextProps, nextState) {
// Only rerender if current state has actually changed
return nextState.callStatus !== this.state.callStatus;
},
callStatusSwitcher: function(status) {
return function() {
this.setState({callStatus: status});
}.bind(this);
},
/**
* Renders the conversation views.
*/
render: function() {
switch (this.state.callStatus) {
case "start": {
return (
);
}
case "failure": {
return (
);
}
case "pending": {
return ;
}
case "connected": {
return (
);
}
case "end": {
return (
);
}
case "expired": {
return (
);
}
default: {
return ;
}
}
},
/**
* Notify the user that the connection was not possible
* @param {{code: number, message: string}} error
*/
_notifyError: function(error) {
console.error(error);
this.props.notifications.errorL10n("connection_error_see_console_notification");
this.setState({callStatus: "end"});
},
/**
* Peer hung up. Notifies the user and ends the call.
*
* Event properties:
* - {String} connectionId: OT session id
*/
_onPeerHungup: function() {
this.props.notifications.warnL10n("peer_ended_conversation2");
this.setState({callStatus: "end"});
},
/**
* Network disconnected. Notifies the user and ends the call.
*/
_onNetworkDisconnected: function() {
this.props.notifications.warnL10n("network_disconnected");
this.setState({callStatus: "end"});
},
/**
* Starts the set up of a call, obtaining the required information from the
* server.
*/
setupOutgoingCall: function() {
var loopToken = this.props.conversation.get("loopToken");
if (!loopToken) {
this.props.notifications.errorL10n("missing_conversation_info");
this.setState({callStatus: "failure"});
} else {
var callType = this.props.conversation.get("selectedCallType");
this.props.client.requestCallInfo(this.props.conversation.get("loopToken"),
callType, function(err, sessionData) {
if (err) {
switch (err.errno) {
// loop-server sends 404 + INVALID_TOKEN (errno 105) whenever a token is
// missing OR expired; we treat this information as if the url is always
// expired.
case 105:
this.setState({callStatus: "expired"});
break;
default:
this.props.notifications.errorL10n("missing_conversation_info");
this.setState({callStatus: "failure"});
break;
}
return;
}
this.props.conversation.outgoing(sessionData);
}.bind(this));
}
},
/**
* Actually starts the call.
*/
startCall: function() {
var loopToken = this.props.conversation.get("loopToken");
if (!loopToken) {
this.props.notifications.errorL10n("missing_conversation_info");
this.setState({callStatus: "failure"});
return;
}
this._setupWebSocket();
this.setState({callStatus: "pending"});
},
/**
* Used to set up the web socket connection and navigate to the
* call view if appropriate.
*
* @param {string} loopToken The session token to use.
*/
_setupWebSocket: function() {
this._websocket = new loop.CallConnectionWebSocket({
url: this.props.conversation.get("progressURL"),
websocketToken: this.props.conversation.get("websocketToken"),
callId: this.props.conversation.get("callId"),
});
this._websocket.promiseConnect().then(function() {
}.bind(this), function() {
// XXX Not the ideal response, but bug 1047410 will be replacing
// this by better "call failed" UI.
this.props.notifications.errorL10n("cannot_start_call_session_not_ready");
return;
}.bind(this));
this._websocket.on("progress", this._handleWebSocketProgress, this);
},
/**
* Checks if the streams have been connected, and notifies the
* websocket that the media is now connected.
*/
_checkConnected: function() {
// Check we've had both local and remote streams connected before
// sending the media up message.
if (this.props.conversation.streamsConnected()) {
this._websocket.mediaUp();
}
},
/**
* Used to receive websocket progress and to determine how to handle
* it if appropraite.
*/
_handleWebSocketProgress: function(progressData) {
switch(progressData.state) {
case "connecting": {
// We just go straight to the connected view as the media gets set up.
this.setState({callStatus: "connected"});
break;
}
case "terminated": {
// At the moment, we show the same text regardless
// of the terminated reason.
this._handleCallTerminated(progressData.reason);
break;
}
}
},
/**
* Handles call rejection.
*
* @param {String} reason The reason the call was terminated (reject, busy,
* timeout, cancel, media-fail, user-unknown, closed)
*/
_handleCallTerminated: function(reason) {
if (reason === "cancel") {
this.setState({callStatus: "start"});
return;
}
// XXX later, we'll want to display more meaningfull messages (needs UX)
this.props.notifications.errorL10n("call_timeout_notification_text");
this.setState({callStatus: "failure"});
},
/**
* Handles ending a call by resetting the view to the start state.
*/
_endCall: function() {
this.setState({callStatus: "end"});
},
});
/**
* Webapp Root View. This is the main, single, view that controls the display
* of the webapp page.
*/
var WebappRootView = React.createClass({
propTypes: {
client: React.PropTypes.instanceOf(loop.StandaloneClient).isRequired,
conversation: React.PropTypes.oneOfType([
React.PropTypes.instanceOf(sharedModels.ConversationModel),
React.PropTypes.instanceOf(FxOSConversationModel)
]).isRequired,
helper: React.PropTypes.instanceOf(sharedUtils.Helper).isRequired,
notifications: React.PropTypes.instanceOf(sharedModels.NotificationCollection)
.isRequired,
sdk: React.PropTypes.object.isRequired,
feedbackApiClient: React.PropTypes.object.isRequired
},
getInitialState: function() {
return {
unsupportedDevice: this.props.helper.isIOS(navigator.platform),
unsupportedBrowser: !this.props.sdk.checkSystemRequirements(),
};
},
render: function() {
if (this.state.unsupportedDevice) {
return ;
} else if (this.state.unsupportedBrowser) {
return ;
} else if (this.props.conversation.get("loopToken")) {
return (
);
} else {
return ;
}
}
});
/**
* App initialization.
*/
function init() {
var helper = new sharedUtils.Helper();
var client = new loop.StandaloneClient({
baseServerUrl: loop.config.serverUrl
});
var notifications = new sharedModels.NotificationCollection();
var conversation
if (helper.isFirefoxOS(navigator.userAgent)) {
conversation = new FxOSConversationModel();
} else {
conversation = new sharedModels.ConversationModel({}, {
sdk: OT
});
}
var feedbackApiClient = new loop.FeedbackAPIClient(
loop.config.feedbackApiUrl, {
product: loop.config.feedbackProductName,
user_agent: navigator.userAgent,
url: document.location.origin
});
// Obtain the loopToken and pass it to the conversation
var locationHash = helper.locationHash();
if (locationHash) {
conversation.set("loopToken", locationHash.match(/\#call\/(.*)/)[1]);
}
React.renderComponent(, document.querySelector("#main"));
// Set the 'lang' and 'dir' attributes to when the page is translated
document.documentElement.lang = mozL10n.language.code;
document.documentElement.dir = mozL10n.language.direction;
}
return {
CallUrlExpiredView: CallUrlExpiredView,
PendingConversationView: PendingConversationView,
StartConversationView: StartConversationView,
FailedConversationView: FailedConversationView,
OutgoingConversationView: OutgoingConversationView,
EndedConversationView: EndedConversationView,
HomeView: HomeView,
UnsupportedBrowserView: UnsupportedBrowserView,
UnsupportedDeviceView: UnsupportedDeviceView,
init: init,
PromoteFirefoxView: PromoteFirefoxView,
WebappRootView: WebappRootView,
FxOSConversationModel: FxOSConversationModel
};
})(jQuery, _, window.OT, navigator.mozL10n);