Skip to content

Commit

Permalink
Adding a configurable user agent string to outgoing requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
Mat Carey committed Feb 23, 2016
1 parent c1c76e7 commit 7b722ee
Show file tree
Hide file tree
Showing 6 changed files with 138 additions and 30 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,14 @@ If the value is present, it will also set the new value. If the value is `null`,

The default value is `4096`.

### fastimage.userAgent([userAgent])

Gets or sets the User Agent String to send on outgoing requests.

If the value is present, it will also set the new value. If the value is `null`, it will restore the default value.

The default value is `4096`.

### fastimage.FastImageStream

A image analysis stream.
Expand Down
86 changes: 57 additions & 29 deletions lib/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
var originalTimeout = 30000;
var timeout = originalTimeout;

var originalUserAgent = "Fast Image - Node Image Lookup - https://www.npmjs.com/package/fastimage";
var userAgent = originalUserAgent;

// Polyfill for Node 0.10
if(typeof Promise === "undefined") // eslint-disable-line no-use-before-define
var Promise = require("promise");
Expand Down Expand Up @@ -55,6 +58,22 @@
return timeout;
};

/**
Gets or sets the user agent string to send when connecting to a host.
*
* @alias module:fastimage.userAget
* @param {string} [value] - The new value to set. Passing `null` will restore the default value (Fast Image - Node Image Lookup).
* @returns {number} The current value
*/
var manageUserAgent = function(value){
if(typeof value === "string")
userAgent = value;
else if(value === null)
userAgent = originalUserAgent;

return userAgent;
};

var identify = function(buffer, url, realUrl, size, time){
var info = null;
var elapsed = null;
Expand Down Expand Up @@ -150,37 +169,44 @@
var unsupportedError = new errors.FastImageError("Unsupported image file.", {url: url, code: "UNSUPPORTED_TYPE"});

// When a response is received, control the HTTP code. If is not in the 2xx range, return a error.
request({url: url, method: "GET", encoding: null, timeout: timeout})
.on("response", function(response){
realUrl = response.request.uri.href;
size = parseFloat(response.headers["content-length"]);

if(response.statusCode / 100 !== 2){
this.abort();
callback(errors.handleNetworkError({code: "HTTP_ERROR", status: response.statusCode}, url));
}
}).on("data", function(chunk){
// Append the new data and try the identification again.
buffer = Buffer.concat([buffer, chunk]);
info = identify(buffer, url, realUrl, size, time);

// Informations found or threshold reached. End the transfer and call the callback.
if(info || buffer.length >= threshold){
this.abort();

if(info)
callback(null, info);
else
callback(unsupportedError);
}
}).on("error", function(error){
request.get({
url: url,
encoding: null,
timeout: timeout,
headers: {
"user-agent": userAgent
}
})
.on("response", function(response){
realUrl = response.request.uri.href;
size = parseFloat(response.headers["content-length"]);

if(response.statusCode / 100 !== 2){
this.abort();
callback(errors.handleNetworkError({code: "HTTP_ERROR", status: response.statusCode}, url));
}
}).on("data", function(chunk){
// Append the new data and try the identification again.
buffer = Buffer.concat([buffer, chunk]);
info = identify(buffer, url, realUrl, size, time);

// Informations found or threshold reached. End the transfer and call the callback.
if(info || buffer.length >= threshold){
this.abort();
callback(errors.handleNetworkError(error, url));
}).on("end", function(){
// The end of the transfer has been reached with no results. Return an error.
if(!this._aborted && !info)

if(info)
callback(null, info);
else
callback(unsupportedError);
});
}
}).on("error", function(error){
this.abort();
callback(errors.handleNetworkError(error, url));
}).on("end", function(){
// The end of the transfer has been reached with no results. Return an error.
if(!this._aborted && !info)
callback(unsupportedError);
});
};

var performAnalysis = function(subject, callback){
Expand All @@ -204,6 +230,8 @@

timeout: manageTimeout,

userAgent: manageUserAgent,

performAnalysis: performAnalysis,

/**
Expand Down
2 changes: 2 additions & 0 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

threshold: core.threshold,

userAgent: core.userAgent,

/**
* Analyzes a source (a local path, a remote URL or a Buffer) and return the image informations.
*
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"mocha": "~2.1.0",
"mocha-lcov-reporter": "0.0.2",
"sepia": "^2.0.1",
"sinon": "^1.17.3",
"through": "^2.3.6"
},
"config": {
Expand Down
11 changes: 11 additions & 0 deletions test/general.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@
});
});

describe("user agent", function(){
it("should set and get the value", function(){
var defaultValue = "Fast Image - Node Image Lookup - https://www.npmjs.com/package/fastimage";
expect(fastimage.userAgent()).to.equal(defaultValue);
expect(fastimage.userAgent("new value")).to.equal("new value");
expect(fastimage.userAgent()).to.equal("new value");
expect(fastimage.userAgent(null)).to.equal(defaultValue);
expect(fastimage.userAgent()).to.equal(defaultValue);
});
});

describe("using callbacks", function(){
this.timeout(5000);

Expand Down
60 changes: 59 additions & 1 deletion test/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

var expect = require("expect.js");
var path = require("path");
var sinon = require("sinon");
var request = require("request");

var fastimage = require("../main");

Expand Down Expand Up @@ -120,5 +122,61 @@
});
});
});

describe("outgoing request", function(){
var waitForTestToCallRequest, defaultUserAgent;

beforeEach(function(){
defaultUserAgent = "Fast Image - Node Image Lookup - https://www.npmjs.com/package/fastimage";
waitForTestToCallRequest = new Promise(function (res) {
sinon.stub(request, "get", function (outgoingRequest) {
res(outgoingRequest);
var ret = {
on: function () {
return ret;
}
};
return ret;
});
});
});
afterEach(function(){
request.get.restore();
});

it("should contain a default user agent string", function (done) {
waitForTestToCallRequest.then(function (outgoingRequest) {
expect(outgoingRequest.headers["user-agent"]).to.be(defaultUserAgent);
done();
}).catch(done);

fastimage.info("http://example.com/");
});

it("should contain a default user agent string", function (done) {
var newUserAgentString = "Hello World!";

waitForTestToCallRequest.then(function (outgoingRequest) {
expect(outgoingRequest.headers["user-agent"]).to.be(newUserAgentString);
done();
}).catch(done);

fastimage.userAgent(newUserAgentString);
fastimage.info("http://example.com/");
});

it("should have a standard setter/getter for user agent string", function (done) {
waitForTestToCallRequest.then(function (outgoingRequest) {
expect(outgoingRequest.headers["user-agent"]).to.be(defaultUserAgent);
done();
}).catch(done);

fastimage.userAgent("this will never actually be used");
expect(fastimage.userAgent()).to.eql("this will never actually be used");
fastimage.userAgent(null);
expect(fastimage.userAgent()).to.eql(defaultUserAgent);
fastimage.info("http://example.com/");
});
});
});
})();
})();

0 comments on commit 7b722ee

Please sign in to comment.