A Chrome extension for Write.as
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

300 lines
8.9 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 fontRadios = document.postForm.font;
  68. var isPopout = window.location.search.substring(1) == "popout";
  69. if (isPopout) {
  70. chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  71. $content.value = request.msg;
  72. });
  73. }
  74. chrome.tabs.executeScript({
  75. code: "window.getSelection().toString();"
  76. }, function(selection) {
  77. if (typeof selection !== 'undefined') {
  78. $content.value = selection[0];
  79. }
  80. // load previous draft
  81. if ($content.value == "") {
  82. H.load($content, 'ext-draft');
  83. }
  84. });
  85. // focus on the paste field
  86. $content.focus();
  87. if (isPopout) {
  88. document.body.className = 'popout';
  89. } else {
  90. document.getElementById('popout').addEventListener('click', function(e) {
  91. e.preventDefault();
  92. chrome.windows.create({
  93. url: "popup.html?popout",
  94. width: 640,
  95. height: 400,
  96. focused: true,
  97. type: "popup"
  98. }, function(window) {
  99. chrome.runtime.sendMessage({msg: $content.value});
  100. });
  101. });
  102. document.getElementById('sync').addEventListener('click', function(e) {
  103. e.preventDefault();
  104. var posts = JSON.parse(H.get('posts', '[]'));
  105. var p = "There ";
  106. p += ((posts.length==1?'is ':'are ') + posts.length + " post" + (posts.length==1?'':'s'));
  107. var thePosts = posts.length == 1 ? 'it' : 'them';
  108. p += " saved on this computer.\n\nSyncing "+thePosts+" to your account gives you access to "+thePosts+" from anywhere. Sync now?";
  109. if (!confirm(p)) {
  110. return;
  111. }
  112. var $sync = this;
  113. $sync.innerText = "Syncing now...";
  114. $sync.className = 'disabled';
  115. var http = new XMLHttpRequest();
  116. var params = [];
  117. for (var i=0; i<posts.length; i++) {
  118. params.push({id: posts[i].id, token: posts[i].token});
  119. }
  120. http.open("POST", "https://write.as/api/posts/claim", true);
  121. http.setRequestHeader("Content-type", "application/json");
  122. http.onreadystatechange = function() {
  123. if (http.readyState == 4) {
  124. $sync.innerText = 'Importing now...';
  125. if (http.status == 200) {
  126. var res = JSON.parse(http.responseText);
  127. if (res.data.length > 0) {
  128. if (res.data.length != posts.length) {
  129. // TODO: handle this serious situation
  130. console.error("Request and result array length didn't match!");
  131. return;
  132. }
  133. for (var i=0; i<res.data.length; i++) {
  134. if (res.data[i].code == 200 || res.data[i].code == 404) {
  135. // Post successfully claimed.
  136. for (var j=0; j<posts.length; j++) {
  137. // Find post in local store
  138. var id = res.data[i].id;
  139. if (typeof res.data[i].post !== 'undefined') {
  140. id = res.data[i].post.id;
  141. }
  142. if (posts[j].id == id) {
  143. // Remove this post
  144. posts.splice(j, 1);
  145. break;
  146. }
  147. }
  148. } else {
  149. for (var j=0; j<posts.length; j++) {
  150. // Find post in local store
  151. if (posts[j].id == res.data[i].id) {
  152. // Note the error in the local post
  153. posts[j].error = res.data[i].error_msg;
  154. break;
  155. }
  156. }
  157. }
  158. }
  159. H.set('posts', JSON.stringify(posts));
  160. $sync.innerText = 'Synced.';
  161. }
  162. } else {
  163. // TODO: show error visually (option to retry)
  164. console.error("Well that didn't work at all!");
  165. $sync.className = '';
  166. $sync.innerText = 'Sync...';
  167. }
  168. }
  169. };
  170. http.send(JSON.stringify(params));
  171. });
  172. }
  173. // bind publish action
  174. $publish.addEventListener('click', function(e) {
  175. e.preventDefault();
  176. publish($content.value, fontRadios.value);
  177. });
  178. $content.addEventListener('keydown', function(e){
  179. if (e.ctrlKey && e.keyCode == 13) {
  180. e.preventDefault();
  181. publish($content.value, fontRadios.value);
  182. }
  183. });
  184. // bind URL select-all action
  185. $url.addEventListener('focus', function(e) {
  186. e.preventDefault();
  187. this.select();
  188. });
  189. // load font setting
  190. H.load(fontRadios, 'font');
  191. $content.className = fontRadios.value;
  192. setPublishText(fontRadios.value, false);
  193. // bind font changing action
  194. for(var i = 0; i < fontRadios.length; i++) {
  195. fontRadios[i].onclick = function() {
  196. $content.className = this.value;
  197. setPublishText(this.value, false);
  198. H.save(fontRadios, 'font');
  199. };
  200. }
  201. var handleRegUser = function() {
  202. var http = new XMLHttpRequest();
  203. http.open("GET", "https://write.as/api/me/", true);
  204. http.onreadystatechange = function() {
  205. if (http.readyState == 4) {
  206. data = JSON.parse(http.responseText);
  207. data = data.data;
  208. if (typeof data.username !== 'undefined' && data.username != "") {
  209. var $accTools = document.getElementById("account-tools")
  210. $accTools.style.display = 'block';
  211. var posts = JSON.parse(H.get('posts', '[]'));
  212. if (posts.length > 0) {
  213. document.getElementById('sync').style.display = 'inline';
  214. } else {
  215. document.getElementById('sync').style.display = 'none';
  216. }
  217. //document.getElementById("sync-count").innerText = posts.length + " post" + (posts.length==1?'':'s');
  218. document.getElementById("username").innerText = data.username;
  219. }
  220. }
  221. }
  222. http.send();
  223. }
  224. handleRegUser();
  225. if (H.get('updatedPostsMeta', '') == '') {
  226. // Add metadata used by Pad to all saved posts
  227. var addPostMetaData = function() {
  228. console.log('Adding post meta data...');
  229. var fetch = function(id, token, callback) {
  230. var http = new XMLHttpRequest();
  231. http.open("GET", "https://write.as/api/" + id + "?created=1&t=" + token, true);
  232. http.onreadystatechange = function() {
  233. if (http.readyState == 4) {
  234. callback(http.responseText, http.status);
  235. }
  236. }
  237. http.send();
  238. }
  239. var posts = JSON.parse(H.get('posts', '[]'));
  240. var migratedPosts = [];
  241. var failedPosts = [];
  242. if (posts.length > 0) {
  243. var i = 0;
  244. var updateMeta = function(content, status) {
  245. if (status == 200) {
  246. data = content.split("\n\n");
  247. created = data.splice(0, 1);
  248. migratedPosts.push(H.createPost(posts[i].id, posts[i].token, data.join("\n\n"), created));
  249. } else {
  250. posts[i].reason = status;
  251. failedPosts.push(posts[i]);
  252. }
  253. i++;
  254. if (i < posts.length) {
  255. fetch(posts[i].id, posts[i].token, updateMeta);
  256. } else {
  257. console.log('Finished! Success: ' + migratedPosts.length + '. Fail: ' + failedPosts.length);
  258. if (failedPosts.length > 0) {
  259. H.set('failedMigrationPosts', JSON.stringify(failedPosts));
  260. }
  261. H.set('posts', JSON.stringify(migratedPosts));
  262. H.set('updatedPostsMeta', 'yes');
  263. }
  264. };
  265. fetch(posts[i].id, posts[i].token, updateMeta);
  266. } else {
  267. H.set('updatedPostsMeta', 'yes');
  268. }
  269. };
  270. addPostMetaData();
  271. }
  272. });