Eluza133 commited on
Commit
b12fca4
·
verified ·
1 Parent(s): cad91cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -32
app.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import flask
2
  from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify, Response
3
  from flask_caching import Cache
@@ -20,8 +22,9 @@ DATA_FILE = 'cloudeng_data_tma.json'
20
  REPO_ID = "Eluza133/Z1e1u"
21
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
22
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
23
- TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6750208873:AAE2hvPlJ99dBdhGa_Brre0IIpUdOvXxHt4")
24
  ADMIN_TELEGRAM_ID = os.getenv("ADMIN_TELEGRAM_ID", "YOUR_ADMIN_TELEGRAM_USER_ID_HERE")
 
25
 
26
  ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
27
  ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "zeusadminpass")
@@ -238,7 +241,6 @@ def load_data():
238
 
239
  return data
240
  except Exception as e:
241
- logging.error(f"Error loading data: {e}")
242
  return {'users': {}}
243
 
244
  def save_data(data):
@@ -248,7 +250,6 @@ def save_data(data):
248
  upload_db_to_hf()
249
  cache.clear()
250
  except Exception as e:
251
- logging.error(f"Error saving data: {e}")
252
  raise
253
 
254
  def upload_db_to_hf():
@@ -261,7 +262,7 @@ def upload_db_to_hf():
261
  commit_message=f"Backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
262
  )
263
  except Exception as e:
264
- logging.error(f"Error uploading database: {e}")
265
 
266
  def download_db_from_hf():
267
  if not HF_TOKEN_READ:
@@ -277,7 +278,6 @@ def download_db_from_hf():
277
  if not os.path.exists(DATA_FILE):
278
  with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}}, f)
279
  except Exception as e:
280
- logging.error(f"Error downloading database: {e}")
281
  if not os.path.exists(DATA_FILE):
282
  with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}}, f)
283
 
@@ -389,7 +389,6 @@ def auth_via_telegram():
389
  try:
390
  save_data(data)
391
  except Exception as e:
392
- logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")
393
  return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500
394
 
395
  session['telegram_user_id'] = tma_user_id_str
@@ -399,7 +398,6 @@ def auth_via_telegram():
399
  return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
400
 
401
  except Exception as e:
402
- logging.error(f"Error in auth_via_telegram: {e}")
403
  return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
404
 
405
  TMA_DASHBOARD_HTML_TEMPLATE = '''
@@ -416,9 +414,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
416
  {% endif %}
417
  </p>
418
  {% if not user_data.unlimited_storage %}
419
- <form method="POST" action="{{ url_for('tma_buy_unlimited') }}" style="display: contents;">
420
- <button type="submit" class="btn" style="background: var(--secondary); margin-left: 0; margin-bottom: 10px;">Купить безлимит за 20 ⭐️</button>
421
- </form>
422
  {% endif %}
423
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
424
  {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
@@ -519,10 +515,8 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
519
 
520
  function tmaDownloadFile(downloadUrl, filename) {
521
  if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) {
522
- console.log(`Attempting TMA download for: ${filename} via URL: ${downloadUrl}`);
523
  Telegram.WebApp.openLink(downloadUrl);
524
  } else {
525
- console.warn("Telegram.WebApp.openLink not available, or not in TMA environment. Attempting fallback download.");
526
  const link = document.createElement('a');
527
  link.href = downloadUrl;
528
  link.setAttribute('download', filename);
@@ -556,6 +550,16 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
556
  });
557
  }
558
  document.getElementById('logout-btn').addEventListener('click', function(e) { e.preventDefault(); window.location.href = "{{ url_for('tma_logout') }}"; });
 
 
 
 
 
 
 
 
 
 
559
  </script></body></html>
560
  '''
561
 
@@ -658,7 +662,7 @@ def tma_dashboard():
658
  else:
659
  errors_list.append(f"Ошибка добавления метаданных для {original_filename}.")
660
  try: api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
661
- except Exception as del_err: logging.error(f"Failed to delete orphaned file {hf_path} from HF Hub: {del_err}")
662
  except Exception as e:
663
  errors_list.append(f"Ошибка загрузки файла {original_filename}: {e}")
664
  finally:
@@ -692,7 +696,8 @@ def tma_dashboard():
692
  breadcrumbs=breadcrumbs, repo_id_js=REPO_ID, HF_TOKEN_READ_js=HF_TOKEN_READ,
693
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
694
  is_tma_user_admin_flag=is_admin_tma(),
695
- user_data=user_data, storage_used_formatted=storage_used_formatted)
 
696
 
697
 
698
  @app.route('/tma_buy_unlimited', methods=['POST'])
@@ -709,16 +714,8 @@ def tma_buy_unlimited():
709
  session.clear()
710
  flash('Пользователь не найден.', 'error')
711
  return redirect(url_for('tma_entry_page'))
712
-
713
- if str(tma_user_id) == str(ADMIN_TELEGRAM_ID):
714
- user_data['unlimited_storage'] = True
715
- try:
716
- save_data(data)
717
- flash('ВНИМАНИЕ (АДМИН): Безлимитное хранилище активировано для этого пользователя.', 'success')
718
- except Exception as e:
719
- flash(f'Ошибка сохранения данных при активации безлимита: {e}', 'error')
720
- else:
721
- flash('Для получения безлимитного хранилища оплатите 20 Telegram Stars через официальный платеж. (Текущая версия: обратитесь к администратору для активации).', 'info')
722
 
723
  return redirect(url_for('tma_dashboard'))
724
 
@@ -833,10 +830,8 @@ def download_tma(file_id):
833
  return resp
834
 
835
  except requests.exceptions.RequestException as e:
836
- logging.error(f"Error downloading file {original_filename} (ID: {file_id}) from HF: {e}")
837
  flash(f'Ошибка скачивания файла: {e}', 'error')
838
  except Exception as e:
839
- logging.error(f"Internal error during download {original_filename} (ID: {file_id}): {e}")
840
  flash(f'Внутренняя ошибка при скачивании: {e}', 'error')
841
  return redirect(redirect_url)
842
 
@@ -1201,7 +1196,6 @@ def admin_delete_user(tma_user_id_str):
1201
  except hf_utils.HfHubHTTPError as e:
1202
  if e.response.status_code != 404:
1203
  flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1204
- logging.info(f"Folder {user_folder_path_on_hf} not found on HF Hub for user {tma_user_id_str} or was already empty, proceeding with DB deletion.")
1205
  except Exception as e:
1206
  flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1207
 
@@ -1260,11 +1254,16 @@ def admin_delete_file(tma_user_id_str_form, file_id):
1260
 
1261
 
1262
  if __name__ == '__main__':
1263
- if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")
1264
- if not HF_TOKEN_READ: logging.warning("HF_TOKEN_READ is not set. Using HF_TOKEN. Downloads/previews might fail for private repos if HF_TOKEN also lacks read.")
1265
- if ADMIN_TELEGRAM_ID == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE": logging.warning("ADMIN_TELEGRAM_ID is not set. TMA admin features might not work as expected for specific users.")
1266
- if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
1267
- logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")
 
 
 
 
 
1268
 
1269
 
1270
  if HF_TOKEN_WRITE:
 
1
+ --- START OF FILE app (36).py ---
2
+
3
  import flask
4
  from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify, Response
5
  from flask_caching import Cache
 
22
  REPO_ID = "Eluza133/Z1e1u"
23
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
24
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
25
+ TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6750208873:AAE2hvPlS99dBdhGa_Brre0IIpUdOvXxHt4")
26
  ADMIN_TELEGRAM_ID = os.getenv("ADMIN_TELEGRAM_ID", "YOUR_ADMIN_TELEGRAM_USER_ID_HERE")
27
+ BOT_USERNAME = os.getenv("BOT_USERNAME", "ZeusCloudBot")
28
 
29
  ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
30
  ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "zeusadminpass")
 
241
 
242
  return data
243
  except Exception as e:
 
244
  return {'users': {}}
245
 
246
  def save_data(data):
 
250
  upload_db_to_hf()
251
  cache.clear()
252
  except Exception as e:
 
253
  raise
254
 
255
  def upload_db_to_hf():
 
262
  commit_message=f"Backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
263
  )
264
  except Exception as e:
265
+ pass
266
 
267
  def download_db_from_hf():
268
  if not HF_TOKEN_READ:
 
278
  if not os.path.exists(DATA_FILE):
279
  with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}}, f)
280
  except Exception as e:
 
281
  if not os.path.exists(DATA_FILE):
282
  with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}}, f)
283
 
 
389
  try:
390
  save_data(data)
391
  except Exception as e:
 
392
  return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500
393
 
394
  session['telegram_user_id'] = tma_user_id_str
 
398
  return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
399
 
400
  except Exception as e:
 
401
  return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
402
 
403
  TMA_DASHBOARD_HTML_TEMPLATE = '''
 
414
  {% endif %}
415
  </p>
416
  {% if not user_data.unlimited_storage %}
417
+ <button type="button" class="btn" style="background: var(--secondary); margin-left: 0; margin-bottom: 10px;" onclick="buyUnlimitedStorage('{{ tma_user_id }}', '{{ bot_username }}')">Купить безлимит за 2000 ⭐️</button>
 
 
418
  {% endif %}
419
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
420
  {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
 
515
 
516
  function tmaDownloadFile(downloadUrl, filename) {
517
  if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) {
 
518
  Telegram.WebApp.openLink(downloadUrl);
519
  } else {
 
520
  const link = document.createElement('a');
521
  link.href = downloadUrl;
522
  link.setAttribute('download', filename);
 
550
  });
551
  }
552
  document.getElementById('logout-btn').addEventListener('click', function(e) { e.preventDefault(); window.location.href = "{{ url_for('tma_logout') }}"; });
553
+
554
+ function buyUnlimitedStorage(userId, botUsername) {
555
+ if (!Telegram.WebApp.openLink) {
556
+ Telegram.WebApp.showAlert('Telegram Web App Link opening is not available.');
557
+ return;
558
+ }
559
+ const deepLink = `https://t.me/${botUsername}?start=buy_unlimited_stars_${userId}`;
560
+ Telegram.WebApp.openLink(deepLink);
561
+ Telegram.WebApp.showAlert('Вас перенаправит в чат с ботом для оплаты. После оплаты свяжитесь с администратором для актива��ии безлимитного хранилища.');
562
+ }
563
  </script></body></html>
564
  '''
565
 
 
662
  else:
663
  errors_list.append(f"Ошибка добавления метаданных для {original_filename}.")
664
  try: api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
665
+ except Exception as del_err: pass
666
  except Exception as e:
667
  errors_list.append(f"Ошибка загрузки файла {original_filename}: {e}")
668
  finally:
 
696
  breadcrumbs=breadcrumbs, repo_id_js=REPO_ID, HF_TOKEN_READ_js=HF_TOKEN_READ,
697
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
698
  is_tma_user_admin_flag=is_admin_tma(),
699
+ user_data=user_data, storage_used_formatted=storage_used_formatted,
700
+ tma_user_id=tma_user_id, bot_username=BOT_USERNAME)
701
 
702
 
703
  @app.route('/tma_buy_unlimited', methods=['POST'])
 
714
  session.clear()
715
  flash('Пользователь не найден.', 'error')
716
  return redirect(url_for('tma_entry_page'))
717
+
718
+ flash('Для получения безлимитного хранилища оплатите 2000 Telegram Stars через бота. После оплаты свяжитесь с администратором для активации.', 'info')
 
 
 
 
 
 
 
 
719
 
720
  return redirect(url_for('tma_dashboard'))
721
 
 
830
  return resp
831
 
832
  except requests.exceptions.RequestException as e:
 
833
  flash(f'Ошибка скачивания файла: {e}', 'error')
834
  except Exception as e:
 
835
  flash(f'Внутренняя ошибка при скачивании: {e}', 'error')
836
  return redirect(redirect_url)
837
 
 
1196
  except hf_utils.HfHubHTTPError as e:
1197
  if e.response.status_code != 404:
1198
  flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
 
1199
  except Exception as e:
1200
  flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1201
 
 
1254
 
1255
 
1256
  if __name__ == '__main__':
1257
+ if os.getenv("HF_TOKEN") is None:
1258
+ pass
1259
+ if os.getenv("HF_TOKEN_READ") is None:
1260
+ pass
1261
+ if os.getenv("ADMIN_TELEGRAM_ID") == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE":
1262
+ pass
1263
+ if os.getenv("ADMIN_USERNAME") == "admin" and os.getenv("ADMIN_PASSWORD") == "zeusadminpass":
1264
+ pass
1265
+ if os.getenv("BOT_USERNAME") == "ZeusCloudBot":
1266
+ pass
1267
 
1268
 
1269
  if HF_TOKEN_WRITE: