📚 MyBibliotheca - Comprehensive Documentation
← Back to Documentation Home | View Beta Version →
MyBibliotheca is a self-hosted personal library management system and reading tracker built with Flask and SQLAlchemy. It serves as an open-source alternative to Goodreads, StoryGraph, and similar services, offering complete control over your reading data with multi-user support and advanced privacy controls.
Table of Contents
- Overview
- Quick Start
- Features
- Key Components
- Database Schema
- Troubleshooting
- Contributing
- License
- Acknowledgments
Overview
What is MyBibliotheca?
MyBibliotheca is a comprehensive personal library management system that allows you to:
- Track your book collection and reading progress
- Import books via ISBN lookup or CSV files
- Log daily reading activities and maintain reading streaks
- Generate monthly reading wrap-up images
- Manage multiple users with complete data isolation
- Share reading activity with community features
- Maintain privacy with granular sharing controls
Key Characteristics
- Self-hosted: Complete control over your data
- Multi-user: Secure authentication with isolated user data
- SQLite Database: Lightweight, file-based database storage
- Flask Framework: Modern Python web framework
- Responsive Design: Mobile-friendly Bootstrap UI
- Privacy-focused: Granular privacy controls for sharing
- Community Features: Optional sharing and social features
Version Information
- Version: 0.1.0
- Database: SQLite with SQLAlchemy ORM
- Framework: Flask with Flask-Login authentication
- Python: Requires Python 3.13+
- Security: CSRF protection, account lockout, password policies
Quick Start
Docker Installation (Recommended)
Option 1: Docker Run Command
# Clone the repository for configuration files
git clone https://github.com/pickles4evaaaa/mybibliotheca.git
cd mybibliotheca
# Run using Docker Hub image
docker run -d \
--name mybibliotheca \
-p 5054:5054 \
-v $(pwd)/data:/app/data \
-e TIMEZONE=America/Chicago \
-e WORKERS=6 \
--restart unless-stopped \
pickles4evaaaa/mybibliotheca:1.1.1
Option 2: Docker Compose (Recommended)
# Clone the repository
git clone https://github.com/pickles4evaaaa/mybibliotheca.git
cd mybibliotheca
# Create .env file with required secrets
cp .env.example .env
# Edit .env and set SECRET_KEY and SECURITY_PASSWORD_SALT
# Start with Docker Compose
docker compose up -d
Docker Compose Configuration (docker-compose.yml):
services:
mybibliotheca:
image: pickles4evaaaa/mybibliotheca:1.1.1
ports:
- "5054:5054"
volumes:
# To change the data directory, change MyBibliotheca_data to your desired location on your local machine
# and ensure the application has write permissions to that directory.
- mybibliotheca_data:/app/data
environment:
# Security - MUST be set via .env file or environment
- SECRET_KEY=${SECRET_KEY}
- SECURITY_PASSWORD_SALT=${SECURITY_PASSWORD_SALT}
# Application settings
- TIMEZONE=${TIMEZONE:-UTC}
- WORKERS=${WORKERS:-4}
restart: unless-stopped
volumes:
mybibliotheca_data:
driver: local
Note: Pre-built Docker images are available on Docker Hub. You can browse all available versions and tags there.
Access the application at http://localhost:5054 and complete the first-time setup to create your admin account.
Features
Core Library Management
📖 Book Management
- Add books via ISBN lookup with automatic metadata fetching
- Manual book entry with custom fields
- Bulk import via CSV files
- Cover image management (automatic download or manual URL)
- Comprehensive book details (title, authors, publisher, categories, etc.)
- Book status tracking (Want to Read, Currently Reading, Finished, Library Only)
📊 Reading Tracking
- Reading progress with percentage tracking
- Daily reading logs with page counts and notes
- Reading streak calculation and offset management
- Monthly wrap-up image generation
- Reading session timing and duration tracking
- Personal ratings and reviews
🔍 Search & Organization
- Full-text search across titles, authors, and descriptions
- Advanced filtering by category, publisher, language, status
- Library grid and list views
- Sorting by multiple criteria
- Category and publisher management
Multi-User Features
👥 User Management
- Secure user registration and authentication
- Individual user accounts with isolated data
- Admin user privileges and management tools
- User profile management and settings
- Reading activity and statistics per user
🔐 Security & Privacy
- Strong password requirements (12+ chars with complexity)
- Account lockout protection after failed attempts
- CSRF protection on all forms
- Forced password changes for new users
- Session management and timeout
- Admin tools for user management
🔒 Privacy Controls
Granular sharing settings per user:
- Share current reading status
- Share reading activity and logs
- Share library contents
- Community features with privacy respect
- Public library views with privacy filters
Advanced Features
📅 Reading Analytics
- Reading streak tracking with offset support
- Monthly and yearly reading statistics
- Books completed tracking
- Reading pace analysis
- Category distribution analytics
🖼️ Visual Features
- Monthly wrap-up image collages
- Responsive book cover displays
- Library grid view with hover effects
- Beautiful book detail pages
- Mobile-optimized interface
🔄 Import & Export
- CSV import with customizable mapping
- Goodreads export compatibility
- Database backup and download
- User data export capabilities
🌐 Community Features
- Community activity feed
- User profile pages
- Shared reading activity (respecting privacy)
- Public library browsing (when enabled)
Key Components
Models (app/models.py)
- User Model: Authentication, privacy settings, reading streaks
- Book Model: Complete bibliographic information and user association
- ReadingLog Model: Daily reading activity tracking
- Database Relationships: Foreign keys and cascading deletes
Authentication (app/auth.py)
- Flask-Login Integration: Session management and user loading
- Security Features: Account lockout, password validation
- Registration/Login: Complete user lifecycle management
- Admin Tools: User promotion and management
Routes (app/routes.py)
- Main Routes: Library, book management, reading logs
- Auth Routes: Login, registration, profile management
- API Endpoints: JSON responses for AJAX operations
- Admin Routes: Administrative functions and statistics
Forms (app/forms.py)
- WTForms Integration: Form validation and CSRF protection
- Book Forms: Add/edit book information
- Auth Forms: Login, registration, password change
- Reading Log Forms: Daily activity logging
Database Schema
Core Tables
Users Table:
CREATE TABLE user (
id INTEGER PRIMARY KEY,
username VARCHAR(80) UNIQUE NOT NULL,
email VARCHAR(120) UNIQUE NOT NULL,
password_hash VARCHAR(128) NOT NULL,
is_admin BOOLEAN DEFAULT FALSE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT TRUE,
failed_login_attempts INTEGER DEFAULT 0,
locked_until DATETIME,
last_login DATETIME,
share_current_reading BOOLEAN DEFAULT TRUE,
share_reading_activity BOOLEAN DEFAULT TRUE,
share_library BOOLEAN DEFAULT TRUE,
password_must_change BOOLEAN DEFAULT FALSE,
password_changed_at DATETIME,
reading_streak_offset INTEGER DEFAULT 0
);
Books Table:
CREATE TABLE book (
id INTEGER PRIMARY KEY,
uid VARCHAR(36) UNIQUE NOT NULL,
user_id INTEGER NOT NULL REFERENCES user(id),
title VARCHAR(500) NOT NULL,
author VARCHAR(500),
isbn VARCHAR(20),
description TEXT,
cover_url VARCHAR(1000),
page_count INTEGER,
publisher VARCHAR(200),
published_date DATE,
categories VARCHAR(500),
language VARCHAR(10),
want_to_read BOOLEAN DEFAULT FALSE,
finish_date DATE,
rating INTEGER,
review TEXT,
library_only BOOLEAN DEFAULT FALSE,
reading_progress REAL DEFAULT 0.0,
added_date DATETIME DEFAULT CURRENT_TIMESTAMP,
last_read_date DATETIME
);
Reading Logs Table:
CREATE TABLE reading_log (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES user(id),
book_id INTEGER NOT NULL REFERENCES book(id),
date DATE NOT NULL,
pages_read INTEGER DEFAULT 0,
notes TEXT,
session_start DATETIME,
session_end DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Relationships
- User → Books: One-to-many (user can have multiple books)
- User → Reading Logs: One-to-many (user can have multiple logs)
- Book → Reading Logs: One-to-many (book can have multiple logs)
- Cascade Deletes: Deleting a user deletes all their books and logs
- Cascade Deletes: Deleting a book deletes all its reading logs
Troubleshooting
Common Issues
Application Won't Start
Check Logs:
# View Docker logs
docker logs mybibliotheca
# View application logs
tail -f data/logs/app.log
Common Solutions:
# Restart the container
docker restart mybibliotheca
# Rebuild the container
docker compose down
docker compose up -d --build
Database Errors
Verify Database:
# Check database file exists and has correct permissions
ls -la data/books.db
# Verify database integrity
sqlite3 data/books.db "PRAGMA integrity_check;"
Backup and Reset:
# Backup current database
cp data/books.db data/books.db.backup
# Reset database (CAUTION: This deletes all data)
rm data/books.db
# Restart application to recreate database
docker restart mybibliotheca
Login Issues
Reset Password:
# Using admin tools
python3 admin_tools.py reset-password --username YOUR_USERNAME
Unlock Account:
# Unlock a locked account
python3 admin_tools.py unlock-user --username YOUR_USERNAME
Debug Mode
Enable Debug Logging:
# Run with debug output
python3 run.py 2>&1 | tee debug.log
Important Log Patterns:
# Authentication errors
grep "Failed login" debug.log
# Database errors
grep "DatabaseError" debug.log
# Performance issues
grep "Slow query" debug.log
System Health Check
# health_check.py
from app import create_app, db
from app.models import User, Book
def health_check():
app = create_app()
with app.app_context():
try:
# Test database connection
user_count = User.query.count()
book_count = Book.query.count()
print(f"✅ Database connection: OK")
print(f"✅ Users: {user_count}")
print(f"✅ Books: {book_count}")
# Test authentication
admin_users = User.query.filter_by(is_admin=True).count()
print(f"✅ Admin users: {admin_users}")
return True
except Exception as e:
print(f"❌ Health check failed: {e}")
return False
if __name__ == '__main__':
health_check()
Recovery Procedures
Data Recovery
Backup and Restore:
# Create backup
cp data/books.db data/backups/books.db.backup_$(date +%Y%m%d_%H%M%S)
# Restore from backup
cp data/backups/books.db.backup_TIMESTAMP data/books.db
# Verify restored database
python3 admin_tools.py validate-database
Emergency Recovery:
# If application won't start, try minimal recovery
export FLASK_ENV=production
export FLASK_DEBUG=false
# Start with basic configuration
python3 -c "
from app import create_app
app = create_app()
with app.app_context():
from app.models import db
db.create_all()
print('Database recreated')
"
User Recovery
Reset Lost Admin Access:
# Create new admin user
python3 admin_tools.py create-admin \
--username recovery_admin \
--email admin@localhost \
--password TempPassword123!
# Use recovery admin to fix original admin
Unlock All Accounts:
# Unlock all locked accounts
python3 admin_tools.py unlock-all-users
# Reset failed login attempts
python3 admin_tools.py reset-login-attempts
Contributing
Contributing Guidelines
Getting Started
- Fork the Repository: Create your own fork on GitHub
- Clone Locally: Clone your fork to your development machine
- Create Branch: Create a feature branch for your changes
- Make Changes: Implement your feature or bug fix
- Test Thoroughly: Ensure all tests pass and add new tests
- Submit PR: Create a pull request with clear description
Development Workflow
# Clone your fork
git clone https://github.com/YOUR_USERNAME/mybibliotheca.git
cd mybibliotheca
# Add upstream remote
git remote add upstream https://github.com/pickles4evaaaa/mybibliotheca.git
# Create feature branch
git checkout -b feature/your-feature-name
# Make changes and commit
git add .
git commit -m "Add your feature description"
# Push to your fork
git push origin feature/your-feature-name
# Create pull request on GitHub
Code Standards
Python Style
- Follow PEP 8 style guidelines
- Use meaningful variable and function names
- Add docstrings to all functions and classes
- Keep line length under 100 characters
- Use type hints where applicable
Code Quality:
# Good example
def calculate_reading_streak(user_id: int, offset: int = 0) -> int:
"""
Calculate the current reading streak for a user.
Args:
user_id: The ID of the user
offset: Additional days to add to streak
Returns:
The current reading streak in days
"""
# Implementation here
pass
Database Patterns
- Always filter by user_id for user data
- Use SQLAlchemy ORM, avoid raw SQL
- Handle database errors gracefully
- Use transactions for related operations
Security Practices
- Validate all user input
- Use CSRF protection on forms
- Follow principle of least privilege
- Log security-relevant events
Testing Requirements
Test Coverage
- Aim for 80%+ test coverage
- Test all new features thoroughly
- Include edge cases and error conditions
- Test security features especially carefully
Test Types:
# Unit tests
def test_user_password_validation():
assert User.is_password_strong("ValidPassword123!")
assert not User.is_password_strong("weak")
# Integration tests
def test_book_creation_endpoint(client, auth):
auth.login()
response = client.post('/api/books', json={
'title': 'Test Book',
'author': 'Test Author'
})
assert response.status_code == 201
# UI tests
def test_login_form_validation(client):
response = client.post('/login', data={
'username': '',
'password': 'test'
})
assert b'Username is required' in response.data
Pull Request Process
PR Requirements
- Clear, descriptive title
- Detailed description of changes
- Reference related issues
- Include screenshots for UI changes
- All tests passing
- Code review approved
PR Template:
**Description**
Brief description of what this PR does
**Type of Change**
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation update
**Testing**
- [ ] Unit tests added/updated
- [ ] Integration tests added/updated
- [ ] Manual testing completed
- [ ] All tests passing
**Screenshots (if applicable)**
Add screenshots to help explain your changes
**Checklist**
- [ ] My code follows the style guidelines
- [ ] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
Community Guidelines
Communication
- Be respectful and constructive in discussions
- Help newcomers and answer questions
- Provide clear bug reports with reproduction steps
- Suggest improvements constructively
Bug Reports:
**Bug Description**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected Behavior**
A clear description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
- Python version
- MyBibliotheca version
**Additional Context**
Add any other context about the problem here.
Feature Requests:
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is.
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
License
MyBibliotheca is licensed under the MIT License. See the LICENSE file on GitHub for details.
Acknowledgments
- Flask: Web framework powering the application
- SQLAlchemy: Object-relational mapping for database operations
- Bootstrap: Responsive UI framework
- Flask-Login: User session management
- WTForms: Form handling and validation
- Google Books API: Metadata source for ISBN lookups
- Community Contributors: Everyone who has contributed to the project
This documentation is maintained by the MyBibliotheca community. For updates and contributions, please visit our GitHub repository.
Version: 0.1.0
Last Updated: October 2025
Framework: Flask + SQLAlchemy
Database: SQLite