How to mark items read with google reader API? - google-reader

I've been working on a client for google reader. Everything works fine, except that I can't edit entries to add tags such as "starred" and "read." The instructions at code.google.com/p/pyrfeed/wiki/GoogleReaderAPI and www.niallkennedy.com/blog/2005/12/google-reader-api.html seem to be outdated. What's more odd is that I've been inspecting the POST data that google itself uses and attempting to replicate it exactly, but I still can't get it to work. The closest I've come is, for example, http://www.google.com/reader/api/0/edit-tag with POST data a=/user/-/state/com.google/starred&async=true&s=[feed]&i=[item]&T=[token]
This seems to be exactly what google itself does, but I lways get back "Invalid Stream Name." Any advice?

I don't have a definitive answer for you, but I was also having some trouble with the API api/0/edit-tag and managed to get them working.
I was already using other parts of the API without any trouble (api/0/stream/items/ids, api/0/unread-count), but this one was not working as easily.
After a while, I started over by inspecting the requests sent to Google Reader by their web frontend (using Chrome dev tools), and made an hardcoded example (you can use this code and you just need to change the ids and stream for you own - just be careful that they have all the needed prefixes: feed/ for stream, and tag:google.com,2005:reader/item/ for id).
String authToken = getGoogleAuthKey();
// I use Jsoup for the requests, but you can use anything you
// like - for jsoup you usually just need to include a jar
// into your java project
Document doc = Jsoup.connect("http://www.google.com/reader/api/0/edit-tag")
.header("Authorization", _AUTHPARAMS + authToken)
.data(
// you don't need the userid, the '-' will suffice
"a", "user/-/state/com.google/read",
"async", "true",
"s", "feed/http://www.gizmodo.com/index.xml",
"i", "tag:google.com,2005:reader/item/1a68fb395bcb6947",
"T", "//wF1kyvFPIe6JiyITNnMWdA"
)
// I also send my API key, but I don't think this is mandatory
.userAgent("[YOUR_APP_ID_GOES_HERE].apps.googleusercontent.com")
.timeout(10000)
// don't forget the post! (using get() will not work)
.**post()**;
Here is my final code for marking a specific item from a stream as read (the translateToItemAtomId method is used for converting the long integer ids as returned by api/0/stream/items/ids into the atom xml ids accepted by this API):
String authToken = getGoogleAuthKey();
Document doc = Jsoup.connect("http://www.google.com/reader/api/0/edit-tag")
.header("Authorization", _AUTHPARAMS + authToken)
.data(
"a", "user/-/state/com.google/read",
"async", "true",
"s", stream,
"i", translateToItemAtomId(itemId),
"T", getGoogleToken(authToken)
)
.userAgent("[YOUR_APP_ID_GOES_HERE].apps.googleusercontent.com")
.timeout(10000).post();
Some extra code you may need (based on http://www.chrisdadswell.co.uk/android-coding-example-authenticating-clientlogin-google-reader-api/):
private static final String _AUTHPARAMS = "GoogleLogin auth=";
private static final String _GOOGLE_LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
private static final String _READER_BASE_URL = "http://www.google.com/reader/";
private static final String _API_URL = _READER_BASE_URL + "api/0/";
private static final String _TOKEN_URL = _API_URL + "token";
private static final String _USER_INFO_URL = _API_URL + "user-info";
private static final String _USER_LABEL = "user/-/label/";
private static final String _TAG_LIST_URL = _API_URL + "tag/list";
private static final String _EDIT_TAG_URL = _API_URL + "tag/edit";
private static final String _RENAME_TAG_URL = _API_URL + "rename-tag";
private static final String _DISABLE_TAG_URL = _API_URL + "disable-tag";
private static final String _SUBSCRIPTION_URL = _API_URL
+ "subscription/edit";
private static final String _SUBSCRIPTION_LIST_URL = _API_URL
+ "subscription/list";
public static String getGoogleAuthKey() throws IOException {
String _USERNAME = "USER_EMAIL#gmail.com";
String _PASSWORD = "USER_PASSWORD";
Document doc = Jsoup
.connect(_GOOGLE_LOGIN_URL)
.data("accountType", "GOOGLE", "Email", _USERNAME, "Passwd",
_PASSWORD, "service", "reader", "source",
"[YOUR_APP_ID_GOES_HERE].apps.googleusercontent.com")
.userAgent("[YOUR_APP_ID_GOES_HERE].apps.googleusercontent.com")
.timeout(4000).post();
// RETRIEVES THE RESPONSE TEXT inc SID and AUTH. We only want the AUTH
// key.
String _AUTHKEY = doc
.body()
.text()
.substring(doc.body().text().indexOf("Auth="),
doc.body().text().length());
_AUTHKEY = _AUTHKEY.replace("Auth=", "");
return _AUTHKEY;
}
// generates a token for edition, needed for edit-tag
public static String getGoogleToken(String authToken) throws IOException {
Document doc = Jsoup.connect(_TOKEN_URL)
.header("Authorization", _AUTHPARAMS + getGoogleAuthKey())
.userAgent("[YOUR_APP_ID_GOES_HERE].apps.googleusercontent.com")
.timeout(10000).get();
// RETRIEVES THE RESPONSE TOKEN
String _TOKEN = doc.body().text();
return _TOKEN;
}
Hope this helps!

Related

Getting all possible values for a key in Firebase's Remote Config

I'm trying to build a settings screen in developer mode in which we can test toggling the different values for a remote config setting using Firebase.
I have been able to get all the keys from Firebase's remoteConfig but can only manage to get the value applied for the current client.
Anyone knows if it's possible to check for all possible values from Firebase?
Manage your configs with something like this:
public class RemoteConfig {
public final static String CONFIG_X = "CONFIG_X";
public final static String CONFIG_Y = "CONFIG_Y";
private final static List<String> keys = new ArrayList<String>(0);
static {
values.add(CONFIG_X);
values.add(CONFIG_Y);
}
public static List<String> getKeys(){
return values;
}
}
And Getting All with this;
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
List<String> remoteConfigs = new ArrayList<>();
for (String key : RemoteConfig.getKeys()) {
String keyValue = String.format("%s: %s", key, mFirebaseRemoteConfig.getString(key));
remoteConfigs.add(keyValue);
}

Create and share Google Drive folders dynamically

I have a list of emails.
For each email, I need to create a Google Drive folder and share it with the given email.
How can I do it programmically?
I am using ASP.NET 4.0.
First of all you need to make sure you have application with clientid/secret and correct redirect uri configured. For my case - it's a desktop application:
So far you'll get clientId/secret key:
Now it's time to write some codes!
Step 1 - authorization:
private async static Task<UserCredential> Auth(ClientSecrets clientSecrets)
{
return await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, Scopes, "user", CancellationToken.None);
}
Step 2 - construct your client for google drive:
private static DriveService GetService(UserCredential credential)
{
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApplicationName",
});
}
Step 3 - create folder (or any other content):
private static string CreateFolder(DriveService service, string folderName)
{
var file = new File {Title = folderName, MimeType = "application/vnd.google-apps.folder"};
var result = service.Files.Insert(file).Execute();
return result.Id;
}
Step 4 - share it!
/// <summary>
/// Share content. Doc link: https://developers.google.com/drive/v2/reference/permissions/insert
/// </summary>
private static void Share(DriveService service, string fileId, string value, string type, string role)
{
var permission = new Permission {Value = value, Type = type, Role = role};
service.Permissions.Insert(permission, fileId).Execute();
}
And finally usage of whole thing:
static void Main(string[] args)
{
var ClientId = "MySecredId";
var SecretKey = "MySecretKey";
var Scopes = new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive };
var secrets = new ClientSecrets { ClientId = ClientId, ClientSecret = SecretKey };
var credentials = Auth(secrets).Result;
var service = GetService(credentials);
var folderId = CreateFolder(service, "folderName");
Share(service, folderId, "user#gmail.com", "user", "reader");
}
For list of emails you can do pretty same thing creating/sharing content in a loop for every email you have.
Some usefull links:
Creating files
Sharing files
Also
You'll need Google.Apis.Drive.v2 nuget package
The steps to perform this hinge on authenticating with Google first. Once you've done that you'll be able to access the Drive API to perform the actions you'd like. The following links walk you through everything you need to do.
Step 1: Authenticate (server side in your case as you're using ASP.NET)
https://developers.google.com/drive/web/auth/web-server
Step 2: Create your folders
https://developers.google.com/drive/web/folder
Step 3: Share your folders
https://developers.google.com/drive/web/manage-sharing
Take a look in below link. It have full course on Google Drive !!
https://www.codeschool.com/courses/discover-drive

Request email from OAuthWebSecurity.RegisterMicrosoftClient

I am trying to integrate oauth authentication from an MVC 4 project to Microsoft (Live service). The followings lines in AuthConfig.cs have been uncommented:
OAuthWebSecurity.RegisterMicrosoftClient(
clientId: "XXX",
clientSecret: "XXX");
And, the app has been set up at https://manage.dev.live.com
Later, when OAuthWebSecurity.VerifyAuthentication is called, I get back the success status, but the email field is not in the returned data.
How can I request an email to be returned from VerifyAuthentication call issued again Microsoft account?
Thanks.
First, you should implement a 'MicrosoftScopedClient' class which implements 'IAuthenticationClient ' interface, and that should implement two methods of interface which is;
public class MicrosoftScopedClient : IAuthenticationClient
{
//Define following three keys in Web.Config file and use it in code, it will maintain code consistency.
private string clientId;
private string clientSecret;
private string scope;
private const string baseUrl = "https://login.live.com/oauth20_authorize.srf";
private const string tokenUrl = "https://login.live.com/oauth20_token.srf";
public void RequestAuthentication(HttpContextBase context, Uri returnUrl)
{
//Getting values of clientId, clientSecret and scope from Web.Config file
clientId=System.Configuration.ConfigurationManager.AppSettings["msClientId"].ToString();
clientSecret=System.Configuration.ConfigurationManager.AppSettings["msClientSecret"].ToString();
scope=System.Configuration.ConfigurationManager.AppSettings["msScope"].ToString();
string url = baseUrl + "?client_id=" + clientId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&scope=" + HttpUtility.UrlEncode(scope) + "&response_type=code";
//this will authenticate the user and register(only if user visited first time).
context.Response.Redirect(url);
}
public AuthenticationResult VerifyAuthentication(HttpContextBase context)
{
string code = context.Request.QueryString["code"];
string rawUrl = context.Request.Url.ToString();
//removing code portion
rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");
IDictionary<string, string> userData = GetUserData(code, rawUrl);
if (userData == null)
return new AuthenticationResult(false, ProviderName, null, null, null);
string id = userData["id"];
string username = userData["email"]; // here you'll get email id of user
userData.Remove("id");
userData.Remove("email");
AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData);
return result;
}
}
////// Finally you need to register all stuffs in AuthConfig.cs and interact with Microsoft through our application.
OAuthWebSecurity.RegisterClient(new MicrosoftScopedClient(System.Configuration.ConfigurationManager.AppSettings["msClientId"].ToString(),
System.Configuration.ConfigurationManager.AppSettings["msClientSecret"].ToString(),
"wl.basic wl.emails"
)
, "Microsoft", null);

how to return list in asp.net to a json post

So in my web service i get the data from textboxes search it in database and create letter objects.Then add those objects to a list.my question is how do i return the list to my web page and create divs. for example if service finds 5 letters how i do i return them and create 5 different divs with their data.Thanks in advance
public Letter(string lid, string companyname, string personname, string email, string fax, string phone, string industryname, string teamname, string sender, string statusname, string description, string date)
{
LID = lid;
CompanyName = companyname;
PersonName = personname;
Email = email;
Fax = fax;
Phone = phone;
IndustryName = industryname;
TeamName = teamname;
Sender = sender;
StatusName = statusname;
Description = description;
Date = date;
}
You just need to decorate your web services with ScriptService attribute and it will return response in raw json format. For more info check it out here and you also want to check out this.
Once you get Json response, you can do something like this to render the output as per your requirement. It's not exactly what you're looking for but it will give you an idea how to proceed further.
In .net 3.5 you can create json by using the System.Web.Script.Serialization.JavaScriptSerializer otherwise you have to do it manually or by a 3rd party component.

Serverside ecommerce transaction push to google analytics

I'm trying to push an ecommerce transaction with minimal information
to analytics, following are two method implementation of it but none
seem to work. These methods are constructed by referring to the
documentation and code snippets on forums.
public static void pushToGoogleAnalytics(String analyticsCode, String
domain, String product_sku, String product) {
Map<String, String> params=new TreeMap<String, String>();
params.put("utmwv", 4+"");
params.put("utmn", new Random().nextInt(2147483647)+"");
params.put("utmhn", domain);
params.put("utmipc", product_sku);
params.put("utmipn", product);
params.put("utmtid", product_sku);
params.put("utmdt", product);
params.put("utmp", "/");
params.put("utmhn", domain);
params.put("utmac", analyticsCode);
params.put("utmcc", "__utma%3D999.999.999.999.999.1%3B");
try {
byte[] response = URLUtils.get(new URL("http://www.google-
analytics.com/__utm.gif"), params);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void pushToGoogleAnalytics(String analyticsCode, String
domain, String product_sku, String product) {
String var_utmac = analyticsCode;
String var_utmhn = domain; // domain
String var_utmn = random(1000000000,2147483647)+""; // random number
String var_cookie = random(10000000,99999999)+""; //random cookie
number
String var_random = random(1000000000,2147483647)+""; //number under
2147483647
String var_today = Utils.getNow().getTime()+"";
String var_uservar="-"; // no user-defined
String urchinUrl="http://www.google-analytics.com/__utm.gif?
utmwv=3&utmn="+var_utmn+"&utmipc="+product_sku+"&utmipn="+product
+"&utmtid="+product_sku+"&utmdt=test&utme=&utmcs=-&utmsr=-&utmsc=-
&utmul=-&utmje=0&utmfl=-&utmdt=-&utmhn="+var_utmhn+"&utmhid="+var_utmn
+"&utmac="+var_utmac+"&utmcc=__utma%3D"+var_cookie+"."+var_random
+"."+var_today+"."+var_today+"."+var_today+".2%3B%2B__utmz
%3D"+var_cookie+"."+var_today+".2.2.utmcsr%3D_SOURCE_%7Cutmccn
%3D_CAMPAIGN_%7Cutmcmd%3D_MEDIUM_%7Cutmctr%3D_KEYWORD_%7Cutmcct
%3D_CONTENT_%3B%2B__utmv%3D"+var_cookie+"."+var_uservar+"%3B";
// urchinUrl=urchinUrl.replace("&", "&");
byte[] response = URLUtils.readURL(urchinUrl);
System.err.println("google analytics push URL: "+urchinUrl);
}
Please have a look at this article I've recently published about pushing data to Google Analytics via Python.
Note that it gives you only the bare minimum and you can easily convert it to your favourite language. You'll need to add e-commerce related parameters though.

Resources