_getAuthorizationHeader = function () { var deferred = Q.defer(); if (IMGUR_ACCESS_TOKEN) { deferred.resolve('Bearer ' + IMGUR_ACCESS_TOKEN); } else if (IMGUR_USERNAME && IMGUR_PASSWORD) { var options = { uri: 'https://api.imgur.com/oauth2/authorize', method: 'GET', encoding: 'utf8', qs: { client_id: IMGUR_CLIENT_ID, response_type: 'token' } }; imgur._request(options).then(function (res) { var authorize_token = res.headers['set-cookie'][0].match('(^|;)[\s]*authorize_token=([^;]*)')[2]; options.method = 'POST'; options.json = true; options.form = { username: IMGUR_USERNAME, password: IMGUR_PASSWORD, allow: authorize_token }; options.headers = { Cookie: 'authorize_token=' + authorize_token }; imgur._request(options).then(function (res) { var location = res.headers.location; var token = JSON.parse('{"' + decodeURI(location.slice(location.indexOf('#') + 1)).replace(/"/g, '\\"').replace(/&/ g, '","').replace(/=/g,'":"') + '"}'); IMGUR_ACCESS_TOKEN = token.access_token; deferred.resolve('Bearer ' + IMGUR_ACCESS_TOKEN); }).catch(function (err) { deferred.reject(err); }); }).catch(function (err) { deferred.reject(err); }); } else { deferred.resolve('Client-ID ' + IMGUR_CLIENT_ID); } return deferred.promise; }
n/a
_imgurRequest = function (operation, payload, extraFormParams) { var deferred = Q.defer(); var form = null; var options = { uri: IMGUR_API_URL, method: null, encoding: 'utf8', json: true }; if (!operation || typeof operation !== 'string' || (!payload && operation !== 'credits')) { deferred.reject(new Error('Invalid argument')); return deferred.promise; } switch(operation) { case 'upload': options.method = 'POST'; options.uri += 'image'; break; case 'credits': options.method = 'GET'; options.uri += 'credits'; break; case 'info': options.method = 'GET'; options.uri += 'image/' + payload; break; case 'album': options.method = 'GET'; options.uri += 'album/' + payload; break; case 'createAlbum': options.method = 'POST'; options.uri += 'album'; break; case 'delete': options.method = 'DELETE'; options.uri += 'image/' + payload; break; default: deferred.reject(new Error('Invalid operation')); return deferred.promise; } imgur._getAuthorizationHeader() .then(function (authorizationHeader) { if(IMGUR_MASHAPE_KEY) { options.headers = { Authorization: authorizationHeader, 'X-Mashape-Key': IMGUR_MASHAPE_KEY }; } else { options.headers = { Authorization: authorizationHeader }; } var r = request(options, function (err, res, body) { if (err) { deferred.reject(err); } else if (body && !body.success) { deferred.reject({status: body.status, message: body.data ? body.data.error : 'No body data response'}); } else { deferred.resolve(body); } }); if (operation === 'upload') { form = r.form(); form.append('image', payload); if (typeof extraFormParams === 'object') { for (var param in extraFormParams) { form.append(param, extraFormParams[param]); } } } }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }
n/a
_request = function (options) { var deferred = Q.defer(); request(options, function (err, res, body) { if (err) { deferred.reject(err); } else { deferred.resolve(res); } }); return deferred.promise; }
n/a
clearClientId = function (path) { return imgur.saveClientId('', path); }
...
if (commander.show) {
console.log(imgur.getClientId());
} else if (commander.clear) {
imgur.clearClientId()
.fail(function (err) {
console.error('Unable to clear client id (%s)', err.message);
});
} else if (commander.save) {
imgur.saveClientId(commander.save)
...
createAlbum = function () { var deferred = Q.defer(); imgur._imgurRequest('createAlbum', 'dummy') .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }
...
});
```
#### Creating an album:
```javascript
imgur.createAlbum()
.then(function(json) {
console.log(json);
})
.catch(function (err) {
console.error(err.message);
});
...
deleteImage = function (deletehash) { var deferred = Q.defer(); if(!deletehash) { deferred.reject('Missing deletehash'); } imgur._imgurRequest('delete', deletehash) .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }
...
```
#### Deleting anonymous uploads
Delete an image based on the deletehash(generated during the image upload)
```javascript
imgur.deleteImage(deletehash)
.then(function(status) {
console.log(status);
})
.catch(function(err) {
console.error(err.message);
});
```
...
getAPIUrl = function () { return IMGUR_API_URL; }
...
```javascript
//Setting
imgur.setAPIUrl('https://api.imgur.com/3/');
//If setAPIUrl() is not called, API URL is read from process.env.IMGUR_API_URL
//Getting
imgur.getAPIUrl();
```
#### Dealing with Mashape Key
Requests to the Mashape URL expects a X-Mashape-Key: MashapeKey header.
Set Mashape Key by using setMashapeKey(MashapeKey) method.
Note: Defaults to process.env.IMGUR_MASHAPE_KEY
...
getAlbumInfo = function (id) { var deferred = Q.defer(); if (!id) { deferred.reject(new Error('Invalid album ID')); return deferred.promise; } imgur._imgurRequest('album', id) .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }
...
```
#### Fetching album data:
```javascript
var kittenAlbum = 'mbgq7nd';
imgur.getAlbumInfo(kittenAlbum)
.then(function(json) {
console.log(json);
})
.catch(function (err) {
console.error(err.message);
});
...
getClientId = function () { return IMGUR_CLIENT_ID; }
...
#### Dealing with client IDs:
```javascript
// Setting
imgur.setClientId('aCs53GSs4tga0ikp');
// Getting
imgur.getClientId();
// Saving to disk. Returns a promise.
// NOTE: path is optional. Defaults to ~/.imgur
imgur.saveClientId(path)
.then(function () {
console.log('Saved.');
})
...
getCredits = function () { var deferred = Q.defer(); imgur._imgurRequest('credits') .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }
...
imgur.saveClientId(commander.save)
.fail(function (err) {
console.error('Unable to save client id (%s)', err.message);
});
} else if (commander.credits) {
imgur.getCredits()
.then(function (json) {
console.log(json.data);
}, function (err) {
console.error('Unable to get credit info (%s)', err.message);
});
} else {
...
getInfo = function (id) { var deferred = Q.defer(); if (!id) { deferred.reject('Invalid image ID'); return deferred.promise; } imgur._imgurRequest('info', id) .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }
...
});
```
#### Fetching image data:
```javascript
var kittenPic = 'mbgq7nd';
imgur.getInfo(kittenPic)
.then(function(json) {
console.log(json);
})
.catch(function (err) {
console.error(err.message);
});
...
getMashapeKey = function () { return IMGUR_MASHAPE_KEY; }
...
Note: Defaults to process.env.IMGUR_MASHAPE_KEY
```javascript
//Setting
imgur.setMashapeKey(https://imgur-apiv3.p.mashape.com/);
//Getting
imgur.getMashapeKey()
```
#### Dealing with credentials:
For when you want to upload images to an account.
```javascript
// Setting
...
loadClientId = function (path) { var deferred = Q.defer(); var clientId = null; path = path || DEFAULT_CLIENT_ID_PATH; fs.readFile(path, { encoding: 'utf8' }, function (err, data) { if (err) { return deferred.reject(err); } if (!data) { deferred.reject(new Error('File is empty')); return deferred.promise; } return deferred.resolve(data); }); return deferred.promise; }
...
.catch(function (err) {
console.log(err.message);
});
// Loading from disk
// NOTE: path is optional. Defaults to ~/.imgur
imgur.loadClientId(path)
.then(imgur.setClientId);
```
#### Dealing with API URL:
In order to change the API Url say Mashape URL, use setAPIUrl(MashapeURL)
```javascript
...
saveClientId = function (clientId, path) { var deferred = Q.defer(); path = path || DEFAULT_CLIENT_ID_PATH; fs.writeFile(path, clientId, function (err) { if (err) { return deferred.reject(err); } return deferred.resolve(); }); return deferred.promise; }
...
imgur.setClientId('aCs53GSs4tga0ikp');
// Getting
imgur.getClientId();
// Saving to disk. Returns a promise.
// NOTE: path is optional. Defaults to ~/.imgur
imgur.saveClientId(path)
.then(function () {
console.log('Saved.');
})
.catch(function (err) {
console.log(err.message);
});
...
setAPIUrl = function (URL) { if(URL && typeof URL === 'string') { IMGUR_API_URL = URL; } }
...
```
#### Dealing with API URL:
In order to change the API Url say Mashape URL, use setAPIUrl(MashapeURL)
```javascript
//Setting
imgur.setAPIUrl('https://api.imgur.com/3/');
//If setAPIUrl() is not called, API URL is read from process.env.IMGUR_API_URL
//Getting
imgur.getAPIUrl();
```
#### Dealing with Mashape Key
...
setClientId = function (clientId) { if (clientId && typeof clientId === 'string') { IMGUR_CLIENT_ID = clientId; } }
...
var imgur = require('imgur');
```
#### Dealing with client IDs:
```javascript
// Setting
imgur.setClientId('aCs53GSs4tga0ikp');
// Getting
imgur.getClientId();
// Saving to disk. Returns a promise.
// NOTE: path is optional. Defaults to ~/.imgur
imgur.saveClientId(path)
...
setCredentials = function (username, password, clientId) { if (clientId && typeof clientId === 'string') { IMGUR_CLIENT_ID = clientId; } if (username && typeof username === 'string') { IMGUR_USERNAME = username; } if (password && typeof password === 'string') { IMGUR_PASSWORD = password; } }
...
```
#### Dealing with credentials:
For when you want to upload images to an account.
```javascript
// Setting
imgur.setCredentials('email@domain.com', 'password', 'aCs53GSs4tga0ikp
');
```
#### Uploading files; globbing supported:
```javascript
// A single image
...
setMashapeKey = function (mashapeKey) { if(mashapeKey && typeof mashapeKey === 'string') { IMGUR_MASHAPE_KEY = mashapeKey; } }
...
Requests to the Mashape URL expects a X-Mashape-Key: MashapeKey header.
Set Mashape Key by using setMashapeKey(MashapeKey) method.
Note: Defaults to process.env.IMGUR_MASHAPE_KEY
```javascript
//Setting
imgur.setMashapeKey(https://imgur-apiv3.p.mashape.com/);
//Getting
imgur.getMashapeKey()
```
#### Dealing with credentials:
For when you want to upload images to an account.
...
uploadAlbum = function (images, uploadType, failSafe) { var deferred = Q.defer(); if (!images || !images.length || !(typeof images === 'string' || images instanceof Array)) { if (failSafe) { deferred.resolve({data: {}, images: []}); } else { deferred.reject(new Error('Invalid image input, only arrays supported')); } return deferred.promise; } imgur.createAlbum() .then(function(album) { imgur.uploadImages(images, uploadType, album.data.id) .then(function (images) { deferred.resolve({data: album.data, images: images}); }) .catch(function (err) { return deferred.reject(err); }); }) .catch(function (err) { return deferred.reject(err); }); return deferred.promise; }
...
Create a new album and upload an array of images of the desired upload type to it ('File', 'Url', 'Base64
').
Returns an object with the album data and an array of images { data: {...}, images: [{...}, ...]}.
The third parameter is an optional fail safe, meaning if the array of images is empty or invalid, it will not fail, but returns
an object with empty data and empty images.
```javascript
imgur.uploadAlbum(images, uploadType /*, failSafe */)
.then(function(album) {
console.log(album.data, album.images);
})
.catch(function (err) {
console.error(err.message);
});
...
uploadBase64 = function (base64, albumId) { var deferred = Q.defer(), extraFormParams = {}; if (typeof albumId === 'string' && albumId.length) { extraFormParams.album = albumId; } if (typeof base64 !== 'string' || !base64 || !base64.length) { deferred.reject(new Error('Invalid Base64 input')); return deferred.promise; } imgur._imgurRequest('upload', base64, extraFormParams) .then(function (image) { deferred.resolve(image); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }
...
```
#### Uploading Base-64 encoded images:
```javascript
var imgurFavicon = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAmUlEQVQ4je2TsQ3CMBBFnxMa08WR2IQKJskIUNwMZAcYwWIQMs65JCUpEEIYW4pJy6v
+6e6+/hVnnGsAzsCBMi7AsbbW/rIMsAU2xrnmkeruuzW7zgIw+JGbv6fGQpWzfy3HOsJlDQY/AlCv3jpF9oS5ZBOICKoB1YCIlCdQDR9127qyBHP5Gyw3CBXPr/qi709JHXE1S995AsqoJu8x78GsAAAAAElFTkSuQmCC
';
imgur.uploadBase64(imgurFavicon)
.then(function (json) {
console.log(json.data.link);
})
.catch(function (err) {
console.error(err.message);
});
```
...
uploadFile = function (file, albumId) { var deferred = Q.defer(), extraFormParams = {}; if (typeof albumId === 'string' && albumId.length) { extraFormParams.album = albumId; } glob(file, function (err, files) { if (err) { deferred.reject(err); return deferred.promise; } else if (!files.length) { deferred.reject(new Error('Invalid file or glob')); return deferred.promise; } files.forEach(function (f, index, arr) { var readStream = fs.createReadStream(f); readStream.on('error', deferred.reject); imgur._imgurRequest('upload', readStream, extraFormParams) .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); }); }); return deferred.promise; }
...
```
#### Uploading files; globbing supported:
```javascript
// A single image
imgur.uploadFile('/home/kai/kittens.png')
.then(function (json) {
console.log(json.data.link);
})
.catch(function (err) {
console.error(err.message);
});
...
uploadImages = function (images, uploadType, albumId) { var deferred = Q.defer(); var upload = imgur['upload' + uploadType]; if (!images || !images.length || !(typeof images === 'string' || images instanceof Array)) { deferred.reject(new Error('Invalid image input, only arrays supported')); return deferred.promise; } var results = []; var progress = 0; var done = images.length; for (var i = 0; i < done; i++) { upload(images[i], albumId) .then(function (image) { results.push(image.data); ++progress; if (progress == done) { deferred.resolve(results); } }) .catch(function (err) { deferred.reject(err); return deferred.promise; }); } return deferred.promise; }
...
#### Uploading multiple images:
Upload an array of images of the desired upload type ('File', 'Url', 'Base64').
Returns an array of images (imgur image data).
```javascript
imgur.uploadImages(images, uploadType /*, albumId */)
.then(function(images) {
console.log(images);
})
.catch(function (err) {
console.error(err.message);
});
...
uploadUrl = function (url, albumId) { var deferred = Q.defer(), extraFormParams = {}; if (typeof albumId === 'string' && albumId.length) { extraFormParams.album = albumId; } if (!url || !urlParser.parse(url).protocol) { deferred.reject(new Error('Invalid URL')); return deferred.promise; } imgur._imgurRequest('upload', url, extraFormParams) .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }
...
```
#### Uploading URLs of images hosted elsewhere:
```javascript
// Include http(s) when specifying URLs
imgur.uploadUrl('https://octodex.github.com/images/topguntocat.png')
.then(function (json) {
console.log(json.data.link);
})
.catch(function (err) {
console.error(err.message);
});
```
...