A Chrome extension for Write.as
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

312 строки
9.4 KiB

  1. var $content;
  2. var $publish;
  3. var $url;
  4. function publish(content, font) {
  5. if (content.trim() == "") {
  6. return;
  7. }
  8. $publish.classList.add('disabled');
  9. setPublishText(font, true);
  10. $publish.disabled = true;
  11. var post = H.getTitleStrict(content);
  12. var http = new XMLHttpRequest();
  13. var url = "https://write.as/api/posts";
  14. var lang = navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage);
  15. lang = lang.substring(0, 2);
  16. var params = "body=" + encodeURIComponent(post.content) + "&title=" + encodeURIComponent(post.title) + "&font=" + font + "&lang=" + lang + "&rtl=auto";
  17. http.open("POST", url, true);
  18. //Send the proper header information along with the request
  19. http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  20. http.onreadystatechange = function() {
  21. if (http.readyState == 4) {
  22. $publish.classList.remove('disabled');
  23. setPublishText(font, false);
  24. $publish.disabled = false;
  25. if (http.status == 201) {
  26. $publish.style.display = 'none';
  27. data = JSON.parse(http.responseText);
  28. // Pull out data parts
  29. id = data.data.id;
  30. if (font == 'code' || font === 'mono') {
  31. url = "https://paste.as/"+id;
  32. } else {
  33. url = "https://write.as/"+id;
  34. }
  35. editToken = data.data.token;
  36. document.getElementById("account-tools").style.display = 'none';
  37. document.getElementById("publish-holder").style.display = 'none';
  38. document.getElementById("result-holder").style.display = 'inline';
  39. $url = document.getElementById("url");
  40. $url.value = url;
  41. var $urlLink = document.getElementById("url-link");
  42. $urlLink.href = url;
  43. // Save the data if user wasn't logged in
  44. if (typeof data.data.owner === 'undefined' || data.data.owner == "") {
  45. posts = JSON.parse(H.get('posts', '[]'));
  46. posts.push(H.createPost(id, editToken, post.content));
  47. H.set('posts', JSON.stringify(posts));
  48. }
  49. } else {
  50. alert("Failed to post. Please try again.");
  51. }
  52. }
  53. }
  54. http.send(params);
  55. }
  56. function setPublishText(font, isPublishing) {
  57. if (font === 'code' || font === 'mono') {
  58. $publish.value = isPublishing ? 'Pasting...' : 'Paste';
  59. } else {
  60. $publish.value = isPublishing ? 'Publishing...' : 'Publish';
  61. }
  62. }
  63. document.addEventListener('DOMContentLoaded', function() {
  64. $content = document.getElementById("content");
  65. $publish = document.getElementById("publish");
  66. $url = document.getElementById("url");
  67. var $sync = document.getElementById('sync');
  68. var $modal = document.getElementById('modal');
  69. var fontRadios = document.postForm.font;
  70. var isPopout = window.location.search.substring(1) == "popout";
  71. if (isPopout) {
  72. chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  73. $content.value = request.msg;
  74. });
  75. }
  76. chrome.tabs.executeScript({
  77. code: "window.getSelection().toString();"
  78. }, function(selection) {
  79. if (typeof selection !== 'undefined') {
  80. $content.value = selection[0];
  81. }
  82. // load previous draft
  83. if ($content.value == "") {
  84. H.load($content, 'ext-draft');
  85. }
  86. });
  87. // focus on the paste field
  88. $content.focus();
  89. if (isPopout) {
  90. document.body.className = 'popout';
  91. } else {
  92. document.getElementById('popout').addEventListener('click', function(e) {
  93. e.preventDefault();
  94. chrome.windows.create({
  95. url: "popup.html?popout",
  96. width: 640,
  97. height: 400,
  98. focused: true,
  99. type: "popup"
  100. }, function(window) {
  101. chrome.runtime.sendMessage({msg: $content.value});
  102. });
  103. });
  104. document.querySelector('#modal .secondary').addEventListener('click', function(e) {
  105. e.preventDefault();
  106. $modal.style.display = 'none';
  107. });
  108. $sync.addEventListener('click', function(e) {
  109. e.preventDefault();
  110. var posts = JSON.parse(H.get('posts', '[]'));
  111. if (posts.length == 0) {
  112. return;
  113. }
  114. var p = "<p>There ";
  115. p += ((posts.length==1?'is':'are') + ' <strong>' + posts.length + " post" + (posts.length==1?'':'s'));
  116. var thePosts = posts.length == 1 ? 'it' : 'them';
  117. p += "</strong> saved on this computer.</p><p>Syncing "+thePosts+" to your account will give you access to "+thePosts+" from anywhere. Sync now?</p>";
  118. $modal.style.display = 'block';
  119. document.getElementById('modal-body').innerHTML = p;
  120. });
  121. document.querySelector('#modal .primary').addEventListener('click', function(e) {
  122. e.preventDefault();
  123. $modal.style.display = 'none';
  124. var posts = JSON.parse(H.get('posts', '[]'));
  125. $sync.innerText = "Syncing now...";
  126. $sync.className = 'disabled';
  127. var http = new XMLHttpRequest();
  128. var params = [];
  129. for (var i=0; i<posts.length; i++) {
  130. params.push({id: posts[i].id, token: posts[i].token});
  131. }
  132. http.open("POST", "https://write.as/api/posts/claim", true);
  133. http.setRequestHeader("Content-type", "application/json");
  134. http.onreadystatechange = function() {
  135. if (http.readyState == 4) {
  136. $sync.innerText = 'Importing now...';
  137. if (http.status == 200) {
  138. var res = JSON.parse(http.responseText);
  139. if (res.data.length > 0) {
  140. if (res.data.length != posts.length) {
  141. // TODO: handle this serious situation
  142. console.error("Request and result array length didn't match!");
  143. return;
  144. }
  145. for (var i=0; i<res.data.length; i++) {
  146. if (res.data[i].code == 200 || res.data[i].code == 404) {
  147. // Post successfully claimed.
  148. for (var j=0; j<posts.length; j++) {
  149. // Find post in local store
  150. var id = res.data[i].id;
  151. if (typeof res.data[i].post !== 'undefined') {
  152. id = res.data[i].post.id;
  153. }
  154. if (posts[j].id == id) {
  155. // Remove this post
  156. posts.splice(j, 1);
  157. break;
  158. }
  159. }
  160. } else {
  161. for (var j=0; j<posts.length; j++) {
  162. // Find post in local store
  163. if (posts[j].id == res.data[i].id) {
  164. // Note the error in the local post
  165. posts[j].error = res.data[i].error_msg;
  166. break;
  167. }
  168. }
  169. }
  170. }
  171. H.set('posts', JSON.stringify(posts));
  172. $sync.innerText = 'Synced.';
  173. }
  174. } else {
  175. // TODO: show error visually (option to retry)
  176. console.error("Well that didn't work at all!");
  177. $sync.className = '';
  178. $sync.innerText = 'Sync...';
  179. }
  180. }
  181. };
  182. http.send(JSON.stringify(params));
  183. });
  184. }
  185. // bind publish action
  186. $publish.addEventListener('click', function(e) {
  187. e.preventDefault();
  188. publish($content.value, fontRadios.value);
  189. });
  190. $content.addEventListener('keydown', function(e){
  191. if (e.ctrlKey && e.keyCode == 13) {
  192. e.preventDefault();
  193. publish($content.value, fontRadios.value);
  194. }
  195. });
  196. // bind URL select-all action
  197. $url.addEventListener('focus', function(e) {
  198. e.preventDefault();
  199. this.select();
  200. });
  201. // load font setting
  202. H.load(fontRadios, 'font');
  203. $content.className = fontRadios.value;
  204. setPublishText(fontRadios.value, false);
  205. // bind font changing action
  206. for(var i = 0; i < fontRadios.length; i++) {
  207. fontRadios[i].onclick = function() {
  208. $content.className = this.value;
  209. setPublishText(this.value, false);
  210. H.save(fontRadios, 'font');
  211. };
  212. }
  213. var handleRegUser = function() {
  214. var http = new XMLHttpRequest();
  215. http.open("GET", "https://write.as/api/me/", true);
  216. http.onreadystatechange = function() {
  217. if (http.readyState == 4) {
  218. data = JSON.parse(http.responseText);
  219. data = data.data;
  220. if (typeof data.username !== 'undefined' && data.username != "") {
  221. var $accTools = document.getElementById("account-tools")
  222. $accTools.style.display = 'block';
  223. var posts = JSON.parse(H.get('posts', '[]'));
  224. if (posts.length > 0) {
  225. $sync.style.display = 'inline';
  226. } else {
  227. $sync.style.display = 'none';
  228. }
  229. //document.getElementById("sync-count").innerText = posts.length + " post" + (posts.length==1?'':'s');
  230. document.getElementById("username").innerText = data.username;
  231. }
  232. }
  233. }
  234. http.send();
  235. }
  236. handleRegUser();
  237. if (H.get('updatedPostsMeta', '') == '') {
  238. // Add metadata used by Pad to all saved posts
  239. var addPostMetaData = function() {
  240. console.log('Adding post meta data...');
  241. var fetch = function(id, token, callback) {
  242. var http = new XMLHttpRequest();
  243. http.open("GET", "https://write.as/api/" + id + "?created=1&t=" + token, true);
  244. http.onreadystatechange = function() {
  245. if (http.readyState == 4) {
  246. callback(http.responseText, http.status);
  247. }
  248. }
  249. http.send();
  250. }
  251. var posts = JSON.parse(H.get('posts', '[]'));
  252. var migratedPosts = [];
  253. var failedPosts = [];
  254. if (posts.length > 0) {
  255. var i = 0;
  256. var updateMeta = function(content, status) {
  257. if (status == 200) {
  258. data = content.split("\n\n");
  259. created = data.splice(0, 1);
  260. migratedPosts.push(H.createPost(posts[i].id, posts[i].token, data.join("\n\n"), created));
  261. } else {
  262. posts[i].reason = status;
  263. failedPosts.push(posts[i]);
  264. }
  265. i++;
  266. if (i < posts.length) {
  267. fetch(posts[i].id, posts[i].token, updateMeta);
  268. } else {
  269. console.log('Finished! Success: ' + migratedPosts.length + '. Fail: ' + failedPosts.length);
  270. if (failedPosts.length > 0) {
  271. H.set('failedMigrationPosts', JSON.stringify(failedPosts));
  272. }
  273. H.set('posts', JSON.stringify(migratedPosts));
  274. H.set('updatedPostsMeta', 'yes');
  275. }
  276. };
  277. fetch(posts[i].id, posts[i].token, updateMeta);
  278. } else {
  279. H.set('updatedPostsMeta', 'yes');
  280. }
  281. };
  282. addPostMetaData();
  283. }
  284. });