Send message to disconnected user? - javascript

so, as you may know there is an admin-ui library (Idk what to call it) in socket.io.
what I want to do is if a client is kicked, send a message to that client (or have the client detect when it is disconnected)
i have tried:
socket.on('disconnect', function(){
alert('disconnected');
});
but that does nothing...

Found a fix using the socket attribute connected and setting an interval to check if the client is connected to a socket:
// client
let offline_alerted = false;
setInterval(function () {
if (socket.connected === false) {
if (offline_alerted === false) {
alert("Disconnected :(");
offline_alerted = true;
}
} else if (offline_alerted === true) {
alert("Reconnected!");
offline_alerted = false;
}
}, 1000);

Related

Notification API permission being reset

I am trying to make a chatroom and have everything up and running, but am getting stuck when it comes to desktop notifications. Whenever I request permission for notifications and get the access set to 'granted', the permission will reset to 'default' not allowing notifications to be displayed. Is there a way to get the permission to stay set as 'granted' or would I have to get them to keep allowing notifications every time a new message is sent? Is it a protection involved with running it as a local file (on ChromeOS)? Here is the code for the part about notifications:
function showNotification() {
var title = "New Message!";
var messageValueNotif = document.querySelectorAll(".message");
if (messageValueNotif.length !== 0) {
messageValueNotif = messageValueNotif[messageValueNotif.length - 1].innerHTML;
} else {
return false;
}
var currentFavicon = document.querySelector('link').href;
var notif = new Notification(title, {
body: messageValueNotif,
icon: currentFavicon
});
notif.onclick = () => {
notif.close();
window.parent.focus();
}
}
function requestAndShowPermission() {
if (Notification.permission === 'granted') {
showNotification();
} else if (Notification.permission !== 'denied') {
Notification.requestPermission().then(function(permission) {
showNotification()
});
}
}
window.onload = requestAndShowPermission();
It is apparently a file protection with ChromeOS.

Bot status changes temporary

I have PresenceUpdate Set so when a specific user streams the bot status updates and it announces in the channel. It did announce and it worked fine but the bot status seems to change for only ~20 seconds then it would go back to its default.
I've tried fixing it using:
For Loop
While Loop
Recursion function
Can anyone help me out and fix this? Here is my code:
client.on("presenceUpdate", (oldPresence, newPresence) => {
let announcement = "Announcement Message";
if (!newPresence.activities) return false;
newPresence.activities.forEach(activity => {
if (activity.type == "STREAMING") {
if(newPresence.user.id == "ID OF USER STREAMING") {
console.log(`${newPresence.user.tag} is streaming at ${activity.url}.`);
client.channels.cache.get("My Channel ID").send(announcement);
client.user.setActivity("to the server", { type: "STREAMING", url: "Twitch Link"});
};
};
});
});
EDIT: Okay so i managed to fix it by removing the part where if they r not streaming the status returns to default. HOWEVER, now it is stuck on streaming even when the user is no longer streaming. How do i solve this? The code has been also updated.
You could store the streaming user's id somewhere, and then check whenever the presence is update if it is this same user.
Here is an example :
if (client.streamingUserID !== undefined && client.streamingUserID !== newPresence.user.id) return;
newPresence.activities.forEach(activity => {
if (activity.type == "STREAMING") {
if(newPresence.user.id == "ID OF USER STREAMING") {
console.log(`${newPresence.user.tag} is streaming at ${activity.url}.`);
client.channels.cache.get("My Channel ID").send(announcement);
client.user.setActivity("to the server", { type: "STREAMING", url: "Twitch Link"});
client.streamingUserID = newPresence.user.id;
};
} else {
// set back activity to default and
delete client.streamingUserID;
}
});

Sorting socketing queries with IF statements?

(ws for node.js)
Like this;
socketserver.on('connection', function(socket) {
socket.on('message', function(data) {
// This is in eventone.html on /eventone
if(data == 'eventone') {
console.log("Event one triggered!");
socket.send(foo);
socket.close();
}
// This is in eventtwo.html on /eventtwo
if(data == 'eventtwo') {
console.log("Event two triggered!");
socket.send(bar);
socket.close();
}
// This is in eventthree.html on /eventthree
if(data == 'eventthree') {
console.log("Event three triggered!");
socket.send(foobar);
socket.close();
}
});
});
Is this a good idea for socketing data through one socketserver across different pages?
I want 'foo' to get sent to eventone.html, 'bar' to eventtwo.html and 'foobar' to eventthree.html, which are loaded on the client side, whenever the client sends the respective event through a button press (or whatever).
If this is a good idea, why would you ever use static routing and such things with request and response, why not just send everything through a socket?

Captcha popup if user comments too fast?

I'm working on a chat app with Meteor and I'm assuming spam will be an issue so I want to incorporate a Captcha that pops up if you comment too quickly (like more than 3 times in 5 seconds). I have the javascript code below but I have no idea how to do this. Is it possible to have a Captcha just pop up somewhere on the screen? If so, does anybody know how to do this? Here is the code for the chat app part:
Javascript:
// render all of our messages in the ui
Template.chatBox.helpers({
"messages": function() {
return chatCollection.find();
}
});
// get the value for handlerbar helper user
Template.chatMessage.helpers({
"user": function() {
if(this.userId == 'me') {
return this.userId;
} else if(this.userId) {
getUsername(this.userId);
return Session.get('user-' + this.userId);
} else {
return 'anonymous-' + this.subscriptionId;
}
}
});
// when Send Chat clicked at the message to the collection
Template.chatBox.events({
"click #send": function() {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
},
"keypress #chat-message": function(e) {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
if (e.which == 13) {
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
console.log("you pressed enter");
e.preventDefault();
//repeat function from #send click event here
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
}
});
chatStream.on('chat', function(message) {
chatCollection.insert({
userId: this.userId,
subscriptionId: this.subscriptionId,
message: message
});
});
This sounds like a great idea, but there are some issues with using a 'conditional captcha'. One being that the JavaScript doesn't have any way to persist beyond a page reload besides cookies and localStorage. So a simple reload and clearing of the cookies would defeat it. Not to mention how to handle it on the server, which isn't sure whether it should be expecting a valid captcha input or not.
With that caveat out of the way, you could set a global variable that acts as a 'timer' and just keeps track of the lapse. So replace the last block with:
chatStream.on('chat', function(message) {
//do we already have a timer?
if(typeof window.chatTimer == 'undefined'){
//no, so start one right now
window.chatTimer = new Date().getTime();
}else{
//we already have a timer. Is it 5 seconds old?
var now = new Date().getTime();
if( now - window.chatTimer < 5000) {
alert('Not so fast, tiger.');
return false;
}else{
chatCollection.insert({
userId: this.userId,
subscriptionId: this.subscriptionId,
message: message
});
}
This example uses reCaptcha, minus the custom stuff you would pass in.
Perhaps this has changed recently, but Spambots don't run JavaScript. They are kinda like search engine crawlers that follow links and look for form and textbox elements, and then knit their poison into a POST request to the form's action attribute, bypassing any JavaScript that wants to block it.
In fact, one of the alternatives to a captcha is simply to dynamically generate a hidden input with JavaScript that has an obscure ID/name that the server is waiting for. Spambots won't run this JavaScript, so the checkbox never gets made, so the bot gets rejected without knowing why. Here's more on that.
I have added some code to your code. I never use Meteor so I don't know whether this code is work or not in Meteor. But is test this by creating similes project here
Template.chatBox.events({
"click #send": function() {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
//Validation
var bot =Check_bots();
if(bot==false)
{
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
else
{
// Do whatever you want when a Bot detected
}
},
"keypress #chat-message": function(e) {
if (Meteor.user() == null) {
alert("You must login to post");
return;
}
if (e.which == 13) {
$('#messages').animate({"scrollTop": $('#messages')[0].scrollHeight}, "fast");
console.log("you pressed enter");
e.preventDefault();
//repeat function from #send click event here
var message = $('#chat-message').val();
chatCollection.insert({
userId: 'me',
message: message
});
$('#chat-message').val('');
//add the message to the stream
chatStream.emit('chat', message);
}
}
});
Here is the Validation Codes
<script type="text/javascript">
var lastintime=0;
var defference=0;
var msg_count=0;
function Check_bots()
{
var seconds = new Date().getTime() / 1000;
seconds=parseInt(seconds);
if(lastintime < seconds)
{
defference = seconds -lastintime;
lastintime=seconds;
if(defference<=5 && msg_count>=3)
{
return true;
}
else
{
return false;
}
}
}
</script>

How to check for internet connection without having to refresh my whole page

I want the following function to be called every x seconds, so I don't have to refresh my page.
var rq = new XMLHttpRequest();
rq.open('GET', "SAME DOMAIN ADDRESS", true);
rq.onreadystatechange = function() {
if(rq.readyState === 4) {
if(rq.status === 200) {
clearTimeout(xmlHttpTimeout);
window.location.href = "Tracker.html"; // if internet connection found, redirect.
} else {
}
}
};
rq.send("");
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
rq.abort();
// IF no internet connection found, call this whole javascript function/code AGAIN in 5 seconds! to check for internet connection
}
Basically, I want to check for internet connection without having to refresh my whole page - and if there is, then redirect to Tracker.html
Check if navigator.onLine is true or false.
The best approach is to use setTimeout:
function callMe() {
// Some Code
setTimeout(callMe, 1000);
}
callMe();
Your code will look like that:
var rq = new XMLHttpRequest();
rq.onreadystatechange = function() {
if(rq.readyState === 4) {
if(rq.status === 200) {
window.location.href = "Tracker.html"; // if internet connection found, redirect.
} else {
setTimeout(rq.send, 5000);
}
}
};
rq.send();
If you want to check if the client is connected you can also use the new online and offline events described here.
An ajax solution will only work on the same domain. However on the same domain you will probably not need to test whether the server is online. With navigator.onLine it will indicate whether the internet is accessible however still the appropriate server can be unreachable.
The trick is to try to load an image of the target server and on error then retry after 5 seconds. And when the image has been loaded successfully then a redirect could be done.
<html>
<header>
</header>
<body>
<script type="text/javascript">
var img = new Image();
var ping = function() { img.src = "http://www.somedomain.com/valid_image.jpg"; }
ping();
img.onerror = function(e) {
console.log('error');
setTimeout(function() {
ping();
}, 5000);
}
img.onload = function(e) {
console.log('YES');
window.location.href = "http://www.google.com";
}
</script>
</body>
</html>

Categories