-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.js
306 lines (266 loc) · 9.36 KB
/
proxy.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
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
// -*- flymake-gjshint: jshint; -*-
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:false, undef:true, unused:true, curly:true, node:true, indent:4, maxerr:100 */
var url = require('url'),
sys = require('sys'),
http = require('http'),
fs = require('fs'),
libxmljs = require("libxmljs"),
zlib = require('zlib'),
buffer = require('buffer'),
C$ = require('./C_doller.js');
var ids = [];
var opts = {
port: 8555
};
function attribute(elm, attr, val) {
var a = elm.attr(attr);
var ret = undefined;
if(!val) {
ret = a.value();
} else {
a.value(val);
}
a.remove();
return ret;
}
// list: [<li>]
function diplayPreviousFirstPost(list) {
for(var i = 0, len = list.length; i < len; i++) {
var idx = list[i].childNodes()[1]; // li > div
if(!idx){ continue; }
var pid = attribute(idx, "data-post-id");
if(!opts["internal.first_post.curr"]){
console.log("pid:", pid);
opts["internal.first_post.curr"] = pid;
}
if(opts["internal.first_post.prev"] == pid) {
console.log("add");
var li = list[i].clone();
var disp = li.childNodes()[1];
li.childNodes()[1].attr({"data-root-id": "0", "data-type": "angelSight"});
disp.get('div[@class="post_wrapper"]').remove();
var elm = disp.node('div');
elm.attr({"class": "post_wrapper"});
elm.text("死");
list[i].addPrevSibling(li);
}
}
}
// list: [<li>]
// ids: [data-post-id]
function filterContent(list, ids) {
for(var i = 0, len = list.length; i < len; i++) {
var idx = list[i].childNodes()[1]; // li > div
if(!idx){ continue; }
var attr = idx.attr("data-root-id");
var post_type = idx.attr("data-type");
if(ids.indexOf(attr.value()) !== -1) {
// 既読posts
console.log("removed: " + attr.value());
attr.remove(); // この行を消してはいけない。lxmljsのバグでGC時に死ぬ
post_type.remove();// 同上
idx.remove();
} else if (opts['exclude.id'].indexOf(attr.value()) != -1) {
// 保護posts
console.log("defilterd: " + attr.value());
} else if (opts['filter.post_type'].indexOf(post_type.value()) != -1) {
// 除外type
console.log("removed by type(" + post_type.value() + "): " + attr.value());
attr.remove();
post_type.remove();
idx.remove();
} else {
// その他(表示)
console.log("added: " + attr.value());
ids.push(attr.value());
}
}
return {ids:ids, xml: list};
}
// lxml output -> original tumblr format html
function convertIntoHTML5(txt) {
txt = txt.replace(/<!\[CDATA\[/g, "").replace(/\]\]>/g, "");
txt = txt.replace(/<(\w+)( [^\/>]+(\/[^\/>]*)*)?\/>/g, "<$1$2></$1>");
txt = txt.replace(/<\/?(?:html|body)>/g, "");
txt = txt.slice(txt.indexOf('\n')+1);
txt = txt.slice(txt.indexOf('\n')+1);
return txt;
}
function scrape(body) {
var xml = libxmljs.parseHtml(body);
var lis = xml.find('//li[@class="post_container"]');
diplayPreviousFirstPost(lis);
filterContent(lis, ids);
console.log("ids length:" + ids.length);
return convertIntoHTML5(xml.toString());
}
function tumblrRequest(serverRequest, serverResponse, ajaxmode) {
var requestUrl = url.parse(serverRequest.url);
var buf = [];
function requestCallback(response) {
serverResponse.writeHead(response.statusCode, response.headers);
response.on('data', function(chunk) {
buf.push(chunk);
});
response.on('end', function() {
zlib.gunzip(buffer.Buffer.concat(buf), function(err, body){
if(!!err) {
console.log("tumblr decode error: "+err);
return;
}
var ret = "";
if(ajaxmode) {
ret = scrape(body);
} else {
body = body.toString();
var re = /<!-- START POSTS -->([\s\S]+)<!-- END POSTS -->/;
var inline = body.match(re)[1];
ret = scrape(inline);
ret = body.replace(re, "<!-- START POSTS -->" + ret + "<!-- END POSTS -->");
}
zlib.gzip(ret, function(err, buf) {
serverResponse.write(buf);
serverResponse.end();
saveCache(opts["filter.cache"], function(){});
});
});
});
}
// クライアントから受け取った通りにリクエスト
var request = http.request({
host: serverRequest.headers.host,
port: requestUrl.port || 80,
path: requestUrl.path,
method: serverRequest.method,
headers: serverRequest.headers
}, requestCallback);
request.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
serverRequest.on('data', function(data) {
request.write(data);
});
serverRequest.on('end', function() {
request.end();
});
serverRequest.on('error', function(e){
console.log('problem with request: ' + e.message);
});
}
function normalRequest(serverRequest, serverResponse) {
var requestUrl = url.parse(serverRequest.url);
function requestCallback(response) {
serverResponse.writeHead(response.statusCode, response.headers);
response.on('data', function(chunk) {
serverResponse.write(chunk);
});
response.on('end', function() {
serverResponse.end();
});
}
// クライアントから受け取った通りにリクエスト
var request = http.request({
host: serverRequest.headers.host,
port: requestUrl.port || 80,
path: requestUrl.path,
method: serverRequest.method,
headers: serverRequest.headers
}, requestCallback);
request.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
serverRequest.on('data', function(data) {
request.write(data);
});
serverRequest.on('end', function() {
request.end();
});
serverRequest.on('error', function(e){
console.log('problem with request: ' + e.message);
});
}
function readJSON (path, callback) {
try{
fs.readFile(path, 'utf8', function(err, data) {
if(!!err) {
return callback(null, err);
} else {
try {
return callback(JSON.parse(data));
} catch(e) {
return callback(null, e);
}
}
});
} catch(e) {
callback(null, e);
}
}
function saveCache(path, callback) {
if(!!path) {
fs.writeFile(path, JSON.stringify(ids), callback);
}
}
function loadCache(path, callback) {
readJSON(opts["filter.cache"], function(cache, err) {
if(!!err) {
console.log(err);
if(err["code"] == 'ENOENT') return callback(null);
return process.abort();
} else {
ids = cache || [];
ids = ids.filter(function(id) {
return opts["exclude.id"].indexOf(id) == -1;
});
return callback(cache);
}
});
}
function loadOpts(callback) {
var argv = process.argv, path;
if(argv.indexOf("-h") != -1) {
console.log("Useage :", argv[1], "[options.json]");
process.exit();
}
path = (argv.length < 3) ? "options.json" : argv[2];
readJSON(path, function(conf, err) {
if(!!err) {
console.log(err);
process.abort();
}
for(var i in conf) {
opts[i] = conf[i];
console.log(i, ":", conf[i]);
}
opts["exclude.id"] = opts["exclude.id"] || [];
opts["exclude.id"] = opts["exclude.id"].map(function(e) {
return e.toString();
});
if(opts["filter.post_type"].indexOf("angelSight") === -1) {
opts["filter.post_type"].push("angelSight");
}
loadCache(opts["filter.cache"], function(){callback(opts);});
});
}
C$(loadOpts).chain(function(opts_) {
opts = opts_;
http.createServer(function(serverRequest, serverResponse) {
var requestUrl = url.parse(serverRequest.url);
if(requestUrl.href.match(/^http:\/\/www\.tumblr\.com\/dashboard(\/\d+)*$/)) {
console.log("***:" + requestUrl.href);
if(!!serverRequest.headers["x-requested-with"]) {
console.log("****:Ajax mode");
tumblrRequest(serverRequest, serverResponse, true);
} else {
opts["internal.first_post.prev"] = opts["internal.first_post.curr"] || 0;
opts["internal.first_post.curr"] = 0;
console.log("prev:", opts["internal.first_post.prev"]);
console.log("curr:", opts["internal.first_post.curr"]);
tumblrRequest(serverRequest, serverResponse, false);
}
} else {
normalRequest(serverRequest, serverResponse);
}
}).listen(opts.port);
sys.puts('Server listening on port ' + opts.port);
})();