PageRenderTime 66ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/chrome/scribefire/apis.js

http://scribefire-chrome.googlecode.com/
JavaScript | 3042 lines | 2236 code | 514 blank | 292 comment | 445 complexity | 8a63a0690a08ee6f0146ec3e8c8f9294 MD5 | raw file
Possible License(s): LGPL-2.1
  1. var blogApis = {
  2. };
  3. function getBlogAPI(type, apiUrl) {
  4. if (apiUrl in blogApis) {
  5. return blogApis[apiUrl];
  6. }
  7. var api = null;
  8. switch (type) {
  9. case "wordpress":
  10. api = new wordpressAPI();
  11. break;
  12. case "blogger":
  13. api = new bloggerAPI();
  14. break;
  15. case "tumblr":
  16. api = new tumblrAPI();
  17. break;
  18. case "metaweblog":
  19. api = new genericMetaWeblogAPI();
  20. break;
  21. case "movabletype":
  22. case "movable type":
  23. api = new genericMovableTypeAPI();
  24. break;
  25. case "atom":
  26. api = new genericAtomAPI();
  27. break;
  28. case "posterous":
  29. api = new posterousAPI();
  30. break;
  31. case "livejournal":
  32. api = new livejournalAPI();
  33. break;
  34. default:
  35. SCRIBEFIRE.error(scribefire_string("error_api_invalid", type));
  36. break;
  37. }
  38. if (api) {
  39. api.apiUrl = apiUrl;
  40. blogApis[apiUrl] = api;
  41. return api;
  42. }
  43. }
  44. var blogAPI = function () {
  45. this.ui = {};
  46. this.ui.categories = true;
  47. this.ui["add-category"] = true;
  48. this.ui.tags = true;
  49. this.ui.draft = false;
  50. this.ui.deleteEntry = true;
  51. this.ui.timestamp = true;
  52. this.ui.slug = false;
  53. this.ui.private = false;
  54. this.ui["text-content_wp_more"] = false;
  55. this.ui.upload = false;
  56. this.ui["custom-fields"] = false;
  57. this.ui.excerpt = false;
  58. this.ui.pages = false;
  59. this.ui.getPosts = true;
  60. this.ui.oauth = false;
  61. this.ui.nooauth = true;
  62. this.oauthToken = null
  63. this.accessToken = null;
  64. /*
  65. this.ui["featured-image"] = false;
  66. */
  67. };
  68. blogAPI.prototype = {
  69. init : function (blogObject) {
  70. for (x in blogObject) {
  71. this[x] = blogObject[x];
  72. }
  73. this.postInit();
  74. return this;
  75. },
  76. postInit : function () { },
  77. getBlogs : function (params, success, failure) {
  78. /**
  79. * params = { "apiUrl" : "http://...", "username": "john", "password" : "secret123" }
  80. */
  81. /**
  82. * success(params) = [ {"url" : "http://...", "id" : "123", "name": "My Blog",
  83. * "apiUrl" : "http://...", "type": "wordpress", "username": "john",
  84. * "password": "secret123"}, ... ]
  85. */
  86. },
  87. getPosts : function (params, success, failure) {
  88. /**
  89. * params = { "limit": <int> }
  90. */
  91. /**
  92. * success(params) = [ { "id": <int>, "title": <string>, "content": <string>, "published": <bool>, "tags": <string>, "categories": <string>[] } ]
  93. */
  94. success([]);
  95. },
  96. publish : function (params, success, failure) {
  97. /**
  98. * params = { "title": <string>, "content": <string>,
  99. * "categories": <int>[], "tags": <string>,
  100. * "draft": <bool>, "id": <int> }
  101. */
  102. /**
  103. * success(params) = { "id": "123" }
  104. */
  105. failure({"status": 0, "msg": scribefire_string("error_api_noBlog")});
  106. },
  107. deletePost : function (params, success, failure) {
  108. /**
  109. * params = { "id" : <int> }
  110. */
  111. /**
  112. * success(params) = true
  113. */
  114. },
  115. getCategories : function (params, success, failure) {
  116. /**
  117. * params = { }
  118. */
  119. /**
  120. * success(params) = [ { "id": 1, "name": "Category 1" }, ... ]
  121. */
  122. success([]);
  123. },
  124. addCategory : function (params, success, failure) {
  125. /**
  126. * params = { "id": 1, "name": "Category" }
  127. */
  128. /**
  129. * success(params) = { "id": 1, "name": "Category" }
  130. */
  131. if (failure) {
  132. failure({ "status": 0, "msg": scribefire_string("error_api_noCategorySupport")});
  133. }
  134. else {
  135. success(false);
  136. }
  137. },
  138. upload : function () {
  139. failure({ "status": 0, "msg": scribefire_string("error_api_noUploadSupport")});
  140. },
  141. getPostCategories : function (params, success, failure) {
  142. success($("#list-entries option[value='"+params.id+"']:first").data("categories"), "value");
  143. }
  144. };
  145. var genericMetaWeblogAPI = function () {
  146. var newUi = {};
  147. for (var x in this.ui) newUi[x] = this.ui[x];
  148. this.ui = newUi;
  149. this.ui.categories = false;
  150. this.ui.timestamp = true;
  151. this.ui.tags = false;
  152. this.ui.upload = !!((platform == 'gecko') || (window.File && window.FileReader && window.FileList && window.Blob));
  153. this.ui.draft = true;
  154. this.postInit = function () {
  155. this.ui.timestamp = !(this.apiUrl.indexOf("http://api.xanga.com/") == 0 || this.apiUrl.indexOf("http://my.opera.com/") == 0);
  156. this.ui.draft = !(this.apiUrl.indexOf("http://my.opera.com/") == 0);
  157. };
  158. this.getBlogs = function (params, success, failure) {
  159. // How safe is it to assume that MetaWeblog APIs implement the blogger_ methods?
  160. if (!params.id || !("id" in params)) {
  161. params.id = "0";
  162. }
  163. var args = [params.id, params.username, params.password];
  164. var xml = performancingAPICalls.blogger_getUsersBlogs(args);
  165. XMLRPC_LIB.doCommand(
  166. params.apiUrl,
  167. xml,
  168. function (rv) {
  169. if (success) {
  170. if (rv.length) {
  171. var blogs = [];
  172. for (var i = 0, _len = rv.length; i < _len; i++) {
  173. var blog = {};
  174. blog.url = resolveHref(params.apiUrl, rv[i].url);
  175. blog.id = rv[i].blogid;
  176. blog.name = rv[i].blogName;
  177. blog.apiUrl = params.apiUrl;
  178. blog.type = params.type;
  179. blog.username = params.username;
  180. blog.password = params.password;
  181. blogs.push(blog);
  182. }
  183. success(blogs);
  184. }
  185. else {
  186. if (failure) {
  187. failure( {"status" : 200, "msg" : scribefire_string("error_api_cannotConnect")});
  188. }
  189. }
  190. }
  191. },
  192. function (status, msg) {
  193. if (failure) {
  194. failure({"status": status, "msg": msg});
  195. }
  196. },
  197. this.oauthToken
  198. );
  199. };
  200. this.getPosts = function (params, success, failure) {
  201. var self = this;
  202. if (!("limit" in params)) params.limit = 100;
  203. var args = [this.id, this.username, this.password, params.limit];
  204. var xml = performancingAPICalls.metaWeblog_getRecentPosts(args);
  205. XMLRPC_LIB.doCommand(
  206. this.apiUrl,
  207. xml,
  208. function (rv) {
  209. if (success) {
  210. for (var i = 0; i < rv.length; i++) {
  211. rv[i].id = rv[i].postid;
  212. rv[i].tags = rv[i].mt_keywords;
  213. rv[i].published = (rv[i].post_status != "draft");
  214. rv[i].private = (rv[i].post_status == "private");
  215. rv[i].content = rv[i].description;
  216. if (("mt_text_more" in rv[i]) && rv[i].mt_text_more) {
  217. rv[i].content += '<!--more-->';
  218. rv[i].content += rv[i].mt_text_more;
  219. }
  220. if (!("categories" in rv[i])){
  221. rv[i].categories = [];
  222. }
  223. if ("wp_slug" in rv[i]) {
  224. rv[i].slug = rv[i].wp_slug;
  225. delete rv[i].wp_slug;
  226. }
  227. if ("mt_excerpt" in rv[i]) {
  228. rv[i].excerpt = rv[i].mt_excerpt;
  229. delete rv[i].mt_excerpt;
  230. }
  231. rv[i].permalink = rv[i].permaLink;
  232. if ("date_created_gmt" in rv[i]) {
  233. rv[i].timestamp = rv[i].date_created_gmt;
  234. delete rv[i].date_created_gmt;
  235. }
  236. else if ("dateCreated" in rv[i]) {
  237. rv[i].timestamp = rv[i].dateCreated;
  238. delete rv[i].dateCreated;
  239. }
  240. /*
  241. if ("wp_featured_image" in rv[i]) {
  242. rv[i].featured_image = rv[i].wp_featured_image;
  243. delete rv[i].wp_featured_image;
  244. }
  245. */
  246. delete rv[i].postid;
  247. delete rv[i].mt_keywords;
  248. delete rv[i].post_status;
  249. delete rv[i].mt_text_more;
  250. delete rv[i].description;
  251. delete rv[i].permaLink;
  252. }
  253. // success(rv);
  254. if (self.ui.pages) {
  255. var args = [self.id, self.username, self.password, params.limit];
  256. var xml = performancingAPICalls.wp_getPages(args);
  257. XMLRPC_LIB.doCommand(
  258. self.apiUrl,
  259. xml,
  260. function (pages_rv) {
  261. // @todo Localize
  262. var true_rv = { "Posts" : rv, "Pages" : [] };
  263. for (var j = 0; j < pages_rv.length; j++) {
  264. var i = true_rv.Pages.length;
  265. true_rv.Pages[i] = pages_rv[j];
  266. if ("page_id" in true_rv.Pages[i]) {
  267. true_rv.Pages[i].id = true_rv.Pages[i].page_id;
  268. delete true_rv.Pages[i].page_id;
  269. }
  270. true_rv.Pages[i].published = (true_rv.Pages[i].page_status != "draft");
  271. true_rv.Pages[i].private = (true_rv.Pages[i].page_status == "private");
  272. delete true_rv.Pages[i].page_status;
  273. true_rv.Pages[i].content = true_rv.Pages[i].description;
  274. delete true_rv.Pages[i].description;
  275. if (("text_more" in true_rv.Pages[i]) && true_rv.Pages[i].text_more) {
  276. true_rv.Pages[i].content += '<!--more-->';
  277. true_rv.Pages[i].content += true_rv.Pages[i].text_more;
  278. }
  279. delete true_rv.Pages[i].text_more;
  280. if (!("categories" in true_rv.Pages[i])){
  281. true_rv.Pages[i].categories = [];
  282. }
  283. if ("wp_slug" in true_rv.Pages[i]) {
  284. true_rv.Pages[i].slug = true_rv.Pages[i].wp_slug;
  285. delete true_rv.Pages[i].wp_slug;
  286. }
  287. true_rv.Pages[i].permalink = true_rv.Pages[i].permaLink;
  288. delete true_rv.Pages[i].permaLink;
  289. if ("date_created_gmt" in true_rv.Pages[i]) {
  290. true_rv.Pages[i].timestamp = true_rv.Pages[i].date_created_gmt;
  291. delete true_rv.Pages[i].date_created_gmt;
  292. }
  293. else if ("dateCreated" in true_rv.Pages[i]) {
  294. true_rv.Pages[i].timestamp = true_rv.Pages[i].dateCreated;
  295. delete true_rv.Pages[i].dateCreated;
  296. }
  297. }
  298. success(true_rv);
  299. },
  300. function (status, msg) {
  301. success(rv);
  302. /*
  303. if (failure) {
  304. failure({"status": status, "msg": msg});
  305. }
  306. */
  307. },
  308. self.oauthToken
  309. );
  310. }
  311. else {
  312. success(rv);
  313. }
  314. }
  315. },
  316. function (status, msg) {
  317. if (failure) {
  318. failure({"status": status, "msg": msg});
  319. }
  320. },
  321. this.oauthToken
  322. );
  323. };
  324. this.publish = function (params, success, failure) {
  325. this.doPublish(params, success, failure);
  326. };
  327. this.doPublish = function (params, success, failure) {
  328. var contentStruct = { };
  329. if ("title" in params) {
  330. contentStruct.title = params.title;
  331. }
  332. if ("content" in params) {
  333. contentStruct.description = params.content;
  334. }
  335. if ("categories" in params) {
  336. contentStruct.categories = params.categories;
  337. }
  338. if ("tags" in params) {
  339. contentStruct.mt_keywords = params.tags;
  340. }
  341. if ("timestamp" in params && params.timestamp) {
  342. // It's converted to UTC in the conversion to XML Step.
  343. contentStruct.date_created_gmt = params.timestamp;
  344. // contentStruct.dateCreated = params.timestamp;
  345. }
  346. if ("private" in params && params.private) {
  347. contentStruct.post_status = "private";
  348. }
  349. if ("slug" in params && params.slug) {
  350. contentStruct.wp_slug = params.slug;
  351. }
  352. if ("draft" in params) {
  353. var publish = params.draft ? "bool0" : "bool1";
  354. if (params.draft) {
  355. // At least in Wordpress, a private post marked as a draft will just be published.
  356. if ("private" in params && params.private) {
  357. if (confirm(scribefire_string("confirm_private_status"))) {
  358. delete contentStruct.post_status;
  359. }
  360. else {
  361. failure({"status" : -1, "msg" : scribefire_string("cancel_private_status") });
  362. return;
  363. }
  364. }
  365. }
  366. }
  367. else {
  368. var publish = "bool1";
  369. }
  370. if ("custom_fields" in params) {
  371. contentStruct.custom_fields = params.custom_fields;
  372. }
  373. if (this.ui.excerpt) {
  374. if ("excerpt" in params) {
  375. contentStruct.mt_excerpt = params.excerpt;
  376. }
  377. }
  378. /*
  379. if (this.ui["featured-image"] && "featured_image" in params) {
  380. contentStruct.wp_featured_image = params.wp_featured_image;
  381. }
  382. */
  383. if (("id" in params) && params.id) {
  384. var args = [params.id, this.username, this.password, contentStruct, publish];
  385. var xml = performancingAPICalls.metaWeblog_editPost(args);
  386. }
  387. else {
  388. var args = [this.id, this.username, this.password, contentStruct, publish];
  389. var xml = performancingAPICalls.metaWeblog_newPost(args);
  390. }
  391. XMLRPC_LIB.doCommand(
  392. this.apiUrl,
  393. xml,
  394. function (rv) {
  395. if (success) {
  396. if (("id" in params) && params.id) {
  397. success({ "id" : params.id });
  398. }
  399. else {
  400. success({ "id": rv });
  401. }
  402. }
  403. },
  404. function (status, msg) {
  405. if (failure) {
  406. failure({"status": status, "msg": msg});
  407. }
  408. },
  409. this.oauthToken
  410. );
  411. };
  412. this.deletePost = function (params, success, failure) {
  413. this.doDeletePost(params, success, failure);
  414. };
  415. this.doDeletePost = function (params, success, failure) {
  416. var args = ["0123456789ABCDEF", params.id, this.username, this.password, "bool1"];
  417. var xml = performancingAPICalls.blogger_deletePost(args);
  418. XMLRPC_LIB.doCommand(
  419. this.apiUrl,
  420. xml,
  421. function (rv) {
  422. if (success) {
  423. success(rv);
  424. }
  425. },
  426. function (status, msg) {
  427. if (failure) {
  428. failure({"status": status, "msg": msg});
  429. }
  430. },
  431. this.oauthToken
  432. );
  433. };
  434. this.upload = function (fileName, fileType, fileData, success, failure) {
  435. var bits = btoa(fileData);
  436. var args = [this.id, this.username, this.password, { name : fileName, type : fileType, bits : bits } ];
  437. var xml = performancingAPICalls.metaWeblog_newMediaObject(args);
  438. XMLRPC_LIB.doCommand(
  439. this.apiUrl,
  440. xml,
  441. function (rv) {
  442. if (success) {
  443. success( { "url" : rv.url } );
  444. }
  445. },
  446. function (status, msg) {
  447. if (failure) {
  448. failure({"status": status, "msg": msg});
  449. }
  450. },
  451. this.oauthToken
  452. );
  453. }
  454. };
  455. genericMetaWeblogAPI.prototype = new blogAPI();
  456. var genericMovableTypeAPI = function () {
  457. var newUi = {};
  458. for (var x in this.ui) newUi[x] = this.ui[x];
  459. this.ui = newUi;
  460. this.ui.categories = true;
  461. this.ui["add-category"] = false;
  462. this.ui.draft = false;
  463. this.ui.excerpt = true;
  464. this.publish = function (params, success, failure) {
  465. /*
  466. // MovableType is hacky about publishing and categories.
  467. // MT supposedly uses the "draft" setting to determine whether
  468. // to rebuild static pages, not whether it's actually a draft.
  469. var trueDraft = params.draft;
  470. params.draft = false;
  471. */
  472. var self = this;
  473. this.doPublish(params,
  474. function newSuccess(rv) {
  475. if (("id" in rv) && rv.id) {
  476. var postId = rv.id;
  477. }
  478. else {
  479. var postId = rv;
  480. }
  481. var categories = [];
  482. $("#list-categories option").each(function () {
  483. var value = $(this).attr("value");
  484. var categoryId = $(this).attr("categoryId");
  485. for (var i = 0; i < params.categories.length; i++) {
  486. if (params.categories[i] == value) {
  487. categories.push( categoryId );
  488. break;
  489. }
  490. }
  491. });
  492. var newParams = {
  493. "id": postId,
  494. "categories": categories
  495. };
  496. self.setCategories(newParams,
  497. function categorySuccess(rv) {
  498. self.publishPost(
  499. newParams,
  500. function publishSuccess(rv) {
  501. success({ "id": postId });
  502. },
  503. function publishFailure(status, msg) {
  504. failure({"status": status, "msg": msg});
  505. }
  506. );
  507. },
  508. function categoryFailure(rv) {
  509. failure(rv);
  510. }
  511. );
  512. },
  513. function newFailure(status, msg) {
  514. failure({"status": status, "msg": msg});
  515. }
  516. );
  517. };
  518. this.getCategories = function (params, success, failure) {
  519. var args = [this.id, this.username, this.password];
  520. var xml = performancingAPICalls.mt_getCategoryList(args);
  521. XMLRPC_LIB.doCommand(
  522. this.apiUrl,
  523. xml,
  524. function (rv) {
  525. if (success) {
  526. for (var i = 0; i < rv.length; i++) {
  527. rv[i].id = rv[i].categoryId;
  528. rv[i].name = rv[i].categoryName;
  529. delete rv[i].categoryId;
  530. delete rv[i].categoryName;
  531. }
  532. success(rv);
  533. }
  534. },
  535. function (status, msg) {
  536. if (failure) {
  537. failure({"status": status, "msg": msg});
  538. }
  539. }
  540. );
  541. };
  542. this.setCategories = function (params, success, failure) {
  543. var categories = [];
  544. for (var i = 0; i < params.categories.length; i++) {
  545. categories.push({"categoryId" : params.categories[i]});
  546. }
  547. var args = [params.id, this.username, this.password, categories];
  548. var xml = performancingAPICalls.mt_setPostCategories(args);
  549. XMLRPC_LIB.doCommand(
  550. this.apiUrl,
  551. xml,
  552. function privateCategorySuccess (rv) {
  553. // rv == true
  554. if (success) {
  555. success(rv);
  556. }
  557. },
  558. function privateCategoryFailure (status, msg) {
  559. if (failure) {
  560. failure({"status": status, "msg": msg});
  561. }
  562. }
  563. );
  564. };
  565. this.getPostCategories = function (params, success, failure) {
  566. var args = [params.id, this.username, this.password];
  567. var xml = performancingAPICalls.mt_getPostCategories(args);
  568. XMLRPC_LIB.doCommand(
  569. this.apiUrl,
  570. xml,
  571. function (rv) {
  572. if (success) {
  573. var categories = [];
  574. for (var i = 0; i < rv.length; i++) {
  575. categories.push(rv[i].categoryId);
  576. }
  577. success(categories, "categoryId");
  578. }
  579. },
  580. function (status, msg) {
  581. if (failure) {
  582. failure({"status": status, "msg": msg});
  583. }
  584. }
  585. );
  586. };
  587. this.publishPost = function (params, success, failure) {
  588. var args = [params.id, this.username, this.password];
  589. var xml = performancingAPICalls.mt_publishPost(args);
  590. XMLRPC_LIB.doCommand(
  591. this.apiUrl,
  592. xml,
  593. function (rv) {
  594. // rv == true
  595. if (success) {
  596. success(rv);
  597. }
  598. },
  599. function (status, msg) {
  600. if (failure) {
  601. failure({"status": status, "msg": msg});
  602. }
  603. }
  604. );
  605. };
  606. };
  607. genericMovableTypeAPI.prototype = new genericMetaWeblogAPI();
  608. genericMovableTypeAPI.prototype.parent = genericMetaWeblogAPI.prototype;
  609. var wordpressAPI = function () {
  610. var newUi = {};
  611. for (var x in this.ui) newUi[x] = this.ui[x];
  612. this.ui = newUi;
  613. this.ui.categories = { "posts" : true, "pages" : false, "default": true };
  614. this.ui.slug = true;
  615. this.ui.private = { "posts" : true, "pages" : false, "default": true };
  616. this.ui["text-content_wp_more"] = true;
  617. this.ui["custom-fields"] = true;
  618. this.ui["tags"] = { "posts" : true, "pages" : false, "default": true };
  619. this.ui.excerpt = true;
  620. this.ui.pages = true;
  621. this.oauthToken = null;
  622. this.oauth = {
  623. clientId : 13,
  624. clientSecret : "JejQPQMRkqLsOcwphSUxyGBtuNO7njtLXehgv0atRTNfCO9hjg6uPnnK1kwq57MB",
  625. redirectUri : "http://www.scribefire.com/oauth2/",
  626. endpoints : {
  627. authorizationUrl : function (metaData) {
  628. return "https://public-api.wordpress.com/oauth2/authorize?client_id=13&redirect_uri=" + encodeURIComponent("http://www.scribefire.com/oauth2/") + "&response_type=code&blog=" + encodeURIComponent(metaData.blogUrl || metaData.url);
  629. }
  630. }
  631. };
  632. /*
  633. this.ui["featured-image"] = (this.ui.upload);
  634. */
  635. this.postInit = function () {
  636. /*
  637. if (this.oauthToken) {
  638. this.id = null;
  639. this.username = null;
  640. this.password = null;
  641. this.ui.oauth = true;
  642. this.ui.nooauth = false;
  643. }
  644. */
  645. };
  646. this.getAuthToken = function (code, callback) {
  647. var req = new XMLHttpRequest();
  648. req.open("POST", "https://public-api.wordpress.com/oauth2/token", true);
  649. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  650. req.onreadystatechange = function () {
  651. if (req.readyState == 4) {
  652. var text = req.responseText;
  653. var json = JSON.parse(text);
  654. var token = json.access_token;
  655. callback(token);
  656. }
  657. };
  658. var argString = "client_id=" + encodeURIComponent(this.oauth.clientId) + "&redirect_uri=" + encodeURIComponent(this.oauth.redirectUri) + "&client_secret=" + encodeURIComponent(this.oauth.clientSecret) + "&code=" + encodeURIComponent(code) + "&grant_type=authorization_code";
  659. req.send(argString);
  660. };
  661. this.publish = function (params, success, failure) {
  662. // Some Wordpress plugins apparently rely on linebreaks being \n and not <br />. This is dumb.
  663. params.content = params.content.replace(/<br\s*\/?>/g, "\n");
  664. params.content = params.content.replace(/<\/p>\s*<p>/g, "\n\n");
  665. if (params.type == "posts") {
  666. /*
  667. if ("featured_image" in params) {
  668. params.wp_featured_image = parseInt(params.featured_image.id, 10);
  669. }
  670. */
  671. this.doPublish(params, success, failure);
  672. }
  673. else {
  674. var contentStruct = { };
  675. if ("title" in params) {
  676. contentStruct.title = params.title;
  677. }
  678. if ("content" in params) {
  679. contentStruct.description = params.content;
  680. }
  681. if ("timestamp" in params && params.timestamp) {
  682. contentStruct.dateCreated = params.timestamp;
  683. }
  684. if ("slug" in params && params.slug) {
  685. contentStruct.wp_slug = params.slug;
  686. }
  687. if ("draft" in params) {
  688. var publish = params.draft ? "bool0" : "bool1";
  689. }
  690. else {
  691. var publish = "bool1";
  692. }
  693. if ("custom_fields" in params) {
  694. contentStruct.custom_fields = params.custom_fields;
  695. }
  696. if (this.ui.excerpt) {
  697. if ("excerpt" in params) {
  698. contentStruct.mt_excerpt = params.excerpt;
  699. }
  700. }
  701. if (("id" in params) && params.id) {
  702. var args = [params.id, this.username, this.password, contentStruct, publish];
  703. var xml = performancingAPICalls.metaWeblog_editPost(args);
  704. }
  705. else {
  706. var args = [this.id, this.username, this.password, contentStruct, publish];
  707. var xml = performancingAPICalls.wp_newPage(args);
  708. }
  709. XMLRPC_LIB.doCommand(
  710. this.apiUrl,
  711. xml,
  712. function (rv) {
  713. if (success) {
  714. if (("id" in params) && params.id) {
  715. success({ "id" : params.id });
  716. }
  717. else {
  718. success({ "id": rv });
  719. }
  720. }
  721. },
  722. function (status, msg) {
  723. if (failure) {
  724. failure({"status": status, "msg": msg});
  725. }
  726. },
  727. this.oauthToken
  728. );
  729. }
  730. };
  731. this.getBlogs = function (params, success, failure) {
  732. var args = [params.username, params.password];
  733. var xml = performancingAPICalls.wp_getUsersBlogs(args);
  734. var self = this;
  735. XMLRPC_LIB.doCommand(
  736. params.apiUrl,
  737. xml,
  738. function (rv) {
  739. if (success) {
  740. if (rv.length) {
  741. var blogs = [];
  742. for (var i = 0, _len = rv.length; i < _len; i++) {
  743. if (rv[i].xmlrpc == params.apiUrl) {
  744. var blog = {};
  745. blog.url = rv[i].url;
  746. blog.id = rv[i].blogid;
  747. blog.name = rv[i].blogName;
  748. blog.apiUrl = rv[i].xmlrpc;
  749. blog.type = params.type;
  750. blog.username = params.username;
  751. blog.password = params.password;
  752. blogs.push(blog);
  753. }
  754. }
  755. success(blogs);
  756. }
  757. else {
  758. if (failure) {
  759. failure( {"status" : 200, "msg" : scribefire_string("error_api_cannotConnect")});
  760. }
  761. }
  762. }
  763. },
  764. function (status, msg) {
  765. if (failure) {
  766. failure({"status": status, "msg": msg});
  767. }
  768. },
  769. this.oauthToken
  770. );
  771. };
  772. this.getCategories = function (params, success, failure) {
  773. var args = [this.id, this.username, this.password];
  774. var xml = performancingAPICalls.mt_getCategoryList(args);
  775. XMLRPC_LIB.doCommand(
  776. this.apiUrl,
  777. xml,
  778. function (rv) {
  779. if (success) {
  780. for (var i = 0; i < rv.length; i++) {
  781. rv[i].id = rv[i].categoryId;
  782. rv[i].name = rv[i].categoryName;
  783. delete rv[i].categoryId;
  784. delete rv[i].categoryName;
  785. }
  786. success(rv);
  787. }
  788. },
  789. function (status, msg) {
  790. if (failure) {
  791. failure({"status": status, "msg": msg});
  792. }
  793. },
  794. this.oauthToken
  795. );
  796. };
  797. this.addCategory = function (params, success, failure) {
  798. var args = [this.id, this.username, this.password, { name : params.name } ];
  799. var xml = performancingAPICalls.wp_newCategory(args);
  800. XMLRPC_LIB.doCommand(
  801. this.apiUrl,
  802. xml,
  803. function (rv) {
  804. if (success) {
  805. success({ "id": rv, "name": params.name });
  806. }
  807. },
  808. function (status, msg) {
  809. if (failure) {
  810. failure({"status": status, "msg": msg});
  811. }
  812. } ,
  813. this.oauthToken
  814. );
  815. }
  816. this.deletePost = function (params, success, failure) {
  817. if (params.type == "posts") {
  818. this.doDeletePost(params, success, failure);
  819. }
  820. else {
  821. var args = [params.id, this.username, this.password, params.id];
  822. var xml = performancingAPICalls.wp_deletePage(args);
  823. XMLRPC_LIB.doCommand(
  824. this.apiUrl,
  825. xml,
  826. function (rv) {
  827. if (success) {
  828. success(rv);
  829. }
  830. },
  831. function (status, msg) {
  832. if (failure) {
  833. failure({"status": status, "msg": msg});
  834. }
  835. } ,
  836. this.oauthToken
  837. );
  838. }
  839. }
  840. this.getMediaLibrary = function (params, success, failure) {
  841. var args = [params.id, this.username, this.password, { number : 1 } ];
  842. var xml = performancingAPICalls.wp_getMediaLibrary(args);
  843. XMLRPC_LIB.doCommand(
  844. this.apiUrl,
  845. xml,
  846. function (rv) {
  847. if (success) {
  848. success(rv);
  849. }
  850. },
  851. function (status, msg) {
  852. if (failure) {
  853. failure({"status": status, "msg": msg});
  854. }
  855. } ,
  856. this.oauthToken
  857. );
  858. };
  859. };
  860. wordpressAPI.prototype = new genericMetaWeblogAPI();
  861. var livejournalAPI = function () {
  862. // LiveJournal doesn't actually use this anymore. It uses Atom.
  863. // But some other blogs still use this interface.
  864. this.ui.private = true;
  865. this.ui.categories = false;
  866. this.ui["add-category"] = false;
  867. this.ui.tags = false;
  868. this.ui.timestamp = false;
  869. this.ui["text-content_wp_more"] = true;
  870. this.getBlogs = function (params, success, failure) {
  871. var self = this;
  872. var args = [ { username : params.username, password : params.password } ];
  873. var xml = XMLRPC_LIB.makeXML("LJ.XMLRPC.login", args);
  874. XMLRPC_LIB.doCommand(
  875. this.apiUrl,
  876. xml,
  877. function (rv) {
  878. var blogs = [];
  879. var blog = {};
  880. blog.name = params.username;
  881. blog.url = self.apiUrl.replace("www.", params.username + ".").replace("interface/xmlrpc", "");
  882. blog.id = rv.userid;
  883. blog.apiUrl = self.apiUrl;
  884. blog.type = "livejournal";
  885. blog.username = params.username;
  886. blog.password = params.password;
  887. blogs.push(blog);
  888. success(blogs);
  889. },
  890. function (status, msg) {
  891. if (failure) {
  892. failure({"status": status, "msg": msg});
  893. }
  894. }
  895. );
  896. };
  897. this.getPosts = function (params, success, failure) {
  898. var self = this;
  899. var args = [ { username : this.username, password : this.password, selecttype : "lastn", howmany : 50, ver : 1 } ];
  900. var xml = XMLRPC_LIB.makeXML("LJ.XMLRPC.getevents", args);
  901. XMLRPC_LIB.doCommand(
  902. this.apiUrl,
  903. xml,
  904. function (rv) {
  905. var posts = [];
  906. for (var i = 0, _len = rv.events.length; i < _len; i++) {
  907. var event = rv.events[i];
  908. var post = {};
  909. post.content = event.event;
  910. post.content = post.content
  911. .replace(/<a name=.cutid1.><\/a>/, '<!--more-->')
  912. .replace(/<a name=.cutid1-end.><\/a>/, '<!--endmore-->');
  913. post.title = event.subject;
  914. var val = event.eventtime;
  915. // Check for a timezone offset
  916. var possibleOffset = val.substr(-6);
  917. var hasTimezone = false;
  918. var minutes = null;
  919. if (possibleOffset.charAt(0) == "-" || possibleOffset.charAt(0) == "+") {
  920. var hours = parseInt(possibleOffset.substr(1,2), 10);
  921. var minutes = (hours * 60) + parseInt(possibleOffset.substr(4,2), 10);
  922. if (possibleOffset.charAt(0) == "+") {
  923. minutes *= -1;
  924. }
  925. hasTimezone = true;
  926. }
  927. val = val.replace(/-/gi, "");
  928. var year = parseInt(val.substring(0, 4), 10);
  929. var month = parseInt(val.substring(4, 6), 10) - 1
  930. var day = parseInt(val.substring(6, 8), 10);
  931. var hour = parseInt(val.substring(9, 11), 10);
  932. var minute = parseInt(val.substring(12, 14), 10);
  933. var second = parseInt(val.substring(15, 17), 10);
  934. var dateutc = Date.UTC(year, month, day, hour, minute, second);
  935. dateutc = new Date(dateutc);
  936. if (!hasTimezone) {
  937. minutes = new Date(dateutc).getTimezoneOffset();
  938. }
  939. var offsetDate = dateutc.getTime();
  940. offsetDate += (1000 * 60 * minutes);
  941. dateutc.setTime(offsetDate);
  942. post.timestamp = dateutc;
  943. post.categories = [];
  944. post.url = event.url;
  945. post.id = event.itemid;
  946. post.published = true;
  947. post.private = false;
  948. if ("security" in event && event.security == "private") {
  949. post.private = true;
  950. }
  951. posts.push(post);
  952. }
  953. success(posts);
  954. },
  955. function (status, msg) {
  956. if (failure) {
  957. failure({"status": status, "msg": msg});
  958. }
  959. }
  960. );
  961. };
  962. this.publish = function (params, success, failure) {
  963. var contentStruct = { };
  964. contentStruct.username = this.username;
  965. contentStruct.password = this.password;
  966. contentStruct.ver = 1;
  967. contentStruct.subject = params.title;
  968. if (params.content.indexOf('<!--more-->') != -1) {
  969. params.content = params.content.replace('<!--more-->', '<lj-cut text="Read more...">');
  970. if (params.content.indexOf('<!--endmore-->') == -1) {
  971. params.content += '</lj-cut>';
  972. }
  973. else {
  974. params.content = params.content.replace('<!--endmore-->', '</lj-cut>');
  975. }
  976. }
  977. contentStruct.event = params.content;
  978. if ("private" in params && params.private) {
  979. contentStruct.security = "private";
  980. }
  981. var now = new Date();
  982. contentStruct.year = now.getFullYear();
  983. contentStruct.mon = now.getMonth() + 1;
  984. contentStruct.day = now.getDate();
  985. contentStruct.hour = now.getHours();
  986. contentStruct.min = now.getMinutes();
  987. var args = [ contentStruct ];
  988. if ("id" in params && params.id) {
  989. contentStruct.itemid = params.id;
  990. var xml = XMLRPC_LIB.makeXML("LJ.XMLRPC.editevent", [ contentStruct ] );
  991. }
  992. else {
  993. var xml = XMLRPC_LIB.makeXML("LJ.XMLRPC.postevent", [ contentStruct ]);
  994. }
  995. XMLRPC_LIB.doCommand(
  996. this.apiUrl,
  997. xml,
  998. function (rv) {
  999. if (success) {
  1000. if (("itemid" in rv) && rv.itemid) {
  1001. success({ "id" : rv.itemid });
  1002. }
  1003. else if ("id" in params && params.id) {
  1004. success({ "id" : params.id });
  1005. }
  1006. else {
  1007. success({ "id" : rv });
  1008. }
  1009. }
  1010. },
  1011. function (status, msg) {
  1012. if (failure) {
  1013. failure({"status": status, "msg": msg});
  1014. }
  1015. }
  1016. );
  1017. };
  1018. this.deletePost = function (params, success, failure) {
  1019. var args = [ { username : this.username, password : this.password, ver : 1, itemid : params.id, event : "" } ];
  1020. var xml = XMLRPC_LIB.makeXML("LJ.XMLRPC.editevent", args);
  1021. XMLRPC_LIB.doCommand(
  1022. this.apiUrl,
  1023. xml,
  1024. function (rv) {
  1025. if (success) {
  1026. success(rv);
  1027. }
  1028. },
  1029. function (status, msg) {
  1030. if (failure) {
  1031. failure({"status": status, "msg": msg});
  1032. }
  1033. }
  1034. );
  1035. };
  1036. };
  1037. livejournalAPI.prototype = new blogAPI();
  1038. var genericAtomAPI = function () {
  1039. var newUi = {};
  1040. for (var x in this.ui) newUi[x] = this.ui[x];
  1041. this.ui = newUi;
  1042. this.ui.tags = false;
  1043. this.ui.categories = false;
  1044. this.ui["text-content_wp_more"] = true;
  1045. this.processResponse = function (req, callback, failure) {
  1046. callback(false);
  1047. };
  1048. this.getBlogs = function (params, success, failure) {
  1049. this.init(params);
  1050. var self = this;
  1051. this.buildRequest(
  1052. "GET",
  1053. this.apiUrl,
  1054. function (req) {
  1055. req.onreadystatechange = function () {
  1056. if (req.readyState == 4) {
  1057. self.processResponse(req, function (redo) {
  1058. if (redo) {
  1059. self.getBlogs(params, success, failure);
  1060. }
  1061. else {
  1062. if (req.status < 300) {
  1063. var xml = xmlFromRequest(req);
  1064. if (!xml) {
  1065. if (failure) {
  1066. failure({"status": req.status, "msg": req.responseText});
  1067. }
  1068. }
  1069. else {
  1070. var jxml = $(xml);
  1071. var blogs = [];
  1072. var blog = {};
  1073. blog.url = jxml.find("link[rel='alternate']:first").attr("href");
  1074. blog.name = jxml.find("title:first").text();
  1075. blog.id = jxml.find("id:first").text().split(":blog-")[1];
  1076. blog.apiUrl = params.apiUrl;
  1077. blog.type = params.type;
  1078. blog.username = params.username;
  1079. blog.password = params.password;
  1080. blog.atomAPIs = self.atomAPIs;
  1081. blogs.push(blog);
  1082. success(blogs);
  1083. }
  1084. }
  1085. else {
  1086. if (failure) {
  1087. failure({"status": req.status, "msg": req.responseText});
  1088. }
  1089. }
  1090. }
  1091. }, failure);
  1092. }
  1093. };
  1094. req.send(null);
  1095. }
  1096. );
  1097. };
  1098. this.getPosts = function (params, success, failure) {
  1099. var self = this;
  1100. this.buildRequest(
  1101. "GET",
  1102. this.atomAPIs["service.feed"],
  1103. function (req) {
  1104. req.onreadystatechange = function () {
  1105. if (req.readyState == 4) {
  1106. self.processResponse(req, function (redo) {
  1107. if (redo) {
  1108. self.getPosts(params, success, failure);
  1109. }
  1110. else {
  1111. if (req.status < 300) {
  1112. // Firefox doesn't do well with namespaced elements
  1113. var fakeReq = {};
  1114. fakeReq.responseText = req.responseText.replace(/<(\/)?app:/g, "<$1app_");
  1115. var xml = xmlFromRequest(fakeReq);
  1116. var jxml = $(xml);
  1117. var posts = [];
  1118. jxml.find("entry").each(function () {
  1119. var post = {};
  1120. post.content = $(this).find("content:first").text();
  1121. post.content = post.content
  1122. .replace(/<a name=.cutid1.><\/a>/, '<!--more-->')
  1123. .replace(/<a name=.cutid1-end.><\/a>/, '<!--endmore-->');
  1124. post.title = $(this).find("title:first").text();
  1125. var val = $(this).find("published:first").text();
  1126. // Check for a timezone offset
  1127. var possibleOffset = val.substr(-6);
  1128. var hasTimezone = false;
  1129. var minutes = null;
  1130. if (possibleOffset.charAt(0) == "-" || possibleOffset.charAt(0) == "+") {
  1131. var hours = parseInt(possibleOffset.substr(1,2), 10);
  1132. var minutes = (hours * 60) + parseInt(possibleOffset.substr(4,2), 10);
  1133. if (possibleOffset.charAt(0) == "+") {
  1134. minutes *= -1;
  1135. }
  1136. hasTimezone = true;
  1137. }
  1138. val = val.replace(/-/gi, "");
  1139. var year = parseInt(val.substring(0, 4), 10);
  1140. var month = parseInt(val.substring(4, 6), 10) - 1
  1141. var day = parseInt(val.substring(6, 8), 10);
  1142. var hour = parseInt(val.substring(9, 11), 10);
  1143. var minute = parseInt(val.substring(12, 14), 10);
  1144. var second = parseInt(val.substring(15, 17), 10);
  1145. var dateutc = Date.UTC(year, month, day, hour, minute, second);
  1146. dateutc = new Date(dateutc);
  1147. if (!hasTimezone) {
  1148. minutes = new Date(dateutc).getTimezoneOffset();
  1149. }
  1150. var offsetDate = dateutc.getTime();
  1151. offsetDate += (1000 * 60 * minutes);
  1152. dateutc.setTime(offsetDate);
  1153. post.timestamp = dateutc;
  1154. post.categories = [];
  1155. $(this).find("category").each(function () {
  1156. post.categories.push($(this).attr("term"));
  1157. });
  1158. $(this).find("link").each(function () {
  1159. if ($(this).attr("rel") == "alternate") {
  1160. post.url = $(this).attr("href");
  1161. }
  1162. });
  1163. //var postUrl = $(this).find("id:first").text();
  1164. post.id = $(this).find("id:first").text();//postUrl.match( /(?:\/|post-)(\d{5,})(?!\d*\/)/)[1];
  1165. if ($(this).find("link[rel='service.edit']:first").length > 0) {
  1166. post["service.edit"] = $(this).find("link[rel='service.edit']:first").attr("href");
  1167. }
  1168. else {
  1169. post["service.edit"] = $(this).find("link[rel='edit']:first").attr("href");
  1170. }
  1171. post.published = true;
  1172. $(this).find("app_draft").each(function () {
  1173. if ($(this).text() == "yes") {
  1174. post.published = false;
  1175. }
  1176. });
  1177. posts.push(post);
  1178. });
  1179. success(posts);
  1180. }
  1181. else {
  1182. failure({ "status": req.status, "msg": req.responseText });
  1183. }
  1184. }
  1185. }, failure);
  1186. }
  1187. };
  1188. req.send(null);
  1189. }
  1190. );
  1191. };
  1192. this.publish = function (params, success, failure) {
  1193. var self = this;
  1194. var method = "POST";
  1195. var apiUrl = this.atomAPIs["service.post"];
  1196. var body = "";
  1197. body += '<?xml version="1.0" encoding="UTF-8" ?>';
  1198. body += '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://purl.org/atom/app#">';
  1199. if ("id" in params && params.id) {
  1200. method = "PUT";
  1201. apiUrl = params["service.edit"];
  1202. // Apparently LiveJournal requires this, but Blogger overlooks it.
  1203. body += '<id>'+params.id+'</id>';
  1204. }
  1205. if ("title" in params) {
  1206. body += '<title><![CDATA[' + params.title + ']]></title>';
  1207. }
  1208. if ("categories" in params) {
  1209. for (var i = 0; i < params.categories.length; i++) {
  1210. // Not all Atom APIs will respect this.
  1211. body += '<category scheme="http://www.blogger.com/atom/ns#" term="'+params.categories[i].replace(/&/g,'&amp;')+'"/>';
  1212. }
  1213. }
  1214. if ("timestamp" in params && params.timestamp) {
  1215. var date = params.timestamp;
  1216. body += '<published>' + date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate()) + "T" + pad(date.getUTCHours()) + ":" + pad(date.getUTCMinutes()) + ":00.000Z" + '</published>';
  1217. }
  1218. if ("content" in params) {
  1219. if (params.content.indexOf('<!--more-->') != -1) {
  1220. params.content = params.content.replace('<!--more-->', '<lj-cut text="Read more...">');
  1221. if (params.content.indexOf('<!--endmore-->') == -1) {
  1222. params.content += '</lj-cut>';
  1223. }
  1224. else {
  1225. params.content = params.content.replace('<!--endmore-->', '</lj-cut>');
  1226. }
  1227. }
  1228. body += '<content type="html"><![CDATA[' + params.content + ']]></content>';
  1229. }
  1230. if ("draft" in params && params.draft) {
  1231. body += '<app:control>';
  1232. body += '<app:draft>yes</app:draft>';
  1233. body += '</app:control>';
  1234. }
  1235. body += '</entry>';
  1236. this.buildRequest(
  1237. method,
  1238. apiUrl,
  1239. function (req) {
  1240. /**
  1241. * If any Atom implementations actually respected it, this is how we would
  1242. * set the post slug.
  1243. */
  1244. /*
  1245. if ("slug" in params) {
  1246. req.setRequestHeader("Slug", params.slug);
  1247. }
  1248. */
  1249. req.onreadystatechange = function () {
  1250. if (req.readyState == 4) {
  1251. self.processResponse(req, function (redo) {
  1252. if (redo) {
  1253. self.publish(params, success, failure);
  1254. }
  1255. else {
  1256. if (req.status < 300) {
  1257. var xml = xmlFromRequest(req);
  1258. var jxml = $(xml);
  1259. var postId = jxml.find("id:first").text();//.split(".post-")[1];
  1260. if (!postId && params.id) {
  1261. postId = params.id;
  1262. }
  1263. success({ "id": postId });
  1264. }
  1265. else {
  1266. failure({ "status": req.status, "msg": req.responseText });
  1267. }
  1268. }
  1269. }, failure);
  1270. }
  1271. };
  1272. req.send(body);
  1273. }
  1274. );
  1275. };
  1276. /*
  1277. // You would think that if the list of categories is made available, it would be possible to add
  1278. // a category to an entry, but noooooo.
  1279. this.getCategories = function (params, success, failure) {
  1280. // This API is checked for exposure the first time that categories need to be loaded.
  1281. if ("service.categories" in this.atomAPIs) {
  1282. if (this.atomAPIs["service.categories"]) {
  1283. this.buildRequest(
  1284. "GET",
  1285. this.atomAPIs["service.categories"],
  1286. function (req) {
  1287. req.onreadystatechange = function () {
  1288. if (req.readyState == 4) {
  1289. if (req.status < 300) {
  1290. var xml = xmlFromRequest(req);
  1291. var jxml = $(xml);
  1292. var categories = [];
  1293. jxml.find("subject").each(function () {
  1294. var cat = $(this).text();
  1295. categories.push({ "id": cat, "name": cat });
  1296. });
  1297. success(categories);
  1298. }
  1299. else {
  1300. failure({ "status": req.status, "msg": req.responseText });
  1301. }
  1302. }
  1303. };
  1304. req.send(null);
  1305. }
  1306. );
  1307. }
  1308. else {
  1309. this.ui.categories = false;
  1310. SCRIBEFIRE.updateOptionalUI();
  1311. success([]);
  1312. }
  1313. }
  1314. else {
  1315. var self = this;
  1316. this.buildRequest(
  1317. "GET",
  1318. this.atomAPIs["service.feed"],
  1319. function (req) {
  1320. req.onreadystatechange = function () {
  1321. if (req.readyState == 4) {
  1322. if (req.status < 300) {
  1323. var xml = xmlFromRequest(req);
  1324. var jxml = $(xml);
  1325. var interfaceUrl = jxml.find("entry:first link[rel='self']:first").attr("href");
  1326. self.buildRequest(
  1327. "GET",
  1328. interfaceUrl,
  1329. function (creq) {
  1330. creq.onreadystatechange = function () {
  1331. if (creq.readyState == 4) {
  1332. if (creq.status < 300) {
  1333. var cxml = xmlFromRequest(creq);
  1334. var cjxml = $(cxml);
  1335. var categoryLink = cjxml.find("link[rel='service.categories']:first");
  1336. if (categoryLink) {
  1337. self.atomAPIs["service.categories"] = categoryLink.attr("href");
  1338. }
  1339. else {
  1340. self.atomAPIs["service.categories"] = false;
  1341. }
  1342. }
  1343. else {
  1344. self.atomAPIs["service.categories"] = false;
  1345. }
  1346. SCRIBEFIRE.setBlogProperty(self.url, self.username, "atomAPIs", self.atomAPIs);
  1347. self.getCategories(params, success, failure);
  1348. }
  1349. };
  1350. creq.send(null);
  1351. }
  1352. );
  1353. }
  1354. else {
  1355. self.atomAPIs["service.categories"] = false;
  1356. SCRIBEFIRE.setBlogProperty(self.url, self.username, "atomAPIs", self.atomAPIs);
  1357. self.getCategories(params, success, failure);
  1358. }
  1359. }
  1360. };
  1361. req.send(null);
  1362. }
  1363. );
  1364. }
  1365. };
  1366. this.addCategory = function (params, success, failure) {
  1367. success({ "id": params.name, "name": params.name });
  1368. };
  1369. */
  1370. this.deletePost = function (params, success, failure) {
  1371. var self = this;
  1372. this.buildRequest(
  1373. "DELETE",
  1374. params["service.edit"],
  1375. function (req) {
  1376. req.onreadystatechange = function () {
  1377. if (req.readyState == 4){
  1378. self.processResponse(req, function (redo) {
  1379. if (redo) {
  1380. self.deletePost(params, success, failure);
  1381. }
  1382. else {
  1383. if (req.status < 300) {
  1384. success(true);
  1385. }
  1386. else {
  1387. failure({ "status": req.status, "msg": req.responseText });
  1388. }
  1389. }
  1390. }, failure);
  1391. }
  1392. };
  1393. req.send(null);
  1394. }
  1395. );
  1396. };
  1397. this.buildRequest = function (method, url, callback) {
  1398. var req = new XMLHttpRequest();
  1399. var urlParts = url.split("://");
  1400. url = urlParts[0] + "://" + encodeURIComponent(this.username) + ":" + encodeURIComponent(this.password) + "@" + urlParts[1];
  1401. req.open(method, url, true);
  1402. req.setRequestHeader("Content-Type", "application/atom+xml");
  1403. callback(req);
  1404. };
  1405. };
  1406. genericAtomAPI.prototype = new blogAPI();
  1407. var bloggerAPI = function () {
  1408. var newUi = {};
  1409. for (var x in this.ui) newUi[x] = this.ui[x];
  1410. this.ui = newUi;
  1411. this.ui.categories = true;
  1412. this.ui.upload = (!!(((platform == 'gecko') || (window.File && window.FileReader && window.FileList && window.Blob)))) && (platform != 'presto');
  1413. this.ui.draft = true;
  1414. // this.oauthToken is the complete JSON response, containing access_token, expires_on, refresh_token.
  1415. this.oauthToken = null;
  1416. // this.accessToken gets set to this.oauthToken.access_token
  1417. this.accessToken = null;
  1418. this.oauth = {
  1419. clientId : "116375103348.apps.googleusercontent.com",
  1420. clientSecret : "ZV6urYYje-6AaTcjoya3RW7Y",
  1421. redirectUri : "urn:ietf:wg:oauth:2.0:oob",
  1422. endpoints : {
  1423. authorizationUrl : function (metaData) {
  1424. return "https://accounts.google.com/o/oauth2/auth?client_id=" + encodeURIComponent("116375103348.apps.googleusercontent.com") + "&redirect_uri=" + encodeURIComponent("urn:ietf:wg:oauth:2.0:oob") + "&scope=" + encodeURIComponent("https://www.blogger.com/feeds/ http://picasaweb.google.com/data/") + "&response_type=code";
  1425. }
  1426. }
  1427. };
  1428. this.postInit = function () {
  1429. /*
  1430. if (this.oauthToken) {
  1431. this.id = null;
  1432. this.username = null;
  1433. this.password = null;
  1434. this.ui.oauth = true;
  1435. this.ui.nooauth = false;
  1436. this.accessToken = this.oauthToken.access_token;
  1437. }
  1438. */
  1439. };
  1440. this.getAuthToken = function (code, callback) {
  1441. var req = new XMLHttpRequest();
  1442. req.open("POST", "https://accounts.google.com/o/oauth2/token", true);
  1443. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1444. req.onreadystatechange = function () {
  1445. if (req.readyState == 4) {
  1446. var json = JSON.parse(req.responseText);
  1447. callback(json);
  1448. }
  1449. };
  1450. var argString = "client_id=" + encodeURIComponent(this.oauth.clientId) + "&redirect_uri=" + encodeURIComponent(this.oauth.redirectUri) + "&client_secret=" + encodeURIComponent(this.oauth.clientSecret) + "&code=" + encodeURIComponent(code) + "&grant_type=authorization_code";
  1451. req.send(argString);
  1452. };
  1453. this.refreshAuthToken = function (success, failure) {
  1454. var self = this;
  1455. var req = new XMLHttpRequest();
  1456. req.open("POST", "https://accounts.google.com/o/oauth2/token", true);
  1457. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1458. req.onreadystatechange = function () {
  1459. if (req.readyState == 4) {
  1460. if (req.status < 300) {
  1461. var json = JSON.parse(req.responseText);
  1462. var blog = SCRIBEFIRE.getBlog();
  1463. blog.oauthToken = json;
  1464. self.oauthToken = json;
  1465. self.accessToken = self.oauthToken.access_token;
  1466. SCRIBEFIRE.setBlog(blog);
  1467. success(true);
  1468. }
  1469. else {
  1470. failure({ status : req.status, "msg" : req.responseText });
  1471. }
  1472. }
  1473. };
  1474. var codeJson = self.oauthToken;
  1475. var argString = "client_id=" + encodeURIComponent(this.oauth.clientId) + "&client_secret=" + encodeURIComponent(this.oauth.clientSecret) + "&refresh_token=" + encodeURIComponent(codeJson.refresh_token) + "&grant_type=refresh_token";
  1476. req.send(argString);
  1477. };
  1478. this.processResponse = function (req, callback, failure) {
  1479. if (!this.accessToken) {
  1480. callback(false);
  1481. }
  1482. else if (req.status != 401) {
  1483. callback(false);
  1484. }
  1485. else {
  1486. this.refreshAuthToken(callback, failure);
  1487. }
  1488. };
  1489. this.authToken = null;
  1490. this.getCategories = function (params, success, failure) {
  1491. var self = this;
  1492. this.getPosts(
  1493. params,
  1494. function (posts) {
  1495. var categories = {};
  1496. for (var i = 0; i < posts.length; i++) {
  1497. for (var j = 0; j < posts[i].categories.length; j++) {
  1498. categories[posts[i].categories[j]] = true;
  1499. }
  1500. }
  1501. var rv = [];
  1502. for (var i in categories) {
  1503. rv.push(i);
  1504. }
  1505. rv.sort();
  1506. for (var i = 0; i < rv.length; i++) {
  1507. var categoryName = rv[i];
  1508. rv[i] = { "id" : rv[i], "name": rv[i] };
  1509. }
  1510. success(rv);
  1511. },
  1512. failure
  1513. );
  1514. };
  1515. this.addCategory = function (params, success, failure) {
  1516. success({ "id": params.name, "name": params.name });
  1517. };
  1518. this.doAuth = function (callback, params) {
  1519. if (this.authToken) {
  1520. callback(this.authToken);
  1521. }
  1522. else {
  1523. var self = this;
  1524. var req = new XMLHttpRequest();
  1525. req.open("POST", "https://www.google.com/accounts/ClientLogin", true);
  1526. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1527. var argString = "Email="+encodeURIComponent(this.username)+"&Passwd="+encodeURIComponent(this.password)+"&service=blogger&source=scribefire";
  1528. if (params) {
  1529. for (var i in params) {
  1530. argString += "&"+i+"="+encodeURIComponent(params[i]);
  1531. }
  1532. }
  1533. req.onreadystatechange = function () {
  1534. if (req.readyState == 4) {
  1535. var lines = req.responseText.split("\n");
  1536. var returnValues = {};
  1537. for (var i = 0; i < lines.length; i++) {
  1538. var parts = lines[i].split("=");
  1539. var key = parts.shift();
  1540. var value = parts.join("=");
  1541. returnValues[key] = value;
  1542. }
  1543. if (req.status < 300) {
  1544. self.authToken = returnValues["Auth"];
  1545. callback(self.authToken);
  1546. }
  1547. else {
  1548. switch (returnValues["Error"]) {
  1549. case 'BadAuthentication':
  1550. SCRIBEFIRE.error(scribefire_string("error_api_blogger_authentication"), "BadAuthentication");
  1551. return;
  1552. break;
  1553. case 'NotVerified':
  1554. SCRIBEFIRE.error(scribefire_string("error_api_blogger_verify"));
  1555. return;
  1556. break;
  1557. case 'TermsNotAgreed':
  1558. SCRIBEFIRE.error(scribefire_string("error_api_blogger_tos"));
  1559. return;
  1560. break;
  1561. case 'AccountDeleted':
  1562. SCRIBEFIRE.error(scribefire_string("error_api_blogger_deleted"));
  1563. return;
  1564. break;
  1565. case 'ServiceDisabled':
  1566. SCRIBEFIRE.error(scribefire_string("error_api_blogger_disabled"));
  1567. return;
  1568. break;
  1569. case 'ServiceUnavailable':
  1570. SCRIBEFIRE.error(scribefire_string("error_api_blogger_unavailable"));
  1571. return;
  1572. break;
  1573. case 'CaptchaRequired':
  1574. var imgUrl = "https://www.google.com/accounts/" + returnValues["CaptchaUrl"];
  1575. var container = $("<div/>");
  1576. var header = $("<h4/>");
  1577. header.text(scribefire_string("error_api_blogger_captcha"));
  1578. container.append(header);
  1579. var message = $("<p/>");
  1580. container.append(message);
  1581. var image = $("<img/>");
  1582. image.attr("src", imgUrl);
  1583. message.append(image);
  1584. var textbox = $("<input/>");
  1585. textbox.attr("type", "text");
  1586. textbox.attr("id", "google-captcha");
  1587. container.append(textbox);
  1588. var submit = $("<input />");
  1589. submit.attr("type", "submit");
  1590. submit.val(scribefire_string("continue"));
  1591. submit.attr("id", "captcha-continue");
  1592. container.append(submit);
  1593. $.facebox(container);
  1594. $("#captcha-continue").live("click", function (e) {
  1595. var captcha = $("#google-captcha").val();
  1596. $(document).trigger("close.facebox");
  1597. if (captcha) {
  1598. self.doAuth(callback, {"logintoken": returnValues["CaptchaToken"], "logincaptcha": captcha });
  1599. return;
  1600. }
  1601. });
  1602. return;
  1603. break;
  1604. case 'Unknown':
  1605. returnValues["Error"] = scribefire_string("error_unknown");
  1606. break;
  1607. default:
  1608. break;
  1609. }
  1610. SCRIBEFIRE.error(scribefire_string("error_api_blogger_unknown", returnValues["Error"]));
  1611. }
  1612. }
  1613. };
  1614. req.send(argString);
  1615. }
  1616. };
  1617. this.buildRequest = function (method, url, callback) {
  1618. var self = this;
  1619. function build(token) {
  1620. var req = new XMLHttpRequest();
  1621. // encodeURIComponent is used here because otherwise some requests were failing
  1622. // when the password contains special characters like "@"
  1623. req.open(method, url, true, encodeURIComponent(self.username), encodeURIComponent(self.password));
  1624. req.setRequestHeader("Authorization", "GoogleLogin auth=" + token);
  1625. req.setRequestHeader("Content-Type", "application/atom+xml");
  1626. return req;
  1627. }
  1628. if (this.accessToken) {
  1629. var req = new XMLHttpRequest();
  1630. req.open(method, url, true);
  1631. req.setRequestHeader("Authorization", "Bearer " + this.accessToken);
  1632. req.setRequestHeader("Content-Type", "application/atom+xml");
  1633. callback(req);
  1634. }
  1635. else if (this.authToken) {
  1636. var req = build(this.authToken);
  1637. callback(req);
  1638. }
  1639. else {
  1640. this.doAuth(function (token) {
  1641. var req = build(token);
  1642. callback(req);
  1643. });
  1644. }
  1645. };
  1646. this.upload = function (fileName, fileType, fileData, success, failure, file) {
  1647. var self = this;
  1648. var invalidTokens = 0;
  1649. if (!(window.File && window.FileReader && window.FileList && window.Blob) && platform == 'gecko') {
  1650. function doUpload(token, tokenType) {
  1651. if (!tokenType) tokenType = "AuthSub";
  1652. var mimeSvc = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
  1653. var theMimeType = mimeSvc.getTypeFromFile(file);
  1654. const MULTI = "@mozilla.org/io/multiplex-input-stream;1";
  1655. const FINPUT = "@mozilla.org/network/file-input-stream;1";
  1656. const BUFFERED = "@mozilla.org/network/buffered-input-stream;1";
  1657. const nsIMultiplexInputStream = Components.interfaces.nsIMultiplexInputStream;
  1658. const nsIFileInputStream = Components.interfaces.nsIFileInputStream;
  1659. const nsIBufferedInputStream = Components.interfaces.nsIBufferedInputStream;
  1660. var buf = null;
  1661. var fin = null;
  1662. var fpLocal = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
  1663. fpLocal.initWithFile(file);
  1664. fin = Components.classes[FINPUT].createInstance(nsIFileInputStream);
  1665. fin.init(fpLocal, 1, 0, false);
  1666. buf = Components.classes[BUFFERED].createInstance(nsIBufferedInputStream);
  1667. buf.init(fin, 9000000);
  1668. var uploadStream = Components.classes[MULTI].createInstance(nsIMultiplexInputStream);
  1669. uploadStream.appendStream(buf);
  1670. var upreq = new XMLHttpRequest();
  1671. upreq.open("POST", "http://picasaweb.google.com/data/feed/api/user/default/albumid/default", true);
  1672. if (tokenType == "AuthSub") {
  1673. upreq.setRequestHeader("Authorization","AuthSub token="+token);
  1674. }
  1675. else {
  1676. upreq.setRequestHeader("Authorization","Bearer "+token);
  1677. }
  1678. upreq.setRequestHeader("Content-Type", theMimeType);
  1679. upreq.setRequestHeader("Content-Length", (uploadStream.available()));
  1680. upreq.overrideMimeType("text/xml");
  1681. upreq.onreadystatechange = function () {
  1682. if (upreq.readyState == 4) {
  1683. self.processResponse(upreq, function (redo) {
  1684. if (redo) {
  1685. self.upload(fileName, fileType, fileData, success, failure, file);
  1686. }
  1687. else {
  1688. if (upreq.status < 300) {
  1689. invalidTokens = 0;
  1690. try {
  1691. var imageUrl = $(xmlFromRequest(upreq)).find("content:first").attr("src");
  1692. success( { "url" : imageUrl } );
  1693. } catch (e) {
  1694. failure( { "status" : upreq.status, "msg" : upreq.responseText });
  1695. }
  1696. }
  1697. else {
  1698. if (tokenType == "AuthSub" && upreq.status == 403 && upreq.responseText.match(/Token invalid/)) {
  1699. invalidTokens++;
  1700. if (invalidTokens > 1) {
  1701. failure( { "status" : upreq.status, "msg" : scribefire_string("error_api_blogger_authToken") });
  1702. }
  1703. else {
  1704. delete tokens_json[self.username];
  1705. SCRIBEFIRE.prefs.setJSONPref("google_tokens", tokens_json);
  1706. SCRIBEFIRE.prefs.setCharPref("google_token", "");
  1707. self.upload(fileName, fileType, fileData, success, failure, file);
  1708. }
  1709. }
  1710. else if (upreq.responseText.match(/Must sign terms/i)) {
  1711. // @todo gOpener.parent.getWebBrowser().selectedTab = gOpener.parent.getWebBrowser().addTab("http://picasaweb.google.com/");
  1712. failure( { "status" : upreq.status, "msg" : upreq.responseText });
  1713. }
  1714. else {
  1715. failure( { "status" : upreq.status, "msg" : scribefire_string("error_api_blogger_uploadAPIUnavailable") } );
  1716. }
  1717. }
  1718. }
  1719. }, failure);
  1720. }
  1721. };
  1722. upreq.send(uploadStream);
  1723. }
  1724. if (self.accessToken) {
  1725. doUpload(self.accessToken, "Bearer");
  1726. }
  1727. else {
  1728. var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).QueryInterface(Components.interfaces.nsIPrefBranch).getBranch("extensions.scribefire.");
  1729. prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
  1730. var prefObserver = {
  1731. observe : function (subject, topic, data) {
  1732. if (topic == 'nsPref:changed') {
  1733. if (data == 'google_token') {
  1734. prefs.removeObserver(prefObserver);
  1735. var token = SCRIBEFIRE.prefs.getCharPref("google_token");
  1736. if (!token) {
  1737. return;
  1738. }
  1739. var req = new XMLHttpRequest();
  1740. req.open("GET", "https://www.google.com/accounts/AuthSubSessionToken", true);
  1741. req.setRequestHeader("Authorization","AuthSub token=\""+token+"\"");
  1742. req.onreadystatechange = function () {
  1743. if (req.readyState == 4) {
  1744. if (req.status == 200) {
  1745. var lines = req.responseText.split("\n");
  1746. var newTokenLine = lines[0];
  1747. var newToken = newTokenLine.split("=")[1];
  1748. var tokens_json = SCRIBEFIRE.prefs.getJSONPref("google_tokens", {});
  1749. tokens_json[self.username] = newToken;
  1750. SCRIBEFIRE.prefs.setJSONPref("google_tokens", tokens_json);
  1751. doUpload(newToken);
  1752. }
  1753. else {
  1754. failure( { "status" : req.status, "msg" : scribefire_string("error_api_blogger_authToken") } );
  1755. }
  1756. }
  1757. };
  1758. req.send(null);
  1759. }
  1760. }
  1761. }
  1762. };
  1763. prefs.addObserver("", prefObserver, false);
  1764. var tokens_json = SCRIBEFIRE.prefs.getJSONPref("google_tokens", {});
  1765. if (self.username in tokens_json) {
  1766. doUpload(tokens_json[self.username]);
  1767. }
  1768. else {
  1769. invalidTokens++;
  1770. window.open("https://www.google.com/accounts/AuthSubRequest"
  1771. + "?scope="+encodeURIComponent('http://picasaweb.google.com/data/')
  1772. + "&next="+ encodeURIComponent('http://www.scribefire.com/token.php') +"&session=1",
  1773. "sf-google-token",
  1774. "height=400,width=600,menubar=no,toolbar=no,location=no,personalbar=no,status=no");
  1775. }
  1776. }
  1777. }
  1778. else {
  1779. function doUpload(token, tokenType) {
  1780. var upreq = new XMLHttpRequest();
  1781. upreq.open("POST", "http://picasaweb.google.com/data/feed/api/user/default/albumid/default", true);
  1782. if (tokenType == "AuthSub") {
  1783. upreq.setRequestHeader("Authorization","AuthSub token="+token);
  1784. }
  1785. else {
  1786. upreq.setRequestHeader("Authorization","Bearer "+token);
  1787. }
  1788. upreq.setRequestHeader("Content-Type", fileType);
  1789. upreq.overrideMimeType("text/xml");
  1790. upreq.onreadystatechange = function () {
  1791. if (upreq.readyState == 4) {
  1792. self.processResponse(upreq, function (redo) {
  1793. if (redo) {
  1794. self.upload(fileName, fileType, fileData, success, failure, file);
  1795. }
  1796. else {
  1797. if (upreq.status < 300) {
  1798. invalidTokens = 0;
  1799. try {
  1800. var imageUrl = $(xmlFromRequest(upreq)).find("content:first").attr("src");
  1801. success( { "url" : imageUrl } );
  1802. } catch (e) {
  1803. failure( { "status" : upreq.status, "msg" : upreq.responseText });
  1804. }
  1805. }
  1806. else {
  1807. if (tokenType == "AuthSub" && upreq.status == 403 && upreq.responseText.match(/Token invalid/)) {
  1808. invalidTokens++;
  1809. if (invalidTokens > 1) {
  1810. failure( { "status" : upreq.status, "msg" : scribefire_string("error_api_blogger_authToken") });
  1811. }
  1812. else {
  1813. delete tokens_json[self.username];
  1814. SCRIBEFIRE.prefs.setJSONPref("google_tokens", tokens_json);
  1815. SCRIBEFIRE.prefs.setCharPref("google_token", "");
  1816. self.upload(fileName, fileType, fileData, success, failure);
  1817. }
  1818. }
  1819. else if (upreq.responseText.match(/Must sign terms/i)) {
  1820. // @todo gOpener.parent.getWebBrowser().selectedTab = gOpener.parent.getWebBrowser().addTab("http://picasaweb.google.com/");
  1821. failure( { "status" : upreq.status, "msg" : upreq.responseText });
  1822. }
  1823. else {
  1824. failure( { "status" : upreq.status, "msg" : scribefire_string("error_api_blogger_uploadAPIUnavailable") + " " + upreq.responseText } );
  1825. }
  1826. }
  1827. }
  1828. }, failure);
  1829. }
  1830. };
  1831. upreq.send(file);
  1832. }
  1833. if (self.accessToken) {
  1834. doUpload(self.accessToken, "Bearer");
  1835. }
  1836. else {
  1837. var prefObserver = {
  1838. observe : function (subject, topic, data) {
  1839. if (topic == 'nsPref:changed') {
  1840. if (data == 'google_token') {
  1841. var token = SCRIBEFIRE.prefs.getCharPref("google_token");
  1842. if (!token) {
  1843. return;
  1844. }
  1845. var req = new XMLHttpRequest();
  1846. req.open("GET", "https://www.google.com/accounts/AuthSubSessionToken", true);
  1847. req.setRequestHeader("Authorization","AuthSub token=\""+token+"\"");
  1848. req.onreadystatechange = function () {
  1849. if (req.readyState == 4) {
  1850. if (req.status == 200) {
  1851. var lines = req.responseText.split("\n");
  1852. var newTokenLine = lines[0];
  1853. var newToken = newTokenLine.split("=")[1];
  1854. var tokens_json = SCRIBEFIRE.prefs.getJSONPref("google_tokens", {});
  1855. tokens_json[self.username] = newToken;
  1856. SCRIBEFIRE.prefs.setJSONPref("google_tokens", tokens_json);
  1857. doUpload(newToken);
  1858. }
  1859. else {
  1860. failure( { "status" : req.status, "msg" : scribefire_string("error_api_blogger_authToken") } );
  1861. }
  1862. }
  1863. };
  1864. req.send(null);
  1865. }
  1866. }
  1867. }
  1868. };
  1869. SCRIBEFIRE.prefs.addObserver(prefObserver);
  1870. var tokens_json = SCRIBEFIRE.prefs.getJSONPref("google_tokens", {});
  1871. if (self.username in tokens_json) {
  1872. doUpload(tokens_json[self.username]);
  1873. }
  1874. else {
  1875. invalidTokens++;
  1876. window.open("https://www.google.com/accounts/AuthSubRequest"
  1877. + "?scope="+encodeURIComponent('http://picasaweb.google.com/data/')
  1878. + "&next="+ encodeURIComponent('http://www.scribefire.com/token.php') +"&session=1",
  1879. "sf-google-token",
  1880. "height=400,width=600,menubar=no,toolbar=no,location=no,personalbar=no,status=no");
  1881. }
  1882. }
  1883. }
  1884. }
  1885. };
  1886. bloggerAPI.prototype = new genericAtomAPI();
  1887. bloggerAPI.prototype.parent = genericAtomAPI.prototype;
  1888. var tumblrAPI = function () {
  1889. var newUi = {};
  1890. for (var x in this.ui) newUi[x] = this.ui[x];
  1891. this.ui = newUi;
  1892. this.ui.categories = false;
  1893. this.ui.timestamp = false;
  1894. this.ui.slug = true;
  1895. this.ui.private = true;
  1896. this.ui.draft = false; // drafts aren't being returned in the /read response
  1897. this.postInit = function () {
  1898. this.ui.getPosts = !this.isPrivate;
  1899. };
  1900. this.getBlogs = function (params, success, failure) {
  1901. var url = "http://www.tumblr.com/api/authenticate";
  1902. var args = {};
  1903. args.email = params.username;
  1904. args.password = params.password;
  1905. var argstring = "";
  1906. for (var i in args) {
  1907. argstring += encodeURIComponent(i) + "=" + encodeURIComponent(args[i]) + "&";
  1908. }
  1909. argstring = argstring.substr(0, argstring.length - 1);
  1910. var req = new XMLHttpRequest();
  1911. req.open("POST", url, true);
  1912. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1913. req.onreadystatechange = function () {
  1914. if (req.readyState == 4) {
  1915. if (req.status == 200) {
  1916. var xml = xmlFromRequest(req);
  1917. var jxml = $(xml);
  1918. var blogs = [];
  1919. var i = 1;
  1920. jxml.find("tumblelog").each(function () {
  1921. var blog = {};
  1922. blog.apiUrl = "http://www.tumblr.com/api";
  1923. blog.type = params.type;
  1924. blog.username = params.username;
  1925. blog.password = params.password;
  1926. blog.isPrivate = ($(this).attr("type") == "private");
  1927. if (blog.isPrivate) {
  1928. blog.id = $(this).attr("private-id");
  1929. blog.name = "Private Tumblr Blog #" + blog.id;
  1930. blog.url = "http://www.tumblr.com/#" + blog.id;
  1931. }
  1932. else {
  1933. blog.id = i++;
  1934. blog.name = $(this).attr("title");
  1935. blog.url = $(this).attr("url");
  1936. }
  1937. blogs.push(blog);
  1938. });
  1939. if (blogs.length > 0) {
  1940. success(blogs);
  1941. }
  1942. else {
  1943. if (failure) {
  1944. failure( {"status" : 200, "msg" : scribefire_string("error_api_cannotConnect")});
  1945. }
  1946. }
  1947. }
  1948. else {
  1949. if (failure) {
  1950. failure({"status": req.status, "msg": req.responseText});
  1951. }
  1952. }
  1953. }
  1954. };
  1955. req.send(argstring);
  1956. };
  1957. this.getPosts = function (params, success, failure) {
  1958. if (!("limit" in params)) params.limit = 50;
  1959. if (this.isPrivate) {
  1960. success([]);
  1961. return;
  1962. }
  1963. else {
  1964. var url = this.url + "api/read";//?start=0&num="+params.limit+"&type=regular";
  1965. }
  1966. var args = {};
  1967. args.email = this.username;
  1968. args.password = this.password;
  1969. // @todo-more-posts
  1970. args.start = 0;
  1971. args.num = params.limit;
  1972. args.type = "text";
  1973. var argstring = "";
  1974. for (var i in args) {
  1975. argstring += "&" + encodeURIComponent(i) + "=" + encodeURIComponent(args[i]);
  1976. }
  1977. argstring = argstring.substr(1);
  1978. var req = new XMLHttpRequest();
  1979. req.open("POST", url, true);
  1980. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1981. req.onreadystatechange = function () {
  1982. if (req.readyState == 4) {
  1983. if (req.status == 200) {
  1984. var xml = xmlFromRequest(req);
  1985. var jxml = $(xml);
  1986. var rv = [];
  1987. jxml.find("post").each(function () {
  1988. var post = {};
  1989. post.title = $(this).find("regular-title:first").text();
  1990. post.content = $(this).find("regular-body:first").text();
  1991. post.id = $(this).attr("id");
  1992. post.url = $(this).attr("url");
  1993. post.published = true;
  1994. post.categories = [];
  1995. post.private = false;
  1996. if ($(this).attr("private") && $(this).attr("private") == "true") {
  1997. post.private = true;
  1998. }
  1999. post.tags = [];
  2000. $(this).find("tag").each(function () {
  2001. post.tags.push($(this).text());
  2002. });
  2003. post.tags = post.tags.join(", ");
  2004. post.slug = $(this).attr("slug");
  2005. rv.push(post);
  2006. });
  2007. success(rv);
  2008. }
  2009. else {
  2010. failure({"status": req.status, "msg" : req.responseText});
  2011. }
  2012. }
  2013. };
  2014. req.send(argstring);
  2015. };
  2016. this.publish = function (params, success, failure) {
  2017. var args = {};
  2018. args.email = this.username;
  2019. args.password = this.password;
  2020. args.generator = "ScribeFire";
  2021. if (!this.isPrivate) {
  2022. args.group = this.url.split("//")[1].split("/")[0];
  2023. }
  2024. else {
  2025. args.group = this.id;
  2026. }
  2027. args.tags = params.tags;
  2028. args.type = 'regular';
  2029. args.format = 'html';
  2030. args.title = params.title;
  2031. args.body = params.content;
  2032. if ("private" in params) {
  2033. args.private = params.private * 1;
  2034. }
  2035. if ("draft" in params) {
  2036. args.state = params.draft ? "draft" : "published";
  2037. }
  2038. if (("id" in params) && params.id) {
  2039. args["post-id"] = params.id;
  2040. }
  2041. if ("slug" in params) {
  2042. args.slug = params.slug;
  2043. }
  2044. var argstring = "";
  2045. for (var i in args) {
  2046. argstring += encodeURIComponent(i) + "=" + encodeURIComponent(args[i]) + "&";
  2047. }
  2048. argstring = argstring.substr(0, argstring.length - 1);
  2049. var req = new XMLHttpRequest();
  2050. req.open("POST", "http://www.tumblr.com/api/write", true);
  2051. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  2052. req.onreadystatechange = function (event) {
  2053. if (req.readyState == 4) {
  2054. if (req.status < 300) {
  2055. if (("id" in params) && params.id) {
  2056. success({ "id" : params.id });
  2057. }
  2058. else {
  2059. success({ "id": req.responseText });
  2060. }
  2061. }
  2062. else {
  2063. failure({ "status": req.status, "msg": req.responseText });
  2064. }
  2065. }
  2066. };
  2067. req.send(argstring);
  2068. };
  2069. this.deletePost = function (params, success, failure) {
  2070. var args = {};
  2071. args.email = this.username;
  2072. args.password = this.password;
  2073. args["post-id"] = params.id;
  2074. var argstring = "";
  2075. for (var i in args) {
  2076. argstring += encodeURIComponent(i) + "=" + encodeURIComponent(args[i]) + "&";
  2077. }
  2078. argstring = argstring.substr(0, argstring.length - 1);
  2079. var req = new XMLHttpRequest();
  2080. req.open("POST", "http://www.tumblr.com/api/delete", true);
  2081. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  2082. req.onreadystatechange = function (event) {
  2083. if (req.readyState == 4) {
  2084. if (req.status < 300) {
  2085. success(true);
  2086. }
  2087. else {
  2088. failure({ "status": req.status, "msg": req.responseText });
  2089. }
  2090. }
  2091. };
  2092. req.send(argstring);
  2093. };
  2094. };
  2095. tumblrAPI.prototype = new blogAPI();
  2096. var posterousAPI = function () {
  2097. var newUi = {};
  2098. for (var x in this.ui) newUi[x] = this.ui[x];
  2099. this.ui = newUi;
  2100. this.ui.categories = false;
  2101. this.ui.timestamp = false; // Scheduling posterous changes the time, but it doesn't delay the publication.
  2102. this.ui.private = true;
  2103. this.ui.upload = (platform == 'gecko');
  2104. this.token = "AFEuheynrHoJlBJqwHzoFEngfEkebtEI";
  2105. this.getBlogs = function (params, success, failure) {
  2106. var self = this;
  2107. var url = "http://posterous.com/api/2/users/me/sites?api_token=" + encodeURIComponent(self.token);
  2108. var req = new XMLHttpRequest();
  2109. req.open("GET", url, true);
  2110. req.setRequestHeader("Authorization", "Basic " + btoa(params.username + ":" + params.password));
  2111. req.onreadystatechange = function () {
  2112. if (req.readyState == 4) {
  2113. if (req.status == 200) {
  2114. try {
  2115. var json = JSON.parse(req.responseText);
  2116. } catch (e) {
  2117. failure({"status" : req.status, "msg" : "Invalid response from server: " + req.responseText });
  2118. return;
  2119. }
  2120. var blogs = [];
  2121. for (var i = 0, _len = json.length; i < _len; i++) {
  2122. var entry = json[i];
  2123. var blog = {};
  2124. blog.id = entry.id;
  2125. blog.apiUrl = "http://posterous.com/api";
  2126. blog.type = params.type;
  2127. blog.username = params.username;
  2128. blog.password = params.password;
  2129. blog.name = entry.name;
  2130. blog.url = "http://" + entry.full_hostname;
  2131. blogs.push(blog);
  2132. }
  2133. if (blogs.length) {
  2134. success(blogs);
  2135. }
  2136. else {
  2137. if (failure) {
  2138. failure( {"status" : 200, "msg" : scribefire_string("error_api_cannotConnect")});
  2139. }
  2140. }
  2141. }
  2142. else {
  2143. if (failure) {
  2144. failure({"status": req.status, "msg": req.responseText});
  2145. }
  2146. }
  2147. }
  2148. };
  2149. req.send(null);
  2150. };
  2151. this.getPosts = function (params, success, failure) {
  2152. var self = this;
  2153. var url = "http://posterous.com/api/2/users/me/sites/" + self.id + "/posts?api_token=" + encodeURIComponent(self.token);
  2154. var req = new XMLHttpRequest();
  2155. req.open("GET", url, true);
  2156. req.setRequestHeader("Authorization", "Basic " + btoa(self.username + ":" + self.password));
  2157. req.onreadystatechange = function () {
  2158. if (req.readyState == 4) {
  2159. if (req.status == 200) {
  2160. try {
  2161. var json = JSON.parse(req.responseText);
  2162. } catch (e) {
  2163. failure({"status" : req.status, "msg" : "Invalid response from server: " + req.responseText });
  2164. return;
  2165. }
  2166. var rv = [];
  2167. for (var i = 0, _len = json.length; i < _len; i++) {
  2168. var json_entry = json[i];
  2169. var entry = {}
  2170. entry.id = json_entry.id;
  2171. entry.content = json_entry.body_full;
  2172. entry.title = json_entry.title;
  2173. entry.published = true; // @todo Does Posterous support drafts?
  2174. entry.private = json_entry.is_private;
  2175. if ("display_date" in json_entry) {
  2176. entry.timestamp = new Date(json_entry.display_date + " -0700");
  2177. /*
  2178. var expectedOffset = parseInt((new Date()).format("Z"), 10);
  2179. var offset = -7 * 60 * 60;
  2180. var delta = expectedOffset - offset;
  2181. if (delta) {
  2182. // entry.timestamp.setTime(entry.timestamp.getTime() + (delta * 1000));
  2183. }
  2184. */
  2185. }
  2186. var tags = [];
  2187. for (var j = 0, _jlen = json_entry.tags.length; j < _jlen; j++) {
  2188. tags.push(json_entry.tags[j].name);
  2189. }
  2190. entry.tags = tags.join(", ");
  2191. entry.categories = [];
  2192. rv.push(entry);
  2193. }
  2194. success(rv);
  2195. }
  2196. else {
  2197. failure({"status": req.status, "msg": req.responseText});
  2198. }
  2199. }
  2200. };
  2201. req.send(null);
  2202. };
  2203. this.publish = function (params, success, failure) {
  2204. var self = this;
  2205. if ("id" in params && params.id) {
  2206. var url = "http://posterous.com/api/2/users/me/sites/" + self.id + "/posts/" + encodeURIComponent(params.id) + "?api_token=" + encodeURIComponent(self.token);
  2207. var method = "PUT";
  2208. }
  2209. else {
  2210. var url = "http://posterous.com/api/2/users/me/sites/" + self.id + "/posts?api_token=" + encodeURIComponent(self.token);
  2211. var method = "POST";
  2212. }
  2213. var req = new XMLHttpRequest();
  2214. req.open(method, url, true);
  2215. req.setRequestHeader("Authorization", "Basic " + btoa(self.username + ":" + self.password));
  2216. var args = {};
  2217. args["post[title]"] = params.title;
  2218. args["post[body]"] = params.content;
  2219. args["post[tags]"] = params.tags;
  2220. args["post[source]"] = "ScribeFire";
  2221. if ("timestamp" in params && params.timestamp) {
  2222. // From what I understand, Posterous assumes all dates passed in are in -0700.
  2223. var timestampCopy = new Date(params.timestamp);
  2224. var offset = parseInt(timestampCopy.format("Z"), 10);
  2225. var expectedOffset = -7 * 60 * 60;
  2226. var delta = expectedOffset - offset;
  2227. if (delta) {
  2228. timestampCopy.setTime(timestampCopy.getTime() + (delta * 1000));
  2229. }
  2230. args["post[display_date]"] = timestampCopy.format("Y/m/d H:i:s");
  2231. }
  2232. if ("private" in params) {
  2233. args["post[is_private]"] = params.private * 1;
  2234. }
  2235. var images = params.content.match(/(<img[^>]+>)/g);
  2236. if (self.ui.upload && images) {
  2237. if (images.length > 0) {
  2238. var ios = Components.classes["@mozilla.org/network/io-service;1"]. getService(Components.interfaces.nsIIOService);
  2239. for (var i = 0, _len = images.length; i < _len; i++) {
  2240. var src = images[i].match(/\ssrc=['"]([^'"]+)['"]/i)[1];
  2241. var url = ios.newURI(src, null, null);
  2242. var theFile = url.QueryInterface(Components.interfaces.nsIFileURL).file;
  2243. args["media["+i+"]"] = {
  2244. "file" : theFile,
  2245. };
  2246. }
  2247. }
  2248. var postRequest = createScribeFirePostRequest(args);
  2249. req.setRequestHeader("Content-Length", (postRequest.requestBody.available()));
  2250. req.setRequestHeader("Content-Type","multipart/form-data; boundary="+postRequest.boundary);
  2251. var argstring = postRequest.requestBody;
  2252. }
  2253. else {
  2254. var argstring = "";
  2255. for (var i in args) {
  2256. argstring += encodeURIComponent(i) + "=" + encodeURIComponent(args[i]) + "&";
  2257. }
  2258. argstring = argstring.substr(0, argstring.length - 1);
  2259. req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  2260. }
  2261. req.onreadystatechange = function () {
  2262. if (req.readyState == 4) {
  2263. if (req.status == 200 || req.status == 201) {
  2264. try {
  2265. var json = JSON.parse(req.responseText);
  2266. } catch (e) {
  2267. failure({ "status" : req.status, "msg" : "Invalid response from the blog server: " + req.responseText });
  2268. return;
  2269. }
  2270. success({ "id": json.id });
  2271. }
  2272. else {
  2273. failure({"status": req.status, "msg": json.message });
  2274. }
  2275. }
  2276. };
  2277. req.send(argstring);
  2278. };
  2279. this.deletePost = function (params, success, failure) {
  2280. var self = this;
  2281. var url = "http://posterous.com/api/2/users/me/sites/" + self.id + "/posts/" + params.id + "?api_token=" + encodeURIComponent(self.token);
  2282. var req = new XMLHttpRequest();
  2283. req.open("DELETE", url, true);
  2284. req.setRequestHeader("Authorization", "Basic " + btoa(self.username + ":" + self.password));
  2285. req.onreadystatechange = function () {
  2286. if (req.readyState == 4) {
  2287. if (req.status == 200) {
  2288. success(true);
  2289. }
  2290. else {
  2291. if (failure) {
  2292. failure({"status": req.status, "msg": req.responseText});
  2293. }
  2294. }
  2295. }
  2296. };
  2297. req.send(null);
  2298. };
  2299. this.upload = function (fileName, fileType, fileData, success, failure, file) {
  2300. success( { "url" : "file://" + file.path } );
  2301. }
  2302. };
  2303. posterousAPI.prototype = new blogAPI();
  2304. var performancingAPICalls = {
  2305. //myParams = [url, appkey, blogid, username, password, content, publish]
  2306. blogger_newPost: function(myParams) {
  2307. return XMLRPC_LIB.makeXML("blogger.newPost", myParams);
  2308. },
  2309. //myParams = [url, appkey, postid, username, password, content, publish]
  2310. blogger_editPost: function(myParams) {
  2311. return XMLRPC_LIB.makeXML("blogger.editPost", myParams);
  2312. },
  2313. //myParams = [url, appkey, postid, username, password, publish]
  2314. blogger_deletePost: function(myParams) {
  2315. return XMLRPC_LIB.makeXML("blogger.deletePost", myParams);
  2316. },
  2317. //myParams = [url, appkey, blogid, username, password, numberOfPosts]
  2318. blogger_getRecentPosts: function(myParams) {
  2319. return XMLRPC_LIB.makeXML("blogger.getRecentPosts", myParams);
  2320. },
  2321. //myParams = [url, appkey, username, password]
  2322. blogger_getUsersBlogs: function(myParams) {
  2323. return XMLRPC_LIB.makeXML("blogger.getUsersBlogs", myParams);
  2324. },
  2325. //myParams = [url, appkey, username, password]
  2326. blogger_getUserInfo: function(myParams) {
  2327. return XMLRPC_LIB.makeXML("blogger.getUserInfo", myParams);
  2328. },
  2329. //myParams = [url, blogid, username, password, content_t, publish]
  2330. metaWeblog_newPost: function(myParams) {
  2331. return XMLRPC_LIB.makeXML("metaWeblog.newPost", myParams);
  2332. },
  2333. metaWeblog_editPost: function(myParams) {
  2334. return XMLRPC_LIB.makeXML("metaWeblog.editPost", myParams);
  2335. },
  2336. //myParams = [url, blogid, username, password, numberOfPosts]
  2337. metaWeblog_getRecentPosts: function(myParams) {
  2338. return XMLRPC_LIB.makeXML("metaWeblog.getRecentPosts", myParams);
  2339. },
  2340. //myParams = [url, blogid, username, password]
  2341. metaWeblog_getCategoryList: function(myParams) {
  2342. return XMLRPC_LIB.makeXML("metaWeblog.getCategories", myParams);
  2343. },
  2344. //myParams = [url, blogid, username, password, mediaStruct]
  2345. metaWeblog_newMediaObject: function(myParams) {
  2346. return XMLRPC_LIB.makeXML("metaWeblog.newMediaObject", myParams);
  2347. },
  2348. //myParams = [url, blogid, username, password, numberOfPosts]
  2349. mt_getRecentPostTitles: function(myParams) {
  2350. return XMLRPC_LIB.makeXML("mt.getRecentPostTitles", myParams);
  2351. },
  2352. //myParams = [url, blogid, username, password]
  2353. mt_getCategoryList: function(myParams) {
  2354. return XMLRPC_LIB.makeXML("mt.getCategoryList", myParams);
  2355. },
  2356. //myParams = [url, postid, username, password, categories]
  2357. mt_setPostCategories: function(myParams) {
  2358. return XMLRPC_LIB.makeXML("mt.setPostCategories", myParams);
  2359. },
  2360. mt_getPostCategories: function(myParams) {
  2361. return XMLRPC_LIB.makeXML("mt.getPostCategories", myParams);
  2362. },
  2363. //mt_publishPost
  2364. //myParams = [url, postid, username, password]
  2365. mt_publishPost: function(myParams) {
  2366. return XMLRPC_LIB.makeXML("mt.publishPost", myParams);
  2367. },
  2368. wp_getPage : function (myParams) {
  2369. return XMLRPC_LIB.makeXML("wp.getPage", myParams);
  2370. },
  2371. wp_getPages : function (myParams) {
  2372. return XMLRPC_LIB.makeXML("wp.getPages", myParams);
  2373. },
  2374. wp_newPage : function (myParams) {
  2375. return XMLRPC_LIB.makeXML("wp.newPage", myParams);
  2376. },
  2377. wp_deletePage : function (myParams) {
  2378. return XMLRPC_LIB.makeXML("wp.deletePage", myParams);
  2379. },
  2380. wp_editPage : function (myParams) {
  2381. return XMLRPC_LIB.makeXML("wp.editPage", myParams);
  2382. },
  2383. wp_getPageList : function (myParams) {
  2384. return XMLRPC_LIB.makeXML("wp.getPageList", myParams);
  2385. },
  2386. wp_getAuthors : function (myParams) {
  2387. return XMLRPC_LIB.makeXML("wp.getAuthors", myParams);
  2388. },
  2389. wp_newCategory : function (myParams) {
  2390. return XMLRPC_LIB.makeXML("wp.newCategory", myParams);
  2391. },
  2392. wp_suggestCategories : function (myParams) {
  2393. return XMLRPC_LIB.makeXML("wp.suggestCategories", myParams);
  2394. },
  2395. wp_getUsersBlogs : function (myParams) {
  2396. return XMLRPC_LIB.makeXML("wp.getUsersBlogs", myParams);
  2397. },
  2398. wp_getMediaLibrary : function (myParams) {
  2399. return XMLRPC_LIB.makeXML("wp.getMediaLibrary", myParams);
  2400. }
  2401. };
  2402. function createScribeFirePostRequest(args) {
  2403. /**
  2404. * Generates a POST request body for uploading.
  2405. *
  2406. * args is an associative array of the form fields.
  2407. *
  2408. * Example:
  2409. * var args = { "field1": "abc", "field2" : "def", "fileField" : { "file": theFile, "headers" : [ "X-Fake-Header: foo" ] } };
  2410. *
  2411. * theFile is an nsILocalFile; the headers param for the file field is optional.
  2412. *
  2413. * This function returns an array like this:
  2414. * { "requestBody" : uploadStream, "boundary" : BOUNDARY }
  2415. *
  2416. * To upload:
  2417. *
  2418. * var postRequest = createPostRequest(args);
  2419. * var req = new XMLHttpRequest();
  2420. * req.open("POST", ...);
  2421. * req.setRequestHeader("Content-Type","multipart/form-data; boundary="+postRequest.boundary);
  2422. * req.setRequestHeader("Content-Length", (postRequest.requestBody.available()));
  2423. * req.send(postRequest.requestBody);
  2424. */
  2425. if (platform == 'gecko') {
  2426. function stringToStream(str) {
  2427. function encodeToUtf8(oStr) {
  2428. var utfStr = oStr;
  2429. var uConv = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  2430. uConv.charset = "UTF-8";
  2431. utfStr = uConv.ConvertFromUnicode(oStr);
  2432. return utfStr;
  2433. }
  2434. str = encodeToUtf8(str);
  2435. var stream = Components.classes["@mozilla.org/io/string-input-stream;1"].createInstance(Components.interfaces.nsIStringInputStream);
  2436. stream.setData(str, str.length);
  2437. return stream;
  2438. }
  2439. function fileToStream(file) {
  2440. var fpLocal = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
  2441. fpLocal.initWithFile(file);
  2442. var finStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
  2443. finStream.init(fpLocal, 1, 0, false);
  2444. var bufStream = Components.classes["@mozilla.org/network/buffered-input-stream;1"].createInstance(Components.interfaces.nsIBufferedInputStream);
  2445. bufStream.init(finStream, 9000000);
  2446. return bufStream;
  2447. }
  2448. var mimeSvc = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
  2449. const BOUNDARY = "---------------------------32191240128944";
  2450. var streams = [];
  2451. for (var i in args) {
  2452. var buffer = "--" + BOUNDARY + "\r\n";
  2453. buffer += "Content-Disposition: form-data; name=\"" + i + "\"";
  2454. streams.push(stringToStream(buffer));
  2455. if (typeof args[i] == "object") {
  2456. buffer = "; filename=\"" + args[i].file.leafName + "\"";
  2457. if ("headers" in args[i]) {
  2458. if (args[i].headers.length > 0) {
  2459. for (var q = 0; q < args[i].headers.length; q++){
  2460. buffer += "\r\n" + args[i].headers[q];
  2461. }
  2462. }
  2463. }
  2464. var theMimeType = mimeSvc.getTypeFromFile(args[i].file);
  2465. buffer += "\r\nContent-Type: " + theMimeType;
  2466. buffer += "\r\n\r\n";
  2467. streams.push(stringToStream(buffer));
  2468. streams.push(fileToStream(args[i].file));
  2469. }
  2470. else {
  2471. buffer = "\r\n\r\n";
  2472. buffer += args[i];
  2473. buffer += "\r\n";
  2474. streams.push(stringToStream(buffer));
  2475. }
  2476. }
  2477. var buffer = "--" + BOUNDARY + "--\r\n";
  2478. streams.push(stringToStream(buffer));
  2479. var uploadStream = Components.classes["@mozilla.org/io/multiplex-input-stream;1"].createInstance(Components.interfaces.nsIMultiplexInputStream);
  2480. for (var i = 0; i < streams.length; i++) {
  2481. uploadStream.appendStream(streams[i]);
  2482. }
  2483. return { "requestBody" : uploadStream, "boundary": BOUNDARY };
  2484. }
  2485. else {
  2486. throw new Exception("MethodNotSupported");
  2487. }
  2488. }