How to send an alert message to a special online user with firebase - multiplayer

I'm trying to make a "FourConnect"-game with javascript. I want, that there is a list from all online users. This list I've made with the example on the firebase site. Now I want that I can choose one online user and send them a invitation to play with me.
So I wrote a function, that all users expect of me have an additional div. When I click on the div this special user should get a confirm box to say okey or cancel. If the user clicks okey the play should begin.
I'll save the name and the id from the user. This already works.
My problem is, that I don't know how to send the request to the other user. I tried out many but always the confirm box is on my brwoser not on the browser of the other user.
I looked for solutions on the firebase page and in google but couldn't find anything which solves my problem.
The code I already have:
var name = prompt("Your name?", "Guest"),
currentStatus = "★ online";
// Get a reference to the presence data in Firebase.
var userListRef = new Firebase(connectFour.CONFIG.firebaseUrl);
// Generate a reference to a new location for my user with push.
var myUserRef = userListRef.push();
var gameId = myUserRef.name();
document.getElementById('labelGameId').innerHTML = gameId;
beginGame({id: gameId, name: name, status: currentStatus});
// Get a reference to my own presence status.
var connectedRef = new Firebase('http://presence.firebaseio-demo.com/.info/connected');
connectedRef.on("value", function(isOnline) {
if (isOnline.val()) {
// If we lose our internet connection, we want ourselves removed from the list.
myUserRef.onDisconnect().remove();
// Set our initial online status.
setUserStatus("★ online");
} else {
// We need to catch anytime we are marked as offline and then set the correct status. We
// could be marked as offline 1) on page load or 2) when we lose our internet connection
// temporarily.
setUserStatus(currentStatus);
}
});
//}
// A helper function to let us set our own state.
function setUserStatus(status) {
// Set our status in the list of online users.
currentStatus = status;
myUserRef.set({ name: name, status: status });
}
// Update our GUI to show someone"s online status.
userListRef.on("child_added", function(snapshot) {
var user = snapshot.val();
$("#output").append($("<div/>").attr("id", snapshot.name()));
$("#" + snapshot.name()).text(user.name + " is currently " + user.status);
if(snapshot.name() != myUserRef.name()){
var $invite = $('<div id="invite">invite</div>');
$("#output").append($invite);
$($invite).on('click', function(){
//startGame(user);
console.log('Gegner2: '+snapshot.name());
console.log('Genger2Name: '+user.name);
joinGame({id: snapshot.name(), name: user.name, status: user.status});
});
}
});
// Update our GUI to remove the status of a user who has left.
userListRef.on("child_removed", function(snapshot) {
$("#" + snapshot.name()).remove();
});
// Update our GUI to change a user"s status.
userListRef.on("child_changed", function(snapshot) {
var user = snapshot.val();
$("#" + snapshot.name()).text(user.name + " is currently " + user.status);
});
document.onIdle = function () {
setUserStatus("☆ idle");
}
document.onAway = function () {
setUserStatus("☄ away");
}
document.onBack = function (isIdle, isAway) {
setUserStatus("★ online");
}
setIdleTimeout(5000);
setAwayTimeout(10000);
function joinGame(opponent) {
console.log(opponent);
console.log(opponent.id);
var player2ID = opponent.id;
myUserRef = new Firebase(connectFour.CONFIG.firebaseUrl + opponent.id);
myUserRef.once('value', function(dataSnapshot){
if(dataSnapshot.val()){
beginGame({id: player2ID , name: opponent.name, status: opponent.status});
}else{
alert("game doesn't exist");
}
});
}
function beginGame(player) {
console.log(player);
console.log('Id spieler1: '+gameId);
});
With this code I can click on "invite" and then I will see the ID which the user had. I also wanted to send the ID to beginGame() but this doesn't really works.
My Firebase Structure:
games
-InmydEpSe5oZcLZUhfU
-InrLM6uxAsoOayOgFce
-name: "Barbara"
-status: "away"

In order to send a message to another user, you need that user to be monitoring a known location in your Firebase. Then when you want to send them a message, you simply modify that location in some way and they'll get a callback. Here's some pseudo code:
var root = new Firebase(...);
//On initialization start listening for messages
root.child("users/inbound-messages").on("child_added",
function(newMessageSnapshot) {
displaySomethingToTheUser(newMessageSnapshot.val());
newMessageSnapshot.ref().remove();
}
);
//Send a message to another user
root.child(otherUserId).child("inbound-messages").push("Hi other user!");

From what I understand. You want a chat window in the game so that users logged to communicate among themselves, okay?
Well, in its structure, you simply add something like:
-Games
    -rooms
     -charOfRoomSpecific
         - users
            
             + InmydEpSe5oZcLZUhfU
              -InrLM6uxAsoOayOgFce
                     name: "Barbara"
                     status "away"
         
       - messages
           + InmyBlaBlae5oZcLPKSu
           -InmyBlaBlae5oZcLPKSu2
                user: "Barbara"
                say: "Hello man, will gamer!"
     + charOfRoomSpecific2
     + charOfRoomSpecific3
     ...
So, for your users in the room can read the message simply:
FirebaseRef.child ("rooms/charOfYourRoomSpecific/messages");
And everyone who has access to this room will see in real time their conversations.

Related

Google Meet: How can i catch the url?

I need to open a new google meet room, and send it. I can't use standard "share" button in app. I need to catch the final url.
I can't catch that with curl (it's not a normal redirect).
My idea is that i need to open a request/link in background or in the same page, wait some second and catch the link, after i can release the page and user can enter.
Do you know something that can help me?
Edit:
Yes, i had miss to tell that i need to generate a room from a click and catch the url from code. Generally, i should to make this with Google Calendar API, but in this case i can't.
I use google Calendar API. I make a webApp for my organization, that from a form (with user information to send togheter meet link) make a google calendar event with google meet room (from google loggedin user account), catch the link and send it by a smsGateway.
function FormForMeet (Args) {
// get calendar name, if it already exists
var meetsCalendar = CalendarApp.getCalendarsByName ('CalendarName');
Logger.log (meetsCalendar.length)
if (meetsCalendar.length> = 1) {
// if some calendar be found, it catch the first, obviously here you can use some differet method. I had choose this because I don't expect to find more than 1
var calendar = meetsCalendar [0] .getId ();
}
else
{
// If miss, create new one.
var calendar = CalendarApp.createCalendar ('CalendarName', {summary: 'descrip Calendar',
// set a color of calendar label :D
color: CalendarApp.Color.PURPLE});
calendar = calendar.getId ();
}
// Call function to create meet
var LinkMeet = CreateConference_ (calendar);
// here you can use what you want for send Args + LinkMeet);
// if you want return link
return LinkMeet;
}
// Function to create Conference. You can obviously use the code up without make a new function.
function CreateConference_ (calendarId) {
// Custom of event, here I created the conferences according to my needs (now, with 1 h / conference)
var now = new Date ();
var start = new Date (now.getTime ()). toISOString ();
var end = new Date (now.getTime () + (1 * 60 * 60 * 1000)). toISOString ();
// generate random string to request
var rdmreqId = genStrg ();
var event = {
"end": {
"dateTime": end
},
"start": {
"dateTime": start
},
"summary": "conferenceName",
"conferenceData": {
"createRequest": {
"conferenceSolutionKey": {
"type": "hangoutsMeet"
},
"requestId": rdmreqId
}
}
};
// insert event in calendar
event = Calendar.Events.insert (event, calendarId, {
"conferenceDataVersion": 1});
// if use the function you can return the link to send
return event.hangoutLink
}
// random strind
function genStrg () {
var data = "something";
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789! # # $% & <> * -";
for (var j = 2; j <= data.length; j ++) {
text = ""; // Reset text to empty string
for (var i = 0; i <possible.length; i ++) {
text + = possible.charAt (Math.floor (Math.random () * possible.length));
}
return text;
}
}
all google meet links look something like this:
https://meet.google.com/abc-defg-hij
You should be able to just copy and paste this link from your browser page. If someone enters this link, they will be taken to the meet lobby and they can enter at any time.
If you can't access this link for some reason, like if you're on mobile, you have to put your meet code (the abc-defg-hij) at the end of the aforementioned url.
edit: You actually can find the link if you're on mobile by going into your meeting lobby and scrolling down until you get to "joining information". Under that there should be the meeting link and the numbers to join by phone.

Google Classroom API : Unable to receive push notifications for courseworks and student submissions (COURSE_WORK_CHANGES)

We are seriously blocked. We have followed the documentation below (among many others) to set up the pub/sub pipelines, create service accounts, assign permissions and use the right scopes and feed types for registrations.
https://developers.google.com/classroom/guides/push-notifications
So programmatically we are able to do the following in .net using the API :
We can Create Courses
We can create registrations for a given courseid
We create/update courseworks for the course that we have created a registration.
All good so far,
BUT, we don't receive notifications for that created/update course work.
some code for clarity :
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer("sa-something#precise-asset-259113.iam.gserviceaccount.com")
{
User = "impersonated user",
Scopes = new string[] { "https://www.googleapis.com/auth/classroom.coursework.students" ,
"https://www.googleapis.com/auth/classroom.courses",
"https://www.googleapis.com/auth/classroom.push-notifications" }}
.FromPrivateKey("My private key"));
//Authorize request
var result = credential.RequestAccessTokenAsync(CancellationToken.None).Result;
var service = new ClassroomService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
});
// We get courses
var courses = service.Courses.List().Execute();
// We get one course for registration
var course = courses.Courses.First();
// We create registration
var registration = service.Registrations.Create(new Google.Apis.Classroom.v1.Data.Registration()
{
Feed = new Google.Apis.Classroom.v1.Data.Feed()
{
FeedType = "COURSE_WORK_CHANGES",
CourseWorkChangesInfo = new Google.Apis.Classroom.v1.Data.CourseWorkChangesInfo()
{
CourseId = course.Id
},
},
CloudPubsubTopic = new Google.Apis.Classroom.v1.Data.CloudPubsubTopic()
{
TopicName = "projects/precise-asset-259113/topics/test"
},
});
//Successful response - We get a registrationID
var response = registration.Execute();
var courseWork = new CourseWork()
{
CourseId = course.Id,
Title = "Ver Test",
Description = "Calculus",
WorkType = "ASSIGNMENT",
MaxPoints = 20.0,
State = "PUBLISHED",
AlternateLink = "www.uni.com",
CreatorUserId = course.OwnerId,
CreationTime = DateTime.UtcNow,
DueTime = new TimeOfDay() { Hours = 5, Minutes = 10, Nanos = 10, Seconds = 10 },
DueDate = new Date() { Day = 3, Month = 12, Year = 2019 },
Assignment = new Assignment() { StudentWorkFolder = new DriveFolder() { AlternateLink = "Somewhere", Title = "My Calculus" } }
};
//Create course work for the course that we registered
var courseWorkResponse = service.Courses.CourseWork.Create(courseWork, course.Id).Execute();
SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
SubscriptionName subscriptionName = new SubscriptionName("precise-asset-259113", "test");
PullResponse pullResponse = subscriber.Pull(
subscriptionName, returnImmediately: true, maxMessages: 20);
// Check for push notifications BUT ....NADA!!!
foreach (ReceivedMessage msg in pullResponse.ReceivedMessages)
{
string text = Encoding.UTF8.GetString(msg.Message.Data.ToArray());
Console.WriteLine($"Message {msg.Message.MessageId}: {text}");
}
Can you please assist?
Thanks
There are several things you need to change in order to ensure you get the notifications:
You need to create your subscription before you send the request that will generate the Pub/Sub message. Only messages published after the successful creation of a subscription are guaranteed to be received by subscribers for that subscription.
A single pull request with returnImmediately set to true is unlikely to return any messages, even if a message has been published. With this property set, if there are no messages immediately in memory of the server reached, the empty response is returned. You should always set returnImmediately to false. This still won't guarantee that messages are returned in a single request/response, even if there are messages available, but it will make it more likely.
Ideally, you would use the asynchronous client library, which opens a stream to the Cloud Pub/Sub service and receives messages as soon as they are available. If you are going to use the synchronous Pull method directly, then you need to keep many of them outstanding simultaneously in order to ensure delivery of messages with minimal latency. As soon as you receive a PullResponse for any of the outstanding requests, you should immediately open up another request to replace it. The goal of the asynchronous client library is to prevent one from having to take all of these step manually to ensure efficient delivery.

In Sharepoint how to get list advanced settings for Opening Documents in the Browser using REST API

Using REST API i want to access this
Settings >> Advanced Settings >> Opening Documents in the Browser
Can anybody know about this?
Thanks
In SSOM this feature corresponds to SPList.DefaultItemOpen property:
Gets or sets a value that specifies whether to open list items in a
client application or in the browser.
In REST/CSOM this property is not exposed but it could be extracted and determined via List schema Xml. For more details about this approach follow this post.
Example
The following example demonstrates how to determine whether to open list items in a client application or in the browser using REST API:
function schemaXml2Json(schemaXml)
{
var jsonObject = {};
var schemaXmlDoc = $.parseXML(schemaXml);
$(schemaXmlDoc).find('List').each(function() {
$.each(this.attributes, function(i, attr){
jsonObject[attr.name] = attr.value;
});
});
return jsonObject;
}
function getDefaultItemOpen(webUrl,listTitle)
{
var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')?$select=schemaXml";
return $.getJSON(endpointUrl).then(function(data){
var listProperties = schemaXml2Json(data.SchemaXml);
var flags = parseInt(listProperties.Flags);
var defaultItemOpen = (flags & 268435456) != 0 ? "Browser" : "PreferClient";
return defaultItemOpen;
});
}
Usage
getDefaultItemOpen(_spPageContextInfo.webAbsoluteUrl,'Documents')
.done(function(value){
console.log('DefaultItemOpen: ' + value);
});

Chat application using CFWebsocket

How can we develop a facebook like chat application using cfwebsocket. There is no description about how to send an user entered message to the server and how to send that message to a particular client from the server.
<script type="text/javascript">
function mymessagehandler(aevent, atoken)
{
console.log(aevent);
console.log(atoken);
var message = aevent.msg;
var txt=document.getElementById("myDiv");
txt.innerHTML = txt.innerHTML + message +"<br>";
}
</script>
<cfwebsocket name="mycfwebsocketobject" onmessage="mymessagehandler" subscribeto="stocks" >
<cfdiv id="myDiv"></cfdiv>
The above code just prints ok in the display. I am not sure how to pass my message inside the stocks object. Can anyone help on this? Thanks in advance
This is the stocks application that I am using
this.wschannels = [ {name="stocks", cfclistener="myChannelListener" }];
This is what I have did to make my chat application work
This is the chat application
<cfwebsocket name="ChatSocket" onOpen="openHandler" onMessage="msgHandler" onError="errHandler">
This is the script
function openHandler(){
//Subscribe to the channel, pass in headers for filtering later
ChatSocket.subscribe('chatChannel',{name: 'TheUserName', UserID: 'TheUserID', AccountID: 'AnUniqueID' });
}
// function to send the message. we can call this when the user clicks on send message
function publish(userID){
var msg = {
AccountID: "AnUniqueID",
publisher: userID,
id: userID,
message: document.getElementById("Name").value + " : " + document.getElementById("message").value
};
//When including headers, the "selector" is where you will filter who it goes to.
var headers = {
AccountID: "AnUniqueID",
publisher: userID,
id: userID
};
// we can save the chat history by an ajax call here
ChatSocket.publish('chatChannel',msg, headers);
}
// this is the receiving function
function msgHandler(message){
// if condition to display the message to the user who are sending and receiving
if(message.data !== undefined && message.data.message !== undefined && (message.data.id == '#session.userID#' || message.data.publisher == '#session.userID#')) {
var data = message.data.message;
console.log(data);
//showing the message
var txt=document.getElementById("myDiv");
txt.innerHTML+= data + "<br>";
}
}
function errHandler(err){
console.log('err');
console.log(err);
}

FB.login cancel button do a redirect

currently i have a page under http://mydomain.com/me/myself/1234
on this page i've included a custom share link, to share information on this page to facebook.
imagine that you're not logged into facebook but in my application and you come to the above page. If you click on the link a FB login pop up appears to give you a chance to authenticate. my code for posting to the wall looks like this:
function loggedIn() {
if (typeof(FB) != 'undefined' && FB != null ) {
FB.login(function(response) {
if (response.session || response.authResponse) {
postToWall();
} else {
return false,
}
}, {scope: 'publish_stream'});
return false;
}
}
function postToWall() {
var prodName= 'test';
var prodPic = 'test.jpg';
var linkUrl = 'http://mydomain.com/me/myself/1234';
var tmpObj = new Object();
tmpObj.value = "CUSTOM";
tmpObj.friends = "ALL_FRIENDS";
var wallPost = {
message : " I've seen a " + prodName ,
picture : prodPic,
link: linkUrl,
name: "the name",
description: "a little description",
privacy: tmpObj
};
FB.api('/me/feed', 'post', wallPost , function(response) {
if (!response || response.error) {
//alert('Error occured');
} else {
//alert('Post ID: ' + response);
}
});
}
So, the only issue now is: if i click the cancel button on the login dialog, i get redirected to my .com page http://mydomain.com. what i need is to stay on the same page. I don't see the error i'm doing.
Would appreciate any help.
best regards,
Ramo
I don't understand why you have a function called loggedIn() calling a function called postToWall(). You might want to refactor or rename the loggedIn() function.
You did not post the event handler code for your button. However, if you are catching the click event but not returning false then not only will the facebook login window get shown, but the normal thing that occurs when you click on a link on a web page will also happen. That said, it doesn't sound like that's the problem but please post more code so that we may know for sure.