Pubnub One to One Chat Sending Message to all users - javascript

This is My Pubnub Chat Code
var pubnub = PUBNUB.init({
publish_key : 'my_key',
subscribe_key : 'sub-key'
});
pubnub.subscribe({
channel : "{{$channel}}",
message : function(m){
$(".conversation-list").append(
'<li class="clearfix '+ m.clearifix +' ">' +
'<div class="chat-avatar">' +
'<img src="' + m.image + '">'+
'<i> {{date('h:i')}} </i>' +
'</div>' +
'<div class="conversation-text">' +
'<div class="ctext-wrap">' +
'<i> '+ m.name + '</i>' +
'<p>' + m.message + '</p>' +
'</div>' +
'</div>' +
'</li>'
).animate({scrollTop: $(".conversation-list")[0].scrollHeight}, 0);
$('.reply-text').val('');
},
//connect : publish
});
$('.send-reply-to-user').on('click', function (e) {
e.preventDefault();
if ($('.reply-text').val()== '')
return false;
else
console.log(pubnub.publish);
// console.log(this);
var user_to_id = $(".send-reply-to-user").attr('user_to_id');
var message = $('.reply-text').val();
var name = $('#user_name').val();
var image = document.getElementById("user_image").getAttribute("src");
var clearifix = $('#user_clearifx').val();
pubnub.publish({
channel : "{{$channel}}",
message: { name : name, message : message, image : image, clearifix : clearifix }
});
if ($.trim(message).length != 0) {
$.ajax({
url: '{{route('send:user:chat:message')}}',
cache: false,
method: 'POST',
data: {user_to_id: user_to_id, message: message, _token: '{{csrf_token()}}'},
beforeSend: function () {
},
success: function (result) {
}
})
}
});
This code is Working perfectly only problem is that messages are going to all users, I want to send msg to one to one user.
Example: User one: John send a message to User two Deo,
Example 2: John sends a message to Marry
and so on. Using Pubnub JS API, Backend as Laravel 5.6

I recommend using PubNub's opinionated JavaScript framework called ChatEngine. It takes away a lot of the heavy lifting involved with making chat with PubNub. Here is some example code to get you started making 1:1 private chats. Make sure you use the setup button to prepare the backend on your account.
<script src="https://cdn.jsdelivr.net/npm/chat-engine#0.9.5/dist/chat-engine.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Init ChatEngine with PubNub
const publishKey = '__Your_PubNub_Publish_Key__';
const subscribeKey = '__Your_PubNub_Subscribe_Key__';
const ChatEngine = ChatEngineCore.create({
publishKey,
subscribeKey,
}, {
globalChannel: 'global',
});
const user = {
uuid: 'randomstringofchars',
name: 'John Smith'
}
const chats = {};
ChatEngine.connect(user.uuid, user);
ChatEngine.on('$.ready', function(data) {
// store my new user as `me`
let me = data.me;
// returns a ChatEngine chat object
function makePrivateChat(theirUserId) {
const chatKey = [theirUserId, me.uuid].sort().join('-');
// Don't make the same 1:1 chat if it already exists
if (chats[chatKey]) {
return;
}
// true for private chat
const chat = new ChatEngine.Chat(chatKey, true);
chats[chatKey] = chat;
}
// Auto add a 1:1 chat to UI when invited by someone
me.direct.on('$.invite', makePrivateChat);
// Define a button for making new 1:1 chats in your UI
newOneToOneChatButton.on('click', function (event, theirUserId) {
someChatObject.invite(theirUserId);
});
});
</script>

Finally Fixed My issue, the private Channels working good , Actually problem was with my back-end. It was returning data from all the users i have fixed now its working fine.

Related

My code has a simple issue that i cant figure out

I am setting up a link for my web page to take me to another site.
Ive tried everything i know how to do . my knowledge is limited though. basically when you visit https://beatsbycayde.com/roster/ it should take you to
"https://braytech.org/2/{destinyId}/{characterId}/legend"
for some reason it doesnt And I cannot figure out why any help would be greatly appreciated it it instead takes you to
https://braytech.org/2/{destinyId}/fstats/legend
I know that i have fstats in there iam trying to us it as an object and call it in the href
// get list of members and populate roster table
var roster = [];
$.when($.ajax({
url: "https://www.bungie.net/platform/GroupV2/699392/Members/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
}
}).success(function(json) {
if (json.ErrorStatus === 'Success') {
roster = json.Response.results;
console.log('Exalted member list:', roster);
} else {
alert('Uh oh, looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(json);
}
}).error(function(json) {
alert('Uh oh, looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(json);
}), $.ajax({
url: 'https://www.bungie.net/platform/destiny2/2/profile/4611686018429000034/?components=200',
headers: {
'X-API-Key': "47b810e692d64237911c2cbe0d433cfe"
}
}).success(function(res) {
console.log('PS4 stats:', res);
})).then(function() {
listMembers(roster);
});
function listMembers(rsp) {
var list = $('.memberList-list'),
on = 0,
sortMembers = function(method) {
// sort by date joined
if (method = joined) {
list.find('.member').sort(function(a, b) {
return ($(b).data('joined')) < ($(a).data('joined')) ? 1 : -1;
}).appendTo(list);
} else if (method = username) {
list.find('.member').sort(function(a, b) {
return ($(b).data('username')) < ($(a).data('username')) ? 1 : -1;
}).appendTo(list);
}
list.find('.member.online').prependTo(list);
};
for (var i = 0; i < rsp.length; i++) {
var profile = rsp[i].bungieNetUserInfo,
member = $('<a></a>');
// tally up online members
if (rsp[i].isOnline) {
on++
}
// check for valid profile
// some users don't have Bungie profiles somehow and it breaks function
if (typeof profile != 'undefined') {
// store response data in semantic variables
var name = rsp[i].destinyUserInfo.displayName,
joinDate = rsp[i].joinDate,
joined = joinDate.substring(0, joinDate.indexOf('T')),
online = rsp[i].isOnline,
icon = profile.iconPath,
memberId = profile.membershipId,
memberType = rsp[i].destinyUserInfo.membershipType,
destinyId = rsp[i].destinyUserInfo.membershipId,
rank = rsp[i].memberType;
// configure D OM node and add to page
$('#destiny-Id').text(destinyId);
$.ajax({
url: "https://www.bungie.net/Platform/Destiny/2/Account/" + destinyId + "/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
}
}).done(function(json) {});
$(function() {
$.ajax({
url: "https://www.bungie.net/Platform/Destiny/2/Account/4611686018429000034/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
},
success: function(data) {
// Gambit stats
var fstats = data.Response.data.characters[0].characterBase.characterId;
// Populate stats
// pvp
$('#player-f-stats').text(fstats);
},
error: function(data) {
alert('Uh oh, failed to load player stats! Looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log('Error loading player stats:', data);
}
});
});
member.attr({
'class': 'j-row vertical-center-row member',
'href': '/player/?bungieId=' + memberId + '&destinyId=' + destinyId + '&joined=' + joined + '&rank=' + rank,
'title': 'See player profile for ' + name,
'data-joined': joined.replace(/-/g, ''),
'data-username': name,
'data-online': 'false',
'data-searchable': name,
}).html('<div class="j-col j-col-1 member-icon"><img src="https://bungie.net/' + icon + '"></div>' + '<div class="j-col j-col-3 member-name"><h3>' + name + '</h3></div>' + '<div class="j-col j-col-3 member-joined" data-label="Joined">' + joined.replace(/-/g, '/') + '</div>' + '<div class="j-col j-col-3 member-status" data-label="Status"><span class="member-online" id="status-' + memberId + '">' + online + '</span></div>' + '<div class="j-col j-col-3 member-button"><a class="button outline gold full-width">' + 'View Stats' + '</a></div>' + '<div class="j-col j-col-3 member-button"> + In Depth Stats' + '</a></div>').appendTo(list);
// indicate online/offline status
if (String(online) === 'true') {
$('#status-' + memberId).text('Online').addClass('online').closest('.member').attr('data-online', true).addClass('online');
} else {
$('#status-' + memberId).text('Offline').removeClass('online');
}
sortMembers(joined); // sort members by join date
}
}
}
You have nested links. That breaks your HTML and prevents the href you want to be used.
Here you create the wrapper of each member. Which is a link.
member.attr({
'class': 'j-row vertical-center-row member',
'href': '/player/?bungieId=' + memberId + '&destinyId=' + destinyId + '&joined=' + joined + '&rank=' + rank,
...
And then you append another link inside of it here:
... In Depth Stats' ...
So I would suggest that you change the structure of your member element. Maybe place the top link in the position of the View Stats button and change that button to a <a> tag. But then as a consensus the whole member element won't be clickable, only the links.
Good luck!

how to show an error when in appbrowser does not load error phonegap

i am developing an application and loading an hosted application using the inapp browser plugin cordova-plugin-inappbrowser
I have gotten most of the functionalities to work but i am unable to get the part of loading an error message when he url does not load, it dosent just work and shows me an error message of the url where i have hosted my application instead.
Which could be embarrassing.
please i need help on this
This is what am working with below thanks for ur potential responses
// my child browser code, the main source of my app content
function fire(){
var ref = cordova.InAppBrowser.open('http://####################', '_blank', 'location=no,zoom=no,hardwareback=yes,clearsessioncache=yes,clearcache=no');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', inAppBrowserbLoadStart);
ref.addEventListener('loadstop', inAppBrowserbLoadStop);
ref.addEventListener('loaderror', loadErrorCallBack);
ref.addEventListener('exit', inAppBrowserbClose);
}
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage =
"alert('Sorry we cannot open that page. Message from the server is : "
+ params.message + "');"
inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function executeScriptCallBack(params) {
if (params[0] == null) {
$('#status-message').text(
"Sorry we couldn't open that page. Message from the server is : '"
+ params.message + "'");
}
}
Your code is generally fine, but you have no control over the title of the alert() function. You can use some other techniques to display the error message. For example, you can use a div:
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage = createMsg('Sorry we cannot open that page. Message from the server is: '
+ params.message);
inAppBrowserRef.executeScript({
code: scriptErrorMesssage
}, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function createMsg(msg) {
return 'var div = document.createElement("div");'
+ 'div.style.position = "absolute";'
+ 'div.style.top = "50%";'
+ 'div.style.left = "50%";'
+ 'div.style.width = "100px";'
+ 'div.style.height = "100px";'
+ 'div.style.color = "#f00";'
+ 'div.innerHTML = "' + msg + '";'
+ 'document.appendChild(div);'
}

Twitch Button (HTML/JScript w bootstrap)

Hello everyone I've tried everything I can think of to make this work. I know it does return stream = null or active through use in the browser, but It will not apply my buttons to my page. Not so good with javascript can anyone point me in the right direction.
<script type="text/javascript">
(function() {
var user_name, api_key;
user_name = "Undead_Atomsk";
api_key = "************************";
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.write(Live!);
} else {
document.write(Offline!);
}
});
})();
</script
Took your advice and used browser tools "Completely forgot about those".
I added this line to my html.
I then made a .js file and used the following code everything works now the twitch API is just slow!
(function() {
var user_name, api_key, twitch_widget;
user_name = "Undead_Atomsk";
api_key = "********************";
twitch_widget = $("#twitch-widget");
twitch_widget.attr("href","https://twitch.tv/" + user_name);
$.getJSON('https://api.twitch.tv/kraken/streams/' + user_name +'?client_id=' + api_key + '&callback=?', function(data) {
if (data.stream) {
document.getElementById("twitch-btn").innerHTML = 'Live!';
} else {
document.getElementById("twitch-btn").innerHTML = 'Offline!';
}
});
})();

What is wrong with my foursquare api call?

The live example is here
http://kenziejoy.github.io/frontend-nanodegree-map/
I'm trying to pull data about locations that I have hard coded in an array - either by their foursquare id (didn't seem to be working) or their lat and lng. (client ID and secret are variables I just haven't shown them here)
I don't need any other functionality than just pulling data from their database to display on a map so I thought it would fall under the userless access but it is giving me an error that the request are bad because I don't have the proper authentication.
Thanks in advance
From the foursquare site
"Userless access
Some of our endpoints that don’t pertain to specific user information, such as venues search are enabled for userless access (meaning you don’t need to have a user auth your app for access). To make a userless request, specify your consumer key's Client ID and Secret instead of an auth token in the request URL.
https://api.foursquare.com/v2/venues/search?ll=40.7,-74&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=YYYYMMDD
To see what level of permissions each endpoint needs, check out the filters at the top of our endpoints page."
/**********FourSquare***************/
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&?client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
var result = data.response.venue;
var contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
var location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
var bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
var description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
var rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
var url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
var contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
I took a look at the live example URL and you were getting a lot of bad request errors in the JavaScript console in Chrome.
Looking at these, you had a bad URL, you were using:
https://api.foursquare.com/v2/venues/search?limit=1&ll=45.5589522,-122.6517163&?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&v=20140806&m=foursquare
The problem seems to be that you have:
&?client_id
which makes the URL invalid.
Changing this to
&client_id
fixes this and I then see data coming back from Foursquare.

Converting an MVC4 Web API Application to Phonegap Android Application

I have an MVC4 Web API application where i have my Api Controller and Code-First EF5 database and some JavaScript functions for the functionality of my app including my Ajax Calls for my Web Api Service.I did the project on MVC because i was having trouble installing Cordova in VS2012, so i have decided to use Eclipse/Android Phonegap platform.Is there a way where i can call my web api service and be able to retrieve my database data designed EF5(MVC4) in my Android Phonegap application without having to start from the beginning the same thing again.I know phonegap is basically Html(JavaScript and Css) but i am having trouble calling my service using the same HTML markup that i used MVC4.I am a beginner please let me know if what i am doing is possible and if not please do show me the light of how i can go about this. T*his is my Html code*
<script type="text/javascript" charset="utf-8" src="phonegap-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
<script type="text/javascript" language="javascript" src="http://api.afrigis.co.za/loadjsapi/?key=...&version=2.6">
</script>
<script type="text/javascript" language="javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
//initialize watchID Variable
var watchID = null;
// device APIs are available
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 30000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
//declare a global map object
var agmap = null;
// declare zoom control of map
var zoomCtrl = null;
function initAGMap() {
agmap = new AGMap(document.getElementById("MapPanel"));
//TODO: must retrieve coords by device location not hard corded.
agmap.centreAndScale(new AGCoord(-25.7482681540537, 28.225935184269), 5); // zoom level 5 heres
// making zoom controls for map
var ctrlPos = new AGControlPosition(new AGPoint(10, 10), AGAnchor.TOP_LEFT);
zoomCtrl = new AGZoomControl(1);
agmap.addControl(zoomCtrl, ctrlPos);
}
function removeZoomCtrl()
{
zoomCtrl.remove();
}
//function search() {
// var lat = $('#latitude').val();
// var long = $('#longitude').val();
// $.ajax({
// url: "api/Attractions/?longitude=" + long + "&latitude=" + lat,
// type: "GET",
// success: function (data) {
// if (data == null) {
// $('#attractionName').html("No attractions to search");
// }
// else {
// $('#attractionName').html("You should visit " + data.Name);
// displayMap(data.Location.Geography.WellKnownText, data.Name);
// }
// }
// });
//}
//function GetCoordinate() {
//todo: get details from cordova, currently mocking up results
//return { latitude: -25.5, longitude: 28.5 };
}
function ShowCoordinate(coords) {
agmap.centreAndScale(new AGCoord(coords.latitude, coords.longitude), 5); // zoom level 5 here
var coord = new AGCoord(coords.latitude, coords.longitude);
var oMarker = new AGMarker(coord);
agmap.addOverlay(oMarker);
oMarker.show();
//todo: create a list of places found and display with marker on AfriGIS Map.
}
function ScanProduct()
{
//todo retrieve id from cordova as mockup
//This is mockup barcode
//return "1234";
//sample code using cordova barcodescanner plugin
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
//Callback function if barcodedont exist
function (error) {
alert("Scanning failed: " + error);
});
}
//Function to display Success or error in encoding.
function encode(type, data) {
window.plugins.barcodeScanner.encode(type, data, function(result) {
alert("encode success: " + result);
}, function(error) {
alert("encoding failed: " + error);
});}
function GetProductDetails(barcodeId,coords)
{
//Ajax Call to my web Api service
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data) {
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if (data.results == null) {
$('#result').append(data.message)
}
else {
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
//Another Solution
//var ul = $("<ul></ul>")
//ul.append("<li> Rand" + data.results.productName + "</li>");
//ul.append("<li> Rand" + data.results.Retailer.Name + "</li>");
//ul.append("<li> Rand" + data.results.price + "</li>");
//ul.append("<li> Rand" + data.results.Distance + "</li>");
//$("#result").append(ul);
}
});
$("#result").append(ul);
});
}
function ShowProductDetails()
{
//todo: display product details
//return productdetails.barcodeId + productdetails.retailerName + ': R' + productdetails.Price + productdetails.Distance;
}
//loading javascript api
$(function () {
initAGMap();
var coord = GetCoordinate();
ShowCoordinate(coord);
var barcodeId = ScanProduct();
var productdetails = GetProductDetails(barcodeId, coord);
ShowProductDetails(productdetails);
});
</script>
It looks like you're on the right track. The obvious error right now is that it's using a relative URL (api/products/?barcodeId=) to call the Web API. Because the HTML is no longer hosted on the same server as the Web API (even though you might be running them both on your local machine still), this won't work anymore. You need to call the service with an absolute URL (for example, http://localhost:8888/api/products/?barcodeId=).
Where is your Web API hosted right now and how are you running the Cordova code? If the Web API is up and running on your local machine and your Cordova app is running on an emulator on the same machine, you should be able to call the service by supplying its full localhost path.
If it still doesn't work, you'll need to somehow debug the code and see what the errors are.

Categories

Resources