Giter Site home page Giter Site logo

node-flickrapi's Introduction

THIS PROJECT HAS BEEN ARCHIVED, YOU ALMOST CERTAINLY WANT TO USE THE Flickr-SDK PACKAGE INSTEAD


A Node.js and browser Flickr API library

With oauth authentication for Flickr API keys if you're using it server-side (authenticated calls from the browser are too insecure to support for the moment, and will throw an error).

You also get API route proxying so you can call the Flickr methods through your own server and get Flickr responses back for free. Super handy!

Quick start guide:

You don't want to read this entire README.md, so just find what you want to do in this handy quick start guide right here at the start of the README, and off you go!

In the browser with client-side credentials:

Script-load the browser/flickrapi.dev.js library for development work, and use the browser/flickrapi.js library in production.

You can access Flickr by creating an API instance as:

var flickr = Flickr.tokenOnly({
  api_key: "1234ABCD1234ABCD1234ABCD1234ABCD"
});

Then query Flickr using the API as described over at http://www.flickr.com/services/api - for instance, to search for all photographs that text-match the terms "red panda", you call:

flickr.photos.search({
  text: "red+panda"
}, function(err, result) {
  if(err) { throw new Error(err); }
  // do something with result
}

All calls are asynchronous, and the callback handling function always has two arguments. The first, if an error occurs, is the error generated by Flickr; the second, if the call succeeds, is the result sent back from Flickr, as plain JavaScript object.

Note: this is not secure. People will be able to see your API key, and this is pretty much the worst idea(tm), so you probably want to use this library...

In the browser, securely via proxied API calls:

Script-load the browser/flickrapi.dev.js library for development work, and use the browser/flickrapi.js library in production, but don't use your API key. Instead, point to your server as a flickr API proxy:

var flickr = new Flickr({
  endpoint: "http//yourhostedplace/services/rest/"
});

To make this work, have flickapi running on your server with a proxy route enabled, and you'll be able to make use of all the Flickr API calls, without having to put your credentials anywhere in your client-side source code.

Proxy mode is explained below, but is essentially a one-liner add to your regular connect/express app.

As a module in a (larger) Node.js program

Install like any other package:

$> npm install flickrapi --save

After that, you have two choices, based on whether you want to authenticate or not. Both approaches require an API key, but using OAuth2 authentication means you get access to the full API, rather than only the public API.

To suppress the progress bars in stdout you can include a progress attribute when initializing:

var Flickr = require('flickrapi');
var flickr = Flickr.tokenOnly({ // or Flickr.authenticate
    api_key: "1234ABCD1234ABCD1234ABCD1234ABCD",
    progress: false
});

No authentication, public API only

var Flickr = require("flickrapi"),
    flickrOptions = {
      api_key: "API key that you get from Flickr",
      secret: "API key secret that you get from Flickr"
    };

Flickr.tokenOnly(flickrOptions, function(error, flickr) {
  // we can now use "flickr" as our API object,
  // but we can only call public methods and access public data
});

Authenticated, full Flickr API access

var Flickr = require("flickrapi"),
    flickrOptions = {
      api_key: "API key that you get from Flickr",
      secret: "API key secret that you get from Flickr"
    };

Flickr.authenticate(flickrOptions, function(error, flickr) {
  // we can now use "flickr" as our API object
});

As flickrapi internally uses the request module, you can also pass default options for request that are accepted by request.defaults() as documented in the request module

var Flickr = require("flickrapi"),
    flickrOptions = {
      api_key: "API key that you get from Flickr",
      secret: "API key secret that you get from Flickr",
      requestOptions: {
        timeout: 20000,
        /* other default options accepted by request.defaults */
      }
    };

Flickr.tokenOnly(flickrOptions, function(error, flickr) {
  // we can now use "flickr" as our API object,
  // but we can only call public methods and access public data
});

The end.

That's it, that's all the quickstart guiding you need. For more detailed information, keep reading. If you just wanted to get up and running, then the preceding text should have gotten you there!


What to do now that you have the library loaded

Call some API functions

calling API functions is then a matter of calling the functions as they are listed on http://www.flickr.com/services/api, so if you wish to get all your own photos, you would call:

flickr.photos.search({
  user_id: flickr.options.user_id,
  page: 1,
  per_page: 500
}, function(err, result) {
  // result is Flickr's response
});

Call functions that don't require authentication, authenticated anyway

Simply add an authenticated: true pair to your function call. Compare:

flickr.people.getPhotos({
  api_key: ...
  user_id: <your own ID>
  page: 1,
  per_page: 100
}, function(err, result) {
  /*
    This will give public results only, even if we used
    Flickr.authenticate(), because the function does not
    *require* authentication to run. It just runs with
    fewer permissions.
  */
});

To:

flickr.people.getPhotos({
  api_key: ...
  user_id: <your own ID>
  authenticated: true,
  page: 1,
  per_page: 100
}, function(err, result) {
  /*
    This will now give all public and private results,
    because we explicitly ran this as an authenticated call
  */
});

Proxy the Flickr API

If your app is a connect or express app, you get Flickr API proxying for free.

Simply use the .proxy() function to set everything up and then call your own API route in the same way you would call the Flickr API, minus the security credentials, since the servers side Flickr api object already has those baked in.

As an example, the test.js script for node-flickrapi uses the following code to set up the local API route:

var express = require("express");

Flickr.authenticate(FlickrOptions, function(error, flickr) {
  var app = express();
  app.configure(function() {
    ...
    flickr.proxy(app, "/service/rest");
    ...
  });
  ...
});

This turns the /service/rest route into a full Flickr API proxy, which the browser library can talk to, using POST operations.

To verify your proxy route works, simply use cURL in the following fashion:

curl -X POST -H "Content-Type: application/json"
             -d '{"method":"flickr.photos.search", "text":"red+pandas"}'
             http://127.0.0.1:3000/service/rest/

Note that the proxy is "open" in that there is no explicit user management. If you want to make sure only "logged in users" get to use your API proxy route, you can pass an authentication middleware function as third argument to the .proxy function:

function authenticator(req, res, next) {
  // assuming your session management uses req.session:
  if(req.session.authenticated) {
    return next();
  }
  next({status:403, message: "not authorised to call API methods"});
}

flickr.proxy(app, "/service/rest/", authenticator);

Upload photos to Flickr

If you're running the code server-side, and you've authenticated with Flickr already, you can use the Flickr.upload function to upload individual photos, or batches of photos, to your own account (or, the account that is tied to the API key that you're using).

Flickr.authenticate(FlickrOptions, function(error, flickr) {
  var uploadOptions = {
    photos: [{
      title: "test",
      tags: [
        "happy fox",
        "test 1"
      ],
      photo: __dirname + "/test.jpg"
    },{
      title: "test2",
      tags: "happy fox image \"test 2\" separate tags",
      photo: __dirname + "/test.jpg"
    }]
  };

  Flickr.upload(uploadOptions, FlickrOptions, function(err, result) {
    if(err) {
      return console.error(error);
    }
    console.log("photos uploaded", result);
  });
});

For the list of available upload properties, see the Flickr Upload API page.

Download data from Flickr

You can use this module to very easily download all your Flickr content, using the built in downsync function:

var Flickr = require("flickrapi"),
    flickrOptions = { ... };
Flickr.authenticate(flickrOptions, flickrapi.downsync());

That's all you need to run. The package will generate a data directory with your images in ./data/images (in several sizes), and the information architecture (metadata, sets, collections, etc) in ./data/ia.

If you want this in a different directory, you can pass the dir as an argument to the downsync function:

var Flickr = require("flickrapi"),
    flickrOptions = { ... };
Flickr.authenticate(flickrOptions, flickrapi.downsync("userdata/me"));

This will now create a ./data for the flickr API information, but also a ./userdata/me/ directory that contains the images and ia dirs with your personal data.

Downloading shortcut: one-step downsyncing

If you just want to immediately downsync all your data right now, simply use the test.js application with the --downsync runtime argument: add your Flickr API key information to the .env file and then run:

$> node test --downsync

Run through the authentication procedure, and then just wait for it to finish. Once it's done, you should have a local mirror of all your Flickr data.

(Re)syncing with Flickr in your code

(Re)syncing is a mostly a matter or running the downsync function again. This will update anything that was updated or added on Flickr, but will not delete anything from your local mirror that was deleted from Flickr unless specifically told to do so, by passing a second argument (internally known as the "removeDeleted" flag in the code) to the downsync function call:

var Flickr = require("flickrapi"),
    flickrOptions = { ... };
Flickr.authenticate(flickrOptions, flickrapi.downsync("userdata/me", true));

If true, this will delete local files that were removed on Flickr (e.g. photos that you didn't like anymore, etc). If false, or omitted, no pruning of the local mirror will be performed.

Use your Flickr data in another application

If you downloaded all your Flickr data, you can use these in your own node apps by "dry loading" Flickr:

var Flickr = require("flickrapi"),
    flickrData = Flickr.loadLocally();

This will give you an object with the following structure:

{
  photos: [photo objects],
  photo_keys: [photo.id array, sorted on publish date],
  photosets: [set objects],
  photoset_keys: [set.id array, sorted on creation date],
  collections: [collection objects],
  collection_keys: [collection.id array, sorted on title],
}

Not sure what these objects look like? head over to your ./data/ia directory and just open a .json file in your favourite text editor.

The loadLocally function can take two arguments, namely a location where the ia data can be found, and an options object. If you want to pass in an options object you must supply a location, too.

flickrData = Flickr.loadLocally("./userdata", {
  loadPrivate: false
});

Currently the options object only has one meaningful property, loadPrivate, which determines whether or not photos and photosets that are marked "not public" in Flickr show up in the photo_keys and photoset_keys lists.

An example of a first run

Fetching Flickr's most up to date API definitions

On first run, the package will fetch all known methods from Flickr, and cache them for future use. This can take a bit, as there are a fair number of methods, but is inconsequential on subsequent package loading.

Authenticate your API key with Flickr

On first run, the authentication function will notice that there are no access_token and access_token_secret values set, and will negotiate these with Flickr using their oauth API, based on the permissions you request for your API key.

By default, the only permissions are "read" permissions, but you can override this by adding a permissions property to the options object:

  • permissions: "read" will give the app read-only access (default)
  • permissions: "write" will give it read + write access
  • permissions: "delete" will give it read, write and delete access

Note that you cannot make use of the upload functions unless you authenticate with write or delete permissions.

An example run

Running the app will show output such as the following block:

$> node app
{ oauth_callback_confirmed: 'true',
  oauth_token: '...',
  oauth_token_secret: '...' }
prompt: oauth_verifier: _

Once the app reaches this point it will open a browser, allowing you to consent to the app accessing your most private of private parts. On Flickr, at least. If you agree to authorize it, you will get an authorisation code that you need to pass so that the flickrapi can negotiate access tokens with Flickr.

Doing so continues the program:

$> node app
{ oauth_callback_confirmed: 'true',
  oauth_token: '...',
  oauth_token_secret: '...' }
prompt: oauth_verifier: 123-456-789

Add the following variables to your environment:

export FLICKR_USER_ID="12345678%40N12"
export FLICKR_ACCESS_TOKEN="72157634942121673-3e02b190b9720d7d"
export FLICKR_ACCESS_TOKEN_SECRET="99c038c9fc77673e"

These are namespaced environment variables, which works really well with env packages like habitat, so if you're going to use a namespace-aware enviroment parser, simply add these variables to your environment, or put them in an .env file and then parse them in.

If you would prefer to use plain process.env consulting, remove the FLICKR_ namespace prefix, and then pass process.env as options object.

Alternatively, if you don't mind hardcoding values (but be careful never to check that code in, because github gets mined by bots for credentials) you can put them straight into your source code:

var FlickrOptions = {
      api_key: "your API key",
      secret: "your API key secret",
      user_id: "...",
      access_token: "...",
      access_token_secret: "..."
    }

The flickrapi package will now be able to authenticate with Flickr without constantly needing to ask you for permission to access data.

Using your own OAuth callback endpoint

By default the oauth callback is set to "out-of-band". You can see this in the .env file as the FLICK_CALLBACK="oob" parameter, but if this is omitted the code falls back to oob automatically. For automated processes, or if you don't want your uers to have to type anything in a console, you can override this by setting your own oauth callback endpoint URL.

Using a custom callback endpoint, the oauth procedure will contact the indicated endpoint with the authentication information, rather than requiring your users to manually copy/paste the authentication values.

Note your users will still need to authenticate the app from a browser!

To use a custom endpoint, add the URL to the options as the callback property:

var options = ...;
options.callback: "http://.../...";
Flickr.authenticate(options, function(error, flickr) {
  ...
}

You can make your life easier by using an environment variable in the .env file rather than hardcoding your endpoint url:

export FLICKR_CALLBACK="http://..."

The callback URL handler will at its minimum need to implement the following middleware function:

function(req, res) {
  res.write("");
  options.exchange(req.query);
}

However, having the response tell the user that authorisation was received and that they can safely close this window/tab is generally a good idea.

If you wish to call the exchange function manually, the object expected by options.exchange looks like this:

{
  oauth_token: "...",
  oauth_verifier: "..."
}

Advanced topics

If all you wanted to know was how to use the flickrapi library, you can stop reading. However, there's some more magic built into the library that you might be interested in, in which case you should totally keep reading.

Custom authentication: browserless, noAPI, and silent

There are a number of special options that can be set to effect different authentication procedures. Calling the authenticate function with an options object means the following options can also be passed:

options = {
  ...

  // console.logs the auth URL instead of opening a browser for it.
  nobrowser: true,

  // only performs authentication, without building the Flickr API.
  noAPI: true,

  // suppress the default console logging on successful authentication.
  silent: true,

  // suppress writing progress bars to stdout
  progress: false

  ...
}

If you use the noAPI option, the authentication credentials can be extracted from the options object inside the callback function that you pass along. The options.access_token and options.access_token_secret will contain the result of the authentication procedure.

(Re)compiling the client-side library

If, for some reason, you want to (re)compile the client-side library, you can run the

$> node compile

command to (re)generate a flickrapi.js client-side library, saved to the browser directory. This generates a sparse library that will let you call all public methods (but currently not any method that requires read-private, write, or delete permissions), but will not tell you what's wrong when errors occur.

If you need the extended information, for instance in a dev setting, use

$> node compile dev

to generate a flickrapi.dev.js library that has all the information needed for developing work; simply use this during development and use the flickrapi.js library in production.

Note that no min version is generated; For development there is no sense in using one, and the savings on the production version are too small to matter (it's only 10kb smaller). If your server can serve content gzipped, the minification will have no effect on the gzipped size anyway (using gzip, the plain library is ~4.5kb, with the dev version being ~30kb).

The options object

Once you have a Flickr API object in the form if the flickr variable, the options can be found as flickr.options so you don't need to pass those on all the time. This object may contain any of the following values (some are quite required, others are entirely optional, and some are automatically generated as you make Flickr API calls):

api_key

your API key.

secret

your API key secret.

###user_id your user id, based on your first-time authorisation.

###access_token the preauthorised Flickr access token.

###access_token_secret its corresponding secret.

###oauth_timestamp the timestamp for the last flickr API call.

###oauth_nonce the cryptographic nonce that request used.

###force_auth

true or false (defaults to false) to indicate whether to force oauth signing for functions that can be called both key-only and authenticated for additional data access (like the photo search function)

###retry_queries if used, Flickr queries will be retried if they fail.

###afterDownsync optional; you can bind an arg-less callback function here that is called after a downsync() call finishes.

###permissions optional 'read', 'write', or 'delete'. defaults to 'read'.

###nobrowser

optional boolean, console.logs the auth URL instead of opening a browser window for it.

###noAPI optional boolean, performs authentication without building the Flickr API object.

###silent optional boolean, suppresses the default console logging on successful authentication.

###progress optional boolean, suppresses writing progress bars to stdout if set to false

###requestOptions adds ability to pass default options for request module

node-flickrapi's People

Contributors

benlowry avatar callmewa avatar lentz avatar mabahj avatar madkoding avatar msmichellegar avatar nabeards avatar neilrickards avatar neojski avatar pomax 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  avatar

node-flickrapi's Issues

Can't get private photos

I may be my fault. I may misuse your API, but I can't get my private photos using you API, neither with flickr.people.getPhotos, nor with flickr.photos.search call. Since I'm correctly authenticate, and I'm the owner of requested photos, I should get them accordingly to Flick API doc. I can't find what I'm doing wrong. Does it sound familiar to you?

jsonFlickrApi( regex

Sometimes, the body returned from Flickr seems to include a newline before jsonFlickrApi

So I changed to following line

body = body.replace(/^jsonFlickrApi\(/,'').replace(/\}\)$/,'}');

with

body = body.replace(/^\n*jsonFlickrApi\(/,'').replace(/\}\)$/,'}');

in utils.js

flickr.stats.photo.getGraphData doesn't exist

Every time a Flickr.tokenOnly is called it's send a request for a method called flickr.stats.photo.getGraphData which apparently doesn't exist. This only happens on my production server, doesn't happen locally (using same key/secret)

add upload API support

started an upload branch to add this in, but ran into oauth issues where the API key is claimed invalid. Posted questions on YDN and Stackoverflow in the hopes of getting some hints on how to get to a working state.

downsync deletions from flickr

Deleting a photo from flickr should also have it deleted during the downsync process. This can be done by tracking known photo ids based on the ia/photos filenames, and resolving those against the filenames that are known to exist on flickr after the initial id list retrieval.

Hide progress bars (enhancement)

The progress bars (at least on server-side, OS X 10.10 / NodeJS v0.10.32 in iTerm2) interferes with parsing or just reading all other terminal output. Please add a way to hide or disable the progress bars.

screenshot 2014-11-28 14 10 49

0.3.28 fails to authenticate for the first time

Seeing some errors when validating for the first time:

function urlCallbackMethod (req, res, next) {
    var options = {
        api_key: api_key,
        secret: secret,
        callback: callback_uri,
        access_token: req.query.oauth_token,
        access_token_secret: req.query.oauth_verifier
    };

    Flickr.authenticate(options, function (err, flickr) {
        // Some code
        });
};

From FlickrAPI.js from line 46:

        queryString = Utils.formQueryString(queryArguments),
        data = Utils.formBaseString("GET", url, queryString),
        signature = Utils.sign(data, options.secret, options.access_token_secret),
        flickrURL = url + "?" + queryString + "&oauth_signature=" + signature;

Results in flickrURL being

https://api.flickr.com/services/rest?method=flickr.auth.oauth.checkToken&oauth_consumer_key=a722f8da2427dc90xxx&oauth_nonce=eccdbc86ae2159e6d9cxxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1421341924189&oauth_token=72157649897363130-xxx&oauth_signature=Vc2U%2F8ndpOyCb%2FAmCQ8Pg55av%2Fg%3D

Results in

null 'oauth_problem=verifier_invalid'

improve the test fromBrowser.js file

make this file able to perform actual API calls based on the drop down menu. Right now it simply shows which arguments are required and which are optional, but the call button always calls flickr.photos.search

Use server side without authentication?

Hi Mike, is it possible to use the package in a node app without authenticating? I would like to build an app that works both authenticated and not, but the only way I see to get the Flickr API object is through the authenticate method.

Thanks, Chris

flickr.photos.getNotInSet with multiple extras

If I call flickr.photos.getNotInSet with {extras:"date_taken,url_o"} then I get an error. It works fine with either of these extras on their own. The same extras work fine with flickr.photosets.getList

require("flickrapi").authenticate(flickrOptions, function(err, flickr) {
    flickr.photos.getNotInSet({extras:"date_taken,url_o"}, function(err, photos) {
        console.log(err);
    })
});
Error
could not parse body as JSON: oauth_problem=signature_invalid&debug_sbs=GET&https%3A%2F%2Fapi.flickr.com%2Fservices%2Frest%2F&api_key%3DREDACTED%26extras%3Ddate_taken%252Curl_o%26format%3Djson%26method%3Dflickr.photos.getNotInSet%26oauth_consumer_key%3DREDACTED%26oauth_nonce%3DREDACTED%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1414966549120%26oauth_token%3DREDACTED

How to call authenticated api calls that require permissions?

I have a problem with API calls that require authorization. I have negotiated the access token and am storing access_token and access_token_secret in the app. I could not find a way to specify which permissions to request for my app so I altered the RequestAuthorization function in auth.js to specifically request 'delete' permissions and indeed after that the flickr authentication page does list the correct permissions so the access token should allow me to call functions that require authentication with permissions.
When I call any API method that required authentication with permissions (even if it is just 'read' permission, such as in flickr.test.login) I get the following error:

could not parse body as JSON: oauth_problem=parameter_absent&oauth_parameters_absent=oauth_signature_method%26oauth_nonce%26oauth_timestamp

The absent parameters are all set in the options, so I am not sure where things are going wrong. Are API calls with permissions not supported?

Compile Problem

Hi,
I am a totally newbie in js.

when I try to compile the project , I get

compile.js:13
      flickrOptions = env.get("FLICKR"),
                          ^
TypeError: Object false has no method 'get'
    at compile.js:13:27
    at Object.<anonymous> (node-flickrapi-master\compile.js:153:2)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:929:3

any idea why this might happen ?
I am on windows 7.

Error initialising the flickr API

It is taking a long time (around 2 minutes) to cache the available methods in the Flickr API. When the caching finally completes, an error is returned:

[Error: HTTP Error: no response for url [https://api.flickr.com/services/rest/?api_key=52c4faaf0c876aed4184fa2dca98ce12&format=json&method=flickr.reflection.getMethodInfo&method_name=flickr.photosets.addPhoto]]

Is anyone else seeing this problem?

Thanks!

Retry Queries Option does not work

When retry_queries is true and the queryFlickr call fails due to no network or similar, then you get the following crash:

ReferenceError: queryFlickr is not defined
    at Request._callback (node_modules/flickrapi/src/utils.js:282:20)
    at self.callback (/node_modules/flickrapi/node_modules/request/index.js:148:22)
    at Request.emit (events.js:95:17)
    at ClientRequest.self.clientErrorHandler (/node_modules/flickrapi/node_modules/request/index.js:258:10)
    at ClientRequest.emit (events.js:95:17)
    at ClientRequest.onError (/node_modules/proxy-out/node_modules/tunnel/lib/tunnel.js:164:21)
    at ClientRequest.g (events.js:180:16)
    at ClientRequest.emit (events.js:95:17)
    at Socket.socketErrorListener (http.js:1547:9)
    at Socket.emit (events.js:95:17)

Added a quick fix to the utils.js:
return this.queryFlickr(queryArguments, flickrOptions, security, processResult, errors);
...
processResult(false, body);
}.bind(this));

But should add some back off timer as well.

Can't authenticate oauth

I was trying out the module but as soon as I attempt to use it for the first time I get this:

$ node server.js
magic happening at: 8080
{ '<html>\r\n<head><title>402 Payment Required</title></head>\r\n<body bgcolor': '"white">\r\n<center><h1>402 Payment Required</h1></center>\r\n<hr><center>nginx/1.4.4</center>\r\n</body>\r\n</html>\r\n' }
prompt: oauth_verifier:  


Add the following variables to your environment:

export FLICKR_USER_ID="undefined"
export FLICKR_ACCESS_TOKEN="undefined"
export FLICKR_ACCESS_TOKEN_SECRET="undefined"

Fetching the Flickr API method information architecture.
[Error: could not parse body as JSON: <html>
<head><title>402 Payment Required</title></head>
<body bgcolor="white">
<center><h1>402 Payment Required</h1></center>
<hr><center>nginx/1.4.4</center>
</body>
</html>
]

This is in server.js

var Flickr = require("flickrapi"),
    flickrOptions = {
      api_key: "The api key",
      secret: "the secret",
      permissions: "delete"
    };
Flickr.authenticate(flickrOptions, function(error, flickr) {
  // we can now use "flickr" as our API object
});

Also tried it without the permissions but no result

node-progress is preventing flickrapi to be run with forever

TypeError: Cannot read property 'length' of null
    at StringDecoder.detectIncompleteChar (string_decoder.js:129:18)
    at StringDecoder.write (string_decoder.js:99:28)
    at Interface._normalWrite (readline.js:303:30)
    at Interface.write (readline.js:294:49)
    at Interface.ProgressBar.rl.clearLine (/.../node_modules/flickrapi/node_modules/progress/lib/node-progress.js:45:10)
    at ProgressBar.tick (/.../node_modules/flickrapi/node_modules/progress/lib/node-progress.js:111:11)
    at parseMethods (/.../node_modules/flickrapi/src/flickr-api-object.js:31:17)
    at handleResults (/.../node_modules/flickrapi/src/flickr-api-object.js:123:14)
    at new <anonymous> (/.../node_modules/flickrapi/src/flickr-api-object.js:130:14)
    at /.../node_modules/flickrapi/src/FlickrAPI.js:121:16
error: Forever detected script exited with code: 8
error: Forever restarting script for 3 time

Is there a way to prevent the API check on startup/authentication? I don't really need to keep checking the Flickr API's on production version.

Sometimes errors aften upload

Sometimes errors after upload.

  1. If an flickr API error occur (show error code)
    the body response is like this :
  <?xml version="1.0" encoding="utf-8" ?>
  <rsp stat="fail">
     <err code="3" msg="General upload failure" />
  </rsp>

The node-flickrapi return a succes with an empty array.

  1. Sometimes the returnred body is undefined and the node-flickrapi use indexOf of body the body.

Tracelog :

TypeError: Cannot call method 'indexOf' of undefined
    at Request._callback (.\flickrapi\src\utils.js:374:17)
    at self.callback (.\flickrapi\node_modules\request\index.js:148:22)
    at Request.emit (events.js:117:20)
    at ClientRequest.self.clientErrorHandler (.\flickrapi\node_modules\request\index.js:258:10)
    at ClientRequest.emit (events.js:95:17)
    at CleartextStream.socketErrorListener (http.js:1547:9)
    at CleartextStream.emit (events.js:95:17)
    at Socket.onerror (tls.js:1442:17)
    at Socket.emit (events.js:117:20)
    at net.js:440:14

To fix the error update the last request.post in utils.js with this code :

  var xpath = require('xpath'),
          dom = require('xmldom').DOMParser;

  var req = request.post(flickrURL, function(error, response, body) {
    if (error) {
      return callback(error);
    }
    if (!body) {
      return callback("Photo upload failed, serveur response is empty.");
    }
    // format:json does not actually work, so we need to grab the photo ID from the response XML:
    // <?xml version="1.0" encoding="utf-8" ?><rsp stat="fail"><err code="3" msg="General upload failure" /></rsp>
    // <?xml version="1.0" encoding="utf-8" ?><rsp stat="ok"><photoid>.........</photoid></rsp>
    var doc = new dom().parseFromString(body);
    var status = xpath.select1('//rsp/@stat', doc);
    if (status && status.value === 'ok') {
      var id = xpath.select('//rsp/photoid/text()', doc)[0].nodeValue;
      return callback(null, id);
    }
    if (status && status.value === 'fail') {
      var code = xpath.select1('//rsp/err/@code', doc).value;
      var msg = xpath.select1('//rsp/err/@msg', doc).value;
      return callback("Photo upload failed, "+msg);
    }
    if (body && body.indexOf("oauth_problem=signature_invalid") > -1) {
      return callback("Photo upload failed, oauth signature is invalid.");
    }
    // Unknown error
    return callback("Photo upload failed, unknown error.");
  });

How do I access external variables in the callback?

I'm a bit of a noob to node.js, so I would appreciate help on something that has been confounding me. I've been trying to understand closures and callbacks and I'm still banging my head against the wall when it comes to flickrapi.

I'm trying to loop through a photoset and record the index of the photo in a database. I can get all the photo information, but I'm having a very difficult time capturing the index of the photo. I have code like the following:

  photos = flickr.photosets.getPhotos({ photoset_id: '72157642921920505' }, 
    function(err, result) {
      if(err) { 
        console.log(err); 
      } else {

        for (var i = 0; i < result.photoset.photo.length; i++) {        
          flickr.photos.getSizes({ photo_id: result.photoset.photo[i].id }, function(err, result) {
            console.log(i);
          });
        }

      }
  });

Since the callback for "getSizes" is called asynchronously, the value of "i" is always lost. How do I call "getSizes" in such a way as to access the value of "i" in the callback?

Image upload response is success but no image is being uploaded

i tried using flicker api in angular-fullstack and i am able to authenticate. But when i tried to upload photos, i am getting an empty array as result. flickr authentication included delete permission.
output:
photos uploaded []

I am not getting any error and no images are being uploaded as well. Kindly guide me

tokenOnly needs authentication for the first run

I tried to use tokenOnly access to search photos but for the first run (just after installing flickrapi module) it doesn't work. You must perform the first access by authenticating with Flickr and only then you can use tokenOnly access.

"Invalid auth token" from tokenOnly call

Hi, I'm testing out flickrapi in my app, I just want to fetch some images from photos.search API method from the server, however Im getting "Invalid auth token" in my console.

This method seems not to require authentication as per API description, I don't know if Im doing something wrong here.

flickr.photos.search

Return a list of photos matching some criteria. Only photos visible to the calling user will be returned. To return private or semi-private photos, the caller must be authenticated with 'read' permissions, and have permission to view the photos. Unauthenticated calls will only return public photos.

Authentication
This method does not require authentication.

var flickrOptions = {
    api_key: 'My API key',
    secret: 'and my API secret'
};
exports.getFlickrImages = function (params, callback){

    Flickr.tokenOnly(flickrOptions, function(error, flickr) {
        // we can now use "flickr" as our API object,
        // but we can only call public methods and access public data

        flickr.photos.search({
            text:params.searchText,
            content_type: 1,
            per_page: 5,
            page:1
        }, callback(err, results)());
    });

};

upload not work

var Flickr = require("flickrapi"),                                                                                                     
    flickrOptions = {                                                                                                                  
    api_key: "xxx",                                                                                       
    secret: "xxx",                                                                                                        
    auth_token: 'xxx',                                                                                  
    nobrowser: true,                                                                                                                   
};                                                                                                                                     
var uploadOptions = {                                                                                                                  
    photos: [{                                                                                                                         
        title: 'test',                                                                                                                 
        photo: './file.jpg',                                                                                   
        is_public: 0,                                                                                                                  
        is_friend: 0,                                                                                                                  
        is_family: 0                                                                                                                   
    }]                                                                                                                                 
};                                                                                                                                     
Flickr.tokenOnly(flickrOptions, function(error, flickr) {                                                                              
    if (error) {                                                                                                                       
        throw error;                                                                                                                   
    }                                                                                                                                  
    Flickr.upload(uploadOptions, flickrOptions, function(err, result) {                                                                
        if(err) {                                                                                                                      
            throw err;                                                                                                               
        }                                                                                                                                      console.log("photos uploaded", result);                                                                                        
    });                                                                                                                                
});
TypeError: Cannot read property 'path' of undefined
    at FormData._multiPartHeader (/tmp/test/node_modules/flickrapi/node_modules/request/node_modules/form-data/lib/form_data.js:151:34)
    at FormData.append (/tmp/test/node_modules/flickrapi/node_modules/request/node_modules/form-data/lib/form_data.js:39:21)
    at /tmp/test/node_modules/flickrapi/src/utils.js:383:14
    at Array.forEach (native)
    at Object.module.exports.uploadtoFlickr (/tmp/test/node_modules/flickrapi/src/utils.js:382:33)
    at next (/tmp/test/node_modules/flickrapi/src/utils.js:341:14)
    at Object.module.exports.upload (/tmp/test/node_modules/flickrapi/src/utils.js:342:8)
    at /tmp/test/1.js:21:12
    at null._onTimeout (/tmp/test/node_modules/flickrapi/src/flickr-api-object.js:21:9)
    at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

flickr.photosets.getList failing to parse body

flickr.photosets.getList({user_id: flickr.options.user_id}, function(err, result) {
..
});

is failing with the following in err:

  could not parse body as JSON: [object Object]

This works in 0.3.26 and fails in 0.3.27

Keep fetching methods on Heroku

I am using this module on heroku, but I have an issue since every time I call an API, it takes one minute to fetch all the available methods.
This doesn't happen in my local environment, since the methods are just cached.
Checking the code on the Heroku file system, I can see the cached files, but it looks like the module is just ignoring them.
Any idea why this is happening?

Allow Flickr data to be written to another resource

Syncing the data directory on first-run whilst running locally works just fine, but when using a PaaS such as Heroku it breaks the rules of a twelve factor app and therefore has to re-download the data directory each and every time. This can be especially problematic when your environment is read-only. Curiously enough, node-flickrapi seems to break silently whilst downloading the data to a read-only environment.

I propose that you allow the data to be written to another resource, such as Redis or MongoDB. Alternatively you could bypass the syncing of data entirely, although I'm not sure how feasible that is for this module.

Uploading photos

Is it possible to upload photos with this module? The upload API method appears to be different from the other API methods (the url is prepended with 'up.flickr.com' for one thing).

There isn't an 'upload' example, so I wasn't sure. Is there a way to make REST requests after being authenticated?

silence "fetching method signatures" progress bar?

It seems odd that all those "fetching method signatures" lines are spit out even when it's reading the data from local files, which takes very little time, but there doesn't seem to be an option for turning them off. Am I missing something?

oauth_callback parameter only works when set to "oob"

Hello,

First thank you for this node module, great work, just what I needed.
I'm building an app where I don't want my users to enter the authorization code after the authentification.

I tried to change the oauth_callback parameter in the RequestTokenFunction but when I set it to http://localhost:3001/ instead of "oob", I have this error :

{ oauth_problem: 'parameter_absent',
  oauth_parameters_absent: 'oauth_consumer_key%26oauth_signature%26oauth_signatu
re_method%26oauth_nonce%26oauth_timestamp' }

I thinked first it's because i'm on localhost but when I change to another URL I have another error : signature_invalid.

Do you have any idea what's wrong ?

EDIT : I reproduced the oauth process by using this : https://github.com/ciaranj/node-oauth and the parameter oauth_callback works perfectly. I think there is a configuration in your code that doesn't allow using this parametter but I don't find it.

Thank you

0.3.24 fails to authenticate the first time

When running the example:

var Flickr = require("flickrapi"),
    flickrOptions = {
      api_key: "API key that you get from Flickr",
      secret: "API key secret that you get from Flickr"
    };

Flickr.authenticate(flickrOptions, function(error, flickr) {
  // we can now use "flickr" as our API object
});

with an api_key and secret, I get the following error:

{ oauth_problem: 'signature_invalid',
  debug_sbs: 'GET',
  'https%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Frequest_token': undefined,
  'oauth_callback%3Doob%26oauth_consumer_key%3Dff855f7766b90faaaa7178aed3a7axxx%26oauth_nonce%3Da3cc86a5f7aaa6a4d84f5390984b5xxx%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1412323826278%26oauth_version%3D1.0': undefined }

0.3.23 does not exhibit this issue

How to have two simultaneous flickr objects?

Likely I'm not using the library correctly, but the following code results in lots of blank lines printed to console then it appears to hang. Behaviour is the same with authenticate(...)

var Flickr = require("flickrapi");

Flickr.tokenOnly({
api_key: MY_API,
secret: MY_SECRET,
user_id: "46936561@N00",
}, function(err, flickr) {});

Flickr.tokenOnly({
api_key: MY_API,
secret: MY_SECRET,
user_id: "23323767@N06",
}, function(err, flickr) {});

download collection icons

icon files are indicated by a collection's iconlarge and iconsmall properties. Downloading these means flickrmirror won't need to build thumbnail batches

Downsync fails with Node 10.22

From Pomax/flickrmirror#10:

Ubuntu 12.04 32 bit on digital ocean.

node app --downsync fails with the following error:

---------------------------------------------------------------------------] 1/5913
events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:980:11)
at Process.ChildProcess._handle.onexit (child_process.js:771:34)
root@riverside-cafe:/usr/local/src/flickrmirror-master#

This is after it's "done fetching photo information from Flickr and during the 1st image during the "downloading photos and metadata from Flickr."

Though I just now noticed it didn't complete the download apparently:

==============================================================-------------] 5900/5913
done fetching photo information from Flickr.

Using node 0.8.9 the downsync completes w/out errors.

no such file or directory data/flickr

When trying to use the API for my first time I got an error when the API tried to download the flickr methods to the data dir, since I didn't have one. I had to make 'data/flickr' and 'data/flickr/methods'.

Listening on 5000
Fetching the Flickr API method information architecture.

Error: ENOENT, no such file or directory 'data/flickr/flickr.reflection.getMethods.json'
at Object.fs.openSync (fs.js:427:18)
at Object.fs.writeFileSync (fs.js:966:15)
at /Users/lisbakke/Documents/work/roadtrippin/node_modules/flickrapi/src/flickr-api-object.js:146:10
at Request._callback (/Users/lisbakke/Documents/work/roadtrippin/node_modules/flickrapi/src/utils.js:111:9)
at Request.self.callback (/Users/lisbakke/Documents/work/roadtrippin/node_modules/flickrapi/node_modules/request/index.js:148:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request. (/Users/lisbakke/Documents/work/roadtrippin/node_modules/flickrapi/node_modules/request/index.js:892:14)
at Request.EventEmitter.emit (events.js:117:20)
at IncomingMessage. (/Users/lisbakke/Documents/work/roadtrippin/node_modules/flickrapi/node_modules/request/index.js:843:12)
at IncomingMessage.EventEmitter.emit (events.js:117:20)

sync collections and sets before photographs

new batches of photographs on a large photostream make it far more efficient to first download the collections and sets, followed by photographs. This will also allow code that stops downsyncing once it reaches already-synced photographs.

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.