Files
Citorrent/cli.py
2026-11-22 00:18:05 +04:00

153 lines
5.8 KiB
Python

import sys
import os
import argparse
import time
from src.core.torrent_session import TorrentSession
from src.data.database_manager import DatabaseManager
def get_app_dir():
if getattr(sys, 'frozen', False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
def main():
parser = argparse.ArgumentParser(description="Citorrent CLI Testing Tool")
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Add command
add_parser = subparsers.add_parser("add", help="Add a torrent (magnet or file path)")
add_parser.add_argument("source", help="Magnet URI or path to .torrent file")
# List command
subparsers.add_parser("list", help="List all torrents in database")
# Status command
status_parser = subparsers.add_parser("status", help="Get status of a specific torrent")
status_parser.add_argument("hash", help="Info hash of the torrent")
# Monitor command
monitor_parser = subparsers.add_parser("monitor", help="Monitor status of a specific torrent in real-time")
monitor_parser.add_argument("hash", help="Info hash of the torrent")
args = parser.parse_args()
app_dir = get_app_dir()
db_path = os.path.join(app_dir, "citorrent.data")
save_path = os.path.join(app_dir, "downloads")
os.makedirs(save_path, exist_ok=True)
session = TorrentSession(save_path=save_path)
db = DatabaseManager(db_path)
if args.command == "add":
print(f"Adding torrent: {args.source}")
try:
handle = None
if args.source.startswith("magnet:"):
handle = session.add_magnet(args.source)
else:
handle = session.add_torrent_file(args.source)
if handle:
info_hash = handle.info_hash().to_string()
if isinstance(info_hash, bytes):
info_hash = info_hash.hex()
# Simplified adding to DB for CLI tool
db.add_torrent({
"info_hash": info_hash,
"name": "Fetching...",
"save_path": save_path,
"status": "Starting",
"progress": 0,
"source": args.source
})
print(f"Successfully added torrent with hash: {info_hash}")
else:
print("Failed to add torrent.")
except Exception as e:
print(f"Error adding torrent: {e}")
elif args.command == "list":
torrents = db.get_all_torrents()
if not torrents:
print("No torrents found in database.")
return
print(f"{'Hash':<40} {'Name':<30} {'Status':<15} {'Progress':<10}")
print("-" * 95)
for t in torrents:
h = t.get('info_hash', 'N/A')
if isinstance(h, bytes):
h = h.hex()
print(f"{h:<40} {t.get('name', 'N/A'):<30} {t.get('status', 'N/A'):<15} {t.get('progress', 0):<10}")
elif args.command == "status":
# For status, we need to check if it's currently in the session
# Since CLI is short-lived, session only has what was just added or resumed
# In a real CLI tool we would resume all from DB first.
print("Resuming torrents from DB to check status...")
existing = db.get_all_torrents()
for t in existing:
source = t.get("source", "")
if source.startswith("magnet:"):
session.add_magnet(source)
elif os.path.exists(source):
session.add_torrent_file(source)
# Now check specific hash
found = False
print(f"Checking {len(session.get_all_handles())} active handles...")
for handle in session.get_all_handles():
h = handle.info_hash().to_string()
if isinstance(h, bytes): h = h.hex()
print(f"Found handle: {h}")
if h == args.hash:
status = session.get_status(handle)
print(f"Torrent {args.hash} Status:")
print(f" Name: {status['name']}")
print(f" Progress: {status['progress']:.2%}")
print(f" State: {status['state']}")
found = True
break
if not found:
print(f"Torrent with hash {args.hash} not found in active session.")
elif args.command == "monitor":
import time
print("Resuming torrents from DB to monitor status...")
existing = db.get_all_torrents()
for t in existing:
source = t.get("source", "")
if source.startswith("magnet:"):
session.add_magnet(source)
elif os.path.exists(source):
session.add_torrent_file(source)
print(f"Monitoring torrent {args.hash}. Press Ctrl+C to stop.")
try:
while True:
found = False
for handle in session.get_all_handles():
h = handle.info_hash().to_string()
if isinstance(h, bytes): h = h.hex()
if h == args.hash:
status = session.get_status(handle)
print(f"[{time.strftime('%H:%M:%S')}] {status['name']} | Progress: {status['progress']:.2%} | State: {status['state']}")
found = True
if str(status['state']) == 'seeding':
print("Torrent is now seeding!")
break
break
if not found:
print(f"[{time.strftime('%H:%M:%S')}] Torrent {args.hash} not found in active session.")
time.sleep(5)
except KeyboardInterrupt:
print("\nMonitoring stopped.")
else:
parser.print_help()
if __name__ == "__main__":
main()