Skip to content

Commit 84dd20a

Browse files
committed
Add custom user agent headers
1 parent 1407e24 commit 84dd20a

1 file changed

Lines changed: 40 additions & 7 deletions

File tree

lib/index.js

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
var request = require('request');
2+
var exec = require('child_process').exec;
23

34
var API_URL = 'https://api.filepreviews.io/v2';
45
var FilePreviews;
@@ -20,6 +21,17 @@ FilePreviews = function(options) {
2021
}
2122
};
2223

24+
FilePreviews.VERSION = require('../package.json').version;
25+
FilePreviews.CLIENT_UA_SERIALIZED = null;
26+
FilePreviews.CLIENT_UA = {
27+
lang: 'node',
28+
publisher: 'filepreviews',
29+
bindings_version: FilePreviews.VERSION,
30+
lang_version: process.version,
31+
platform: process.platform,
32+
uname: null
33+
};
34+
2335
FilePreviews.prototype.log = function(msg) {
2436
if (this.debug) {
2537
console.log(msg);
@@ -82,13 +94,30 @@ FilePreviews.prototype.request = function(url, options, callback) {
8294
callback(body);
8395
}.bind(this);
8496

97+
var getClientUserAgent = function(cb) {
98+
if (FilePreviews.CLIENT_UA_SERIALIZED) {
99+
return cb(FilePreviews.CLIENT_UA_SERIALIZED);
100+
}
101+
102+
exec('uname -a', function(err, uname) {
103+
FilePreviews.CLIENT_UA.uname = uname || 'UNKNOWN';
104+
FilePreviews.CLIENT_UA_SERIALIZED = JSON.stringify(FilePreviews.CLIENT_UA);
105+
cb(FilePreviews.CLIENT_UA_SERIALIZED);
106+
});
107+
};
108+
85109
var requestOptions = {
86110
url: url,
87111
method: _options.method || 'GET',
88112
json: true,
89113
auth: {
90114
username: this.apiKey,
91115
password: this.apiSecret
116+
},
117+
headers: {
118+
'Accept': 'application/json',
119+
'Content-Type': 'application/json',
120+
'User-Agent': 'FilePreviews/v2 NodeBindings/' + FilePreviews.VERSION
92121
}
93122
};
94123

@@ -98,13 +127,17 @@ FilePreviews.prototype.request = function(url, options, callback) {
98127

99128
this.log('API request to: ' + url);
100129

101-
this._request(requestOptions, function(error, response, body) {
102-
if (error) {
103-
onError(error, response, body);
104-
} else {
105-
onSuccess(error, response, body);
106-
}
107-
});
130+
getClientUserAgent(function(clientUA) {
131+
requestOptions.headers['X-FilePreviews-Client-User-Agent'] = clientUA;
132+
133+
this._request(requestOptions, function(error, response, body) {
134+
if (error) {
135+
onError(error, response, body);
136+
} else {
137+
onSuccess(error, response, body);
138+
}
139+
});
140+
}.bind(this));
108141
};
109142

110143
FilePreviews.prototype.getAPIRequestData = function(url, options) {

0 commit comments

Comments
 (0)