Skip to content

Instantly share code, notes, and snippets.

@zacck-zz
Created August 20, 2018 04:35
Show Gist options
  • Save zacck-zz/d549b820262f4ecfb8a234eddff91fcd to your computer and use it in GitHub Desktop.
Save zacck-zz/d549b820262f4ecfb8a234eddff91fcd to your computer and use it in GitHub Desktop.
// Brunch automatically concatenates all files in your
// watched paths. Those paths can be configured at
// config.paths.watched in "brunch-config.js".
//
// However, those files will only be executed if
// explicitly imported. The only exception are files
// in vendor, which are never wrapped in imports and
// therefore are always executed.
// Import dependencies
//
// If you no longer want to use a dependency, remember
// to also remove its path from "config.paths.watched".
import "phoenix_html"
// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".
// import socket from "./socket"
import {Socket, Presence} from "phoenix"
let user = document.getElementById("user").innerText
let socket = new Socket("/socket", {params: {user: user}})
socket.connect()
//////////////////////////// for video 1a
let localStream, peerConnection;
let localVideo,remoteVideo,connectButton,callButton,hangupButton;
if(window.location.pathname !="/group"){
localVideo = document.getElementById("localVideo");
remoteVideo = document.getElementById("remoteVideo");
connectButton = document.getElementById("connect");
//callButton = document.getElementById("call");
hangupButton = document.getElementById("hangup");
hangupButton.disabled = true;
//callButton.disabled = true;
connectButton.onclick = connect;
//callButton.onclick = call;
hangupButton.onclick = hangup;
}
//////////////////////////////////
////presence
let presences = {}
let formatTimestamp = (timestamp) => {
let date = new Date(timestamp)
return date.toLocaleTimeString()
}
let listBy = (user, {metas: metas}) => {
let my_username=document.getElementById("user").innerHTML;
if(document.getElementById("userid").value == "")
document.getElementById("userid").value=(metas[0].phx_ref).replace(/\//g, "-");
return {
user: user,
user_id: (metas[0].phx_ref).replace(/\//g, "-"), //generateUUID(),//metas[0].phx_ref,
onlineAt: formatTimestamp(metas[0].online_at)
}
}
let userList = document.getElementById("UserList")
let render = (presences) => {
userList.innerHTML = Presence.list(presences, listBy)
// .map(presence => `
// <li>
// ${presence.user}
// <br>
// <small>online since ${presence.onlineAt}</small>
// </li>
// `)
.map(presence => `
<li>
<button id="${presence.user_id}" name="btnOnline" onclick="goto_single_user('${presence.user_id}', '${presence.user}')">
${presence.user}
</button>
<br>
<small>online since ${presence.onlineAt}</small>
</li>
`)
.join("")
let user_id=document.getElementById("user").innerHTML;
var my_buttons= document.getElementsByName("btnOnline");
var i=0;
//console.log(my_buttons[0].innerText + "-------" + user_id);
for(i=0; i< my_buttons.length; i++){
if(user_id == my_buttons[i].innerText){
my_buttons[i].disabled=true;
}
}
}
// Channels
let room = getchannel();
room.on("presence_state", state => {
presences = Presence.syncState(presences, state)
render(presences)
})
room.on("presence_diff", diff => {
presences = Presence.syncDiff(presences, diff)
render(presences)
})
room.join()
.receive("ok", resp => { console.log("Successfully joined channel", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
/////////////////////////// video 1b
function connect() {
console.log("Requesting local stream");
navigator.getUserMedia({audio:true, video:true}, gotStream, error => {
console.log("getUserMedia error: ", error);
});
room.push("message:new", "<span style='color:red'>Initiating video call, if you are on the other side please cick on the connect button</span>");
}
function gotStream(stream) {
console.log("Received local stream");
localVideo.src = URL.createObjectURL(stream);
localStream = stream;
setupPeerConnection();
}
function setupPeerConnection() {
connectButton.disabled = true;
//callButton.disabled = false;
hangupButton.disabled = false;
console.log("Waiting for call");
let servers = {
"iceServers": [{
url: "turn:numb.viagenie.ca",
username: "[email protected]",
credential: "alphabeta1"
}]
};
peerConnection = new RTCPeerConnection(servers);
console.log("Created local peer connection");
peerConnection.onicecandidate = gotLocalIceCandidate;
peerConnection.onaddstream = gotRemoteStream;
peerConnection.addStream(localStream);
console.log("Added localStream to localPeerConnection");
call()
}
function call() {
//callButton.disabled = true;
console.log("Starting call");
room.push("message:new", "Call clicked by the other user");
peerConnection.createOffer(gotLocalDescription, handleError);
}
function gotLocalDescription(description){
peerConnection.setLocalDescription(description, () => {
room.push("message", { body: JSON.stringify({ /// change here
"sdp": peerConnection.localDescription
})});
}, handleError);
console.log("Offer from localPeerConnection: \n" + description.sdp);
}
function gotRemoteDescription(description){
console.log("Answer from remotePeerConnection: \n" + description.sdp);
peerConnection.setRemoteDescription(new RTCSessionDescription(description.sdp));
peerConnection.createAnswer(gotLocalDescription, handleError);
}
function gotRemoteStream(event) {
remoteVideo.src = URL.createObjectURL(event.stream);
console.log("Received remote stream");
}
function gotLocalIceCandidate(event) {
if (event.candidate) {
console.log("Local ICE candidate: \n" + event.candidate.candidate);
room.push("message", {body: JSON.stringify({
"candidate": event.candidate
})});
}
}
function gotRemoteIceCandidate(event) {
//callButton.disabled = true;
if (event.candidate) {
peerConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
console.log("Remote ICE candidate: \n " + event.candidate.candidate);
}
}
room.on("message", payload => {
let videomessage = JSON.parse(payload.body);
if (videomessage.sdp) {
gotRemoteDescription(videomessage);
} else {
gotRemoteIceCandidate(videomessage);
}
})
function hangup() {
console.log("Ending call");
localStream.getVideoTracks()[0].stop();
peerConnection.close();
localVideo.src = null;
peerConnection = null;
hangupButton.disabled = true;
connectButton.disabled = false;
//callButton.disabled = true;
}
function handleError(error) {
console.log(error.name + ": " + error.message);
}
////////////////////////
///chat
let messageInput = document.getElementById("NewMessage")
messageInput.addEventListener("keypress", (e) => {
if (e.keyCode == 13 && messageInput.value != "") {
var returnedMsg=checkForYouTubeLink(messageInput.value);
room.push("message:new",returnedMsg) //messageInput.value)
messageInput.value = ""
}
})
let messageList = document.getElementById("MessageList")
let renderMessage = (message) => {
message.body=checkforprivatechatmessage(message.body);
let messageElement = document.createElement("li")
messageElement.innerHTML = `
<b style="color: green">${message.user} : </b>
<b>${message.body}</b>
<p>${formatTimestamp(message.timestamp)}</p>
`
$("#MessageList").animate({ scrollTop: 0 }, "fast");
if(messageList.firstChild) {
messageList.insertBefore (messageElement ,messageList.firstChild)
}else messageList.appendChild(messageElement)
messageList.scrollTop = messageList.scrollHeight;
}
room.on("message:new", message => renderMessage(message))
//add user name
///var name=null
function getchannel(){
console.log(window.location.pathname);
if(window.location.pathname != "/group"){
let a= window.location.pathname;
console.log(a);
var splitUrl = a.split('/');
let uid=splitUrl[2];
return socket.channel("priv:" + uid)
}else{
return socket.channel("room:group")
}
}
//export { getchannel };
function generateUUID() { //not used
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
};
function checkForYouTubeLink(message){
var total_seconds=0;
if(message.indexOf("$$start-") > -1){
var with_time=message.replace("$$start-","");
var linkAndTime= with_time.split(" ");
var startandendtime=linkAndTime[1].split("-");
var starttime=startandendtime[0].split(":");
var endtime=startandendtime[1].split(":");
var total_start_seconds= parseInt(starttime[0]) * 60 + parseInt(starttime[1]);
var total_end_seconds= parseInt(endtime[0]) * 60 + parseInt(endtime[1]);
console.log(total_start_seconds + "---------"+ total_end_seconds);
}
var other_link= message.match(/(\b(https?|ftp|file|http):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig);
//https://www.youtube.com/watch?v=KVz2VkaaDfA
if(other_link){
var match=message.match(/(http:|https:)?\/\/(www\.)?(youtube.com|youtu.be)\/(watch)?(\?v=)?(\S+)?/);
if(match){
var embeded_link=match[0].replace("watch?v=", "embed/");
console.log(embeded_link);
var generated_html=`<iframe width="560" height="315" src=${embeded_link}?start=${total_start_seconds}&end=${total_end_seconds} frameborder="0" allowfullscreen></iframe>`
return generated_html;
}else{
return `<a href=${message}>${message}</a>`
}
}else{
return message;
}
}
function checkforprivatechatmessage(message){
if(message.indexOf("privatemsgid---") > -1){
message=message.replace("privatemsgid---","");
if((document.getElementById("userid").value) == message){
return `<a id='${message}' name='priv_msg' href='../private/${message}'> Lets talk in private </b> </a>`;
}else
return "<i>Secret message for some user</i>";
}else{
return message;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment