From 549107df283446482057a3dabc1dca9d8c145925 Mon Sep 17 00:00:00 2001 From: Shaun Kruger Date: Sun, 25 Oct 2026 18:50:12 -0600 Subject: [PATCH] Add comprehensive ps-serve command guide Includes: - Installation instructions for testing in a virtualenv - Detailed reference for all ps-serve commands (init, create-user, create-key, serve) - Complete workflow examples - Troubleshooting guide - Development tips and security best practices - Quick reference cheat sheet Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .gitignore | 6 + .idea/dataSources.xml | 12 + README_SERVE.md | 541 ++++++++++++++++++ privatestudio/_version.py | 24 - .../web/__pycache__/auth.cpython-313.pyc | Bin 0 -> 5055 bytes privatestudio/web/cli.py | 6 +- 6 files changed, 562 insertions(+), 27 deletions(-) create mode 100644 .gitignore create mode 100644 .idea/dataSources.xml create mode 100644 README_SERVE.md delete mode 100644 privatestudio/_version.py create mode 100644 privatestudio/web/__pycache__/auth.cpython-313.pyc diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..551933d --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.venv/ +dist/ +privatestudio/_version.py +*.egg-info/ + +storage/ \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000..8d0be2e --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,12 @@ + + + + + sqlite.xerial + true + org.sqlite.JDBC + jdbc:sqlite:$PROJECT_DIR$/transcoding.db + $ProjectFileDir$ + + + \ No newline at end of file diff --git a/README_SERVE.md b/README_SERVE.md new file mode 100644 index 0000000..eacc779 --- /dev/null +++ b/README_SERVE.md @@ -0,0 +1,541 @@ +# ps-serve Command Guide + +A comprehensive guide to using the `ps-serve` command-line interface for managing the Private Studio video transcoding service. + +## Overview + +`ps-serve` is the command-line tool for Private Studio. It provides commands to: +- Initialize the database +- Create and manage user accounts +- Generate and manage API keys +- Start the web server + +## Installation for Testing + +### Quick Setup in a Virtual Environment + +If you want to test the web service locally, here's the fastest way to get started: + +#### 1. Clone the Repository + +```bash +git clone https://github.com/yourusername/privatestudio.git +cd privatestudio +``` + +#### 2. Create a Virtual Environment + +```bash +python3 -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +``` + +#### 3. Install in Development Mode + +```bash +pip install -e ".[dev]" +``` + +This installs the package in "editable" mode, which means: +- Changes to the code are immediately reflected +- All dependencies (FastAPI, SQLAlchemy, etc.) are installed +- Development tools (pytest, httpx) are also installed + +#### 4. Verify Installation + +```bash +ps-serve --help +``` + +You should see the help output showing all available commands. + +### Virtual Environment Location + +Keep your virtual environment separate from the source code: + +```bash +# Recommended structure +~/projects/privatestudio/ +├── venv/ # Virtual environment (git-ignored) +├── privatestudio/ # Source code +├── tests/ +├── pyproject.toml +└── README.md +``` + +### Updating Your Installation + +When you pull new changes from git: + +```bash +# Activate your virtual environment +source venv/bin/activate + +# Reinstall to pick up new dependencies +pip install -e ".[dev]" + +# Run tests to verify everything works +pytest tests/test_web.py -v +``` + +## Commands Reference + +### ps-serve init + +Initialize the database for a new installation. + +**Syntax:** +```bash +ps-serve init +``` + +**What it does:** +- Creates a `transcoding.db` SQLite database file in the current directory +- Creates all tables (users, api_keys, assets, jobs, profiles, etc.) +- Safe to run multiple times (idempotent) + +**Example:** +```bash +$ mkdir ~/transcoding-server && cd ~/transcoding-server +$ ps-serve init +Database initialized +$ ls +transcoding.db +``` + +**Environment Variable:** +- `DATABASE_URL`: Path to database (default: `./transcoding.db`) + +```bash +DATABASE_URL="sqlite:///var/lib/privatestudio/transcoding.db" ps-serve init +``` + +--- + +### ps-serve create-user + +Create a new user account for API access. + +**Syntax:** +```bash +ps-serve create-user +``` + +**Arguments:** +- ``: The username for the new account (must be unique) + +**What it does:** +- Creates a new user in the database +- Returns the user ID (needed for creating API keys) +- Users can have multiple API keys + +**Examples:** +```bash +$ ps-serve create-user alice +User created: alice (ID: 1) + +$ ps-serve create-user bob +User created: bob (ID: 2) +``` + +**Error Handling:** +```bash +$ ps-serve create-user alice +Error: User 'alice' already exists +``` + +**Output Format:** +The command prints the username and user ID, which you'll need for the next step. + +--- + +### ps-serve create-key + +Generate a new API key for a user. + +**Syntax:** +```bash +ps-serve create-key +``` + +**Arguments:** +- ``: The ID of the user (obtained from `create-user` output) + +**What it does:** +- Generates a random 32-character API key +- Stores the SHA256 hash in the database +- Prints the plain key (save this somewhere safe!) +- The key cannot be recovered later—users must create a new one if lost + +**Example:** +```bash +$ ps-serve create-key 1 +API key created for user 1 +Key: 4YXDJoXf26auwGFQPKB6aB-kY6HxbkKPJzmWFbs7cnM +Keep this key safe - you won't be able to see it again! +``` + +**Security Notes:** +- The key is only displayed once +- Store it securely (environment variable, secret manager, encrypted file) +- Never commit it to version control +- Users can have multiple active keys (useful for key rotation) + +**Example Workflow:** +```bash +# Create two keys for the same user (one for testing, one for production) +$ ps-serve create-key 1 +Key: test_key_abc123... + +$ ps-serve create-key 1 +Key: prod_key_xyz789... +``` + +--- + +### ps-serve serve + +Start the FastAPI web server. + +**Syntax:** +```bash +ps-serve serve [OPTIONS] +``` + +**Options:** +``` +--host HOST Server host address (default: 0.0.0.0) +--port PORT Server port (default: 8000) +--reload Enable auto-reload on code changes (for development) +--log-level LEVEL Log level: debug, info, warning, error (default: info) +``` + +**What it does:** +- Starts the FastAPI server +- Initializes the database if it doesn't exist +- Listens for HTTP requests +- Logs all requests and errors + +**Examples:** + +**Start with defaults:** +```bash +$ ps-serve serve +INFO: Application startup complete +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +``` + +**Development mode with auto-reload:** +```bash +ps-serve serve --reload +``` + +Changes to Python files will automatically restart the server. + +**Custom host and port:** +```bash +ps-serve serve --host 127.0.0.1 --port 5000 +``` + +Now the server is only accessible locally at `http://127.0.0.1:5000` + +**Detailed logging:** +```bash +ps-serve serve --log-level debug +``` + +**All options together:** +```bash +ps-serve serve --host localhost --port 8080 --reload --log-level debug +``` + +**Environment Variables:** +These can also be set via environment variables: +- `SERVER_HOST`: Server host (default: `0.0.0.0`) +- `SERVER_PORT`: Server port (default: `8000`) +- `DATABASE_URL`: Database path (default: `./transcoding.db`) +- `STORAGE_PATH`: File storage directory (default: `./storage`) +- `SQL_ECHO`: Log all SQL queries (true/false) + +Example: +```bash +export SERVER_HOST=localhost +export SERVER_PORT=9000 +export STORAGE_PATH=/media/transcoding +ps-serve serve +``` + +--- + +## Complete Workflow + +Here's a typical setup workflow from start to finish: + +### 1. Initialize Database + +```bash +mkdir ~/my-transcoding-server +cd ~/my-transcoding-server +ps-serve init +``` + +### 2. Create Users + +```bash +ps-serve create-user alice +ps-serve create-user bob +``` + +### 3. Create API Keys + +```bash +ps-serve create-key 1 # For alice +# Save this key somewhere secure +ps-serve create-key 2 # For bob +``` + +### 4. Start the Server + +```bash +ps-serve serve +``` + +### 5. Use the API + +In another terminal: + +```bash +# Upload a video +curl -X PUT \ + -H "Authorization: Bearer YOUR_API_KEY" \ + -F "file=@myvideo.mp4" \ + http://localhost:8000/s3/1/videos/myvideo.mp4 + +# List uploaded files +curl -H "Authorization: Bearer YOUR_API_KEY" \ + http://localhost:8000/s3/1 +``` + +--- + +## Troubleshooting + +### Command not found: ps-serve + +**Problem:** `ps-serve: command not found` + +**Solution:** Make sure you've activated the virtual environment and installed the package: + +```bash +source venv/bin/activate +pip install -e . +``` + +### Database locked error + +**Problem:** `sqlite3.OperationalError: database is locked` + +**Solution:** SQLite doesn't handle concurrent writes well. For production: +1. Stop any running servers +2. Use PostgreSQL instead (change `DATABASE_URL`) +3. Reduce concurrency + +### Port already in use + +**Problem:** `OSError: [Errno 48] Address already in use` + +**Solution:** Use a different port: + +```bash +ps-serve serve --port 8001 +``` + +Or kill the existing process: + +```bash +# Find the process +lsof -i :8000 +# Kill it +kill -9 +``` + +### API key not working + +**Problem:** `401 Unauthorized: Invalid API key` + +**Possible causes:** +1. Wrong API key +2. API key was revoked +3. Key header is malformed (must be `Authorization: Bearer KEY`) + +**Debug:** +```bash +# List all keys for a user +curl -H "Authorization: Bearer YOUR_KEY" \ + http://localhost:8000/api/keys +``` + +--- + +## Running Tests + +After making changes, run the test suite to ensure everything works: + +```bash +# Activate virtual environment +source venv/bin/activate + +# Run all tests +pytest tests/test_web.py -v + +# Run a specific test +pytest tests/test_web.py::test_upload_file -v + +# Run with coverage +pytest tests/test_web.py --cov=privatestudio.web --cov-report=html +``` + +Coverage report is generated in `htmlcov/index.html` + +--- + +## Development Tips + +### 1. Auto-reload During Development + +```bash +ps-serve serve --reload +``` + +Every time you save a Python file, the server will restart automatically. + +### 2. View SQL Queries + +```bash +export SQL_ECHO=true +ps-serve serve +``` + +This logs all database queries to stdout for debugging. + +### 3. Use a Specific Database + +```bash +export DATABASE_URL="sqlite:///./test_db.db" +ps-serve init +ps-serve serve +``` + +Useful for keeping multiple database instances (dev, test, prod). + +### 4. Store Configuration in .env + +Create a `.env` file: + +```bash +# .env +DATABASE_URL=sqlite:///./transcoding.db +STORAGE_PATH=./media +SERVER_HOST=localhost +SERVER_PORT=8000 +SQL_ECHO=false +``` + +Then source it before running commands: + +```bash +source .env +ps-serve serve +``` + +Or use a tool like `python-dotenv`: + +```bash +pip install python-dotenv +``` + +Then in your code or shell initialization. + +--- + +## Security Best Practices + +1. **Protect API Keys** + - Never commit keys to version control + - Store in environment variables or secure vaults + - Rotate keys regularly + +2. **Database Security** + - Use PostgreSQL for production (not SQLite) + - Enable database backups + - Run database on a separate server + +3. **Network Security** + - Use HTTPS in production (behind a reverse proxy like nginx) + - Bind to localhost if only local access is needed + - Implement rate limiting and authentication + +4. **File Storage** + - Keep storage directory outside the web root + - Use a dedicated disk or object storage (S3, MinIO) for production + - Implement backup strategy + +--- + +## Next Steps + +After getting `ps-serve` running: + +1. **Upload Your First Video** + - See DEPLOYMENT.md for S3 API examples + +2. **Create a Transcode Profile** + - Define encoding profiles in YAML + - Request transcode jobs + +3. **Integrate with Your Application** + - Use the REST API from your application + - Handle job status polling + +4. **Deploy to Production** + - Use a real database (PostgreSQL) + - Run behind nginx or similar proxy + - Set up monitoring and backups + +--- + +## Getting Help + +For more detailed information: + +- **API Documentation**: Start the server and visit `http://localhost:8000/docs` +- **Deployment Guide**: See `DEPLOYMENT.md` +- **Source Code**: Check `privatestudio/web/` for implementation details + +--- + +## Quick Reference Cheat Sheet + +```bash +# Setup +python3 -m venv venv +source venv/bin/activate +pip install -e ".[dev]" + +# First time +ps-serve init +ps-serve create-user myuser +ps-serve create-key 1 + +# Development +ps-serve serve --reload --log-level debug + +# Testing +pytest tests/test_web.py -v + +# Production +DATABASE_URL="postgresql://user:pass@localhost/psdb" \ +SERVER_HOST=0.0.0.0 \ +SERVER_PORT=8000 \ +ps-serve serve +``` diff --git a/privatestudio/_version.py b/privatestudio/_version.py deleted file mode 100644 index ef74ff3..0000000 --- a/privatestudio/_version.py +++ /dev/null @@ -1,24 +0,0 @@ -# file generated by vcs-versioning -# don't change, don't track in version control -from __future__ import annotations - -__all__ = [ - "__version__", - "__version_tuple__", - "version", - "version_tuple", - "__commit_id__", - "commit_id", -] - -version: str -__version__: str -__version_tuple__: tuple[int | str, ...] -version_tuple: tuple[int | str, ...] -commit_id: str | None -__commit_id__: str | None - -__version__ = version = '0.2.dev1+g72b4fcc10.d20261026' -__version_tuple__ = version_tuple = (0, 2, 'dev1', 'g72b4fcc10.d20261026') - -__commit_id__ = commit_id = 'g72b4fcc10' diff --git a/privatestudio/web/__pycache__/auth.cpython-313.pyc b/privatestudio/web/__pycache__/auth.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73db91b42116c541e3b36c74592caf3872914d7a GIT binary patch literal 5055 zcmcgv-ESMm5#J+^AL2GYKjI#ED#qXOl-| z?llAtPTpf(yHN>QMG^g|!|Cx~GHIv2+^+5kn~XxPnjXO=ulVuTva zLl@-k-p=go&hE@_W?!_l_z0BUpFX|*?-oM-i63_H);cc^3WR(@qJ)vC5OvH5OyI49 zIe6=2PH3Go;vZ!B5R9EFw)FN+eh5d7Csu}JdUW$zdEA+c_|v;JT1V}%13wc z(YEB0F_|b;_T}J+q2{dhw`tTyE>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WXVAUlW=Cq`#A+MRN2TGVl%Q`4<`fh8(H59m2@nM1?@JmUxLx#pe*l zgf%`kCafDs8xtOyNE{Q8+P~I|AN>`dBn0kGR0uTpfe)H>V1uTz*DrM6y;&j9the*# zVaG$`(fGrk6^GBi#NkSx2POjxH0#cn*gW4w_8)w3{g3HV_pz_qcCQ`$Xz00XR0uq7 Y-BWQw`^@XF;5XQ<+xNW(dOUsm4?2%0tpET3 literal 0 HcmV?d00001 diff --git a/privatestudio/web/cli.py b/privatestudio/web/cli.py index 21b4157..0748fe8 100644 --- a/privatestudio/web/cli.py +++ b/privatestudio/web/cli.py @@ -31,8 +31,8 @@ def create_key_command(args): """Create an API key for a user.""" db = SessionLocal() try: - plain_key, api_key = create_api_key(db, args.user_id) - print(f"API key created for user {args.user_id}") + plain_key, api_key = create_api_key(db, args.user_name) + print(f"API key created for user {args.user_name}") print(f"Key: {plain_key}") print(f"Keep this key safe - you won't be able to see it again!") except ValueError as e: @@ -79,7 +79,7 @@ def main(): # Create key command key_parser = subparsers.add_parser("create-key", help="Create an API key for a user") - key_parser.add_argument("user_id", type=int, help="User ID") + key_parser.add_argument("user_name", type=str, help="User name") key_parser.set_defaults(func=create_key_command) # Serve command