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 8.3
  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. // Hàm lấy mã chương dựa vào tiêu đề
  427. function getChapterCode(title) {
  428. // Lấy số chương + tên chương, bỏ qua các ký tự đặc biệt
  429. const match = title.match(/[Cc]hương\s*(\d+)\s*:/);
  430. if (!match) return title.trim();
  431. const chapterNum = match[1];
  432. return `chap_${chapterNum}`;
  433. }
  434. for (let i = 0; i < lines.length; i++) {
  435. let line = lines[i];
  436. let isChapterTitle = /^\t[Cc]hương\s*\d+\s*:/.test(line) || /^\s{4,}[Cc]hương\s*\d+\s*:/.test(line);
  437. debugOutput.push(`Line ${i}: ${visualizeWhitespace(line.substring(0, 50))}${line.length > 50 ? '...' : ''}`);
  438. debugOutput.push(` Is chapter: ${isChapterTitle}`);
  439.  
  440. if (isChapterTitle) {
  441. // Lấy mã chương để so sánh
  442. const currentChapterCode = getChapterCode(line);
  443. const lastTitleCode = lastTitle ? getChapterCode(lastTitle) : null;
  444. if (currentChapter.length > 0) {
  445. // Kiểm tra nếu chương hiện tại khác chương trước đó
  446. if (currentChapterCode !== lastTitleCode) {
  447. chapters.push(currentChapter.join('\n'));
  448. currentChapter = [line];
  449. lastTitle = line;
  450. debugOutput.push(` -> New chapter started: ${currentChapterCode}`);
  451. } else {
  452. debugOutput.push(` -> Skipped duplicate chapter: ${currentChapterCode}`);
  453. // Không cần thêm dòng này vào chapter hiện tại vì nó là tiêu đề trùng lặp
  454. }
  455. } else {
  456. currentChapter = [line];
  457. lastTitle = line;
  458. debugOutput.push(` -> First chapter started: ${currentChapterCode}`);
  459. }
  460. } else if (currentChapter.length > 0) {
  461. currentChapter.push(line);
  462. }
  463. }
  464. if (currentChapter.length > 0) {
  465. chapters.push(currentChapter.join('\n'));
  466. debugOutput.push("-> Added final chapter");
  467. }
  468. debugOutput.push("=== Results ===");
  469. debugOutput.push(`Found ${chapters.length} chapters`);
  470. const processedChapters = [];
  471. for (let i = 0; i < chapters.length; i++) {
  472. const chapterLines = chapters[i].split('\n');
  473. const title = chapterLines.shift().trim();
  474. const chapterText = chapterLines.join('\n');
  475. const charCount = chapterText.length;
  476. debugOutput.push(`Chapter ${i+1} character count: ${charCount}`);
  477. if (charCount > 40000) {
  478. const parts = Math.ceil(charCount / 40000);
  479. debugOutput.push(`Splitting into ${parts} parts`);
  480. const charsPerPart = Math.ceil(charCount / parts);
  481. debugOutput.push(`Characters per part: ~${charsPerPart}`);
  482. let currentText = chapterText;
  483. let totalProcessed = 0;
  484. for (let part = 0; part < parts; part++) {
  485. const isLastPart = part === parts - 1;
  486. const targetSize = isLastPart ? currentText.length : charsPerPart;
  487. let endPos = Math.min(targetSize, currentText.length);
  488. if (!isLastPart && endPos < currentText.length) {
  489. const nextParagraph = currentText.indexOf('\n\n', endPos - 500);
  490. if (nextParagraph !== -1 && nextParagraph < endPos + 500) {
  491. endPos = nextParagraph + 2;
  492. } else {
  493. const sentenceEnd = Math.max(
  494. currentText.lastIndexOf('. ', endPos),
  495. currentText.lastIndexOf('! ', endPos),
  496. currentText.lastIndexOf('? ', endPos)
  497. );
  498. if (sentenceEnd !== -1 && sentenceEnd > endPos - 500) {
  499. endPos = sentenceEnd + 2;
  500. }
  501. }
  502. }
  503. const partContent = currentText.substring(0, endPos);
  504. totalProcessed += partContent.length;
  505. currentText = currentText.substring(endPos);
  506. let chapterTitle = title;
  507. if (title.includes(':')) {
  508. chapterTitle = title.substring(title.indexOf(':') + 1).trim();
  509. }
  510. let newTitle = `${title} (Phn ${part+1}/${parts})`;
  511. processedChapters.push(newTitle + '\n' + partContent);
  512. debugOutput.push(`Part ${part+1}: ${partContent.length} chars`);
  513. }
  514. debugOutput.push(`Total processed: ${totalProcessed}/${charCount} chars`);
  515. } else {
  516. processedChapters.push(chapters[i]);
  517. }
  518. }
  519. debugOutput.push(`After processing: ${processedChapters.length} chapters`);
  520. const chaptersToFill = processedChapters.slice(0, MAX_CHAPTER_POST);
  521. const remainingChapters = processedChapters.slice(MAX_CHAPTER_POST);
  522. var titles = jQuery("input[name^='chap_name']");
  523. var contents = jQuery("textarea[name^='introduce']");
  524. var advs = jQuery("textarea[name^='adv']");
  525. debugOutput.push(`Forms found: ${titles.length}`);
  526. if (processedChapters.length === 0) {
  527. showNotification('Không tìm thấy chương nào', 'error');
  528. jQuery('#debug-output').text(debugOutput.join('\n'));
  529. return;
  530. }
  531. if (remainingChapters.length > 0) {
  532. debugOutput.push(`${remainingChapters.length} chapters will be copied to clipboard`);
  533. }
  534. const neededForms = chaptersToFill.length - titles.length;
  535. if (neededForms > 0 && titles.length < MAX_CHAPTER_POST) {
  536. debugOutput.push(`Need to add ${neededForms} more forms`);
  537. for (let i = 0; i < neededForms && (titles.length + i) < MAX_CHAPTER_POST; i++) {
  538. this.addNewChapter();
  539. }
  540. titles = jQuery("input[name^='chap_name']");
  541. contents = jQuery("textarea[name^='introduce']");
  542. advs = jQuery("textarea[name^='adv']");
  543. }
  544. debugOutput.push(`Filling ${chaptersToFill.length} chapters into forms`);
  545. jQuery.each(titles, function(k, v) {
  546. if (k < chaptersToFill.length) {
  547. var content = chaptersToFill[k].split('\n');
  548. var title = content.shift().trim();
  549. var chapterTitle = title;
  550. if (title.includes(':')) {
  551. chapterTitle = title.substring(title.indexOf(':') + 1).trim();
  552. }
  553. debugOutput.push(`\nFilling chapter ${k + 1}:`);
  554. debugOutput.push(`Original title: ${title}`);
  555. debugOutput.push(`Extracted title: ${chapterTitle}`);
  556. debugOutput.push(`Content length: ${content.length} lines`);
  557. if (!chapterTitle || chapterTitle.trim() === '') {
  558. chapterTitle = "Vô đề";
  559. debugOutput.push(`Empty title detected, using default: ${chapterTitle}`);
  560. }
  561. titles[k].value = chapterTitle;
  562. contents[k].value = HEADER_SIGN + "\r\n" + content.join('\n') + "\r\n" + FOOTER_SIGN;
  563. if (advs[k]) advs[k].value = "";
  564. jQuery(contents[k]).trigger('input');
  565. }
  566. });
  567. if (remainingChapters.length > 0) {
  568. try {
  569. const clipboardContent = remainingChapters.map(chap => {
  570. const lines = chap.trim().split('\n');
  571. if (lines.length > 0) {
  572. if (!lines[0].startsWith('\t')) {
  573. lines[0] = '\t' + lines[0];
  574. }
  575. }
  576. return lines.join('\n');
  577. }).join('\n\n---CHAPTER_SEPARATOR---\n\n');
  578. let splitChapters = 0;
  579. let shortChapters = 0;
  580. let shortChapterDetails = [];
  581. let longChapterDetails = [];
  582. for (let i = 0; i < chapters.length; i++) {
  583. const chapterLines = chapters[i].split('\n');
  584. const title = chapterLines.shift().trim();
  585. const chapterText = chapterLines.join('\n');
  586. if (chapterText.length > 40000) {
  587. splitChapters++;
  588. const partsCount = Math.ceil(chapterText.length / 40000);
  589. longChapterDetails.push({
  590. title: title,
  591. parts: partsCount
  592. });
  593. }
  594. if (chapterText.length < 3000) {
  595. shortChapters++;
  596. shortChapterDetails.push({
  597. title: title,
  598. length: chapterText.length
  599. });
  600. }
  601. }
  602. const splittedChaptersCount = processedChapters.length - (chapters.length - splitChapters);
  603. let message = '';
  604. message = message.concat(`📝Đã x lý ${processedChapters.length} Chương\n`);
  605. message = message.concat(`📝Đã nhp ${Math.min(processedChapters.length, MAX_CHAPTER_POST)} Chương\n`);
  606.  
  607. if (remainingChapters.length > 0) {
  608. message = message.concat(`📋Đã lưu li ${remainingChapters.length} Chương\n`);
  609. }
  610. if (splitChapters > 0) {
  611. message = message.concat(`📑Có ${splitChapters} Chương đã chia thành ${splittedChaptersCount} Chương\n`);
  612. longChapterDetails.forEach(chapter => {
  613. let chapterName = chapter.title;
  614. if (chapterName.includes(':')) {
  615. chapterName = chapterName.trim();
  616. }
  617. message = message.concat(` - ${chapterName}: ${chapter.parts} Chương\n`);
  618. });
  619. }
  620. if (shortChapters > 0) {
  621. message = message.concat(`⚠️<span class="short-chapters-warning">Có ${shortChapters} chương dưới 3000 ký tự</span>\n`);
  622. shortChapterDetails.forEach(chapter => {
  623. let chapterName = chapter.title;
  624. if (chapterName.includes(':')) {
  625. chapterName = chapterName.trim();
  626. }
  627. message = message.concat(`<span class="short-chapters-warning"> - ${chapterName}: có ${chapter.length.toLocaleString()} ký tự</span>\n`);
  628. });
  629. }
  630. if (navigator.clipboard && navigator.clipboard.writeText) {
  631. navigator.clipboard.writeText(clipboardContent)
  632. .then(() => {
  633. debugOutput.push(`📋Đã lưu li ${remainingChapters.length} Chương\n`);
  634. showNotification(message, remainingChapters.length > 0 ? 'warning' : 'success');
  635. })
  636. .catch(err => {
  637. throw err;
  638. });
  639. } else {
  640. const tempTextarea = document.createElement('textarea');
  641. tempTextarea.style.position = 'fixed';
  642. tempTextarea.style.top = '0';
  643. tempTextarea.style.left = '0';
  644. tempTextarea.style.width = '2em';
  645. tempTextarea.style.height = '2em';
  646. tempTextarea.style.opacity = '0';
  647. tempTextarea.style.pointerEvents = 'none';
  648. tempTextarea.value = clipboardContent;
  649. document.body.appendChild(tempTextarea);
  650. tempTextarea.focus();
  651. tempTextarea.select();
  652. const successful = document.execCommand('copy');
  653. document.body.removeChild(tempTextarea);
  654. if (!successful) {
  655. throw new Error('Không thể sao chép vào clipboard');
  656. }
  657. debugOutput.push(`Đã sao chép ${remainingChapters.length} chương vào clipboard (execCommand)`);
  658. showNotification(message, 'success');
  659. }
  660. } catch (err) {
  661. console.error('Lỗi khi sao chép vào clipboard:', err);
  662. debugOutput.push(`Li khi sao chép vào clipboard: ${err.message}`);
  663. showNotification('Không thể sao chép vào clipboard. Vui lòng thử lại.', 'error');
  664. const manualCopyArea = document.createElement('div');
  665. manualCopyArea.style.position = 'fixed';
  666. manualCopyArea.style.top = '50%';
  667. manualCopyArea.style.left = '50%';
  668. manualCopyArea.style.transform = 'translate(-50%, -50%)';
  669. manualCopyArea.style.backgroundColor = 'white';
  670. manualCopyArea.style.padding = '20px';
  671. manualCopyArea.style.borderRadius = '8px';
  672. manualCopyArea.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1)';
  673. manualCopyArea.style.zIndex = '10000';
  674. manualCopyArea.style.maxWidth = '80%';
  675. manualCopyArea.style.maxHeight = '80%';
  676. manualCopyArea.style.overflow = 'auto';
  677. manualCopyArea.innerHTML = `
  678. <h3 style="margin-top: 0;">Sao chép th công</h3>
  679. <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>
  680. <textarea style="width: 100%; height: 300px; padding: 10px;">${clipboardContent}</textarea>
  681. <div style="text-align: right; margin-top: 10px;">
  682. <button id="closeManualCopy" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 4px; cursor: pointer;">Đóng</button>
  683. </div>
  684. `;
  685. document.body.appendChild(manualCopyArea);
  686. document.getElementById('closeManualCopy').addEventListener('click', () => {
  687. document.body.removeChild(manualCopyArea);
  688. });
  689. }
  690. }
  691. this.ELEMENTS.qpButtonSubmit.removeClass("btn-disable").addClass("btn-success");
  692. this.ELEMENTS.qpContent.val("Đã thựchiện xong");
  693. if (remainingChapters.length === 0) {
  694. let splitChapters = 0;
  695. let shortChapters = 0;
  696. let shortChapterDetails = [];
  697. let longChapterDetails = [];
  698. for (let i = 0; i < chapters.length; i++) {
  699. const chapterLines = chapters[i].split('\n');
  700. const title = chapterLines.shift().trim();
  701. const chapterText = chapterLines.join('\n');
  702. if (chapterText.length > 40000) {
  703. splitChapters++;
  704. const partsCount = Math.ceil(chapterText.length / 40000);
  705. longChapterDetails.push({
  706. title: title,
  707. parts: partsCount
  708. });
  709. }
  710. if (chapterText.length < 3000) {
  711. shortChapters++;
  712. shortChapterDetails.push({
  713. title: title,
  714. length: chapterText.length
  715. });
  716. }
  717. }
  718. const splittedChaptersCount = processedChapters.length - (chapters.length - splitChapters);
  719. let message = '';
  720. message = message.concat(`📝Đã x lý ${processedChapters.length} Chương\n`);
  721. message = message.concat(`📝Đã nhp ${Math.min(processedChapters.length, MAX_CHAPTER_POST)} Chương\n`);
  722. if (splitChapters > 0) {
  723. message = message.concat(`📑Có ${splitChapters} Chương dài chia thành ${splittedChaptersCount} Chương\n`);
  724. longChapterDetails.forEach(chapter => {
  725. let chapterName = chapter.title;
  726. if (chapterName.includes(':')) {
  727. chapterName = chapterName.trim();
  728. }
  729. message = message.concat(` - ${chapterName}: ${chapter.parts} Chương\n`);
  730. });
  731. }
  732. if (shortChapters > 0) {
  733. message = message.concat(`⚠️<span class="short-chapters-warning">Có ${shortChapters} chương dưới 3000 ký tự</span>\n`);
  734. shortChapterDetails.forEach(chapter => {
  735. let chapterName = chapter.title;
  736. if (chapterName.includes(':')) {
  737. chapterName = chapterName.trim();
  738. }
  739. message = message.concat(`<span class="short-chapters-warning"> - ${chapterName}: có ${chapter.length.toLocaleString()} ký tự</span>\n`);
  740. });
  741. }
  742. showNotification(message, 'success');
  743. }
  744. jQuery('#debug-output').text(debugOutput.join('\n'));
  745. return processedChapters.length;
  746. } catch (e) {
  747. console.error("Error in performAction:", e);
  748. showNotification('Có lỗi khi tách chương', 'error');
  749. return 0;
  750. }
  751. },
  752. removeEmptyChapters: function() {
  753. const forms = document.querySelectorAll('[data-gen="MK_GEN"]');
  754. let removed = 0;
  755.  
  756. forms.forEach(form => {
  757. const content = form.querySelector('textarea[name^="introduce"]').value.trim();
  758. if (!content) {
  759. form.remove();
  760. removed++;
  761. this.updateChapNumber(false);
  762. }
  763. });
  764. showNotification(`Đã x lý ${forms.length} chương`, 'info');
  765. },
  766. toggleAutoPost: function() {
  767. this.STATE.AUTO_POST = !this.STATE.AUTO_POST;
  768.  
  769. if (this.STATE.AUTO_POST) {
  770. // Lưu trạng thái tự động đăng vào localStorage
  771. localStorage.setItem('TTV_AUTO_POST', 'true');
  772. this.STATE.TOTAL_CHAPTERS = parseInt(prompt("Nhập tổng số lần tự động đăng:", "10")) || 0;
  773. this.STATE.POSTED_CHAPTERS = parseInt(localStorage.getItem('TTV_POSTED_CHAPTERS') || '0');
  774.  
  775. localStorage.setItem('TTV_TOTAL_CHAPTERS', this.STATE.TOTAL_CHAPTERS.toString());
  776.  
  777. this.ELEMENTS.qpButtonAutoPost.text(`🔄 (ON) ${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS}`);
  778. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-warning').addClass('btn-info');
  779.  
  780. showNotification(`Đã bt t động đăng (${this.STATE.POSTED_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS})`, 'success');
  781.  
  782. // Bắt đầu quy trình tự động
  783. if (window.location.href.includes('/dang-chuong/story/')) {
  784. setTimeout(() => this.runAutoPostSequence(), 2000);
  785. }
  786. } else {
  787. // Tắt tự động đăng
  788. localStorage.setItem('TTV_AUTO_POST', 'false');
  789. // Reset số lần đã đăng về 0
  790. this.STATE.POSTED_CHAPTERS = 0;
  791. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  792. // Reset tổng số lần đăng về 0
  793. this.STATE.TOTAL_CHAPTERS = 0;
  794. localStorage.setItem('TTV_TOTAL_CHAPTERS', '0');
  795. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  796. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  797. showNotification('Đã tắt tự động đăng và reset số lần đăng', 'info');
  798. }
  799. },
  800.  
  801. runAutoPostSequence: function() {
  802. // Kiểm tra trước khi chạy tự động
  803. if (this.STATE.POSTED_CHAPTERS >= this.STATE.TOTAL_CHAPTERS) {
  804. // Reset trạng thái tự động nếu đã hoàn thành
  805. this.STATE.AUTO_POST = false;
  806. localStorage.setItem('TTV_AUTO_POST', 'false');
  807. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  808. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  809.  
  810. // Reset số lần đã đăng
  811. this.STATE.POSTED_CHAPTERS = 0;
  812. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  813.  
  814. showNotification(`Đã hoàn thành t động đăng ${this.STATE.TOTAL_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS} chương và đã reset s ln đăng`, 'success');
  815. return;
  816. }
  817.  
  818. if (!this.STATE.AUTO_POST) {
  819. return;
  820. }
  821.  
  822. // Tự động nhấn nút Paste sau 2 giây
  823. setTimeout(() => {
  824. if (this.STATE.AUTO_POST) {
  825. this.handlePasteButton();
  826.  
  827. // Tự động nhấn nút Đăng chương sau 3 giây
  828. setTimeout(() => {
  829. if (this.STATE.AUTO_POST) {
  830. this.submitChapters();
  831. }
  832. }, 3000);
  833. }
  834. }, 2000);
  835. },
  836.  
  837. submitChapters: function() {
  838. if (!validateChapterLengths()) {
  839. return;
  840. }
  841. this.showLoading();
  842. document.querySelector('form[name="postChapForm"] button[type="submit"]').click();
  843.  
  844. if (this.STATE.AUTO_POST) {
  845. // Cập nhật số chương đã đăng
  846. this.STATE.POSTED_CHAPTERS++;
  847. localStorage.setItem('TTV_POSTED_CHAPTERS', this.STATE.POSTED_CHAPTERS.toString());
  848.  
  849. // Kiểm tra và tắt tự động đăng nếu đã đủ số chương
  850. if (this.STATE.POSTED_CHAPTERS >= this.STATE.TOTAL_CHAPTERS) {
  851. this.STATE.AUTO_POST = false;
  852. localStorage.setItem('TTV_AUTO_POST', 'false');
  853. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  854. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  855.  
  856. // Reset số lần đã đăng
  857. this.STATE.POSTED_CHAPTERS = 0;
  858. localStorage.setItem('TTV_POSTED_CHAPTERS', '0');
  859.  
  860. setTimeout(() => {
  861. showNotification(`Đã hoàn thành t động đăng ${this.STATE.TOTAL_CHAPTERS}/${this.STATE.TOTAL_CHAPTERS} chương và đã reset s ln đăng`, 'success');
  862. }, 3000);
  863. }
  864. }
  865.  
  866. setTimeout(() => this.hideLoading(), 2000);
  867. },
  868. addNewChapter: function() {
  869. if ((this.STATE.CHAP_NUMBER + 1) <= MAX_CHAPTER_POST) {
  870. this.updateChapNumber(true);
  871. const html = createChapterHTML(this.STATE.CHAP_NUMBER);
  872. jQuery('#add-chap').before(html);
  873. setupCharacterCounter();
  874. } else {
  875. showNotification(`Ch có th đăng ti đa ${MAX_CHAPTER_POST} chương mt ln`, 'warning');
  876. }
  877. },
  878. updateChapNumber: function(isAdd) {
  879. try{
  880. if (isAdd) {
  881. let maxStt =0;
  882. let maxSerial = 0;
  883. jQuery('input[name^="chap_stt"]').each(function() {
  884. const val = parseInt(jQuery(this).val()) || 0;
  885. maxStt = Math.max(maxStt, val);
  886. });
  887. jQuery('input[name^="chap_number"]').each(function() {
  888. const val = parseInt(jQuery(this).val()) || 0;
  889. maxSerial = Math.max(maxSerial, val);
  890. });
  891. const chapStt = parseInt(jQuery('.chap_stt1').val()) || 0;
  892. const chapSerial = parseInt(jQuery('.chap_serial').val()) || 0;
  893. maxStt = Math.max(maxStt, chapStt);
  894. maxSerial = Math.max(maxSerial, chapSerial);
  895. this.STATE.CHAP_STT = maxStt + 1;
  896. this.STATE.CHAP_SERIAL = maxSerial + 1;
  897. this.STATE.CHAP_NUMBER++;
  898. } else {
  899. if (this.STATE.CHAP_NUMBER > this.STATE.CHAP_NUMBER_ORIGINAL) {
  900. this.STATE.CHAP_NUMBER--;
  901. }
  902. if (this.STATE.CHAP_STT > this.STATE.CHAP_STT_ORIGINAL) {
  903. this.STATE.CHAP_STT--;
  904. }
  905. if (this.STATE.CHAP_SERIAL > this.STATE.CHAP_SERIAL_ORIGINAL) {
  906. this.STATE.CHAP_SERIAL--;
  907. }
  908. }
  909. jQuery('#chap_number').val(this.STATE.CHAP_NUMBER);
  910. jQuery('#chap_stt').val(this.STATE.CHAP_STT);
  911. jQuery('#chap_serial').val(this.STATE.CHAP_SERIAL);
  912. jQuery('#countNumberPost').text(this.STATE.CHAP_NUMBER);
  913. } catch (e) {
  914. console.log("Lỗi: " + e);
  915. }
  916. },
  917. showLoading: function() {
  918. const loading = jQuery("<div>", {
  919. class: "loading-overlay",
  920. css: {
  921. position: "fixed",
  922. inset: 0,
  923. backgroundColor: "rgba(0, 0, 0, 0.5)",
  924. display: "flex",
  925. alignItems: "center",
  926. justifyContent: "center",
  927. zIndex: 9999
  928. },
  929. html: "<div class='loading-spinner'></div>"
  930. });
  931. jQuery("body").append(loading);
  932. },
  933. hideLoading: function() {
  934. jQuery(".loading-overlay").remove();
  935. },
  936. resetAutoPost: function() { // Added reset function
  937. this.STATE.TOTAL_CHAPTERS = 0;
  938. this.STATE.POSTED_CHAPTERS = 0;
  939. localStorage.removeItem('TTV_TOTAL_CHAPTERS');
  940. localStorage.removeItem('TTV_POSTED_CHAPTERS');
  941. this.ELEMENTS.qpButtonAutoPost.text('🔄 (OFF)');
  942. this.ELEMENTS.qpButtonAutoPost.removeClass('btn-info').addClass('btn-warning');
  943. showNotification('Đã reset số lần tự động đăng', 'info');
  944. },
  945. toggleAutoMode: function() {
  946. const isAutoMode = this.ELEMENTS.qpOptionLoop.is(':checked');
  947.  
  948. if (isAutoMode) {
  949. // Hiển thị nút tự động đăng và reset, ẩn nút paste và đăng chương
  950. this.ELEMENTS.qpButtonAutoPost.show();
  951. this.ELEMENTS.qpButtonReset.show();
  952. this.ELEMENTS.qpButtonPaste.hide();
  953. this.ELEMENTS.qpButtonSubmit.hide();
  954.  
  955. showNotification('Đã bật chế độ tự động', 'info');
  956. } else {
  957. // Hiển thị nút paste và đăng chương, ẩn nút tự động đăng và reset
  958. this.ELEMENTS.qpButtonAutoPost.hide();
  959. this.ELEMENTS.qpButtonReset.hide();
  960. this.ELEMENTS.qpButtonPaste.show();
  961. this.ELEMENTS.qpButtonSubmit.show();
  962.  
  963. showNotification('Đã tắt chế độ tự động', 'info');
  964. }
  965.  
  966. // Lưu trạng thái vào localStorage
  967. localStorage.setItem('TTV_AUTO_MODE', isAutoMode.toString());
  968. }
  969. };
  970. dăngnhanhTTV.init();
  971. })();