How to use Chrome Copresence API? - javascript

This is a basic question, but I am new to JavaScript, and I want to use some Chrome APIs. My problem lies in understanding what the page is trying to tell me, for instance, what do they mean by types on this page? How would I create a message using the details on that page for a message? I apologize if it seems like a newb question, but I am new to this and am completely lost.
Basically I am trying to better understand what is meant by type. Does that mean I have to create variables that satisfy the parameters of that type? SO for the execute method, I would pass it a variable that satisfies the type of a message? Thanks!
var message = ("type","payload");
chrome.copresence.execute([message], function callback)

Untested due to the lack of a supported device:
chrome.copresence.execute([
{
publish: {
id: "someID",
message: {type: "joke", payload: data},
timeToLiveMillis: 1000,
policy: {onlyEarshot: true}
}
}
], function(status) {
console.log(status);
});
payload is an ArrayBuffer per documentation, so to send a string you'd have to convert it (I guess) like this, for example:
var data = new TextEncoder("utf8").encode("Hello, world!").buffer;

Related

Parse error code 121

I am trying to save a value on a 'collection' called 'orders'. But when i click 'save', it gives me an error code 121.
I have already checked my key-value parameters, but i can't find a $ or a . to make it give me this error...
Here is my code (the variable names are in portuguese, but only that)
var objRevenda = Parse.Object.extend("resellers"),
objPedido = Parse.Object.extend("orders"),
query = new Parse.Query(objRevenda),
idRevenda = $scope.revenda.id;
query.get(idRevenda, {
success: function(revenda) {
var valores = {
status: 'aberto',
client: $rootScope.usuarioAtual,
reseller: revenda,
payment_method: metodo_pgto,
items: $scope.itens,
total: $scope.totalPedido
};
var pedido = new objPedido();
pedido.save(valores, {
success: function(pedido) {
console.log('Sucesso');
},
error: function(pedido, error) {
console.error('Ops... ', error);
}
});
},
error: function(revenda, error) {
console.log(error);
}
});
Can someone help me find the error?
Btw: I am using AngularJS and Ionic Framework.
Thanks in advance.
If you are using a JSON object (sending it to Parse via AngularJS), it will have a $$hashKey, wich Angular uses to make ng-repeats and all, having unique identifiers. If you use JSON.Parse(object), Angular creates the $$hashKey, altough, if you use angular.toJson(object), the hash key should be gone. Make sure that before sending to Parse, you do a console.log(json-object), to make sure the hash key is really gone. If not, i think you should remove it by doing a conditional operation. I removed the hash key and now it works like a charm ;)
I figured out that if you are using angular (maybe other frameworks as well) that an identical embedded key/value pair on multiple levels will result in a $$hashKey key being created and will cause this error.
Maker sure that none of your objects contain something like the following:
{
id: 65ftvjbh,
user: {
id: 65ftvjbh,
name: John Doe
}

Parse iOS SDK: Understanding Cloud Code

Scenario = I am slowly but surely wrapping my head around what is going on with Parse's cloud code features. I just need some help from those who would like to answer some short, relatively simple questions about what is going on in some sample cloud code functions.
The code I will use in this example is below
1) cloud code
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId,
newColText = request.params.newColText;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
user.set('new_col', newColText);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
2) called from iOS
[PFCloud callFunction:#"editUser" withParameters:#{
#"userId": #"someuseridhere",
#"newColText": #"new text!"
}];
This code was taken from here
Question 1 =
(request, response)
I am confused by what this is. Is this like typecasting in iOS where I am saying (in the iOS call) I want to pass an NSString into this function ("userId") and inside the cloud code function I'm going to call it "request"? Is that what's going on here?
Question 2 =
Parse.Object.extend('_User')
Is this grabbing the "User" class from the Parse database so that a "PFObject" of sorts can update it by creating a new "user" in the line below it?
Is this like a...
PFObject *userObject = [PFObject objectWithClassName:#"User"]?
Question 3 =
user.set('new_col', newColText)
This obviously 'sets' the values to be saved to the PFUser (~I think). I know that the "newColText" variable is the text that is to be set - but what is 'new_col'? Only thing I can think of is that this sets the name of a new column in the database of whatever type is being passed through the "request"?
Is this like a...
[[PFUser currentUser] setObject: forKey:]
Question 4 =
Parse.Cloud.useMasterKey()
Without getting too technical, is this basically all I have to type before I can edit a "User" object from another User?
Question 5 =
user.save().then(function(user) {
response.success(user);
}
Is this like a...
[user saveInBackgroundWithBlock:]?
and if so, is
function(error) {
response.error(error)
just setting what happens if there is an error in the saveInBackgroundWithBlock?
Please keep in mind, I know iOS - not JavaScript. So try to be as descriptive as possible to someone who understands the Apple realm.
Here's my take on your questions:
The request parameter is for you to access everything that is part of the request/call to your cloud function, it includes the parameters passed (request.params), the User that is authenticated on the client (request.user) and some other things you can learn about in the documentation. The response is for you to send information back to the calling code, you generally call response.success() or response.error() with an optional string/object/etc that gets included in the response, again documentation here.
That's a way of creating an instance of a User, which because it is a special internal class is named _User instead, same with _Role and _Installation. It is creating an instance of the user with an ID, not creating a new one (which wouldn't have an ID until saved). When you create an object this way you can "patch" it by just changing the properties you want updated.
Again, look at the documentation or an example, the first parameter is the column name (it will be created if it doesn't exist), the second value is what you want that column set to.
You have to do Parse.Cloud.useMasterKey() when you need to do something that the user logged into the client doesn't have permission to do. It means "ignore all security, I know what I'm doing".
You're seeing a promise chain, each step in the chain allows you to pass in a "success" handler and an optional "error" handler. There is some great documentation. It is super handy when you want to do a couple of things in order, e.g.
Sample code:
var post = new Parse.Object('Post');
var comment = new Parse.Object('Comment');
// assume we set a bunch of properties on the post and comment here
post.save().then(function() {
// we know the post is saved, so now we can reference it from our comment
comment.set('post', post);
// return the comment save promise, so we can keep chaining
return comment.save();
}).then(function() {
// success!
response.success();
}, function(error) {
// uh oh!
// this catches errors anywhere in the chain
response.error(error);
});
I'm pretty much at the same place as you are, but here are my thoughts:
No, these are the parameters received by the function. When something calls the editUser cloud function, you'll have those two objects to use: request & response. The request is basically what the iOS device sent to the server, and response is what the server will send to the iOS device.
Not quite that. It's like creating a subclass of _User.
Think of Parse objects types as a database table and it's instances as rows. The set will set (derp) the value of 'newColText' to the attribute/column 'new_col'.
Not sure, never used that function as I don't handle User objects. But might be that.
Pretty much that. But it's more sort of like (pseudo-code, mixing JS with Obj-C):
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
if(error){
response.error(error); // mark the function as failed and return the error object to the iOS device
}
else{
response.success(user); // mark the function call as successful and return the user object to the iOS device
}
}];

javascript - make facebook page post

I am not using the Javascript SDK because that is client-side whereas I'm making a server-side call.
I want to make a page post so that I can make an ad creative with it. I can do the call perfectly fine in the Graph API Explorer tool, but I cannot make the same call (with the same long-lived access tokens that continue to work in the Graph Explorer) from Javascript. Here is my code:
tok = <valid and never expiring user token>;
var pg_tok = <valid and never expiring page token>;
var act_id = <account_id>;
var pg_id = <page_id>;
var call_to_action = 'INSTALL_MOBILE_APP';
var fb_app_url = 'https://itunes.apple.com/us/app/id284882215';
var msg = 'Test creative, ya see';
var pic_url = 'https://s3.amazonaws.com/<path_to_my_image>';
var ROOT = 'https://graph.facebook.com/';
var pagepost_endpoint = ROOT+pg_id+'/feed';
console.log(pagepost_endpoint);
var pagepost_params = {
access_token: pg_tok,
call_to_action: {
type: call_to_action,
value: {link: fb_app_url}
},
message: msg,
picture: pic_url,
published: false
};
console.log(pagepost_params);
var pagepost_res = HTTP.post(pagepost_endpoint, {params: pagepost_params});
console.log(pagepost_res);
I have played around a bunch with params vs. data for where pagepost_params goes in the HTTP.post that is giving the error (that is Meteor's HTTP btw).
-Putting everything in params gives the error: {"error":{"type":"Exception","message":"No Call To Action Type was parseable. Please refer to the call to action api documentation","code":1373054,"is_transient":false}}.
-Putting everything in data gives the error: {"error":{"message":"(#200) This API call requires a valid app_id.","type":"OAuthException","code":200}}.
-Putting access_token in params and everything else in data gives the error: {"error":{"message":"Invalid parameter","type":"FacebookApiException","code":100,"error_subcode":1349125}}.
One more clue for everyone, if I change the HTTP.post to HTTP.get, and just put access_token in params and include no other parameters (in params or in data), the call succeeds and I see past posts I have made on this page through the Graph Explorer (only the ones with published: true, though), so the access token and endpoint do work, just something is faulty about POST-ing instead of GET-ing and the specific parameters I'm using.
Have you tried posting to /photos instead of /feed? The error subcode is the same as mentioned here Posting to facebook wall using graph api
Hope this helps
Turned out to be an issue with Meteor's HTTP. It does not handle nested JSON very well, and we're going to submit a pull request for that. But for those seeing this, the important thing to take away is that the call_to_action may not be a valid JSON object, and even if it is, it may not be being stringified/parsed as expected. My fix was using request.post instead of HTTP.post. (then instead of params or data, you use form. look up node's request https://github.com/mikeal/request)

Can I relabel the person.noun for Profile object type in Facebook Open Graph?

I have created a Story using Open Graph and the object I want to use is called Service, which is really just a Profile but I want the text in the post to say 'service' rather than 'person' (which it does now). I have tried creating a custom object but it seems overly complicated for what I need so I have 2 questions:
Can I create a custom type that simply inherits from Profile that can be created in the same way (using the FB.api javascript method)? I don't want to have to use self-hosted types..
Can I simply re-label person.noun from 'person' to 'service' somehow? I can't see a way to do that..
My code to post the story is:
FB.login(function (response) {
if (response.authResponse) {
var strmessage = 'Some message';
var profileid = 'xxxxxxxxx;
var opts = {
profile: profileid,
message: strmessage,
no_feed_story: false,
'fb:explicitly_shared': true
};
FB.api('https://graph.facebook.com/me/mynamespace:myaction', 'post', opts, function (response) {
if (!response || response.error) {
Result("Your message has not been posted");
}
else {
//Message has been posted
Result("Your message has been posted");
}
});
You're going to have to do the custom object if you want a custom name. And, you're going to have to do it on the FB Developer site and go through the whole approval process and all that. And no, there is no way to do any sort of inherence on this.
FB's Open Graph is pretty simple if you use the built in actions and objects, but as soon as you go down the road of wanting custom names for stuff, you are going to have to go all in with it.
I finally put the time aside to implement a custom action and type. It wasn't the most intuitive process but I got there in the end and my app is now approved and doing exactly what I wanted it to do. I'm actually glad I put myself through this learning process as custom stories have great potential and I'm sure I'll find other applications for them in the future.

'POST 400 bad request' error when updating parse.com table

I am getting a 'POST 400 bad request' error when trying to update a table on parse.com using JS SDK.
var Gallery = Parse.Object.extend("Gallery");
var gallery = new Gallery();
var activeArtworks = 0;
gallery.save(null, {
success: function(gallery) {
gallery.set("activeArtworks", activeArtworks);
gallery.save();
}
});
Please help!
I can't see how this is any different to the sample code provided by parse here
The sample code you reference creates all of its parameters before setting up the save() method. This is the step you're missing; you need to create the activeArtworks parameter on your gallery instance. Your update is failing because you're trying to update a property that was never created.
I would expect this code to work, though I didn't test it because parse.com requires you to set up an account to run any code, which is silly, and I didn't feel like creating one:
var Gallery = Parse.Object.extend("Gallery");
var gallery = new Gallery();
var activeArtworks = 0;
gallery.activeArtworks = []; // or some more appropriate default if you have one.
gallery.save(null, {
success: function(gallery) {
gallery.set("activeArtworks", activeArtworks);
gallery.save();
}
});
It might also be worth checking if there's any info in the headers of the 400 error (the debug console in your browser will show these in its Network tab). I would expect Parse to give you some sort of information to help you debug issues, and that's the only place it would fit for an HTTP error.
If you had use user.logIn(callback) function with Parse JS, maybe your session invalid. Please check your callback function error code, if error.code==209 (invalid session token), use Parse.User.logOut() and re-login again.
Like this:
if (error.code == 209) {
Parse.User.logOut();
user.logIn(loginCallback);
return;
}
I had this same issue and it was resolved after realising that the data type that I was posting was different to that specified in the columns that I had created.
In my case, I was trying to save an object when I had specified an array when creating the column in the class.

Categories