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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | 1× 1× 1× 1× 1× 1× 1× 1× 14× 14× 14× 14× 14× 14× 1× 13× 5× 14× 8× 8× 14× 8× 6× 4× 4× 6× 4× 4× 4× 2× 2× 2× 123× 80× 123× 123× 123× 2× 121× 2× 2× 2× 2× 2× 2× 2× 119× 119× 938× 2× 2× 119× 2× 2× 117× 121× 121× 121× 119× 119× 255× 121× 121× 2× 119× 5× 114× 114× 112× 112× 112× 1× 113× 113× 113× 113× 30× 113× 2× 111× 107× 111× 98× 13× 121× 19× 19× 102× 85× 85× 85× 121× 121× 1× 121× 121× 121× 237× 121× 121× 121× 121× 121× 17× 17× 104× | /*eslint key-spacing:0 no-undefined:0*/ 'use strict'; var request = require('request'); var urlParser = require('url'); var zlib = require('zlib'); var RSVP = require('rsvp'); var prettyjson = require('prettyjson'); // クッキー設定 var jar = request.jar(); request.defaults({ jar: jar }); /** * http(s)リクエスト処理メインモジュール */ module.exports = { /** * プロパティ */ core : null, // cheerio-httpcli本体 encoding : null, // encodingモジュール cheerio : null, // 拡張cheerioオブジェクト /** * メソッド */ /** * promise/callbackに両対応したエラー終了処理(promise実行後) * * @param err Errorオブジェクトもしくはエラーメッセージ文字列 * @param options prepareで作成したオプション情報 * @param extra Errorオブジェクトに追加する情報 * @param result 処理結果オブジェクト * @param reject (promise処理時のみ)reject関数 */ fail: function (err, options, extra, result, reject) { extra = extra || {}; result = result || {}; var error = (err instanceof Error) ? err : new Error(err); Eif (options.param.uri) { error.url = options.param.uri; } if (options.param.form) { error.param = options.param.form; } else if (options.param.qs) { error.param = options.param.qs; } Object.keys(extra).forEach(function (ex) { Eif (typeof extra[ex] !== 'undefined') { error[ex] = extra[ex]; } }); // promise処理時とcallback処理時で処理の返し方を切り替え if (options.callback instanceof Function) { options.callback(error, result.$, result.response, result.body); } else { Object.keys(result).forEach(function (r) { Eif (typeof result[r] !== 'undefined') { error[r] = result[r]; } }); reject(error); } }, /** * promise/callbackに両対応したエラー終了処理(promise実行前) * * @param err Errorオブジェクトもしくはエラーメッセージ文字列 * @param options prepareで作成したオプション情報 * @param extra Errorオブジェクトに追加する情報 * @param result 処理結果オブジェクト * @param reject (promise処理時のみ)reject関数 */ error: function (err, options, extra, result) { extra = extra || {}; result = result || {}; if (options.callback instanceof Function) { return this.fail(err, options, extra, result); } // callbackを指定しなかった場合はpromiseオブジェクトを返す return new RSVP.Promise((function (resolve, reject) { return this.fail(err, options, extra, result, reject); }).bind(this)); }, /** * gzip転送に対応したリクエスト処理 * * @param param requestモジュールでのhttpアクセス時に指定するパラメータ * @param gzip gzip転送をするかどうか * @param callback リクエスト完了時のコールバック関数(err, response, body(buffer)) * @param retry 内部処理用引数(リトライ回数) */ request: function (param, gzip, callback, retry) { if (gzip) { // gzipヘッダ追加 param.headers['Accept-Encoding'] = 'gzip, deflate'; } // デバッグ情報 Iif (this.core.debug) { var label = '[DEBUG]'; var debugParams = {}; debugParams[label] = {}; [ 'uri', 'method', 'headers', 'qs', 'form' ].forEach(function (v) { if (param[v]) { debugParams[label][v] = param[v]; } }); var cookies = {}; param.jar.getCookies(param.uri).forEach(function (c) { cookies[c.key] = c.value; }); if (Object.keys(cookies).length > 0) { debugParams[label].cookies = cookies; } process.stderr.write(prettyjson.render(debugParams) + '\n\n'); } // リクエスト実行 request(param, (function (err, res, body) { if (err) { return callback(err, res, body); } // POSTした先でリダイレクトされてもちゃんと飛んでくれないことがあるので自力で飛ぶ if (/^30\d$/.test(res.statusCode) && res.headers.location) { retry = retry || 0; Iif (retry > 5) { return callback(new Error('redirect limit over'), res, body); } // パラメータの調整 param.url = res.headers.location; param.method = 'GET'; delete(param.form); delete(param.qs); return this.request(param, gzip, callback, retry + 1); } // レスポンスヘッダを確認してコンテンツがgzip圧縮されているかどうかチェック var gzipped = false; for (var h in res.headers) { if (h.toLowerCase() === 'content-encoding' && res.headers[h].toLowerCase() === 'gzip') { gzipped = true; break; } } if (gzipped) { // gzip化されているコンテンツを解凍したものをセットしてコールバック zlib.unzip(body, function (err, buf) { callback(err, res, buf); }); } else { return callback(undefined, res, body); } }).bind(this)); }, /** * http通信処理本体 * * @param options prepareで作成したオプション情報 * @param resolve (promise処理時のみ)resolve関数 * @param reject (promise処理時のみ)reject関数 */ execute: function (options, resolve, reject) { // 処理結果格納先 var result = {}; // リクエスト実行 this.request(options.param, options.gzip, (function (err, res, body) { // クッキー取得 if (res) { res.cookies = {}; options.param.jar.getCookies(options.param.uri).forEach(function (c) { res.cookies[c.key] = c.value; }); } result.response = res; if (err) { return this.fail(err, options, {}, result, reject); } if ((body || []).length === 0) { return this.fail('no content', options, { statusCode: res.statusCode }, result, reject); } // Buffer状態のHTMLコンテンツからエンコーディングを判定してUTF-8に変換 var enc = options.encode || this.encoding.detect(body); if (enc) { enc = enc.toLowerCase(); try { body = this.encoding.convert(enc, body); } catch (e) { return this.fail(e, options, { charset: enc }, result, reject); } } result.body = body.toString('utf8'); // cheerioでHTMLコンテンツをパース & 現在のページ情報を追加 result.$ = this.cheerio.load(result.body, { decodeEntities: false }); result.$._root._documentInfo = { url: res.request.uri.href, encoding: enc }; result.$.documentInfo = function () { return this._root._documentInfo; }; // HTMLが取得できてもレスポンスステータスが200でない場合(ソフト404など)はエラーとして処理する if (res.statusCode !== 200) { return this.fail('server status', options, { statusCode: res.statusCode }, result, reject); } if (options.referer) { // 次のリクエスト時に今アクセスしたURLをRefererとする options.headers.Referer = result.$._root._documentInfo.url; } // promise処理時とcallback処理時で処理の返し方を切り替え if (options.callback instanceof Function) { options.callback(result.error, result.$, result.response, result.body); } else { resolve(result); } }).bind(this)); }, /** * リクエスト時に必要なオプション情報を作成 * * @param method リクエストメソッド * @param url リクエスト先のURL * @param param リクエストパラメータ * @param encode 取得先のHTMLのエンコーディング(default: 自動判定) * @param callback リクエスト完了時のコールバック関数(err, cheerio, response, body) * @return オプション情報オブジェクト */ prepare: function (method, url, param, encode, callback) { // 省略されている引数に合わせて調整 if (encode instanceof Function) { callback = encode; encode = undefined; } else if (param instanceof Function) { callback = param; param = undefined; encode = undefined; } var cli = this.core; // デフォルトはChromeとして振る舞う if (! ('User-Agent' in cli.headers)) { cli.setBrowser('chrome'); } // リクエストヘッダ作成 var parsed = urlParser.parse(url); var reqHeader = { Host: parsed.host }; Object.keys(cli.headers).forEach(function (h) { reqHeader[h] = cli.headers[h]; }); var options = { param: { uri: url, method: method, encoding: null, // Bufferでコンテンツを取得する headers: reqHeader, timeout: cli.timeout, followRedirect: true, jar: jar }, headers: cli.headers, gzip: cli.gzip, referer: cli.referer, encode: encode, callback: callback }; options.param[(method === 'GET') ? 'qs' : 'form'] = param; return options; }, /** * リクエスト処理スタート * * @param method リクエストメソッド * @param url リクエスト先のURL * @param param リクエストパラメータ * @param encode 取得先のHTMLのエンコーディング(default: 自動判定) * @param callback リクエスト完了時のコールバック関数(err, cheerio, response, body) */ run: function (method, url, param, encode, callback) { var options = this.prepare(method, url, param, encode, callback); if (! (options.callback instanceof Function)) { // callbackを指定しなかった場合はpromiseオブジェクトを返す return new RSVP.Promise((function (resolve, reject) { this.execute(options, resolve, reject); }).bind(this)); } this.execute(options); } }; |