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