-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsearch.js
270 lines (229 loc) · 8.65 KB
/
search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*
* TESS searcher
*/
'use strict';
const cheerio = require('cheerio');
const fs = require('fs');
const magic = require('stream-mmmagic');
const mkdirp = require('mkdirp');
const rp = require('request-promise');
const Promise = require('bluebird').Promise;
// CONSTANTS
const HOST = 'http://tmsearch.uspto.gov';
const HANDLER_URL = HOST + '/bin/gate.exe';
const LOGIN = HANDLER_URL + '?f=login&p_lang=english&p_d=trmk';
const IMAGE_HANDLER_URL = HOST + '/ImageAgent/ImageAgentProxy?getImage={serialNumber}';
const selectors = {
documentLink: 'a[href*="f=doc"]',
logoutButton: 'input[value="Logout"]',
resultsTable: 'table:contains(Filing Date)',
searchForm: 'form[name=search_text]',
searchPageLink: 'a:contains("Free Form")',
titleContainingError: 'title:contains(Error)'
};
const MAX_PARALLEL_DOCUMENTS = 1; // TESS sometimes throws errors when same session requests multiple pages at once
const MAX_PARALLEL_IMAGES = 10;
const IMAGE_FOLDER_NAME = 'images';
const imageMimetypes = {
'image/jpeg': 'jpg',
'image/gif': 'gif',
'image/png': 'png'
};
mkdirp(require('path').resolve(__dirname, IMAGE_FOLDER_NAME));
const cookieJar = rp.jar();
const request = rp.defaults({
jar: cookieJar,
// proxy: 'http://localhost:8888',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0 (compatible; TESS-GIF)'
}
});
/**
* @param {Cheerio} $form - form element to serialize
* @returns {object} - object mapping field names to values
*/
function serializeForm ($form) {
return $form.serializeArray().reduce(function (o, v) {
o[v.name] = v.value;
return o;
}, {});
}
/**
* @param {string} message - user-facing error message
* @param {object|string} [details] - any extra error details for debug purposes
*/
function TessError (message, details) {
this.name = 'TessError';
this.message = message;
this.details = details;
this.stack = (new Error()).stack;
}
TessError.prototype = Object.create(Error.prototype);
TessError.prototype.constructor = TessError;
/**
* @param {string} message - user-facing progress message
* @param {object|string} [details] - details for debug purposes
*/
function TessProgress (message, details) {
this.message = message;
this.details = details;
}
/**
* @param {string} message - user-facing progress message
* @param {number} fraction - fraction of the current task this progress event marks completed
*/
function TessFractionalProgress (message, fraction) {
this.message = message;
this.fraction = fraction;
}
/**
* @param {string} searchTerm - TESS free-form query
* @param {boolean} withImages - Whether to retrieve images and include their filenames in object output
* @param {function} [progressHandler] - optional handler for progress-related events
*/
function search (searchTerm, withImages, progressHandler) {
/**
* Calls progress handler with specified message template and incremental status.
* @param {string} messageTemplate - templated message
* @param {number} progress - # of X finished out of total
* @param {number} total - total count of X, representing completion
*/
function announceProgress (messageTemplate, progress, total) {
const message = messageTemplate.replace('{total}', total);
const fraction = (progress > 0) ? progress / total : 0;
progressHandler(new TessFractionalProgress(message, fraction));
}
/**
* Gets a TESS session, returning a Disposer for session cleanup
* @returns Bluebird.Promise.prototype.disposer
*/
function getSession () {
progressHandler(new TessProgress('Logging in to TESS...'));
return request(LOGIN)
.catch(function (e) {
throw new TessError('Encountered error logging in to TESS', e);
})
.disposer(function (pageData) {
const $ = cheerio.load(pageData);
const $logoutForm = $(selectors.logoutButton).closest('form');
if (!$logoutForm.length) {
return new TessError('Failed to find TESS logout form!');
}
progressHandler(new TessProgress('Logging out of TESS...'));
return request.post({
uri: HANDLER_URL,
form: serializeForm($logoutForm)
}).catch(function () {
return new TessError('Encountered an error disposing TESS session!');
});
});
}
return Promise.using(getSession(), function (entryPageHtml) {
const $ = cheerio.load(entryPageHtml);
// Get a link to the search page (which includes session token)
const link = $(selectors.searchPageLink);
if (!link.length) {
throw new TessError('Failed to find link to search page!', entryPageHtml);
}
// Load the search page
return rp(HOST + link.attr('href'), { resolveWithFullResponse: true })
.then(function (response) {
// Search
const $ = cheerio.load(response.body);
const formData = serializeForm($(selectors.searchForm));
formData.p_s_ALL = searchTerm;
formData.a_search = 'Submit Query';
formData.p_L = 500; // 500 results/page
// cookieJar.setCookie(request.cookie('queryCookie=' + encodeURIComponent(formData.p_s_ALL)), HOST);
progressHandler(new TessProgress('Querying ' + searchTerm));
return request.post({
uri: HANDLER_URL,
form: formData,
resolveWithFullResponse: true,
headers: {
Referer: response.request.href
}
});
})
.then(function (response) {
const $ = cheerio.load(response.body);
const titleContainingError = $(selectors.titleContainingError);
if (titleContainingError.length) {
throw new TessError('Encountered an error querying TESS', $('body').text());
}
progressHandler(new TessProgress('Got search response', response.body));
return $(selectors.documentLink).toArray().map(function (el) {
return {
imageUrl: IMAGE_HANDLER_URL.replace('{serialNumber}', $(el).html()),
docUrl: HOST + $(el).attr('href')
};
});
}).then(function (documentData) {
/* Get full data for each document */
let requestsCompleted = 0;
function getPromiseForDocument (doc) {
return request.get(doc.docUrl)
.then(function (document) {
let $ = cheerio.load(document);
requestsCompleted++;
announceProgress('Retrieving {total} documents', requestsCompleted, documentData.length);
doc.full = {};
$(selectors.resultsTable).find('tr').each(function (i, el) {
const fieldName = $(el).find('td:first-of-type').text().trim();
const fieldValue = $(el).find('td:last-of-type').text().trim();
doc.full[fieldName] = fieldValue;
});
doc._html = $('body').html();
return doc;
});
}
return Promise.map(documentData, getPromiseForDocument, {
concurrency: MAX_PARALLEL_DOCUMENTS
});
}).then(function (documentData) {
/* Retrieve images */
if (!withImages) {
return documentData;
}
let requestsCompleted = 0;
function getPromiseForImage (doc) {
return new Promise(function (resolve) {
const input = request
.get(doc.imageUrl)
.on('error', function (err) {
throw new TessError('Encountered an error retrieving image', err);
});
// Detect mimetype for file extension
magic(input, function (err, mime, output) {
if (err) {
throw err;
}
const extension = imageMimetypes[mime.type];
const serialNumber = doc.full['Serial Number'];
if (!extension) {
// Not an image - sometimes server responds with text indicating
// no image was available
doc.imageFile = null;
return resolve(doc);
}
if (!serialNumber) {
throw new TessError('Document serial number not found!');
}
doc.imageFile = IMAGE_FOLDER_NAME + '/' + serialNumber + '.' + extension;
output
.pipe(fs.createWriteStream(doc.imageFile))
.on('finish', function () {
requestsCompleted++;
announceProgress('Retrieving {total} images', requestsCompleted, documentData.length);
resolve(doc);
});
});
});
}
return Promise.map(documentData, getPromiseForImage, {
concurrency: MAX_PARALLEL_IMAGES
});
});
});
}
module.exports = search;