-
Notifications
You must be signed in to change notification settings - Fork 55
/
20_Tumblr.js
executable file
·565 lines (496 loc) · 14.7 KB
/
20_Tumblr.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
if(typeof(models)=='undefined')
this.models = models = new Repository();
var Tumblr = update({}, AbstractSessionService, {
name : 'Tumblr',
ICON : 'http://www.tumblr.com/images/favicon.gif',
MEDIA_URL : 'http://media.tumblr.com/',
TUMBLR_URL : 'http://www.tumblr.com/',
PAGE_LIMIT : 50,
/**
* 各Tumblrの基本情報(総件数/タイトル/タイムゾーン/名前)を取得する。
*
* @param {String} user ユーザー名。
* @param {XML} post ポストノード。
* @return {Object} ポスト共通情報。ポストID、タイプ、タグなどを含む。
*/
getInfo : function(user, type){
return request('http://'+user+'.tumblr.com/api/read', {
queryString : {
type : type,
start : 0,
num : 0,
}
}).addCallback(function(res){
var xml = convertToXML(res.responseText);
return {
type : ''+xml.posts.@type,
start : 1*xml.posts.@start,
total : 1*xml.posts.@total,
name : ''+xml.tumblelog.@name,
title : ''+xml.tumblelog.@title,
timezone : ''+xml.tumblelog.@timezone,
};
});
},
/**
* Tumblr APIからポストデータを取得する。
*
* @param {String} user ユーザー名。
* @param {optional String} type ポストタイプ。未指定の場合、全タイプとなる。
* @param {String} count 先頭から何件を取得するか。
* @param {Function} handler
* 各ページ個別処理関数。段階的に処理を行う場合に指定する。
* ページ内の全ポストが渡される。
* @return {Deferred} 取得した全ポストが渡される。
*/
read : function(user, type, count, handler){
// FIXME: ストリームにする
var pages = Tumblr._splitRequests(count);
var result = [];
var d = succeed();
d.addCallback(function(){
// 全ページを繰り返す
return deferredForEach(pages, function(page, pageNum){
// ページを取得する
return request('http://'+user+'.tumblr.com/api/read', {
queryString : {
type : type,
start : page[0],
num : page[1],
},
}).addCallback(function(res){
var xml = convertToXML(res.responseText);
// 全ポストを繰り返す
var posts = map(function(post){
var info = {
user : user,
id : ''+ post.@id,
url : ''+ post.@url,
date : ''+ post.@date,
type : ''+ post.@type,
tags : map(function(tag){return ''+tag}, post.tag),
};
return Tumblr[info.type.capitalize()].convertToModel(post, info);
}, xml.posts.post);
result = result.concat(posts);
return handler && handler(posts, (pageNum * Tumblr.PAGE_LIMIT));
}).addCallback(wait, 1); // ウェイト
});
});
d.addErrback(function(err){
if(err.message!=StopProcess)
throw err;
})
d.addCallback(function(){
return result;
});
return d;
},
/**
* API読み込みページリストを作成する。
* TumblrのAPIは120件データがあるとき、100件目から50件を読もうとすると、
* 差し引かれ70件目から50件が返ってくる。
*
* @param {Number} count 読み込み件数。
* @return {Array}
*/
_splitRequests : function(count){
var res = [];
var limit = Tumblr.PAGE_LIMIT;
for(var i=0,len=Math.ceil(count/limit) ; i<len ; i++){
res.push([i*limit, limit]);
}
count%limit && (res[res.length-1][1] = count%limit);
return res;
},
/**
* ポストを削除する。
*
* @param {Number || String} id ポストID。
* @return {Deferred}
*/
remove : function(id){
var self = this;
return this.getToken().addCallback(function(token){
return request(self.TUMBLR_URL+'delete', {
redirectionLimit : 0,
referrer : Tumblr.TUMBLR_URL,
sendContent : {
id : id,
form_key : token,
redirect_to : 'dashboard',
},
});
});
},
/**
* reblog情報を取り除く。
*
* @param {Array} form reblogフォーム。
* @return {Deferred}
*/
trimReblogInfo : function(form){
if(!getPref('trimReblogInfo'))
return;
function trimQuote(entry){
entry = entry.replace(/<p><\/p>/g, '').replace(/<p><a[^<]+<\/a>:<\/p>/g, '');
entry = (function(all, contents){
return contents.replace(/<blockquote>(([\n\r]|.)+)<\/blockquote>/gm, arguments.callee);
})(null, entry);
return entry.trim();
}
switch(form['post[type]']){
case 'link':
form['post[three]'] = trimQuote(form['post[three]']);
break;
case 'regular':
case 'photo':
case 'video':
form['post[two]'] = trimQuote(form['post[two]']);
break;
case 'quote':
form['post[two]'] = form['post[two]'].replace(/ \(via <a.*?<\/a>\)/g, '').trim();
break;
}
return form;
},
/**
* ポスト可能かをチェックする。
*
* @param {Object} ps
* @return {Boolean}
*/
check : function(ps){
return (/(regular|photo|quote|link|conversation|video)/).test(ps.type);
},
/**
* 新規エントリーをポストする。
*
* @param {Object} ps
* @return {Deferred}
*/
post : function(ps){
var endpoint = Tumblr.TUMBLR_URL + 'new/' + ps.type;
return this.postForm(function(){
return Tumblr.getForm(endpoint).addCallback(function(form){
update(form, Tumblr[ps.type.capitalize()].convertToForm(ps));
Tumblr.appendTags(form, ps);
return request(endpoint, {sendContent : form});
});
});
},
/**
* ポストフォームを取得する。
* reblogおよび新規エントリーのどちらでも利用できる。
*
* @param {Object} url フォームURL。
* @return {Deferred}
*/
getForm : function(url){
return request(url).addCallback(function(res){
var doc = convertToHTMLDocument(res.responseText);
var form = formContents(doc);
delete form.preview_post;
form.redirect_to = Tumblr.TUMBLR_URL+'dashboard';
if(form.reblog_post_id){
Tumblr.trimReblogInfo(form);
// Tumblrから他サービスへポストするため画像URLを取得しておく
if(form['post[type]']=='photo')
form.image = $x('id("edit_post")//img[contains(@src, "media.tumblr.com/") or contains(@src, "data.tumblr.com/")]/@src', doc);
}
return form;
});
},
/**
* フォームへタグとプライベートを追加する。
*
* @param {Object} url フォームURL。
* @return {Deferred}
*/
appendTags : function(form, ps){
return update(form, {
'post[tags]' : (ps.tags && ps.tags.length)? joinText(ps.tags, ',') : '',
'post[is_private]' : ps.private==null? form['post[is_private]'] : (ps.private? 1 : 0),
});
},
/**
* reblogする。
* Tombloo.Service.extractors.ReBlogの各抽出メソッドを使いreblog情報を抽出できる。
*
* @param {Object} ps
* @return {Deferred}
*/
favor : function(ps){
// メモをreblogフォームの適切なフィールドの末尾に追加する
var form = ps.favorite.form;
items(Tumblr[ps.type.capitalize()].convertToForm({
description : ps.description,
})).forEach(function([name, value]){
if(!value)
return;
form[name] += '\n\n' + value;
});
Tumblr.appendTags(form, ps);
return this.postForm(function(){
return request(ps.favorite.endpoint, {sendContent : form})
});
},
/**
* フォームをポストする。
* 新規エントリーとreblogのエラー処理をまとめる。
*
* @param {Function} fn
* @return {Deferred}
*/
postForm : function(fn){
var d = succeed();
d.addCallback(fn);
d.addCallback(function(res){
var url = res.channel.URI.asciiSpec.replace(/\?.*/,'');
switch(true){
case RegExp(Tumblr.TUMBLR_URL+'dashboard').test(url):
return;
case url == Tumblr.TUMBLR_URL+'login':
throw new Error(getMessage('error.notLoggedin'));
default:
// このチェックをするためリダイレクトを追う必要がある
// You've used 100% of your daily photo uploads. You can upload more tomorrow.
if(res.responseText.match('more tomorrow'))
throw new Error("You've exceeded your daily post limit.");
error(res);
throw new Error('Error posting entry.');
}
});
return d;
},
openTab : function(ps){
if(ps.type == 'reblog')
return addTab(Tumblr.TUMBLR_URL + 'reblog/' + ps.token.id + '/' + ps.token.token +'?redirect_to='+encodeURIComponent(ps.pageUrl));
var form = Tumblr[ps.type.capitalize()].convertToForm(ps);
return addTab(Tumblr.TUMBLR_URL+'new/' + ps.type).addCallback(function(win){
withDocument(win.document, function(){
populateForm(currentDocument().getElementById('edit_post'), form);
var setDisplay = function(id, style){
currentDocument().getElementById(id).style.display = style;
}
switch(ps.type){
case 'photo':
setDisplay('photo_upload', 'none');
setDisplay('photo_url', 'block');
setDisplay('add_photo_link', 'none');
setDisplay('photo_link', 'block');
break;
case 'link':
setDisplay('add_link_description', 'none');
setDisplay('link_description', 'block');
break;
}
});
});
},
getPasswords : function(){
return getPasswords('http://www.tumblr.com');
},
login : function(user, password){
var self = this;
return request(this.TUMBLR_URL+'login', {
sendContent : {
email : user,
password : password,
}
}).addCallback(function(){
self.updateSession();
self.user = user;
});
},
logout : function(){
return request(this.TUMBLR_URL+'logout');
},
getAuthCookie : function(){
return getCookieString('www.tumblr.com');
},
/**
* ログイン中のユーザーを取得する。
* 結果はキャッシュされ、再ログインまで再取得は行われない。
* アカウント切り替えのためのインターフェースメソッド。
*
* @return {Deferred} ログインに使われるメールアドレスが返される。
*/
getCurrentUser : function(){
switch (this.updateSession()){
case 'none':
return succeed('');
case 'same':
if(this.user)
return succeed(this.user);
case 'changed':
var self = this;
return request(this.TUMBLR_URL+'preferences').addCallback(function(res){
var doc = convertToHTMLDocument(res.responseText);
return self.user = $x('id("user_email")/@value', doc);
});
}
},
/**
* ログイン中のユーザーIDを取得する。
*
* @return {Deferred} ユーザーIDが返される。
*/
getCurrentId : function(){
switch (this.updateSession()){
case 'none':
return succeed('');
case 'same':
if(this.id)
return succeed(this.id);
case 'changed':
var self = this;
return request(this.TUMBLR_URL+'customize').addCallback(function(res){
var doc = convertToHTMLDocument(res.responseText);
return self.id = $x('id("edit_tumblelog_name")/@value', doc);
});
}
},
/**
* ポストや削除に使われるトークン(form_key)を取得する。
* 結果はキャッシュされ、再ログインまで再取得は行われない。
*
* @return {Deferred} トークン(form_key)が返される。
*/
getToken : function(){
switch (this.updateSession()){
case 'none':
throw new Error(getMessage('error.notLoggedin'));
case 'same':
if(this.token)
return succeed(this.token);
case 'changed':
var self = this;
return request(this.TUMBLR_URL+'new/text').addCallback(function(res){
var doc = convertToHTMLDocument(res.responseText);
return self.token = $x('id("form_key")/@value', doc);
});
}
},
});
Tumblr.Regular = {
convertToModel : function(post, info){
return update(info, {
body : ''+ post['regular-body'],
title : ''+ post['regular-title'],
});
},
convertToForm : function(ps){
return {
'post[type]' : ps.type,
'post[one]' : ps.item,
'post[two]' : joinText([ps.body, ps.description], '\n\n'),
};
},
}
Tumblr.Photo = {
convertToModel : function(post, info){
var photoUrl = post['photo-url'];
var photoUrl500 = ''+photoUrl.(@['max-width'] == 500);
var image = Tombloo.Photo.getImageInfo(photoUrl500);
return update(info, {
photoUrl500 : photoUrl500,
photoUrl400 : ''+ photoUrl.(@['max-width'] == 400),
photoUrl250 : ''+ photoUrl.(@['max-width'] == 250),
photoUrl100 : ''+ photoUrl.(@['max-width'] == 100),
photoUrl75 : ''+ photoUrl.(@['max-width'] == 75),
body : ''+ post['photo-caption'],
imageId : image.id,
extension : image.extension,
});
},
convertToForm : function(ps){
var form = {
'post[type]' : ps.type,
't' : ps.item,
'u' : ps.pageUrl,
'post[two]' : joinText([
(ps.item? ps.item.link(ps.pageUrl) : '') + (ps.author? ' (via ' + ps.author.link(ps.authorUrl) + ')' : ''),
ps.description], '\n\n'),
'post[three]' : ps.pageUrl,
};
ps.file? (form['images[o1]'] = ps.file) : (form['photo_src'] = ps.itemUrl);
return form;
},
/**
* 画像をダウンロードする。
*
* @param {nsIFile} file 保存先のローカルファイル。このファイル名が取得先のURLにも使われる。
* @return {Deferred}
*/
download : function(file){
return download(Tumblr.MEDIA_URL + file.leafName, file);
},
}
Tumblr.Video = {
convertToModel : function(post, info){
return update(info, {
body : ''+ post['video-caption'],
source : ''+ post['video-source'],
player : ''+ post['video-player'],
});
},
convertToForm : function(ps){
return {
'post[type]' : ps.type,
'post[one]' : ps.body || ps.itemUrl,
'post[two]' : joinText([
(ps.item? ps.item.link(ps.pageUrl) : '') + (ps.author? ' (via ' + ps.author.link(ps.authorUrl) + ')' : ''),
ps.description], '\n\n'),
};
},
}
Tumblr.Link = {
convertToModel : function(post, info){
return update(info, {
title : ''+ post['link-text'],
source : ''+ post['link-url'],
body : ''+ post['link-description'],
});
},
convertToForm : function(ps){
var thumb = getPref('thumbnailTemplate').replace(RegExp('{url}', 'g'), ps.pageUrl);
return {
'post[type]' : ps.type,
'post[one]' : ps.item,
'post[two]' : ps.itemUrl,
'post[three]' : joinText([thumb, ps.body, ps.description], '\n\n'),
};
},
}
Tumblr.Conversation = {
convertToModel : function(post, info){
return update(info, {
title : ''+ post['conversation-title'],
body : ''+ post['conversation-text'],
});
},
convertToForm : function(ps){
return {
'post[type]' : ps.type,
'post[one]' : ps.item,
'post[two]' : joinText([ps.body, ps.description], '\n\n'),
};
},
}
Tumblr.Quote = {
convertToModel : function(post, info){
return update(info, {
body : ''+ post['quote-text'],
source : ''+ post['quote-source'],
});
},
convertToForm : function(ps){
return {
'post[type]' : ps.type,
'post[one]' : ps.body,
'post[two]' : joinText([(ps.item? ps.item.link(ps.pageUrl) : ''), ps.description], '\n\n'),
};
},
}
models.register(Tumblr);