Skip to content

Instantly share code, notes, and snippets.

@abourget
Created March 13, 2012 05:26
Show Gist options
  • Save abourget/2026984 to your computer and use it in GitHub Desktop.
Save abourget/2026984 to your computer and use it in GitHub Desktop.
Simple WebRTC initiation code
if(window.Audio) {
var audio = new Audio("notification.ogg")
}
var name = ""
var name_el = <input maxlength=18 placeholder=_Name>
var name_error_el
var name_form_el
var message_list_el
var message_form_el
var message_ids = {}
var pending_message_el
var websocket = window.WebSocket
var socket
var socket_connected
var socket_error
var socket_ping_timeout
var peer_connection
window.onload = function() {
if(!http_request()) {
doc.body.innerHTML = "Your browser does not support XMLHttpRequest. Get a newer browser."
return
}
var ok_el = <input id=c type=button value=OK>
name_form_el = <div id=b> _"Welcome! What's your name?" <br> (name_el) (ok_el)
message_list_el = <div id=d> (create_loading_el())
var body_el = <input placeholder=_"Send message">
message_form_el = <div id=e> (body_el)
append_to_body(<div id=a> (name_form_el) (message_list_el) (message_form_el))
name_el.focus()
name_el.onkeydown = function(e) {
e = (e || event).which
if(e == 10 || e == 13) {
ok_el.click()
}
}
ok_el.onclick = function() {
clear_name_error()
name = name_el.value.replace(/^\s+|\s+$/g)
if(name) {
name_el.disabled = 1
ok_el.disabled = 1
if(socket_connected) {
send("name " + name)
}
} else {
add_name_error(_("Must be entered"))
}
}
body_el.onkeydown = function(e) {
e = (e || event).which
if(e == 10 || e == 13) {
var body = body_el.value
if(body) {
if(name_form_el) {
if(name_error_el) {
remove_el(name_error_el)
}
add_name_error(_("A name must be entered before sending a message"))
} else if(body == ".") {
start_video()
} else if(!pending_message_el) {
body_el.value = ""
send("message " + body)
pending_message_el = <div class=message> (<div class=message_timestamp> _"Pending") (<b> (cte(name))) (<div class=message_body> (cte(body)))
add_message(pending_message_el)
}
}
}
}
fit()
window.onresize = fit
connect()
}
function fit() {
message_list_el.style.height = innerHeight - (name_form_el ? name_form_el.offsetHeight : 0) - message_form_el.offsetHeight
}
function add_name_error(message) {
name_error_el = <div id=name_error> (cte(message))
ael(name_form_el, name_error_el)
fit()
name_el.focus()
name_el.oninput = clear_name_error
}
function clear_name_error() {
if(name_error_el) {
name_el.oninput = null
remove_el(name_error_el)
name_error_el = 0
fit()
}
}
function add_message(el) {
var scroll = message_list_el.scrollTop + message_list_el.clientHeight >= message_list_el.scrollHeight
ael(message_list_el, el)
if(scroll) {
message_list_el.scrollTop = message_list_el.scrollHeight
while(message_list_el.childNodes.length > 100) {
el = message_list_el.firstChild
remove_el(el)
for(var i in message_ids) {
if(message_ids[i] == e) {
delete message_ids[i]
}
}
}
}
}
function start_video() {
function onSuccess(stream) {
add_message(<div class=notice> _"Starting video communication succeeded.")
var video_el = <video height=240 style="left:0;position:absolute;top:248" width=320>
video_el.autoplay = 1
video_el.src = navigator.getUserMedia ? stream : webkitURL.createObjectURL(stream)
append_to_body(video_el)
var connection = new webkitPeerConnection("", function(signal) {
add_message(<div class=notice> (cte(_("Sent signal:") + " " + signal)))
send("signal " + signal)
})
connection.onopen = function() {
add_message(<div class=notice> _"Connection opened.")
}
connection.onaddstream = function(e) {
add_message(<div class=notice> _"Received incoming stream.")
var video_el = <video height=240 style="left:0;position:abssolute;top:0" width=320>
video_el.autoplay = 1
video_el.src = webkitURL.createObjectURL(e.stream)
append_to_body(video_el)
}
connection.addStream(stream)
peer_connection = connection
}
function onError() {
add_message(<div class=notice> _"Starting video communication failed.")
}
if(navigator.getUserMedia) {
navigator.getUserMedia({"audio": 1, "video": 1}, onSuccess, onError)
} else if(navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia("audio, video", onSuccess, onError)
} else {
add_message(<div class=notice> _"Video communication is not available in your browser.")
}
}
function connect() {
if(websocket) {
socket = new websocket("ws://" + location.host + "/websockets")
window.onunload = function() {
socket.close()
}
} else {
socket = long_poll_socket("long_poll")
}
if(socket) {
socket.onclose = socket_onclose
socket.onmessage = socket_onmessage
socket.onopen = socket_onopen
} else {
clear_el(message_list_el, <div class=notice> _"Failed to connect")
}
}
function set_ping_timeout() {
socket_ping_timeout = setTimeout(function() {
send("")
}, 50000)
}
function send(message) {
socket.send(message)
clearTimeout(socket_ping_timeout)
set_ping_timeout()
}
function socket_onclose() {
if(!socket_error) {
if(!socket_connected && websocket) {
websocket = 0
connect()
} else {
ael(message_list_el, <div class=notice> (cte(socket_connected ? _("The connection is broken.") : _("Failed to connect."))))
}
}
}
function socket_onmessage(e) {
var data = e.data
console.log("message", data)
if(data == "connected" && name_form_el) {
remove_el(name_form_el)
name_form_el = 0
fit()
return
}
var index = data.indexOf(" ")
var message_type = data.substr(0, index)
data = data.substr(index + 1)
if(message_type == "alert") {
add_message(<div class=notice> (cte(data)))
} else if(message_type == "error") {
socket_error = 1
add_message(<div class=notice> (cte(data)))
} else if(message_type == "message") {
data = data.split("\r")
var body_el = <div class=message_body>
body_el.innerHTML = data[3]
message_el = <div class=message> (<div class=message_timestamp> (cte(data[1]))) (<b> (cte(data[2]))) (body_el)
message_ids[data[0]] = message_el
add_message(message_el)
if(audio) {
audio.play()
}
} else if(message_type == "message_failed" && pending_message_el) {
add_message(<div class=notice> (cte(data)))
pending_message_el.firstChild.firstChild.innerText = _("Failed to send")
pending_message_el.firstChild.firstChild.textContent = _("Failed to send")
pending_message_el = 0
} else if(message_type == "message_ok" && pending_message_el) {
data = data.split("\r")
message_ids[data[0]] = pending_message_el
pending_message_el.firstChild.firstChild.innerText = data[1]
pending_message_el.firstChild.firstChild.textContent = data[1]
pending_message_el.lastChild.innerHTML = data[2]
pending_message_el = 0
} else if(message_type == "append") {
data = data.split("\r")
var message_el = message_ids[data[0]]
console.log("append", data[0], data[1], message_el)
if(message_el) {
var el = <div>
el.innerHTML = data[1]
ael(message_el.lastChild, el)
}
} else if(message_type == "signal") {
add_message(<div class=notice> (cte(_("Received signal:") + " " + data)))
if(peer_connection) {
// You call that with the received SDP packet (like through websocket)
peer_connection.processSignalingMessage(data)
}
}
}
function socket_onopen() {
socket_connected = 1
set_ping_timeout()
clear_el(message_list_el)
if(name) {
send("name " + name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment