Is OAuth a must before using Google+API - oauth

I m trying to use get and list method with google plus comment. In official site it said (All API calls require either an OAuth 2.0 token or an API key. ) and I have tried send GET request without the step of OAuth it works it returns json format data. My question is OAuth must require before using google+ API?

It depends on exactly what data you're trying to get.
https://developers.google.com/+/api/oauth documents the benefits of using OAuth, but in general, if you want to get private profile data, or if you wish to use the /me/ URL shortcut, you will need to use OAuth and may, if you wish, use an App Key in addition. If all you're interested in is public data, you can use the App Key.

The short answer to whether you can do it is that you can get comments from Google+ without OAuth.
As for the how would you do this, I'm not sure which language you're doing this in but the following code shows how this is done in JavaScript.
The API calls used here can be experimented with in the API explorer:
Listing Activities
Listing Comments
A demo of this code is here.
You will need an API key (the simple key) for a project with the Google+ APIs from the Google APIs console. When you set up the project, you will only need to enable the Google+ API from the services section.
First, grab the activities using the public data API:
// Gets the activities for a profile
function getActivities(profileID){
var activities = null;
var URL = "https://www.googleapis.com/plus/v1/people/" + profileID + "/activities/public?alt=json&key=" + key;
var request = new XMLHttpRequest();
request.open('GET', URL, false);
request.send(); // because of "false" above, will block until the request is done
// and status is available. Not recommended, however it works for simple cases.
if (request.status === 200) {
if (debug) console.log("retrieved activities \n\n");
var activities = jQuery.parseJSON(request.responseText).items;
console.log("Discovered " + activities.length + " activities");
}else{
handleRequestIssue(request);
}
return activities;
}
The following code loops through the activities
for (var i=0; i < activities.length; i++) {
console.log("trying to do something with an activity: " + i);
var activity = activities[i];
console.log(activity.id);
}
Next, you can use the activity IDs to retrieve the comments per activity:
function getCommentsForActivity(activityID){
var comments = "";
var URL = "https://www.googleapis.com/plus/v1/activities/" + activityID + "/comments?alt=json&key=" + key;
var request = new XMLHttpRequest();
request.open('GET', URL, false);
request.send(); // because of "false" above, will block until the request is done
// and status is available. Not recommended, however it works for simple cases.
if (request.status === 200) {
if (debug) console.log(request.responseText);
var comments = jQuery.parseJSON(request.responseText).items;
if (debug){
for (comment in comments){
console.log(comment);
}
}
}else{
handleRequestIssue(request);
}
return comments;
}
function manualTrigger(){
var activities = getActivities("109716647623830091721");
}
The following code brings it all together and retrieves activities and comments for a specific post:
$(document).ready(function () {
var renderMe = "";
var activities = getActivities("109716647623830091721");
console.log("activities retrieved: " + activities.length);
for (var i=0; i < activities.length; i++) {
console.log("trying to do something with an activity: " + i);
var activity = activities[i];
renderMe += "<br/><div class=\"article\"><p>" + activity.title + "</p>";
console.log(activity.id);
// get comments
var comments = getCommentsForActivity(activity.id);
for (var j=0; j<comments.length; j++){
renderMe += "<br/><div class=\"comment\">" + comments[j].object.content + "</div>";
}
renderMe += "</div>";
}
console.log("I'm done");
document.getElementById("ac").innerHTML = renderMe;
});

Related

Dynamics CRM WEB API- Select field from entity reference

I am trying to select a field from another CRM entity by using an expand with my odata query.
Query string: studios$?Select=studioid,studioname,titleid&$Expand=
Title id is a field in custom entity called title. How do I write an expand clause to expand title and select titleid?
Any help is appreciated!
first you can refer to this article from docs.microsoft explaining in detail the $expand feature, however for simplicity is followed by the relation name with targeted entity then the fields you want to select in parentheses
for ex. $expand={relation_name}($select=filed1,field2)
which might be something like this
$expand=new_new_entity1_new_entity2($select=new_name,createdon)
Notice: the values you get from expand relation will be actually navigation URL to actual data, so you don't expect [new_name,createdon] from new_entity2 to be retrieved, what you will get will be a url to OData those values and for that you might below helping function 1 will do it for you
Also you can use XRM Rest Builder that's an amazing solution when you install on the crm you will find it's button in solutions view. that solution is a tool helps you to design your OData query with nice GUI so that you don't need to write and refine your OData query which is faster and easier.
Helping function 1
`
function OdataExpand(expandUrl) {
var result = null;
var req = new XMLHttpRequest();
req.open("GET", expandUrl, false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
result = results;
} else {
console.log("OdataExpand Error : ");
console.log(this);
}
}
};
req.send();
return result;
}
`
but if you want to get all the data with one call and maybe you want to expand to more than one entity i recommend that you use Fetch XML simply design the fetch you need using advanced find tool to extract the fetchXML then pass it to Helping Function 2 that should return the full data but be aware that max fetch length in this approach is limited to 2,048 characters [Max Length for GET Request].
Helping Function 2
`
function ExecuteFetchXMLQuery(dataSet, fetchQuery) {
var encodedFetchXML = encodeURIComponent(fetchQuery);
var result;
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/" + dataSet + "?fetchXml=" + encodedFetchXML, false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200 || (this.status >= 200 && this.status <= 206)) {
console.log("Success Executing Fetch");
var results = JSON.parse(this.response);
result = results;
}
else {
console.log("Error Executing Fetch");
console.log(this);
console.log(this.statusText);
}
}
};
req.send();
return result;}
`
Try this:
studios?$select=studioid,studioname,titleid&$expand=titleid($select=titleid,name)
Also it’s recommended to use CRM REST Builder to compose & test CRM web api queries.
Read more
Note: Check your entity & field names, they should look like new_studio & new_studioid

Can I get speaker notes from Google Slides by API?

I want to get speaker notes from Google Slides by API, but I could not find any fields for speaker notes.
For reference: Method: presentations.pages.get
What would be a good way to do this?
Support for speaker notes is now available in the Slides API v1. Documentation is here: https://developers.google.com/slides/how-tos/notes
In the absence of the API, I wouldn't suggest this is a good way of doing it. In fact it is horrible. But here it is. If you absolutely had to do it. It is likely a bit flakey too.
Steps are:
Export the presentation, via the Drive API, as a PowerPoint .pptx file
Unpack the file - it is a zip file containing a directory structure with XML files in.
Identify the speaker notes files and process them as per your requirement (e.g. extract all text, or work on the XML etc).
Ugly right? Here's an example in Apps Script:
Enable Drive API in Advanced Services within your script (Resources > Advanced Google Services).
function example() {
// Print out the speaker notes
Logger.log(getNotes('123abc......asd'));
}
// Returns an array of strings, one string per slide
// representing the speaker notes.
function getNotes(presentationId) {
//DriveApp.createFile();
var notesRegex = /ppt\/notesSlides\/notesSlide\d+\.xml/;
var url = 'https://www.googleapis.com/drive/v2/files/' + presentationId +
'/export?mimeType=application%2Fvnd.openxmlformats-officedocument.presentationml.presentation';
var options = {
headers: {
Authorization : 'Bearer ' + ScriptApp.getOAuthToken()
}
};
var response = UrlFetchApp.fetch(url, options);
var zipBlob = Utilities.newBlob(response.getContent(), 'application/zip');
var data = Utilities.unzip(zipBlob);
var notes = [];
for (var i = 0; i < data.length; i++) {
if (notesRegex.test(data[i].getName())) {
// Example simply extracts text from speaker notes
// You could do something more complex.
notes.push(extractTextFromXml(data[i].getDataAsString()));
}
}
return notes;
}
function extractTextFromXml(xml) {
var doc = XmlService.parse(xml);
var root = doc.getRootElement();
var ns = root.getNamespace('a');
var text = [];
function walkNode(node) {
if (node.getText()) {
text.push(node.getText());
}
var children = node.getChildren();
if (children.length) {
children.forEach(function(child) {
walkNode(child);
});
}
}
walkNode(root);
return text.join('\n');
}

Unauthorized Twitter Stream Sample

I'm trying to learn Twitter API using LinqToTwitter. It works fine to connect to Twitter API but not Twitter Stream. As far as I can tell I need special rights to access the firehouse but the sample stream and the filter stream should be accessable. If that's true I can't seem to understand why I get "401 Unauthorized" with the following code:
var auth = new ApplicationOnlyAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
}
};
auth.Authorize();
var twitterCtx = new TwitterContext(auth);
int count = 0;
string response = "";
(from strm in twitterCtx.Streaming
where strm.Type == StreamingType.Filter &&
strm.Track == query
select strm)
.StreamingCallback(strm =>
{
if (strm.Status != TwitterErrorStatus.Success)
{
Console.WriteLine(strm.Error.ToString());
return;
}
response += "<p>" + strm.Content + "</p>";
if (count++ >= 2)
{
strm.CloseStream();
}
})
.SingleOrDefault();
Twitter streams don't support application-only authorization. Try the SingleUserAuthorizer. Also, a 401 error can happen for several reasons and you can review the LINQ to Twitter FAQ for help.

Usage Twitter Stream api for search

i`m trying use Twitter Stream Api for searching some hashtags in Google Spreadsheet. Twitter search api useless cause i wanna trak retweet count too. My function sample here. Can anybody explain me what i must do for working well..
function miniSearch(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
// Authorize to Twitter
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(TWITTER_CONSUMER_KEY);
oauthConfig.setConsumerSecret(TWITTER_CONSUMER_SECRET);
// "twitter" value must match the argument to "addOAuthService" above.
var options = {
'method': 'POST',
"oAuthServiceName" : "twitter",
"oAuthUseToken" : "always"
};
var url = "https://stream.twitter.com/1/statuses/filter.json?track="+"twitterapi";
var response = UrlFetchApp.fetch(url, options);
var tweets = JSON.parse(response.getContentText());
sumSheet.getRange('B8').setValue(tweets[0]["text"]);
}
this function return error code 504;
I don't think Google Apps Script can keep a persistent HTTP connection open which is resulting in the 504 (See Twitter Streaming APIs Doc)
[I've a basic retweet counter in this Google Spreadsheet Template (TAGS v4.0). The filterUnique formula uses this code (the pseudocode is strip out any links from tweet text then extract 1st 90% of text (to take account of any old style RT+ annotation), then if not in unique array add or add 1 to existing value):
function filterUnique(tweets){
var output = [];
var temp = {};
for (i in tweets){
if (i>0){
var tmp = tweets[i][0];
var urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
tmp = tmp.replace(urlPattern,"")
tmp = tmp.substring(0,parseInt(tmp.length*0.9));
if (temp[tmp] == undefined){
temp[tmp] = [tweets[i][0],0];
}
temp[tmp] = [tweets[i][0],temp[tmp][1]+1];
}
}
for (i in temp){
output.push([temp[i][0],temp[i][1]]);
}
output.sort(function(a,b) {
return b[1]-a[1];
});
return output.slice(0, 12);
}
]

Get all tweets with specific hashtag

I've been experimenting with the Twitter API because I want to display a few lists of tweets on a special page.
Among those lists is a list with all tweets containing a specific hashtag (e.g. #test)
However I cannot find how to get that list in either XML or JSON (preferably the latter), does anyone know how? It is also fine if it can be done in TweetSharp
You can simply fetch http://search.twitter.com/search.json?q=%23test to get a list of tweets containing #test in JSON, where %23test is #test URL encoded.
I'm not familiar with TweetSharp, but I guess there must be a search command that you can use to search for #test, and then transform the resulting tweets into JSON yourself.
First install TweetSharp using github
https://github.com/danielcrenna/tweetsharp
Here is the code to do a search
TwitterService service = new TwitterService();
var tweets = service.Search("#Test", 100);
List<TwitterSearchStatus> resultList = new List<TwitterSearchStatus>(tweets.Statuses);
If you have more then one page results you can setup a loop and call each page
service.Search("#Test", i += 1, 100);
It seems like there is a change in the API since last few months. Here is the updated code:
TwitterSearchResult res = twitter.Search(new SearchOptions { Q = "xbox" });
IEnumerable<TwitterStatus> status = res.Statuses;
u access with this url for your tweet searchs. But u have to use OAuth protocols.
https://api.twitter.com/1.1/search/tweets.json?q=%40twitterapi
I struggled with the same problem. Here is my vague solution . Enjoy Programming.
It will get out of the function whenever your required number of tweets are acquired/fetched.
string maxid = "1000000000000"; // dummy value
int tweetcount = 0;
if (maxid != null)
{
var tweets_search = twitterService.Search(new SearchOptions { Q = keyword, Count = Convert.ToInt32(count) });
List<TwitterStatus> resultList = new List<TwitterStatus>(tweets_search.Statuses);
maxid = resultList.Last().IdStr;
foreach (var tweet in tweets_search.Statuses)
{
try
{
ResultSearch.Add(new KeyValuePair<String, String>(tweet.Id.ToString(), tweet.Text));
tweetcount++;
}
catch { }
}
while (maxid != null && tweetcount < Convert.ToInt32(count))
{
maxid = resultList.Last().IdStr;
tweets_search = twitterService.Search(new SearchOptions { Q = keyword, Count = Convert.ToInt32(count), MaxId = Convert.ToInt64(maxid) });
resultList = new List<TwitterStatus>(tweets_search.Statuses);
foreach (var tweet in tweets_search.Statuses)
{
try
{
ResultSearch.Add(new KeyValuePair<String, String>(tweet.Id.ToString(), tweet.Text));
tweetcount++;
}
catch { }
}
}

Resources