Skip to content

Instantly share code, notes, and snippets.

@NaokiStark
Created March 10, 2015 06:11
Show Gist options
  • Save NaokiStark/9dd2b1d33fda58f9e9e2 to your computer and use it in GitHub Desktop.
Save NaokiStark/9dd2b1d33fda58f9e9e2 to your computer and use it in GitHub Desktop.
var nPp=null;
var showNoty= function(title,text,img, link){
if(NP==="granted"){
var opts= {body:text,icon:img};
nPp = new Notification(title,opts);
nPp.onclick=function(){
window.open(link);
this.close();
};
setTimeout(function(){nPp.close();},10000);
}
}
var getSocketDir = function(){
var rData;
$.ajax({
url: '/protocolo',
data:"",
async:false, //Wait for request
beforeSend: function(xhr, settings) {settings.url="/protocolo"; xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});},
success: function(r) {
var re = /Realtime\({"host":"([\d.]+)","port":([\d]+)}\)/ig;
var m;
while ((m = re.exec(r)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
rData={error:false,host:m[1],port:m[2]};
}
},
error: function() {
console.log('fail');
rData={error:true};
}
});
return rData;
}
var NP=Notification.permission;
if(NP != "granted"){
Notification.requestPermission();
NP=Notification.permission;
}
function clearQuotes(text){
var v = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
var vq = ["á", "é", "í", "ó", "ú", "Á", "É", "Í", "Ó", "Ú"];
for (a=0;a<v.length;a++){
text= text.replace("&" + v[a] + "acute;",vq[a]);
}
text = text.replace( "&Ntilde;", "Ñ");
text = text.replace( "&ntilde;", "ñ");
text = text.replace( "&iquest;", "¿");
text = text.replace("&quot;", '"');
return text;
}
//Creamos el ws, gracias taringa de mierda
var coco;
function openWs(ioi){
var chnn=localStorage.Realtime_channels.split(':')[0].replace('{','').replace('"','').replace('"','');
coco = new WebSocket('ws://' + ioi.host + ':' + ioi.port + '/ws/' + chnn);
coco.onmessage = function(msg){
//console.log(msg.data); //Awesome!
var pM=$.parseJSON(msg.data);
if((pM.text.event.actionName=='new-message' && pM.text.event.feedName=='realtime')||pM.text.event.feedName=='notification'){
//Launch notify
var regex = /(<([^>]+)>)/ig, body = pM.text.event.shortText, result = body.replace(regex, "");
var avatar='http://www.taringa.net/avatar.php?user='+pM.text.event.image.href.replace('/','');
showNoty('Taringa',clearQuotes(result),avatar,'http://www.taringa.net/feed-markAsRead.php?feedName='+pM.text.event.feedName+'&id='+pM.text.event.id+'&to='+pM.text.event.object.link);
//The End
}
}
coco.onopen = function(){
console.log("Ws open");
}
coco.onclose = function(){
console.log("Ws closed, reconnecting");
openWs(ioi);
}
}
var ioi;
$(document).ready(function(){
ioi= getSocketDir();
if(!ioi.error){
openWs(ioi);
}
else{
console.log("error");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment