Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.16 KB | None | 0 0
  1. // ==UserScript==
  2. // @name save_race_in_blog
  3. // @namespace klavogonki
  4. // @version 1.1.4
  5. // @description добавляет кнопку для сохранения результата любого заезда в бортжурнале
  6. // @include http://klavogonki.ru/g/*
  7. // @author Lexin13, agile
  8. // ==/UserScript==
  9.  
  10. function saveRaceInBlog () {
  11. var link = document.querySelector('.dropmenu a');
  12. if (!link) {
  13. throw new Error('.dropmenu a element not found.');
  14. }
  15.  
  16. var userId = parseInt(link.href.match(/\/u\/#\/(\d+)/)[1]);
  17.  
  18. function checkJSON (response) {
  19. try {
  20. var json = JSON.parse(response);
  21. if (!('players' in json)) {
  22. return false;
  23. }
  24.  
  25. for (var i = 0; i < json.players.length; i++) {
  26. if ('record' in json.players[i] && json.players[i].record.user === userId) {
  27. return json.players[i].record.id;
  28. }
  29. }
  30.  
  31. return false;
  32. } catch (e) {
  33. return false;
  34. }
  35. }
  36.  
  37. function saveResult (result) {
  38. var gameTypes = {
  39. normal: 'Oбычный',
  40. abra: 'Абракадабра',
  41. referats: 'Яндекс.Рефераты',
  42. noerror: 'Безошибочный',
  43. marathon: 'Марафон',
  44. chars: 'Буквы',
  45. digits: 'Цифры',
  46. sprint: 'Спринт',
  47. };
  48.  
  49. var text = "";// = '`#`' + result.id + ' | ';
  50. if (result.gameType === 'voc') {
  51. text += '«[' + result.vocName + '](/vocs/' + result.vocId + '/ "Перейти на страницу словаря")»: ' + ' | *' + document.getElementById("complexity").innerText + '* | ';
  52. } else {
  53. text += '**' + gameTypes[result.gameType] + '** | *' + document.getElementById("complexity").innerText + '* | ';
  54. }
  55.  
  56. text += result.stats.speed + '&nbsp;зн/мин | ' +
  57. result.stats.errors.replace(')', '&#41;') + '\n\n';// | ' +
  58. //result.stats.time + '\n\n';
  59.  
  60. var typedMarked = result.typedHtml
  61. .replace(/<span class="error">|<\/span>/g, '**')
  62. .replace(/<s class="error">/g, '~~**')
  63. .replace(/<\/s>/g, '**~~');
  64.  
  65. text += '> ' + typedMarked;
  66.  
  67. //if (confirm('Добавить запись в бортжурнал?')) {
  68. var xhr = new XMLHttpRequest();
  69. xhr.open('POST', '/api/profile/add-journal-post');
  70. xhr.onload = function () {
  71. if (this.status !== 200) {
  72. throw new Error('Something went wrong.');
  73. }
  74.  
  75. alert('Запись успешно добавлена.');
  76. };
  77. xhr.send(JSON.stringify({
  78. userId: userId,
  79. text: text,
  80. hidden: false,
  81. }));
  82. }
  83. //}
  84.  
  85. function init (resultId) {
  86. var container = document.createElement('div');
  87. container.style.fontSize = '10pt';
  88. var link = document.createElement('a');
  89. link.style.color = '#ff3855';
  90. link.textContent = 'Сохранить в бортжурнале';
  91.  
  92. var typed = document.querySelector('#errors_text p');
  93. if (!typed) {
  94. throw new Error('#errors_text p element not found.');
  95. }
  96.  
  97. var statsContainer = document.querySelector('.player.you .stats');
  98. if (!statsContainer) {
  99. throw new Error('.player.you .stats element not found.');
  100. }
  101.  
  102. var matches = statsContainer.textContent.match(/(\d{2}:\d{2}\.\d)(\d+) зн\/мин(\d+ ошиб\S+ \([\d,%]+\))/);
  103. if (!matches) {
  104. throw new Error('result stats were not parsed.');
  105. }
  106.  
  107. var span = document.querySelector('#gamedesc span');
  108. if (!span) {
  109. throw new Error('#gamedesc span element not found.');
  110. }
  111.  
  112. var gameType = span.className.split('-').pop();
  113. var vocName = gameType === 'voc' ? span.textContent.replace(/[«»]/g, '') : '';
  114. var vocId = gameType === 'voc' ? parseInt(span.querySelector('a').href.match(/vocs\/(\d+)/)[1]) : '';
  115.  
  116. var stats = {
  117. time: matches[1],
  118. speed: matches[2],
  119. errors: matches[3],
  120. };
  121.  
  122. var resultData = {
  123. id: resultId,
  124. stats: stats,
  125. typedHtml: typed.innerHTML,
  126. gameType: gameType,
  127. vocName: vocName,
  128. vocId: vocId,
  129. };
  130.  
  131. link.addEventListener('click', saveResult.bind(null, resultData));
  132. container.appendChild(link);
  133.  
  134. var again = document.getElementById('again');
  135. if (!again) {
  136. throw new Error('#again element not found.');
  137. }
  138.  
  139. var cell = again.querySelector('td');
  140. if (cell) {
  141. container.style.float = 'left';
  142. again.insertBefore(container, again.firstChild);
  143. } else {
  144. again.parentNode.appendChild(container);
  145. }
  146. }
  147.  
  148. // Saving the original prototype method:
  149. var proxied = window.XMLHttpRequest.prototype.send;
  150.  
  151. window.XMLHttpRequest.prototype.send = function () {
  152. this.addEventListener('load', function () {
  153. var resultId = checkJSON(this.responseText);
  154. if (resultId) {
  155. init(resultId);
  156. }
  157. }.bind(this));
  158. return proxied.apply(this, [].slice.call(arguments));
  159. };
  160. }
  161.  
  162. var script = document.createElement('script');
  163. script.textContent = '(' + saveRaceInBlog.toString() + ')();';
  164. document.body.appendChild(script);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement