Failing to fetch CategorizedFacebookType - facebook-graph-api

I have an application which I developed about a year ago and I'm
fetching facebook accounts like this:
facebookClient = new DefaultFacebookClient(access_token);
Connection<CategorizedFacebookType> con = facebookClient.fetchConnection("me/accounts", CategorizedFacebookType.class);
fbAccounts = con.getData();
It worked fine until about a month ago, but now it returns the
fbAccounts list empty. Why is that?
I was hoping moving from restfb-1.6.2.jar to restfb-1.6.9.jar would
help but no luck, it comes up empty on both.
What am I missing?
EDIT, to provide the code for another error I have with this API. The following code used to work:
String id = page.getFbPageID(); // (a valid facebook page id)
FBInsightsDaily daily = new FBInsightsDaily(); // an object holding some insights values
try {
Parameter param = Parameter.with("asdf", "asdf"); // seems like the param is required
JsonObject allValues = facebookClient.executeMultiquery(createQueries(date, id), JsonObject.class, param);
daily.setPageActiveUsersDaily((Integer)(((JsonArray)allValues.opt("page_active_users_daily")).getJsonObject(0)).opt("value"));
...
This throws the following exception:
com.restfb.json.JsonException: JsonArray[0] not found.
at com.restfb.json.JsonArray.get(JsonArray.java:252)
at com.restfb.json.JsonArray.getJsonObject(JsonArray.java:341)
Again, this used to work fine but now throws this.

You need the manage_pages permission from the user to access their list of adminned pages - a year ago I'm not sure you did - check that you're obtaining that permission from your users
{edit}
Some of the insights metrics were also deprecated, the specific values you're checking may no longer exist - https://developers.facebook.com/docs/reference/fql/insights/ should have the details of what is available now
Try to check your queries manually in the Graph API Explorer to eliminate any issues in your code and hopefully get more detailed error messages that your SDK may be swallowing

Related

Different results when making a Corda query via API and inside a flow

I’m getting some strange behaviour. When I update a state with a list of partner ids - other nodes - and and read the state afterwards it seems that via rpcOps.vaultQueryBy I can see the updated - or unconsumed - state with the updated list of partners, but if I do same query via serviceHub.vaultService.queryBy it looks like the state’s parner list hasn’t changed at all.
If I get all states in the flow - also the consumed - it looks like there has not been a change, but via API all updates into partners list are visible. Is this some sort of a bug I have encountered or am I just not understanding something?
We're using Corda 4.0.
Via API
var servicestates = rpcOps.vaultQueryBy<ServiceState>().states.map { it.state.data }
var services = getServices().filter {
it.linearId == UniqueIdentifier.fromString(serviceId)
}.single()
Inside flow
val serviceStateAndRef = serviceHub.vaultService.queryBy<ServiceState>(
QueryCriteria.LinearStateQueryCriteria(linearId = listOf(serviceLinearId))
).states.single()
#Ashutosh Meher You got it near enough. The problem was in a previous flow, where, when creating a new partner state the command call for contract, there was only the caller listed.
So
Command(ServiceContract.Commands.AddPartner(),listOf(ourIdentity.owningKey))
had to be edited to include necessary other parties.
Command(ServiceContract.Commands.AddPartner(),updatedServiceState.participants.map { it.owningKey })
That resulted the other node not to see the change. It was right under my eyes all the time... ;)

How to specify the database in an ArangoDb AQL query?

If have multiple databases defined on a particular ArangoDB server, how do I specify the database I'd like an AQL query to run against?
Running the query through the REST endpoint that includes the db name (substituted into [DBNAME] below) ie:
/_db/[DBNAME]/_api/cursor
doesn't seem to work. The error message says 'unknown path /_db/[DBNAME]/_api/cursor'
Is this something I have to specify in the query itself?
Also: The query I'm trying to run is:
FOR col in COLLECTIONS() RETURN col.name
Fwiw, I haven't found a way to set the "current" database through the REST API. Also, I'm accessing the REST API from C++ using fuerte.
Tom Regner deserves primary credit here for prompting the enquiry that produced this answer. I am posting my findings here as an answer to help others who might run into this.
I don't know if this is a fuerte bug, shortcoming or just an api caveat that wasn't clear to me... BUT...
In order for the '/_db/[DBNAME/' prefix in an endpoint (eg full endpoint '/_db/[DBNAME/_api/cursor') to be registered and used in the header of a ::arangodb::fuerte::Request, it is NOT sufficient (as of arangodb 3.5.3 and the fuerte version available at the time of this answer) to simply call:
std::unique_ptr<fuerte::Request> request;
const char *endpoint = "/_db/[DBNAME/_api/cursor";
request = fuerte::createRequest(fuerte::RestVerb::Post,endpoint);
// and adding any arguments to the request using a VPackBuilder...
// in this case the query (omitted)
To have the database name included as part of such a request, you must additionally call the following:
request->header.parseArangoPath(endpoint);
Failure to do so seems to result in an error about an 'unknown path'.
Note 1: Simply setting the database member variable, ie
request->header.database = "[DBNAME]";
does not work.
Note 2: that operations without the leading '/_db/[DBNAME]/' prefix, seem to work fine using the 'current' database. (which at least for me, seems to be stuck at '_system' since as far as I can tell, there doesn't seem to be an endpoint to change this via the HTTP REST Api.)
The docs aren't very helpful right now, so just incase someone is looking for a more complete example, then please consider the following code.
EventLoopService eventLoopService;
// adjust the connection for your environment!
std::shared_ptr<Connection> conn = ConnectionBuilder().endpoint("http://localhost:8529")
.authenticationType(AuthenticationType::Basic)
.user(?) // enter a user with access
.password(?) // enter the password
.connect(eventLoopService);
// create the request
std::unique_ptr<Request> request = createRequest(RestVerb::Post, ContentType::VPack);
// enter the database name (ensure the user has access)
request->header.database = ?;
// API endpoint to submit AQL queries
request->header.path = "/_api/cursor";
// Create a payload to be submitted to the API endpoint
VPackBuilder builder;
builder.openObject();
// here is your query
builder.add("query", VPackValue("for col in collections() return col.name"));
builder.close();
// add the payload to the request
request->addVPack(builder.slice());
// send the request (blocking)
std::unique_ptr<Response> response = conn->sendRequest(std::move(request));
// check the response code - it should be 201
unsigned int statusCode = response->statusCode();
// slice has the response data
VPackSlice slice = response->slices().front();
std::cout << slice.get("result").toJson() << std::endl;

PowerBI Failed to execute 'atob' on 'Window' in parsePowerBIAccessToken

Randomly today my powerbi embedded code has been throwing:
DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
at window.atob (eval at <anonymous> (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1326:504), <anonymous>:1:83)
at e.parsePowerBIAccessToken (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:2331307)
at e.isTokenTenantValid (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:2331046)
at t.isPowerBIAccessTokenValid (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:31523)
at t.promptForLogin (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:31233)
at m.scope.promptForLogin (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:25515)
at fn (eval at compile (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1444:307), <anonymous>:4:374)
at m.$digest (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1350:310)
at https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:1626830
at t.i [as _next] (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:189984)
I checked the access token and they appear valid. (No different to the ones working yesterday). I added a debug hook into window.atob and it seems like something inside of parsePowerBIAccessToken is passing undefined to atob. I can't figure out why though unless this code changed.
Kind of stuck on how to figure out the issue. (Not helping that Chrome seems to struggle to debug the lines without crashing).
The code path is trying to run the embed token through this code:
e.prototype.parsePowerBIAccessToken = function() {
return JSON.parse(atob(i.powerBIAccessToken.split(".")[1]))
}
Odd because the code is clearly using "tokenType: models.TokenType.Embed," and thus probably shouldn't be going down that code path?
I noticed it works if I'm logged into the MS account though, so it's using cookies.
If you copy and paste the embed URL from a report it'll have autoAuth=true in the URL. You must remove this from the embed URL or it attempts to use your cookies to authenticate. (It'll also try to use the embed token like an access token and execute wrong code, so that's MS's bug).
In my JS code I removed the autoAuth from the embed url and it'll skip trying to use cookies.
embedURL = embedURL.replace(/autoAuth=true&/ig, '');
You should always get the embed URL using the REST APIs.
From the embed for your customers (Embed Token) documentation
using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;
// You need to provide the workspaceId where the dashboard resides.
ODataResponseListReport reports = await client.Reports.GetReportsInGroupAsync(workspaceId);
// Get the first report in the group.
Report report = reports.Value.FirstOrDefault();
// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Reports.GenerateTokenInGroup(workspaceId, report.Id, generateTokenRequestParameters);
// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
EmbedToken = tokenResponse,
EmbedUrl = report.EmbedUrl,
Id = report.Id
};
You get the embed URL from the Report object.
The URL you got from powerbi.com is powerbi secure embed and it is not recommended to use this URL for another scenario.
We raised this issue with the PowerBI team. You are supposed to use an API call to get the embed URL for a report. There is an API tester here: https://learn.microsoft.com/en-us/rest/api/power-bi/reports/getreportingroup
Here is a playground for testing embedding: https://microsoft.github.io/PowerBI-JavaScript/demo/v2-demo/index.html

Instagram authentication scope param using coldfusion

I have an Instagram application written in Coldfusion 8 that basically pulls in media by tags and then allows people to Like / vote on the photos which is all done via the Instagram API. The Liking part is causing me no end of grief though, as I can get the Authentication and Access_Token without a drama, however the Access_Token doesn't appear to have permission to Like by default. There is an optional param for the Authenticate call "scope" which allows you to pass the permissions allowed for the Access_Token but i cannot work out how to pass this via ColdFusion CFHTTP as a POST.
Here is the preparation for the data to be sent over CFHTTP looping over all params as type="FormField". No matter how I try and present the scope options, either JSON format, string with spaces, string with "+" delimiters it seems to have no effect and the Like operation continues to fail due to permission errors.
<cfscript>
var LOCAL = {};
LOCAL['config'] = {};
LOCAL['returnStruct'] = {};
// prep packet required by the main call method
// the following values are required for EVERY call
LOCAL['config']['method'] = 'POST';
LOCAL['config']['format'] = ARGUMENTS['outputType'];
LOCAL['config']['url'] = VARIABLES.authURL;
// variables required by this method
LOCAL['config']['params'] = {};
LOCAL['config']['params']['client_secret'] = ARGUMENTS.client_secret;
LOCAL['config']['params']['grant_type'] = 'authorization_code';
LOCAL['config']['params']['redirect_uri'] = ARGUMENTS.redirect_uri;
LOCAL['config']['params']['code'] = ARGUMENTS.code;
LOCAL['config']['params']['scope'] = 'likes comments relationships';
</cfscript>
If anyone else is running into the same issues with "scope" not being correctly applied to the return Access_Token it turns out the problem was Instagram Documentation being vague about where this argument should be used. I had tried it every way possible as a POST operation as it suggested during the server-side Authentication, however it appears to only work if sent as GET params and after some playing around I decided to tack the "scope" param onto the 2nd stage of the authentication which is where the Code is requested and that worked! See below
https://api.instagram.com/oauth/authorize/?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=likes+basic
This will present the user with an confirmation message from Instagram to allow the application to perform Likes on behalf of the user and everything else works like a charm after this.

How execute a FQL Insights query with Facebook Graph API

I try without success to execute a FQL query using Graph API to get the value of Insights counters.
Does anyone know how I can do this?
I use "Facebook C# SDK" version 5.4.1, C# 4.0.
If I use C# sample code provided in the documentation
var fb = new FacebookClient(m_accessToken);
dynamic result = fb.Query("SELECT name, uid FROM user WHERE uid= me()");
I receive a good response
{"name":"","uid":100002632407830}
With the same syntax, If I request "pages_fans" Insights counter and use library 5.4.1
var fb = new FacebookClient(m_accessToken);
dynamic result = fb.Query("SELECT metric, value FROM insights WHERE object_id=6176018219 AND metric='page_fans' AND end_time=end_time_date('2011-12-31') AND period=period('lifetime')");
I receive always an empty response
{[]}
With the same code but with library 5.2.1
I receive always a good response
{[{"metric":"page_fans","value":"125535"}]}
It is the same problem described here : Error with FQL query with library 5.4.1 but with another syntax.
Currently I use FQL Insights queries using REST API (with libary 5.2.1) but I want to migrate to FQL Insights queries using the Graph API (with library 5.4.1) because the REST API is deprecated.
Where is the bug:
In my syntax request?
In the "Facebook C# SDK" library?
On Facebook server?
Best regards.
I made a request with the Facebook Graph API Explorer
https://graph.facebook.com/fql?q=SELECT metric, value FROM insights
WHERE object_id=6176018219 AND metric='page_fans' AND
end_time=end_time_date('2011-12-31') AND period=period('lifetime')
I receive always an empty response.
{
"data": [
]
}
It is a Facebook's bug.
A bug was created about it on Facebook : http://developers.facebook.com/bugs/232510993491615?browse=search_4f08c675cce9d2265724293
I found another way to retrieving the info which works reliably
I found another way of retrieving insights which seems to be reliable.
documentation found here http://developers.facebook.com/docs/reference/api/insights/.
with more options to allow format and period changes - below example.
https://graph.facebook.com/2439131959/insights/application_active_users/[period]?format=json&since=[timestamp]&until=[timestamp]&access_token=[access_token]
period is day, month, week, lifetime.
timestamp has to be a valid PST midnight only.
access_token = could be.
1. nothing for the metrics that don't need permission.
2. app_id|secret_code or
3. your authentication token granted that you have access to the insight data of the application or pages (ie owner or insight users).
C# sdk example:
FacebookClient fbClient = new FacebookClient([appID], [secret]);
DateTime untilDate= (new DateTime([Now].Year, [Now].Month, [Now].Day));
DateTime sinceDate= (new DateTime([Now].Year, [Now].Month, [Now].Day)).AddDays(-1);
TimeSpan t = (untilDate- new DateTime(1970, 1, 1));
int timestampUntil = (int)t.TotalSeconds;
t = (sinceDate- new DateTime(1970, 1, 1));
int timeStampSince = (int)t.TotalSeconds;
var result = (IDictionary<string, object>)fbClient.Get([appID] + "/insights/" + [metricID] + "/" + [period] + "?format=json&since="+timeStampSince+"&until="+timestampUntil );
Console.WriteLine(result["data"]);
Make sure you have the correct permissions when you get your Access Token
<fb:login-button perms="read_insights"></fb:login-button>
This issue related to Facebook C# SDK.
Probably best thing you can do is file a bug on codeplex, and replace usage of end_time_date to "time in seconds" and period to "lifetime".