Initial project structure and Phase 2 completion

This commit is contained in:
Mikan
2026-11-17 18:58:54 +04:00
commit 5415f32f78
12 changed files with 544 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Python
__pycache__/
*.py[cod]
*$py.class
.venv/
venv/
ENV/
env/
build/
dist/
*.egg-info/
# IDEs
.idea/
.vscode/
# Database
*.db
*.sqlite3
# Tests
.pytest_cache/
htmlcov/
.coverage

44
README.md Normal file
View File

@@ -0,0 +1,44 @@
# Citorrent
A simple, convenient, portable, and efficient torrent client.
## Tech Stack
- **Language**: Python 3.10+
- **Core Engine**: `libtorrent`
- **GUI**: `PySide6` (Qt for Python)
- **Database**: `SQLite`
- **Testing**: `pytest`
## Roadmap & Tasks
### Phase 1: Core Torrent Logic (TDD)
- [ ] Task 1.1: Setup project structure and environment.
- [x] Task 1.2: Implement basic `TorrentSession` wrapper for libtorrent.
- [ ] Task 1.3: Implement Magnet link adding functionality.
- [ ] Task 1.4: Implement `.torrent` file loading.
- [ ] Task 1.5: Track download progress and status updates.
### Phase 2: Data Persistence (TDD)
- [x] Task 2.1: Design SQLite schema for torrents and settings.
- [x] Task 2.2: Implement `DatabaseManager` for saving/loading torrent list.
- [x] Task 2.3: Implement settings persistence (paths, limits).
### Phase 3: GUI Development (TDD/Iterative)
- [ ] Task 3.1: Create main window layout with PySide6.
- [ ] Task 3.2: Implement torrent list view (updating in real-time).
- [ ] Task 3.3: Add "Add Torrent" dialog (Magnet/File).
- [ ] Task 3.4: Integrate Core and Data layers into the GUI via signals/slots.
- [ ] Task 3.5: Implement QSS styling for a modern look & feel.
- [ ] Task 3.6: Add application icons and visual assets.
### Phase 4: Portability & Polishing
- [ ] Task 4.1: Implement portable mode (config files in app directory).
- [ ] Task 4.2: Optimize memory and CPU usage.
- [ ] Task 4.3: Configure PyInstaller/Nuitka (.spec file) for a clean build.
- [ ] Task 4.4: Bundle into a single executable with embedded assets.
## Development Notes
- Follow TDD: Write tests first, then implementation.
- Use subagents for parallel work on Core, Data, and GUI modules.
- DatabaseManager uses SQLite with two tables: 'torrents' (for torrent metadata) and 'settings' (key-value store for application configuration). Row factory is used to return results as dictionaries for easier access.
- Used Python 3.12 because libtorrent had DLL load issues on Python 3.8 in this environment.

3
requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
pyside6
pytest
# libtorrent installation might vary; usually it's 'libtorrent' but we will verify in the environment setup phase.

View File

@@ -0,0 +1,15 @@
import libtorrent as lt
import os
class TorrentSession:
def __init__(self, save_path=None):
# Initialize a libtorrent session
self.lt_session = lt.session({'listen_interfaces': '0.0.0.0:6881'})
self.save_path = save_path or os.getcwd()
def add_magnet(self, magnet_link):
params = lt.parse_magnet_uri(magnet_link)
params.save_path = self.save_path
handle = self.lt_session.add_torrent(params)
return handle

View File

@@ -0,0 +1,98 @@
import sqlite3
from datetime import datetime
class DatabaseManager:
def __init__(self, db_path):
self.db_path = db_path
self._init_db()
def _init_db(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# Torrents table
cursor.execute('''
CREATE TABLE IF NOT EXISTS torrents (
info_hash TEXT PRIMARY KEY,
name TEXT,
save_path TEXT,
status TEXT,
progress REAL,
added_at DATETIME
)
''')
# Settings table
cursor.execute('''
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)
''')
conn.commit()
def add_torrent(self, torrent_data):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO torrents (info_hash, name, save_path, status, progress, added_at)
VALUES (?, ?, ?, ?, ?, ?)
''', (
torrent_data["info_hash"],
torrent_data["name"],
torrent_data["save_path"],
torrent_data["status"],
torrent_data["progress"],
datetime.now().isoformat()
))
conn.commit()
def get_torrent(self, info_hash):
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('SELECT * FROM torrents WHERE info_hash = ?', (info_hash,))
row = cursor.fetchone()
if row:
return dict(row)
return None
def get_all_torrents(self):
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('SELECT * FROM torrents')
rows = cursor.fetchall()
return [dict(row) for row in rows]
def update_torrent(self, info_hash, updates):
if not updates:
return
keys = list(updates.keys())
values = list(updates.values())
set_clause = ", ".join([f"{key} = ?" for key in keys])
params = values + [info_hash]
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(f'UPDATE torrents SET {set_clause} WHERE info_hash = ?', params)
conn.commit()
def remove_torrent(self, info_hash):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('DELETE FROM torrents WHERE info_hash = ?', (info_hash,))
conn.commit()
def set_setting(self, key, value):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)', (key, str(value)))
conn.commit()
def get_setting(self, key, default=None):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('SELECT value FROM settings WHERE key = ?', (key,))
row = cursor.fetchone()
return row[0] if row else default

View File

@@ -0,0 +1,109 @@
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
QLineEdit, QPushButton, QFileDialog, QComboBox)
from PySide6.QtCore import Qt
class AddTorrentDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("AddTorrentDialog")
self.setWindowTitle("Add Torrent")
self.setMinimumWidth(400)
self._setup_ui()
def _setup_ui(self):
layout = QVBoxLayout(self)
# Source Selection
source_layout = QHBoxLayout()
source_label = QLabel("Source:")
source_label.setObjectName("lblSource")
self.source_combo = QComboBox()
self.source_combo.setObjectName("cmbSource")
self.source_combo.addItems(["Magnet Link", "Torrent File"])
self.source_combo.currentTextChanged.connect(self._on_source_changed)
source_layout.addWidget(source_label)
source_layout.addWidget(self.source_combo)
layout.addLayout(source_layout)
# Input Area
self.input_container = QVBoxLayout()
# We will use a QStackedWidget for switching between Magnet and File inputs
from PySide6.QtWidgets import QStackedWidget
self.stack = QStackedWidget()
self.stack.setObjectName("InputStack")
# Magnet Page
magnet_page = QWidget()
magnet_page.setObjectName("MagnetPage")
mag_lay = QVBoxLayout(magnet_page)
self.magnet_label = QLabel("Magnet Link:")
self.magnet_label.setObjectName("lblMagnet")
self.magnet_input = QLineEdit()
self.magnet_input.setObjectName("txtMagnetLink")
self.magnet_input.setPlaceholderText("paste magnet link here...")
mag_lay.addWidget(self.magnet_label)
mag_lay.addWidget(self.magnet_input)
mag_lay.addStretch()
# File Page
file_page = QWidget()
file_page.setObjectName("FilePage")
file_lay = QVBoxLayout(file_page)
path_lay = QHBoxLayout()
self.file_label = QLabel("Torrent File:")
self.file_label.setObjectName("lblFile")
self.file_path_input = QLineEdit()
self.file_path_input.setObjectName("txtFilePath")
self.file_path_input.setReadOnly(True)
browse_btn = QPushButton("Browse...")
browse_btn.setObjectName("btnBrowse")
browse_btn.clicked.connect(self._on_browse_clicked)
path_lay.addWidget(self.file_path_input)
path_lay.addWidget(browse_btn)
file_lay.addWidget(self.file_label)
file_lay.addLayout(path_lay)
file_lay.addStretch()
self.stack.addWidget(magnet_page) # index 0
self.stack.addWidget(file_page) # index 1
self.input_container.addWidget(self.stack)
layout.addLayout(self.input_container)
# Buttons
btn_layout = QHBoxLayout()
ok_btn = QPushButton("Add")
ok_btn.setObjectName("btnAddTorrentConfirm")
cancel_btn = QPushButton("Cancel")
cancel_btn.setObjectName("btnCancelTorrent")
ok_btn.clicked.connect(self.accept)
cancel_btn.clicked.connect(self.reject)
btn_layout.addStretch()
btn_layout.addWidget(cancel_btn)
btn_layout.addWidget(ok_btn)
layout.addLayout(btn_layout)
def _on_source_changed(self, text):
if text == "Magnet Link":
self.stack.setCurrentIndex(0)
else:
self.stack.setCurrentIndex(1)
def _on_browse_clicked(self):
file_path, _ = QFileDialog.getOpenFileName(self, "Select Torrent File", "", "Torrent Files (*.torrent);;All Files (*)")
if file_path:
self.file_path_input.setText(file_path)
def get_data(self):
"""Return the selected source and value."""
source = self.source_combo.currentText()
if source == "Magnet Link":
return {"type": "magnet", "value": self.magnet_input.text()}
else:
return {"type": "file", "value": self.file_path_input.text()}

81
src/gui/main_window.py Normal file
View File

@@ -0,0 +1,81 @@
from PySide6.QtWidgets import (QMainWindow, QTableView, QVBoxLayout, QHBoxLayout,
QWidget, QPushButton, QToolBar, QStatusBar, QHeaderView)
from PySide6.QtCore import Qt, QTimer
from .torrent_model import TorrentModel
from .add_torrent_dialog import AddTorrentDialog
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setObjectName("MainWindow")
self.setWindowTitle("Citorrent")
self.resize(800, 600)
# Setup UI components
self._setup_toolbar()
self._setup_central_widget()
self._setup_statusbar()
# Task 3.2: Mock real-time updates
self._setup_mock_updates()
def _setup_toolbar(self):
toolbar = QToolBar("Main Toolbar")
toolbar.setObjectName("MainToolbar")
self.addToolBar(toolbar)
self.add_torrent_btn = QPushButton("Add Torrent")
self.add_torrent_btn.setObjectName("btnAddTorrent")
# Task 3.3: This will trigger the dialog later
self.add_torrent_btn.clicked.connect(self._on_add_torrent_clicked)
toolbar.addWidget(self.add_torrent_btn)
def _setup_central_widget(self):
central_widget = QWidget()
central_widget.setObjectName("CentralWidget")
layout = QVBoxLayout(central_widget)
# Torrent List View (Task 3.2)
self.torrent_table = QTableView()
self.torrent_table.setObjectName("TorrentTable")
self.model = TorrentModel()
self.torrent_table.setModel(self.model)
# Stretch columns to fill space
header = self.torrent_table.horizontalHeader()
header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
layout.addWidget(self.torrent_table)
self.setCentralWidget(central_widget)
def _setup_statusbar(self):
self.setStatusBar(QStatusBar())
self.statusBar().setObjectName("MainStatusBar")
def _on_add_torrent_clicked(self):
# Task 3.3: Implementation of Add Torrent dialog
dialog = AddTorrentDialog(self)
if dialog.exec():
data = dialog.get_data()
print(f"Adding torrent: {data}")
self.statusBar().showMessage(f"Added {data['type']}: {data['value'][:30]}...", 5000)
def _setup_mock_updates(self):
"""Simulate real-time torrent progress updates."""
self.update_timer = QTimer()
self.update_timer.timeout.connect(self._simulate_progress)
self.update_timer.start(1000) # Update every second
def _simulate_progress(self):
import random
# Randomly update one of the torrents in the mock model
idx = random.randint(0, self.model.rowCount() - 1)
# Accessing _torrents directly for simplicity in mock
torrent = self.model._torrents[idx]
if torrent["progress"] < 1.0:
new_progress = min(1.0, torrent["progress"] + random.uniform(0.001, 0.02))
status = "Downloading" if new_progress < 1.0 else "Completed"
self.model.update_torrent_progress(idx, new_progress, status)

51
src/gui/torrent_model.py Normal file
View File

@@ -0,0 +1,51 @@
from PySide6.QtCore import Qt, QAbstractTableModel, QModelIndex
class TorrentModel(QAbstractTableModel):
def __init__(self, torrents=None):
super().__init__()
# Mock data: List of dicts
self._torrents = torrents or [
{"name": "Ubuntu 22.04 LTS", "size": "4.5 GB", "progress": 0.45, "status": "Downloading"},
{"name": "Debian GNU/Linux", "size": "3.8 GB", "progress": 1.0, "status": "Completed"},
{"name": "Fedora Workstation", "size": "2.1 GB", "progress": 0.12, "status": "Downloading"},
{"name": "Arch Linux ISO", "size": "850 MB", "progress": 0.0, "status": "Queued"},
]
self._headers = ["Name", "Size", "Progress", "Status"]
def rowCount(self, parent=QModelIndex()):
return len(self._torrents)
def columnCount(self, parent=QModelIndex()):
return len(self._headers)
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
if not index.isValid():
return None
torrent = self._torrents[index.row()]
column = index.column()
if role == Qt.ItemDataRole.DisplayRole:
if column == 0:
return torrent["name"]
elif column == 1:
return torrent["size"]
elif column == 2:
return f"{torrent['progress'] * 100:.1f}%"
elif column == 3:
return torrent["status"]
return None
def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
return self._headers[section]
return None
def update_torrent_progress(self, index, progress, status):
"""Update mock data for real-time simulation."""
if 0 <= index < len(self._torrents):
self._torrents[index]["progress"] = progress
self._torrents[index]["status"] = status
# Notify the view that this row has changed
self.dataChanged.emit(self.index(index, 2), self.index(index, 3))

14
src/main.py Normal file
View File

@@ -0,0 +1,14 @@
import sys
from PySide6.QtWidgets import QApplication
from gui.main_window import MainWindow
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,17 @@
import pytest
from src.core.torrent_session import TorrentSession
def test_torrent_session_initialization():
session = TorrentSession()
assert session is not None
# We expect the session to have an internal libtorrent session object
assert hasattr(session, 'lt_session')
assert session.lt_session is not None
def test_add_magnet_link():
session = TorrentSession()
magnet_link = "magnet:?xt=urn:btih:d548903162f7e9c534da2a0bc8b42968681f5ca3&dn=ubuntu-22.04.3-desktop-amd64"
handle = session.add_magnet(magnet_link)
assert handle is not None
# The handle should be a libtorrent torrent_handle object, which has status() method
assert hasattr(handle, 'status')

View File

@@ -0,0 +1,60 @@
import pytest
import os
from src.data.database_manager import DatabaseManager
def test_add_and_get_torrent(tmp_path):
db_path = tmp_path / "test_citorrent.db"
db = DatabaseManager(str(db_path))
torrent_data = {
"info_hash": "abc123hash",
"name": "Test Torrent",
"save_path": "/downloads/test",
"status": "downloading",
"progress": 0.5
}
db.add_torrent(torrent_data)
retrieved = db.get_torrent("abc123hash")
assert retrieved is not None
assert retrieved["name"] == "Test Torrent"
assert retrieved["info_hash"] == "abc123hash"
def test_get_all_torrents(tmp_path):
db_path = tmp_path / "test_citorrent.db"
db = DatabaseManager(str(db_path))
torrents = [
{"info_hash": "h1", "name": "T1", "save_path": "/p1", "status": "s1", "progress": 0.1},
{"info_hash": "h2", "name": "T2", "save_path": "/p2", "status": "s2", "progress": 0.2},
]
for t in torrents:
db.add_torrent(t)
all_torrents = db.get_all_torrents()
assert len(all_torrents) == 2
hashes = [t["info_hash"] for t in all_torrents]
assert "h1" in hashes
assert "h2" in hashes
def test_update_torrent(tmp_path):
db_path = tmp_path / "test_citorrent.db"
db = DatabaseManager(str(db_path))
db.add_torrent({"info_hash": "h1", "name": "T1", "save_path": "/p1", "status": "s1", "progress": 0.1})
db.update_torrent("h1", {"progress": 0.6, "status": "completed"})
retrieved = db.get_torrent("h1")
assert retrieved["progress"] == 0.6
assert retrieved["status"] == "completed"
def test_remove_torrent(tmp_path):
db_path = tmp_path / "test_citorrent.db"
db = DatabaseManager(str(db_path))
db.add_torrent({"info_hash": "h1", "name": "T1", "save_path": "/p1", "status": "s1", "progress": 0.1})
db.remove_torrent("h1")
assert db.get_torrent("h1") is None

View File

@@ -0,0 +1,28 @@
import pytest
from src.data.database_manager import DatabaseManager
def test_set_and_get_setting(tmp_path):
db_path = tmp_path / "test_citorrent.db"
db = DatabaseManager(str(db_path))
db.set_setting("download_path", "/downloads/my_torrents")
value = db.get_setting("download_path")
assert value == "/downloads/my_torrents"
def test_get_nonexistent_setting(tmp_path):
db_path = tmp_path / "test_citorrent.db"
db = DatabaseManager(str(db_path))
value = db.get_setting("nonexistent")
assert value is None
def test_update_setting(tmp_path):
db_path = tmp_path / "test_citorrent.db"
db = DatabaseManager(str(db_path))
db.set_setting("max_connections", "100")
db.set_setting("max_connections", "200")
value = db.get_setting("max_connections")
assert value == "200"