Sada8888 commited on
Commit
bce119b
·
verified ·
1 Parent(s): 1df78e5

Update templates/editor.html

Browse files
Files changed (1) hide show
  1. templates/editor.html +99 -91
templates/editor.html CHANGED
@@ -150,7 +150,7 @@
150
  /* === END: استایل جدید برای نمایش راهنما === */
151
 
152
  #loading-placeholder { display: none; }
153
- #result-container.loading #loading-placeholder { display: flex; animation: fadeIn 0.5s; justify-content: center; align-items: center; width: 100%; flex-direction: column;}
154
  .generator-container { position: relative; width: 400px; max-width: 100%; height: 300px; border: 2px solid #38bdf8; border-radius: 20px; overflow: hidden; box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); animation: pulse 5s infinite cubic-bezier(0.4, 0, 0.6, 1); background-color: #161b22; color: #f0f6fc; }
155
  @keyframes pulse { 0% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } 50% { box-shadow: 0 0 60px rgba(56, 189, 248, 0.7); } 100% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } }
156
  .noise-layer, .sketch-layer, .building-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
@@ -164,7 +164,7 @@
164
  @keyframes dissolve-grid { 0% { opacity: 1; } 70% { opacity: 0.5; } 100% { opacity: 0; } }
165
  .particles { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(circle, rgba(56, 189, 248, 0.2) 0%, transparent 50%); animation: flow-particles 7s infinite cubic-bezier(0.4, 0, 0.6, 1); }
166
  @keyframes flow-particles { 0% { transform: translate(0, 0) scale(1); } 50% { transform: translate(10px, -15px) scale(1.05); } 100% { transform: translate(0, 0) scale(1); } }
167
- .text-overlay { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); font-size: 18px; font-weight: 700; text-shadow: 0 0 20px rgba(56, 189, 248, 0.8); animation: glow-text 7s infinite ease-in-out; font-family: var(--app-font); width: 90%; text-align: center;}
168
  @keyframes glow-text { 0% { opacity: 0.7; } 50% { opacity: 1; } 100% { opacity: 0.7; } }
169
  .progress-bar { position: absolute; bottom: 0; left: 0; width: 0%; height: 6px; background: linear-gradient(to right, #38bdf8, #bb86fc, #facc15); animation: progress 7s infinite linear; }
170
  @keyframes progress { 0% { width: 0%; } 100% { width: 100%; } }
@@ -172,7 +172,7 @@
172
  #result-container.has-content #result-grid { display: grid; }
173
  #result-grid img { width: 100%; object-fit: contain; border-radius: var(--radius-input); cursor: pointer; transition: var(--transition-smooth); box-shadow: var(--shadow-md); border: 1px solid var(--panel-border); }
174
  #result-grid img:hover { transform: scale(1.05); box-shadow: var(--shadow-lg); z-index: 10; position: relative; }
175
- #error-message { color: #d93025; text-align: center; margin-top: 1rem; display: none; font-weight: 500; }
176
  .gallery-header { display: flex; justify-content: space-between; align-items: center; }
177
  #clear-history-btn { background: none; border: 1px solid var(--panel-border); color: var(--text-secondary); padding: 0.5rem 1rem; border-radius: var(--radius-btn); cursor: pointer; display: none; align-items: center; gap: 0.5rem; font-family: var(--app-font); font-weight: 500; transition: all 0.2s; }
178
  #clear-history-btn:hover { border-color: var(--danger-color); color: var(--danger-color); }
@@ -288,7 +288,7 @@
288
  <button id="upgrade-button">⭐️ ارتقا به نسخه کامل و نامحدود</button>
289
 
290
  <button id="submit-btn" disabled>
291
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L12 8L17 10L12 12L10 3z"/></svg>
292
  <span id="btn-text">ایجاد کن</span>
293
  <div class="spinner"></div>
294
  </button>
@@ -355,8 +355,8 @@
355
  </div>
356
 
357
  <script type="module">
358
- // === START: بخش مدیریت کاربر و ارتباط با والد ===
359
- let userSubscriptionStatus = 'free'; let userFingerprint = null; let countdownInterval = null; const PREMIUM_PAGE_ID = '1149636';
360
  async function getBrowserFingerprint() { const components = [navigator.userAgent, navigator.language, screen.width + 'x' + screen.height, new Date().getTimezoneOffset()]; try { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx.fillText("a1b2c3d4e5f6g7h8i9j0", 2, 15); components.push(canvas.toDataURL()); } catch (e) { components.push("canvas-error"); } const fingerprintString = components.join('---'); let hash = 0; for (let i = 0; i < fingerprintString.length; i++) { hash = ((hash << 5) - hash) + fingerprintString.charCodeAt(i); hash |= 0; } return 'fp_' + Math.abs(hash).toString(16); }
361
  function isUserPaid(userObject) { return userObject && userObject.isLogin && userObject.accessible_pages && (userObject.accessible_pages.includes(PREMIUM_PAGE_ID) || userObject.accessible_pages.includes(parseInt(PREMIUM_PAGE_ID))); }
362
  function updateUIForSubscriptionStatus(status) { userSubscriptionStatus = status; const creditInfoDiv = document.getElementById('credit-info-section'); const upgradeBtn = document.getElementById('upgrade-button'); const subscriptionBadge = document.getElementById('subscription-status-badge'); if (status === 'paid') { subscriptionBadge.textContent = 'نسخه نامحدود'; subscriptionBadge.className = 'paid-badge'; creditInfoDiv.style.display = 'none'; upgradeBtn.style.display = 'none'; if(countdownInterval) clearInterval(countdownInterval); checkFormState(); } else { subscriptionBadge.textContent = 'نسخه رایگان'; subscriptionBadge.className = 'free-badge'; checkFreeUserCredit(); } subscriptionBadge.style.display = 'inline-block'; }
@@ -368,48 +368,72 @@
368
  // === START: منطق اصلی برنامه ===
369
  const uploadArea = document.getElementById('upload-area'); const fileInput = document.getElementById('file-input'); const previewImage = document.getElementById('preview-image-main'); const removeFileBtn = document.getElementById('remove-file-btn-main'); const promptInput = document.getElementById('prompt-input'); const submitBtn = document.getElementById('submit-btn'); const resultContainer = document.getElementById('result-container'); let resultGrid = document.getElementById('result-grid'); const errorMessage = document.getElementById('error-message'); const lightbox = document.getElementById('lightbox'); const lightboxImg = document.getElementById('lightbox-img'); const lightboxClose = document.getElementById('lightbox-close'); const lightboxDownload = document.getElementById('lightbox-download'); const lightboxNext = document.getElementById('lightbox-next'); const historyGrid = document.getElementById('history-grid'); const clearHistoryBtn = document.getElementById('clear-history-btn'); const confirmationModal = document.getElementById('confirmation-modal'); const modalMessageText = document.getElementById('modal-message-text'); const modalConfirmBtn = document.getElementById('modal-confirm-btn'); const modalCancelBtn = document.getElementById('modal-cancel-btn');
370
  let uploadedFile = null; let currentLightboxUrl = null; let currentLightboxGroup = []; let currentLightboxIndex = 0;
371
- let pollTimer = null;
372
 
373
- // --- START: IndexedDB Handler ---
374
  const dbHandler = { db: null, dbName: 'aiPhotoshopDB', storeName: 'history', initDB() { return new Promise((resolve, reject) => { const request = indexedDB.open(this.dbName, 1); request.onerror = (event) => { console.error("IndexedDB error:", event.target.error); reject("Error opening DB"); }; request.onsuccess = (event) => { this.db = event.target.result; resolve(); }; request.onupgradeneeded = (event) => { const db = event.target.result; const store = db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true }); store.createIndex('timestamp', 'timestamp', { unique: false }); }; }); }, add(item) { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readwrite'); const store = transaction.objectStore(this.storeName); const request = store.add(item); request.onsuccess = () => resolve(); request.onerror = (event) => reject(event.target.error); }); }, getAll() { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readonly'); const store = transaction.objectStore(this.storeName); const request = store.getAll(); request.onsuccess = () => { resolve(request.result.sort((a, b) => b.timestamp - a.timestamp)); }; request.onerror = (event) => reject(event.target.error); }); }, delete(id) { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readwrite'); const store = transaction.objectStore(this.storeName); const request = store.delete(id); request.onsuccess = () => resolve(); request.onerror = (event) => reject(event.target.error); }); }, clear() { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readwrite'); const store = transaction.objectStore(this.storeName); const request = store.clear(); request.onsuccess = () => resolve(); request.onerror = (event) => reject(event.target.error); }); }, deleteOlderThan(timestamp) { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readwrite'); const store = transaction.objectStore(this.storeName); const index = store.index('timestamp'); const keyRange = IDBKeyRange.upperBound(timestamp); const request = index.openCursor(keyRange); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { store.delete(cursor.primaryKey); cursor.continue(); } else { resolve(); } }; request.onerror = (event) => reject(event.target.error); }); } };
375
-
 
376
  function enhancePrompt(prompt) {
377
  const words = prompt.trim().split(/\s+/);
378
  if (words.length === 1) {
379
  const commonVerbs = ["add", "put", "make", "change", "remove", "turn", "create"];
380
  const hasVerb = commonVerbs.some(verb => prompt.toLowerCase().includes(verb));
381
- if (!hasVerb) return `Add a ${prompt}`;
382
  }
383
- return prompt;
384
  }
 
385
 
386
- // --- بررسی کلمات ممنوعه ---
387
- const forbiddenWords = ['سکس', 'سکسی', 'پورن', 'عریان', 'لخت', 'شهوانی', 'برهنه', 'آلت', 'جنسی', 'xxx', 'پورنو', 'تجاوز', 'sex', 'sexy', 'porn', 'nsfw', 'nude', 'naked', 'erotic', 'penis', 'vagina', 'hentai', 'boobs', 'ass', 'dick'];
 
 
 
 
388
  let warningTimeout;
389
- function checkContentSafety(text) { const lowerText = text.toLowerCase(); return forbiddenWords.some(word => lowerText.includes(word)); }
390
- function showContentWarning() { const warningDiv = document.getElementById('content-warning'); if (warningTimeout) clearTimeout(warningTimeout); warningDiv.classList.remove('hide'); warningDiv.classList.add('show'); warningTimeout = setTimeout(() => { warningDiv.classList.remove('show'); warningDiv.classList.add('hide'); }, 3000); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
392
  const GPU_QUOTA_ERROR_HTML = `
393
  <div class="ip-reset-guide-container">
394
  <div class="guide-header">
395
  <svg class="guide-header-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" stroke="#667eea" stroke-width="2" fill="rgba(102, 126, 234, 0.1)"/><path d="M8 12.5l2.5 2.5L16 9" stroke="#667eea" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
396
- <div><h2>یک قدم تا ویرایش تصاویر جدید</h2><p>نیازمند تغییر نقطه دستیابی</p></div>
397
  </div>
398
  <div class="guide-content">
399
  <div class="info-card">
400
  <div class="info-card-header"><svg class="info-card-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="#667eea" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg><span class="info-card-title">راه حل سریع</span></div>
401
- <p>طبق ویدیو آموزشی پایین بین نقطه دستیابی جابجا شوید تلاش مجدد بزنید تا تصویر مجدداً پردازش بشه.</p>
 
 
 
 
402
  </div>
403
  </div>
404
  <div class="video-button-container">
405
  <button id="tutorialLinkBtn" class="elegant-video-button">
406
  <svg class="elegant-video-button-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg>
407
- دیدن ویدیو آموزشی
408
  </button>
409
  </div>
410
  <div class="guide-actions">
411
- <button class="action-button back-button" id="guide-back-btn"><svg class="action-button-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>بازگشت</button>
412
- <button class="action-button retry-button" id="guide-retry-btn"><svg class="action-button-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M23 4v6h-6M1 20v-6h6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> تلاش مجدد</button>
413
  </div>
414
  </div>
415
  `;
@@ -425,28 +449,21 @@
425
  `;
426
 
427
  const convertToPNG = (file) => new Promise((resolve, reject) => { const image = new Image(); const reader = new FileReader(); image.onload = () => { const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); canvas.toBlob((blob) => { if (!blob) { reject(new Error('تبدیل به PNG ناموفق بود.')); return; } const originalName = file.name.substring(0, file.name.lastIndexOf('.')) || file.name; const pngFile = new File([blob], `${originalName}.png`, { type: 'image/png' }); resolve(pngFile); }, 'image/png', 1.0); }; image.onerror = () => reject(new Error('فایل تصویر قابل خواندن نیست.')); reader.onload = e => { image.src = e.target.result; }; reader.onerror = () => reject(new Error('خطا در خواندن فایل.')); reader.readAsDataURL(file); });
 
428
  const handleFile = async (file) => { if (!file || !file.type.startsWith('image/')) { displayError('لطفا یک فایل تصویری معتبر انتخاب کنید.'); return; } let fileToProcess = file; if (file.type !== 'image/png' && file.type !== 'image/jpeg') { try { fileToProcess = await convertToPNG(file); } catch (error) { console.error('Image conversion failed:', error); displayError('خطا در تبدیل فرمت تصویر.'); resetUploader(); return; } } uploadedFile = fileToProcess; const reader = new FileReader(); reader.onload = (e) => { previewImage.src = e.target.result; }; reader.readAsDataURL(file); uploadArea.classList.add('has-file'); checkFormState(); clearResult(); };
 
429
  const resetUploader = () => { uploadedFile = null; fileInput.value = ''; previewImage.src = ''; uploadArea.classList.remove('has-file'); checkFormState(); };
430
  const checkFormState = () => { const isReady = uploadedFile && promptInput.value.trim() !== ''; if (userSubscriptionStatus === 'free' && document.getElementById('upgrade-button').style.display === 'block') { submitBtn.disabled = true; } else { submitBtn.disabled = !isReady; } };
431
 
432
- const setLoading = (isLoading, message = 'در حال پردازش...') => {
433
- const btnSpinner = submitBtn.querySelector('.spinner'); const btnText = document.getElementById('btn-text'); const btnIcon = submitBtn.querySelector('svg');
434
- if (isLoading) {
435
- clearResult();
436
- resultContainer.classList.add('loading');
437
- btnSpinner.style.display = 'inline-block'; btnIcon.style.display = 'none'; btnText.textContent = message; submitBtn.disabled = true;
438
- if(resultGrid) resultGrid.innerHTML = ''; errorMessage.style.display = 'none';
439
- } else {
440
- resultContainer.classList.remove('loading'); btnSpinner.style.display = 'none'; btnIcon.style.display = 'inline-block'; btnText.textContent = 'ایجاد کن'; checkFormState();
441
- }
442
- };
443
 
444
  const displayResult = (imageUrls) => {
445
  if (!resultGrid) return;
446
  resultGrid.innerHTML = '';
447
  imageUrls.forEach((url) => {
448
  const img = document.createElement('img');
449
- img.src = url; img.alt = 'تصویر ویرایش شده';
 
450
  img.addEventListener('click', () => openLightbox(url, imageUrls));
451
  resultGrid.appendChild(img);
452
  });
@@ -458,9 +475,10 @@
458
  resultGrid = document.getElementById('result-grid');
459
  errorMessage.style.display = 'none';
460
  resultContainer.classList.remove('has-content');
461
- resultContainer.classList.remove('loading', 'has-error-guide');
 
462
  };
463
-
464
  const displayError = (message) => {
465
  setLoading(false);
466
  const triggers = ['پاسخ معتبری از سرور دریافت نشد', 'free generation limit', 'You have reached the free generation limit'];
@@ -468,11 +486,10 @@
468
 
469
  if (shouldShowGuide) {
470
  resultContainer.innerHTML = GPU_QUOTA_ERROR_HTML;
471
- resultContainer.classList.add('has-content', 'has-error-guide');
472
-
473
- document.getElementById('guide-back-btn').addEventListener('click', clearResult);
474
- document.getElementById('guide-retry-btn').addEventListener('click', () => submitBtn.click());
475
- document.getElementById('tutorialLinkBtn').addEventListener('click', () => {
476
  const tutorialUrl = '#/nav/online/news/getSingle/1149635/eyJpdiI6IjhHVGhPQWJwb3E0cjRXbnFWTW5BaUE9PSIsInZhbHVlIjoiS1V0dTdvT21wbXAwSXZaK1RCTG1pVXZqdlFJa1hXV1RKa2FLem9zU3pXMjd5MmlVOGc2YWY0NVdNR3h3Smp1aSIsIm1hYyI6IjY1NTA5ZDYzMjAzMTJhMGQyMWQ4NjA4ZDgyNGZjZDVlY2MyNjdiMjA2NWYzOWRjY2M4ZmVjYWRlMWNlMWQ3ODEiLCJ0YWciOiIifQ==/21135210';
477
  window.parent.postMessage({ type: 'NAVIGATE_TO_URL', url: tutorialUrl }, '*');
478
  });
@@ -493,86 +510,78 @@
493
  const handleDeleteItem = (id) => { showConfirmationModal('آیا از حذف این مورد مطمئن هستید؟', async () => { await dbHandler.delete(id); await renderHistory(); }); };
494
  const renderHistory = async () => { try { const expirationTime = 23 * 60 * 60 * 1000; const expirationTimestamp = Date.now() - expirationTime; await dbHandler.deleteOlderThan(expirationTimestamp); const history = await dbHandler.getAll(); historyGrid.innerHTML = ''; clearHistoryBtn.style.display = history.length > 0 ? 'flex' : 'none'; history.forEach((item) => { const card = document.createElement('div'); card.className = 'history-item'; const deleteBtn = document.createElement('button'); deleteBtn.className = 'history-delete-btn'; deleteBtn.title = 'حذف'; deleteBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`; deleteBtn.onclick = () => handleDeleteItem(item.id); card.appendChild(deleteBtn); const imageGrid = document.createElement('div'); imageGrid.className = 'history-item-grid'; item.urls.forEach(url => { const img = document.createElement('img'); img.src = url; img.alt = 'تصویر تاریخچه'; img.addEventListener('click', () => openLightbox(url, item.urls)); imageGrid.appendChild(img); }); card.appendChild(imageGrid); historyGrid.appendChild(card); }); } catch (error) { console.error("Could not render history:", error); historyGrid.innerHTML = '<p style="color: var(--danger-color); grid-column: 1 / -1; text-align: center;">خطا در بارگذاری تاریخچه.</p>'; } };
495
 
496
- // === START: اتصال به داکر بجای اتصال مستقیم ===
497
  const proceedWithImageGeneration = async () => {
498
- if (checkContentSafety(promptInput.value)) { showContentWarning(); return; }
 
 
 
499
  if (submitBtn.disabled) return;
500
-
501
  clearResult();
502
- setLoading(true, 'در حال آپلود و ترجمه...');
503
-
504
  try {
505
  const loadingStatusText = document.getElementById('loading-status-text');
506
  if(loadingStatusText) loadingStatusText.innerHTML = 'در حال آپلود و ترجمه...<br><small>مرحله ۱ از ۳</small>';
507
-
508
- let rawPrompt = promptInput.value.trim();
509
- let finalPrompt = enhancePrompt(rawPrompt);
510
 
511
  const formData = new FormData();
512
  formData.append('image', uploadedFile);
513
  formData.append('prompt', finalPrompt);
514
 
515
- // ارسال به سرور داکر
516
  const res = await fetch('/api/edit', {
517
  method: 'POST',
518
  body: formData
519
  });
 
520
  const data = await res.json();
521
-
522
  if (data.status === 'success') {
523
  if(loadingStatusText) loadingStatusText.innerHTML = `دستور ترجمه شد: ${data.translated}<br><small>مرحله ۲ از ۳: در حال ویرایش تصویر در سرور... (حدود ۱ دقیقه)</small>`;
524
 
525
- pollTimer = setInterval(() => checkEditorResult(data.run_id), 3000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
  } else {
527
- throw new Error('خطا در ارتباط با سرور.');
528
  }
529
  } catch (error) {
530
- displayError(`متاسفانه خطایی رخ داد: ${error.message}`);
531
- setLoading(false);
532
  }
533
  };
534
-
535
- async function checkEditorResult(run_id) {
536
- try {
537
- const res = await fetch(`/api/status/${run_id}`);
538
- const data = await res.json();
539
-
540
- if (data.status === 'ready') {
541
- clearInterval(pollTimer);
542
-
543
- const imageUrls = [data.url];
544
-
545
- if (userSubscriptionStatus === 'free') {
546
- await fetch('/api/use-credit', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) });
547
- checkFreeUserCredit();
548
- }
549
-
550
- displayResult(imageUrls);
551
- await addToHistory({ prompt: promptInput.value.trim(), urls: imageUrls });
552
- setLoading(false);
553
- }
554
- } catch (e) {
555
- console.log('Polling...', e);
556
- }
557
- }
558
- // === END: اتصال به داکر بجای اتصال مستقیم ===
559
 
560
  submitBtn.addEventListener('click', async () => {
561
  if (checkContentSafety(promptInput.value)) { showContentWarning(); return; }
562
- if (userSubscriptionStatus === 'paid') {
563
- await proceedWithImageGeneration();
564
- } else {
565
- try {
566
- const response = await fetch('/api/check-credit', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) });
567
- const result = await response.json();
568
- if (result.limit_reached) { updateUIForSubscriptionStatus('free'); return; }
569
- await proceedWithImageGeneration();
570
- } catch (err) { displayError(`خطا در سیستم اعتبار: ${err.message}`); }
571
- }
572
  });
573
 
574
- // Event Listeners
575
- document.addEventListener('DOMContentLoaded', async () => { try { await dbHandler.initDB(); await renderHistory(); } catch (error) { console.error("Failed to initialize the application:", error); displayError("خطا در راه اندازی اولیه برنامه. لطفا صفحه را رفرش کنید."); } userFingerprint = await getBrowserFingerprint(); parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*'); checkFormState(); });
576
  removeFileBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); resetUploader(); });
577
  fileInput.addEventListener('change', (e) => handleFile(e.target.files[0]));
578
  ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(e => { uploadArea.addEventListener(e, p => { p.preventDefault(); p.stopPropagation(); }); });
@@ -588,7 +597,6 @@
588
  </script>
589
 
590
  <script>
591
- // --- Header Animation Script ---
592
  document.addEventListener('DOMContentLoaded', () => { const canvas = document.getElementById('neural-network-canvas'); if (!canvas) return; const header = canvas.parentElement; const ctx = canvas.getContext('2d'); let particles = []; const particleCount = 20; const maxDistance = 100; const computedStyles = getComputedStyle(document.documentElement); const particleColor = computedStyles.getPropertyValue('--accent-primary').trim(); const lineColor = computedStyles.getPropertyValue('--text-tertiary').trim(); function resizeCanvas() { canvas.width = header.clientWidth; canvas.height = header.clientHeight; init(); } class Particle { constructor() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.vx = (Math.random() - 0.5) * 0.3; this.vy = (Math.random() - 0.5) * 0.3; this.radius = 1.2; } update() { this.x += this.vx; this.y += this.vy; if (this.x < 0 || this.x > canvas.width) this.vx *= -1; if (this.y < 0 || this.y > canvas.height) this.vy *= -1; } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = particleColor; ctx.fill(); } } function init() { particles = []; for (let i = 0; i < particleCount; i++) { particles.push(new Particle()); } } function connectParticles() { for (let i = 0; i < particles.length; i++) { for (let j = i + 1; j < particles.length; j++) { const dx = particles[i].x - particles[j].x; const dy = particles[i].y - particles[j].y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < maxDistance) { ctx.beginPath(); ctx.moveTo(particles[i].x, particles[i].y); ctx.lineTo(particles[j].x, particles[j].y); ctx.strokeStyle = lineColor; ctx.lineWidth = 0.2; ctx.globalAlpha = 1 - distance / maxDistance; ctx.stroke(); } } } ctx.globalAlpha = 1; } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(particle => { particle.update(); particle.draw(); }); connectParticles(); requestAnimationFrame(animate); } window.addEventListener('resize', resizeCanvas); resizeCanvas(); animate(); });
593
  </script>
594
  </body>
 
150
  /* === END: استایل جدید برای نمایش راهنما === */
151
 
152
  #loading-placeholder { display: none; }
153
+ #result-container.loading #loading-placeholder { display: flex; animation: fadeIn 0.5s; justify-content: center; align-items: center; width: 100%; }
154
  .generator-container { position: relative; width: 400px; max-width: 100%; height: 300px; border: 2px solid #38bdf8; border-radius: 20px; overflow: hidden; box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); animation: pulse 5s infinite cubic-bezier(0.4, 0, 0.6, 1); background-color: #161b22; color: #f0f6fc; }
155
  @keyframes pulse { 0% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } 50% { box-shadow: 0 0 60px rgba(56, 189, 248, 0.7); } 100% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } }
156
  .noise-layer, .sketch-layer, .building-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
 
164
  @keyframes dissolve-grid { 0% { opacity: 1; } 70% { opacity: 0.5; } 100% { opacity: 0; } }
165
  .particles { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(circle, rgba(56, 189, 248, 0.2) 0%, transparent 50%); animation: flow-particles 7s infinite cubic-bezier(0.4, 0, 0.6, 1); }
166
  @keyframes flow-particles { 0% { transform: translate(0, 0) scale(1); } 50% { transform: translate(10px, -15px) scale(1.05); } 100% { transform: translate(0, 0) scale(1); } }
167
+ .text-overlay { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); font-size: 24px; font-weight: 700; text-shadow: 0 0 20px rgba(56, 189, 248, 0.8); animation: glow-text 7s infinite ease-in-out; font-family: var(--app-font); }
168
  @keyframes glow-text { 0% { opacity: 0.7; } 50% { opacity: 1; } 100% { opacity: 0.7; } }
169
  .progress-bar { position: absolute; bottom: 0; left: 0; width: 0%; height: 6px; background: linear-gradient(to right, #38bdf8, #bb86fc, #facc15); animation: progress 7s infinite linear; }
170
  @keyframes progress { 0% { width: 0%; } 100% { width: 100%; } }
 
172
  #result-container.has-content #result-grid { display: grid; }
173
  #result-grid img { width: 100%; object-fit: contain; border-radius: var(--radius-input); cursor: pointer; transition: var(--transition-smooth); box-shadow: var(--shadow-md); border: 1px solid var(--panel-border); }
174
  #result-grid img:hover { transform: scale(1.05); box-shadow: var(--shadow-lg); z-index: 10; position: relative; }
175
+ #error-message { color: var(--danger-color); text-align: center; margin-top: 1rem; display: none; font-weight: 500; }
176
  .gallery-header { display: flex; justify-content: space-between; align-items: center; }
177
  #clear-history-btn { background: none; border: 1px solid var(--panel-border); color: var(--text-secondary); padding: 0.5rem 1rem; border-radius: var(--radius-btn); cursor: pointer; display: none; align-items: center; gap: 0.5rem; font-family: var(--app-font); font-weight: 500; transition: all 0.2s; }
178
  #clear-history-btn:hover { border-color: var(--danger-color); color: var(--danger-color); }
 
288
  <button id="upgrade-button">⭐️ ارتقا به نسخه کامل و نامحدود</button>
289
 
290
  <button id="submit-btn" disabled>
291
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/></svg>
292
  <span id="btn-text">ایجاد کن</span>
293
  <div class="spinner"></div>
294
  </button>
 
355
  </div>
356
 
357
  <script type="module">
358
+ // === START: بخش مدیریت کاربر و ارتباط با والد (بدون تغییر) ===
359
+ let userSubscriptionStatus = 'free'; let userFingerprint = null; let countdownInterval = null; let pollTimer = null; const PREMIUM_PAGE_ID = '1149636';
360
  async function getBrowserFingerprint() { const components = [navigator.userAgent, navigator.language, screen.width + 'x' + screen.height, new Date().getTimezoneOffset()]; try { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx.fillText("a1b2c3d4e5f6g7h8i9j0", 2, 15); components.push(canvas.toDataURL()); } catch (e) { components.push("canvas-error"); } const fingerprintString = components.join('---'); let hash = 0; for (let i = 0; i < fingerprintString.length; i++) { hash = ((hash << 5) - hash) + fingerprintString.charCodeAt(i); hash |= 0; } return 'fp_' + Math.abs(hash).toString(16); }
361
  function isUserPaid(userObject) { return userObject && userObject.isLogin && userObject.accessible_pages && (userObject.accessible_pages.includes(PREMIUM_PAGE_ID) || userObject.accessible_pages.includes(parseInt(PREMIUM_PAGE_ID))); }
362
  function updateUIForSubscriptionStatus(status) { userSubscriptionStatus = status; const creditInfoDiv = document.getElementById('credit-info-section'); const upgradeBtn = document.getElementById('upgrade-button'); const subscriptionBadge = document.getElementById('subscription-status-badge'); if (status === 'paid') { subscriptionBadge.textContent = 'نسخه نامحدود'; subscriptionBadge.className = 'paid-badge'; creditInfoDiv.style.display = 'none'; upgradeBtn.style.display = 'none'; if(countdownInterval) clearInterval(countdownInterval); checkFormState(); } else { subscriptionBadge.textContent = 'نسخه رایگان'; subscriptionBadge.className = 'free-badge'; checkFreeUserCredit(); } subscriptionBadge.style.display = 'inline-block'; }
 
368
  // === START: منطق اصلی برنامه ===
369
  const uploadArea = document.getElementById('upload-area'); const fileInput = document.getElementById('file-input'); const previewImage = document.getElementById('preview-image-main'); const removeFileBtn = document.getElementById('remove-file-btn-main'); const promptInput = document.getElementById('prompt-input'); const submitBtn = document.getElementById('submit-btn'); const resultContainer = document.getElementById('result-container'); let resultGrid = document.getElementById('result-grid'); const errorMessage = document.getElementById('error-message'); const lightbox = document.getElementById('lightbox'); const lightboxImg = document.getElementById('lightbox-img'); const lightboxClose = document.getElementById('lightbox-close'); const lightboxDownload = document.getElementById('lightbox-download'); const lightboxNext = document.getElementById('lightbox-next'); const historyGrid = document.getElementById('history-grid'); const clearHistoryBtn = document.getElementById('clear-history-btn'); const confirmationModal = document.getElementById('confirmation-modal'); const modalMessageText = document.getElementById('modal-message-text'); const modalConfirmBtn = document.getElementById('modal-confirm-btn'); const modalCancelBtn = document.getElementById('modal-cancel-btn');
370
  let uploadedFile = null; let currentLightboxUrl = null; let currentLightboxGroup = []; let currentLightboxIndex = 0;
 
371
 
372
+ // --- START: IndexedDB Handler (بدون تغییر) ---
373
  const dbHandler = { db: null, dbName: 'aiPhotoshopDB', storeName: 'history', initDB() { return new Promise((resolve, reject) => { const request = indexedDB.open(this.dbName, 1); request.onerror = (event) => { console.error("IndexedDB error:", event.target.error); reject("Error opening DB"); }; request.onsuccess = (event) => { this.db = event.target.result; resolve(); }; request.onupgradeneeded = (event) => { const db = event.target.result; const store = db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true }); store.createIndex('timestamp', 'timestamp', { unique: false }); }; }); }, add(item) { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readwrite'); const store = transaction.objectStore(this.storeName); const request = store.add(item); request.onsuccess = () => resolve(); request.onerror = (event) => reject(event.target.error); }); }, getAll() { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readonly'); const store = transaction.objectStore(this.storeName); const request = store.getAll(); request.onsuccess = () => { resolve(request.result.sort((a, b) => b.timestamp - a.timestamp)); }; request.onerror = (event) => reject(event.target.error); }); }, delete(id) { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readwrite'); const store = transaction.objectStore(this.storeName); const request = store.delete(id); request.onsuccess = () => resolve(); request.onerror = (event) => reject(event.target.error); }); }, clear() { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readwrite'); const store = transaction.objectStore(this.storeName); const request = store.clear(); request.onsuccess = () => resolve(); request.onerror = (event) => reject(event.target.error); }); }, deleteOlderThan(timestamp) { return new Promise((resolve, reject) => { const transaction = this.db.transaction([this.storeName], 'readwrite'); const store = transaction.objectStore(this.storeName); const index = store.index('timestamp'); const keyRange = IDBKeyRange.upperBound(timestamp); const request = index.openCursor(keyRange); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { store.delete(cursor.primaryKey); cursor.continue(); } else { resolve(); } }; request.onerror = (event) => reject(event.target.error); }); } };
374
+
375
+ // <<< این تابع برای بهبود دستور در فرانت اند حفظ شده >>>
376
  function enhancePrompt(prompt) {
377
  const words = prompt.trim().split(/\s+/);
378
  if (words.length === 1) {
379
  const commonVerbs = ["add", "put", "make", "change", "remove", "turn", "create"];
380
  const hasVerb = commonVerbs.some(verb => prompt.toLowerCase().includes(verb));
381
+ if (!hasVerb) { return `Add a ${prompt}`; }
382
  }
383
+ return prompt;
384
  }
385
+ // === END: توابع جدید ===
386
 
387
+ // === START: لیست کلمات ممنوعه و تابع بررسی ===
388
+ const forbiddenWords = [
389
+ 'سکس', 'سکسی', 'پورن', 'عریان', 'لخت', 'شهوانی', 'برهنه', 'آلت', 'جنسی', 'xxx', 'پورنو', 'تجاوز',
390
+ 'sex', 'sexy', 'porn', 'nsfw', 'nude', 'naked', 'erotic', 'penis', 'vagina', 'xxx', 'hentai', 'boobs', 'ass', 'dick'
391
+ ];
392
+
393
  let warningTimeout;
394
+
395
+ function checkContentSafety(text) {
396
+ const lowerText = text.toLowerCase();
397
+ return forbiddenWords.some(word => lowerText.includes(word));
398
+ }
399
+
400
+ function showContentWarning() {
401
+ const warningDiv = document.getElementById('content-warning');
402
+ if (warningTimeout) clearTimeout(warningTimeout);
403
+ warningDiv.classList.remove('hide');
404
+ warningDiv.classList.add('show');
405
+ warningTimeout = setTimeout(() => {
406
+ warningDiv.classList.remove('show');
407
+ warningDiv.classList.add('hide');
408
+ }, 3000);
409
+ }
410
+ // === END: لیست کلمات ممنوعه و تابع بررسی ===
411
 
412
  const GPU_QUOTA_ERROR_HTML = `
413
  <div class="ip-reset-guide-container">
414
  <div class="guide-header">
415
  <svg class="guide-header-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" stroke="#667eea" stroke-width="2" fill="rgba(102, 126, 234, 0.1)"/><path d="M8 12.5l2.5 2.5L16 9" stroke="#667eea" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
416
+ <div><h2>یک قدم تا ساخت تصاویر جدید</h2><p>نیازمند تغییر نقطه دستیابی</p></div>
417
  </div>
418
  <div class="guide-content">
419
  <div class="info-card">
420
  <div class="info-card-header"><svg class="info-card-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="#667eea" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg><span class="info-card-title">راه حل سریع</span></div>
421
+ <p>طبق ویدیو آموزشی پایین بین نقطه دستیابی جابجا شوید تلاش مجدد بزنید تا تصاویر مجدداً تولید بشه.</p>
422
+ </div>
423
+ <div class="summary-section">
424
+ <div class="summary-header"><svg class="summary-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9 12l2 2 4-4" stroke="#2f5a33" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><circle cx="12" cy="12" r="10" stroke="#2f5a33" stroke-width="2"></circle></svg><span class="summary-title">خلاصه راهنما</span></div>
425
+ <div class="summary-text">هربار که این صفحه را مشاهده کردید: از اینترنت سیم‌کارت استفاده کنید، VPN را خاموش کرده و طبق ویدیو آموزشی پایین نقطه دستیابی رو تغییر دهید. «تلاش مجدد» کلیک کنید. با این روش ساده می‌توانید به صورت نامحدود تصویر بسازید! ☘️</div>
426
  </div>
427
  </div>
428
  <div class="video-button-container">
429
  <button id="tutorialLinkBtn" class="elegant-video-button">
430
  <svg class="elegant-video-button-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg>
431
+ دیدن ویدیو آموزشی استفاده نامحدود
432
  </button>
433
  </div>
434
  <div class="guide-actions">
435
+ <button class="action-button back-button"><svg class="action-button-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>بازگشت</button>
436
+ <button class="action-button retry-button"><svg class="action-button-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M23 4v6h-6M1 20v-6h6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg> تلاش مجدد</button>
437
  </div>
438
  </div>
439
  `;
 
449
  `;
450
 
451
  const convertToPNG = (file) => new Promise((resolve, reject) => { const image = new Image(); const reader = new FileReader(); image.onload = () => { const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); canvas.toBlob((blob) => { if (!blob) { reject(new Error('تبدیل به PNG ناموفق بود.')); return; } const originalName = file.name.substring(0, file.name.lastIndexOf('.')) || file.name; const pngFile = new File([blob], `${originalName}.png`, { type: 'image/png' }); resolve(pngFile); }, 'image/png', 1.0); }; image.onerror = () => reject(new Error('فایل تصویر قابل خواندن نیست.')); reader.onload = e => { image.src = e.target.result; }; reader.onerror = () => reject(new Error('خطا در خواندن فایل.')); reader.readAsDataURL(file); });
452
+
453
  const handleFile = async (file) => { if (!file || !file.type.startsWith('image/')) { displayError('لطفا یک فایل تصویری معتبر انتخاب کنید.'); return; } let fileToProcess = file; if (file.type !== 'image/png' && file.type !== 'image/jpeg') { try { fileToProcess = await convertToPNG(file); } catch (error) { console.error('Image conversion failed:', error); displayError('خطا در تبدیل فرمت تصویر.'); resetUploader(); return; } } uploadedFile = fileToProcess; const reader = new FileReader(); reader.onload = (e) => { previewImage.src = e.target.result; }; reader.readAsDataURL(file); uploadArea.classList.add('has-file'); checkFormState(); clearResult(); };
454
+
455
  const resetUploader = () => { uploadedFile = null; fileInput.value = ''; previewImage.src = ''; uploadArea.classList.remove('has-file'); checkFormState(); };
456
  const checkFormState = () => { const isReady = uploadedFile && promptInput.value.trim() !== ''; if (userSubscriptionStatus === 'free' && document.getElementById('upgrade-button').style.display === 'block') { submitBtn.disabled = true; } else { submitBtn.disabled = !isReady; } };
457
 
458
+ const setLoading = (isLoading) => { const btnSpinner = submitBtn.querySelector('.spinner'); const btnText = document.getElementById('btn-text'); const btnIcon = submitBtn.querySelector('svg'); if (isLoading) { resultContainer.classList.remove('has-content'); resultContainer.classList.add('loading'); btnSpinner.style.display = 'inline-block'; btnIcon.style.display = 'none'; btnText.textContent = 'در حال پردازش...'; submitBtn.disabled = true; if(resultGrid) resultGrid.innerHTML = ''; errorMessage.style.display = 'none'; } else { resultContainer.classList.remove('loading'); btnSpinner.style.display = 'none'; btnIcon.style.display = 'inline-block'; btnText.textContent = 'ایجاد کن'; checkFormState(); } };
 
 
 
 
 
 
 
 
 
 
459
 
460
  const displayResult = (imageUrls) => {
461
  if (!resultGrid) return;
462
  resultGrid.innerHTML = '';
463
  imageUrls.forEach((url) => {
464
  const img = document.createElement('img');
465
+ img.src = url;
466
+ img.alt = 'تصویر ویرایش شده';
467
  img.addEventListener('click', () => openLightbox(url, imageUrls));
468
  resultGrid.appendChild(img);
469
  });
 
475
  resultGrid = document.getElementById('result-grid');
476
  errorMessage.style.display = 'none';
477
  resultContainer.classList.remove('has-content');
478
+ resultContainer.classList.remove('loading');
479
+ if (pollTimer) clearInterval(pollTimer);
480
  };
481
+
482
  const displayError = (message) => {
483
  setLoading(false);
484
  const triggers = ['پاسخ معتبری از سرور دریافت نشد', 'free generation limit', 'You have reached the free generation limit'];
 
486
 
487
  if (shouldShowGuide) {
488
  resultContainer.innerHTML = GPU_QUOTA_ERROR_HTML;
489
+ resultContainer.classList.add('has-content');
490
+ resultContainer.querySelector('.back-button').addEventListener('click', clearResult);
491
+ resultContainer.querySelector('.retry-button').addEventListener('click', () => submitBtn.click());
492
+ resultContainer.querySelector('#tutorialLinkBtn').addEventListener('click', () => {
 
493
  const tutorialUrl = '#/nav/online/news/getSingle/1149635/eyJpdiI6IjhHVGhPQWJwb3E0cjRXbnFWTW5BaUE9PSIsInZhbHVlIjoiS1V0dTdvT21wbXAwSXZaK1RCTG1pVXZqdlFJa1hXV1RKa2FLem9zU3pXMjd5MmlVOGc2YWY0NVdNR3h3Smp1aSIsIm1hYyI6IjY1NTA5ZDYzMjAzMTJhMGQyMWQ4NjA4ZDgyNGZjZDVlY2MyNjdiMjA2NWYzOWRjY2M4ZmVjYWRlMWNlMWQ3ODEiLCJ0YWciOiIifQ==/21135210';
494
  window.parent.postMessage({ type: 'NAVIGATE_TO_URL', url: tutorialUrl }, '*');
495
  });
 
510
  const handleDeleteItem = (id) => { showConfirmationModal('آیا از حذف این مورد مطمئن هستید؟', async () => { await dbHandler.delete(id); await renderHistory(); }); };
511
  const renderHistory = async () => { try { const expirationTime = 23 * 60 * 60 * 1000; const expirationTimestamp = Date.now() - expirationTime; await dbHandler.deleteOlderThan(expirationTimestamp); const history = await dbHandler.getAll(); historyGrid.innerHTML = ''; clearHistoryBtn.style.display = history.length > 0 ? 'flex' : 'none'; history.forEach((item) => { const card = document.createElement('div'); card.className = 'history-item'; const deleteBtn = document.createElement('button'); deleteBtn.className = 'history-delete-btn'; deleteBtn.title = 'حذف'; deleteBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`; deleteBtn.onclick = () => handleDeleteItem(item.id); card.appendChild(deleteBtn); const imageGrid = document.createElement('div'); imageGrid.className = 'history-item-grid'; item.urls.forEach(url => { const img = document.createElement('img'); img.src = url; img.alt = 'تصویر تاریخچه'; img.addEventListener('click', () => openLightbox(url, item.urls)); imageGrid.appendChild(img); }); card.appendChild(imageGrid); historyGrid.appendChild(card); }); } catch (error) { console.error("Could not render history:", error); historyGrid.innerHTML = '<p style="color: var(--danger-color); grid-column: 1 / -1; text-align: center;">خطا در بارگذاری تاریخچه.</p>'; } };
512
 
513
+ // === START: اتصال به بک‌اند داکر (تغییر کلیدی) ===
514
  const proceedWithImageGeneration = async () => {
515
+ if (checkContentSafety(promptInput.value)) {
516
+ showContentWarning();
517
+ return;
518
+ }
519
  if (submitBtn.disabled) return;
 
520
  clearResult();
521
+ setLoading(true);
522
+
523
  try {
524
  const loadingStatusText = document.getElementById('loading-status-text');
525
  if(loadingStatusText) loadingStatusText.innerHTML = 'در حال آپلود و ترجمه...<br><small>مرحله ۱ از ۳</small>';
526
+
527
+ let finalPrompt = enhancePrompt(promptInput.value.trim());
 
528
 
529
  const formData = new FormData();
530
  formData.append('image', uploadedFile);
531
  formData.append('prompt', finalPrompt);
532
 
533
+ // ارسال به سرور داکر خودمان به جای اتصال مستقیم گرادیو
534
  const res = await fetch('/api/edit', {
535
  method: 'POST',
536
  body: formData
537
  });
538
+
539
  const data = await res.json();
540
+
541
  if (data.status === 'success') {
542
  if(loadingStatusText) loadingStatusText.innerHTML = `دستور ترجمه شد: ${data.translated}<br><small>مرحله ۲ از ۳: در حال ویرایش تصویر در سرور... (حدود ۱ دقیقه)</small>`;
543
 
544
+ // بررسی مداوم برای دریافت عکس از گیت هاب
545
+ pollTimer = setInterval(async () => {
546
+ try {
547
+ const statusRes = await fetch(`/api/status/${data.run_id}`);
548
+ const statusData = await statusRes.json();
549
+
550
+ if (statusData.status === 'ready') {
551
+ clearInterval(pollTimer);
552
+
553
+ // کسر اعتبار کاربر رایگان
554
+ if (userSubscriptionStatus === 'free') {
555
+ await fetch('/api/use-credit', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) });
556
+ checkFreeUserCredit();
557
+ }
558
+
559
+ setLoading(false);
560
+ // فرستادن لینک عکس برگشتی به گالری و نمایش
561
+ displayResult([statusData.url]);
562
+ await addToHistory({ prompt: promptInput.value.trim(), urls: [statusData.url] });
563
+ }
564
+ } catch (pollErr) {
565
+ console.log('Polling...', pollErr);
566
+ }
567
+ }, 3000);
568
  } else {
569
+ throw new Error(data.message || 'خطا در ارسال به سرور گیت‌هاب!');
570
  }
571
  } catch (error) {
572
+ const errorMessageText = error.message || "خطای نامشخصی رخ داد.";
573
+ displayError(`متاسفانه خطایی رخ داد: ${errorMessageText}`);
574
  }
575
  };
576
+ // === END: اتصال به بک‌اند داکر ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577
 
578
  submitBtn.addEventListener('click', async () => {
579
  if (checkContentSafety(promptInput.value)) { showContentWarning(); return; }
580
+ if (userSubscriptionStatus === 'paid') { await proceedWithImageGeneration(); }
581
+ else { try { const response = await fetch('/api/check-credit', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ fingerprint: userFingerprint }) }); const result = await response.json(); if (result.limit_reached) { updateUIForSubscriptionStatus('free'); return; } await proceedWithImageGeneration(); } catch (err) { displayError(`خطا در سیستم اعتبار: ${err.message}`); } }
 
 
 
 
 
 
 
 
582
  });
583
 
584
+ document.addEventListener('DOMContentLoaded', async () => { try { await dbHandler.initDB(); await renderHistory(); } catch (error) { console.error("Failed to init", error); displayError("خطا در راه‌اندازی اولیه برنامه."); } userFingerprint = await getBrowserFingerprint(); parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*'); checkFormState(); });
 
585
  removeFileBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); resetUploader(); });
586
  fileInput.addEventListener('change', (e) => handleFile(e.target.files[0]));
587
  ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(e => { uploadArea.addEventListener(e, p => { p.preventDefault(); p.stopPropagation(); }); });
 
597
  </script>
598
 
599
  <script>
 
600
  document.addEventListener('DOMContentLoaded', () => { const canvas = document.getElementById('neural-network-canvas'); if (!canvas) return; const header = canvas.parentElement; const ctx = canvas.getContext('2d'); let particles = []; const particleCount = 20; const maxDistance = 100; const computedStyles = getComputedStyle(document.documentElement); const particleColor = computedStyles.getPropertyValue('--accent-primary').trim(); const lineColor = computedStyles.getPropertyValue('--text-tertiary').trim(); function resizeCanvas() { canvas.width = header.clientWidth; canvas.height = header.clientHeight; init(); } class Particle { constructor() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.vx = (Math.random() - 0.5) * 0.3; this.vy = (Math.random() - 0.5) * 0.3; this.radius = 1.2; } update() { this.x += this.vx; this.y += this.vy; if (this.x < 0 || this.x > canvas.width) this.vx *= -1; if (this.y < 0 || this.y > canvas.height) this.vy *= -1; } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = particleColor; ctx.fill(); } } function init() { particles = []; for (let i = 0; i < particleCount; i++) { particles.push(new Particle()); } } function connectParticles() { for (let i = 0; i < particles.length; i++) { for (let j = i + 1; j < particles.length; j++) { const dx = particles[i].x - particles[j].x; const dy = particles[i].y - particles[j].y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < maxDistance) { ctx.beginPath(); ctx.moveTo(particles[i].x, particles[i].y); ctx.lineTo(particles[j].x, particles[j].y); ctx.strokeStyle = lineColor; ctx.lineWidth = 0.2; ctx.globalAlpha = 1 - distance / maxDistance; ctx.stroke(); } } } ctx.globalAlpha = 1; } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(particle => { particle.update(); particle.draw(); }); connectParticles(); requestAnimationFrame(animate); } window.addEventListener('resize', resizeCanvas); resizeCanvas(); animate(); });
601
  </script>
602
  </body>