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 5.2
  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. PROCESSED_CHAPTERS: 0, // Added: Tracks processed chapters
  246. TARGET_CHAPTERS: 0 // Added: Tracks target chapters
  247. },
  248. ELEMENTS: {
  249. qpContent: null,
  250. qpButtonSubmit: null,
  251. qpButtonRemoveEmpty: null,
  252. qpButtonReset: null // Added element
  253. },
  254. init: function() {
  255. try {
  256. console.log('[TTV-DEBUG] Script bắt đầu khởi tạo...');
  257. console.log('[TTV-DEBUG] Phiên bản script: 3.0');
  258. this.initializeChapterValues();
  259. console.log('[TTV-DEBUG] Đã khởi tạo giá trị chương');
  260.  
  261. // Khôi phục trạng thái tự động đăng
  262. this.loadAutoPostState();
  263. console.log('[TTV-DEBUG] Đã khôi phục trạng thái tự động đăng');
  264.  
  265. this.createInterface();
  266. console.log('[TTV-DEBUG] Đã tạo giao diện');
  267. this.cacheElements();
  268. console.log('[TTV-DEBUG] Đã cache các elements');
  269. this.registerEvents();
  270. console.log('[TTV-DEBUG] Đã đăng ký các events');
  271. console.log('[TTV-DEBUG] Script đã khởi động thành công');
  272. showNotification('Công cụ đã chạy', 'success');
  273.  
  274. // Cập nhật hiển thị nút tự động đăng
  275. if (this.STATE.AUTO_POST) {
  276. this.ELEMENTS.qpButtonAutoPost.text(`🔄 (ON) ${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS}`);
  277. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-warning').addClass('btn-info');
  278. }
  279.  
  280. // Khôi phục trạng thái chế độ tự động đăng
  281. const isAutoMode = localStorage.getItem('TTV_AUTO_MODE') === 'true';
  282. if (isAutoMode) {
  283. this.ELEMENTS.qpOptionLoop.prop('checked', true);
  284. this.toggleAutoMode(); // Áp dụng giao diện theo chế độ
  285. }
  286.  
  287. // Khởi tạo biến theo dõi số chương đã xử lý
  288. this.STATE.PROCESSED_CHAPTERS = 0;
  289. this.STATE.TARGET_CHAPTERS = 0;
  290. } catch (e) {
  291. console.error('[TTV-ERROR] Lỗi khởi tạo:', e);
  292. showNotification('Có lỗi khi khởi tạo Script', 'error');
  293. }
  294. },
  295.  
  296. loadAutoPostState: function() {
  297. // Khôi phục trạng thái tự động đăng từ localStorage
  298. const autoPost = localStorage.getItem('TTV_AUTO_POST') === 'true';
  299. this.STATE.AUTO_POST = autoPost;
  300.  
  301. if (autoPost) {
  302. this.STATE.TOTAL_CHAPTERS = parseInt(localStorage.getItem('TTV_TOTAL_CHAPTERS') || '0');
  303. this.STATE.POSTED_CHAPTERS = parseInt(localStorage.getItem('TTV_POSTED_CHAPTERS') || '0');
  304.  
  305. console.log(`[TTV-DEBUG] Khôi phc t động đăng: ${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS}`);
  306. }
  307. },
  308. createInterface: function() {
  309. const html = `
  310. <div id="modern-uploader">
  311. <div class="text-center mb-4">
  312. <h3 style="color: #4285f4; margin-bottom: 15px; font-weight: 700; font-size: 18px;">📝 CÔNG C ĐĂNG NHANH</h3>
  313. </div>
  314. <div class="form-group">
  315. <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>
  316. </div>
  317. <div class="text-center mb-3">
  318. <label style="color: #bef385;"><input type="checkbox" id="qpOptionLoop" class="form-control" style="height:10px;width: 10px;display: inline-block;">Chế độ t động</label>
  319. </div>
  320. <div class="button-container" style="display: flex; justify-content: center; gap: 15px;">
  321. <button class="btn btn-primary" id="qpButtonPaste">📋 Paste</button>
  322. <button class="btn btn-success" id="qpButtonSubmit">📤 Đăng chương</button>
  323. <button class="btn btn-danger" id="qpButtonRemoveEmpty" style="display: none;">Ẩn chương trng</button>
  324. <button class="btn btn-warning" id="qpButtonAutoPost" style="display: none;">🔄 (OFF)</button>
  325. <button class="btn btn-secondary" id="qpButtonReset" style="display: none;">🔁 Reset</button>
  326. </div>
  327. <div class="notification-container"></div>
  328. </div>`;
  329.  
  330. jQuery(".list-in-user").before(html);
  331. },
  332. initializeChapterValues: function() {
  333. try {
  334. const chap_number = parseInt(jQuery('#chap_number').val());
  335. let chap_stt = parseInt(jQuery('.chap_stt1').val());
  336. let chap_serial = parseInt(jQuery('.chap_serial').val());
  337.  
  338. if (parseInt(jQuery('#chap_stt').val()) > chap_stt) {
  339. chap_stt = parseInt(jQuery('#chap_stt').val());
  340. }
  341. if (parseInt(jQuery('#chap_serial').val()) > chap_serial) {
  342. chap_serial = parseInt(jQuery('#chap_serial').val());
  343. }
  344.  
  345. this.STATE.CHAP_NUMBER = this.STATE.CHAP_NUMBER_ORIGINAL = chap_number || 1;
  346. this.STATE.CHAP_STT = this.STATE.CHAP_STT_ORIGINAL = chap_stt || 1;
  347. this.STATE.CHAP_SERIAL = this.STATE.CHAP_SERIAL_ORIGINAL = chap_serial || 1;
  348. } catch (e) {
  349. console.error("Error initializing chapter values:", e);
  350. }
  351. },
  352. cacheElements: function() {
  353. this.ELEMENTS.qpContent = jQuery("#qpContent");
  354. this.ELEMENTS.qpButtonSubmit = jQuery("#qpButtonSubmit");
  355. this.ELEMENTS.qpButtonRemoveEmpty = jQuery("#qpButtonRemoveEmpty");
  356. this.ELEMENTS.qpButtonPaste = jQuery("#qpButtonPaste");
  357. this.ELEMENTS.qpButtonAutoPost = jQuery("#qpButtonAutoPost");
  358. this.ELEMENTS.qpButtonReset = jQuery("#qpButtonReset"); // Added element caching
  359. this.ELEMENTS.qpOptionLoop = jQuery("#qpOptionLoop"); // Added checkbox caching
  360. },
  361. registerEvents: function() {
  362. this.ELEMENTS.qpContent.on("paste", this.handlePaste.bind(this));
  363. this.ELEMENTS.qpButtonRemoveEmpty.on('click', this.removeEmptyChapters.bind(this));
  364. this.ELEMENTS.qpButtonSubmit.on('click', this.submitChapters.bind(this));
  365. this.ELEMENTS.qpButtonPaste.on('click', this.handlePasteButton.bind(this));
  366. this.ELEMENTS.qpButtonAutoPost.on('click', this.toggleAutoPost.bind(this));
  367. this.ELEMENTS.qpButtonReset.on('click', this.resetAutoPost.bind(this)); //Added event listener
  368. this.ELEMENTS.qpOptionLoop.on('change', this.toggleAutoMode.bind(this)); // Added checkbox event
  369. setupCharacterCounter();
  370.  
  371. // Kiểm tra và bắt đầu tự động đăng nếu đã bật
  372. if (window.location.href.includes('/dang-chuong/story/')) {
  373. setTimeout(() => {
  374. if (this.STATE.AUTO_POST && this.STATE.POSTED_CHAPTERS < this.STATE.TOTAL_CHAPTERS) {
  375. this.runAutoPostSequence();
  376. }
  377. }, 2000);
  378. }
  379. },
  380. handlePasteButton: function() {
  381. this.showLoading();
  382. navigator.clipboard.readText()
  383. .then(text => {
  384. this.ELEMENTS.qpContent.val(text);
  385. setTimeout(() => {
  386. this.performAction();
  387. this.hideLoading();
  388. }, 100);
  389. })
  390. .catch(err => {
  391. console.error('Không thể đọc dữ liệu từ clipboard:', err);
  392. this.hideLoading();
  393. showNotification('Không thể truy cập clipboard. Vui lòng dán trực tiếp vào ô nội dung.', 'error');
  394. });
  395. },
  396. handlePaste: function(e) {
  397. e.preventDefault();
  398. this.ELEMENTS.qpContent.val("");
  399. this.showLoading();
  400. const pastedText = e.originalEvent.clipboardData.getData('text');
  401. this.ELEMENTS.qpContent.val(pastedText);
  402. setTimeout(() => {
  403. this.performAction();
  404. this.hideLoading();
  405. }, 100);
  406. },
  407. performAction: function() {
  408. try {
  409. console.log("Starting performAction");
  410. var text = this.ELEMENTS.qpContent.val();
  411.  
  412. if (!text) {
  413. showNotification('Không có nội dung để tách chương', 'error');
  414. return 0;
  415. }
  416. var debugOutput = [];
  417. var chapters = [];
  418. var lines = text.split('\n');
  419. var currentChapter = [];
  420. var lastTitle = null;
  421. debugOutput.push("=== Processing Text ===");
  422. debugOutput.push(`Total lines: ${lines.length}`);
  423. debugOutput.push("=== Line Analysis ===");
  424. function visualizeWhitespace(str) {
  425. return str.split('').map(c => {
  426. if (c === '\t') return '\\t';
  427. if (c === ' ') return '·';
  428. if (c === '\n') return '\\n';
  429. return c;
  430. }).join('');
  431. }
  432. for (let i = 0; i < lines.length; i++) {
  433. let line = lines[i];
  434. let isChapterTitle = /^\t[Cc]hương\s*\d+\s*:/.test(line) || /^\s{4,}[Cc]hương\s*\d+\s*:/.test(line);
  435. debugOutput.push(`Line ${i}: ${visualizeWhitespace(line.substring(0, 50))}${line.length > 50 ? '...' : ''}`);
  436. debugOutput.push(` Is chapter: ${isChapterTitle}`);
  437.  
  438. if (isChapterTitle) {
  439. if (currentChapter.length > 0) {
  440. if (line !== lastTitle) {
  441. chapters.push(currentChapter.join('\n'));
  442. currentChapter = [line];
  443. lastTitle = line;
  444. debugOutput.push(` -> New chapter started`);
  445. } else {
  446. debugOutput.push(` -> Skipped duplicate title`);
  447. }
  448. } else {
  449. currentChapter = [line];
  450. lastTitle = line;
  451. debugOutput.push(` -> First chapter started`);
  452. }
  453. } else if (currentChapter.length > 0) {
  454. currentChapter.push(line);
  455. }
  456. }
  457. if (currentChapter.length > 0) {
  458. chapters.push(currentChapter.join('\n'));
  459. debugOutput.push("-> Added final chapter");
  460. }
  461. debugOutput.push("=== Results ===");
  462. debugOutput.push(`Found ${chapters.length} chapters`);
  463. const processedChapters = [];
  464. for (let i = 0; i < chapters.length; i++) {
  465. const chapterLines = chapters[i].split('\n');
  466. const title = chapterLines.shift().trim();
  467. const chapterText = chapterLines.join('\n');
  468. const charCount = chapterText.length;
  469. debugOutput.push(`Chapter ${i+1} character count: ${charCount}`);
  470. if (charCount > 40000) {
  471. const parts = Math.ceil(charCount / 40000);
  472. debugOutput.push(`Splitting into ${parts} parts`);
  473. const charsPerPart = Math.ceil(charCount / parts);
  474. debugOutput.push(`Characters per part: ~${charsPerPart}`);
  475. let currentText = chapterText;
  476. let totalProcessed = 0;
  477. for (let part = 0; part < parts; part++) {
  478. const isLastPart = part === parts - 1;
  479. const targetSize = isLastPart ? currentText.length : charsPerPart;
  480. let endPos = Math.min(targetSize, currentText.length);
  481. if (!isLastPart && endPos < currentText.length) {
  482. const nextParagraph = currentText.indexOf('\n\n', endPos - 500);
  483. if (nextParagraph !== -1 && nextParagraph < endPos + 500) {
  484. endPos = nextParagraph + 2;
  485. } else {
  486. const sentenceEnd = Math.max(
  487. currentText.lastIndexOf('. ', endPos),
  488. currentText.lastIndexOf('! ', endPos),
  489. currentText.lastIndexOf('? ', endPos)
  490. );
  491. if (sentenceEnd !== -1 && sentenceEnd > endPos - 500) {
  492. endPos = sentenceEnd + 2;
  493. }
  494. }
  495. }
  496. const partContent = currentText.substring(0, endPos);
  497. totalProcessed += partContent.length;
  498. currentText = currentText.substring(endPos);
  499. let chapterTitle = title;
  500. if (title.includes(':')) {
  501. chapterTitle = title.substring(title.indexOf(':') + 1).trim();
  502. }
  503. let newTitle = `${title} (Phn ${part+1}/${parts})`;
  504. processedChapters.push(newTitle + '\n' + partContent);
  505. debugOutput.push(`Part ${part+1}: ${partContent.length} chars`);
  506. }
  507. debugOutput.push(`Total processed: ${totalProcessed}/${charCount} chars`);
  508. } else {
  509. processedChapters.push(chapters[i]);
  510. }
  511. }
  512. debugOutput.push(`After processing: ${processedChapters.length} chapters`);
  513. const chaptersToFill = processedChapters.slice(0, MAX_CHAPTER_POST);
  514. const remainingChapters = processedChapters.slice(MAX_CHAPTER_POST);
  515. var titles = jQuery("input[name^='chap_name']");
  516. var contents = jQuery("textarea[name^='introduce']");
  517. var advs = jQuery("textarea[name^='adv']");
  518. debugOutput.push(`Forms found: ${titles.length}`);
  519. if (processedChapters.length === 0) {
  520. showNotification('Không tìm thấy chương nào', 'error');
  521. jQuery('#debug-output').text(debugOutput.join('\n'));
  522. return;
  523. }
  524. if (remainingChapters.length > 0) {
  525. debugOutput.push(`${remainingChapters.length} chapters will be copied to clipboard`);
  526. }
  527. const neededForms = chaptersToFill.length - titles.length;
  528. if (neededForms > 0 && titles.length < MAX_CHAPTER_POST) {
  529. debugOutput.push(`Need to add ${neededForms} more forms`);
  530. for (let i = 0; i < neededForms && (titles.length + i) < MAX_CHAPTER_POST; i++) {
  531. this.addNewChapter();
  532. }
  533. titles = jQuery("input[name^='chap_name']");
  534. contents = jQuery("textarea[name^='introduce']");
  535. advs = jQuery("textarea[name^='adv']");
  536. }
  537. debugOutput.push(`Filling ${chaptersToFill.length} chapters into forms`);
  538. jQuery.each(titles, function(k, v) {
  539. if (k < chaptersToFill.length) {
  540. var content = chaptersToFill[k].split('\n');
  541. var title = content.shift().trim();
  542. var chapterTitle = title;
  543. if (title.includes(':')) {
  544. chapterTitle = title.substring(title.indexOf(':') + 1).trim();
  545. }
  546. debugOutput.push(`\nFilling chapter ${k + 1}:`);
  547. debugOutput.push(`Original title: ${title}`);
  548. debugOutput.push(`Extracted title: ${chapterTitle}`);
  549. debugOutput.push(`Content length: ${content.length} lines`);
  550. if (!chapterTitle || chapterTitle.trim() === '') {
  551. chapterTitle = "Vô đề";
  552. debugOutput.push(`Empty title detected, using default: ${chapterTitle}`);
  553. }
  554. titles[k].value = chapterTitle;
  555. contents[k].value = HEADER_SIGN + "\r\n" + content.join('\n') + "\r\n" + FOOTER_SIGN;
  556. if (advs[k]) advs[k].value = "";
  557. jQuery(contents[k]).trigger('input');
  558. }
  559. });
  560. if (remainingChapters.length > 0) {
  561. try {
  562. const clipboardContent = remainingChapters.map(chap => {
  563. const lines = chap.trim().split('\n');
  564. if (lines.length > 0) {
  565. if (!lines[0].startsWith('\t')) {
  566. lines[0] = '\t' + lines[0];
  567. }
  568. }
  569. return lines.join('\n');
  570. }).join('\n\n---CHAPTER_SEPARATOR---\n\n');
  571. let splitChapters = 0;
  572. let shortChapters = 0;
  573. let shortChapterDetails = [];
  574. let longChapterDetails = [];
  575. for (let i = 0; i < chapters.length; i++) {
  576. const chapterLines = chapters[i].split('\n');
  577. const title = chapterLines.shift().trim();
  578. const chapterText = chapterLines.join('\n');
  579. if (chapterText.length > 40000) {
  580. splitChapters++;
  581. const partsCount = Math.ceil(chapterText.length / 40000);
  582. longChapterDetails.push({
  583. title: title,
  584. parts: partsCount
  585. });
  586. }
  587. if (chapterText.length < 3000) {
  588. shortChapters++;
  589. shortChapterDetails.push({
  590. title: title,
  591. length: chapterText.length
  592. });
  593. }
  594. }
  595. const splittedChaptersCount = processedChapters.length - (chapters.length - splitChapters);
  596. let message = '';
  597. message = message.concat(`📝Đã x lý ${processedChapters.length} Chương\n`);
  598. message = message.concat(`📝Đã nhp ${Math.min(processedChapters.length, MAX_CHAPTER_POST)} Chương\n`);
  599.  
  600. if (remainingChapters.length > 0) {
  601. message = message.concat(`📋Đã lưu li ${remainingChapters.length} Chương\n`);
  602. }
  603. if (splitChapters > 0) {
  604. message = message.concat(`📑Có ${splitChapters} Chương đã chia thành ${splittedChaptersCount} Chương\n`);
  605. longChapterDetails.forEach(chapter => {
  606. let chapterName = chapter.title;
  607. if (chapterName.includes(':')) {
  608. chapterName = chapterName.trim();
  609. }
  610. message = message.concat(` - ${chapterName}: ${chapter.parts} Chương\n`);
  611. });
  612. }
  613. if (shortChapters > 0) {
  614. message = message.concat(`⚠️<span class="short-chapters-warning">Có ${shortChapters} chương dưới 3000 ký tự</span>\n`);
  615. shortChapterDetails.forEach(chapter => {
  616. let chapterName = chapter.title;
  617. if (chapterName.includes(':')) {
  618. chapterName = chapterName.trim();
  619. }
  620. message = message.concat(`<span class="short-chapters-warning"> - ${chapterName}: có ${chapter.length.toLocaleString()} ký tự</span>\n`);
  621. });
  622. }
  623. // Cập nhật số chương đã xử lý
  624. this.STATE.PROCESSED_CHAPTERS += processedChapters.length;
  625.  
  626. // Kiểm tra xem đã xử lý đủ số chương chưa
  627. if (this.STATE.TARGET_CHAPTERS > 0 && this.STATE.PROCESSED_CHAPTERS >= this.STATE.TARGET_CHAPTERS) {
  628. message = message.concat(`\n🎯 Đã đạt mc tiêu x lý ${this.STATE.PROCESSED_CHAPTERS}/${this.STATE.TARGET_CHAPTERS} chương`);
  629. // Xóa clipboard nếu đã đủ số chương
  630. if (navigator.clipboard && navigator.clipboard.writeText) {
  631. navigator.clipboard.writeText("");
  632. }
  633. }
  634.  
  635. showNotification(message, 'success');
  636. } catch (err) {
  637. console.error('Lỗi khi sao chép vào clipboard:', err);
  638. debugOutput.push(`Li khi sao chép vào clipboard: ${err.message}`);
  639. showNotification('Không thể sao chép vào clipboard. Vui lòng thử lại.', 'error');
  640. const manualCopyArea = document.createElement('div');
  641. manualCopyArea.style.position = 'fixed';
  642. manualCopyArea.style.top = '50%';
  643. manualCopyArea.style.left = '50%';
  644. manualCopyArea.style.transform = 'translate(-50%, -50%)';
  645. manualCopyArea.style.backgroundColor = 'white';
  646. manualCopyArea.style.padding = '20px';
  647. manualCopyArea.style.borderRadius = '8px';
  648. manualCopyArea.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1)';
  649. manualCopyArea.style.zIndex = '10000';
  650. manualCopyArea.style.maxWidth = '80%';
  651. manualCopyArea.style.maxHeight = '80%';
  652. manualCopyArea.style.overflow = 'auto';
  653. manualCopyArea.innerHTML = `
  654. <h3 style="margin-top: 0;">Sao chép th công</h3>
  655. <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>
  656. <textarea style="width: 100%; height: 300px; padding: 10px;">${clipboardContent}</textarea>
  657. <div style="text-align: right; margin-top: 10px;">
  658. <button id="closeManualCopy" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 4px; cursor: pointer;">Đóng</button>
  659. </div>
  660. `;
  661. document.body.appendChild(manualCopyArea);
  662. document.getElementById('closeManualCopy').addEventListener('click', () => {
  663. document.body.removeChild(manualCopyArea);
  664. });
  665. }
  666. }
  667. this.ELEMENTS.qpButtonSubmit.removeClass("btn-disable").addClass("btn-success");
  668. this.ELEMENTS.qpContent.val("Đã thựchiện xong");
  669. if (remainingChapters.length === 0) {
  670. let splitChapters = 0;
  671. let shortChapters = 0;
  672. let shortChapterDetails = [];
  673. let longChapterDetails = [];
  674. for (let i = 0; i < chapters.length; i++) {
  675. const chapterLines = chapters[i].split('\n');
  676. const title = chapterLines.shift().trim();
  677. const chapterText = chapterLines.join('\n');
  678. if (chapterText.length > 40000) {
  679. splitChapters++;
  680. const partsCount = Math.ceil(chapterText.length / 40000);
  681. longChapterDetails.push({
  682. title: title,
  683. parts: partsCount
  684. });
  685. }
  686. if (chapterText.length < 3000) {
  687. shortChapters++;
  688. shortChapterDetails.push({
  689. title: title,
  690. length: chapterText.length
  691. });
  692. }
  693. }
  694. const splittedChaptersCount = processedChapters.length - (chapters.length - splitChapters);
  695. let message = '';
  696. message = message.concat(`📝Đã x lý ${processedChapters.length} Chương\n`);
  697. message = message.concat(`📝Đã nhp ${Math.min(processedChapters.length, MAX_CHAPTER_POST)} Chương\n`);
  698. if (splitChapters > 0) {
  699. message = message.concat(`📑Có ${splitChapters} Chương dài chia thành ${splittedChaptersCount} Chương\n`);
  700. longChapterDetails.forEach(chapter => {
  701. let chapterName = chapter.title;
  702. if (chapterName.includes(':')) {
  703. chapterName = chapterName.trim();
  704. }
  705. message = message.concat(` - ${chapterName}: ${chapter.parts} Chương\n`);
  706. });
  707. }
  708. if (shortChapters > 0) {
  709. message = message.concat(`⚠️<span class="short-chapters-warning">Có ${shortChapters} chương dưới 3000 ký tự</span>\n`);
  710. shortChapterDetails.forEach(chapter => {
  711. let chapterName = chapter.title;
  712. if (chapterName.includes(':')) {
  713. chapterName = chapterName.trim();
  714. }
  715. message = message.concat(`<span class="short-chapters-warning"> - ${chapterName}: có ${chapter.length.toLocaleString()} ký tự</span>\n`);
  716. });
  717. }
  718. showNotification(message, 'success');
  719. }
  720. jQuery('#debug-output').text(debugOutput.join('\n'));
  721. return processedChapters.length;
  722. } catch (e) {
  723. console.error("Error in performAction:", e);
  724. showNotification('Có lỗi khi tách chương', 'error');
  725. return 0;
  726. }
  727. },
  728. removeEmptyChapters: function() {
  729. const forms = document.querySelectorAll('[data-gen="MK_GEN"]');
  730. let removed = 0;
  731.  
  732. forms.forEach(form => {
  733. const content = form.querySelector('textarea[name^="introduce"]').value.trim();
  734. if (!content) {
  735. form.remove();
  736. removed++;
  737. this.updateChapNumber(false);
  738. }
  739. });
  740. showNotification(`Đã x lý ${forms.length} chương`, 'info');
  741. },
  742. toggleAutoPost: function() {
  743. this.STATE.AUTO_POST = !this.STATE.AUTO_POST;
  744.  
  745. if (this.STATE.AUTO_POST) {
  746. // Lưu trạng thái tự động đăng vào localStorage
  747. localStorage.setItem('TTV_AUTO_POST', 'true');
  748. this.STATE.TOTAL_CHAPTERS = parseInt(prompt("Nhập tổng số lần tự động đăng:", "10")) || 0;
  749. this.STATE.POSTED_CHAPTERS = parseInt(localStorage.getItem('TTV_POSTED_CHAPTERS') || '0');
  750. this.STATE.TARGET_CHAPTERS = this.STATE.TOTAL_CHAPTERS; // Set target chapters
  751.  
  752. localStorage.setItem('TTV_TOTAL_CHAPTERS', this.STATE.TOTAL_CHAPTERS.toString());
  753.  
  754. this.ELEMENTS.qpButtonAutoPost.text(`🔄 (ON) ${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS}`);
  755. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-warning').addClass('btn-info');
  756.  
  757. showNotification(`Đã bt t động đăng (${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS})`, 'success');
  758.  
  759. // Bắt đầu quy trình tự động
  760. if (window.location.href.includes('/dang-chuong/story/')) {
  761. setTimeout(() => this.runAutoPostSequence(), 2000);
  762. }
  763. } else {
  764. // Tắt tự động đăng
  765. localStorage.setItem('TTV_AUTO_POST', 'false');
  766. // Reset số lần đã đăng về 0
  767. this.STATE.POSTED_CHAPTERS = 0;
  768. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  769. // Reset tổng số lần đăng về 0
  770. this.STATE.TOTAL_CHAPTERS = 0;
  771. localStorage.setItem('TTV_TOTAL_CHAPTERS', '0');
  772. this.STATE.TARGET_CHAPTERS = 0; // Reset target chapters
  773. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  774. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  775. showNotification('Đã tắt tự động đăng và reset số lần đăng', 'info');
  776. }
  777. },
  778.  
  779. runAutoPostSequence: function() {
  780. // Kiểm tra trước khi chạy tự động
  781. if (this.STATE.POSTED_CHAPTERS >= this.STATE.TOTAL_CHAPTERS) {
  782. // Reset trạng thái tự động nếu đã hoàn thành
  783. this.STATE.AUTO_POST = false;
  784. localStorage.setItem('TTV_AUTO_POST', 'false');
  785. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  786. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  787.  
  788. // Reset số lần đã đăng
  789. this.STATE.POSTED_CHAPTERS = 0;
  790. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  791.  
  792. showNotification(`Đã hoàn thành t động đăng ${this.STATE.TOTAL_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS} chương và đã reset s ln đăng`, 'success');
  793. return;
  794. }
  795.  
  796. if (!this.STATE.AUTO_POST) {
  797. return;
  798. }
  799.  
  800. // Tự động nhấn nút Paste sau 2 giây
  801. setTimeout(() => {
  802. if (this.STATE.AUTO_POST) {
  803. this.handlePasteButton();
  804.  
  805. // Tự động nhấn nút Đăng chương sau 3 giây
  806. setTimeout(() => {
  807. if (this.STATE.AUTO_POST) {
  808. this.submitChapters();
  809. }
  810. }, 3000);
  811. }
  812. }, 2000);
  813. },
  814.  
  815. submitChapters: function() {
  816. if (!validateChapterLengths()) {
  817. return;
  818. }
  819. this.showLoading();
  820. document.querySelector('form[name="postChapForm"] button[type="submit"]').click();
  821.  
  822. if (this.STATE.AUTO_POST) {
  823. // Cập nhật số chương đã đăng
  824. this.STATE.POSTED_CHAPTERS++;
  825. localStorage.setItem('TTV_POSTED_CHAPTERS', this.STATE.POSTED_CHAPTERS.toString());
  826.  
  827. // Kiểm tra và tắt tự động đăng nếu đã đủ số chương
  828. if (this.STATE.POSTED_CHAPTERS >= this.STATE.TOTAL_CHAPTERS) {
  829. this.STATE.AUTO_POST = false;
  830. localStorage.setItem('TTV_AUTO_POST', 'false');
  831. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  832. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  833.  
  834. // Reset số lần đã đăng
  835. this.STATE.POSTED_CHAPTERS = 0;
  836. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  837.  
  838. setTimeout(() => {
  839. showNotification(`Đã hoàn thành t động đăng ${this.STATE.TOTAL_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS} chương và đã reset s ln đăng`, 'success');
  840. }, 3000);
  841. }
  842. }
  843.  
  844. setTimeout(() => this.hideLoading(), 2000);
  845. },
  846. addNewChapter: function() {
  847. if ((this.STATE.CHAP_NUMBER + 1) <= MAX_CHAPTER_POST) {
  848. this.updateChapNumber(true);
  849. const html = createChapterHTML(this.STATE.CHAP_NUMBER);
  850. jQuery('#add-chap').before(html);
  851. setupCharacterCounter();
  852. } else {
  853. showNotification(`Ch có th đăng ti đa ${MAX_CHAPTER_POST} chương mt ln`, 'warning');
  854. }
  855. },
  856. updateChapNumber: function(isAdd) {
  857. try{
  858. if (isAdd) {
  859. let maxStt =0;
  860. let maxSerial = 0;
  861. jQuery('input[name^="chap_stt"]').each(function() {
  862. const val = parseInt(jQuery(this).val()) || 0;
  863. maxStt = Math.max(maxStt, val);
  864. });
  865. jQuery('input[name^="chap_number"]').each(function() {
  866. const val = parseInt(jQuery(this).val()) || 0;
  867. maxSerial = Math.max(maxSerial, val);
  868. });
  869. const chapStt = parseInt(jQuery('.chap_stt1').val()) || 0;
  870. const chapSerial = parseInt(jQuery('.chap_serial').val()) || 0;
  871. maxStt = Math.max(maxStt, chapStt);
  872. maxSerial = Math.max(maxSerial, chapSerial);
  873. this.STATE.CHAP_STT = maxStt + 1;
  874. this.STATE.CHAP_SERIAL = maxSerial + 1;
  875. this.STATE.CHAP_NUMBER++;
  876. } else {
  877. if (this.STATE.CHAP_NUMBER > this.STATE.CHAP_NUMBER_ORIGINAL) {
  878. this.STATE.CHAP_NUMBER--;
  879. }
  880. if (this.STATE.CHAP_STT > this.STATE.CHAP_STT_ORIGINAL) {
  881. this.STATE.CHAP_STT--;
  882. }
  883. if (this.STATE.CHAP_SERIAL > this.STATE.CHAP_SERIAL_ORIGINAL) {
  884. this.STATE.CHAP_SERIAL--;
  885. }
  886. }
  887. jQuery('#chap_number').val(this.STATE.CHAP_NUMBER);
  888. jQuery('#chap_stt').val(this.STATE.CHAP_STT);
  889. jQuery('#chap_serial').val(this.STATE.CHAP_SERIAL);
  890. jQuery('#countNumberPost').text(this.STATE.CHAP_NUMBER);
  891. } catch (e) {
  892. console.log("Lỗi: " + e);
  893. }
  894. },
  895. showLoading: function() {
  896. const loading = jQuery("<div>", {
  897. class: "loading-overlay",
  898. css: {
  899. position: "fixed",
  900. inset: 0,
  901. backgroundColor: "rgba(0, 0, 0, 0.5)",
  902. display: "flex",
  903. alignItems: "center",
  904. justifyContent: "center",
  905. zIndex: 9999
  906. },
  907. html: "<div class='loading-spinner'></div>"
  908. });
  909. jQuery("body").append(loading);
  910. },
  911. hideLoading: function() {
  912. jQuery(".loading-overlay").remove();
  913. },
  914. resetAutoPost: function() { // Added reset function
  915. this.STATE.TOTAL_CHAPTERS = 0;
  916. this.STATE.POSTED_CHAPTERS = 0;
  917. this.STATE.TARGET_CHAPTERS = 0; // Reset target chapters
  918. localStorage.removeItem('TTV_TOTAL_CHAPTERS');
  919. localStorage.removeItem('TTV_POSTED_CHAPTERS');
  920. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  921. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  922. showNotification('Đã reset số lần tự động đăng', 'info');
  923. },
  924. toggleAutoMode: function() {
  925. const isAutoMode = this.ELEMENTS.qpOptionLoop.is(':checked');
  926.  
  927. if (isAutoMode) {
  928. // Hiển thị nút tự động đăng và reset, ẩn nút paste và đăng chương
  929. this.ELEMENTS.qpButtonAutoPost.show();
  930. this.ELEMENTS.qpButtonReset.show();
  931. this.ELEMENTS.qpButtonPaste.hide();
  932. this.ELEMENTS.qpButtonSubmit.hide();
  933.  
  934. showNotification('Đã bật chế độ tự động', 'info');
  935. } else {
  936. // Hiển thị nút paste và đăng chương, ẩn nút tự động đăng và reset
  937. this.ELEMENTS.qpButtonAutoPost.hide();
  938. this.ELEMENTS.qpButtonReset.hide();
  939. this.ELEMENTS.qpButtonPaste.show();
  940. this.ELEMENTS.qpButtonSubmit.show();
  941.  
  942. showNotification('Đã tắt chế độ tự động', 'info');
  943. }
  944.  
  945. // Lưu trạng thái vào localStorage
  946. localStorage.setItem('TTV_AUTO_MODE', isAutoMode.toString());
  947. }
  948. };
  949. dăngnhanhTTV.init();
  950. })();