Cxops commited on
Commit
4ab04de
·
verified ·
1 Parent(s): d6fad93

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -30
app.py CHANGED
@@ -80,6 +80,10 @@ def db_remove_file(enc_path):
80
  cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
81
  conn.commit()
82
 
 
 
 
 
83
  # --------------- CALLBACK MAPPINGS ---------------
84
  file_callback_map = {} # token -> enc_path
85
  upload_prompt_map = {} # token -> list of (user_id, message_id, orig_filename)
@@ -261,14 +265,12 @@ async def do_download_job(chat_id, enc_path, orig_name, job_id, cancel_event, st
261
  try:
262
  loop = asyncio.get_event_loop()
263
 
264
- # 1. Download from HF using robust hf_hub_download (handles retries + resume)
265
  await status_msg.edit_text("⬇️ Downloading from dataset...",
266
  reply_markup=InlineKeyboardMarkup([
267
  [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]
268
  ]))
269
 
270
- # Run the download in an executor; cancel_event will stop waiting but the download may still finish.
271
- # We can't cancel the download itself, but we'll stop sending the file if cancelled.
272
  download_future = loop.run_in_executor(
273
  None,
274
  lambda: hf_hub_download(
@@ -280,15 +282,13 @@ async def do_download_job(chat_id, enc_path, orig_name, job_id, cancel_event, st
280
  )
281
  )
282
 
283
- # Wait for download to complete or cancel
284
  while not download_future.done():
285
  if cancel_event.is_set():
286
- # We can't cancel the future, but we can stop waiting and cleanup
287
  await status_msg.edit_text("❌ Download cancelled.", reply_markup=None)
288
  return
289
  await asyncio.sleep(1)
290
 
291
- local_file = download_future.result() # raises if error
292
  total_size = os.path.getsize(local_file)
293
 
294
  # 2. Send back to Telegram (with speed/progress if single file)
@@ -336,8 +336,9 @@ async def do_download_job(chat_id, enc_path, orig_name, job_id, cancel_event, st
336
  finally:
337
  cleanup(temp_dir)
338
 
339
- # --------------- DELETE FILE HELPER ---------------
340
  async def delete_user_file(chat_id, user_id, enc_path, token, query):
 
341
  try:
342
  hf.delete_file(
343
  path_in_repo=enc_path,
@@ -351,7 +352,37 @@ async def delete_user_file(chat_id, user_id, enc_path, token, query):
351
  except Exception as e:
352
  await query.answer(f"Error: {e}", show_alert=True)
353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  async def refresh_file_list(chat_id, user_id, message):
 
355
  user_files = db_get_user_files(user_id)
356
  if not user_files:
357
  return await message.edit_text("You have no uploaded files.", reply_markup=None)
@@ -365,6 +396,9 @@ async def refresh_file_list(chat_id, user_id, message):
365
  InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}")
366
  ])
367
 
 
 
 
368
  await message.edit_text(
369
  "Your uploaded files (click to download, delete to remove):",
370
  reply_markup=InlineKeyboardMarkup(buttons)
@@ -372,7 +406,6 @@ async def refresh_file_list(chat_id, user_id, message):
372
 
373
  # --------------- ALBUM GROUP PROCESSING ---------------
374
  async def process_album_group(media_group_id: str):
375
- """Called after a timer to handle all files in an album."""
376
  group_data = album_groups.pop(media_group_id, None)
377
  if not group_data:
378
  return
@@ -382,33 +415,24 @@ async def process_album_group(media_group_id: str):
382
  messages = group_data['messages'] # list of (message_id, filename)
383
 
384
  if len(messages) == 1:
385
- # Single file – treat as normal (should already have been handled, but just in case)
386
  msg_id, filename = messages[0]
387
- # This case won't normally occur because we send individual prompt immediately; but if timer fired for a single message, do normal.
388
- # We'll just fall back to single prompt.
389
  token = make_token()
390
  upload_prompt_map[token] = [(user_id, msg_id, filename)]
391
  kb = InlineKeyboardMarkup([
392
  [InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
393
  [InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")]
394
  ])
395
- try:
396
- await app.send_message(chat_id, f"Do you want to upload `{filename}`?", reply_markup=kb)
397
- except Exception:
398
- pass
399
  else:
400
- # Multiple files – build a combined prompt
401
  files_list = "\n".join(f"• {fname}" for _, fname in messages)
402
  token = make_token()
403
- # Store all files in the mapping
404
  upload_prompt_map[token] = [(user_id, msg_id, fname) for msg_id, fname in messages]
405
 
406
- # Buttons: "Upload All" + individual "Upload File" for each file
407
  button_rows = []
408
  button_rows.append([InlineKeyboardButton("⬆️ Upload All", callback_data=f"upload_all:{token}")])
409
- for idx, (msg_id, fname) in enumerate(messages):
410
- # Separate token for individual upload? We could use same token but we need to know which file.
411
- # Better: create individual tokens for each file.
412
  individual_token = make_token()
413
  upload_prompt_map[individual_token] = [(user_id, msg_id, fname)]
414
  button_rows.append([InlineKeyboardButton(f"📤 {fname[:40]}", callback_data=f"upload:{individual_token}")])
@@ -493,6 +517,9 @@ async def list_files_cmd(_, message):
493
  InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}")
494
  ])
495
 
 
 
 
496
  await message.reply_text(
497
  "Your uploaded files (click to download, delete to remove):",
498
  reply_markup=InlineKeyboardMarkup(buttons)
@@ -543,6 +570,12 @@ async def delete_file_callback(_, query):
543
 
544
  await delete_user_file(chat_id, user_id, enc_path, token, query)
545
 
 
 
 
 
 
 
546
  @app.on_callback_query(filters.regex("^cancel_job:"))
547
  async def cancel_job_callback(_, query):
548
  _, job_id_str = query.data.split(":")
@@ -560,7 +593,6 @@ async def upload_callback(_, query):
560
  if not data:
561
  return await query.answer("Upload prompt expired. Please send the file again.", show_alert=True)
562
 
563
- # data is a list of (user_id, message_id, orig_filename) – for single upload it's one item
564
  chat_id = query.message.chat.id
565
  for user_id, msg_id, orig_filename in data:
566
  try:
@@ -572,12 +604,12 @@ async def upload_callback(_, query):
572
  await query.answer(f"File {orig_filename} no longer available.", show_alert=True)
573
  continue
574
 
575
- job_id = int(time.time() * 1000 + hash(orig_filename)) # ensure uniqueness
576
  active_jobs[job_id] = {"status": "queued"}
577
  await upload_queue.put((user_id, chat_id, file_msg, orig_filename, job_id))
578
 
579
  await query.message.edit_text(
580
- f"📦 {len(data)} file(s) added to queue.\nYou'll be notified when each starts.",
581
  reply_markup=None
582
  )
583
 
@@ -612,7 +644,6 @@ async def cancel_upload_prompt(_, query):
612
  # ----------- RECEIVING FILES (with album grouping) -----------
613
  @app.on_message(filters.document | filters.video | filters.audio | filters.photo)
614
  async def on_file(_, message):
615
- # Determine filename
616
  if message.document:
617
  filename = message.document.file_name
618
  elif message.video:
@@ -622,7 +653,6 @@ async def on_file(_, message):
622
  else:
623
  filename = f"{message.photo.file_unique_id}.jpg"
624
 
625
- # Check if part of an album (media_group_id exists)
626
  if message.media_group_id:
627
  group_id = str(message.media_group_id)
628
  chat_id = message.chat.id
@@ -638,19 +668,17 @@ async def on_file(_, message):
638
 
639
  album_groups[group_id]['messages'].append((message.id, filename))
640
 
641
- # Cancel existing timer
642
  if album_groups[group_id]['timer']:
643
  album_groups[group_id]['timer'].cancel()
644
 
645
- # Set a new timer for 2 seconds
646
  async def timer_callback(gid=group_id):
647
  await asyncio.sleep(2)
648
  await process_album_group(gid)
649
 
650
  album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
651
- return # Don't send individual prompt yet
652
 
653
- # Single file (no group)
654
  token = make_token()
655
  upload_prompt_map[token] = [(message.from_user.id, message.id, filename)]
656
 
 
80
  cursor.execute("DELETE FROM files WHERE enc_path = ?", (enc_path,))
81
  conn.commit()
82
 
83
+ def db_remove_all_user_files(user_id):
84
+ cursor.execute("DELETE FROM files WHERE user_id = ?", (user_id,))
85
+ conn.commit()
86
+
87
  # --------------- CALLBACK MAPPINGS ---------------
88
  file_callback_map = {} # token -> enc_path
89
  upload_prompt_map = {} # token -> list of (user_id, message_id, orig_filename)
 
265
  try:
266
  loop = asyncio.get_event_loop()
267
 
268
+ # 1. Download from HF using robust hf_hub_download (resilient to connection issues)
269
  await status_msg.edit_text("⬇️ Downloading from dataset...",
270
  reply_markup=InlineKeyboardMarkup([
271
  [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]
272
  ]))
273
 
 
 
274
  download_future = loop.run_in_executor(
275
  None,
276
  lambda: hf_hub_download(
 
282
  )
283
  )
284
 
 
285
  while not download_future.done():
286
  if cancel_event.is_set():
 
287
  await status_msg.edit_text("❌ Download cancelled.", reply_markup=None)
288
  return
289
  await asyncio.sleep(1)
290
 
291
+ local_file = download_future.result()
292
  total_size = os.path.getsize(local_file)
293
 
294
  # 2. Send back to Telegram (with speed/progress if single file)
 
336
  finally:
337
  cleanup(temp_dir)
338
 
339
+ # --------------- DELETE FUNCTIONS ---------------
340
  async def delete_user_file(chat_id, user_id, enc_path, token, query):
341
+ """Delete a single file from HF and DB, then refresh the list."""
342
  try:
343
  hf.delete_file(
344
  path_in_repo=enc_path,
 
352
  except Exception as e:
353
  await query.answer(f"Error: {e}", show_alert=True)
354
 
355
+ async def delete_all_user_files(chat_id, user_id, query):
356
+ """Delete all files of a user from HF and DB, then refresh."""
357
+ user_files = db_get_user_files(user_id)
358
+ if not user_files:
359
+ await query.answer("No files to delete.", show_alert=True)
360
+ return
361
+
362
+ # Delete from HF
363
+ for enc_path, _, _ in user_files:
364
+ try:
365
+ hf.delete_file(
366
+ path_in_repo=enc_path,
367
+ repo_id=DATASET_REPO,
368
+ repo_type="dataset",
369
+ )
370
+ except Exception:
371
+ pass # skip if not found
372
+
373
+ # Clear DB
374
+ db_remove_all_user_files(user_id)
375
+
376
+ # Clear callback tokens for this user
377
+ tokens_to_delete = [tok for tok, path in file_callback_map.items() if path.startswith(get_encrypted_folder(user_id))]
378
+ for tok in tokens_to_delete:
379
+ file_callback_map.pop(tok, None)
380
+
381
+ await query.answer(f"Deleted {len(user_files)} file(s).", show_alert=True)
382
+ await refresh_file_list(chat_id, user_id, query.message)
383
+
384
  async def refresh_file_list(chat_id, user_id, message):
385
+ """Re‑fetch user files and edit the message with updated buttons."""
386
  user_files = db_get_user_files(user_id)
387
  if not user_files:
388
  return await message.edit_text("You have no uploaded files.", reply_markup=None)
 
396
  InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}")
397
  ])
398
 
399
+ # Add "Delete All" button as a separate row
400
+ buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
401
+
402
  await message.edit_text(
403
  "Your uploaded files (click to download, delete to remove):",
404
  reply_markup=InlineKeyboardMarkup(buttons)
 
406
 
407
  # --------------- ALBUM GROUP PROCESSING ---------------
408
  async def process_album_group(media_group_id: str):
 
409
  group_data = album_groups.pop(media_group_id, None)
410
  if not group_data:
411
  return
 
415
  messages = group_data['messages'] # list of (message_id, filename)
416
 
417
  if len(messages) == 1:
418
+ # single file – normal prompt
419
  msg_id, filename = messages[0]
 
 
420
  token = make_token()
421
  upload_prompt_map[token] = [(user_id, msg_id, filename)]
422
  kb = InlineKeyboardMarkup([
423
  [InlineKeyboardButton("⬆️ Upload File", callback_data=f"upload:{token}")],
424
  [InlineKeyboardButton("❌ Cancel", callback_data="cancel_upload:0")]
425
  ])
426
+ await app.send_message(chat_id, f"Do you want to upload `{filename}`?", reply_markup=kb)
 
 
 
427
  else:
428
+ # multiple files – combined prompt
429
  files_list = "\n".join(f"• {fname}" for _, fname in messages)
430
  token = make_token()
 
431
  upload_prompt_map[token] = [(user_id, msg_id, fname) for msg_id, fname in messages]
432
 
 
433
  button_rows = []
434
  button_rows.append([InlineKeyboardButton("⬆️ Upload All", callback_data=f"upload_all:{token}")])
435
+ for msg_id, fname in messages:
 
 
436
  individual_token = make_token()
437
  upload_prompt_map[individual_token] = [(user_id, msg_id, fname)]
438
  button_rows.append([InlineKeyboardButton(f"📤 {fname[:40]}", callback_data=f"upload:{individual_token}")])
 
517
  InlineKeyboardButton("🗑 Delete", callback_data=f"delete:{token}")
518
  ])
519
 
520
+ # Add "Delete All" button
521
+ buttons.append([InlineKeyboardButton("⚠️ Delete All Files", callback_data=f"delete_all:{user_id}")])
522
+
523
  await message.reply_text(
524
  "Your uploaded files (click to download, delete to remove):",
525
  reply_markup=InlineKeyboardMarkup(buttons)
 
570
 
571
  await delete_user_file(chat_id, user_id, enc_path, token, query)
572
 
573
+ @app.on_callback_query(filters.regex("^delete_all:"))
574
+ async def delete_all_callback(_, query):
575
+ user_id = int(query.data.split(":")[-1])
576
+ chat_id = query.message.chat.id
577
+ await delete_all_user_files(chat_id, user_id, query)
578
+
579
  @app.on_callback_query(filters.regex("^cancel_job:"))
580
  async def cancel_job_callback(_, query):
581
  _, job_id_str = query.data.split(":")
 
593
  if not data:
594
  return await query.answer("Upload prompt expired. Please send the file again.", show_alert=True)
595
 
 
596
  chat_id = query.message.chat.id
597
  for user_id, msg_id, orig_filename in data:
598
  try:
 
604
  await query.answer(f"File {orig_filename} no longer available.", show_alert=True)
605
  continue
606
 
607
+ job_id = int(time.time() * 1000 + hash(orig_filename))
608
  active_jobs[job_id] = {"status": "queued"}
609
  await upload_queue.put((user_id, chat_id, file_msg, orig_filename, job_id))
610
 
611
  await query.message.edit_text(
612
+ f"📦 {len(data)} file(s) added to queue.",
613
  reply_markup=None
614
  )
615
 
 
644
  # ----------- RECEIVING FILES (with album grouping) -----------
645
  @app.on_message(filters.document | filters.video | filters.audio | filters.photo)
646
  async def on_file(_, message):
 
647
  if message.document:
648
  filename = message.document.file_name
649
  elif message.video:
 
653
  else:
654
  filename = f"{message.photo.file_unique_id}.jpg"
655
 
 
656
  if message.media_group_id:
657
  group_id = str(message.media_group_id)
658
  chat_id = message.chat.id
 
668
 
669
  album_groups[group_id]['messages'].append((message.id, filename))
670
 
 
671
  if album_groups[group_id]['timer']:
672
  album_groups[group_id]['timer'].cancel()
673
 
 
674
  async def timer_callback(gid=group_id):
675
  await asyncio.sleep(2)
676
  await process_album_group(gid)
677
 
678
  album_groups[group_id]['timer'] = asyncio.create_task(timer_callback())
679
+ return
680
 
681
+ # Single file
682
  token = make_token()
683
  upload_prompt_map[token] = [(message.from_user.id, message.id, filename)]
684