TTV Auto Upload

Công cụ đăng chương hiện đại cho Tàng Thư Viện với UI/UX được tối ưu

当前为 2025-03-08 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name TTV Auto Upload
  3. // @namespace http://tampermonkey.net/
  4. // @version 6.0
  5. // @description Công cụ đăng chương hiện đại cho Tàng Thư Viện với UI/UX được tối ưu
  6. // @author HA
  7. // @match https://tangthuvien.net/dang-chuong/story/*
  8. // @match https://tangthuvien.net/danh-sach-chuong/story/*
  9. // @grant GM_addStyle
  10. // @grant GM_setValue
  11. // @grant GM_getValue
  12. // @required https://code.jquery.com/jquery-3.2.1.min.js
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17. if (window.location.href.includes('/danh-sach-chuong/story/')) {
  18. const storyId = window.location.pathname.split('/').pop();
  19. setTimeout(() => {
  20. window.location.href = `https://tangthuvien.net/dang-chuong/story/${storyId}`;
  21. }, 3000);
  22. return;
  23. }
  24.  
  25. const HEADER_SIGN = "";
  26. const FOOTER_SIGN = "";
  27. const MAX_CHAPTER_POST = 10;
  28. GM_addStyle(`
  29. /* Vị trí và giao diện của công cụ đăng nhanh */
  30. #modern-uploader {
  31. background-color: white;
  32. padding: 20px;
  33. border-radius: 10px;
  34. box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  35. position: fixed;
  36. right: 20px;
  37. top: 50%;
  38. transform: translateY(-50%);
  39. width: 400px;
  40. max-height: 90vh;
  41. overflow-y: auto;
  42. z-index: 1000;
  43. }
  44. @keyframes shortChapterBlink {
  45. 0% { background-color: rgba(255, 0, 0, 0.1); }
  46. 50% { background-color: rgba(255, 0, 0, 0.2); }
  47. 100% { background-color: rgba(255, 0, 0, 0.1); }
  48. }
  49. textarea[name^="introduce"] {
  50. transition: all 0.3s ease;
  51. }
  52. textarea[name^="introduce"].short-chapter {
  53. animation: shortChapterBlink 1s infinite;
  54. border: 2px solid #ff0000 !important;
  55. background-color: rgba(255, 0, 0, 0.1) !important;
  56. }
  57. .chapter-character-count {
  58. text-align: right;
  59. font-size: 12px;
  60. margin-top: 5px;
  61. color: #666;
  62. }
  63. .short-chapters-warning {
  64. color: #ff0000;
  65. font-weight: bold;
  66. animation: shortChapterBlink 1s infinite;
  67. }
  68.  
  69. .button-container {
  70. display: flex;
  71. justify-content: space-between;
  72. align-items: center;
  73. gap: 15px;
  74. margin-top: 15px;
  75. }
  76. #modern-uploader .btn {
  77. padding: 10px 20px;
  78. border-radius: 6px;
  79. cursor: pointer;
  80. font-weight: 600;
  81. font-size: 14px;
  82. transition: all 0.2s ease;
  83. }
  84. #modern-uploader .form-control {
  85. width: 100%;
  86. padding: 15px;
  87. border: 1px solid #ddd;
  88. border-radius: 8px;
  89. margin-bottom: 15px;
  90. font-size: 16px;
  91. transition: border-color 0.2s ease;
  92. }
  93. #modern-uploader .form-control:focus {
  94. border-color: #4285f4;
  95. outline: none;
  96. }
  97. `);
  98. function showNotification(message, type) {
  99. jQuery('#modern-uploader .notification-container').remove();
  100. const container = jQuery("<div>", {
  101. class: "notification-container",
  102. css: {
  103. width: "100%",
  104. padding: "10px 0",
  105. marginTop: "10px",
  106. textAlign: "left",
  107. borderTop: "1px solid rgba(0,0,0,0.1)"
  108. }
  109. });
  110. const notification = jQuery("<div>", {
  111. class: `notification-${type}`,
  112. css: {
  113. backgroundColor: "#e8f5e9",
  114. color: "#000000",
  115. padding: "10px 15px",
  116. borderRadius: "8px",
  117. fontSize: "14px",
  118. fontWeight: "500",
  119. boxShadow: "0 4px 10px rgba(0,0,0,0.15)",
  120. display: "inline-block",
  121. maxWidth: "90%",
  122. margin: "0",
  123. wordBreak: "break-word",
  124. border: "1px solid #81c784"
  125. }
  126. });
  127. const lines = message.split('\n');
  128. lines.forEach((line, index) => {
  129. notification.append(jQuery("<div>").html(line));
  130. });
  131. container.append(notification);
  132. jQuery("#modern-uploader .button-container").after(container);
  133. notification.fadeIn(300);
  134. }
  135. function createChapterHTML(chapNum) {
  136. const chap_vol = parseInt(jQuery('.chap_vol').val()) || 1;
  137. const chap_vol_name = jQuery('.chap_vol_name').val() || '';
  138. return `
  139. <div data-gen="MK_GEN" id="COUNT_CHAP_${chapNum}_MK">
  140. <div class="col-xs-12 form-group"></div>
  141. <div class="form-group">
  142. <label class="col-sm-2" for="chap_stt">STT</label>
  143. <div class="col-sm-8">
  144. <input class="form-control" required name="chap_stt[${chapNum}]" value="${dăngnhanhTTV.STATE.CHAP_STT}" placeholder="Số thứ tự của chương" type="text"/>
  145. </div>
  146. </div>
  147. <div class="form-group">
  148. <label class="col-sm-2" for="chap_number">Chương thứ..</label>
  149. <div class="col-sm-8">
  150. <input value="${dăngnhanhTTV.STATE.CHAP_SERIAL}" required class="form-control" name="chap_number[${chapNum}]" placeholder="Chương thứ.. (1,2,3..)" type="text"/>
  151. </div>
  152. </div>
  153. <div class="form-group">
  154. <label class="col-sm-2" for="chap_name">Quyn số</label>
  155. <div class="col-sm-8">
  156. <input class="form-control" name="vol[${chapNum}]" placeholder="Quyển số" type="number" value="${chap_vol}" required/>
  157. </div>
  158. </div>
  159. <div class="form-group">
  160. <label class="col-sm-2" for="chap_name">Tên quyn</label>
  161. <div class="col-sm-8">
  162. <input class="form-control chap_vol_name" name="vol_name[${chapNum}]" placeholder="Tên quyển" type="text" value="${chap_vol_name}" />
  163. </div>
  164. </div>
  165. <div class="form-group">
  166. <label class="col-sm-2" for="chap_name">Tên chương</label>
  167. <div class="col-sm-8">
  168. <input required class="form-control" name="chap_name[${chapNum}]" placeholder="Tên chương" type="text"/>
  169. </div>
  170. </div>
  171. <div class="form-group">
  172. <label class="col-sm-2" for="introduce">Ni dung</label>
  173. <div class="col-sm-8">
  174. <textarea maxlength="75000" style="color:#000;font-weight: 400;" required class="form-control" name="introduce[${chapNum}]" rows="20" placeholder="Nội dung" type="text"></textarea>
  175. <div class="chapter-character-count"></div>
  176. </div>
  177. </div>
  178. <div class="form-group">
  179. <label class="col-sm-2" for="adv">Qung cáo</label>
  180. <div class="col-sm-8">
  181. <textarea maxlength="1000" class="form-control" name="adv[${chapNum}]" placeholder="Quảng cáo" type="text"></textarea>
  182. </div>
  183. </div>
  184. </div>`;
  185. }
  186. function setupCharacterCounter() {
  187. jQuery(document).on("input", "[name^=introduce]", function() {
  188. const text = jQuery(this).val();
  189. const charCount = text.length;
  190. let charCountElement = jQuery(this).next('.chapter-character-count');
  191. if (charCountElement.length === 0) {
  192. charCountElement = jQuery('<div class="chapter-character-count"></div>');
  193. jQuery(this).after(charCountElement);
  194. }
  195. if(charCount < 3000) {
  196. jQuery(this).addClass('short-chapter');
  197. charCountElement.html(`<span class="short-chapters-warning">${charCount.toLocaleString()}/40.000 ký tự</span>`);
  198. } else {
  199. jQuery(this).removeClass('short-chapter');
  200. if(charCount > 40000) {
  201. charCountElement.html(`<span style="color: #fbbc05;">${charCount.toLocaleString()}/40.000 ký tự</span>`);
  202. } else {
  203. charCountElement.html(`<span style="color: #34a853;">${charCount.toLocaleString()}/40.000 ký tự</span>`);
  204. }
  205. }
  206. });
  207. }
  208. function validateChapterLengths() {
  209. let hasError = false;
  210. jQuery('form[name="postChapForm"] .chapter-detail').each(function() {
  211. const form = this;
  212. const contentTextarea = form.querySelector('textarea[name^="introduce"]');
  213. const content = contentTextarea.value;
  214. if (content.length < 3000) {
  215. jQuery(contentTextarea).addClass('short-chapter');
  216. let warningIcon = form.querySelector('.warning-icon');
  217. if (!warningIcon) {
  218. warningIcon = document.createElement('div');
  219. warningIcon.className = 'warning-icon';
  220. warningIcon.innerHTML = '⚠️';
  221. contentTextarea.parentNode.appendChild(warningIcon);
  222. }
  223. hasError = true;
  224. } else {
  225. jQuery(contentTextarea).removeClass('short-chapter');
  226. const warningIcon = form.querySelector('.warning-icon');
  227. if (warningIcon) {
  228. warningIcon.remove();
  229. }
  230. }
  231. });
  232. return !hasError;
  233. }
  234. const dăngnhanhTTV = {
  235. STATE: {
  236. CHAP_NUMBER: 1,
  237. CHAP_STT: 1,
  238. CHAP_SERIAL: 1,
  239. CHAP_NUMBER_ORIGINAL: 1,
  240. CHAP_STT_ORIGINAL: 1,
  241. CHAP_SERIAL_ORIGINAL: 1,
  242. AUTO_POST: false,
  243. TOTAL_CHAPTERS: 0,
  244. POSTED_CHAPTERS: 0
  245. },
  246. ELEMENTS: {
  247. qpContent: null,
  248. qpButtonSubmit: null,
  249. qpButtonRemoveEmpty: null,
  250. qpButtonReset: null // Added element
  251. },
  252. init: function() {
  253. try {
  254. console.log('[TTV-DEBUG] Script bắt đầu khởi tạo...');
  255. console.log('[TTV-DEBUG] Phiên bản script: 3.0');
  256. this.initializeChapterValues();
  257. console.log('[TTV-DEBUG] Đã khởi tạo giá trị chương');
  258.  
  259. // Khôi phục trạng thái tự động đăng
  260. this.loadAutoPostState();
  261. console.log('[TTV-DEBUG] Đã khôi phục trạng thái tự động đăng');
  262.  
  263. this.createInterface();
  264. console.log('[TTV-DEBUG] Đã tạo giao diện');
  265. this.cacheElements();
  266. console.log('[TTV-DEBUG] Đã cache các elements');
  267. this.registerEvents();
  268. console.log('[TTV-DEBUG] Đã đăng ký các events');
  269. console.log('[TTV-DEBUG] Script đã khởi động thành công');
  270. showNotification('Công cụ đã chạy', 'success');
  271.  
  272. // Cập nhật hiển thị nút tự động đăng
  273. if (this.STATE.AUTO_POST) {
  274. this.ELEMENTS.qpButtonAutoPost.text(`🔄 (ON) ${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS}`);
  275. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-warning').addClass('btn-info');
  276. }
  277.  
  278. // Khôi phục trạng thái chế độ tự động đăng
  279. const isAutoMode = localStorage.getItem('TTV_AUTO_MODE') === 'true';
  280. if (isAutoMode) {
  281. this.ELEMENTS.qpOptionLoop.prop('checked', true);
  282. this.toggleAutoMode(); // Áp dụng giao diện theo chế độ
  283. }
  284. } catch (e) {
  285. console.error('[TTV-ERROR] Lỗi khởi tạo:', e);
  286. showNotification('Có lỗi khi khởi tạo Script', 'error');
  287. }
  288. },
  289.  
  290. loadAutoPostState: function() {
  291. // Khôi phục trạng thái tự động đăng từ localStorage
  292. const autoPost = localStorage.getItem('TTV_AUTO_POST') === 'true';
  293. this.STATE.AUTO_POST = autoPost;
  294.  
  295. if (autoPost) {
  296. this.STATE.TOTAL_CHAPTERS = parseInt(localStorage.getItem('TTV_TOTAL_CHAPTERS') || '0');
  297. this.STATE.POSTED_CHAPTERS = parseInt(localStorage.getItem('TTV_POSTED_CHAPTERS') || '0');
  298.  
  299. console.log(`[TTV-DEBUG] Khôi phc t động đăng: ${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS}`);
  300. }
  301. },
  302. createInterface: function() {
  303. const html = `
  304. <div id="modern-uploader">
  305. <div class="text-center mb-4">
  306. <h3 style="color: #4285f4; margin-bottom: 15px; font-weight: 700; font-size: 18px;">📝 CÔNG C ĐĂNG NHANH</h3>
  307. </div>
  308. <div class="form-group">
  309. <textarea placeholder="Nội dung truyện (Dán vào đây để tự động tách chương)" id="qpContent" class="form-control" rows="5"></textarea>
  310. </div>
  311. <div class="text-center mb-3">
  312. <label style="color: #bef385;"><input type="checkbox" id="qpOptionLoop" class="form-control" style="height:10px;width: 10px;display: inline-block;">Chế độ t động</label>
  313. </div>
  314. <div class="button-container" style="display: flex; justify-content: center; gap: 15px;">
  315. <button class="btn btn-primary" id="qpButtonPaste">📋 Paste</button>
  316. <button class="btn btn-success" id="qpButtonSubmit">📤 Đăng chương</button>
  317. <button class="btn btn-danger" id="qpButtonRemoveEmpty" style="display: none;">Ẩn chương trng</button>
  318. <button class="btn btn-warning" id="qpButtonAutoPost" style="display: none;">🔄 (OFF)</button>
  319. <button class="btn btn-secondary" id="qpButtonReset" style="display: none;">🔁 Reset</button>
  320. </div>
  321. <div class="notification-container"></div>
  322. </div>`;
  323.  
  324. jQuery(".list-in-user").before(html);
  325. },
  326. initializeChapterValues: function() {
  327. try {
  328. const chap_number = parseInt(jQuery('#chap_number').val());
  329. let chap_stt = parseInt(jQuery('.chap_stt1').val());
  330. let chap_serial = parseInt(jQuery('.chap_serial').val());
  331.  
  332. if (parseInt(jQuery('#chap_stt').val()) > chap_stt) {
  333. chap_stt = parseInt(jQuery('#chap_stt').val());
  334. }
  335. if (parseInt(jQuery('#chap_serial').val()) > chap_serial) {
  336. chap_serial = parseInt(jQuery('#chap_serial').val());
  337. }
  338.  
  339. this.STATE.CHAP_NUMBER = this.STATE.CHAP_NUMBER_ORIGINAL = chap_number || 1;
  340. this.STATE.CHAP_STT = this.STATE.CHAP_STT_ORIGINAL = chap_stt || 1;
  341. this.STATE.CHAP_SERIAL = this.STATE.CHAP_SERIAL_ORIGINAL = chap_serial || 1;
  342. } catch (e) {
  343. console.error("Error initializing chapter values:", e);
  344. }
  345. },
  346. cacheElements: function() {
  347. this.ELEMENTS.qpContent = jQuery("#qpContent");
  348. this.ELEMENTS.qpButtonSubmit = jQuery("#qpButtonSubmit");
  349. this.ELEMENTS.qpButtonRemoveEmpty = jQuery("#qpButtonRemoveEmpty");
  350. this.ELEMENTS.qpButtonPaste = jQuery("#qpButtonPaste");
  351. this.ELEMENTS.qpButtonAutoPost = jQuery("#qpButtonAutoPost");
  352. this.ELEMENTS.qpButtonReset = jQuery("#qpButtonReset"); // Added element caching
  353. this.ELEMENTS.qpOptionLoop = jQuery("#qpOptionLoop"); // Added checkbox caching
  354. },
  355. registerEvents: function() {
  356. this.ELEMENTS.qpContent.on("paste", this.handlePaste.bind(this));
  357. this.ELEMENTS.qpButtonRemoveEmpty.on('click', this.removeEmptyChapters.bind(this));
  358. this.ELEMENTS.qpButtonSubmit.on('click', this.submitChapters.bind(this));
  359. this.ELEMENTS.qpButtonPaste.on('click', this.handlePasteButton.bind(this));
  360. this.ELEMENTS.qpButtonAutoPost.on('click', this.toggleAutoPost.bind(this));
  361. this.ELEMENTS.qpButtonReset.on('click', this.resetAutoPost.bind(this)); //Added event listener
  362. this.ELEMENTS.qpOptionLoop.on('change', this.toggleAutoMode.bind(this)); // Added checkbox event
  363. setupCharacterCounter();
  364.  
  365. // Kiểm tra và bắt đầu tự động đăng nếu đã bật
  366. if (window.location.href.includes('/dang-chuong/story/')) {
  367. setTimeout(() => {
  368. if (this.STATE.AUTO_POST && this.STATE.POSTED_CHAPTERS < this.STATE.TOTAL_CHAPTERS) {
  369. this.runAutoPostSequence();
  370. }
  371. }, 2000);
  372. }
  373. },
  374. handlePasteButton: function() {
  375. this.showLoading();
  376. navigator.clipboard.readText()
  377. .then(text => {
  378. this.ELEMENTS.qpContent.val(text);
  379. setTimeout(() => {
  380. this.performAction();
  381. this.hideLoading();
  382. }, 100);
  383. })
  384. .catch(err => {
  385. console.error('Không thể đọc dữ liệu từ clipboard:', err);
  386. this.hideLoading();
  387. showNotification('Không thể truy cập clipboard. Vui lòng dán trực tiếp vào ô nội dung.', 'error');
  388. });
  389. },
  390. handlePaste: function(e) {
  391. e.preventDefault();
  392. this.ELEMENTS.qpContent.val("");
  393. this.showLoading();
  394. const pastedText = e.originalEvent.clipboardData.getData('text');
  395. this.ELEMENTS.qpContent.val(pastedText);
  396. setTimeout(() => {
  397. this.performAction();
  398. this.hideLoading();
  399. }, 100);
  400. },
  401. performAction: function() {
  402. try {
  403. console.log("Starting performAction");
  404. var text = this.ELEMENTS.qpContent.val();
  405.  
  406. if (!text) {
  407. showNotification('Không có nội dung để tách chương', 'error');
  408. return 0;
  409. }
  410. var debugOutput = [];
  411. var chapters = [];
  412. var lines = text.split('\n');
  413. var currentChapter = [];
  414. var lastTitle = null;
  415. debugOutput.push("=== Processing Text ===");
  416. debugOutput.push(`Total lines: ${lines.length}`);
  417. debugOutput.push("=== Line Analysis ===");
  418. function visualizeWhitespace(str) {
  419. return str.split('').map(c => {
  420. if (c === '\t') return '\\t';
  421. if (c === ' ') return '·';
  422. if (c === '\n') return '\\n';
  423. return c;
  424. }).join('');
  425. }
  426. for (let i = 0; i < lines.length; i++) {
  427. let line = lines[i];
  428. let isChapterTitle = /^\t[Cc]hương\s*\d+\s*:/.test(line) || /^\s{4,}[Cc]hương\s*\d+\s*:/.test(line);
  429. debugOutput.push(`Line ${i}: ${visualizeWhitespace(line.substring(0, 50))}${line.length > 50 ? '...' : ''}`);
  430. debugOutput.push(` Is chapter: ${isChapterTitle}`);
  431.  
  432. if (isChapterTitle) {
  433. if (currentChapter.length > 0) {
  434. if (line !== lastTitle) {
  435. chapters.push(currentChapter.join('\n'));
  436. currentChapter = [line];
  437. lastTitle = line;
  438. debugOutput.push(` -> New chapter started`);
  439. } else {
  440. debugOutput.push(` -> Skipped duplicate title`);
  441. }
  442. } else {
  443. currentChapter = [line];
  444. lastTitle = line;
  445. debugOutput.push(` -> First chapter started`);
  446. }
  447. } else if (currentChapter.length > 0) {
  448. currentChapter.push(line);
  449. }
  450. }
  451. if (currentChapter.length > 0) {
  452. chapters.push(currentChapter.join('\n'));
  453. debugOutput.push("-> Added final chapter");
  454. }
  455. debugOutput.push("=== Results ===");
  456. debugOutput.push(`Found ${chapters.length} chapters`);
  457. const processedChapters = [];
  458. for (let i = 0; i < chapters.length; i++) {
  459. const chapterLines = chapters[i].split('\n');
  460. const title = chapterLines.shift().trim();
  461. const chapterText = chapterLines.join('\n');
  462. const charCount = chapterText.length;
  463. debugOutput.push(`Chapter ${i+1} character count: ${charCount}`);
  464. if (charCount > 40000) {
  465. const parts = Math.ceil(charCount / 40000);
  466. debugOutput.push(`Splitting into ${parts} parts`);
  467. const charsPerPart = Math.ceil(charCount / parts);
  468. debugOutput.push(`Characters per part: ~${charsPerPart}`);
  469. let currentText = chapterText;
  470. let totalProcessed = 0;
  471. for (let part = 0; part < parts; part++) {
  472. const isLastPart = part === parts - 1;
  473. const targetSize = isLastPart ? currentText.length : charsPerPart;
  474. let endPos = Math.min(targetSize, currentText.length);
  475. if (!isLastPart && endPos < currentText.length) {
  476. const nextParagraph = currentText.indexOf('\n\n', endPos - 500);
  477. if (nextParagraph !== -1 && nextParagraph < endPos + 500) {
  478. endPos = nextParagraph + 2;
  479. } else {
  480. const sentenceEnd = Math.max(
  481. currentText.lastIndexOf('. ', endPos),
  482. currentText.lastIndexOf('! ', endPos),
  483. currentText.lastIndexOf('? ', endPos)
  484. );
  485. if (sentenceEnd !== -1 && sentenceEnd > endPos - 500) {
  486. endPos = sentenceEnd + 2;
  487. }
  488. }
  489. }
  490. const partContent = currentText.substring(0, endPos);
  491. totalProcessed += partContent.length;
  492. currentText = currentText.substring(endPos);
  493. let chapterTitle = title;
  494. if (title.includes(':')) {
  495. chapterTitle = title.substring(title.indexOf(':') + 1).trim();
  496. }
  497. let newTitle = `${title} (Phn ${part+1}/${parts})`;
  498. processedChapters.push(newTitle + '\n' + partContent);
  499. debugOutput.push(`Part ${part+1}: ${partContent.length} chars`);
  500. }
  501. debugOutput.push(`Total processed: ${totalProcessed}/${charCount} chars`);
  502. } else {
  503. processedChapters.push(chapters[i]);
  504. }
  505. }
  506. debugOutput.push(`After processing: ${processedChapters.length} chapters`);
  507. const chaptersToFill = processedChapters.slice(0, MAX_CHAPTER_POST);
  508. const remainingChapters = processedChapters.slice(MAX_CHAPTER_POST);
  509. var titles = jQuery("input[name^='chap_name']");
  510. var contents = jQuery("textarea[name^='introduce']");
  511. var advs = jQuery("textarea[name^='adv']");
  512. debugOutput.push(`Forms found: ${titles.length}`);
  513. if (processedChapters.length === 0) {
  514. showNotification('Không tìm thấy chương nào', 'error');
  515. jQuery('#debug-output').text(debugOutput.join('\n'));
  516. return;
  517. }
  518. if (remainingChapters.length > 0) {
  519. debugOutput.push(`${remainingChapters.length} chapters will be copied to clipboard`);
  520. }
  521. const neededForms = chaptersToFill.length - titles.length;
  522. if (neededForms > 0 && titles.length < MAX_CHAPTER_POST) {
  523. debugOutput.push(`Need to add ${neededForms} more forms`);
  524. for (let i = 0; i < neededForms && (titles.length + i) < MAX_CHAPTER_POST; i++) {
  525. this.addNewChapter();
  526. }
  527. titles = jQuery("input[name^='chap_name']");
  528. contents = jQuery("textarea[name^='introduce']");
  529. advs = jQuery("textarea[name^='adv']");
  530. }
  531. debugOutput.push(`Filling ${chaptersToFill.length} chapters into forms`);
  532. jQuery.each(titles, function(k, v) {
  533. if (k < chaptersToFill.length) {
  534. var content = chaptersToFill[k].split('\n');
  535. var title = content.shift().trim();
  536. var chapterTitle = title;
  537. if (title.includes(':')) {
  538. chapterTitle = title.substring(title.indexOf(':') + 1).trim();
  539. }
  540. debugOutput.push(`\nFilling chapter ${k + 1}:`);
  541. debugOutput.push(`Original title: ${title}`);
  542. debugOutput.push(`Extracted title: ${chapterTitle}`);
  543. debugOutput.push(`Content length: ${content.length} lines`);
  544. if (!chapterTitle || chapterTitle.trim() === '') {
  545. chapterTitle = "Vô đề";
  546. debugOutput.push(`Empty title detected, using default: ${chapterTitle}`);
  547. }
  548. titles[k].value = chapterTitle;
  549. contents[k].value = HEADER_SIGN + "\r\n" + content.join('\n') + "\r\n" + FOOTER_SIGN;
  550. if (advs[k]) advs[k].value = "";
  551. jQuery(contents[k]).trigger('input');
  552. }
  553. });
  554. if (remainingChapters.length > 0) {
  555. try {
  556. const clipboardContent = remainingChapters.map(chap => {
  557. const lines = chap.trim().split('\n');
  558. if (lines.length > 0) {
  559. if (!lines[0].startsWith('\t')) {
  560. lines[0] = '\t' + lines[0];
  561. }
  562. }
  563. return lines.join('\n');
  564. }).join('\n\n---CHAPTER_SEPARATOR---\n\n');
  565. let splitChapters = 0;
  566. let shortChapters = 0;
  567. let shortChapterDetails = [];
  568. let longChapterDetails = [];
  569. for (let i = 0; i < chapters.length; i++) {
  570. const chapterLines = chapters[i].split('\n');
  571. const title = chapterLines.shift().trim();
  572. const chapterText = chapterLines.join('\n');
  573. if (chapterText.length > 40000) {
  574. splitChapters++;
  575. const partsCount = Math.ceil(chapterText.length / 40000);
  576. longChapterDetails.push({
  577. title: title,
  578. parts: partsCount
  579. });
  580. }
  581. if (chapterText.length < 3000) {
  582. shortChapters++;
  583. shortChapterDetails.push({
  584. title: title,
  585. length: chapterText.length
  586. });
  587. }
  588. }
  589. const splittedChaptersCount = processedChapters.length - (chapters.length - splitChapters);
  590. let message = '';
  591. message = message.concat(`📝Đã x lý ${processedChapters.length} Chương\n`);
  592. message = message.concat(`📝Đã nhp ${Math.min(processedChapters.length, MAX_CHAPTER_POST)} Chương\n`);
  593.  
  594. if (remainingChapters.length > 0) {
  595. message = message.concat(`📋Đã lưu li ${remainingChapters.length} Chương\n`);
  596. }
  597. if (splitChapters > 0) {
  598. message = message.concat(`📑Có ${splitChapters} Chương đã chia thành ${splittedChaptersCount} Chương\n`);
  599. longChapterDetails.forEach(chapter => {
  600. let chapterName = chapter.title;
  601. if (chapterName.includes(':')) {
  602. chapterName = chapterName.trim();
  603. }
  604. message = message.concat(` - ${chapterName}: ${chapter.parts} Chương\n`);
  605. });
  606. }
  607. if (shortChapters > 0) {
  608. message = message.concat(`⚠️<span class="short-chapters-warning">Có ${shortChapters} chương dưới 3000 ký tự</span>\n`);
  609. shortChapterDetails.forEach(chapter => {
  610. let chapterName = chapter.title;
  611. if (chapterName.includes(':')) {
  612. chapterName = chapterName.trim();
  613. }
  614. message = message.concat(`<span class="short-chapters-warning"> - ${chapterName}: có ${chapter.length.toLocaleString()} ký tự</span>\n`);
  615. });
  616. }
  617. if (navigator.clipboard && navigator.clipboard.writeText) {
  618. navigator.clipboard.writeText(clipboardContent)
  619. .then(() => {
  620. debugOutput.push(`📋Đã lưu li ${remainingChapters.length} Chương\n`);
  621. showNotification(message, remainingChapters.length > 0 ? 'warning' : 'success');
  622. })
  623. .catch(err => {
  624. throw err;
  625. });
  626. } else {
  627. const tempTextarea = document.createElement('textarea');
  628. tempTextarea.style.position = 'fixed';
  629. tempTextarea.style.top = '0';
  630. tempTextarea.style.left = '0';
  631. tempTextarea.style.width = '2em';
  632. tempTextarea.style.height = '2em';
  633. tempTextarea.style.opacity = '0';
  634. tempTextarea.style.pointerEvents = 'none';
  635. tempTextarea.value = clipboardContent;
  636. document.body.appendChild(tempTextarea);
  637. tempTextarea.focus();
  638. tempTextarea.select();
  639. const successful = document.execCommand('copy');
  640. document.body.removeChild(tempTextarea);
  641. if (!successful) {
  642. throw new Error('Không thể sao chép vào clipboard');
  643. }
  644. debugOutput.push(`Đã sao chép ${remainingChapters.length} chương vào clipboard (execCommand)`);
  645. showNotification(message, 'success');
  646. }
  647. } catch (err) {
  648. console.error('Lỗi khi sao chép vào clipboard:', err);
  649. debugOutput.push(`Li khi sao chép vào clipboard: ${err.message}`);
  650. showNotification('Không thể sao chép vào clipboard. Vui lòng thử lại.', 'error');
  651. const manualCopyArea = document.createElement('div');
  652. manualCopyArea.style.position = 'fixed';
  653. manualCopyArea.style.top = '50%';
  654. manualCopyArea.style.left = '50%';
  655. manualCopyArea.style.transform = 'translate(-50%, -50%)';
  656. manualCopyArea.style.backgroundColor = 'white';
  657. manualCopyArea.style.padding = '20px';
  658. manualCopyArea.style.borderRadius = '8px';
  659. manualCopyArea.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1)';
  660. manualCopyArea.style.zIndex = '10000';
  661. manualCopyArea.style.maxWidth = '80%';
  662. manualCopyArea.style.maxHeight = '80%';
  663. manualCopyArea.style.overflow = 'auto';
  664. manualCopyArea.innerHTML = `
  665. <h3 style="margin-top: 0;">Sao chép th công</h3>
  666. <p>Không th sao chép t động. Vui lòng chn toàn b ni dung bên dưới và sao chép (Ctrl+C):</p>
  667. <textarea style="width: 100%; height: 300px; padding: 10px;">${clipboardContent}</textarea>
  668. <div style="text-align: right; margin-top: 10px;">
  669. <button id="closeManualCopy" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 4px; cursor: pointer;">Đóng</button>
  670. </div>
  671. `;
  672. document.body.appendChild(manualCopyArea);
  673. document.getElementById('closeManualCopy').addEventListener('click', () => {
  674. document.body.removeChild(manualCopyArea);
  675. });
  676. }
  677. }
  678. this.ELEMENTS.qpButtonSubmit.removeClass("btn-disable").addClass("btn-success");
  679. this.ELEMENTS.qpContent.val("Đã thựchiện xong");
  680. if (remainingChapters.length === 0) {
  681. let splitChapters = 0;
  682. let shortChapters = 0;
  683. let shortChapterDetails = [];
  684. let longChapterDetails = [];
  685. for (let i = 0; i < chapters.length; i++) {
  686. const chapterLines = chapters[i].split('\n');
  687. const title = chapterLines.shift().trim();
  688. const chapterText = chapterLines.join('\n');
  689. if (chapterText.length > 40000) {
  690. splitChapters++;
  691. const partsCount = Math.ceil(chapterText.length / 40000);
  692. longChapterDetails.push({
  693. title: title,
  694. parts: partsCount
  695. });
  696. }
  697. if (chapterText.length < 3000) {
  698. shortChapters++;
  699. shortChapterDetails.push({
  700. title: title,
  701. length: chapterText.length
  702. });
  703. }
  704. }
  705. const splittedChaptersCount = processedChapters.length - (chapters.length - splitChapters);
  706. let message = '';
  707. message = message.concat(`📝Đã x lý ${processedChapters.length} Chương\n`);
  708. message = message.concat(`📝Đã nhp ${Math.min(processedChapters.length, MAX_CHAPTER_POST)} Chương\n`);
  709. if (splitChapters > 0) {
  710. message = message.concat(`📑Có ${splitChapters} Chương dài chia thành ${splittedChaptersCount} Chương\n`);
  711. longChapterDetails.forEach(chapter => {
  712. let chapterName = chapter.title;
  713. if (chapterName.includes(':')) {
  714. chapterName = chapterName.trim();
  715. }
  716. message = message.concat(` - ${chapterName}: ${chapter.parts} Chương\n`);
  717. });
  718. }
  719. if (shortChapters > 0) {
  720. message = message.concat(`⚠️<span class="short-chapters-warning">Có ${shortChapters} chương dưới 3000 ký tự</span>\n`);
  721. shortChapterDetails.forEach(chapter => {
  722. let chapterName = chapter.title;
  723. if (chapterName.includes(':')) {
  724. chapterName = chapterName.trim();
  725. }
  726. message = message.concat(`<span class="short-chapters-warning"> - ${chapterName}: có ${chapter.length.toLocaleString()} ký tự</span>\n`);
  727. });
  728. }
  729. showNotification(message, 'success');
  730. }
  731. jQuery('#debug-output').text(debugOutput.join('\n'));
  732. return processedChapters.length;
  733. } catch (e) {
  734. console.error("Error in performAction:", e);
  735. showNotification('Có lỗi khi tách chương', 'error');
  736. return 0;
  737. }
  738. },
  739. removeEmptyChapters: function() {
  740. const forms = document.querySelectorAll('[data-gen="MK_GEN"]');
  741. let removed = 0;
  742.  
  743. forms.forEach(form => {
  744. const content = form.querySelector('textarea[name^="introduce"]').value.trim();
  745. if (!content) {
  746. form.remove();
  747. removed++;
  748. this.updateChapNumber(false);
  749. }
  750. });
  751. showNotification(`Đã x lý ${forms.length} chương`, 'info');
  752. },
  753. toggleAutoPost: function() {
  754. this.STATE.AUTO_POST = !this.STATE.AUTO_POST;
  755.  
  756. if (this.STATE.AUTO_POST) {
  757. // Lưu trạng thái tự động đăng vào localStorage
  758. localStorage.setItem('TTV_AUTO_POST', 'true');
  759. this.STATE.TOTAL_CHAPTERS = parseInt(prompt("Nhập tổng số lần tự động đăng:", "10")) || 0;
  760. this.STATE.POSTED_CHAPTERS = parseInt(localStorage.getItem('TTV_POSTED_CHAPTERS') || '0');
  761.  
  762. localStorage.setItem('TTV_TOTAL_CHAPTERS', this.STATE.TOTAL_CHAPTERS.toString());
  763.  
  764. this.ELEMENTS.qpButtonAutoPost.text(`🔄 (ON) ${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS}`);
  765. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-warning').addClass('btn-info');
  766.  
  767. showNotification(`Đã bt t động đăng (${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS})`, 'success');
  768.  
  769. // Bắt đầu quy trình tự động
  770. if (window.location.href.includes('/dang-chuong/story/')) {
  771. setTimeout(() => this.runAutoPostSequence(), 2000);
  772. }
  773. } else {
  774. // Tắt tự động đăng
  775. localStorage.setItem('TTV_AUTO_POST', 'false');
  776. // Reset số lần đã đăng về 0
  777. this.STATE.POSTED_CHAPTERS = 0;
  778. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  779. // Reset tổng số lần đăng về 0
  780. this.STATE.TOTAL_CHAPTERS = 0;
  781. localStorage.setItem('TTV_TOTAL_CHAPTERS', '0');
  782. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  783. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  784. showNotification('Đã tắt tự động đăng và reset số lần đăng', 'info');
  785. }
  786. },
  787.  
  788. runAutoPostSequence: function() {
  789. // Kiểm tra trước khi chạy tự động
  790. if (this.STATE.POSTED_CHAPTERS >= this.STATE.TOTAL_CHAPTERS) {
  791. // Reset trạng thái tự động nếu đã hoàn thành
  792. this.STATE.AUTO_POST = false;
  793. localStorage.setItem('TTV_AUTO_POST', 'false');
  794. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  795. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  796.  
  797. // Reset số lần đã đăng
  798. this.STATE.POSTED_CHAPTERS = 0;
  799. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  800.  
  801. showNotification(`Đã hoàn thành t động đăng ${this.STATE.TOTAL_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS} chương và đã reset s ln đăng`, 'success');
  802. return;
  803. }
  804.  
  805. if (!this.STATE.AUTO_POST) {
  806. return;
  807. }
  808.  
  809. // Tự động nhấn nút Paste sau 2 giây
  810. setTimeout(() => {
  811. if (this.STATE.AUTO_POST) {
  812. this.handlePasteButton();
  813.  
  814. // Tự động nhấn nút Đăng chương sau 3 giây
  815. setTimeout(() => {
  816. if (this.STATE.AUTO_POST) {
  817. this.submitChapters();
  818. }
  819. }, 3000);
  820. }
  821. }, 2000);
  822. },
  823.  
  824. submitChapters: function() {
  825. if (!validateChapterLengths()) {
  826. return;
  827. }
  828. this.showLoading();
  829. document.querySelector('form[name="postChapForm"] button[type="submit"]').click();
  830.  
  831. if (this.STATE.AUTO_POST) {
  832. // Cập nhật số chương đã đăng
  833. this.STATE.POSTED_CHAPTERS++;
  834. localStorage.setItem('TTV_POSTED_CHAPTERS', this.STATE.POSTED_CHAPTERS.toString());
  835.  
  836. // Kiểm tra và tắt tự động đăng nếu đã đủ số chương
  837. if (this.STATE.POSTED_CHAPTERS >= this.STATE.TOTAL_CHAPTERS) {
  838. this.STATE.AUTO_POST = false;
  839. localStorage.setItem('TTV_AUTO_POST', 'false');
  840. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  841. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  842.  
  843. // Reset số lần đã đăng
  844. this.STATE.POSTED_CHAPTERS = 0;
  845. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  846.  
  847. setTimeout(() => {
  848. showNotification(`Đã hoàn thành t động đăng ${this.STATE.TOTAL_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS} chương và đã reset s ln đăng`, 'success');
  849. }, 3000);
  850. }
  851. }
  852.  
  853. setTimeout(() => this.hideLoading(), 2000);
  854. },
  855. addNewChapter: function() {
  856. if ((this.STATE.CHAP_NUMBER + 1) <= MAX_CHAPTER_POST) {
  857. this.updateChapNumber(true);
  858. const html = createChapterHTML(this.STATE.CHAP_NUMBER);
  859. jQuery('#add-chap').before(html);
  860. setupCharacterCounter();
  861. } else {
  862. showNotification(`Ch có th đăng ti đa ${MAX_CHAPTER_POST} chương mt ln`, 'warning');
  863. }
  864. },
  865. updateChapNumber: function(isAdd) {
  866. try{
  867. if (isAdd) {
  868. let maxStt =0;
  869. let maxSerial = 0;
  870. jQuery('input[name^="chap_stt"]').each(function() {
  871. const val = parseInt(jQuery(this).val()) || 0;
  872. maxStt = Math.max(maxStt, val);
  873. });
  874. jQuery('input[name^="chap_number"]').each(function() {
  875. const val = parseInt(jQuery(this).val()) || 0;
  876. maxSerial = Math.max(maxSerial, val);
  877. });
  878. const chapStt = parseInt(jQuery('.chap_stt1').val()) || 0;
  879. const chapSerial = parseInt(jQuery('.chap_serial').val()) || 0;
  880. maxStt = Math.max(maxStt, chapStt);
  881. maxSerial = Math.max(maxSerial, chapSerial);
  882. this.STATE.CHAP_STT = maxStt + 1;
  883. this.STATE.CHAP_SERIAL = maxSerial + 1;
  884. this.STATE.CHAP_NUMBER++;
  885. } else {
  886. if (this.STATE.CHAP_NUMBER > this.STATE.CHAP_NUMBER_ORIGINAL) {
  887. this.STATE.CHAP_NUMBER--;
  888. }
  889. if (this.STATE.CHAP_STT > this.STATE.CHAP_STT_ORIGINAL) {
  890. this.STATE.CHAP_STT--;
  891. }
  892. if (this.STATE.CHAP_SERIAL > this.STATE.CHAP_SERIAL_ORIGINAL) {
  893. this.STATE.CHAP_SERIAL--;
  894. }
  895. }
  896. jQuery('#chap_number').val(this.STATE.CHAP_NUMBER);
  897. jQuery('#chap_stt').val(this.STATE.CHAP_STT);
  898. jQuery('#chap_serial').val(this.STATE.CHAP_SERIAL);
  899. jQuery('#countNumberPost').text(this.STATE.CHAP_NUMBER);
  900. } catch (e) {
  901. console.log("Lỗi: " + e);
  902. }
  903. },
  904. showLoading: function() {
  905. const loading = jQuery("<div>", {
  906. class: "loading-overlay",
  907. css: {
  908. position: "fixed",
  909. inset: 0,
  910. backgroundColor: "rgba(0, 0, 0, 0.5)",
  911. display: "flex",
  912. alignItems: "center",
  913. justifyContent: "center",
  914. zIndex: 9999
  915. },
  916. html: "<div class='loading-spinner'></div>"
  917. });
  918. jQuery("body").append(loading);
  919. },
  920. hideLoading: function() {
  921. jQuery(".loading-overlay").remove();
  922. },
  923. resetAutoPost: function() { // Added reset function
  924. this.STATE.TOTAL_CHAPTERS = 0;
  925. this.STATE.POSTED_CHAPTERS = 0;
  926. localStorage.removeItem('TTV_TOTAL_CHAPTERS');
  927. localStorage.removeItem('TTV_POSTED_CHAPTERS');
  928. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  929. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  930. showNotification('Đã reset số lần tự động đăng', 'info');
  931. },
  932. toggleAutoMode: function() {
  933. const isAutoMode = this.ELEMENTS.qpOptionLoop.is(':checked');
  934.  
  935. if (isAutoMode) {
  936. // Hiển thị nút tự động đăng và reset, ẩn nút paste và đăng chương
  937. this.ELEMENTS.qpButtonAutoPost.show();
  938. this.ELEMENTS.qpButtonReset.show();
  939. this.ELEMENTS.qpButtonPaste.hide();
  940. this.ELEMENTS.qpButtonSubmit.hide();
  941.  
  942. showNotification('Đã bật chế độ tự động', 'info');
  943. } else {
  944. // Hiển thị nút paste và đăng chương, ẩn nút tự động đăng và reset
  945. this.ELEMENTS.qpButtonAutoPost.hide();
  946. this.ELEMENTS.qpButtonReset.hide();
  947. this.ELEMENTS.qpButtonPaste.show();
  948. this.ELEMENTS.qpButtonSubmit.show();
  949.  
  950. showNotification('Đã tắt chế độ tự động', 'info');
  951. }
  952.  
  953. // Lưu trạng thái vào localStorage
  954. localStorage.setItem('TTV_AUTO_MODE', isAutoMode.toString());
  955. }
  956. };
  957. dăngnhanhTTV.init();
  958. })();