Coder Social home page Coder Social logo

dracoblue / node-facebook-client Goto Github PK

View Code? Open in Web Editor NEW
188.0 11.0 26.0 568 KB

A javascript (nodejs) implementation of facebook's client for oauth and rest+graph api

Home Page: http://dracoblue.net/c/node-facebook-client/

License: Other

JavaScript 100.00%

node-facebook-client's Introduction

node-facebook-client README

Version: 1.6.1

Official Site: http://dracoblue.net/

node-facebook-client is copyright 2010-2012 by DracoBlue http://dracoblue.net

What is node-facebook-client?

The node-facebook-client library is a set of nodejs classes to communicate with the rest and graph api provided by facebook.

It works great if you embed the facebook connect button on your page and want to use the rest + graph api by facebook. Oauth-support may work but is not tested that well.

The library is not officially created nor maintained by facebook. It is created by dracoblue and licensed under the terms of MIT License.

Example

This small example uses the FacebookClient class to retrieve the name of a user. requst.headers are the headers from the server request.

var FacebookClient = require("facebook-client").FacebookClient;

var facebook_client = new FacebookClient(
    "yourappid", // configure like your fb app page states
    "yourappsecret", // configure like your fb app page states
    {
        "timeout": 10000 // modify the global timeout for facebook calls (Default: 10000)
    }
);

facebook_client.getSessionByRequestHeaders(request.headers)(function(facebook_session) {
    facebook_session.graphCall("/me", {
    })(function(result) {
        console.log('Username is:' + result.name);
    });
    facebook_session.graphCall("/me/feed", {message:"I love node.js!"}, 'POST')(function(result) {
        console.log('The new feed post id is: ' + result.id);
    });
});

A full example may be executed with: node run_example.js. Please configure yourappid+yourappsecret in that file first.

Graph API

FacebookClient#graphCall(path, params[, method, options])

Doing a call against the graph server.

client.graphCall(path, params, method)(function(result) {
    // 
});

The parameter method can be omitted and is 'GET' in this case. You may use options.timeout = 5000 to modify the timeout until the request will be canceled.

Rest API

FacebookSession#restCall(method, params, access_token[, options])

Doing a signed call against the rest api server, by using the session of the user.

session.restCall("users.getInfo", {
    fields: "name",
    uids: session.uid
})(function(response_users) {
    // work with it
});

You may use options.timeout = 5000 to modify the timeout until the request will be canceled.

General API

FacebookClient#getSessionByRequestHeaders(request_headers)

Use the request headers to retrieve the session.

facebook_client.getSessionByRequestHeaders(request.headers)(function(facebook_session) {
    // session is either undefined or a valid FacebookSession
});

FacebookSession#isValid()

Calls /me on the graph api, to check whether the session is still valid or the user has already logged out.

session.isValid()(function(is_valid) {
    // is either true or false
});

Remember to do that only when necessary and not on every request.

FacebookClient#getSessionByAccessToken(access_token)

Creating a new FacebookSession instance with a given access_token.

FacebookSession#getId()

Retrieving the id of the session.

session.getId()(function(id) {
    // is either a string or undefined, in case the session has no id
});

FacebookSession#getMeta()

Tries to retrieve all data from the graph call /me for the user.

session.getMeta()(function(user_data) {
    // work with it
});

Internal API

FacebookClient#getAccessToken(access_params)

Retrieving an AccessToken with the given parameters. You don't need to use this function if you used FacebookClient#getSessionByRequestHeaders.

client.getAccessToken(access_params)(function(access_token, expires) {
    // 
});

FacebookSession#retrieveAccessToken(code, redirect_uri)

Retrieve an access token by providing a code and a redirect_uri. Usually from successful oauth redirect.

FacebookSession#injectAccessToken(access_token)

Used to inject an access_token into an existing FacebookSession. This will enable calls like FacebookSession#restCall and FacebookSession#graphCall to work authenticated. It is triggered by FacebookClient#getSessionByRequestHeaders after successful creation of the session.

FacebookSession#getAccessToken(access_params)

Retrieving an AccessToken with the given parameters and injecting it into the FacebookSession.

FacebookToolkit.generateSignature(params, api_secret)

Calculates the signature for a given set of parameters and the api_secret.

Changelog

  • 1.6.1 (2012/10/02)
    • removed unused sys
  • 1.6.0 (2012/01/22)
    • rewrote requests from multiple parameters to options-object
    • added options.timeout for restCall and graphCall #22
    • fixed error handling in case the timeout is reached #22
  • 1.5.3 (2012/01/22)
    • fixed issue with graphCall and method parameter #21
  • 1.5.2 (2012/01/07)
    • added multiquery-support for graphCall #12
  • 1.5.1 (2012/01/06)
    • fixed isValid: throwed an exception, when user_data.error was not existant
    • added backward compatibility for node 0.4.x, if toString('hex') was missing
  • 1.5.0 (2012/01/05)
    • added support for fbsr-cookie from new facebook auth #16
    • added support for lazy-access-token retrieval if oauth-code is given
    • added timeout of 10 seconds for each call against facebook #15
  • 1.4.0 (2011/10/06)
    • added multiquery-support. #12
  • 1.3.0 (2011/04/26)
    • added FacebookSession#isValid
    • fixed expires validation fixes #5
    • added method argument to session.graphCall to permit POSTing in addition to GETting
  • 1.2.0 (2011/03/09)
    • added support for node 0.4
  • 1.1.0 (2010/12/29)
    • removed session_key support
    • added example
  • 1.0.1 (2010/12/29)
    • added secure url for access_token
  • 1.0.0 (2010/10/05)
    • Initial release

Contributors

License

node-facebook-client is licensed under the terms of MIT. See LICENSE for more information.

node-facebook-client's People

Contributors

deedubs avatar dracoblue avatar jharlap avatar kaareal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-facebook-client's Issues

Large amount of timeouts over time

Hi, we are using this module for a lot of users on our production server. After running the nodes for a while we are experiencing a lot of timeouts, even when increasing the timeout to 20 seconds.

We've been investigating this problem for some time but still have not found the culprit. We've had several hypotheses that we have not disproved to be the problem.

  • We thought the request.on('close') event could be called earlier than the 'end' event. This is not the case.
  • We thought that perhaps sockets were not closed properly, leaving a big pile of open connections. This is not the case.

Is anyone experiencing a similar problem?

getSessionByRequestHeaders(request.headers)

In the call back function, this method is not able to detect a that the current session has been terminated if the session was terminated on facebook (rather than the aplication).

Error in running run_example.js

Hi,

I've tried running your example and I got the following error:

throw e; // process.nextTick error, or 'error' event on first tick
^
Error: socket hang up
at Client. (http.js:1493:26)
at Client.emit (events.js:42:17)
at Array. (net.js:800:12)
at EventEmitter._tickCallback (node.js:108:26)

May I know how do i fix this? I'm a node.js newbie and I'm using node.js 0.4.1.

Best Regards.

restCall fails on fql.multiquery

fql.multiquery requires a "queries" parameter that is a javascript array. At the moment the library cannot turn an array into a suitable query string, instead it casts as the string "[object Object]".

Workaround for now: write the array as a string and pass that as the "queries" parameter. This seems to work, but different compared to how other libraries do multiquery.

Weird error running the example

Hi,
I got a weird error running the example. The error message was:

node.js:183
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Cannot find module 'facebook-client'
at Function._resolveFilename (module.js:322:11)
at Function._load (module.js:267:25)
at require (module.js:367:19)
at Object. (/home/eugene/public_html/nodejs/examples/DracoBlue-node-facebook-client-1fe4a7e/run_example.js:2:22)
at Module._compile (module.js:423:26)
at Object..js (module.js:429:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at Array. (module.js:442:10)
at EventEmitter._tickCallback (node.js:175:26)

May i know why is facebook-client missing?

I simply downloaded node-facebook-client and extracted it into a folder, than ran the example after changing the appid and secret.

I'm using node-facebook-client v1.3.0 and node.js version 0.5.0-pre ( the latest version as of today ).

Am i missing anything?

Possible to do FQL queries using this library?

Is it possible to make run Facebook Query Language queries using this library?

https://developers.facebook.com/docs/reference/fql/

Trying to port some functionality from Ruby in which I used https://github.com/nov/fb_graph to issue FQL queries. Something like:

query = "select ... from ..."
posts   = FbGraph::Query.new(query).fetch(user.access_token)

Thanks for the hard work on this library, looks very cool, and I will probably use it either way. (FQL will just save me time writing the particular actions I need.)

Facebook Connection problem (>100 concurrent users)

Hi,
I tried Facebook client with my project, it works fine under development.
But after put on production server, there was a problem when more user access (>100 concurrent), Facebook client caused node to stop responding. And when I checked the server traffic, report shown that the all requests to Facebook API got freeze and nothing return.
When I restarted node, everything go back to work perfectly, but only for a short period of time. Whenever more user enter the site, same problem happened again.
Do you have any idea..? Really need help.

Not able to parse facebook cookie from request.headers

Hi There,

var facebook_cookie_raw = request_headers["cookie"].match(/fbs_[\d]+="([^; ]+)"/); is returning null in FacebookClient.js for the valid facebook cookie

my req.headers.cookie has the format
'"fbsr_116977245018363=MmGgHKw9HEk9U28uapJ0plycsXtKFVfh1JNQi4v_sBo.eyJhbGdvcml0aG0... (length: 276)"

which i am assuming is the right value, because i am logged in to facebook but because above matching returns null.. facebook client doesn't gives me the session back.

Any idea?

Thanks in advance ;)

Improve error handling

hey,

thanks for you work so far.

However, I'd appreciate some proper error handling, at best in a (de-facto) standard way, i.e. calling callbacks like

cb(error)

when an error occured,
or

cb(null, result)

when everything is alright and we just want to pass the result.

I can change that myself but would like to know your feedback first

html returned sometimes which causes stacktrace

Every once and a while FB probably messes up and starts to return junk which causes a stack trace...

2012-12-22 00:59:51+00:00 app web.3     - - undefined:1
2012-12-22 00:59:51+00:00 app web.3     - - <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2012-12-22 00:59:51+00:00 app web.3     - - ^
2012-12-22 00:59:51+00:00 app web.3     - - SyntaxError: Unexpected token <
    at Object.parse [as parser] (native)
    at IncomingMessage.<anonymous> (/app/node_modules/facebook-client/lib/facebook-client/FacebookClient.js:70:28)
    at IncomingMessage.EventEmitter.emit (events.js:126:20)
    at IncomingMessage._emitEnd (http.js:366:10)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
    at CleartextStream.socketOnData [as ondata] (http.js:1367:20)
    at CleartextStream.CryptoStream._push (tls.js:526:27)
    at SecurePair.cycle (tls.js:880:20)
    at EncryptedStream.CryptoStream.write (tls.js:267:13)
    at Socket.ondata (stream.js:38:26) EXCEPT

cookie expiration check reversed

    var now = new Date();
    var expires_time = parseInt(facebook_cookie['expires'], 10) * 1000;

    if (now.getTime() < expires_time)
    {
        /*
         * The token is expired.
         */
        cb();
        return ;
    }

makes no sense - the cookie is supposed to expire in the future (replace < with >)
this breaks for me with run_example.js

Any way to know when user logged out of FB?

I can't figure out how to detect that user has logged out from Facebook without calling isValid() on every request. In my case, I keep getting valid session from getSessionByRequestHeaders() even if I log out of Facebook. I have to actually delete Facebook cookies to see that session is undefined.

Avoid double-checking returned values

Currently, FacebookClient#getSessionByRequestHeaders() returns either a session object or undefined. At the same time, FacebookSession#isValid() is supposed to be called on a session object that's returned by getSessionByRequestHeaders method. If user is not logged in - calling isValid throws a TypeError.

I suggest that getSessionByRequestHeaders should return something that isValid can be called on regardless of login status. This way, there would be no need to check if session is not undefined before attempting to validate it.

Configurable timeout?

Some of my queries sometimes take longer than 10 seconds to execute.

I tried to fork and make a patch to pass in a custom timeout, but your function returns function way of structuring things makes it very hard to get down to the core components.

Any way you could add a configurable timeout?

Thanks,
~Jordan

btw, this library rocks. Thanks. 

FacebookClient.getSessionByFbsrCookie fails in node 0.4.7

The error thrown is

Error: Unknown encoding
at Buffer.toString (buffer.js:321:13)
at /Users/lenny/dev/node/stef-dev/node_modules/facebook-client/lib/facebook-client/FacebookClient.js:238:108
at /Users/lenny/dev/node/stef-dev/node_modules/facebook-client/lib/facebook-client/FacebookClient.js:321:63

This is because version 0.4.7 does not support "hex" enconding.

Facebook stops responding after a while

We are also using the Facebook client, and we seem to be experiencing the same issue as reported by Ran (reported on your weblog). We request the facebook api every 30 seconds for an update, and do that for multiple users (separately in their own respective loops). After a while, facebook stops responding, and all requests freeze and return nothing. Only after a restart of node everything works fine again, until facebook stops responding again. Do you have any idea? Could it be caused by the fact that every request is done with the same agent?
I don't believe we are hitting some Facebook limit, otherwise a restart wouldn't help. Any help here is greatly appreciated.

The freezing issue could be related to an https issue in node, see nodejs/node-v0.x-archive#728 which is fixed in node after v0.4.12, but this is just a wild guess.

publish v1.6.1 to npm

Hello :)

The current version in the repo is 1.6.1 but on npm the latest published version is 1.6.0

Add method to FacebookClient to parse signed_request

When working with an app directly on Facebook or installed in a Facebook Page, Facebook makes a POST to the url set in the config with a signed_request. This is basically the same that the cookie stores when calling FB.init from client side with cookies enabled.

But there are times that you need to access the signed_request that the first POST gives you, because it contains extra data already sent by Facebook. To be concrete, my case is that I need to know wether a user accesing the app installed in a Facebook Page likes that page. Facebook sends that info in the signed_request.

It would be great if this lib had a method for parsing the signed_request. In fact, by looking at the code, that is almost done in getSessionByFbsrCookie. I created the parse_request method by copying some of the code there:

    function parse_signed_request(signed_request, secret) {
        var encoded_data = signed_request.split('.');

        var signature = facebook.convertBase64ToHex(encoded_data[0].replace(/\-/g, '+').replace(/\_/g, '/'));
        var payload = encoded_data[1];
        var data_raw_json = new Buffer(payload.replace(/\-/g, '+').replace(/\_/g, '/'), 'base64').toString('binary');

        var data;

        try
        {
            data = JSON.parse(data_raw_json);
        }
        catch (error)
        {
            data = null;
        }

        if (!data) return null;

        if (!data['algorithm'] || !data['issued_at']) {
          return null;
        }

        if (data['algorithm'].toUpperCase() != 'HMAC-SHA256')
        {
            return null;
        }

        var expected_signature = facebook.signaturePayload(payload);

        if (expected_signature !== signature)
        {
            return null;
        }

        return data;
    }

I think from here you can add the method in FacebookClient.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.