Compare commits

..
Author SHA1 Message Date
Gustavo Henrique Miranda e7a7d0cd87 Merge 447dffd7df into f825236c45 2025-07-24 23:26:20 +00:00
Gustavo Henrique Miranda f825236c45 Merge pull request #48 from gmbrax/staging
Staging
2025-07-19 20:28:17 -03:00
Gustavo Henrique Miranda 8f36e5a770 Merge pull request #37 from gmbrax/dependabot/pip/typing-extensions-4.14.1
Bump typing-extensions from 4.14.0 to 4.14.1
2025-07-14 19:15:54 -03:00
Gustavo Henrique Miranda 11e9cf6e75 Merge pull request #38 from gmbrax/dependabot/pip/textual-approx-eq-4.0.0
Update textual requirement from ~=3.3.0 to ~=4.0.0
2025-07-14 19:14:47 -03:00
13 changed files with 642 additions and 450 deletions
+34 -55
View File
@@ -6,84 +6,63 @@ The format is based on Keep a Changelog, and this project adheres to Semantic Ve
## Unreleased ## Unreleased
## Planned ## Planned
* Restore from backup functionality * Installation Method 1 (repository compilation)
* Organization of trips by date, location, or theme * Organization of trips by date, location, or theme
* Enhanced photo management features * Enhanced photo management features
* Search functionality * Search functionality
* Export features * Export features
* UI Testing with Textual Pilot * Testing implementation
## [0.0.5] - 2025-07-24
### Added
* **Backup Feature:** Introduced a full backup feature to export the database and all photos to a single ZIP file.
* **Diary Settings Screen:** Added a dedicated settings screen per diary, accessible with the 's' key from the diary list.
* **Advanced Deletion Options:** The new settings screen allows for deleting the entire diary, all of its entries, or all of its photos.
* **Confirmation Modals:** Added confirmation modals that require the user to type the diary's name to proceed with critical delete operations, preventing accidental data loss.
* **Comprehensive Test Suite:** Implemented a robust unit and integration test suite for the entire backend (services, models, utils, application), achieving high code coverage and ensuring stability.
### Changed
* **Architectural Refactor:** Service methods were refactored to be transactional, allowing for more complex operations to be executed safely and atomically.
* **Configuration:** The "auto-open diary on startup" setting is now managed and persisted via the `config.toml` file.
* **Project Structure:** Standardized project metadata and build configuration in `pyproject.toml` and converted all imports to use a consistent absolute path structure.
### Fixed
* **Directory Name Sanitization:** Fixed a bug where directory names were not correctly sanitized, now properly handling accented and special characters by using transliteration.
* **Data Integrity:** Enforced `NOT NULL` constraints on `title` and `date` fields for entries in the database, preventing the creation of entries with invalid data.
### Removed
* **Obsolete Mocks:** Removed old and unused mock service files from the production codebase.
## [0.0.4] - 2025-07-19 ## [0.0.4] - 2025-07-19
### Added ### Added
* Support for creating new diaries asynchronously, with an option to automatically open the newly created diary. * Support for creating new diaries asynchronously, with an option to automatically open the newly created diary
* Unified "Enter" key support for saving or creating diaries across relevant modals. * Unified "Enter" key support for saving or creating diaries across relevant modals
* Automatic diary list refresh when returning to the diary screen. * Automatic diary list refresh when returning to the diary screen
* Application configuration management with a new centralized config system. * Application configuration management with a new centralized config system
* Database location and initialization now configurable via the new config manager. * Database location and initialization now configurable via the new config manager
* Automatic migration of database file to the configuration directory. * Automatic migration of database file to the configuration directory
* Display of database URL on application startup for transparency. * Display of database URL on application startup for transparency
* Duplicate photo detection before photo creation to prevent redundant entries. * Duplicate photo detection before photo creation to prevent redundant entries
* Photo hash indexing to improve photo lookup performance. * Photo hash indexing to improve photo lookup performance
### Changed ### Changed
* Enhanced feedback and validation when editing or creating diary names. * Enhanced feedback and validation when editing or creating diary names
* Streamlined and unified save logic for diary modals, reducing duplicated behavior. * Streamlined and unified save logic for diary modals, reducing duplicated behavior
* About screen now displays the actual installed application version dynamically. * About screen now displays the actual installed application version dynamically
* Sidebar and photo-related UI text updated to remove emoji icons for a cleaner appearance. * Sidebar and photo-related UI text updated to remove emoji icons for a cleaner appearance
* Sidebar layout and scrolling behavior improved for better usability. * Sidebar layout and scrolling behavior improved for better usability
* Photo hash generation now relies on existing service-provided hashes instead of local computation. * Photo hash generation now relies on existing service-provided hashes instead of local computation
### Improved ### Improved
* Enhanced feedback and validation when editing or creating diary names. * Enhanced feedback and validation when editing or creating diary names
* Streamlined and unified save logic for diary modals, reducing duplicated behavior. * Streamlined and unified save logic for diary modals, reducing duplicated behavior
* Sidebar layout and scrolling behavior for better usability. * Sidebar layout and scrolling behavior for better usability
## [0.0.3] - 2025-07-07 ## [0.0.3] - 2025-07-07
### Changed ### Changed
* Removed the dependency on textual-dev from pyproject.toml. * Removed the dependency on textual-dev from pyproject.toml
## [0.0.2] - 2025-07-07 ## [0.0.2] - 2025-07-07
### Changed ### Changed
* Changed the license in pyproject.toml to BSD. * Changed the license in pyproject.toml to BSD
## [0.0.1] - 2025-07-06 ## [0.0.1] - 2025-07-06
### Added ### Added
* Initial alpha release of Pilgrim travel diary application. * Initial alpha release of Pilgrim travel diary application
* Create and edit travel diaries. * Create and edit travel diaries
* Create and edit diary entries. * Create and edit diary entries
* Photo ingestion system. * Photo ingestion system
* Photo addition and reference via sidebar. * Photo addition and reference via sidebar
* Text User Interface (TUI) built with Textual framework. * Text User Interface (TUI) built with Textual framework
* Pre-compiled binary installation method (Method 2). * Pre-compiled binary installation method (Method 2)
* Support for Linux operating systems. * Support for Linux operating systems
* Basic project documentation (README). * Basic project documentation (README)
### Known Issues ### Known Issues
* Installation Method 1 not yet implemented. * Installation Method 1 not yet implemented
* No testing suite implemented yet. * No testing suite implemented yet
* Some features may be unstable in an alpha version. * Some features may be unstable in an alpha version
+2 -6
View File
@@ -1,6 +1,5 @@
from typing import Any, List from typing import Any
from pilgrim.models.photo import Photo
from pilgrim.models.photo_in_entry import photo_entry_association from pilgrim.models.photo_in_entry import photo_entry_association
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
@@ -22,12 +21,9 @@ class Entry(Base):
fk_travel_diary_id = Column(Integer, ForeignKey("travel_diaries.id"), nullable=False) fk_travel_diary_id = Column(Integer, ForeignKey("travel_diaries.id"), nullable=False)
travel_diary = relationship("TravelDiary", back_populates="entries") travel_diary = relationship("TravelDiary", back_populates="entries")
def __init__(self, title: str, text: str, date: Any, travel_diary_id: int, photos: List[Photo] = None, **kw: Any): def __init__(self, title: str, text: str, date: str, travel_diary_id: int, **kw: Any):
super().__init__(**kw) super().__init__(**kw)
self.title = title self.title = title
self.text = text self.text = text
self.date = date self.date = date
self.fk_travel_diary_id = travel_diary_id self.fk_travel_diary_id = travel_diary_id
if photos is not None:
self.photos = photos
@@ -0,0 +1,123 @@
from typing import List, Tuple
import asyncio
from pilgrim.service.entry_service import EntryService
from pilgrim.models.entry import Entry
class EntryServiceMock(EntryService):
def __init__(self):
super().__init__(None)
self.mock_data = {
1: Entry(title="The Adventure Begins", text="I'm hopping in the Plane to finally visit canadian lands",
date="26/07/2025", travel_diary_id=1, id=1,
photos=[]),
2: Entry(title="The Landing", text="Finally on Canadian Soil", date="27/07/2025",
travel_diary_id=1, id=2,photos=[]),
3: Entry(title="The Mount Royal", text="The Mount Royal is fucking awesome", date="28/07/2025",
travel_diary_id=1, id=3, photos=[]),
4: Entry(title="Old Montreal", text="Exploring the historic district", date="29/07/2025",
travel_diary_id=1, id=4, photos=[]),
5: Entry(title="Notre-Dame Basilica", text="Beautiful architecture", date="30/07/2025",
travel_diary_id=1, id=5, photos=[]),
6: Entry(title="Parc Jean-Drapeau", text="Great views of the city", date="31/07/2025",
travel_diary_id=1, id=6, photos=[]),
7: Entry(title="La Ronde", text="Amusement park fun", date="01/08/2025",
travel_diary_id=1, id=7, photos=[]),
8: Entry(title="Biodome", text="Nature and science", date="02/08/2025",
travel_diary_id=1, id=8, photos=[]),
9: Entry(title="Botanical Gardens", text="Peaceful walk", date="03/08/2025",
travel_diary_id=1, id=9, photos=[]),
10: Entry(title="Olympic Stadium", text="Historic venue", date="04/08/2025",
travel_diary_id=1, id=10, photos=[]),
}
self._next_id = 11
# Synchronous methods (kept for compatibility)
def create(self, travel_diary_id: int, title: str, text: str, date: str) -> Entry:
"""Synchronous version"""
new_entry = Entry(title, text, date, travel_diary_id, id=self._next_id)
self.mock_data[self._next_id] = new_entry
self._next_id += 1
return new_entry
def read_by_id(self, entry_id: int) -> Entry | None:
"""Synchronous version"""
return self.mock_data.get(entry_id)
def read_all(self) -> List[Entry]:
"""Synchronous version"""
return list(self.mock_data.values())
def read_by_travel_diary_id(self, travel_diary_id: int) -> List[Entry]:
"""Synchronous version - reads entries by diary"""
return [entry for entry in self.mock_data.values() if entry.fk_travel_diary_id == travel_diary_id]
def read_paginated(self, travel_diary_id: int, page: int = 1, page_size: int = 5) -> Tuple[List[Entry], int, int]:
"""Synchronous version - reads paginated entries by diary"""
entries = self.read_by_travel_diary_id(travel_diary_id)
entries.sort(key=lambda x: x.id, reverse=True) # Most recent first
total_entries = len(entries)
total_pages = (total_entries + page_size - 1) // page_size
start_index = (page - 1) * page_size
end_index = start_index + page_size
page_entries = entries[start_index:end_index]
return page_entries, total_pages, total_entries
def update(self, entry_src: Entry, entry_dst: Entry) -> Entry | None:
"""Synchronous version"""
item_to_update = self.mock_data.get(entry_src.id)
if item_to_update:
item_to_update.title = entry_dst.title if entry_dst.title is not None else item_to_update.title
item_to_update.text = entry_dst.text if entry_dst.text is not None else item_to_update.text
item_to_update.date = entry_dst.date if entry_dst.date is not None else item_to_update.date
item_to_update.fk_travel_diary_id = entry_dst.fk_travel_diary_id if (entry_dst.fk_travel_diary_id
is not None) else entry_dst.id
item_to_update.photos.extend(entry_dst.photos)
return item_to_update
return None
def delete(self, entry_src: Entry) -> Entry | None:
"""Synchronous version"""
return self.mock_data.pop(entry_src.id, None)
# Async methods (main)
async def async_create(self, travel_diary_id: int, title: str, text: str, date: str) -> Entry:
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.create(travel_diary_id, title, text, date)
async def async_read_by_id(self, entry_id: int) -> Entry | None:
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.read_by_id(entry_id)
async def async_read_all(self) -> List[Entry]:
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.read_all()
async def async_read_by_travel_diary_id(self, travel_diary_id: int) -> List[Entry]:
"""Async version - reads entries by diary"""
await asyncio.sleep(0.01) # Simulates I/O
return self.read_by_travel_diary_id(travel_diary_id)
async def async_read_paginated(self, travel_diary_id: int, page: int = 1, page_size: int = 5) -> Tuple[List[Entry], int, int]:
"""Async version - reads paginated entries by diary"""
await asyncio.sleep(0.01) # Simulates I/O
return self.read_paginated(travel_diary_id, page, page_size)
async def async_update(self, entry_src: Entry, entry_dst: Entry) -> Entry | None:
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.update(entry_src, entry_dst)
async def async_delete(self, entry_src: Entry) -> Entry | None:
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.delete(entry_src)
@@ -0,0 +1,48 @@
from pathlib import Path
from typing import List
from pilgrim.models.photo import Photo
from pilgrim.service.photo_service import PhotoService
class PhotoServiceMock(PhotoService):
def __init__(self):
super().__init__(None)
self.mock_data = {}
self._next_id = 1
def create(self, filepath: Path, name: str, travel_diary_id, addition_date=None, caption=None) -> Photo | None:
new_photo = Photo(
filepath=filepath,
name=name,
addition_date=addition_date,
caption=caption,
fk_travel_diary_id=travel_diary_id
)
new_photo.id = self._next_id
self.mock_data[self._next_id] = new_photo
self._next_id += 1
return new_photo
def read_by_id(self, photo_id: int) -> Photo:
return self.mock_data.get(photo_id)
def read_all(self) -> List[Photo]:
return list(self.mock_data.values())
def update(self, photo_src: Photo, photo_dst: Photo) -> Photo | None:
item_to_update: Photo = self.mock_data.get(photo_src.id)
if item_to_update:
item_to_update.filepath = photo_dst.filepath if photo_dst.filepath else item_to_update.filepath
item_to_update.name = photo_dst.name if photo_dst.name else item_to_update.name
item_to_update.caption = photo_dst.caption if photo_dst.caption else item_to_update.caption
item_to_update.addition_date = photo_dst.addition_date if photo_dst.addition_date else item_to_update.addition_date
item_to_update.fk_travel_diary_id = photo_dst.fk_travel_diary_id if photo_dst.fk_travel_diary_id else item_to_update.fk_travel_diary_id
if photo_dst.entries:
item_to_update.entries = photo_dst.entries
return item_to_update
return None
def delete(self, photo_src: Photo) -> Photo | None:
return self.mock_data.pop(photo_src.id, None)
@@ -0,0 +1,22 @@
from pilgrim.service.mocks.entry_service_mock import EntryServiceMock
from pilgrim.service.mocks.photo_service_mock import PhotoServiceMock
from pilgrim.service.mocks.travel_diary_service_mock import TravelDiaryServiceMock
from pilgrim.service.servicemanager import ServiceManager
class ServiceManagerMock(ServiceManager):
def __init__(self):
super().__init__()
# Cria instâncias únicas para manter estado consistente
self._travel_diary_service = TravelDiaryServiceMock()
self._entry_service = EntryServiceMock()
self._photo_service = PhotoServiceMock()
def get_entry_service(self):
return self._entry_service
def get_travel_diary_service(self):
return self._travel_diary_service
def get_photo_service(self):
return self._photo_service
@@ -0,0 +1,67 @@
from pilgrim.service.travel_diary_service import TravelDiaryService
from pilgrim.models.travel_diary import TravelDiary
import asyncio
class TravelDiaryServiceMock(TravelDiaryService):
def __init__(self):
super().__init__(None)
self.mock_data = {
1: TravelDiary(id=1, name="Montreal"),
2: TravelDiary(id=2, name="Rio de Janeiro"),
}
self._next_id = 3
# Synchronous methods (original)
def create(self, name: str):
"""Synchronous version"""
new_travel_diary = TravelDiary(id=self._next_id, name=name)
self.mock_data[self._next_id] = new_travel_diary
self._next_id += 1
return new_travel_diary
def read_by_id(self, travel_id: int):
"""Synchronous version"""
return self.mock_data.get(travel_id)
def read_all(self):
"""Synchronous version"""
return list(self.mock_data.values())
def update(self, travel_diary_id: int, name: str):
"""Synchronous version"""
item_to_update = self.mock_data.get(travel_diary_id)
if item_to_update:
item_to_update.name = name
return item_to_update
return None
def delete(self, travel_diary_id: int):
"""Synchronous version"""
return self.mock_data.pop(travel_diary_id, None)
# Async methods (new)
async def async_create(self, name: str):
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.create(name)
async def async_read_by_id(self, travel_id: int):
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.read_by_id(travel_id)
async def async_read_all(self):
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.read_all()
async def async_update(self, travel_diary_id: int, name: str):
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.update(travel_diary_id, name)
async def async_delete(self, travel_diary_id: int):
"""Async version"""
await asyncio.sleep(0.01) # Simulates I/O
return self.delete(travel_diary_id)
+342 -70
View File
@@ -9,15 +9,12 @@ from pilgrim.ui.screens.modals.add_photo_modal import AddPhotoModal
from pilgrim.ui.screens.modals.confirm_delete_modal import ConfirmDeleteModal from pilgrim.ui.screens.modals.confirm_delete_modal import ConfirmDeleteModal
from pilgrim.ui.screens.modals.edit_photo_modal import EditPhotoModal from pilgrim.ui.screens.modals.edit_photo_modal import EditPhotoModal
from pilgrim.ui.screens.rename_entry_modal import RenameEntryModal from pilgrim.ui.screens.rename_entry_modal import RenameEntryModal
from textual.app import ComposeResult from textual.app import ComposeResult
from textual.binding import Binding from textual.binding import Binding
from textual.containers import Container, Horizontal, Vertical from textual.containers import Container, Horizontal, Vertical
from textual.screen import Screen from textual.screen import Screen
from textual.widgets import Header, Footer, Static, TextArea, OptionList from textual.widgets import Header, Footer, Static, TextArea, OptionList
from pilgrim.ui.screens.widgets.photo_sidebar import PhotoSidebar
class EditEntryScreen(Screen): class EditEntryScreen(Screen):
TITLE = "Pilgrim - Edit" TITLE = "Pilgrim - Edit"
@@ -87,7 +84,26 @@ class EditEntryScreen(Screen):
# Text area # Text area
self.text_entry = TextArea(id="text_entry", classes="EditEntryScreen-text-entry") self.text_entry = TextArea(id="text_entry", classes="EditEntryScreen-text-entry")
self.sidebar = PhotoSidebar() # Sidebar widgets
self.sidebar_title = Static("Photos", classes="EditEntryScreen-sidebar-title")
self.photo_list = OptionList(id="photo_list", classes="EditEntryScreen-sidebar-photo-list")
self.photo_info = Static("", classes="EditEntryScreen-sidebar-photo-info")
self.help_text = Static("", classes="EditEntryScreen-sidebar-help")
# Sidebar container: photo list and info in a flexible container, help_text fixed at bottom
self.sidebar_content = Vertical(
self.photo_list,
self.photo_info,
id="sidebar_content",
classes="EditEntryScreen-sidebar-content"
)
self.sidebar = Vertical(
self.sidebar_title,
self.sidebar_content,
self.help_text, # Always at the bottom, never scrolls
id="sidebar",
classes="EditEntryScreen-sidebar"
)
# Main container # Main container
self.main = Container( self.main = Container(
@@ -265,75 +281,91 @@ class EditEntryScreen(Screen):
self.call_after_refresh(self._finish_display_update) self.call_after_refresh(self._finish_display_update)
def _update_sidebar_content(self):
"""Updates the sidebar content with photos for the current diary"""
try:
self._load_photos_for_diary(self.diary_id)
# Clear existing options safely
self.photo_list.clear_options()
# Add the 'Ingest Photo' option at the top
self.photo_list.add_option("➕ Ingest Photo")
if not self.cached_photos:
self.photo_info.update("No photos found for this diary")
self.help_text.update("No photos available\n\nUse Photo Manager to add photos")
return
# Add photos to the list with hash
for photo in self.cached_photos:
# Show name and hash in the list
photo_hash = str(photo.photo_hash)[:8]
self.photo_list.add_option(f"{photo.name} \\[{photo_hash}\]")
self.photo_info.update(f"{len(self.cached_photos)} photos in diary")
# Updated help a text with hash information
help_text = (
"[b]Sidebar Shortcuts[/b]\n"
"[b][green]i[/green][/b]: Insert photo into entry\n"
"[b][green]n[/green][/b]: Add new photo\n"
"[b][green]d[/green][/b]: Delete selected photo\n"
"[b][green]e[/green][/b]: Edit selected photo\n"
"[b][yellow]Tab[/yellow][/b]: Back to editor\n"
"[b][yellow]F8[/yellow][/b]: Show/hide sidebar\n"
"[b]📝 Photo References[/b]\n"
"\\[\\[photo::hash\\]\\]"
)
self.help_text.update(help_text)
except Exception as e:
self.notify(f"Error updating sidebar: {str(e)}", severity="error")
# Set fallback content
self.photo_info.update("Error loading photos")
self.help_text.update("Error loading sidebar content")
def _load_photos_for_diary(self, diary_id: int):
"""Loads all photos for the specific diary"""
try:
service_manager = self.app.service_manager
photo_service = service_manager.get_photo_service()
all_photos = photo_service.read_all()
self.cached_photos = [photo for photo in all_photos if photo.fk_travel_diary_id == diary_id]
self.cached_photos.sort(key=lambda x: x.id)
return self.cached_photos
except Exception as e:
self.notify(f"Error loading photos: {str(e)}")
return []
def action_toggle_sidebar(self): def action_toggle_sidebar(self):
self.sidebar_visible = not self.sidebar_visible """Toggles the sidebar visibility"""
self.sidebar.display = self.sidebar_visible try:
if self.sidebar_visible: self.sidebar_visible = not self.sidebar_visible
# Chama o novo worker síncrono
self.run_worker(self._load_and_update_sidebar_worker, exclusive=True, thread=True)
self.sidebar.focus() if self.sidebar_visible:
else: self.sidebar.display = True
self.text_entry.focus() self._update_sidebar_content()
# Automatically focus the sidebar when opening
self.sidebar_focused = True
self.photo_list.focus()
self._sidebar_opened_once = True
else:
self.sidebar.display = False
self.sidebar_focused = False # Reset focus when hiding
self.text_entry.focus() # Return focus to editor
def _load_and_update_sidebar_worker(self): # Update footer after context change
""" self._update_footer_context()
Worker que roda em uma thread para carregar as fotos sem travar a UI. self.refresh(layout=True)
""" except Exception as e:
# A lógica de buscar os dados pode ser feita diretamente , self.notify(f"Error toggling sidebar: {str(e)}", severity="error")
# pois já estamos em uma thread de segundo plano. # Reset state on error
photo_service = self.app.service_manager.get_photo_service() self.sidebar_visible = False
all_photos = photo_service.read_all() self.sidebar_focused = False
self.cached_photos = [p for p in all_photos if p.fk_travel_diary_id == self.diary_id] self.sidebar.display = False
# MUDANÇA 2: Não podemos atualizar a UI diretamente de outra thread.
# Usamos 'call_from_thread' para agendar a atualização de forma segura.
self.app.call_from_thread(self.sidebar.update_photo_list, self.cached_photos)
def on_photo_sidebar_insert_photo_reference(self, message: PhotoSidebar.InsertPhotoReference):
"""Reage à mensagem para inserir uma referência de foto."""
photo_ref = f"[[photo::{message.photo_hash}]]"
self.text_entry.insert(photo_ref)
self.text_entry.focus()
def on_photo_sidebar_ingest_new_photo(self, message: PhotoSidebar.IngestNewPhoto):
"""Reage à mensagem para ingerir uma nova foto."""
def refresh_sidebar_after_add(result):
if result:
self.notify(f"Photo '{result['name']}' added successfully!")
self.run_worker(self._load_and_update_sidebar)
self.app.push_screen(
AddPhotoModal(diary_id=self.diary_id),
refresh_sidebar_after_add
)
def on_photo_sidebar_edit_photo(self, message: PhotoSidebar.EditPhoto):
"""Reage à mensagem para editar uma foto."""
def refresh_sidebar_after_edit(result):
if result:
self.notify(f"Photo '{result['name']}' updated successfully!")
self.run_worker(self._load_and_update_sidebar)
self.app.push_screen(
EditPhotoModal(photo=message.photo),
refresh_sidebar_after_edit
)
def on_photo_sidebar_delete_photo(self, message: PhotoSidebar.DeletePhoto):
"""Reage à mensagem para deletar uma foto."""
def refresh_sidebar_after_delete(result):
if result:
self.notify(f"Photo '{message.photo.name}' deleted successfully!")
self.run_worker(self._load_and_update_sidebar)
self.app.push_screen(
ConfirmDeleteModal(photo=message.photo),
refresh_sidebar_after_delete
)
def action_toggle_focus(self): def action_toggle_focus(self):
"""Toggles focus between editor and sidebar""" """Toggles focus between editor and sidebar"""
@@ -351,8 +383,248 @@ class EditEntryScreen(Screen):
# Update footer after focus change # Update footer after focus change
self._update_footer_context() self._update_footer_context()
def action_insert_photo(self):
"""Insert selected photo into text"""
if not self.sidebar_focused or not self.sidebar_visible:
self.notify("Use F8 to open the sidebar first.", severity="warning")
return
# Get a selected photo
if self.photo_list.highlighted is None:
self.notify("No photo selected", severity="warning")
return
# Adjust index because of 'Ingest Photo' at the top
photo_index = self.photo_list.highlighted - 1
self._load_photos_for_diary(self.diary_id)
if photo_index < 0 or photo_index >= len(self.cached_photos):
self.notify("No photo selected", severity="warning")
return
selected_photo = self.cached_photos[photo_index]
photo_hash = selected_photo.photo_hash[:8]
# Insert photo reference using hash format without escaping
# Using raw string to avoid markup conflicts with [[
photo_ref = f"[[photo::{photo_hash}]]"
# Insert at the cursor position
self.text_entry.insert(photo_ref)
# Switch focus back to editor
self.sidebar_focused = False
self.text_entry.focus()
# Update footer context
self._update_footer_context()
# Show selected photo info
photo_details = f"📷 {selected_photo.name}\n"
photo_details += f"🔗 {photo_hash}\n"
photo_details += f"📅 {selected_photo.addition_date}\n"
photo_details += f"💬 {selected_photo.caption or 'No caption'}\n"
photo_details += "[b]Reference formats:[/b]\n"
photo_details += f"\\[\\[photo::{photo_hash}\\]\\]"
self.photo_info.update(photo_details)
# Show notification without escaping brackets
self.notify(f"Inserted photo: {selected_photo.name} \\[{photo_hash}\\]", severity="information")
def action_ingest_new_photo(self):
"""Ingest a new photo using modal"""
if not self.sidebar_focused or not self.sidebar_visible:
self.notify("Use F8 to open the sidebar first.", severity="warning")
return
# Open add photo modal
try:
self.notify("Trying to push the modal screen...")
self.app.push_screen(
AddPhotoModal(diary_id=self.diary_id),
self.handle_add_photo_result
)
except Exception as e:
self.notify(f"Error: {str(e)}", severity="error")
self.app.notify("Error: {str(e)}", severity="error")
def handle_add_photo_result(self, result: dict | None) -> None:
"""Callback that processes the add photo modal result."""
if result is None:
self.notify("Add photo cancelled")
return
# Photo was already created in the modal, just refresh the sidebar
if self.sidebar_visible:
self._update_sidebar_content()
self.notify(f"Photo '{result['name']}' added successfully!")
async def _async_create_photo(self, photo_data: dict):
"""Creates a new photo asynchronously"""
try:
service_manager = self.app.service_manager
photo_service = service_manager.get_photo_service()
current_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
new_photo = photo_service.create(
filepath=Path(photo_data["filepath"]),
name=photo_data["name"],
travel_diary_id=self.diary_id,
addition_date=current_date,
caption=photo_data["caption"]
)
if new_photo:
self.notify(f"Photo '{new_photo.name}' added successfully!")
# Refresh sidebar content
if self.sidebar_visible:
self._update_sidebar_content()
else:
self.notify("Error creating photo")
except Exception as e:
self.notify(f"Error creating photo: {str(e)}")
def action_delete_photo(self):
"""Delete selected photo"""
if not self.sidebar_focused or not self.sidebar_visible:
self.notify("Use F8 to open the sidebar first.", severity="warning")
return
if self.photo_list.highlighted is None:
self.notify("No photo selected", severity="warning")
return
# Adjust index because of 'Ingest Photo' at the top
photo_index = self.photo_list.highlighted - 1
photos = self._load_photos_for_diary(self.diary_id)
if photo_index < 0 or photo_index >= len(photos):
self.notify("No photo selected", severity="warning")
return
selected_photo = photos[photo_index]
# Open confirm delete modal
self.app.push_screen(
ConfirmDeleteModal(photo=selected_photo),
self.handle_delete_photo_result
)
def handle_delete_photo_result(self, result: bool) -> None:
"""Callback that processes the delete photo modal result."""
if result:
# Get the selected photo with an adjusted index
photos = self._load_photos_for_diary(self.diary_id)
photo_index = self.photo_list.highlighted - 1 # Adjust for 'Ingest Photo' at top
if self.photo_list.highlighted is None or photo_index < 0 or photo_index >= len(photos):
self.notify("Photo no longer available", severity="error")
return
selected_photo = photos[photo_index]
# Schedule async deletion
self.call_later(self._async_delete_photo, selected_photo)
else:
self.notify("Delete cancelled")
async def _async_delete_photo(self, photo: Photo):
"""Deletes a photo asynchronously"""
try:
service_manager = self.app.service_manager
photo_service = service_manager.get_photo_service()
result = photo_service.delete(photo)
if result:
self.notify(f"Photo '{photo.name}' deleted successfully!")
# Refresh sidebar content
if self.sidebar_visible:
self._update_sidebar_content()
else:
self.notify("Error deleting photo")
except Exception as e:
self.notify(f"Error deleting photo: {str(e)}")
def action_edit_photo(self):
"""Edit selected photo using modal"""
if not self.sidebar_focused or not self.sidebar_visible:
self.notify("Use F8 to open the sidebar first.", severity="warning")
return
if self.photo_list.highlighted is None:
self.notify("No photo selected", severity="warning")
return
# Adjust index because of 'Ingest Photo' at the top
photo_index = self.photo_list.highlighted - 1
photos = self._load_photos_for_diary(self.diary_id)
if photo_index < 0 or photo_index >= len(photos):
self.notify("No photo selected", severity="warning")
return
selected_photo = photos[photo_index]
# Open edit photo modal
self.app.push_screen(
EditPhotoModal(photo=selected_photo),
self.handle_edit_photo_result
)
def handle_edit_photo_result(self, result: dict | None) -> None:
"""Callback that processes the edit photo modal result."""
if result is None:
self.notify("Edit photo cancelled")
return
# Get the selected photo with adjusted index
photos = self._load_photos_for_diary(self.diary_id)
photo_index = self.photo_list.highlighted - 1 # Adjust for 'Ingest Photo' at top
if self.photo_list.highlighted is None or photo_index < 0 or photo_index >= len(photos):
self.notify("Photo no longer available", severity="error")
return
selected_photo = photos[photo_index]
# Schedule async update
self.call_later(self._async_update_photo, selected_photo, result)
async def _async_update_photo(self, original_photo: Photo, photo_data: dict):
"""Updates a photo asynchronously"""
try:
service_manager = self.app.service_manager
photo_service = service_manager.get_photo_service()
# Create updated photo object
updated_photo = Photo(
filepath=photo_data["filepath"],
name=photo_data["name"],
addition_date=original_photo.addition_date,
caption=photo_data["caption"],
entries=original_photo.entries if original_photo.entries is not None else [],
id=original_photo.id,
photo_hash=original_photo.photo_hash,
)
result = photo_service.update(original_photo, updated_photo)
if result:
self.notify(f"Photo '{updated_photo.name}' updated successfully!")
# Refresh sidebar content
if self.sidebar_visible:
self._update_sidebar_content()
else:
self.notify("Error updating photo")
except Exception as e:
self.notify(f"Error updating photo: {str(e)}")
def _get_linked_photos_from_text(self) -> Optional[List[Photo]]: def _get_linked_photos_from_text(self) -> Optional[List[Photo]]:
""" """
@@ -1,125 +0,0 @@
from textual.app import ComposeResult
from textual.containers import Vertical
from textual.message import Message
from textual.widgets import Static, OptionList
from textual.widgets.option_list import Option
from pilgrim.models.photo import Photo
class PhotoSidebar(Vertical):
class PhotoSelected(Message):
def __init__(self, photo_id: int) -> None:
self.photo_id = photo_id
super().__init__()
class InsertPhotoReference(Message):
def __init__(self, photo_hash: str) -> None:
self.photo_hash = photo_hash
super().__init__()
class IngestNewPhoto(Message):
pass
class EditPhoto(Message):
def __init__(self, photo_id: int) -> None:
self.photo_id = photo_id
super().__init__()
class DeletePhoto(Message):
def __init__(self, photo_id: int) -> None:
self.photo_id = photo_id
super().__init__()
def __init__(self, **kwargs):
super().__init__(id="sidebar", classes="EditEntryScreen-sidebar", **kwargs)
self.cached_photos = []
def compose(self) -> ComposeResult:
yield Static("Photos", classes="EditEntryScreen-sidebar-title")
yield Vertical(
OptionList(id="photo_list", classes="EditEntryScreen-sidebar-photo-list"),
Static("", id="photo_info", classes="EditEntryScreen-sidebar-photo-info"),
id="sidebar_content",
classes="EditEntryScreen-sidebar-content"
)
yield Static("", id="help_text", classes="EditEntryScreen-sidebar-help")
def _get_selected_photo(self) -> Photo | None:
"""Busca a foto selecionada na lista."""
photo_list = self.query_one("#photo_list", OptionList)
if photo_list.highlighted is None:
return None
option = photo_list.get_option_at_index(photo_list.highlighted)
if option.id == "ingest":
return None
try:
photo_id = int(str(option.id).split("_")[1])
return next((p for p in self.cached_photos if p.id == photo_id), None)
except (IndexError, ValueError):
return None
def update_photo_list(self, photos: list[Photo]):
"""Método público para a tela principal popular a lista de fotos."""
self.cached_photos = photos
photo_list = self.query_one("#photo_list", OptionList)
photo_list.clear_options()
# Adiciona opção de ingest
photo_list.add_option(Option("➕ Ingest New Photo", id="ingest"))
# Adiciona fotos
for photo in self.cached_photos:
photo_hash = str(photo.photo_hash)[:8]
photo_list.add_option(
Option(f"{photo.name} [{photo_hash}]", id=f"photo_{photo.id}")
)
# Atualiza info
photo_info = self.query_one("#photo_info", Static)
if not self.cached_photos:
photo_info.update("No photos in diary")
else:
photo_info.update(f"{len(self.cached_photos)} photos in diary")
def on_option_list_option_selected(self, event: OptionList.OptionSelected):
"""Lida com a seleção de um item na lista."""
if event.option.id == "ingest":
self.post_message(self.IngestNewPhoto())
else:
# Emite PhotoSelected para outras opções
try:
photo_id = int(str(event.option.id).split("_")[1])
self.post_message(self.PhotoSelected(photo_id))
except (IndexError, ValueError):
pass
def on_key(self, event) -> None:
"""Lida com os atalhos de teclado quando a barra lateral está em foco."""
key = event.key
if key == "n":
self.post_message(self.IngestNewPhoto())
event.stop()
return
selected_photo = self._get_selected_photo()
if not selected_photo:
return
if key == "i":
self.post_message(self.InsertPhotoReference(selected_photo.photo_hash[:8]))
event.stop()
elif key == "e":
self.post_message(self.EditPhoto(selected_photo.id)) # Corrigido: passa o ID
event.stop()
elif key == "d":
self.post_message(self.DeletePhoto(selected_photo.id)) # Corrigido: passa o ID
event.stop()
def on_mount(self) -> None:
"""Inicializa a lista com a opção padrão."""
photo_list = self.query_one("#photo_list", OptionList)
photo_list.add_option(Option("➕ Ingest New Photo", id="ingest"))
-75
View File
@@ -1,18 +1,10 @@
from pathlib import Path
from unittest.mock import patch
import pytest import pytest
from sqlalchemy import create_engine from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
from datetime import datetime
from pilgrim.models.entry import Entry
from pilgrim.database import Base from pilgrim.database import Base
from pilgrim.models.travel_diary import TravelDiary from pilgrim.models.travel_diary import TravelDiary
from pilgrim.models.entry import Entry
from pilgrim.models.photo import Photo from pilgrim.models.photo import Photo
from pilgrim.utils import DirectoryManager
# Todos os imports necessários para as fixtures devem estar aqui # Todos os imports necessários para as fixtures devem estar aqui
# ... # ...
@@ -70,70 +62,3 @@ def session_with_photos(session_with_one_diary):
session.commit() session.commit()
return session, [photo1, photo2] return session, [photo1, photo2]
@pytest.fixture
def backup_test_env_files_only(tmp_path):
fake_config_dir = tmp_path / "config"
fake_diaries_root = tmp_path / "diaries"
fake_db_path = fake_config_dir / "database.db"
fake_config_dir.mkdir()
fake_diaries_root.mkdir()
with patch.object(DirectoryManager, 'get_database_path', return_value=fake_db_path), \
patch.object(DirectoryManager, 'get_config_directory', return_value=fake_config_dir), \
patch.object(DirectoryManager, 'get_diaries_root', return_value=fake_diaries_root):
engine = create_engine(f"sqlite:///{fake_db_path}")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
diary = TravelDiary(name="Viagem de Teste", directory_name="viagem_de_teste")
session.add(diary)
session.commit()
photo_file_path_str = str(fake_diaries_root / "viagem_de_teste" / "images" / "foto1.jpg")
photo = Photo(filepath=photo_file_path_str, name="Foto 1", photo_hash="hash123", fk_travel_diary_id=diary.id)
session.add(photo)
session.commit()
photo_file_path = Path(photo_file_path_str)
photo_file_path.parent.mkdir(parents=True)
photo_file_path.touch()
yield {
"session": session,
"db_path": fake_db_path,
"config_dir": fake_config_dir,
"diaries_root": fake_diaries_root,
}
session.close()
@pytest.fixture
def entry_with_photo_references(session_with_one_diary):
session, diary = session_with_one_diary
photo1 = Photo(filepath="p1.jpg", name="P1", photo_hash="aaaaaaaa", fk_travel_diary_id=diary.id)
photo2 = Photo(filepath="p2.jpg", name="P2", photo_hash="bbbbbbbb", fk_travel_diary_id=diary.id)
session.add_all([photo1, photo2])
session.flush()
entry = Entry(
title="Entrada com Fotos",
text="Texto com a foto A [[photo::aaaaaaaa]] e também a foto B [[photo::bbbbbbbb]].",
date=datetime.now(),
travel_diary_id=diary.id,
photos=[photo1, photo2]
)
session.add(entry)
session.commit()
session.refresh(entry)
return session, entry
@pytest.fixture
def session_with_multiple_entries(session_with_one_diary):
session, diary = session_with_one_diary
session.query(Entry).delete()
entry1 = Entry(title="Entrada 1", text="Texto 1", date=datetime.now(), travel_diary_id=diary.id)
entry2 = Entry(title="Entrada 2", text="Texto 2", date=datetime.now(), travel_diary_id=diary.id)
session.add_all([entry1, entry2])
session.commit()
return session, diary
-39
View File
@@ -1,39 +0,0 @@
import zipfile
from pathlib import Path
from unittest.mock import patch, MagicMock
from pilgrim.service.backup_service import BackupService
from pilgrim.utils.directory_manager import DirectoryManager
import pytest
@patch.object(DirectoryManager, 'get_diaries_root')
@patch.object(DirectoryManager, 'get_config_directory')
@patch.object(DirectoryManager, 'get_database_path')
def test_create_backup_success(mock_get_db_path, mock_get_config_dir, mock_get_diaries_root, backup_test_env_files_only):
env = backup_test_env_files_only
session = env["session"]
mock_get_db_path.return_value = env["db_path"]
mock_get_config_dir.return_value = env["config_dir"]
mock_get_diaries_root.return_value = env["diaries_root"]
service = BackupService(session)
backup_zip_path = env["config_dir"] / "backup.zip"
success, returned_path = service.create_backup()
assert success is True
assert returned_path == backup_zip_path
assert backup_zip_path.exists()
with zipfile.ZipFile(backup_zip_path, 'r') as zf:
file_list = zf.namelist()
assert "database.sql" in file_list
assert "diaries/viagem_de_teste/images/foto1.jpg" in file_list
sql_dump = zf.read("database.sql").decode('utf-8')
assert "Viagem de Teste" in sql_dump
@patch.object(DirectoryManager, 'get_database_path')
def test_create_backup_fails_if_db_not_found(mock_get_db_path, tmp_path: Path):
non_existent_db_path = tmp_path / "non_existent.db"
mock_get_db_path.return_value = non_existent_db_path
mock_session = MagicMock()
service = BackupService(mock_session)
with pytest.raises(FileNotFoundError, match="No Database Found"):
service.create_backup()
-43
View File
@@ -261,46 +261,3 @@ def test_delete_returns_none_if_entry_does_not_exist(db_session):
non_existent_entry.id = 999 non_existent_entry.id = 999
result = service.delete(non_existent_entry) result = service.delete(non_existent_entry)
assert result is None assert result is None
def test_delete_references_for_specific_photo(entry_with_photo_references):
session, entry = entry_with_photo_references
service = EntryService(session)
updated_entry = service.delete_references_for_specific_photo(entry, "aaaaaaaa")
assert "[[photo::aaaaaaaa]]" not in updated_entry.text
assert "[[photo::bbbbbbbb]]" in updated_entry.text
def test_delete_specific_photo_reference_does_nothing_if_no_match(entry_with_photo_references):
session, entry = entry_with_photo_references
service = EntryService(session)
original_text = entry.text
updated_entry = service.delete_references_for_specific_photo(entry, "cccccccc")
assert updated_entry.text == original_text
def test_delete_all_photo_references_removes_all_refs(entry_with_photo_references):
session, entry = entry_with_photo_references
service = EntryService(session)
updated_entry = service.delete_all_photo_references(entry)
assert "[[photo::aaaaaaaa]]" not in updated_entry.text
assert "[[photo::bbbbbbbb]]" not in updated_entry.text
def test_delete_all_photo_references_uses_truncated_hash(session_with_one_diary):
session, diary = session_with_one_diary
service = EntryService(session)
long_hash_photo = Photo(
filepath="long.jpg", name="Long",
photo_hash="1234567890abcdef", # Hash com 16 caracteres
fk_travel_diary_id=diary.id
)
entry = Entry(
title="Teste de Hash Curto",
text="Referência com hash truncado [[photo::12345678]].", # Texto usa só os 8 primeiros
date=datetime.now(),
travel_diary_id=diary.id
)
entry.photos.append(long_hash_photo)
session.add_all([long_hash_photo, entry])
session.commit()
updated_entry = service.delete_all_photo_references(entry)
expected_text = "Referência com hash truncado ."
assert "[[photo::12345678]]" not in updated_entry.text
+2 -35
View File
@@ -1,12 +1,9 @@
from pathlib import Path
from unittest.mock import patch, MagicMock from unittest.mock import patch, MagicMock
from pathlib import Path
import pytest import pytest
from pilgrim.models.photo import Photo from pilgrim import TravelDiary
from pilgrim.models.travel_diary import TravelDiary
from pilgrim.models.entry import Entry
from pilgrim.service.travel_diary_service import TravelDiaryService from pilgrim.service.travel_diary_service import TravelDiaryService
@patch.object(TravelDiaryService, '_ensure_diary_directory') @patch.object(TravelDiaryService, '_ensure_diary_directory')
@@ -144,33 +141,3 @@ def test_sanitize_directory_name_handles_uniqueness(db_session):
third_sanitized_name = service._sanitize_directory_name("Viagem para a Praia") third_sanitized_name = service._sanitize_directory_name("Viagem para a Praia")
assert third_sanitized_name == "viagem_para_a_praia_2" assert third_sanitized_name == "viagem_para_a_praia_2"
def test_delete_all_entries_successfully(session_with_multiple_entries):
session, diary = session_with_multiple_entries
service = TravelDiaryService(session)
diary_id = 1
assert session.query(Entry).filter_by(fk_travel_diary_id=diary_id).count() == 2
result = service.delete_all_entries(diary)
assert result is True
assert session.query(Entry).filter_by(fk_travel_diary_id=diary_id).count() == 0
@patch.object(TravelDiaryService, '_ensure_diary_directory')
@patch('pathlib.Path.unlink')
@patch('pathlib.Path.exists', return_value=True)
@patch('pilgrim.utils.DirectoryManager.get_diaries_root', return_value=Path("/fake/diaries_root"))
def test_delete_all_photos_orchestration(
mock_ensure_dir, mock_unlink, mock_exists, mock_get_root, entry_with_photo_references
):
session, entry = entry_with_photo_references
diary_id = entry.fk_travel_diary_id
service = TravelDiaryService(session)
assert session.query(Photo).filter_by(fk_travel_diary_id=diary_id).count() == 2
assert "[[photo::" in entry.text
diary = session.get(TravelDiary, diary_id)
result = service.delete_all_photos(diary)
assert result is True
photos_after_delete = session.query(Photo).filter_by(fk_travel_diary_id=diary_id).all()
assert len(photos_after_delete) == 0
session.refresh(entry)
assert "[[photo::" not in entry.text
assert mock_unlink.call_count == 2