Permalink
Browse files

graph api working

  • Loading branch information...
1 parent 733f4fb commit c691b57a4cad8c630a96ec6f1242dbabed4c761d @mackers mackers committed Mar 29, 2011
View
@@ -301,13 +301,10 @@ var fbLib = {
FacebookLogin: function() {
- gBrowser.selectedTab = gBrowser.addTab("https://www.facebook.com/dialog/oauth?client_id=117949738281674&redirect_uri=http://www.facebook.com/&scope=user_photos,&response_type=token");
-
- return;
-
if (fbSvc.loggedIn) {
dump('logging out\n');
+ /*
// Some methods require us to get the wrapped object (namely getCommonParams())
var facebookSvc = Cc['@facebook.com/facebook-service;1'].
getService(Ci.fbIFacebookService).
@@ -319,12 +316,16 @@ var fbLib = {
req.send('api_key=' + facebookSvc.apiKey +
'&uid=' + facebookSvc.loggedInUser.id +
'&session_key=' + facebookSvc.getCommonParams().session_key);
+ */
+
fbSvc.sessionEnd();
} else {
+
+ gBrowser.selectedTab = gBrowser.addTab("https://www.facebook.com/dialog/oauth?client_id=117949738281674&redirect_uri=http://www.facebook.com/&scope=user_photos,publish_stream,status_update,friends_status&response_type=token");
+
// popup login page height is at most 500, but add 20 pixels for the
// button we show at the bottom of the page
- window.open('chrome://facebook/content/login.xul', '',
- 'chrome,centerscreen,width=646,height=520,modal=yes,dialog=yes,close=yes');
+ //window.open('chrome://facebook/content/login.xul', '','chrome,centerscreen,width=646,height=520,modal=yes,dialog=yes,close=yes');
}
},
@@ -51,7 +51,7 @@ if (typeof(JSON) == "undefined") {
JSON.stringify = JSON.toString;
}
-const DEBUG = false;
+const DEBUG = true;
// Debugging.
function LOG(s) {
@@ -404,11 +404,12 @@ var PhotoSet = {
return mis;
},
- _uploadPhoto: function(albumId, photo, onProgress, onComplete, onError) {
+ _uploadPhoto: function(albumId, objectId, photo, onProgress, onComplete, onError) {
LOG("Uploading photo: " + photo);
var params = {};
+ /*
// method specific:
params.method = "facebook.photos.upload";
params.aid = albumId;
@@ -425,8 +426,9 @@ var PhotoSet = {
paramsForSig.push(name + "=" + value);
}
params.sig = gFacebookService.generateSig(paramsForSig);
+ */
- const RESTSERVER = 'http://api.facebook.com/restserver.php';
+ //const RESTSERVER = 'http://api.facebook.com/restserver.php';
var xhr = new XMLHttpRequest();
@@ -444,7 +446,10 @@ var PhotoSet = {
xhr.upload.onprogress = updateProgress;
}
- xhr.open("POST", RESTSERVER);
+ var postURL = "https://graph.facebook.com/" + objectId + "/photos?access_token=" + gFacebookService.accessToken;
+ LOG("post url = " + postURL);
+
+ xhr.open("POST", postURL);
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
xhr.setRequestHeader("MIME-version", "1.0");
@@ -453,6 +458,8 @@ var PhotoSet = {
if (xhr.readyState != 4)
return;
+ LOG("upload api response: " + xhr.responseText);
+
try {
var data = JSON.parse(xhr.responseText);
} catch(e) {
@@ -496,15 +503,15 @@ var PhotoSet = {
);
},
- _uploadAndTagPhoto: function(albumId, photo, onProgress, onComplete, onError) {
- this._uploadPhoto(albumId, photo, onProgress,
+ _uploadAndTagPhoto: function(albumId, objectId, photo, onProgress, onComplete, onError) {
+ this._uploadPhoto(albumId, objectId, photo, onProgress,
function(photoId) { // onComplete callback
PhotoSet._tagPhoto(photo, photoId, onComplete, onError);
},
onError);
},
- upload: function(albumId, onProgress, onComplete, onError) {
+ upload: function(albumId, objectId, onProgress, onComplete, onError) {
this._cancelled = false;
var toUpload = this._photos;
var total = toUpload.length;
@@ -533,7 +540,7 @@ var PhotoSet = {
var photoSize = photo.sizeInBytes;
try {
- self._uploadAndTagPhoto(albumId, photo,
+ self._uploadAndTagPhoto(albumId, objectId, photo,
function(photoPercent) { // onProgress callback
LOG("on progress from photo upload " + photoPercent);
var donePercent = (uploadedBytes / totalSizeBytes) * 100;
@@ -1171,9 +1178,10 @@ var PhotoUpload = {
var menuitem = document.createElement("menuitem");
menuitem.setAttribute("label", album.name);
menuitem.setAttribute("albumid", album.aid);
+ menuitem.setAttribute("objectid", album.object_id);
if (album.aid == lastAlbumId)
selectedItem = menuitem;
- LOG("Album name: " + album.name + " album id: " + album.aid);
+ LOG("Album name: " + album.name + " object id: " + album.object_id + " album id: " + album.aid);
albumsPopup.insertBefore(menuitem, albumsPopupPlaceHolder);
}
var albumsList = document.getElementById("albumsList");
@@ -1436,7 +1444,7 @@ var PhotoUpload = {
this._uploadComplete(UPLOAD_ERROR, null, "Unexpected state");
return;
}
- this._uploadToAlbum(albumsList.selectedItem.getAttribute("albumid"));
+ this._uploadToAlbum(albumsList.selectedItem.getAttribute("albumid"), albumsList.selectedItem.getAttribute("objectid"));
},
/**
@@ -1470,14 +1478,14 @@ var PhotoUpload = {
* in a separate method in order to be called asynchronously when creating
* a new album
*/
- _uploadToAlbum: function(albumId) {
+ _uploadToAlbum: function(albumId, objectId) {
if (this._uploadCancelled) {
this._uploadComplete(UPLOAD_CANCELLED, albumId);
return;
}
var self = this;
- PhotoSet.upload(albumId,
+ PhotoSet.upload(albumId, objectId,
function(percent) { // onProgress callback
LOG("Got progress " + percent);
self._uploadProgress.value = percent;
@@ -157,7 +157,9 @@ var facebook = {
if (tup[0] == "access_token")
{
event.originalTarget.defaultView.close();
- fbSvc.sessionStart(tup[1]);
+ fbLib.debug( "have access token : " + tup[1]);
+ fbSvc.sessionStartOAuth(tup[1]);
+ fbLib.debug( "finished session start");
}
}
}
View
@@ -20,7 +20,7 @@
const BASE_CHECK_INTERVAL = 5*60*1000; // 5 minutes
const DEBUG = true;
-const VERBOSITY = 0; // 0: no dumping, 1: normal dumping, 2: massive dumping
+const VERBOSITY = 2; // 0: no dumping, 1: normal dumping, 2: massive dumping
var debug = ( VERBOSITY < 1 )
? function() {}
@@ -459,6 +459,9 @@ facebookService.prototype = {
get numGroupInvs() { return this._groupInvs.count; },
// ----------- End Notifications -----------------//
+ get accessToken() {
+ return this._accessToken;
+ },
get apiKey() {
return this._apiKey;
},
@@ -476,6 +479,17 @@ facebookService.prototype = {
return Boolean(this._canSetStatus);
},
savedSessionStart: function() {
+ var accessToken = this._prefService.getCharPref('extensions.facebook.access_token');
+
+ debug("saved access token: " + accessToken);
+
+ if (accessToken)
+ {
+ this.sessionStartOAuth(accessToken);
+ }
+
+ return;
+
var uid = this._prefService.getCharPref('extensions.facebook.uid');
if (!uid) {return;}
debug( 'SAVED SESSION', uid );
@@ -506,22 +520,39 @@ facebookService.prototype = {
this.sessionStart( session_key.value, session_secret.value, uid, true );
}
},
- sessionStart: function(accessToken) {
+ sessionStartOAuth: function(accessToken) {
debug('sessionStart2');
this._accessToken = accessToken;
- this._loggedIn = true;
- this._timer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
- this._timer.initWithCallback(this._checker, BASE_CHECK_INTERVAL/5, Ci.nsITimer.TYPE_REPEATING_SLACK);
+ var fbSvc = this;
- // fire off another thread to get things started
- this._oneShotTimer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
- this._oneShotTimer.initWithCallback(this._initialize, 1, Ci.nsITimer.TYPE_ONE_SHOT);
+ this.fetchGraphObject("me", function(response)
+ {
+ if (response.id)
+ {
+ fbSvc._uid = response.id;
+ fbSvc._loggedIn = true;
+ fbSvc._prefService.setCharPref('extensions.facebook.access_token', accessToken)
+ fbSvc._prefService.setCharPref('extensions.facebook.uid', response.id)
+ }
+ else
+ {
+ debug("missing id in 'me' graph call :(");
+ return;
+ }
- this.checkCanSetStatus();
+ fbSvc._timer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
+ fbSvc._timer.initWithCallback(fbSvc._checker, BASE_CHECK_INTERVAL/5, Ci.nsITimer.TYPE_REPEATING_SLACK);
+
+ // fire off another thread to get things started
+ fbSvc._oneShotTimer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
+ fbSvc._oneShotTimer.initWithCallback(fbSvc._initialize, 1, Ci.nsITimer.TYPE_ONE_SHOT);
+
+ fbSvc.checkCanSetStatus();
+ });
},
- sessionStartOLD: function(sessionKey, sessionSecret, uid, saved) {
+ sessionStart: function(sessionKey, sessionSecret, uid, saved) {
debug( 'sessionStart', sessionKey, sessionSecret, uid );
if (!sessionKey || !sessionSecret || !uid) {
debug('sessionStart called with invalid values, aborting');
@@ -579,6 +610,7 @@ facebookService.prototype = {
// remove session info from prefs because of explicit logout
// or because they didn't work
this.savePref( 'extensions.facebook.uid', '' );
+ this.savePref( 'extensions.facebook.access_token', '' );
if (this._ff3Login) { // Clear out saved information for this extension
var hostname = PASSWORD_URL;
var formSubmitURL = PASSWORD_URL;
@@ -665,6 +697,10 @@ facebookService.prototype = {
checkCanSetStatus: function() {
if (null != this._canSetStatus) {return;}
+ fbSvc._canSetStatus = 1;
+
+ return;
+
this.callMethod('facebook.users.hasAppPermission', ['ext_perm=status_update'], function(data){
vdebug('data:', data);
@@ -1017,13 +1053,56 @@ facebookService.prototype = {
}
this._lastCallId = callId;
return {
- 'session_key': this._sessionKey,
- 'api_key': this._apiKey,
- 'v': '1.0',
- 'call_id': callId,
+ //'session_key': this._sessionKey,
+ //'api_key': this._apiKey,
+ //'v': '1.0',
+ //'call_id': callId,
'format': 'json'
};
},
+
+
+ fetchGraphObject: function(obj, callback)
+ {
+ if (!this._accessToken)
+ {
+ debug("Can't fetch graph object: missing access token");
+ return;
+ }
+
+ var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
+ .createInstance(Components.interfaces.nsIXMLHttpRequest);
+ req.onreadystatechange = function(e)
+ {
+ try
+ {
+ if (req.readyState != 4) { return; }
+
+ debug("finished graph call, status = " + req.status);
+ debug("graph response: " + req.responseText);
+
+ if (req.status != 200)
+ {
+ //TODO
+ return;
+ }
+
+ var jsObject = JSON.parse(req.responseText);
+
+ callback(jsObject);
+ }
+ catch (e)
+ {
+ // TODO
+ debug("graph error: " + e);
+ return;
+ }
+
+ };
+ req.open("GET", "https://graph.facebook.com/" + obj + "?access_token=" + this._accessToken, true);
+ req.send(null);
+ },
+
// Note that this is intended to call non-login related Facebook API
// functions - ie things other than facebook.auth.*. The login-related
// calls are done in the chrome layer because they are in direct response to user actions.
@@ -1055,12 +1134,12 @@ facebookService.prototype = {
}
var message = paramsEncoded.join('&');
- //dump("api message: " + message + " \n");
+ dump("api message: " + message + " \n");
try {
// Yuck...xmlhttprequest doesn't always work so we have to do this
// the hard way. Thanks to Manish from Flock for the tip!
- var restserver = 'http://api.facebook.com/method/'+method;
+ var restserver = 'https://api.facebook.com/method/'+method;
var channel = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService)
.newChannel(restserver, null, null)
.QueryInterface(Ci.nsIHttpChannel);
@@ -1087,6 +1166,7 @@ facebookService.prototype = {
onStopRequest: function(request, context, statusCode) {
if (statusCode == Components.results.NS_OK) {
var data = null;
+ vdebug("raw response from callMethod: '" + this.resultTxt + "'");
// native JSON seems to have problems parsing
// primitives like "true", "1", etc. as of FF3.1b2
try {
View
Binary file not shown.
@@ -18,6 +18,7 @@ pref("extensions.facebook.notifications.upload.complete", true);
pref("extensions.facebook.notifications.growl", false);
// populated on login
pref("extensions.facebook.uid", "" );
+pref("extensions.facebook.access_token", "" );
// What to do after a photo upload:
// 0: ask user
// 1: open album page
View
@@ -40,12 +40,14 @@ interface fbIFacebookService : nsISupports
{
readonly attribute AString apiKey;
readonly attribute AString secret;
+ readonly attribute AString accessToken;
// login.xul is responsible for performing the login sequence. Once that
// is finished, it should call sessionStart, which initiates the polling
// process. If the session ever ends, the polling will stop until
// sessionStart is called again. Aside from the facebook.auth methods,
// all other Facebook API calls should be done inside this service.
+ void sessionStartOAuth(in AString accessToken);
void sessionStart(in AString sessionKey, in AString sessionSecret, in AString uid);
void savedSessionStart(); // attempt to start a saved session
void sessionEnd();

0 comments on commit c691b57

Please sign in to comment.