Shveiauto commited on
Commit
746f53a
·
verified ·
1 Parent(s): 8e60fa0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +325 -1201
app.py CHANGED
@@ -1,1267 +1,391 @@
1
- from flask import Flask, render_template_string, request, redirect, url_for, jsonify, flash
2
  import json
3
- import os
4
  import logging
 
5
  import threading
6
- import time
7
- from datetime import datetime
8
- from huggingface_hub import HfApi, hf_hub_download
9
- from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError
10
- from werkzeug.utils import secure_filename
11
- from dotenv import load_dotenv
12
- import uuid
13
- import hmac
14
- import hashlib
15
- import urllib.parse
16
-
17
- load_dotenv()
18
 
19
- app = Flask(__name__)
20
- app.secret_key = os.getenv("FLASK_SECRET_KEY", 'tontalent_secret_key_for_flash_messages_only')
21
- DATA_FILE = 'tontalent_data.json'
22
- SYNC_FILES = [DATA_FILE]
 
 
23
 
24
- REPO_ID = os.getenv("HF_REPO_ID", "Kgshop/tontalent2")
25
- HF_TOKEN_WRITE = os.getenv("HF_TOKEN_WRITE")
26
- HF_TOKEN_READ = os.getenv("HF_TOKEN_READ")
27
 
28
- TELEGRAM_BOT_TOKEN = "7549355625:AAGhdbf6x1JEzpH0mUtuxTF83Soi7MFVNZ8"
 
 
 
29
 
30
- DOWNLOAD_RETRIES = 3
31
- DOWNLOAD_DELAY = 5
 
32
 
 
33
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY):
36
- if not HF_TOKEN_READ and not HF_TOKEN_WRITE:
37
- logging.warning("HF_TOKEN_READ/HF_TOKEN_WRITE not set. Download might fail for private repos.")
38
- token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE
39
- files_to_download = [specific_file] if specific_file else SYNC_FILES
40
- logging.info(f"Attempting download for {files_to_download} from {REPO_ID}...")
41
- all_successful = True
42
- for file_name in files_to_download:
43
- success = False
44
- for attempt in range(retries + 1):
45
- try:
46
- logging.info(f"Downloading {file_name} (Attempt {attempt + 1}/{retries + 1})...")
47
- local_path = hf_hub_download(
48
- repo_id=REPO_ID, filename=file_name, repo_type="dataset",
49
- token=token_to_use, local_dir=".", local_dir_use_symlinks=False,
50
- force_download=True, resume_download=False
51
- )
52
- logging.info(f"Successfully downloaded {file_name} to {local_path}.")
53
- success = True
54
- break
55
- except RepositoryNotFoundError:
56
- logging.error(f"Repository {REPO_ID} not found. Download cancelled for all files.")
57
- return False
58
- except HfHubHTTPError as e:
59
- if e.response.status_code == 404:
60
- logging.warning(f"File {file_name} not found in repo {REPO_ID} (404). Skipping this file.")
61
- if attempt == 0 and not os.path.exists(file_name):
62
- try:
63
- if file_name == DATA_FILE:
64
- with open(file_name, 'w', encoding='utf-8') as f:
65
- json.dump({'resumes': [], 'vacancies': [], 'freelance_offers': [], 'users': {}}, f)
66
- logging.info(f"Created empty local file {file_name} because it was not found on HF.")
67
- except Exception as create_e:
68
- logging.error(f"Failed to create empty local file {file_name}: {create_e}")
69
- success = True
70
- break
71
- else:
72
- logging.error(f"HTTP error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...")
73
- except Exception as e:
74
- logging.error(f"Unexpected error downloading {file_name} (Attempt {attempt + 1}): {e}. Retrying in {delay}s...", exc_info=True)
75
- if attempt < retries: time.sleep(delay)
76
- if not success:
77
- logging.error(f"Failed to download {file_name} after {retries + 1} attempts.")
78
- all_successful = False
79
- logging.info(f"Download process finished. Overall success: {all_successful}")
80
- return all_successful
81
-
82
- def upload_db_to_hf(specific_file=None):
83
- if not HF_TOKEN_WRITE:
84
- logging.warning("HF_TOKEN_WRITE not set. Skipping upload to Hugging Face.")
85
- return
86
  try:
87
- api = HfApi()
88
- files_to_upload = [specific_file] if specific_file else SYNC_FILES
89
- logging.info(f"Starting upload of {files_to_upload} to HF repo {REPO_ID}...")
90
- for file_name in files_to_upload:
91
- if os.path.exists(file_name):
92
- try:
93
- api.upload_file(
94
- path_or_fileobj=file_name, path_in_repo=file_name, repo_id=REPO_ID,
95
- repo_type="dataset", token=HF_TOKEN_WRITE,
96
- commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
97
- )
98
- logging.info(f"File {file_name} successfully uploaded to Hugging Face.")
99
- except Exception as e:
100
- logging.error(f"Error uploading file {file_name} to Hugging Face: {e}")
101
- else:
102
- logging.warning(f"File {file_name} not found locally, skipping upload.")
103
- logging.info("Finished uploading files to HF.")
104
  except Exception as e:
105
- logging.error(f"General error during Hugging Face upload initialization or process: {e}", exc_info=True)
106
 
107
- def periodic_backup():
108
- backup_interval = 1800
109
- logging.info(f"Setting up periodic backup every {backup_interval} seconds.")
110
- while True:
111
- time.sleep(backup_interval)
112
- logging.info("Starting periodic backup...")
113
- upload_db_to_hf()
114
- logging.info("Periodic backup finished.")
115
-
116
- def load_data():
117
- default_data = {'resumes': [], 'vacancies': [], 'freelance_offers': [], 'users': {}}
118
  try:
119
- with open(DATA_FILE, 'r', encoding='utf-8') as file:
120
- data = json.load(file)
121
- logging.info(f"Local data loaded successfully from {DATA_FILE}")
122
- if not isinstance(data, dict):
123
- logging.warning(f"Local {DATA_FILE} is not a dictionary. Attempting download.")
124
- raise FileNotFoundError
125
- for key in default_data:
126
- if key not in data: data[key] = default_data[key]
127
- return data
128
- except (FileNotFoundError, json.JSONDecodeError) as e:
129
- logging.warning(f"Error loading local data ({e}). Attempting download from HF.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
- if download_db_from_hf(specific_file=DATA_FILE):
 
 
 
132
  try:
133
- with open(DATA_FILE, 'r', encoding='utf-8') as file:
134
- data = json.load(file)
135
- logging.info(f"Data loaded successfully from {DATA_FILE} after download.")
136
- if not isinstance(data, dict):
137
- logging.error(f"Downloaded {DATA_FILE} is not a dictionary. Using default.")
138
- return default_data
139
- for key in default_data:
140
- if key not in data: data[key] = default_data[key]
141
- return data
142
- except Exception as load_e:
143
- logging.error(f"Error loading downloaded {DATA_FILE}: {load_e}. Using default.", exc_info=True)
144
- return default_data
145
- else:
146
- logging.error(f"Failed to download {DATA_FILE} from HF. Using empty default data structure.")
147
- if not os.path.exists(DATA_FILE):
148
- try:
149
- with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump(default_data, f)
150
- logging.info(f"Created empty local file {DATA_FILE} after failed download.")
151
- except Exception as create_e:
152
- logging.error(f"Failed to create empty local file {DATA_FILE}: {create_e}")
153
- return default_data
154
 
155
- def save_data(data):
156
- try:
157
- if not isinstance(data, dict):
158
- logging.error("Attempted to save invalid data structure (not a dict). Aborting save.")
159
- return
160
- default_keys = {'resumes': [], 'vacancies': [], 'freelance_offers': [], 'users': {}}
161
- for key in default_keys:
162
- if key not in data: data[key] = default_keys[key]
163
-
164
- with open(DATA_FILE, 'w', encoding='utf-8') as file:
165
- json.dump(data, file, ensure_ascii=False, indent=4)
166
- logging.info(f"Data successfully saved to {DATA_FILE}")
167
- upload_db_to_hf(specific_file=DATA_FILE)
168
- except Exception as e:
169
- logging.error(f"Error saving data to {DATA_FILE}: {e}", exc_info=True)
170
 
171
- def verify_telegram_auth_data(auth_data_str, bot_token):
172
- if not auth_data_str:
173
- return False, None
174
-
175
- params = dict(urllib.parse.parse_qsl(auth_data_str))
176
- if 'hash' not in params:
177
- return False, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- received_hash = params.pop('hash')
180
-
181
- sorted_params = sorted(params.items())
182
- data_check_string_parts = []
183
- for key, value in sorted_params:
184
- data_check_string_parts.append(f"{key}={value}")
185
-
186
- data_check_string = "\n".join(data_check_string_parts)
187
-
188
- secret_key = hmac.new("WebAppData".encode(), bot_token.encode(), hashlib.sha256).digest()
189
- calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
190
-
191
- if calculated_hash == received_hash:
192
- try:
193
- user_data = json.loads(params.get('user', '{}'))
194
- return True, user_data
195
- except json.JSONDecodeError:
196
- return False, None
197
- return False, None
198
 
 
 
199
 
200
- MAIN_APP_TEMPLATE = '''
201
  <!DOCTYPE html>
202
- <html lang="en">
203
  <head>
204
  <meta charset="UTF-8">
205
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
206
- <title>TonTalent</title>
207
- <script src="https://telegram.org/js/telegram-web-app.js"></script>
208
  <style>
209
- :root {
210
- --tg-theme-bg-color: #ffffff;
211
- --tg-theme-text-color: #000000;
212
- --tg-theme-hint-color: #999999;
213
- --tg-theme-link-color: #007aff;
214
- --tg-theme-button-color: #007aff;
215
- --tg-theme-button-text-color: #ffffff;
216
- --tg-theme-secondary-bg-color: #f0f0f0;
217
- --tg-theme-header-bg-color: #efeff4;
218
- --tg-theme-section-bg-color: #ffffff;
219
- --tg-theme-section-header-text-color: #8e8e93;
220
- --tg-theme-destructive-text-color: #ff3b30;
221
- --tg-theme-accent-text-color: #007aff;
222
- }
223
- body {
224
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Helvetica Neue", Arial, sans-serif;
225
- margin: 0;
226
- padding: 0;
227
- background-color: var(--tg-theme-bg-color);
228
- color: var(--tg-theme-text-color);
229
- overscroll-behavior-y: none;
230
- -webkit-font-smoothing: antialiased;
231
- -moz-osx-font-smoothing: grayscale;
232
- line-height: 1.4;
233
- }
234
- .app-container { display: flex; flex-direction: column; min-height: 100vh; min-height: -webkit-fill-available; }
235
- .header {
236
- background-color: var(--tg-theme-header-bg-color);
237
- padding: 12px 15px;
238
- text-align: center;
239
- font-weight: 600;
240
- font-size: 17px;
241
- border-bottom: 0.5px solid var(--tg-theme-secondary-bg-color);
242
- position: sticky;
243
- top: 0;
244
- z-index: 100;
245
- }
246
- .user-info-bar {
247
- display: flex;
248
- align-items: center;
249
- padding: 10px 15px;
250
- background-color: var(--tg-theme-section-bg-color);
251
- border-bottom: 0.5px solid var(--tg-theme-secondary-bg-color);
252
- }
253
- .user-info-bar.clickable {
254
- cursor: pointer;
255
- transition: background-color 0.2s ease;
256
- }
257
- .user-info-bar.clickable:active {
258
- background-color: var(--tg-theme-secondary-bg-color);
259
- }
260
- .user-info-bar img {
261
- width: 40px;
262
- height: 40px;
263
- border-radius: 50%;
264
- margin-right: 12px;
265
- object-fit: cover;
266
- background-color: var(--tg-theme-secondary-bg-color);
267
  }
268
- .user-info-bar span {
269
- font-size: 15px;
270
- font-weight: 500;
271
- color: var(--tg-theme-text-color);
 
272
  }
273
- .tabs { display: flex; background-color: var(--tg-theme-secondary-bg-color); padding: 5px; }
274
- .tab-button {
275
- flex: 1;
276
- padding: 12px 10px;
277
  text-align: center;
278
- cursor: pointer;
279
- background: none;
280
- border: none;
281
- color: var(--tg-theme-hint-color);
282
- font-size: 15px;
283
- font-weight: 500;
284
- border-bottom: 2.5px solid transparent;
285
- transition: color 0.2s ease, border-bottom-color 0.2s ease;
286
- -webkit-tap-highlight-color: transparent;
287
- }
288
- .tab-button.active { color: var(--tg-theme-link-color); border-bottom-color: var(--tg-theme-link-color); }
289
- .content { flex-grow: 1; padding: 0; overflow-x: hidden; transition: opacity 0.2s ease-out; }
290
- .list-item {
291
- background-color: var(--tg-theme-section-bg-color);
292
- padding: 12px 15px;
293
- margin: 10px 15px;
294
- border-radius: 10px;
295
- box-shadow: 0 2px 8px rgba(0,0,0,0.06);
296
- cursor: pointer;
297
- transition: transform 0.1s ease-out, background-color 0.1s ease;
298
- }
299
- .list-item:active { transform: scale(0.98); background-color: var(--tg-theme-secondary-bg-color); }
300
- .list-item h3 { margin: 0 0 6px 0; font-size: 17px; font-weight: 600; color: var(--tg-theme-text-color); }
301
- .list-item p { margin: 0 0 4px 0; font-size: 14px; color: var(--tg-theme-hint-color); }
302
- .list-item .meta { font-size: 13px; color: var(--tg-theme-hint-color); margin-top: 8px; }
303
- .form-container, .detail-view { padding: 20px 15px; background-color: var(--tg-theme-section-bg-color); min-height: calc(100vh - 180px); /* Adjust based on header/tabs/userbar height */ }
304
- .form-group { margin-bottom: 18px; }
305
- .form-group label { display: block; font-size: 14px; color: var(--tg-theme-section-header-text-color); margin-bottom: 6px; font-weight: 500; }
306
- .form-group input, .form-group textarea {
307
- width: 100%;
308
- padding: 12px;
309
- border: 1px solid var(--tg-theme-secondary-bg-color);
310
- border-radius: 8px;
311
- font-size: 16px;
312
- background-color: var(--tg-theme-bg-color);
313
- color: var(--tg-theme-text-color);
314
- box-sizing: border-box;
315
- transition: border-color 0.2s ease;
316
  }
317
- .form-group input:focus, .form-group textarea:focus { border-color: var(--tg-theme-link-color); outline: none; }
318
- .form-group textarea { min-height: 100px; resize: vertical; }
319
- .fab {
320
- position: fixed;
321
- bottom: 25px;
322
- right: 25px;
323
- width: 56px;
324
- height: 56px;
325
- background-color: var(--tg-theme-button-color);
326
- color: var(--tg-theme-button-text-color);
327
  border-radius: 50%;
328
- display: flex;
329
- align-items: center;
330
- justify-content: center;
331
- font-size: 28px;
332
- line-height: 1;
333
- box-shadow: 0 4px 12px rgba(0,0,0,0.15);
334
- cursor: pointer;
335
- z-index: 1000;
336
- border: none;
337
- transition: transform 0.15s ease-out;
338
  }
339
- .fab:active { transform: scale(0.92); }
340
- .detail-view h2 { margin-top: 0; font-size: 22px; font-weight: 600; color: var(--tg-theme-text-color); margin-bottom: 15px; }
341
- .detail-view p { margin-bottom: 10px; line-height: 1.6; font-size: 16px; }
342
- .detail-view strong { font-weight: 500; color: var(--tg-theme-text-color); }
343
- .detail-view .meta-detail { font-size: 13px; color: var(--tg-theme-hint-color); margin-top: 20px; }
344
- .detail-view a { color: var(--tg-theme-link-color); text-decoration: none; }
345
- .detail-view a:hover { text-decoration: underline; }
346
- .loading, .empty-state { text-align: center; padding: 50px 15px; color: var(--tg-theme-hint-color); font-size: 16px; }
347
-
348
- .action-button {
349
- display: block;
350
- width: 100%;
351
- padding: 12px 15px;
352
- margin-top: 15px;
353
- border: none;
354
- border-radius: 8px;
355
- font-size: 16px;
356
- font-weight: 500;
357
- cursor: pointer;
358
- text-align: center;
359
- transition: background-color 0.2s ease;
360
- }
361
- .button-destructive {
362
- background-color: var(--tg-theme-destructive-text-color);
363
- color: #ffffff;
364
  }
365
- .button-destructive:active {
366
- background-color: color-mix(in srgb, var(--tg-theme-destructive-text-color) 80%, black);
367
- }
368
- .error-message { color: var(--tg-theme-destructive-text-color); font-size: 14px; margin-top: 10px; text-align: center; }
369
  </style>
370
  </head>
371
  <body>
372
- <div class="app-container">
373
- <div class="header" id="appHeader">TonTalent</div>
374
- <div class="user-info-bar" id="userInfoBar">
375
- <img id="userAvatar" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="Avatar">
376
- <span id="userInfoText">Loading user...</span>
377
- </div>
378
- <div class="tabs">
379
- <button class="tab-button active" data-tab="resumes">Resumes</button>
380
- <button class="tab-button" data-tab="vacancies">Vacancies</button>
381
- <button class="tab-button" data-tab="freelance_offers">Freelance</button>
382
- </div>
383
- <div class="content" id="mainContent">
384
- <div class="loading">Loading content...</div>
385
- </div>
386
- <button class="fab" id="fabButton" title="Add New Item">+</button>
387
  </div>
388
 
389
  <script>
390
- const tg = window.Telegram.WebApp;
391
- let currentUser = null;
392
- let currentView = 'resumes';
393
- let currentItem = null;
394
- let previousViewBeforeMyPosts = 'resumes';
395
- const mainContent = document.getElementById('mainContent');
396
- const fabButton = document.getElementById('fabButton');
397
- const appHeader = document.getElementById('appHeader');
398
- const tabOrder = ['resumes', 'vacancies', 'freelance_offers'];
399
 
400
- function capitalizeFirstLetter(string) {
401
- return string.charAt(0).toUpperCase() + string.slice(1);
402
- }
403
 
404
- function applyThemeParams() {
405
- const rootStyle = document.documentElement.style;
406
- rootStyle.setProperty('--tg-theme-bg-color', tg.themeParams.bg_color || '#ffffff');
407
- rootStyle.setProperty('--tg-theme-text-color', tg.themeParams.text_color || '#000000');
408
- rootStyle.setProperty('--tg-theme-hint-color', tg.themeParams.hint_color || '#999999');
409
- rootStyle.setProperty('--tg-theme-link-color', tg.themeParams.link_color || '#007aff');
410
- rootStyle.setProperty('--tg-theme-button-color', tg.themeParams.button_color || '#007aff');
411
- rootStyle.setProperty('--tg-theme-button-text-color', tg.themeParams.button_text_color || '#ffffff');
412
- rootStyle.setProperty('--tg-theme-secondary-bg-color', tg.themeParams.secondary_bg_color || '#f0f0f0');
413
-
414
- rootStyle.setProperty('--tg-theme-header-bg-color', tg.themeParams.header_bg_color || tg.themeParams.secondary_bg_color || '#efeff4');
415
- rootStyle.setProperty('--tg-theme-section-bg-color', tg.themeParams.section_bg_color || tg.themeParams.bg_color || '#ffffff');
416
- rootStyle.setProperty('--tg-theme-section-header-text-color', tg.themeParams.section_header_text_color || tg.themeParams.hint_color || '#8e8e93');
417
- rootStyle.setProperty('--tg-theme-destructive-text-color', tg.themeParams.destructive_text_color || '#ff3b30');
418
- rootStyle.setProperty('--tg-theme-accent-text-color', tg.themeParams.accent_text_color || tg.themeParams.link_color || '#007aff');
419
- }
420
-
421
- async function apiCall(endpoint, method = 'GET', body = null) {
422
- const headers = { 'Content-Type': 'application/json' };
423
- if (tg.initData) {
424
- headers['X-Telegram-Auth'] = tg.initData;
425
- }
426
- const options = { method, headers };
427
- if (body) options.body = JSON.stringify(body);
428
  try {
429
- const response = await fetch(endpoint, options);
430
- if (!response.ok) {
431
- const errorData = await response.json().catch(() => ({ error: 'Request failed without JSON body' }));
432
- throw new Error(errorData.error || `HTTP error ${response.status}`);
433
- }
434
- return response.json();
435
- } catch (error) {
436
- console.error('API Call Error:', error);
437
- tg.showAlert(error.message || 'An API error occurred.');
438
- throw error;
439
- }
440
- }
441
-
442
- function renderList(items, type) {
443
- mainContent.style.opacity = 0;
444
- if (!items || items.length === 0) {
445
- mainContent.innerHTML = `<div class="empty-state">No ${type} found. Be the first to add one!</div>`;
446
- } else {
447
- mainContent.innerHTML = items.map(item => `
448
- <div class="list-item" onclick="handleItemClick('${type}', '${item.id}')">
449
- <h3>${item.title || item.name || 'Untitled'}</h3>
450
- ${type === 'vacancies' && item.company_name ? `<p><strong>Company:</strong> ${item.company_name}</p>` : ''}
451
- ${type === 'freelance_offers' && item.budget ? `<p><strong>Budget:</strong> ${item.budget}</p>` : ''}
452
- <p class="meta">Posted by: @${item.user_telegram_username || 'anonymous'} on ${new Date(item.timestamp).toLocaleDateString()}</p>
453
- </div>
454
- `).join('');
455
- }
456
- setTimeout(() => { mainContent.style.opacity = 1; }, 50);
457
- }
458
-
459
- function handleItemClick(type, id) {
460
- tg.HapticFeedback.impactOccurred('light');
461
- showDetailView(type, id);
462
- }
463
-
464
- function formatContactField(contactValue, userTelegramUsername) {
465
- let displayContact = contactValue;
466
- if (!displayContact && userTelegramUsername) {
467
- return `<a href="tg://resolve?domain=${userTelegramUsername}" target="_blank" rel="noopener noreferrer">@${userTelegramUsername}</a>`;
468
- }
469
- if (displayContact) {
470
- if (displayContact.startsWith('@')) {
471
- const username = displayContact.substring(1);
472
- return `<a href="tg://resolve?domain=${username}" target="_blank" rel="noopener noreferrer">${displayContact}</a>`;
473
- } else if (displayContact.startsWith('http://') || displayContact.startsWith('https://')) {
474
- return `<a href="${displayContact}" target="_blank" rel="noopener noreferrer">${displayContact}</a>`;
475
- } else if (displayContact.includes('@') && displayContact.includes('.') && !displayContact.startsWith('http')) {
476
- return `<a href="mailto:${displayContact}">${displayContact}</a>`;
477
- }
478
- }
479
- return displayContact || 'N/A';
480
- }
481
-
482
- function showDetailView(type, id) {
483
- mainContent.style.opacity = 0;
484
- tg.BackButton.show();
485
- tg.BackButton.onClick(() => {
486
- tg.HapticFeedback.impactOccurred('light');
487
- if (currentView === 'my_posts') {
488
- showMyPostsView();
489
- } else {
490
- loadView(type);
491
- }
492
- });
493
- tg.MainButton.hide();
494
- fabButton.style.display = 'none';
495
-
496
- apiCall(`/api/${type}/${id}`)
497
- .then(item => {
498
- currentItem = item;
499
- let detailsHtml = `<div class="detail-view"><h2>${item.title || item.name}</h2>`;
500
-
501
- const itemContact = formatContactField(item.contact, item.user_telegram_username);
502
- const postedByLink = item.user_telegram_username
503
- ? `<a href="tg://resolve?domain=${item.user_telegram_username}" target="_blank" rel="noopener noreferrer">@${item.user_telegram_username}</a>`
504
- : 'anonymous';
505
-
506
- if (type === 'resumes') {
507
- detailsHtml += `
508
- <p><strong>Skills:</strong> ${item.skills || 'N/A'}</p>
509
- <p><strong>Experience:</strong><br>${item.experience ? item.experience.replace(/\\n/g, '<br>') : 'N/A'}</p>
510
- <p><strong>Education:</strong><br>${item.education ? item.education.replace(/\\n/g, '<br>') : 'N/A'}</p>
511
- <p><strong>Contact:</strong> ${itemContact}</p>
512
- ${item.portfolio_link ? `<p><strong>Portfolio:</strong> <a href="${item.portfolio_link}" target="_blank" rel="noopener noreferrer">${item.portfolio_link}</a></p>` : ''}
513
- `;
514
- } else if (type === 'vacancies') {
515
- detailsHtml += `
516
- <p><strong>Company:</strong> ${item.company_name || 'N/A'}</p>
517
- <p><strong>Description:</strong><br>${item.description ? item.description.replace(/\\n/g, '<br>') : 'N/A'}</p>
518
- <p><strong>Requirements:</strong><br>${item.requirements ? item.requirements.replace(/\\n/g, '<br>') : 'N/A'}</p>
519
- <p><strong>Salary:</strong> ${item.salary || 'N/A'}</p>
520
- <p><strong>Location:</strong> ${item.location || 'N/A'}</p>
521
- <p><strong>Contact/Apply:</strong> ${itemContact}</p>
522
- `;
523
- } else if (type === 'freelance_offers') {
524
- detailsHtml += `
525
- <p><strong>Description:</strong><br>${item.description ? item.description.replace(/\\n/g, '<br>') : 'N/A'}</p>
526
- <p><strong>Budget:</strong> ${item.budget || 'N/A'}</p>
527
- <p><strong>Deadline:</strong> ${item.deadline || 'N/A'}</p>
528
- <p><strong>Skills Needed:</strong> ${item.skills_needed || 'N/A'}</p>
529
- <p><strong>Contact:</strong> ${itemContact}</p>
530
- `;
531
- }
532
- detailsHtml += `<p class="meta-detail">Posted by: ${postedByLink} on ${new Date(item.timestamp).toLocaleDateString()}</p>`;
533
-
534
- if (currentUser && item.user_id === String(currentUser.id)) {
535
- detailsHtml += `<button id="editItemButton" class="action-button" style="background-color: var(--tg-theme-button-color); color: var(--tg-theme-button-text-color); margin-top: 25px;">Edit Post</button>`;
536
- detailsHtml += `<button id="deleteItemButton" class="action-button button-destructive">Delete Post</button>`;
537
- }
538
- detailsHtml += `</div>`;
539
- mainContent.innerHTML = detailsHtml;
540
-
541
- if (currentUser && item.user_id === String(currentUser.id)) {
542
- document.getElementById('editItemButton')?.addEventListener('click', () => {
543
- tg.HapticFeedback.impactOccurred('light');
544
- showForm(type, item);
545
- });
546
- document.getElementById('deleteItemButton')?.addEventListener('click', () => {
547
- tg.HapticFeedback.impactOccurred('light');
548
- handleDeleteItem(type, item.id);
549
- });
550
- }
551
- setTimeout(() => { mainContent.style.opacity = 1; }, 50);
552
- })
553
- .catch(err => {
554
- mainContent.innerHTML = `<div class="empty-state">Error loading details.</div>`;
555
- setTimeout(() => { mainContent.style.opacity = 1; }, 50);
556
  });
557
- }
558
-
559
- function showForm(type, itemToEdit = null) {
560
- mainContent.style.opacity = 0;
561
- currentItem = itemToEdit;
562
- tg.BackButton.show();
563
- tg.BackButton.onClick(() => {
564
- tg.HapticFeedback.impactOccurred('light');
565
- if (itemToEdit) showDetailView(type, itemToEdit.id);
566
- else if (currentView === 'my_posts') showMyPostsView();
567
- else loadView(type);
568
- });
569
- fabButton.style.display = 'none';
570
-
571
- let formHtml = `<div class="form-container"><h2>${itemToEdit ? 'Edit' : 'New'} ${type.slice(0, -1)}</h2>`;
572
- if (type === 'resumes') {
573
- formHtml += `
574
- <div class="form-group"><label for="name">Full Name *</label><input type="text" id="name" value="${itemToEdit?.name || ''}" required></div>
575
- <div class="form-group"><label for="title">Job Title / Desired Position *</label><input type="text" id="title" value="${itemToEdit?.title || ''}" required></div>
576
- <div class="form-group"><label for="skills">Skills (comma separated)</label><textarea id="skills">${itemToEdit?.skills || ''}</textarea></div>
577
- <div class="form-group"><label for="experience">Experience</label><textarea id="experience">${itemToEdit?.experience || ''}</textarea></div>
578
- <div class="form-group"><label for="education">Education</label><textarea id="education">${itemToEdit?.education || ''}</textarea></div>
579
- <div class="form-group"><label for="contact">Contact Info (e.g., email, or leave blank to use Telegram)</label><input type="text" id="contact" value="${itemToEdit?.contact || ''}"></div>
580
- <div class="form-group"><label for="portfolio_link">Portfolio Link (optional)</label><input type="url" id="portfolio_link" value="${itemToEdit?.portfolio_link || ''}"></div>
581
- `;
582
- } else if (type === 'vacancies') {
583
- formHtml += `
584
- <div class="form-group"><label for="company_name">Company Name *</label><input type="text" id="company_name" value="${itemToEdit?.company_name || ''}" required></div>
585
- <div class="form-group"><label for="title">Job Title *</label><input type="text" id="title" value="${itemToEdit?.title || ''}" required></div>
586
- <div class="form-group"><label for="description">Description</label><textarea id="description">${itemToEdit?.description || ''}</textarea></div>
587
- <div class="form-group"><label for="requirements">Requirements</label><textarea id="requirements">${itemToEdit?.requirements || ''}</textarea></div>
588
- <div class="form-group"><label for="salary">Salary/Compensation</label><input type="text" id="salary" value="${itemToEdit?.salary || ''}"></div>
589
- <div class="form-group"><label for="location">Location (e.g., Remote, City)</label><input type="text" id="location" value="${itemToEdit?.location || ''}"></div>
590
- <div class="form-group"><label for="contact">Contact Info / How to Apply</label><textarea id="contact">${itemToEdit?.contact || ''}</textarea></div>
591
- `;
592
- } else if (type === 'freelance_offers') {
593
- formHtml += `
594
- <div class="form-group"><label for="title">Project Title *</label><input type="text" id="title" value="${itemToEdit?.title || ''}" required></div>
595
- <div class="form-group"><label for="description">Description of Work</label><textarea id="description">${itemToEdit?.description || ''}</textarea></div>
596
- <div class="form-group"><label for="budget">Budget</label><input type="text" id="budget" value="${itemToEdit?.budget || ''}"></div>
597
- <div class="form-group"><label for="deadline">Expected Deadline</label><input type="text" id="deadline" value="${itemToEdit?.deadline || ''}"></div>
598
- <div class="form-group"><label for="skills_needed">Skills Needed (comma separated)</label><textarea id="skills_needed">${itemToEdit?.skills_needed || ''}</textarea></div>
599
- <div class="form-group"><label for="contact">Contact Info (or leave blank to use Telegram)</label><input type="text" id="contact" value="${itemToEdit?.contact || ''}"></div>
600
- `;
601
- }
602
- formHtml += `<div id="formError" class="error-message"></div></div>`;
603
- mainContent.innerHTML = formHtml;
604
- setTimeout(() => { mainContent.style.opacity = 1; }, 50);
605
-
606
- tg.MainButton.setText(itemToEdit ? 'Save Changes' : 'Post');
607
- tg.MainButton.show();
608
- tg.MainButton.onClick(() => handleSubmit(type, itemToEdit ? itemToEdit.id : null));
609
- }
610
-
611
- function handleSubmit(type, itemId = null) {
612
- const payload = {};
613
- let isValid = true;
614
- document.getElementById('formError').textContent = '';
615
-
616
- if (type === 'resumes') {
617
- payload.name = document.getElementById('name').value.trim();
618
- payload.title = document.getElementById('title').value.trim();
619
- payload.skills = document.getElementById('skills').value.trim();
620
- payload.experience = document.getElementById('experience').value.trim();
621
- payload.education = document.getElementById('education').value.trim();
622
- payload.contact = document.getElementById('contact').value.trim();
623
- payload.portfolio_link = document.getElementById('portfolio_link').value.trim();
624
- if (!payload.name || !payload.title) isValid = false;
625
- } else if (type === 'vacancies') {
626
- payload.company_name = document.getElementById('company_name').value.trim();
627
- payload.title = document.getElementById('title').value.trim();
628
- payload.description = document.getElementById('description').value.trim();
629
- payload.requirements = document.getElementById('requirements').value.trim();
630
- payload.salary = document.getElementById('salary').value.trim();
631
- payload.location = document.getElementById('location').value.trim();
632
- payload.contact = document.getElementById('contact').value.trim();
633
- if (!payload.company_name || !payload.title) isValid = false;
634
- } else if (type === 'freelance_offers') {
635
- payload.title = document.getElementById('title').value.trim();
636
- payload.description = document.getElementById('description').value.trim();
637
- payload.budget = document.getElementById('budget').value.trim();
638
- payload.deadline = document.getElementById('deadline').value.trim();
639
- payload.skills_needed = document.getElementById('skills_needed').value.trim();
640
- payload.contact = document.getElementById('contact').value.trim();
641
- if (!payload.title) isValid = false;
642
- }
643
-
644
- if (!isValid) {
645
- document.getElementById('formError').textContent = 'Please fill in all required fields (*).';
646
- tg.HapticFeedback.notificationOccurred('error');
647
- return;
648
- }
649
-
650
- tg.MainButton.showProgress();
651
- tg.HapticFeedback.impactOccurred('light');
652
-
653
- const method = itemId ? 'PUT' : 'POST';
654
- const endpoint = itemId ? `/api/${type}/${itemId}` : `/api/${type}`;
655
 
656
- apiCall(endpoint, method, payload)
657
- .then(response => {
658
- tg.HapticFeedback.notificationOccurred('success');
659
- tg.MainButton.hideProgress();
660
- tg.MainButton.hide();
661
- if (currentView === 'my_posts') showMyPostsView();
662
- else loadView(type);
663
- })
664
- .catch(err => {
665
- tg.HapticFeedback.notificationOccurred('error');
666
- tg.MainButton.hideProgress();
667
- document.getElementById('formError').textContent = err.message || 'Failed to submit.';
668
- });
669
- }
670
-
671
- function handleDeleteItem(type, itemId) {
672
- tg.showConfirm('Are you sure you want to delete this post?', (confirmed) => {
673
- if (confirmed) {
674
- tg.HapticFeedback.impactOccurred('medium');
675
- apiCall(`/api/${type}/${itemId}`, 'DELETE')
676
- .then(() => {
677
- tg.HapticFeedback.notificationOccurred('success');
678
- tg.showAlert('Post deleted successfully.');
679
- if (currentView === 'my_posts') showMyPostsView();
680
- else loadView(type);
681
- })
682
- .catch(err => {
683
- tg.HapticFeedback.notificationOccurred('error');
684
- tg.showAlert(err.message || 'Failed to delete post.');
685
- });
686
  } else {
687
- tg.HapticFeedback.impactOccurred('light');
688
- }
689
- });
690
- }
691
-
692
- function loadView(tabName, fromSwipe = false) {
693
- if (!fromSwipe && currentView !== tabName) tg.HapticFeedback.impactOccurred('light');
694
-
695
- if (currentView === 'my_posts' && tabName !== 'my_posts') {
696
- appHeader.textContent = 'TonTalent';
697
- }
698
- currentView = tabName;
699
-
700
- document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
701
- document.querySelector(`.tab-button[data-tab="${tabName}"]`).classList.add('active');
702
-
703
- mainContent.style.opacity = 0;
704
- mainContent.innerHTML = `<div class="loading">Loading ${tabName}...</div>`;
705
-
706
- tg.BackButton.hide();
707
- tg.MainButton.hide();
708
- fabButton.style.display = 'block';
709
-
710
- apiCall(`/api/${tabName}`)
711
- .then(data => renderList(data, tabName))
712
- .catch(err => {
713
- mainContent.innerHTML = `<div class="empty-state">Error loading ${tabName}.</div>`;
714
- setTimeout(() => { mainContent.style.opacity = 1; }, 50);
715
- });
716
- }
717
-
718
- function renderMyPostsList(items) {
719
- mainContent.style.opacity = 0;
720
- if (!items || items.length === 0) {
721
- mainContent.innerHTML = `<div class="empty-state">You haven't posted anything yet.</div>`;
722
- } else {
723
- mainContent.innerHTML = items.map(item => `
724
- <div class="list-item" onclick="handleItemClick('${item.type}', '${item.id}')">
725
- <h3>${item.title || item.name || 'Untitled'} <span style="font-weight:normal; font-size: 0.8em; color: var(--tg-theme-hint-color);">(${capitalizeFirstLetter(item.type.slice(0,-1))})</span></h3>
726
- ${item.type === 'vacancies' && item.company_name ? `<p><strong>Company:</strong> ${item.company_name}</p>` : ''}
727
- ${item.type === 'freelance_offers' && item.budget ? `<p><strong>Budget:</strong> ${item.budget}</p>` : ''}
728
- <p class="meta">Posted on ${new Date(item.timestamp).toLocaleDateString()}${item.updated_timestamp ? ' (Edited: ' + new Date(item.updated_timestamp).toLocaleDateString() + ')' : ''}</p>
729
- </div>
730
- `).join('');
731
- }
732
- setTimeout(() => { mainContent.style.opacity = 1; }, 50);
733
- }
734
-
735
- function showMyPostsView() {
736
- tg.HapticFeedback.impactOccurred('light');
737
- if (currentView !== 'my_posts') { // Store the view only if we are not already in my_posts
738
- previousViewBeforeMyPosts = currentView;
739
- }
740
- currentView = 'my_posts';
741
- appHeader.textContent = 'My Posts';
742
-
743
- document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
744
- fabButton.style.display = 'none';
745
- tg.MainButton.hide();
746
-
747
- tg.BackButton.show();
748
- tg.BackButton.onClick(() => {
749
- tg.HapticFeedback.impactOccurred('light');
750
- appHeader.textContent = 'TonTalent';
751
- loadView(previousViewBeforeMyPosts);
752
- });
753
-
754
- mainContent.style.opacity = 0;
755
- mainContent.innerHTML = '<div class="loading">Loading your posts...</div>';
756
-
757
- Promise.all([
758
- apiCall('/api/resumes'),
759
- apiCall('/api/vacancies'),
760
- apiCall('/api/freelance_offers')
761
- ]).then(([resumes, vacancies, freelanceOffers]) => {
762
- const myResumes = resumes.filter(item => String(item.user_id) === String(currentUser.id));
763
- const myVacancies = vacancies.filter(item => String(item.user_id) === String(currentUser.id));
764
- const myFreelanceOffers = freelanceOffers.filter(item => String(item.user_id) === String(currentUser.id));
765
-
766
- const allMyPosts = [
767
- ...myResumes.map(item => ({ ...item, type: 'resumes' })),
768
- ...myVacancies.map(item => ({ ...item, type: 'vacancies' })),
769
- ...myFreelanceOffers.map(item => ({ ...item, type: 'freelance_offers' }))
770
- ].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
771
-
772
- renderMyPostsList(allMyPosts);
773
- }).catch(err => {
774
- mainContent.innerHTML = '<div class="empty-state">Error loading your posts.</div>';
775
- setTimeout(() => { mainContent.style.opacity = 1; }, 50);
776
- });
777
- }
778
-
779
- let touchstartX = 0;
780
- let touchendX = 0;
781
- const swipeThreshold = 70;
782
-
783
- mainContent.addEventListener('touchstart', e => {
784
- if (currentView === 'my_posts') return; // Disable swipe on "My Posts" view
785
- touchstartX = e.changedTouches[0].screenX;
786
- }, { passive: true });
787
-
788
- mainContent.addEventListener('touchend', e => {
789
- if (currentView === 'my_posts') return; // Disable swipe on "My Posts" view
790
- touchendX = e.changedTouches[0].screenX;
791
- handleSwipeGesture();
792
- });
793
-
794
- function handleSwipeGesture() {
795
- const swipeLength = touchendX - touchstartX;
796
- if (Math.abs(swipeLength) < swipeThreshold) return;
797
-
798
- let currentIndex = tabOrder.indexOf(currentView);
799
- if (currentIndex === -1) return; // Should not happen if currentView is one of the tabs
800
- let newIndex;
801
-
802
- if (touchendX < touchstartX) {
803
- newIndex = (currentIndex + 1) % tabOrder.length;
804
- } else {
805
- newIndex = (currentIndex - 1 + tabOrder.length) % tabOrder.length;
806
- }
807
-
808
- if (newIndex !== currentIndex) {
809
- tg.HapticFeedback.impactOccurred('light');
810
- loadView(tabOrder[newIndex], true);
811
- }
812
- }
813
-
814
- async function init() {
815
- tg.ready();
816
- applyThemeParams();
817
- tg.expand();
818
- tg.enableClosingConfirmation();
819
-
820
- tg.onEvent('themeChanged', applyThemeParams);
821
-
822
- const userInfoText = document.getElementById('userInfoText');
823
- const userAvatar = document.getElementById('userAvatar');
824
- const userInfoBar = document.getElementById('userInfoBar');
825
-
826
- userInfoText.textContent = `Welcome, ${tg.initDataUnsafe.user?.first_name || 'User'}!`;
827
- if (tg.initDataUnsafe.user?.username) {
828
- userInfoText.textContent += ` (@${tg.initDataUnsafe.user.username})`;
829
- }
830
-
831
- try {
832
- const authResponse = await apiCall('/api/auth_user', 'POST', { init_data: tg.initData });
833
- currentUser = authResponse.user;
834
- if (currentUser) {
835
- userInfoText.textContent = `${currentUser.first_name || ''} ${currentUser.last_name || ''}`.trim();
836
- if (currentUser.username) userInfoText.textContent += ` (@${currentUser.username})`;
837
- else userInfoText.textContent += ` (ID: ${currentUser.id})`;
838
-
839
- if (currentUser.photo_url) {
840
- userAvatar.src = currentUser.photo_url;
841
- } else {
842
- // Keep default placeholder or hide
843
- }
844
- userInfoBar.classList.add('clickable');
845
- userInfoBar.addEventListener('click', () => {
846
- if(currentUser) showMyPostsView();
847
- });
848
  }
849
  } catch (error) {
850
- console.error("Auth error:", error);
851
- userInfoText.textContent = `Auth failed. Using basic info.`;
852
- // tg.showAlert("Authentication with the server failed. Some features might be limited.");
 
 
 
853
  }
854
-
855
- document.querySelectorAll('.tab-button').forEach(button => {
856
- button.addEventListener('click', () => loadView(button.dataset.tab));
857
- });
858
- fabButton.addEventListener('click', () => {
859
- tg.HapticFeedback.impactOccurred('medium');
860
- showForm(currentView); // currentView should be one of the main tabs here
861
- });
862
-
863
- loadView('resumes');
864
- }
865
-
866
- init();
867
  </script>
868
  </body>
869
  </html>
870
- '''
871
-
872
- ADMIN_TEMPLATE = '''
873
- <!DOCTYPE html>
874
- <html lang="en">
875
- <head>
876
- <meta charset="UTF-8">
877
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
878
- <title>TonTalent Admin</title>
879
- <style>
880
- body { font-family: sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
881
- .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
882
- h1, h2 { color: #333; }
883
- .section { margin-bottom: 30px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background-color: #f9f9f9;}
884
- .item { border-bottom: 1px solid #eee; padding: 10px 0; }
885
- .item:last-child { border-bottom: none; }
886
- .item h3 { margin: 0 0 5px 0; }
887
- .item p { margin: 3px 0; font-size: 0.9em; color: #555; }
888
- .button { padding: 8px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 0.9em; margin-right: 5px; }
889
- .button-primary { background-color: #007bff; color: white; }
890
- .button-danger { background-color: #dc3545; color: white; }
891
- .button-secondary { background-color: #6c757d; color: white; }
892
- .message { padding: 10px; margin-bottom: 15px; border-radius: 4px; }
893
- .message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
894
- .message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
895
- .message.warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
896
- .sync-buttons form { display: inline-block; margin-right: 10px; }
897
- </style>
898
- </head>
899
- <body>
900
- <div class="container">
901
- <h1>TonTalent Admin Panel</h1>
902
-
903
- {% with messages = get_flashed_messages(with_categories=true) %}
904
- {% if messages %}
905
- {% for category, message in messages %}
906
- <div class="message {{ category }}">{{ message }}</div>
907
- {% endfor %}
908
- {% endif %}
909
- {% endwith %}
910
-
911
- <div class="section">
912
- <h2>Data Synchronization with Hugging Face</h2>
913
- <div class="sync-buttons">
914
- <form method="POST" action="{{ url_for('force_upload_admin') }}" onsubmit="return confirm('Upload local data to Hugging Face? This will overwrite server data.');">
915
- <button type="submit" class="button button-primary">Upload DB to HF</button>
916
- </form>
917
- <form method="POST" action="{{ url_for('force_download_admin') }}" onsubmit="return confirm('Download data from Hugging Face? This will overwrite local data.');">
918
- <button type="submit" class="button button-secondary">Download DB from HF</button>
919
- </form>
920
- </div>
921
- <p style="font-size: 0.8em; color: #666;">Automatic backup runs every 30 minutes if HF_TOKEN_WRITE is set.</p>
922
- </div>
923
-
924
- <div class="section">
925
- <h2>Resumes ({{ resumes|length }})</h2>
926
- {% for resume in resumes %}
927
- <div class="item">
928
- <h3>{{ resume.name }} - {{ resume.title }}</h3>
929
- <p>User ID: {{ resume.user_id }} (@{{ resume.user_telegram_username }})</p>
930
- <p>Posted: {{ resume.timestamp }}</p>
931
- <form method="POST" action="{{ url_for('admin_delete_item') }}" style="display:inline;" onsubmit="return confirm('Delete this resume?');">
932
- <input type="hidden" name="item_type" value="resumes">
933
- <input type="hidden" name="item_id" value="{{ resume.id }}">
934
- <button type="submit" class="button button-danger">Delete</button>
935
- </form>
936
- </div>
937
- {% else %}
938
- <p>No resumes found.</p>
939
- {% endfor %}
940
- </div>
941
-
942
- <div class="section">
943
- <h2>Vacancies ({{ vacancies|length }})</h2>
944
- {% for vacancy in vacancies %}
945
- <div class="item">
946
- <h3>{{ vacancy.title }} - {{ vacancy.company_name }}</h3>
947
- <p>User ID: {{ vacancy.user_id }} (@{{ vacancy.user_telegram_username }})</p>
948
- <p>Posted: {{ vacancy.timestamp }}</p>
949
- <form method="POST" action="{{ url_for('admin_delete_item') }}" style="display:inline;" onsubmit="return confirm('Delete this vacancy?');">
950
- <input type="hidden" name="item_type" value="vacancies">
951
- <input type="hidden" name="item_id" value="{{ vacancy.id }}">
952
- <button type="submit" class="button button-danger">Delete</button>
953
- </form>
954
- </div>
955
- {% else %}
956
- <p>No vacancies found.</p>
957
- {% endfor %}
958
- </div>
959
 
960
- <div class="section">
961
- <h2>Freelance Offers ({{ freelance_offers|length }})</h2>
962
- {% for offer in freelance_offers %}
963
- <div class="item">
964
- <h3>{{ offer.title }}</h3>
965
- <p>User ID: {{ offer.user_id }} (@{{ offer.user_telegram_username }})</p>
966
- <p>Budget: {{ offer.budget }}</p>
967
- <p>Posted: {{ offer.timestamp }}</p>
968
- <form method="POST" action="{{ url_for('admin_delete_item') }}" style="display:inline;" onsubmit="return confirm('Delete this freelance offer?');">
969
- <input type="hidden" name="item_type" value="freelance_offers">
970
- <input type="hidden" name="item_id" value="{{ offer.id }}">
971
- <button type="submit" class="button button-danger">Delete</button>
972
- </form>
973
- </div>
974
- {% else %}
975
- <p>No freelance offers found.</p>
976
- {% endfor %}
977
- </div>
978
- </div>
979
- </body>
980
- </html>
981
- '''
982
-
983
- @app.route('/')
984
- def main_app_view():
985
- return render_template_string(MAIN_APP_TEMPLATE)
986
-
987
- @app.route('/api/auth_user', methods=['POST'])
988
- def auth_user():
989
- auth_data_str = request.headers.get('X-Telegram-Auth')
990
- if not auth_data_str:
991
- init_data_payload = request.json.get('init_data')
992
- if init_data_payload:
993
- auth_data_str = init_data_payload
994
- else:
995
- return jsonify({"error": "Authentication data not provided"}), 401
996
-
997
- is_valid, user_data_from_auth = verify_telegram_auth_data(auth_data_str, TELEGRAM_BOT_TOKEN)
998
-
999
- if not is_valid or not user_data_from_auth:
1000
- return jsonify({"error": "Invalid authentication data"}), 403
1001
-
1002
- data = load_data()
1003
- users = data.get('users', {})
1004
- user_id_str = str(user_data_from_auth.get('id'))
1005
-
1006
- if user_id_str not in users:
1007
- users[user_id_str] = {
1008
- 'id': user_data_from_auth.get('id'),
1009
- 'first_name': user_data_from_auth.get('first_name'),
1010
- 'last_name': user_data_from_auth.get('last_name'),
1011
- 'username': user_data_from_auth.get('username'),
1012
- 'language_code': user_data_from_auth.get('language_code'),
1013
- 'photo_url': user_data_from_auth.get('photo_url'),
1014
- 'first_seen': datetime.now().isoformat()
1015
- }
1016
- users[user_id_str]['last_seen'] = datetime.now().isoformat()
1017
- if user_data_from_auth.get('photo_url'):
1018
- users[user_id_str]['photo_url'] = user_data_from_auth.get('photo_url')
1019
-
1020
- data['users'] = users
1021
- save_data(data)
1022
 
1023
- return jsonify({"message": "User authenticated", "user": users[user_id_str]}), 200
1024
-
1025
- def get_authenticated_user_details(request_headers):
1026
- auth_data_str = request_headers.get('X-Telegram-Auth')
1027
- if not auth_data_str:
1028
- return None
1029
- is_valid, user_data_from_auth = verify_telegram_auth_data(auth_data_str, TELEGRAM_BOT_TOKEN)
1030
- if is_valid and user_data_from_auth:
1031
- data = load_data()
1032
- user_id_str = str(user_data_from_auth.get('id'))
1033
- return data.get('users', {}).get(user_id_str)
1034
- return None
1035
-
1036
- @app.route('/api/<item_type>', methods=['GET'])
1037
- def get_items(item_type):
1038
- if item_type not in ['resumes', 'vacancies', 'freelance_offers']:
1039
- return jsonify({"error": "Invalid item type"}), 400
1040
- data = load_data()
1041
- items = sorted(data.get(item_type, []), key=lambda x: x.get('timestamp', ''), reverse=True)
1042
- return jsonify(items), 200
1043
-
1044
- @app.route('/api/<item_type>/<item_id>', methods=['GET'])
1045
- def get_item(item_type, item_id):
1046
- if item_type not in ['resumes', 'vacancies', 'freelance_offers']:
1047
- return jsonify({"error": "Invalid item type"}), 400
1048
- data = load_data()
1049
- item = next((i for i in data.get(item_type, []) if i['id'] == item_id), None)
1050
- if item:
1051
- return jsonify(item), 200
1052
- return jsonify({"error": "Item not found"}), 404
1053
-
1054
- @app.route('/api/<item_type>', methods=['POST'])
1055
- def create_item(item_type):
1056
- user = get_authenticated_user_details(request.headers)
1057
- if not user:
1058
- return jsonify({"error": "Authentication required or user not found in DB"}), 401
1059
-
1060
- if item_type not in ['resumes', 'vacancies', 'freelance_offers']:
1061
- return jsonify({"error": "Invalid item type"}), 400
1062
 
1063
- req_data = request.json
1064
- if not req_data:
1065
- return jsonify({"error": "No data provided"}), 400
1066
-
1067
- new_item = {
1068
- "id": str(uuid.uuid4()),
1069
- "user_id": str(user.get('id')),
1070
- "user_telegram_username": user.get('username', 'unknown'),
1071
- "timestamp": datetime.now().isoformat(),
1072
  }
1073
 
1074
- if item_type == 'resumes':
1075
- required_fields = ['name', 'title']
1076
- for field in required_fields:
1077
- if not req_data.get(field): return jsonify({"error": f"Missing field: {field}"}), 400
1078
- new_item.update({
1079
- "name": req_data.get('name'), "title": req_data.get('title'),
1080
- "skills": req_data.get('skills', ''), "experience": req_data.get('experience', ''),
1081
- "education": req_data.get('education', ''), "contact": req_data.get('contact', ''),
1082
- "portfolio_link": req_data.get('portfolio_link', '')
1083
- })
1084
- elif item_type == 'vacancies':
1085
- required_fields = ['company_name', 'title']
1086
- for field in required_fields:
1087
- if not req_data.get(field): return jsonify({"error": f"Missing field: {field}"}), 400
1088
- new_item.update({
1089
- "company_name": req_data.get('company_name'), "title": req_data.get('title'),
1090
- "description": req_data.get('description', ''), "requirements": req_data.get('requirements', ''),
1091
- "salary": req_data.get('salary', ''), "location": req_data.get('location', ''),
1092
- "contact": req_data.get('contact', '')
1093
- })
1094
- elif item_type == 'freelance_offers':
1095
- required_fields = ['title']
1096
- for field in required_fields:
1097
- if not req_data.get(field): return jsonify({"error": f"Missing field: {field}"}), 400
1098
- new_item.update({
1099
- "title": req_data.get('title'), "description": req_data.get('description', ''),
1100
- "budget": req_data.get('budget', ''), "deadline": req_data.get('deadline', ''),
1101
- "skills_needed": req_data.get('skills_needed', ''), "contact": req_data.get('contact', '')
1102
- })
1103
-
1104
- data = load_data()
1105
- data[item_type].append(new_item)
1106
- save_data(data)
1107
- return jsonify(new_item), 201
1108
-
1109
- @app.route('/api/<item_type>/<item_id>', methods=['PUT'])
1110
- def update_item(item_type, item_id):
1111
- user = get_authenticated_user_details(request.headers)
1112
- if not user: return jsonify({"error": "Authentication required or user not found in DB"}), 401
1113
-
1114
- if item_type not in ['resumes', 'vacancies', 'freelance_offers']:
1115
- return jsonify({"error": "Invalid item type"}), 400
1116
-
1117
- req_data = request.json
1118
- if not req_data: return jsonify({"error": "No data provided"}), 400
1119
-
1120
- data = load_data()
1121
- items_list = data.get(item_type, [])
1122
- item_index = -1
1123
- for idx, i in enumerate(items_list):
1124
- if i['id'] == item_id:
1125
- item_index = idx
1126
- break
1127
-
1128
- if item_index == -1: return jsonify({"error": "Item not found"}), 404
1129
-
1130
- original_item = items_list[item_index]
1131
- if str(original_item.get('user_id')) != str(user.get('id')):
1132
- return jsonify({"error": "Forbidden: You can only edit your own items"}), 403
1133
-
1134
- updated_item = original_item.copy()
1135
- updated_item['updated_timestamp'] = datetime.now().isoformat()
1136
-
1137
- if item_type == 'resumes':
1138
- updated_item.update({
1139
- "name": req_data.get('name', original_item.get('name')),
1140
- "title": req_data.get('title', original_item.get('title')),
1141
- "skills": req_data.get('skills', original_item.get('skills')),
1142
- "experience": req_data.get('experience', original_item.get('experience')),
1143
- "education": req_data.get('education', original_item.get('education')),
1144
- "contact": req_data.get('contact', original_item.get('contact')),
1145
- "portfolio_link": req_data.get('portfolio_link', original_item.get('portfolio_link'))
1146
- })
1147
- elif item_type == 'vacancies':
1148
- updated_item.update({
1149
- "company_name": req_data.get('company_name', original_item.get('company_name')),
1150
- "title": req_data.get('title', original_item.get('title')),
1151
- "description": req_data.get('description', original_item.get('description')),
1152
- "requirements": req_data.get('requirements', original_item.get('requirements')),
1153
- "salary": req_data.get('salary', original_item.get('salary')),
1154
- "location": req_data.get('location', original_item.get('location')),
1155
- "contact": req_data.get('contact', original_item.get('contact'))
1156
- })
1157
- elif item_type == 'freelance_offers':
1158
- updated_item.update({
1159
- "title": req_data.get('title', original_item.get('title')),
1160
- "description": req_data.get('description', original_item.get('description')),
1161
- "budget": req_data.get('budget', original_item.get('budget')),
1162
- "deadline": req_data.get('deadline', original_item.get('deadline')),
1163
- "skills_needed": req_data.get('skills_needed', original_item.get('skills_needed')),
1164
- "contact": req_data.get('contact', original_item.get('contact'))
1165
- })
1166
-
1167
- data[item_type][item_index] = updated_item
1168
- save_data(data)
1169
- return jsonify(updated_item), 200
1170
-
1171
- @app.route('/api/<item_type>/<item_id>', methods=['DELETE'])
1172
- def delete_item(item_type, item_id):
1173
- user = get_authenticated_user_details(request.headers)
1174
- if not user: return jsonify({"error": "Authentication required or user not found in DB"}), 401
1175
 
1176
- if item_type not in ['resumes', 'vacancies', 'freelance_offers']:
1177
- return jsonify({"error": "Invalid item type"}), 400
 
1178
 
1179
- data = load_data()
1180
- items_list = data.get(item_type, [])
1181
- original_length = len(items_list)
1182
-
1183
- item_to_delete = next((i for i in items_list if i['id'] == item_id), None)
1184
- if not item_to_delete: return jsonify({"error": "Item not found"}), 404
1185
 
1186
- if str(item_to_delete.get('user_id')) != str(user.get('id')):
1187
- return jsonify({"error": "Forbidden: You can only delete your own items"}), 403
1188
 
1189
- data[item_type] = [i for i in items_list if i['id'] != item_id]
 
1190
 
1191
- if len(data[item_type]) < original_length:
1192
- save_data(data)
1193
- return jsonify({"message": "Item deleted successfully"}), 200
1194
- return jsonify({"error": "Item not found or deletion failed"}), 404
1195
-
1196
-
1197
- @app.route('/admin', methods=['GET'])
1198
- def admin_panel():
1199
- data = load_data()
1200
- return render_template_string(ADMIN_TEMPLATE,
1201
- resumes=sorted(data.get('resumes', []), key=lambda x: x.get('timestamp', ''), reverse=True),
1202
- vacancies=sorted(data.get('vacancies', []), key=lambda x: x.get('timestamp', ''), reverse=True),
1203
- freelance_offers=sorted(data.get('freelance_offers', []), key=lambda x: x.get('timestamp', ''), reverse=True))
1204
-
1205
- @app.route('/admin/delete', methods=['POST'])
1206
- def admin_delete_item():
1207
- item_type = request.form.get('item_type')
1208
- item_id = request.form.get('item_id')
1209
-
1210
- if not item_type or not item_id or item_type not in ['resumes', 'vacancies', 'freelance_offers']:
1211
- flash('Invalid item type or ID for deletion.', 'error')
1212
- return redirect(url_for('admin_panel'))
1213
-
1214
- data = load_data()
1215
- items_list = data.get(item_type, [])
1216
- original_length = len(items_list)
1217
- data[item_type] = [i for i in items_list if i['id'] != item_id]
1218
-
1219
- if len(data[item_type]) < original_length:
1220
- save_data(data)
1221
- flash(f'{item_type.capitalize()[:-1]} deleted successfully.', 'success')
1222
- else:
1223
- flash('Item not found or already deleted.', 'warning')
1224
- return redirect(url_for('admin_panel'))
1225
-
1226
- @app.route('/admin/force_upload', methods=['POST'])
1227
- def force_upload_admin():
1228
- logging.info("Admin forcing upload to Hugging Face...")
1229
  try:
1230
- upload_db_to_hf()
1231
- flash("Data successfully uploaded to Hugging Face.", 'success')
1232
  except Exception as e:
1233
- logging.error(f"Error during forced upload: {e}", exc_info=True)
1234
- flash(f"Error uploading to Hugging Face: {e}", 'error')
1235
- return redirect(url_for('admin_panel'))
1236
-
1237
- @app.route('/admin/force_download', methods=['POST'])
1238
- def force_download_admin():
1239
- logging.info("Admin forcing download from Hugging Face...")
1240
- try:
1241
- if download_db_from_hf():
1242
- flash("Data successfully downloaded from Hugging Face. Local files updated.", 'success')
1243
- load_data()
1244
- else:
1245
- flash("Failed to download data from Hugging Face. Check logs.", 'error')
1246
- except Exception as e:
1247
- logging.error(f"Error during forced download: {e}", exc_info=True)
1248
- flash(f"Error downloading from Hugging Face: {e}", 'error')
1249
- return redirect(url_for('admin_panel'))
1250
-
1251
 
1252
  if __name__ == '__main__':
1253
- logging.info("Application starting up. Performing initial data load/download...")
1254
- download_db_from_hf()
1255
- load_data()
1256
- logging.info("Initial data load complete.")
 
1257
 
1258
- if HF_TOKEN_WRITE:
1259
- backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1260
- backup_thread.start()
1261
- logging.info("Periodic backup thread started.")
1262
- else:
1263
- logging.warning("Periodic backup will NOT run (HF_TOKEN_WRITE not set).")
1264
 
1265
- port = int(os.environ.get('PORT', 7860))
1266
- logging.info(f"Starting Flask app on host 0.0.0.0 and port {port}")
1267
- app.run(debug=False, host='0.0.0.0', port=port)
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
  import json
 
3
  import logging
4
+ import os
5
  import threading
6
+ from pathlib import Path
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ from aiogram import Bot, Dispatcher, types
9
+ from aiogram.filters import CommandStart
10
+ from aiogram.enums import ParseMode
11
+ from aiogram.types import FSInputFile
12
+ from aiogram.utils.markdown import html_escape
13
+ from aiogram.exceptions import TelegramAPIError
14
 
15
+ from flask import Flask, request, render_template_string, redirect, url_for
16
+ from werkzeug.utils import secure_filename
 
17
 
18
+ # --- Configuration ---
19
+ BOT_TOKEN = "7835463659:AAGNePbelZIAOeaglyQi1qulOqnjs4BGQn4"
20
+ FLASK_HOST = "0.0.0.0"
21
+ FLASK_PORT = 7860
22
 
23
+ BASE_DIR = Path(__file__).resolve().parent
24
+ SUBSCRIBED_USERS_FILE = BASE_DIR / "subscribed_users.json"
25
+ UPLOAD_FOLDER = BASE_DIR / "uploads"
26
 
27
+ # --- Logging ---
28
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # --- Global Variables for Bot and Queue ---
32
+ # These will be initialized in main_async
33
+ bot_instance: Bot = None
34
+ dp: Dispatcher = None
35
+ message_queue: asyncio.Queue = None
36
+ subscribed_users: set = set()
37
+ bot_loop: asyncio.AbstractEventLoop = None # To run coroutines from Flask thread
38
+
39
+ # --- User Persistence ---
40
+ def load_subscribed_users():
41
+ global subscribed_users
42
+ if SUBSCRIBED_USERS_FILE.exists():
43
+ try:
44
+ with open(SUBSCRIBED_USERS_FILE, 'r') as f:
45
+ user_ids = json.load(f)
46
+ subscribed_users = set(user_ids)
47
+ logger.info(f"Loaded {len(subscribed_users)} subscribed users.")
48
+ except json.JSONDecodeError:
49
+ logger.error(f"Error decoding JSON from {SUBSCRIBED_USERS_FILE}. Starting with empty list.")
50
+ subscribed_users = set()
51
+ except Exception as e:
52
+ logger.error(f"Error loading subscribed users: {e}")
53
+ subscribed_users = set()
54
+ else:
55
+ logger.info("Subscribed users file not found. Starting with empty list.")
56
+ subscribed_users = set()
57
 
58
+ def save_subscribed_users():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  try:
60
+ with open(SUBSCRIBED_USERS_FILE, 'w') as f:
61
+ json.dump(list(subscribed_users), f)
62
+ logger.info(f"Saved {len(subscribed_users)} subscribed users.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  except Exception as e:
64
+ logger.error(f"Error saving subscribed users: {e}")
65
 
66
+ # --- Aiogram Bot Logic ---
67
+ async def send_notification_to_user(user_id: int, text: str, file_path: str = None, file_type: str = None):
68
+ """Sends a notification to a single user, handling potential errors."""
69
+ global bot_instance
 
 
 
 
 
 
 
70
  try:
71
+ input_file = FSInputFile(file_path) if file_path else None
72
+
73
+ if file_path and input_file:
74
+ if file_type == 'photo':
75
+ await bot_instance.send_photo(chat_id=user_id, photo=input_file, caption=text, parse_mode=ParseMode.HTML)
76
+ elif file_type == 'video':
77
+ await bot_instance.send_video(chat_id=user_id, video=input_file, caption=text, parse_mode=ParseMode.HTML)
78
+ elif file_type == 'document':
79
+ await bot_instance.send_document(chat_id=user_id, document=input_file, caption=text, parse_mode=ParseMode.HTML)
80
+ elif file_type == 'audio':
81
+ await bot_instance.send_audio(chat_id=user_id, audio=input_file, caption=text, parse_mode=ParseMode.HTML)
82
+ else: # Default to sending text if file_type is unknown or file couldn't be processed
83
+ await bot_instance.send_message(chat_id=user_id, text=text, parse_mode=ParseMode.HTML)
84
+ if file_path: logger.warning(f"Unknown file type '{file_type}' for {file_path}, sent as text.")
85
+ elif text:
86
+ await bot_instance.send_message(chat_id=user_id, text=text, parse_mode=ParseMode.HTML)
87
+
88
+ logger.info(f"Sent notification to {user_id}")
89
+ return True
90
+
91
+ except TelegramAPIError as e:
92
+ logger.error(f"Telegram API Error sending to {user_id}: {e}")
93
+ if "bot was blocked by the user" in str(e) or "user is deactivated" in str(e) or "chat not found" in str(e):
94
+ logger.info(f"User {user_id} blocked the bot or is deactivated. Removing from subscribers.")
95
+ if user_id in subscribed_users:
96
+ subscribed_users.remove(user_id)
97
+ save_subscribed_users()
98
+ return False
99
+ except Exception as e:
100
+ logger.error(f"Unexpected error sending to {user_id}: {e}")
101
+ return False
102
 
103
+ async def process_notifications_from_queue():
104
+ """Continuously processes messages from the queue and sends them."""
105
+ global message_queue
106
+ while True:
107
  try:
108
+ notification_item = await message_queue.get()
109
+ text_content = notification_item.get("text")
110
+ file_path = notification_item.get("file_path")
111
+ file_type = notification_item.get("file_type")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
+ logger.info(f"Processing notification: Text='{text_content[:50]}...', File='{file_path}'")
114
+
115
+ # Create a copy of subscribed_users to iterate over, in case it's modified
116
+ current_subscribers = list(subscribed_users)
117
+
118
+ for user_id in current_subscribers:
119
+ await send_notification_to_user(user_id, text_content, file_path, file_type)
120
+ await asyncio.sleep(0.1) # Small delay to avoid hitting rate limits too hard
 
 
 
 
 
 
 
121
 
122
+ if file_path and os.path.exists(file_path):
123
+ try:
124
+ os.remove(file_path)
125
+ logger.info(f"Temporary file {file_path} deleted.")
126
+ except Exception as e:
127
+ logger.error(f"Error deleting temporary file {file_path}: {e}")
128
+
129
+ message_queue.task_done()
130
+ except asyncio.CancelledError:
131
+ logger.info("Notification processor task cancelled.")
132
+ break
133
+ except Exception as e:
134
+ logger.error(f"Error in notification processor: {e}")
135
+ # Potentially re-queue or handle the error, for now just log
136
+ if 'message_queue' in locals() and message_queue is not None: # Check if message_queue exists
137
+ message_queue.task_done() # Ensure task_done is called even on error to prevent blocking
138
+
139
+ @dp.message(CommandStart())
140
+ async def handle_start(message: types.Message):
141
+ user_id = message.from_user.id
142
+ if user_id not in subscribed_users:
143
+ subscribed_users.add(user_id)
144
+ save_subscribed_users()
145
+ logger.info(f"User {user_id} ({message.from_user.full_name}) subscribed.")
146
+ await message.reply("🎉 вы подписались на уведомления!")
147
+ else:
148
+ logger.info(f"User {user_id} ({message.from_user.full_name}) is already subscribed.")
149
+ await message.reply("Вы уже подписаны на уведомления. 👍")
150
 
151
+ # --- Flask Admin Panel ---
152
+ flask_app = Flask(__name__)
153
+ flask_app.config['UPLOAD_FOLDER'] = str(UPLOAD_FOLDER) # Flask expects string path
154
+ flask_app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50 MB limit for uploads
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
156
+ # Ensure UPLOAD_FOLDER exists
157
+ UPLOAD_FOLDER.mkdir(parents=True, exist_ok=True)
158
 
159
+ ADMIN_PANEL_HTML = """
160
  <!DOCTYPE html>
161
+ <html lang="ru">
162
  <head>
163
  <meta charset="UTF-8">
164
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
165
+ <title>Admin Panel - Telegram Notifier</title>
 
166
  <style>
167
+ body { font-family: sans-serif; margin: 20px; background-color: #f4f4f9; color: #333; }
168
+ .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
169
+ h1 { color: #5a5a5a; text-align: center; }
170
+ label { display: block; margin-bottom: 8px; font-weight: bold; }
171
+ textarea, input[type="file"] {
172
+ width: calc(100% - 22px); /* Adjust for padding and border */
173
+ padding: 10px;
174
+ margin-bottom: 20px;
175
+ border: 1px solid #ddd;
176
+ border-radius: 4px;
177
+ box-sizing: border-box; /* Important for width calculation */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  }
179
+ textarea { min-height: 100px; resize: vertical; }
180
+ button {
181
+ background-color: #007bff; color: white; padding: 12px 20px;
182
+ border: none; border-radius: 4px; cursor: pointer; font-size: 16px;
183
+ transition: background-color 0.3s ease;
184
  }
185
+ button:hover { background-color: #0056b3; }
186
+ .status {
187
+ margin-top: 20px; padding: 10px; border-radius: 4px;
 
188
  text-align: center;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  }
190
+ .status.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
191
+ .status.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
192
+ .loader {
193
+ border: 5px solid #f3f3f3; /* Light grey */
194
+ border-top: 5px solid #3498db; /* Blue */
 
 
 
 
 
195
  border-radius: 50%;
196
+ width: 30px;
197
+ height: 30px;
198
+ animation: spin 1s linear infinite;
199
+ margin: 10px auto;
200
+ display: none; /* Hidden by default */
 
 
 
 
 
201
  }
202
+ @keyframes spin {
203
+ 0% { transform: rotate(0deg); }
204
+ 100% { transform: rotate(360deg); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  }
 
 
 
 
206
  </style>
207
  </head>
208
  <body>
209
+ <div class="container">
210
+ <h1>Отправить уведомление</h1>
211
+ <form id="notificationForm" enctype="multipart/form-data">
212
+ <div>
213
+ <label for="message_text">Текст сообщения (HTML поддерживается):</label>
214
+ <textarea id="message_text" name="message_text" rows="5" required></textarea>
215
+ </div>
216
+ <div>
217
+ <label for="media_file">Прикрепить медиафайл (фото, видео, документ, аудио):</label>
218
+ <input type="file" id="media_file" name="media_file" accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.txt,.zip">
219
+ </div>
220
+ <button type="submit">Отправить всем</button>
221
+ </form>
222
+ <div class="loader" id="loader"></div>
223
+ <div id="statusMessage" class="status" style="display:none;"></div>
224
  </div>
225
 
226
  <script>
227
+ document.getElementById('notificationForm').addEventListener('submit', async function(event) {
228
+ event.preventDefault();
229
+ const form = event.target;
230
+ const formData = new FormData(form);
231
+ const statusDiv = document.getElementById('statusMessage');
232
+ const loader = document.getElementById('loader');
 
 
 
233
 
234
+ statusDiv.style.display = 'none';
235
+ statusDiv.className = 'status'; // Reset class
236
+ loader.style.display = 'block'; // Show loader
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  try {
239
+ const response = await fetch('/send_notification', {
240
+ method: 'POST',
241
+ body: formData
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  });
243
+ const result = await response.json();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
+ if (response.ok) {
246
+ statusDiv.textContent = result.message || 'Уведомление успешно отправлено в очередь.';
247
+ statusDiv.classList.add('success');
248
+ form.reset(); // Clear the form
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  } else {
250
+ statusDiv.textContent = result.error || 'Ошибка при отправке уведомления.';
251
+ statusDiv.classList.add('error');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  }
253
  } catch (error) {
254
+ console.error('Fetch error:', error);
255
+ statusDiv.textContent = 'Сетевая ошибка или ошибка сервера. Подробности в консоли.';
256
+ statusDiv.classList.add('error');
257
+ } finally {
258
+ loader.style.display = 'none'; // Hide loader
259
+ statusDiv.style.display = 'block';
260
  }
261
+ });
 
 
 
 
 
 
 
 
 
 
 
 
262
  </script>
263
  </body>
264
  </html>
265
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
 
267
+ @flask_app.route('/', methods=['GET'])
268
+ def admin_panel():
269
+ return render_template_string(ADMIN_PANEL_HTML)
270
+
271
+ def get_file_type(filename: str) -> str:
272
+ """Determines file type based on extension."""
273
+ ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
274
+ if ext in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']:
275
+ return 'photo'
276
+ elif ext in ['mp4', 'mov', 'avi', 'mkv', 'webm']:
277
+ return 'video'
278
+ elif ext in ['mp3', 'ogg', 'wav', 'flac', 'm4a']:
279
+ return 'audio'
280
+ elif ext in ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'rar']:
281
+ return 'document'
282
+ return None # Unknown or unsupported for specific sending
283
+
284
+ @flask_app.route('/send_notification', methods=['POST'])
285
+ def handle_send_notification():
286
+ global message_queue, bot_loop
287
+ if not message_queue or not bot_loop:
288
+ logger.error("Bot components (queue or loop) not initialized for Flask.")
289
+ return {"error": "Серверная ошибка: компоненты бота не инициализированы."}, 500
290
+
291
+ message_text_html = request.form.get('message_text', '')
292
+ if not message_text_html and 'media_file' not in request.files:
293
+ return {"error": "Требуется текст сообщения или медиафайл."}, 400
294
+
295
+ # HTML escape text if you don't trust the admin input for Telegram HTML parsing
296
+ # For this example, we assume admin can use basic HTML like <b>, <i>, <a>
297
+ # text_content = html_escape(message_text) # if you want to be super safe and send as plain text
298
+ text_content = message_text_html # Use as is, assuming admin knows HTML for Telegram
299
+
300
+ file_path = None
301
+ file_type = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
303
+ uploaded_file = request.files.get('media_file')
304
+ if uploaded_file and uploaded_file.filename != '':
305
+ filename = secure_filename(uploaded_file.filename)
306
+ file_path = str(UPLOAD_FOLDER / filename) # Store as string
307
+ try:
308
+ uploaded_file.save(file_path)
309
+ file_type = get_file_type(filename)
310
+ if not file_type:
311
+ logger.warning(f"Uploaded file {filename} has an unknown type for specific sending, will be sent as generic document or text only.")
312
+ # If file_type is crucial, you might want to return an error or default to 'document'
313
+ except Exception as e:
314
+ logger.error(f"Error saving uploaded file {filename}: {e}")
315
+ return {"error": f"Ошибка сохранения файла: {e}"}, 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
 
317
+ notification_item = {
318
+ "text": text_content,
319
+ "file_path": file_path,
320
+ "file_type": file_type
 
 
 
 
 
321
  }
322
 
323
+ try:
324
+ # Put the item into the asyncio queue from this synchronous thread
325
+ future = asyncio.run_coroutine_threadsafe(message_queue.put(notification_item), bot_loop)
326
+ future.result(timeout=5) # Wait for the put operation to complete, with a timeout
327
+ logger.info(f"Notification enqueued: Text='{text_content[:30]}...', File='{file_path}'")
328
+ return {"message": "Уведомление добавлено в очередь на отправку."}, 200
329
+ except asyncio.TimeoutError:
330
+ logger.error("Timeout putting notification onto the queue.")
331
+ if file_path and os.path.exists(file_path): # Cleanup if queueing failed
332
+ os.remove(file_path)
333
+ return {"error": "Не удалось добавить уведомление в очередь (тайм-аут)."}, 500
334
+ except Exception as e:
335
+ logger.error(f"Error putting notification onto the queue: {e}")
336
+ if file_path and os.path.exists(file_path): # Cleanup if queueing failed
337
+ os.remove(file_path)
338
+ return {"error": f"Ошибка добавления в очередь: {e}"}, 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
+ # --- Main Execution ---
341
+ async def main_async():
342
+ global bot_instance, dp, message_queue, bot_loop
343
 
344
+ bot_instance = Bot(token=BOT_TOKEN)
345
+ # dp is already initialized globally if you stick to that pattern,
346
+ # otherwise initialize here: dp = Dispatcher()
347
+ message_queue = asyncio.Queue()
348
+ bot_loop = asyncio.get_running_loop() # Get the current event loop
 
349
 
350
+ load_subscribed_users() # Load users before starting any tasks
 
351
 
352
+ # Start the background task for processing notifications
353
+ asyncio.create_task(process_notifications_from_queue())
354
 
355
+ logger.info("Starting Telegram bot polling...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  try:
357
+ await dp.start_polling(bot_instance, allowed_updates=dp.resolve_used_update_types())
 
358
  except Exception as e:
359
+ logger.critical(f"Fatal error in bot polling: {e}")
360
+ finally:
361
+ await bot_instance.session.close()
362
+ logger.info("Bot polling stopped and session closed.")
363
+
364
+ def run_flask():
365
+ logger.info(f"Starting Flask server on {FLASK_HOST}:{FLASK_PORT}")
366
+ # Use a production-ready WSGI server like gunicorn or waitress in a real setup
367
+ # For simplicity, Flask's built-in server is used here.
368
+ # Setting debug=False is generally recommended for anything beyond local dev.
369
+ flask_app.run(host=FLASK_HOST, port=FLASK_PORT, debug=False, use_reloader=False)
 
 
 
 
 
 
 
370
 
371
  if __name__ == '__main__':
372
+ # Initialize Dispatcher here if not done globally already
373
+ # This pattern is common when dp needs to be accessible globally for route decorators
374
+ dp = Dispatcher()
375
+ # Register handlers after dp is initialized
376
+ dp.message.register(handle_start, CommandStart())
377
 
 
 
 
 
 
 
378
 
379
+ # Start Flask in a separate thread
380
+ flask_thread = threading.Thread(target=run_flask, daemon=True)
381
+ flask_thread.start()
382
+
383
+ # Start Aiogram bot
384
+ try:
385
+ asyncio.run(main_async())
386
+ except KeyboardInterrupt:
387
+ logger.info("Application shutting down (KeyboardInterrupt)...")
388
+ except Exception as e:
389
+ logger.critical(f"Application crashed: {e}", exc_info=True)
390
+ finally:
391
+ logger.info("Application shutdown complete.")