Skip to content

Home Information - Your home, your data, organized.

Python

[Bugfix, Ops] Audio fix, install scripts, dependency updates (#154)

Tony C9a2944d6ac7b
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
new file mode 100644
index 00000000..8b377c3e
--- /dev/null
+++ b/.github/workflows/docker-publish.yml
@@ -0,0 +1,70 @@
+name: Build and Publish Docker Image
+
+on:
+ release:
+ types: [published]
+ workflow_dispatch: # Allow manual triggering for testing
+
+jobs:
+ docker-publish:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ packages: write
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Extract version from tag
+ id: extract_version
+ run: |
+ if [ "${{ github.event_name }}" = "release" ]; then
+ VERSION=${GITHUB_REF#refs/tags/}
+ else
+ # Use branch name for manual triggers
+ VERSION="${{ github.ref_name }}"
+ fi
+ echo "version=${VERSION}" >> $GITHUB_OUTPUT
+ echo "Version: ${VERSION}"
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Extract metadata
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: ghcr.io/${{ github.repository_owner }}/home-information
+ tags: |
+ type=ref,event=tag
+ type=raw,value=latest,enable={{is_default_branch}}
+ type=raw,value=${{ steps.extract_version.outputs.version }}
+
+ - name: Build and push Docker image
+ uses: docker/build-push-action@v5
+ with:
+ context: .
+ file: ./Dockerfile
+ push: true
+ tags: ${{ steps.meta.outputs.tags }}
+ labels: ${{ steps.meta.outputs.labels }}
+ platforms: linux/amd64,linux/arm64
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+
+ - name: Display installation instructions
+ if: github.event_name == 'release'
+ run: |
+ echo "πŸŽ‰ Docker image published successfully to GitHub Container Registry!"
+ echo "πŸ“¦ Tags: ${{ steps.meta.outputs.tags }}"
+ echo ""
+ echo "πŸš€ Single-command installation:"
+ echo "curl -fsSL https://raw.githubusercontent.com/${{ github.repository }}/master/install.sh | bash"
diff --git a/.github/workflows/release-assets.yml b/.github/workflows/release-assets.yml
index d0a3bcb1..35271aad 100644
--- a/.github/workflows/release-assets.yml
+++ b/.github/workflows/release-assets.yml
@@ -7,6 +7,8 @@ on:
jobs:
create-assets:
runs-on: ubuntu-latest
+ permissions:
+ contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4
diff --git a/.github/workflows/rollback.yml b/.github/workflows/rollback.yml
new file mode 100644
index 00000000..ea8f1931
--- /dev/null
+++ b/.github/workflows/rollback.yml
@@ -0,0 +1,172 @@
+name: Rollback Release
+
+on:
+ workflow_dispatch:
+ inputs:
+ rollback_to_version:
+ description: 'Version to rollback to (e.g., v1.0.1)'
+ required: true
+ type: string
+ bad_version:
+ description: 'Bad version to mark as DO NOT USE (e.g., v1.0.2)'
+ required: true
+ type: string
+ reason:
+ description: 'Brief reason for rollback'
+ required: false
+ type: string
+ default: 'Critical issue identified'
+
+jobs:
+ rollback:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ packages: write
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Validate inputs
+ run: |
+ echo "Rolling back to: ${{ inputs.rollback_to_version }}"
+ echo "Marking as bad: ${{ inputs.bad_version }}"
+ echo "Reason: ${{ inputs.reason }}"
+
+ # Basic validation
+ if [[ ! "${{ inputs.rollback_to_version }}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ echo "Error: rollback_to_version must be in format vX.Y.Z"
+ exit 1
+ fi
+
+ if [[ ! "${{ inputs.bad_version }}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ echo "Error: bad_version must be in format vX.Y.Z"
+ exit 1
+ fi
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Pull target rollback version
+ run: |
+ echo "Pulling version to rollback to: ${{ inputs.rollback_to_version }}"
+ docker pull ghcr.io/${{ github.repository_owner }}/home-information:${{ inputs.rollback_to_version }}
+
+ - name: Re-tag as latest
+ run: |
+ echo "Re-tagging ${{ inputs.rollback_to_version }} as latest"
+ docker tag ghcr.io/${{ github.repository_owner }}/home-information:${{ inputs.rollback_to_version }} \
+ ghcr.io/${{ github.repository_owner }}/home-information:latest
+
+ - name: Push updated latest tag
+ run: |
+ echo "Pushing updated latest tag"
+ docker push ghcr.io/${{ github.repository_owner }}/home-information:latest
+
+ - name: Update bad release notes
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const { rollback_to_version, bad_version, reason } = context.payload.inputs;
+
+ try {
+ // Get the bad release
+ const release = await github.rest.repos.getReleaseByTag({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ tag: bad_version
+ });
+
+ // Update the release
+ const originalName = release.data.name || bad_version;
+ const updatedName = originalName.startsWith('⚠️ DO NOT USE')
+ ? originalName
+ : `⚠️ DO NOT USE - ROLLED BACK - ${originalName}`;
+
+ const warningNotice = `
+ ## ⚠️ ROLLBACK NOTICE ⚠️
+
+ **This release has been rolled back due to: ${reason}**
+
+ **DO NOT USE THIS VERSION**
+
+ Please use version ${rollback_to_version} instead or run:
+ \`\`\`bash
+ curl -fsSL https://raw.githubusercontent.com/${context.repo.owner}/${context.repo.repo}/master/update.sh | bash
+ \`\`\`
+
+ ---
+
+ `;
+
+ const updatedBody = warningNotice + (release.data.body || '');
+
+ await github.rest.repos.updateRelease({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ release_id: release.data.id,
+ name: updatedName,
+ body: updatedBody,
+ prerelease: true // Mark as prerelease to de-emphasize
+ });
+
+ console.log(`Updated release ${bad_version} with rollback warning`);
+
+ } catch (error) {
+ console.log(`Warning: Could not update release ${bad_version}: ${error.message}`);
+ // Don't fail the workflow if release update fails
+ }
+
+ - name: Create rollback issue
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const { rollback_to_version, bad_version, reason } = context.payload.inputs;
+
+ const title = `Rollback executed: ${bad_version} β†’ ${rollback_to_version}`;
+ const body = `
+ ## Rollback Summary
+
+ **Rolled back from:** ${bad_version}
+ **Rolled back to:** ${rollback_to_version}
+ **Reason:** ${reason}
+ **Executed by:** @${context.actor}
+ **Date:** ${new Date().toISOString()}
+
+ ## Actions Taken
+ - βœ… Docker \`latest\` tag updated to point to ${rollback_to_version}
+ - βœ… Release ${bad_version} marked as "DO NOT USE"
+ - βœ… Users can update with: \`curl -fsSL https://raw.githubusercontent.com/${context.repo.owner}/${context.repo.repo}/master/update.sh | bash\`
+
+ ## Next Steps
+ - [ ] Investigate root cause of issue in ${bad_version}
+ - [ ] Create fix for the issue
+ - [ ] Create new patch release
+ - [ ] Post-mortem (if needed)
+
+ cc: @${context.repo.owner}
+ `;
+
+ await github.rest.issues.create({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ title: title,
+ body: body,
+ labels: ['rollback', 'critical']
+ });
+
+ - name: Display success message
+ run: |
+ echo "🚨 ROLLBACK COMPLETED SUCCESSFULLY 🚨"
+ echo ""
+ echo "πŸ“¦ Docker latest tag now points to: ${{ inputs.rollback_to_version }}"
+ echo "⚠️ Bad release marked: ${{ inputs.bad_version }}"
+ echo "πŸ“‹ Tracking issue created for follow-up"
+ echo ""
+ echo "Users can update immediately with:"
+ echo "curl -fsSL https://raw.githubusercontent.com/${{ github.repository }}/master/update.sh | bash"
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
index 9c973354..dc08e4ae 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -44,6 +44,7 @@ RUN rm -f /etc/nginx/conf.d/default.conf \
COPY package/docker_entrypoint.sh /src/entrypoint.sh
RUN chmod +x /src/entrypoint.sh
+COPY HI_VERSION /HI_VERSION
COPY src /src
RUN chmod +x /src/bin/docker-start-gunicorn.sh
diff --git a/HI_VERSION b/HI_VERSION
index 7dea76ed..b18d4654 100644
--- a/HI_VERSION
+++ b/HI_VERSION
@@ -1 +1 @@
-1.0.1
+v1.0.1
diff --git a/README.md b/README.md
index 07c4af21..0b98aace 100644
--- a/README.md
+++ b/README.md
@@ -23,13 +23,36 @@ See [Why Home Information?](docs/WhyHomeInformation.md) for more details on our
## Quick Start
-**Ready to try it?** Get running in under 5 minutes:
-
-### Requirements
-- Docker installed and running
+### Prerequisites
+- **Docker** installed and running ([Get Docker](https://docs.docker.com/get-docker/))
+- **Python 3.6+** for secure credential generation
- Basic command line familiarity
-### Installation
+### Single-Command Installation (Recommended)
+
+**Get running in 30 seconds:**
+
+```shell
+curl -fsSL https://raw.githubusercontent.com/cassandra/home-information/master/install.sh | bash
+```
+
+**Then visit:** [http://localhost:9411](http://localhost:9411)
+
+The script will automatically:
+- Check that Docker is running
+- Create necessary directories (`~/.hi/`)
+- Generate secure admin credentials
+- Pull and start the application
+
+**To update an existing installation:**
+```shell
+curl -fsSL https://raw.githubusercontent.com/cassandra/home-information/master/update.sh | bash
+```
+
+### Manual Installation (Full Control)
+
+**Step-by-step process for advanced users:**
+
```shell
# Download latest release
curl -L https://github.com/cassandra/home-information/releases/latest/download/home-information.zip -o home-information.zip
diff --git a/deploy/run_container.sh b/deploy/run_container.sh
index c98c10a6..b58ab18c 100755
--- a/deploy/run_container.sh
+++ b/deploy/run_container.sh
@@ -22,7 +22,7 @@ while [[ $# -gt 0 ]]; do
DATA_DIR="$2"
shift 2
;;
- -port)
+ -port)
EXTERNAL_PORT="$2"
shift 2
;;
diff --git a/docs/Installation.md b/docs/Installation.md
index 8473bee8..a45bc916 100644
--- a/docs/Installation.md
+++ b/docs/Installation.md
@@ -4,9 +4,49 @@
## Requirements and Dependencies
-- Docker - installed and running
+- **Docker** - installed and running ([Get Docker](https://docs.docker.com/get-docker/))
+- **Python 3.6+** - for secure credential generation (usually pre-installed on most systems)
-See the [Dependencies Page](dev/Dependencies.md) if you want help installing those.
+See the [Dependencies Page](dev/Dependencies.md) if you want help installing these dependencies.
+
+## Single-Command Installation (Recommended)
+
+The fastest way to get Home Information running:
+
+```shell
+curl -fsSL https://raw.githubusercontent.com/cassandra/home-information/master/install.sh | bash
+```
+
+This automated installer will:
+- Check that Docker is installed and running
+- Create required directories in `~/.hi/`
+- Generate secure admin credentials automatically
+- Pull the latest Docker image from GitHub Container Registry
+- Start the application container
+- Display access URL and admin credentials
+
+**Result:** Visit [http://localhost:9411](http://localhost:9411) and sign in with the displayed credentials.
+
+Your data will be stored in:
+- Database: `~/.hi/database/`
+- Uploaded files: `~/.hi/media/`
+
+### Updating to Latest Version
+
+To update an existing installation to the latest version:
+
+```shell
+curl -fsSL https://raw.githubusercontent.com/cassandra/home-information/master/update.sh | bash
+```
+
+This will:
+- Pull the latest Docker image
+- Restart the container with your existing configuration
+- Preserve all your data and settings
+
+## Advanced Installation (Full Control)
+
+For users who want full control over the installation process or need to customize the setup:
## Pre-install Considerations
@@ -89,6 +129,29 @@ The database file and any uploaded documents live outside the Docker container i
- Database file: `$HOME/.hi/database/hi.sqlite3`
- Uploaded files: `$HOME/.hi/media`
+#### Updating (Manual Installation)
+
+To update a manual installation to the latest version:
+
+**Option 1: Use the update script**
+```shell
+curl -fsSL https://raw.githubusercontent.com/cassandra/home-information/master/update.sh | bash
+```
+
+**Option 2: Manual update steps**
+```shell
+# Pull latest code
+cd $PROJ_DIR/home-information*
+git pull # or download and extract latest release
+
+# Rebuild the Docker image
+make docker-build
+
+# Restart with new image
+make docker-stop
+make docker-run
+```
+
### Getting Started
With the server running, you are now ready to set up for your home's use. See the [Getting Started Page](GettingStarted.md).
diff --git a/docs/dev/workflow/release-process.md b/docs/dev/workflow/release-process.md
index a905631f..0ccd1ad4 100644
--- a/docs/dev/workflow/release-process.md
+++ b/docs/dev/workflow/release-process.md
@@ -66,22 +66,57 @@ Or via GitHub web interface:
7. **Settings**: Check "Set as latest release"
8. Click "Publish Release"
+#### Check GitHub Actions
+
+- Check that ZIP file was successfully built
+- Check that Docker image was built.
+
### 5. Validate Install URL Works
-Make sure that the published ZIP install link works and that it is at least 10MB in size.
+Make sure that the published ZIP install link works and that it is at least 10MB in size and no more than 100MB in size.
+Test the manual instalation ZIP file.
```bash
curl -L https://github.com/cassandra/home-information/releases/latest/download/home-information.zip -o home-information.zip
```
## 6. Cleanup
-For safety, move back to staging branch.
+For safety, move back to staging branch and get latest tags.
```bash
-git fetch --tags
git checkout staging
+git fetch --tags
```
+This is where the automated release process ends.
+
+## Post-Release Tasks (Manual)
+
+### Validate Install Script Works
+
+Test the single-command installation script (this must be done manually):
+```
+curl -fsSL https://raw.githubusercontent.com/cassandra/home-information/master/install.sh | bash
+```
+
+### Post-Release Monitoring
+
+**Critical**: Monitor the release for the first few hours after publication:
+- Check GitHub Issues for user reports
+- Monitor GitHub Discussions for problems
+
+**If critical issues are discovered**, see [Rollback Process](rollback-process.md) for immediate response procedures.
+
+### Docker Image Cleanup (Periodic)
+
+**Every few releases**, clean up old Docker images to prevent clutter:
+1. Go to: `https://github.com/cassandra/home-information/pkgs/container/home-information`
+2. Review old versions and delete:
+ - Versions older than 6 months (except major releases)
+ - Keep at least 10 recent versions for rollback capability
+ - Always keep `latest` and current stable version
+3. This helps with storage management and reduces user confusion
+
## Version Bumping Criteria
**TBD** - Establish guidelines for:
@@ -104,3 +139,4 @@ git checkout staging
## Related Documentation
- Workflow guidelines: [Workflow Guidelines](workflow-guidelines.md)
+- **[Rollback Process](rollback-process.md)** - Emergency rollback procedures for problematic releases
diff --git a/docs/dev/workflow/rollback-process.md b/docs/dev/workflow/rollback-process.md
new file mode 100644
index 00000000..56472c89
--- /dev/null
+++ b/docs/dev/workflow/rollback-process.md
@@ -0,0 +1,92 @@
+# Rollback Process
+
+This document outlines the process for rolling back a problematic release of Home Information.
+
+## When to Rollback vs Hotfix
+
+### Rollback When:
+- **Critical security vulnerability** in the new release
+- **Data corruption** or **database issues**
+- **Application won't start** or crashes immediately
+- **Major functionality broken** affecting core features
+- **Issue affects all/most users** and no quick fix available
+
+### Hotfix When:
+- **Minor bugs** that don't prevent normal operation
+- **Issues affecting subset of users** or specific configurations
+- **Quick fix available** (< 2 hours to implement and test)
+- **Non-critical performance degradation**
+
+**When in doubt, rollback first** - it's easier to rollback immediately and then decide on a fix than to wait and have more users affected.
+
+## Rollback Execution
+
+### Prerequisites
+- Identify the **last known good version** (check previous releases)
+- Confirm the **problematic version** that needs to be rolled back
+- Have **admin access** to the GitHub repository
+
+### Step-by-Step Process
+
+1. **Navigate to GitHub Actions**
+ - Go to: `https://github.com/cassandra/home-information/actions`
+ - Click on "Rollback Release" workflow
+
+2. **Trigger Manual Rollback**
+ - Click "Run workflow" button
+ - Fill in required inputs:
+ - **Rollback to version**: Previous good version (e.g., `v1.0.1`)
+ - **Bad version**: Problematic version to mark (e.g., `v1.0.2`)
+ - **Reason**: Brief description (e.g., "Critical database migration issue")
+ - Click "Run workflow"
+
+3. **Monitor Execution**
+ - Watch the workflow progress
+ - Ensure all steps complete successfully
+ - Check for any error messages
+
+4. **Verify Rollback**
+ - Confirm Docker `latest` tag points to rollback version
+ - Verify bad release is marked "DO NOT USE"
+ - Check that tracking issue was created
+
+### What the Rollback Does Automatically
+
+The rollback workflow will:
+- Pull the target rollback version from registry
+- Re-tag it as `latest`
+- Push updated `latest` tag
+- Mark bad release with "DO NOT USE - ROLLED BACK" warning
+- Update release notes with warning and update instructions
+- Mark bad release as "prerelease" to de-emphasize
+- Create tracking issue for follow-up work
+
+## Post-Rollback Actions
+
+### Immediate (Within 1 hour)
+- [ ] **Verify rollback worked**: Test that `update.sh` pulls the correct version
+- [ ] **Communicate incident**:
+ - Post in GitHub Discussions if community exists
+ - Update any external communication channels
+- [ ] **Monitor for issues**: Watch for user reports about the rollback
+
+### Short-term (Within 24 hours)
+- [ ] **Investigate root cause**: Analyze what went wrong in the bad release
+- [ ] **Plan fix strategy**: Determine approach for addressing the issue
+- [ ] **Create fix branch**: Start work on resolving the underlying problem
+
+### Medium-term (Within 1 week)
+- [ ] **Implement fix**: Resolve the issue that caused the rollback
+- [ ] **Test thoroughly**: Ensure fix works and doesn't introduce new issues
+- [ ] **Create new release**: Publish patched version
+- [ ] **Post-mortem**: Document lessons learned (for major incidents)
+
+## Rollback Limitations
+
+**What rollback CANNOT fix:**
+- Database migrations that destroyed data
+- Issues requiring manual user intervention
+- Problems with user-specific configuration files
+- Third-party service integration issues
+
+**In these cases**, additional recovery procedures may be needed beyond the automated rollback.
diff --git a/install.sh b/install.sh
new file mode 100755
index 00000000..c5d6c4fc
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,291 @@
+#!/bin/bash
+set -e # Exit on any error
+
+# Home Information - Single Command Installer
+# Installs and runs Home Information with minimal user interaction
+# Requires: Docker
+
+# Configuration
+DOCKER_IMAGE="ghcr.io/cassandra/home-information" # GitHub Container Registry
+DOCKER_TAG="${1:-latest}" # Allow override for testing (default: latest)
+CONTAINER_NAME="hi"
+EXTERNAL_PORT="9411"
+HI_HOME="${HOME}/.hi"
+ENV_DIR="${HI_HOME}/env"
+DATABASE_DIR="${HI_HOME}/database"
+MEDIA_DIR="${HI_HOME}/media"
+ENV_FILE="${ENV_DIR}/local.env"
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+print_header() {
+ echo -e "${BLUE}================================${NC}"
+ echo -e "${BLUE} Home Information Installer${NC}"
+ echo -e "${BLUE}================================${NC}"
+}
+
+print_success() {
+ echo -e "${GREEN}βœ“ $1${NC}"
+}
+
+print_info() {
+ echo -e "${BLUE}β€’ $1${NC}"
+}
+
+print_warning() {
+ echo -e "${YELLOW}⚠ $1${NC}"
+}
+
+print_error() {
+ echo -e "${RED}βœ— $1${NC}"
+ exit 1
+}
+
+# Check if Docker is installed and running
+check_docker() {
+ print_info "Checking Docker installation..."
+
+ if ! command -v docker &> /dev/null; then
+ print_error "Docker is not installed. Please install Docker first: https://docs.docker.com/get-docker/"
+ fi
+
+ if ! docker info &> /dev/null; then
+ print_error "Docker is not running. Please start Docker and try again."
+ fi
+
+ print_success "Docker is installed and running"
+}
+
+# Check if Python3 is installed (needed for secure secret generation)
+check_python() {
+ print_info "Checking Python 3 installation..."
+
+ if ! command -v python3 &> /dev/null; then
+ print_error "Python 3.6+ is required but not installed. Please install Python 3.6 or later."
+ fi
+
+ print_success "Python 3 is installed"
+}
+
+# Generate cryptographically secure Django secret key
+generate_secret_key() {
+ python3 -c "
+import secrets
+import string
+chars = string.ascii_letters + string.digits + string.punctuation
+print(''.join(secrets.choice(chars) for _ in range(50)))
+"
+}
+
+# Generate memorable admin password
+generate_admin_password() {
+ python3 -c "
+import secrets
+words = [
+ 'apple', 'banana', 'cherry', 'delta', 'eagle', 'falcon', 'grape',
+ 'hunter', 'island', 'joker', 'kitten', 'lemon', 'melon', 'ninja', 'ocean',
+ 'piano', 'queen', 'robot', 'stone', 'tiger', 'unity', 'voice', 'water',
+ 'xenon', 'yacht', 'zebra', 'anchor', 'bridge', 'camera', 'dream', 'energy'
+]
+chosen_words = [secrets.choice(words) for _ in range(3)]
+random_number = str(secrets.randbelow(1000))
+chosen_words.append(random_number)
+print('-'.join(chosen_words))
+"
+}
+
+# Create required directories
+create_directories() {
+ print_info "Creating directories..."
+
+ # Create directories with proper permissions
+ mkdir -p "${ENV_DIR}"
+ mkdir -p "${DATABASE_DIR}"
+ mkdir -p "${MEDIA_DIR}"
+
+ # Secure the env directory (user only)
+ chmod 700 "${ENV_DIR}"
+
+ print_success "Directories created: ${HI_HOME}"
+}
+
+# Generate environment file
+create_env_file() {
+ print_info "Generating configuration and secrets..."
+
+ # Check if env file already exists
+ if [[ -f "${ENV_FILE}" ]]; then
+ print_warning "Configuration file already exists: ${ENV_FILE}"
+ read -p "Do you want to overwrite it? (y/N): " -n 1 -r
+ echo
+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+ print_error "Installation cancelled. Remove ${ENV_FILE} to start fresh."
+ fi
+
+ # Create backup (using portable date format)
+ TIMESTAMP=$(date "+%Y%m%d_%H%M%S")
+ BACKUP_FILE="${ENV_FILE}.BAK.${TIMESTAMP}"
+ cp "${ENV_FILE}" "${BACKUP_FILE}"
+ print_info "Backup created: ${BACKUP_FILE}"
+ fi
+
+ # Generate secrets
+ DJANGO_SECRET_KEY=$(generate_secret_key)
+ DJANGO_ADMIN_PASSWORD=$(generate_admin_password)
+
+ # Create environment file
+ cat > "${ENV_FILE}" << EOF
+# Home Information Environment Configuration
+# Generated by install.sh on $(date)
+
+# Core Django Settings
+DJANGO_SETTINGS_MODULE=hi.settings.local
+DJANGO_SERVER_PORT=8000
+DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY}
+
+# Admin User (for Django admin interface)
+DJANGO_SUPERUSER_PASSWORD=${DJANGO_ADMIN_PASSWORD}
+
+# Data Paths (inside Docker container)
+HI_DB_PATH=/data/database
+HI_MEDIA_PATH=/data/media
+
+# Redis Configuration
+HI_REDIS_HOST=127.0.0.1
+HI_REDIS_PORT=6379
+HI_REDIS_KEY_PREFIX=
+
+# Authentication (disabled for simple setup)
+HI_SUPPRESS_AUTHENTICATION=true
+
+# Email Settings (disabled for simple setup)
+HI_EMAIL_SUBJECT_PREFIX=
+HI_DEFAULT_FROM_EMAIL=
+HI_SERVER_EMAIL=
+HI_EMAIL_HOST=
+HI_EMAIL_PORT=587
+HI_EMAIL_HOST_USER=
+HI_EMAIL_HOST_PASSWORD=
+HI_EMAIL_USE_TLS=false
+HI_EMAIL_USE_SSL=false
+
+# Network Configuration (for localhost only)
+HI_EXTRA_HOST_URLS=
+HI_EXTRA_CSP_URLS=
+EOF
+
+ # Secure the env file
+ chmod 600 "${ENV_FILE}"
+
+ print_success "Configuration file created: ${ENV_FILE}"
+
+ # Store admin password for display later
+ ADMIN_PASSWORD="${DJANGO_ADMIN_PASSWORD}"
+}
+
+# Pull Docker image
+pull_docker_image() {
+ print_info "Pulling Home Information Docker image..."
+
+ if docker pull "${DOCKER_IMAGE}:${DOCKER_TAG}"; then
+ print_success "Docker image pulled successfully"
+ else
+ print_error "Failed to pull Docker image. Please check your internet connection."
+ fi
+}
+
+# Stop any existing container
+stop_existing_container() {
+ if docker ps -a --format 'table {{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
+ print_info "Stopping existing container..."
+ docker stop "${CONTAINER_NAME}" 2>/dev/null || true
+ docker rm "${CONTAINER_NAME}" 2>/dev/null || true
+ print_success "Existing container removed"
+ fi
+}
+
+# Start the container
+start_container() {
+ print_info "Starting Home Information container..."
+
+ docker run -d \
+ --name "${CONTAINER_NAME}" \
+ --restart unless-stopped \
+ --env-file "${ENV_FILE}" \
+ -v "${DATABASE_DIR}:/data/database" \
+ -v "${MEDIA_DIR}:/data/media" \
+ -p "${EXTERNAL_PORT}:8000" \
+ "${DOCKER_IMAGE}:${DOCKER_TAG}"
+
+ print_success "Container started successfully"
+}
+
+# Wait for application to be ready
+wait_for_app() {
+ print_info "Waiting for application to start (this may take a minute)..."
+
+ # Wait up to 60 seconds for the app to be ready
+ for i in {1..60}; do
+ if curl -s "http://localhost:${EXTERNAL_PORT}" > /dev/null 2>&1; then
+ print_success "Application is ready!"
+ return 0
+ fi
+ sleep 1
+ if [ $((i % 10)) -eq 0 ]; then
+ print_info "Still waiting... (${i}s)"
+ fi
+ done
+
+ print_warning "Application may still be starting. Check docker logs hi for details."
+}
+
+# Display success message
+show_success() {
+ echo
+ echo -e "${GREEN}================================${NC}"
+ echo -e "${GREEN} Installation Complete!${NC}"
+ echo -e "${GREEN}================================${NC}"
+ echo
+ echo -e "${BLUE}🌐 Access your Home Information system:${NC}"
+ echo -e " ${BLUE}http://localhost:${EXTERNAL_PORT}${NC}"
+ echo
+ echo -e "${BLUE}πŸ” Admin credentials:${NC}"
+ echo -e " Email: [email protected]"
+ echo -e " Password: ${ADMIN_PASSWORD}"
+ echo
+ echo -e "${BLUE}πŸ“ Your data is stored in:${NC}"
+ echo -e " Database: ${DATABASE_DIR}"
+ echo -e " Uploads: ${MEDIA_DIR}"
+ echo
+ echo -e "${BLUE}πŸ”§ Useful commands:${NC}"
+ echo -e " View logs: docker logs hi"
+ echo -e " Stop: docker stop hi"
+ echo -e " Start: docker start hi"
+ echo
+ echo -e "${GREEN}IMPORTANT: Save your admin credentials securely!${NC}"
+ echo
+}
+
+# Main installation function
+main() {
+ print_header
+
+ check_docker
+ check_python
+ create_directories
+ create_env_file
+ pull_docker_image
+ stop_existing_container
+ start_container
+ wait_for_app
+ show_success
+}
+
+# Run main function
+main "$@"
\ No newline at end of file
diff --git a/src/hi/apps/attribute/tests/attribute_framework_test_base.py b/src/hi/apps/attribute/tests/attribute_framework_test_base.py
index 4e75abb4..998b9be3 100644
--- a/src/hi/apps/attribute/tests/attribute_framework_test_base.py
+++ b/src/hi/apps/attribute/tests/attribute_framework_test_base.py
@@ -342,8 +342,7 @@ class AttributeEditResponseRendererTestMixin(AttributeFrameworkTestMixin, ABC):
context = self.create_item_edit_context(owner)
renderer = AttributeEditResponseRenderer()
- request = self.factory.post('/test/')
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/')
response = renderer.render_form_success_response(
attr_item_context=context,
@@ -379,8 +378,7 @@ class AttributeEditResponseRendererTestMixin(AttributeFrameworkTestMixin, ABC):
is_valid = handler.validate_forms(edit_form_data=form_data)
self.assertFalse(is_valid)
- request = self.factory.post('/test/')
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/')
response = renderer.render_form_error_response(
attr_item_context=context,
@@ -403,8 +401,7 @@ class AttributeEditResponseRendererTestMixin(AttributeFrameworkTestMixin, ABC):
context = self.create_item_edit_context(owner)
renderer = AttributeEditResponseRenderer()
- request = self.factory.get('/test/')
- request.session = MockSession()
+ request = self.create_hi_request('GET', '/test/')
# Create mock history records
history_records = []
@@ -426,8 +423,7 @@ class AttributeEditResponseRendererTestMixin(AttributeFrameworkTestMixin, ABC):
context = self.create_item_edit_context(owner)
renderer = AttributeEditResponseRenderer()
- request = self.factory.post('/test/')
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/')
response = renderer.render_restore_success_response(
attr_item_context=context,
@@ -572,8 +568,7 @@ class AttributeViewMixinTestMixin(AttributeFrameworkTestMixin, ABC):
# Create valid POST data
post_data = self.create_valid_form_data(owner, name="Updated via View")
- request = self.factory.post('/test/', post_data)
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/', post_data)
response = view.post_attribute_form(
request=request,
@@ -592,8 +587,7 @@ class AttributeViewMixinTestMixin(AttributeFrameworkTestMixin, ABC):
# Create invalid POST data
invalid_data = self.create_invalid_form_data(owner)
- request = self.factory.post('/test/', invalid_data)
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/', invalid_data)
response = view.post_attribute_form(
request=request,
@@ -635,12 +629,11 @@ class AttributeViewMixinTestMixin(AttributeFrameworkTestMixin, ABC):
content_type="text/plain"
)
- request = self.factory.post('/test/', {
+ request = self.create_hi_request('POST', '/test/', {
'file_value': test_file,
'name': 'uploaded_document',
'value': 'Test Document'
})
- request.session = MockSession()
response = view.post_upload(
request=request,
@@ -661,8 +654,7 @@ class AttributeViewMixinTestMixin(AttributeFrameworkTestMixin, ABC):
context = self.create_item_edit_context(owner)
view = self.create_test_view_instance()
- request = self.factory.get('/test/')
- request.session = MockSession()
+ request = self.create_hi_request('GET', '/test/')
response = view.get_history(
request=request,
@@ -687,8 +679,7 @@ class AttributeViewMixinTestMixin(AttributeFrameworkTestMixin, ABC):
# Mock history record ID
history_id = 1
- request = self.factory.post('/test/')
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/')
response = view.post_restore(
request=request,
diff --git a/src/hi/apps/attribute/tests/attribute_multi_framework_test_base.py b/src/hi/apps/attribute/tests/attribute_multi_framework_test_base.py
index 42fdb9ff..d8b28782 100644
--- a/src/hi/apps/attribute/tests/attribute_multi_framework_test_base.py
+++ b/src/hi/apps/attribute/tests/attribute_multi_framework_test_base.py
@@ -11,7 +11,6 @@ from typing import List, Dict, Any
from django.test import RequestFactory
from django.http import QueryDict
-from hi.testing.base_test_case import MockRequest, MockSession
from hi.apps.attribute.edit_context import AttributePageEditContext, AttributeItemEditContext
from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
@@ -169,8 +168,7 @@ class AttributeMultiEditFormHandlerTestMixin(AttributeMultiFrameworkTestMixin, A
self.assertTrue(handler.validate_forms_multi(multi_edit_form_data_list=multi_edit_form_data_list))
# Save forms
- request = MockRequest()
- request.POST = post_data
+ request = self.create_hi_request('POST', '/test/', post_data)
handler.save_forms_multi(
multi_edit_form_data_list=multi_edit_form_data_list,
request=request
@@ -196,8 +194,7 @@ class AttributeMultiEditResponseRendererTestMixin(AttributeMultiFrameworkTestMix
attr_item_context_list=item_context_list
)
- request = MockRequest()
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/')
response = renderer.render_form_success_response_multi(
attr_page_context=page_context,
@@ -242,9 +239,7 @@ class AttributeMultiEditResponseRendererTestMixin(AttributeMultiFrameworkTestMix
is_valid = handler.validate_forms_multi(multi_edit_form_data_list=multi_edit_form_data_list)
self.assertFalse(is_valid)
- request = MockRequest()
- request.POST = post_data
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/', post_data)
response = renderer.render_form_error_response_multi(
attr_page_context=page_context,
@@ -313,9 +308,7 @@ class AttributeMultiEditViewMixinTestMixin(AttributeMultiFrameworkTestMixin, ABC
else:
post_data[key] = value
- request = MockRequest()
- request.POST = post_data
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/', post_data)
response = view.post_attribute_form(
request=request,
@@ -344,9 +337,7 @@ class AttributeMultiEditViewMixinTestMixin(AttributeMultiFrameworkTestMixin, ABC
else:
post_data[key] = value
- request = MockRequest()
- request.POST = post_data
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/test/', post_data)
response = view.post_attribute_form(
request=request,
diff --git a/src/hi/apps/common/datetimeproxy.py b/src/hi/apps/common/datetimeproxy.py
index 7868f807..7c6a56bb 100644
--- a/src/hi/apps/common/datetimeproxy.py
+++ b/src/hi/apps/common/datetimeproxy.py
@@ -30,8 +30,6 @@ def now( tzname = None ):
Wraps Django's timezone.now() to return a timezone aware
datetime object.
"""
- global _time_delta
-
# This assumes the Django system time is in UTC !!!
utcnow = timezone.now() + _time_delta
if tzname is None:
diff --git a/src/hi/apps/common/redis_client.py b/src/hi/apps/common/redis_client.py
index 77e46ac1..8fb66a4c 100644
--- a/src/hi/apps/common/redis_client.py
+++ b/src/hi/apps/common/redis_client.py
@@ -1,9 +1,7 @@
import logging
import redis
-import redlock
from django.conf import settings
-from django.contrib.auth.models import User as UserType
logger = logging.getLogger(__name__)
@@ -60,14 +58,12 @@ def initialize_global_cache_client():
def exists_redis_client():
- global _g_global_redis_client
if not _g_global_redis_client:
initialize_global_cache_client()
return _g_global_redis_client is not None
def get_redis_client():
- global _g_global_redis_client
if not _g_global_redis_client:
initialize_global_cache_client()
return _g_global_redis_client
@@ -83,24 +79,8 @@ def clear_redis_client():
return
-def get_redis_lock( lock_key : str ):
- redis_client = get_redis_client()
-
- lock_retry_times = 20
- lock_retry_delay_ms = 250
- lock_ttl_ms = 30 * 1000
-
- return redlock.RedLock( lock_key,
- connection_details = [ redis_client ],
- retry_times = lock_retry_times,
- retry_delay = lock_retry_delay_ms,
- ttl = lock_ttl_ms )
-
-
class CacheNotAvailableError(Exception):
pass
-def get_user_lock( user : UserType ):
- return get_redis_lock( f'trip:{user.id}:lock' )
diff --git a/src/hi/apps/config/tests/test_config_attribute_framework.py b/src/hi/apps/config/tests/test_config_attribute_framework.py
index 9bab7dbe..36190873 100644
--- a/src/hi/apps/config/tests/test_config_attribute_framework.py
+++ b/src/hi/apps/config/tests/test_config_attribute_framework.py
@@ -271,8 +271,7 @@ class SubsystemAttributeEditResponseRendererTest(AttributeEditResponseRendererTe
context = self.create_item_edit_context(subsystem)
renderer = self._get_renderer()
- request = self.factory.post('/config/subsystem/test/')
- request.session = self._get_mock_session()
+ request = self.create_hi_request('POST', '/config/subsystem/test/')
response = renderer.render_form_success_response(
attr_item_context=context,
@@ -304,8 +303,7 @@ class SubsystemAttributeEditResponseRendererTest(AttributeEditResponseRendererTe
attr_item_context_list=item_context_list
)
- request = self.factory.post('/config/subsystem/multi/test/')
- request.session = self._get_mock_session()
+ request = self.create_hi_request('POST', '/config/subsystem/multi/test/')
response = renderer.render_form_success_response_multi(
attr_page_context=page_context,
@@ -337,13 +335,10 @@ class SubsystemAttributeEditResponseRendererTest(AttributeEditResponseRendererTe
from hi.apps.attribute.edit_form_handler import AttributeEditFormHandler
return AttributeEditFormHandler()
- def _get_mock_session(self):
- """Get mock session for testing."""
- from hi.testing.base_test_case import MockSession
- return MockSession()
-
-class SubsystemAttributeEditTemplateContextBuilderTest(AttributeEditTemplateContextBuilderTestMixin, BaseTestCase):
+class SubsystemAttributeEditTemplateContextBuilderTest(
+ AttributeEditTemplateContextBuilderTestMixin,
+ BaseTestCase ):
"""Test AttributeEditTemplateContextBuilder with Subsystem-specific implementations."""
def create_owner_instance(self, **kwargs):
diff --git a/src/hi/apps/config/tests/test_config_multi_attribute_framework.py b/src/hi/apps/config/tests/test_config_multi_attribute_framework.py
index 8ac368a7..ebc1a227 100644
--- a/src/hi/apps/config/tests/test_config_multi_attribute_framework.py
+++ b/src/hi/apps/config/tests/test_config_multi_attribute_framework.py
@@ -7,7 +7,6 @@ where multiple subsystems are edited simultaneously.
import logging
from typing import List, Dict, Any
-from hi.testing.base_test_case import MockRequest, MockSession
from django.http import QueryDict
from hi.testing.base_test_case import BaseTestCase
@@ -189,8 +188,7 @@ class SubsystemMultiAttributeEditResponseRendererTest(AttributeMultiEditResponse
attr_item_context_list=item_context_list
)
- request = MockRequest()
- request.session = MockSession()
+ request = self.create_hi_request('POST', '/config/subsystem/multi/test/')
response = renderer.render_form_success_response_multi(
attr_page_context=page_context,
@@ -348,9 +346,11 @@ class SubsystemMultiAttributeViewMixinTest(AttributeMultiEditViewMixinTestMixin,
else:
post_data[key] = value
- request = MockRequest()
- request.POST = post_data
- request.session = MockSession()
+ request = self.create_hi_request(
+ method='POST',
+ path='/config/subsystem/multi/test/',
+ data=post_data
+ )
# Test the multi-edit view workflow
response = view.post_attribute_form(
diff --git a/src/hi/apps/config/tests/test_views.py b/src/hi/apps/config/tests/test_views.py
index 276ef8fd..03b0c04e 100644
--- a/src/hi/apps/config/tests/test_views.py
+++ b/src/hi/apps/config/tests/test_views.py
@@ -1,12 +1,11 @@
import logging
-from unittest.mock import patch
from django.urls import reverse
from hi.apps.config.enums import ConfigPageType
from hi.apps.config.models import Subsystem, SubsystemAttribute
from hi.enums import ViewType, ViewMode
-from hi.testing.view_test_base import DualModeViewTestCase, SyncViewTestCase
+from hi.testing.view_test_base import DualModeViewTestCase
logging.disable(logging.CRITICAL)
@@ -152,93 +151,3 @@ class TestConfigSettingsView(DualModeViewTestCase):
self.assertGreaterEqual(len(form_data_list), 1) # At least our test subsystem
-class TestConfigInternalView(SyncViewTestCase):
- """
- Tests for ConfigInternalView - demonstrates simple JSON API view testing.
- This view returns internal configuration data as JSON.
- """
-
- def test_get_config_data(self):
- """Test getting internal configuration data."""
- url = reverse('config_internal')
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-
- data = response.json()
-
- # Check for expected configuration keys
- expected_keys = [
- 'ALLOWED_HOSTS',
- 'DATABASES_NAME_PATH',
- 'REDIS_HOST',
- 'REDIS_PORT',
- 'MEDIA_ROOT',
- 'DEFAULT_FROM_EMAIL',
- 'SERVER_EMAIL',
- 'EMAIL_HOST',
- 'EMAIL_PORT',
- 'EMAIL_HOST_USER',
- 'EMAIL_USE_TLS',
- 'EMAIL_USE_SSL',
- 'CORS_ALLOWED_ORIGINS',
- 'CSP_DEFAULT_SRC',
- 'CSP_CONNECT_SRC',
- 'CSP_FRAME_SRC',
- 'CSP_SCRIPT_SRC',
- 'CSP_STYLE_SRC',
- 'CSP_MEDIA_SRC',
- 'CSP_IMG_SRC',
- 'CSP_CHILD_SRC',
- 'CSP_FONT_SRC',
- ]
-
- for key in expected_keys:
- self.assertIn(key, data, f"Expected key '{key}' not found in config data")
-
- def test_post_not_allowed(self):
- """Test that POST requests are not allowed."""
- url = reverse('config_internal')
- response = self.client.post(url)
-
- # Should return 405 Method Not Allowed
- self.assertEqual(response.status_code, 405)
-
- @patch('hi.apps.config.views.settings')
- def test_config_values_from_settings(self, mock_settings):
- """Test that config values are pulled from Django settings."""
- # Set mock values
- mock_settings.ALLOWED_HOSTS = ['test.example.com']
- mock_settings.REDIS_HOST = 'redis.test.com'
- mock_settings.REDIS_PORT = 6379
- mock_settings.DATABASES = {'default': {'NAME': '/test/db.sqlite3'}}
- mock_settings.MEDIA_ROOT = '/test/media'
- mock_settings.DEFAULT_FROM_EMAIL = '[email protected]'
- mock_settings.SERVER_EMAIL = '[email protected]'
- mock_settings.EMAIL_HOST = 'smtp.test.com'
- mock_settings.EMAIL_PORT = 587
- mock_settings.EMAIL_HOST_USER = 'testuser'
- mock_settings.EMAIL_USE_TLS = True
- mock_settings.EMAIL_USE_SSL = False
- mock_settings.CORS_ALLOWED_ORIGINS = ['http://test.com']
- mock_settings.CSP_DEFAULT_SRC = ["'self'"]
- mock_settings.CSP_CONNECT_SRC = ["'self'"]
- mock_settings.CSP_FRAME_SRC = ["'self'"]
- mock_settings.CSP_SCRIPT_SRC = ["'self'"]
- mock_settings.CSP_STYLE_SRC = ["'self'"]
- mock_settings.CSP_MEDIA_SRC = ["'self'"]
- mock_settings.CSP_IMG_SRC = ["'self'"]
- mock_settings.CSP_CHILD_SRC = ["'self'"]
- mock_settings.CSP_FONT_SRC = ["'self'"]
-
- url = reverse('config_internal')
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- data = response.json()
-
- # Verify mock values are returned
- self.assertEqual(data['ALLOWED_HOSTS'], ['test.example.com'])
- self.assertEqual(data['REDIS_HOST'], 'redis.test.com')
- self.assertEqual(data['REDIS_PORT'], 6379)
diff --git a/src/hi/apps/config/urls.py b/src/hi/apps/config/urls.py
index e4641400..0022e51a 100644
--- a/src/hi/apps/config/urls.py
+++ b/src/hi/apps/config/urls.py
@@ -13,9 +13,6 @@ urlpatterns = [
views.ConfigSettingsView.as_view(),
name='config_settings' ),
- re_path( r'^internal$',
- views.ConfigInternalView.as_view(),
- name='config_internal' ),
re_path( r'^attribute/history/(?P<subsystem_id>\d+)/(?P<attribute_id>\d+)/$',
views.SubsystemAttributeHistoryInlineView.as_view(),
diff --git a/src/hi/apps/config/views.py b/src/hi/apps/config/views.py
index 04717114..36dd300b 100644
--- a/src/hi/apps/config/views.py
+++ b/src/hi/apps/config/views.py
@@ -1,7 +1,6 @@
import logging
-from django.conf import settings
-from django.http import JsonResponse, HttpResponseRedirect
+from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import View
@@ -81,41 +80,7 @@ class ConfigPageView( HiGridView ):
def config_page_type(self) -> ConfigPageType:
raise NotImplementedError('Subclasses must override this method.')
-
-class ConfigInternalView( View ):
-
- @classmethod
- def get_config_data(self):
- return {
- 'ALLOWED_HOSTS': settings.ALLOWED_HOSTS,
- 'DATABASES_NAME_PATH': settings.DATABASES['default']['NAME'],
- 'REDIS_HOST': settings.REDIS_HOST,
- 'REDIS_PORT': settings.REDIS_PORT,
- 'MEDIA_ROOT': settings.MEDIA_ROOT,
- 'DEFAULT_FROM_EMAIL': settings.DEFAULT_FROM_EMAIL,
- 'SERVER_EMAIL': settings.SERVER_EMAIL,
- 'EMAIL_HOST': settings.EMAIL_HOST,
- 'EMAIL_PORT': settings.EMAIL_PORT,
- 'EMAIL_HOST_USER': settings.EMAIL_HOST_USER,
- 'EMAIL_USE_TLS': settings.EMAIL_USE_TLS,
- 'EMAIL_USE_SSL': settings.EMAIL_USE_SSL,
- 'CORS_ALLOWED_ORIGINS': settings.CORS_ALLOWED_ORIGINS,
- 'CSP_DEFAULT_SRC': settings.CSP_DEFAULT_SRC,
- 'CSP_CONNECT_SRC': settings.CSP_CONNECT_SRC,
- 'CSP_FRAME_SRC': settings.CSP_FRAME_SRC,
- 'CSP_SCRIPT_SRC': settings.CSP_SCRIPT_SRC,
- 'CSP_STYLE_SRC': settings.CSP_STYLE_SRC,
- 'CSP_MEDIA_SRC': settings.CSP_MEDIA_SRC,
- 'CSP_IMG_SRC': settings.CSP_IMG_SRC,
- 'CSP_CHILD_SRC': settings.CSP_CHILD_SRC,
- 'CSP_FONT_SRC': settings.CSP_FONT_SRC,
- }
- def get(self, request, *args, **kwargs):
- data = self.get_config_data()
- return JsonResponse( data, safe = False )
-
-
class ConfigSettingsView( ConfigPageView,
SubsystemAttributeMixin,
AttributeMultiEditViewMixin ):
diff --git a/src/hi/apps/entity/tests/test_entity_attribute_framework.py b/src/hi/apps/entity/tests/test_entity_attribute_framework.py
index 6c23f247..3a5c67d7 100644
--- a/src/hi/apps/entity/tests/test_entity_attribute_framework.py
+++ b/src/hi/apps/entity/tests/test_entity_attribute_framework.py
@@ -148,14 +148,15 @@ class EntityAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, Base
content_type="text/plain"
)
- from hi.testing.base_test_case import MockRequest, MockSession
- request = MockRequest()
- request.POST = {
- 'name': 'entity_document',
- 'value': 'Entity Test Document'
- }
- request.FILES = {'file_value': test_file}
- request.session = MockSession()
+ _ = self.create_hi_request(
+ method='POST',
+ path='/entity/test/',
+ data={
+ 'name': 'entity_document',
+ 'value': 'Entity Test Document'
+ },
+ files={'file_value': test_file}
+ )
# Should handle file upload processing
@@ -209,8 +210,7 @@ class EntityAttributeEditResponseRendererTest(AttributeEditResponseRendererTestM
context = self.create_item_edit_context(entity)
renderer = self._get_renderer()
- request = self.factory.post('/entity/test/')
- request.session = self._get_mock_session()
+ request = self.create_hi_request('POST', '/entity/test/')
response = renderer.render_form_success_response(
attr_item_context=context,
@@ -231,13 +231,10 @@ class EntityAttributeEditResponseRendererTest(AttributeEditResponseRendererTestM
from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
return AttributeEditResponseRenderer()
- def _get_mock_session(self):
- """Get mock session for testing."""
- from hi.testing.base_test_case import MockSession
- return MockSession()
-
-class EntityAttributeEditTemplateContextBuilderTest(AttributeEditTemplateContextBuilderTestMixin, BaseTestCase):
+class EntityAttributeEditTemplateContextBuilderTest(
+ AttributeEditTemplateContextBuilderTestMixin,
+ BaseTestCase ):
"""Test AttributeEditTemplateContextBuilder with Entity-specific implementations."""
def create_owner_instance(self, **kwargs):
@@ -387,8 +384,7 @@ class EntityAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
context = self.create_item_edit_context(entity)
# Test GET request (initial template context)
- get_request = self.factory.get(f'/entity/{entity.id}/edit/')
- get_request.session = self._get_mock_session()
+ _ = self.create_hi_request('GET', f'/entity/{entity.id}/edit/')
template_context = view.create_initial_template_context(
attr_item_context=context
@@ -409,8 +405,7 @@ class EntityAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
view = self.create_test_view_instance()
context = self.create_item_edit_context(entity)
- request = self.factory.get(f'/entity/{entity.id}/attr/{attribute.id}/history/')
- request.session = self._get_mock_session()
+ request = self.create_hi_request('GET', f'/entity/{entity.id}/attr/{attribute.id}/history/')
response = view.get_history(
request=request,
@@ -438,8 +433,7 @@ class EntityAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
entity.name = "External Update"
entity.save()
- request = self.factory.post(f'/entity/{entity.id}/edit/', form_data)
- request.session = self._get_mock_session()
+ request = self.create_hi_request('POST', f'/entity/{entity.id}/edit/', form_data)
response = view.post_attribute_form(
request=request,
@@ -449,8 +443,4 @@ class EntityAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
# Should handle gracefully (may succeed or fail depending on validation)
self.assertIn(response.status_code, [200, 400])
- def _get_mock_session(self):
- """Get mock session for testing."""
- from hi.testing.base_test_case import MockSession
- return MockSession()
diff --git a/src/hi/apps/location/tests/test_location_attribute_framework.py b/src/hi/apps/location/tests/test_location_attribute_framework.py
index 3ce806ed..475ca04e 100644
--- a/src/hi/apps/location/tests/test_location_attribute_framework.py
+++ b/src/hi/apps/location/tests/test_location_attribute_framework.py
@@ -170,14 +170,15 @@ class LocationAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, Ba
content_type="application/pdf"
)
- from hi.testing.base_test_case import MockRequest, MockSession
- request = MockRequest()
- request.POST = {
- 'name': 'location_document',
- 'value': 'Location Test Document'
- }
- request.FILES = {'file_value': test_file}
- request.session = MockSession()
+ _ = self.create_hi_request(
+ method='POST',
+ path='/location/test/',
+ data={
+ 'name': 'location_document',
+ 'value': 'Location Test Document'
+ },
+ files={'file_value': test_file}
+ )
# Should handle file upload processing context
initial_count = LocationAttribute.objects.filter(
@@ -257,8 +258,7 @@ class LocationAttributeEditResponseRendererTest(AttributeEditResponseRendererTes
context = self.create_item_edit_context(location)
renderer = self._get_renderer()
- request = self.factory.post('/location/test/')
- request.session = self._get_mock_session()
+ request = self.create_hi_request('POST', '/location/test/')
response = renderer.render_form_success_response(
attr_item_context=context,
@@ -296,13 +296,10 @@ class LocationAttributeEditResponseRendererTest(AttributeEditResponseRendererTes
from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
return AttributeEditResponseRenderer()
- def _get_mock_session(self):
- """Get mock session for testing."""
- from hi.testing.base_test_case import MockSession
- return MockSession()
-
-class LocationAttributeEditTemplateContextBuilderTest(AttributeEditTemplateContextBuilderTestMixin, BaseTestCase):
+class LocationAttributeEditTemplateContextBuilderTest(
+ AttributeEditTemplateContextBuilderTestMixin,
+ BaseTestCase ):
"""Test AttributeEditTemplateContextBuilder with Location-specific implementations."""
def create_owner_instance(self, **kwargs):
@@ -471,8 +468,7 @@ class LocationAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
context = self.create_item_edit_context(location)
# Test GET request (initial template context)
- get_request = self.factory.get(f'/location/{location.id}/edit/')
- get_request.session = self._get_mock_session()
+ _ = self.create_hi_request('GET', f'/location/{location.id}/edit/')
template_context = view.create_initial_template_context(
attr_item_context=context
@@ -493,8 +489,7 @@ class LocationAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
view = self.create_test_view_instance()
context = self.create_item_edit_context(location)
- request = self.factory.get(f'/location/{location.id}/attr/{attribute.id}/history/')
- request.session = self._get_mock_session()
+ request = self.create_hi_request('GET', f'/location/{location.id}/attr/{attribute.id}/history/')
response = view.get_history(
request=request,
@@ -524,8 +519,4 @@ class LocationAttributeViewMixinTest(AttributeViewMixinTestMixin, BaseTestCase):
location_in_context = template_context['location']
self.assertEqual(location_in_context.svg_view_box_str, "0 0 2000 1500")
- def _get_mock_session(self):
- """Get mock session for testing."""
- from hi.testing.base_test_case import MockSession
- return MockSession()
diff --git a/src/hi/context_processors.py b/src/hi/context_processors.py
index 6b505191..7ce0a624 100644
--- a/src/hi/context_processors.py
+++ b/src/hi/context_processors.py
@@ -1,3 +1,4 @@
+
from .constants import DIVID
diff --git a/src/hi/environment/__init__.py b/src/hi/environment/__init__.py
new file mode 100644
index 00000000..4656081b
--- /dev/null
+++ b/src/hi/environment/__init__.py
@@ -0,0 +1,6 @@
+"""
+Home Information configuration module.
+
+This module provides centralized configuration handling for server-side and client-side
+configuration objects used throughout the Home Information system.
+"""
diff --git a/src/hi/environment/apps.py b/src/hi/environment/apps.py
new file mode 100644
index 00000000..73a76f83
--- /dev/null
+++ b/src/hi/environment/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class EnvironmentConfig(AppConfig):
+
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "hi.environment"
diff --git a/src/hi/environment/client.py b/src/hi/environment/client.py
new file mode 100644
index 00000000..264eafbe
--- /dev/null
+++ b/src/hi/environment/client.py
@@ -0,0 +1,29 @@
+from dataclasses import dataclass, asdict
+import json
+
+
+@dataclass
+class ClientConfig:
+ """Structured client-side configuration object. Provides type safety
+ and clear field definitions for server-to-client communication via
+ template injected JS via context processor. Consumed only by main.css.
+ ALl other JS modules should look to main.css for relaying of these as
+ needed.
+
+ """
+ DEBUG : bool
+ ENVIRONMENT : str
+ VERSION : str
+ VIEW_MODE : str
+ VIEW_TYPE : str
+ IS_EDIT_MODE : bool
+
+ def to_json_dict(self) -> dict:
+ """
+ Convert to dictionary suitable for JSON serialization in templates.
+ Ensures proper JavaScript boolean/null handling.
+ """
+ return json.dumps({
+ key: (value if value is not None else 'null')
+ for key, value in asdict(self).items()
+ }, indent=4 )
diff --git a/src/hi/environment/context_processors.py b/src/hi/environment/context_processors.py
new file mode 100644
index 00000000..51e2b42a
--- /dev/null
+++ b/src/hi/environment/context_processors.py
@@ -0,0 +1,30 @@
+from django.conf import settings
+
+from .client import ClientConfig
+
+
+def client_config(request):
+ """
+ Provides client-side configuration to templates.
+
+ Creates a structured configuration object that gets injected into
+ JavaScript as HiClientConfig, providing a single source of truth for
+ all client configuration needs.
+
+ Fails fast on missing required data - no masking of interface problems.
+
+ Returns:
+ dict: Context variables for templates
+ """
+ config = ClientConfig(
+ DEBUG = settings.DEBUG,
+ ENVIRONMENT = settings.ENV.environment_name,
+ VERSION = settings.ENV.VERSION,
+ VIEW_MODE = str(request.view_parameters.view_mode),
+ VIEW_TYPE = str(request.view_parameters.view_type) if request.view_parameters.view_type else None,
+ IS_EDIT_MODE = request.view_parameters.is_editing,
+ )
+
+ return {
+ 'hi_client_config': config
+ }
diff --git a/src/hi/settings/helpers.py b/src/hi/environment/server.py
similarity index 92%
rename from src/hi/settings/helpers.py
rename to src/hi/environment/server.py
index 8f302098..f99ea004 100644
--- a/src/hi/settings/helpers.py
+++ b/src/hi/environment/server.py
@@ -19,6 +19,7 @@ class EnvironmentSettings:
#
DJANGO_SETTINGS_MODULE : str = None
DJANGO_SERVER_PORT : int = 8000
+ VERSION : str = 'unknown'
SECRET_KEY : str = None
DJANGO_SUPERUSER_EMAIL : str = None
DJANGO_SUPERUSER_PASSWORD : str = None
@@ -44,6 +45,19 @@ class EnvironmentSettings:
EMAIL_USE_TLS : bool = False
EMAIL_USE_SSL : bool = False
+ @property
+ def environment_name(self) -> str:
+ """
+ Extract environment name from DJANGO_SETTINGS_MODULE.
+ """
+ if not self.DJANGO_SETTINGS_MODULE:
+ return 'unknown'
+
+ parts = self.DJANGO_SETTINGS_MODULE.split('.')
+ if len(parts) > 1:
+ return parts[-1]
+ return 'unknown'
+
@classmethod
def get( cls ) -> 'EnvironmentSettings':
env_settings = EnvironmentSettings()
@@ -69,6 +83,13 @@ class EnvironmentSettings:
)
except ( TypeError, ValueError ):
pass
+ # Read version from HI_VERSION file (single source of truth)
+ version_file_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'HI_VERSION')
+ try:
+ with open(version_file_path, 'r') as f:
+ env_settings.VERSION = f.read().strip()
+ except (FileNotFoundError, IOError) as e:
+ raise ImproperlyConfigured(f"Cannot read version file {version_file_path}: {e}")
env_settings.SECRET_KEY = cls.get_env_variable(
'DJANGO_SECRET_KEY',
env_settings.SECRET_KEY,
diff --git a/src/hi/environment/tests/__init__.py b/src/hi/environment/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/environment/tests/test_views.py b/src/hi/environment/tests/test_views.py
new file mode 100644
index 00000000..1e479e3e
--- /dev/null
+++ b/src/hi/environment/tests/test_views.py
@@ -0,0 +1,100 @@
+import logging
+from unittest.mock import patch
+
+from django.urls import reverse
+
+from hi.testing.view_test_base import SyncViewTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEnvironmentHomeView(SyncViewTestCase):
+ """
+ Tests for EnvironmentHomeView - demonstrates simple JSON API view testing.
+ This view returns internal configuration data as JSON.
+ """
+ def test_get_config_data(self):
+ """Test getting internal configuration data."""
+ url = reverse('env_home')
+ response = self.client.get(url)
+ self.assertSuccessResponse(response)
+ self.assertJsonResponse(response)
+
+ data = response.json()
+
+ # Check for expected configuration keys
+ expected_keys = [
+ 'ALLOWED_HOSTS',
+ 'DATABASES_NAME_PATH',
+ 'REDIS_HOST',
+ 'REDIS_PORT',
+ 'MEDIA_ROOT',
+ 'DEFAULT_FROM_EMAIL',
+ 'SERVER_EMAIL',
+ 'EMAIL_HOST',
+ 'EMAIL_PORT',
+ 'EMAIL_HOST_USER',
+ 'EMAIL_USE_TLS',
+ 'EMAIL_USE_SSL',
+ 'CORS_ALLOWED_ORIGINS',
+ 'CSP_DEFAULT_SRC',
+ 'CSP_CONNECT_SRC',
+ 'CSP_FRAME_SRC',
+ 'CSP_SCRIPT_SRC',
+ 'CSP_STYLE_SRC',
+ 'CSP_MEDIA_SRC',
+ 'CSP_IMG_SRC',
+ 'CSP_CHILD_SRC',
+ 'CSP_FONT_SRC',
+ ]
+
+ for key in expected_keys:
+ self.assertIn(key, data, f"Expected key '{key}' not found in config data")
+
+ def test_post_not_allowed(self):
+ """Test that POST requests are not allowed."""
+ url = reverse('env_home')
+ response = self.client.post(url)
+ # Should return 405 Method Not Allowed
+ self.assertEqual(response.status_code, 405)
+
+ @patch('hi.environment.views.settings')
+ def test_config_values_from_settings(self, mock_settings):
+ """Test that config values are pulled from Django settings."""
+ # Set mock values
+ mock_settings.ENV.environment_name = 'test'
+ mock_settings.ENV.VERSION = '1.0.0'
+ mock_settings.ALLOWED_HOSTS = ['test.example.com']
+ mock_settings.REDIS_HOST = 'redis.test.com'
+ mock_settings.REDIS_PORT = 6379
+ mock_settings.DATABASES = {'default': {'NAME': '/test/db.sqlite3'}}
+ mock_settings.MEDIA_ROOT = '/test/media'
+ mock_settings.DEFAULT_FROM_EMAIL = '[email protected]'
+ mock_settings.SERVER_EMAIL = '[email protected]'
+ mock_settings.EMAIL_HOST = 'smtp.test.com'
+ mock_settings.EMAIL_PORT = 587
+ mock_settings.EMAIL_HOST_USER = 'testuser'
+ mock_settings.EMAIL_USE_TLS = True
+ mock_settings.EMAIL_USE_SSL = False
+ mock_settings.CORS_ALLOWED_ORIGINS = ['http://test.com']
+ mock_settings.CSP_DEFAULT_SRC = ["'self'"]
+ mock_settings.CSP_CONNECT_SRC = ["'self'"]
+ mock_settings.CSP_FRAME_SRC = ["'self'"]
+ mock_settings.CSP_SCRIPT_SRC = ["'self'"]
+ mock_settings.CSP_STYLE_SRC = ["'self'"]
+ mock_settings.CSP_MEDIA_SRC = ["'self'"]
+ mock_settings.CSP_IMG_SRC = ["'self'"]
+ mock_settings.CSP_CHILD_SRC = ["'self'"]
+ mock_settings.CSP_FONT_SRC = ["'self'"]
+
+ url = reverse('env_home')
+ response = self.client.get(url)
+ self.assertSuccessResponse(response)
+
+ data = response.json()
+ self.assertEqual(data['ENVIRONMENT'], 'test')
+ self.assertEqual(data['VERSION'], '1.0.0')
+ self.assertEqual(data['ALLOWED_HOSTS'], ['test.example.com'])
+ self.assertEqual(data['REDIS_HOST'], 'redis.test.com')
+ self.assertEqual(data['EMAIL_USE_TLS'], True)
+ self.assertEqual(data['EMAIL_USE_SSL'], False)
diff --git a/src/hi/environment/urls.py b/src/hi/environment/urls.py
new file mode 100644
index 00000000..4d1988ec
--- /dev/null
+++ b/src/hi/environment/urls.py
@@ -0,0 +1,10 @@
+from django.urls import re_path
+
+from . import views
+
+
+urlpatterns = [
+ re_path(r'^$',
+ views.EnvironmentHomeView.as_view(),
+ name='env_home'),
+]
diff --git a/src/hi/environment/views.py b/src/hi/environment/views.py
new file mode 100644
index 00000000..a9b24dc0
--- /dev/null
+++ b/src/hi/environment/views.py
@@ -0,0 +1,42 @@
+from django.conf import settings
+from django.http import JsonResponse
+from django.views.generic import View
+
+
+class EnvironmentHomeView(View):
+
+ @classmethod
+ def get_env_data_for_view(self):
+ # We do not necessarily want to expose every setting item in a
+ # view (e.g., passwords), so we pick and choose the safe ones here.
+ return {
+ 'ENVIRONMENT': settings.ENV.environment_name,
+ 'VERSION': settings.ENV.VERSION,
+ 'ALLOWED_HOSTS': settings.ALLOWED_HOSTS,
+ 'DATABASES_NAME_PATH': settings.DATABASES['default']['NAME'],
+ 'REDIS_HOST': settings.REDIS_HOST,
+ 'REDIS_PORT': settings.REDIS_PORT,
+ 'MEDIA_ROOT': settings.MEDIA_ROOT,
+ 'DEFAULT_FROM_EMAIL': settings.DEFAULT_FROM_EMAIL,
+ 'SERVER_EMAIL': settings.SERVER_EMAIL,
+ 'EMAIL_HOST': settings.EMAIL_HOST,
+ 'EMAIL_PORT': settings.EMAIL_PORT,
+ 'EMAIL_HOST_USER': settings.EMAIL_HOST_USER,
+ 'EMAIL_USE_TLS': settings.EMAIL_USE_TLS,
+ 'EMAIL_USE_SSL': settings.EMAIL_USE_SSL,
+ 'CORS_ALLOWED_ORIGINS': settings.CORS_ALLOWED_ORIGINS,
+ 'CSP_DEFAULT_SRC': settings.CSP_DEFAULT_SRC,
+ 'CSP_CONNECT_SRC': settings.CSP_CONNECT_SRC,
+ 'CSP_FRAME_SRC': settings.CSP_FRAME_SRC,
+ 'CSP_SCRIPT_SRC': settings.CSP_SCRIPT_SRC,
+ 'CSP_STYLE_SRC': settings.CSP_STYLE_SRC,
+ 'CSP_MEDIA_SRC': settings.CSP_MEDIA_SRC,
+ 'CSP_IMG_SRC': settings.CSP_IMG_SRC,
+ 'CSP_CHILD_SRC': settings.CSP_CHILD_SRC,
+ 'CSP_FONT_SRC': settings.CSP_FONT_SRC,
+ }
+
+ def get(self, request, *args, **kwargs):
+ data = self.get_env_data_for_view()
+ return JsonResponse( data, safe = False )
+
diff --git a/src/hi/requirements/base.txt b/src/hi/requirements/base.txt
index 934db759..b1949f04 100644
--- a/src/hi/requirements/base.txt
+++ b/src/hi/requirements/base.txt
@@ -1,51 +1,32 @@
-aiofiles==24.1.0
-aiohappyeyeballs==2.4.0
-aiohttp==3.10.11
-aiosignal==1.3.1
-asgiref==3.8.1
+asgiref==3.9.1
attrs==24.2.0
cachetools==5.5.0
-certifi==2024.7.4
-charset-normalizer==3.3.2
-dateparser==1.2.0
-Django==4.2.22
+certifi==2025.8.3
+charset-normalizer==3.4.3
+dateparser==1.2.2
+Django==4.2.24
django-constance==3.1.0
django-csp==3.8
-django-picklefield==3.2
+django-picklefield==3.3
django-pipeline==4.0.0
-django-pipeline-csscompressor==0.1
frozenlist==1.4.1
gunicorn==23.0.0
-idna==3.7
-imutils==0.5.4
+idna==3.10
multidict==6.0.5
-mysql-connector-python==9.4.0
numpy==2.1.0
pillow==10.4.0
-Pint==0.24.4
-portalocker==2.10.1
-progressbar2==4.4.2
+Pint==0.25
psutil==6.0.0
-pyinsteon==1.6.3
-Pypubsub==4.0.3
-pyserial-asyncio==0.6
-pyserial==3.5
python-dateutil==2.9.0.post0
-python-dotenv==1.0.1
-python-utils==3.8.2
-pytz==2024.1
-pytz==2024.1
-pyzm==0.3.64
+python-dotenv==1.1.1
+python-utils==3.9.1
+pytz==2025.2
redis==5.2.0
-redlock==1.2.0
-regex==2024.7.24
-shapely==2.0.6
-six==1.16.0
-SQLAlchemy==1.3.24
-sqlparse==0.5.1
-typing_extensions==4.12.2
-tzlocal==5.2
-urllib3==2.2.3
-voluptuous==0.15.2
+requests==2.32.5
+six==1.17.0
+sqlparse==0.5.3
+typing_extensions==4.15.0
+tzlocal==5.3.1
+urllib3==2.5.0
websocket-client==1.8.0
yarl==1.12.0
diff --git a/src/hi/requirements/development.txt b/src/hi/requirements/development.txt
index eeea9c1d..b780a196 100644
--- a/src/hi/requirements/development.txt
+++ b/src/hi/requirements/development.txt
@@ -1,9 +1,9 @@
-r base.txt
-autopep8==2.3.1
+autopep8==2.3.2
black==24.8.0
-flake8==7.1.1
-jedi==0.19.1
-pipdeptree==2.25.0
-rope==1.13.0
-yapf==0.40.2
+flake8==7.3.0
+jedi==0.19.2
+pipdeptree==2.28.0
+rope==1.14.0
+yapf==0.43.0
diff --git a/src/hi/services/zoneminder/management/commands/zm_test.py b/src/hi/services/zoneminder/management/commands/zm_test.py
index 12738c10..10dd7806 100644
--- a/src/hi/services/zoneminder/management/commands/zm_test.py
+++ b/src/hi/services/zoneminder/management/commands/zm_test.py
@@ -1,4 +1,4 @@
-import pyzm.api as zmapi
+from .pyzm_client import api as zmapi
import traceback
from django.core.management.base import BaseCommand
diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.py
index d97d93b3..2ae98ffe 100644
--- a/src/hi/services/zoneminder/monitors.py
+++ b/src/hi/services/zoneminder/monitors.py
@@ -2,7 +2,7 @@ from asgiref.sync import sync_to_async
from cachetools import TTLCache
from datetime import datetime
import logging
-from pyzm.helpers.Monitor import Monitor as ZmMonitor
+from .pyzm_client.helpers.Monitor import Monitor as ZmMonitor
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.entity.enums import EntityStateValue
diff --git a/src/hi/services/zoneminder/pyzm_client/__init__.py b/src/hi/services/zoneminder/pyzm_client/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/services/zoneminder/pyzm_client/api.py b/src/hi/services/zoneminder/pyzm_client/api.py
new file mode 100644
index 00000000..d1ffa145
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/api.py
@@ -0,0 +1,435 @@
+"""
+ZMApi
+=============
+Python API wrapper for ZM.
+Exposes login, monitors, events, etc. API
+
+Important:
+
+ Make sure you have the following settings in ZM:
+
+ - ``AUTH_RELAY`` is set to hashed
+ - A valid ``AUTH_HASH_SECRET`` is provided (not empty)
+ - ``AUTH_HASH_IPS`` is disabled
+ - ``OPT_USE_APIS`` is enabled
+ - If you are using any version lower than ZM 1.34, ``OPT_USE_GOOG_RECAPTCHA`` is disabled
+ - If you are NOT using authentication at all in ZM, that is ``OPT_USE_AUTH`` is disabled, then make sure you also disable authentication in zmNinja, otherwise it will keep waiting for auth keys.
+ - I don't quite know why, but on some devices, connection issues are caused because ZoneMinder's CSRF code causes issues. See `this <https://forums.zoneminder.com/viewtopic.php?f=33&p=115422#p115422>`__ thread, for example. In this case, try turning off CSRF checks by going to ``ZM->Options->System`` and disable "Enable CSRF magic".
+
+"""
+
+import requests
+import datetime
+from .helpers.Base import Base
+from .helpers.Monitors import Monitors
+from .helpers.Events import Events
+from .helpers.States import States
+# from .helpers.Configs import Configs # Not needed for our use case
+from .helpers import globals as g
+
+
+class ZMApi (Base):
+ def __init__(self, options={}):
+ '''
+ Options is a dict with the following keys:
+
+ - apiurl - the full API URL (example https://server/zm/api)
+ - portalurl - the full portal URL (example https://server/zm). Only needed if you are downloading events/images
+ - user - username (don't specify if no auth)
+ - password - password (don't specify if no auth)
+ - disable_ssl_cert_check - if True will let you use self signed certs
+ - basic_auth_user - basic auth username
+ - basic_auth_password - basic auth password
+ Note: you can connect your own customer logging class to the API in which case all modules will use your custom class. Your class will need to implement some methods for this to work. See :class:`pyzm.helpers.Base.SimpleLog` for method details.
+ '''
+
+ self.api_url = options.get('apiurl')
+ self.portal_url = options.get('portalurl')
+ if not self.portal_url and self.api_url.endswith('/api'):
+ self.portal_url = self.api_url[:-len('/api')]
+ g.logger.Debug(2, 'Guessing portal URL is: {}'.format(self.portal_url))
+
+ self.options = options
+
+ self.authenticated = False
+ self.auth_enabled = True
+ self.access_token = ''
+ self.refresh_token = ''
+ self.access_token_expires = None
+ self.refresh_token_expires = None
+ self.refresh_token_datetime = None
+ self.access_token_datetime = None
+
+ self.legacy_credentials = None
+ self.session = requests.Session()
+ if (self.options.get('basic_auth_user')):
+ g.logger.Debug(2, 'Basic auth requested, configuring')
+ self.session.auth = (self.options.get('basic_auth_user'), self.options.get('basic_auth_password'))
+ if options.get('disable_ssl_cert_check', True):
+ self.session.verify = False
+ g.logger.Debug(2, 'API SSL certificate check has been disbled')
+ from urllib3.exceptions import InsecureRequestWarning
+ requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
+ self.api_version = None
+ self.zm_version = None
+ self.zm_tz = None
+
+ self._login()
+
+ self.Monitors = None
+ self.Events = None
+ self.Configs = None
+
+ def _versiontuple(self, v):
+ # https://stackoverflow.com/a/11887825/1361529
+ return tuple(map(int, (v.split("."))))
+
+ def get_session(self):
+ return self.session
+
+ def version(self):
+ """Returns version of API and ZM
+
+ Returns:
+ dict: Version of API and ZM::
+
+ {
+ status: string # if 'error' then will also have 'reason'
+ api_version: string # if status is 'ok'
+ zm_version: string # if status is 'ok'
+ }
+ """
+ if not self.authenticated:
+ return {'status':'error', 'reason':'not authenticated'}
+ return {
+ 'status': 'ok',
+ 'api_version': self.api_version,
+ 'zm_version': self.zm_version
+ }
+
+ def tz(self):
+ """Returns timezone of ZoneMinder server
+
+ Returns:
+ string: timezone of ZoneMinder server (or None if API not supported)
+ """
+ if not self.zm_tz:
+ url = self.api_url + '/host/gettimezone.json'
+
+ try:
+ r = self._make_request(url=url)
+ self.zm_tz = r.get('tz')
+ except requests.exceptions.HTTPError:
+ g.logger.Error('Timezone API not found, relative timezones will be local time')
+ return self.zm_tz
+
+ def authenticated(self):
+ """True if login API worked
+
+ Returns:
+ boolean -- True if Login API worked
+ """
+ return self.authenticated
+
+ # called in _make_request to avoid 401s if possible
+ def _refresh_tokens_if_needed(self):
+ if not (self.access_token_expires and self.refresh_token_expires):
+ return
+ tr = (self.access_token_datetime - datetime.datetime.now()).total_seconds()
+ if (tr >= 60 * 5): # 5 mins grace
+ g.logger.Debug(3, 'No need to relogin as access token still has {} minutes remaining'.format(tr / 60))
+ return
+ else:
+ self._relogin()
+
+ def _relogin(self):
+ """ Used for 401. I could use _login too but decided to do a simpler fn
+ """
+ if self._versiontuple(self.api_version) >= self._versiontuple('2.0'):
+ # use tokens
+ tr = (self.refresh_token_datetime - datetime.datetime.now()).total_seconds()
+
+ if (tr >= 60 * 5): # 5 mins grace
+ g.logger.Debug(2, 'Going to use refresh token as it still has {} minutes remaining'.format(tr / 60))
+ self.options['token'] = self.refresh_token
+ else:
+ g.logger.Debug(1, 'Refresh token only has {}s of lifetime, going to use user/pass'.format(tr))
+ self.options['token'] = None
+ self._login()
+
+ def _login(self):
+ """This is called by the constructor. You are not expected to call this directly.
+
+ Raises:
+ err: reason for failure
+ """
+ try:
+ url = self.api_url + '/host/login.json'
+ if self.options.get('token'):
+ g.logger.Debug(1, 'Using token for login [{}]'.format(self.options.get('token')))
+ data = {'token': self.options.get('token')}
+ self.auth_enabled = True
+
+ elif self.options.get('user') and self.options.get('password'):
+ g.logger.Debug(1, 'using username/password for login')
+ data = {'user': self.options.get('user'), 'pass': self.options.get('password')}
+ self.auth_enabled = True
+
+ else:
+ g.logger.Debug(1, 'Not using auth')
+ self.auth_enabled = False
+ data = {}
+ url = self.api_url + '/host/getVersion.json'
+
+ r = self.session.post(url, data=data)
+ if r.status_code == 401 and self.options.get('token') and self.auth_enabled:
+ g.logger.Debug(1, 'Token auth with refresh failed. Likely revoked, doing u/p login')
+ self.options['token'] = None
+ data = {'user': self.options.get('user'), 'pass': self.options.get('password')}
+ r = self.session.post(url, data=data)
+ r.raise_for_status()
+ else:
+ r.raise_for_status()
+
+ g.logger.Debug(1, r.text)
+ rj = r.json()
+ self.api_version = rj.get('apiversion')
+ self.zm_version = rj.get('version')
+ if self.auth_enabled:
+ if (self._versiontuple(self.api_version) >= self._versiontuple('2.0')):
+ g.logger.Debug(2, 'Using new token API')
+ self.access_token = rj.get('access_token','')
+ if rj.get('refresh_token'):
+ self.refresh_token = rj.get('refresh_token')
+ if (rj.get('access_token_expires')):
+ self.access_token_expires = int(rj.get('access_token_expires'))
+ self.access_token_datetime = datetime.datetime.now() + datetime.timedelta(seconds = self.access_token_expires)
+ g.logger.Debug(1, 'Access token expires on:{} [{}s]'.format(self.access_token_datetime, self.access_token_expires))
+ if (rj.get('refresh_token_expires')):
+ self.refresh_token_expires = int(rj.get('refresh_token_expires'))
+ self.refresh_token_datetime = datetime.datetime.now() + datetime.timedelta(seconds=self.refresh_token_expires)
+ g.logger.Debug(1, 'Refresh token expires on:{} [{}s]'.format(self.refresh_token_datetime, self.refresh_token_expires))
+ else:
+ g.logger.Info('Using old credentials API. Recommended you upgrade to token API')
+ self.legacy_credentials = rj.get('credentials')
+ if (rj.get('append_password') == '1'):
+ self.legacy_credentials = self.legacy_credentials + self.options.get('password')
+ self.authenticated = True
+ # print (vars(self.session))
+
+ except requests.exceptions.HTTPError as err:
+ g.logger.Error('Got API login error: {}'.format(err))
+ self.authenticated = False
+ raise err
+
+ def get_apibase(self):
+ return self.api_url
+
+ def get_portalbase(self):
+ return self.portal_url
+
+ def get_auth(self):
+ if not self.auth_enabled:
+ return ''
+
+ if self._versiontuple(self.api_version) >= self._versiontuple('2.0'):
+ return 'token=' + self.access_token
+ else:
+ return self.legacy_credentials
+
+ def _make_request(self, url=None, query={}, payload={}, type='get', reauth=True):
+
+ self._refresh_tokens_if_needed()
+ type = type.lower()
+ if self.auth_enabled:
+ if self._versiontuple(self.api_version) >= self._versiontuple('2.0'):
+ query['token'] = self.access_token
+ # ZM 1.34 API bug, will be fixed soon
+ # self.session = requests.Session()
+
+ else:
+ # credentials is already query formatted
+ lurl = url.lower()
+ if lurl.endswith('json') or lurl.endswith('/'):
+ qchar = '?'
+ else:
+ qchar = '&'
+ url += qchar + self.legacy_credentials
+
+ try:
+ g.logger.Debug(3, 'make_request called with url={} payload={} type={} query={}'.format(url, payload, type, query))
+ if type == 'get':
+ r = self.session.get(url, params=query)
+
+ elif type == 'post':
+ r = self.session.post(url, data=payload, params=query)
+ elif type == 'put':
+ r = self.session.put(url, data=payload, params=query)
+ elif type == 'delete':
+ r = self.session.delete(url, data=payload, params=query)
+ else:
+ g.logger.Error('Unsupported request type:{}'.format(type))
+ raise ValueError('Unsupported request type:{}'.format(type))
+ # print (url, params)
+ # r = requests.get(url, params=params)
+ # print(r.request.headers)
+
+ r.raise_for_status()
+
+ # Empty response, e.g. to DELETE requests, can't be parsed to json
+ # even if the content-type says it is application/json
+
+ if r.headers.get('content-type').startswith("application/json") and r.text:
+ return r.json()
+ elif r.headers.get('content-type').startswith('image/'):
+ return r
+ elif type == 'delete':
+ return None
+ else:
+ # A non 0 byte response will usually mean its an image eid request that needs re-login
+ if r.headers.get('content-length') != '0':
+ g.logger.Debug(2, 'Raising RELOGIN ValueError')
+ raise ValueError("RELOGIN")
+ else:
+ # ZM returns 0 byte body if index not found
+ g.logger.Debug(2, 'Raising BAD_IMAGE ValueError as Content-Length:0')
+ raise ValueError("BAD_IMAGE")
+ # return r.text
+
+ except requests.exceptions.HTTPError as err:
+ g.logger.Debug(1, 'HTTP error: {}'.format(err))
+ if err.response.status_code == 401 and reauth:
+ g.logger.Debug(1, 'Got 401 (Unauthorized) - retrying login once')
+ self._relogin()
+ g.logger.Debug(1, 'Retrying failed request again...')
+ return self._make_request(url, query, payload, type, reauth=False)
+ elif err.response.status_code == 404:
+ # ZM returns 404 when an image cannot be decoded
+ g.logger.Debug(3, 'Raising BAD_IMAGE ValueError for a 404')
+ raise ValueError("BAD_IMAGE")
+ except ValueError as err:
+ err_msg = '{}'.format(err)
+ if err_msg == "RELOGIN":
+ if reauth:
+ g.logger.Debug(1, 'Got ValueError access error: {}'.format(err))
+ g.logger.Debug(1, 'Retrying login once')
+ self._relogin()
+ g.logger.Debug(1, 'Retrying failed request again...')
+ return self._make_request(url, query, payload, type, reauth=False)
+ else:
+ raise err
+ elif err_msg == "BAD_IMAGE":
+ raise ValueError("BAD_IMAGE")
+
+ def monitors(self, options={}):
+ """Returns list of monitors. Given monitors are fairly static, maintains a cache and returns from cache on subsequent calls.
+
+ Args:
+ options (dict, optional): Available fields::
+
+ {
+ 'force_reload': boolean # if True refreshes monitors
+
+ }
+
+ Returns:
+ list of :class:`pyzm.helpers.Monitor`: list of monitors
+ """
+ if options.get('force_reload') or not self.Monitors:
+ self.Monitors = Monitors(api=self)
+ return self.Monitors
+
+ def events(self, options={}):
+ """Returns list of events based on filter criteria. Note that each time you called events, a new HTTP call is made.
+
+ Args:
+ options (dict, optional): Various filters that will be applied to events. Defaults to {}. Available fields::
+
+ {
+ 'event_id': string # specific event ID to fetch
+ 'tz': string # long form timezone (example America/New_York),
+ 'from': string # string # minimum start time (including human readable
+ # strings like '1 hour ago' or '10 minutes ago to 5 minutes ago' to create a range)
+ 'to': string # string # maximum end time
+ 'mid': int # monitor id
+ 'min_alarmed_frames': int # minimum alarmed frames
+ 'max_alarmed_frames': int # maximum alarmed frames
+ 'object_only': boolean # if True will only pick events
+ # that have objects
+
+ }
+
+ Returns:
+ list of :class:`pyzm.helpers.Event`: list of events that match criteria
+ """
+ self.Events = Events(api=self, options=options)
+ return self.Events
+
+ def states(self, options={}):
+ """Returns configured states
+
+ Args:
+ options (dict, optional): Not used. Defaults to {}.
+
+ Returns:
+ list of :class:`pyzm.helpers.State`: list of states
+ """
+ self.States = States(api=self)
+ return self.States
+
+ def restart(self):
+ """Restarts ZoneMinder
+
+ Returns:
+ json: json value of restart command
+ """
+ return self.set_state(state='restart')
+
+ def stop(self):
+ """Stops ZoneMinder
+
+ Returns:
+ json: json value of stop command
+ """
+ return self.set_state(state='stop')
+
+ def start(self):
+ """Starts ZoneMinder
+
+ Returns:
+ json: json value of start command
+ """
+ return self.set_state(state='start')
+
+ def set_state(self, state):
+ """Sets Zoneminder state to specific state
+
+ Args:
+ state (string): Name of state
+
+ Returns:
+ json: value of state change command
+ """
+ if not state:
+ return
+ url = self.api_url + '/states/change/{}.json'.format(state)
+ return self._make_request(url=url)
+
+ def configs(self, options={}):
+ """Returns config values of ZM
+
+ Args:
+ options (dict, optional): Defaults to {}.
+ options::
+
+ {
+ 'force_reload': boolean # if True, reloads
+ }
+
+ Returns:
+ :class:`pyzm.helpers.Configs`: ZM configs
+ """
+ if options.get('force_reload') or not self.Configs:
+ # self.Configs = Configs(api=self) # Configs not imported
+ pass
+ return self.Configs
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/Base.py b/src/hi/services/zoneminder/pyzm_client/helpers/Base.py
new file mode 100644
index 00000000..a00bccd3
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/helpers/Base.py
@@ -0,0 +1,56 @@
+"""
+Base
+======
+All classes derive from this Base class.
+It implements some common functions that apply across all.
+For now, this basically holds a pointer to the logging function to invoke
+to log messages including a simple console based print function if none is provided
+
+"""
+
+from datetime import datetime
+
+
+class Base:
+ def __init__(self):
+ pass
+
+
+class ConsoleLog:
+ ' console based logging function that is used if no logging handler is passed'
+ def __init__(self):
+ self.dtformat = "%b %d %Y %H:%M:%S.%f"
+ self.level = 5
+
+ def set_level(self, level):
+ self.level = level
+
+ def get_level(self):
+ return self.level
+
+ def Debug(self, level, message, caller=None):
+ if level <= self.level:
+ dt = datetime.now().strftime(self.dtformat)
+ print('{} [DBG {}] {}'.format(dt, level, message))
+
+ def Info(self, message, caller=None):
+ dt = datetime.now().strftime(self.dtformat)
+ print('{} [INF] {}'.format(dt, message))
+
+ def Warning(self, message, caller=None):
+ dt = datetime.now().strftime(self.dtformat)
+ print('{} [WAR] {}'.format(dt, message))
+
+ def Error(self, message, caller=None):
+ dt = datetime.now().strftime(self.dtformat)
+ print('{} [ERR] {}'.format(dt, message))
+
+ def Fatal(self, message, caller=None):
+ dt = datetime.now().strftime(self.dtformat)
+ print('{} [FAT] {}'.format(dt, message))
+ exit(-1)
+
+ def Panic(self, message, caller=None):
+ dt = datetime.now().strftime(self.dtformat)
+ print('{} [PNC] {}'.format(dt, message))
+ exit(-2)
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/Event.py b/src/hi/services/zoneminder/pyzm_client/helpers/Event.py
new file mode 100644
index 00000000..01bc965f
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/helpers/Event.py
@@ -0,0 +1,273 @@
+"""
+Event
+======
+Each Event will hold a single ZoneMinder Event.
+It is basically a bunch of getters for each access to event data.
+If you don't see a specific getter, just use the generic get function to get
+the full object
+"""
+
+from .Base import Base
+# import progressbar as pb # Removed dependency - progress bars not needed
+import requests
+import os
+from . import globals as g
+
+
+class Event(Base):
+ def __init__(self, event=None, api=None):
+ self.event = event
+ self.api = api
+
+ def get(self):
+ """Returns event object.
+
+ Returns:
+ :class:`pyzm.helpers.Event`: Event object
+ """
+ return self.event['Event']
+
+ def get_image_url(self, fid='snapshot'):
+ """Returns the image URL for the specified frame
+
+ Args:
+ fid (str, optional): Default frame identification. Defaults to 'snapshot'.
+
+ Returns:
+ string: URL for the image
+ """
+ eid = self.id()
+ url = self.api.portal_url + '/index.php?view=image&eid={}&fid={}'.format(eid, fid) + '&' + self.api.get_auth()
+ return url
+
+ def get_video_url(self):
+ """Returms the video URL for the specified event
+
+ Returns:
+ string: URL for the video file
+ """
+ if not self.video_file():
+ g.logger.Error('Event {} does not have a video file'.format(self.id()))
+ return None
+ eid = self.id()
+ url = self.api.portal_url + '/index.php?mode=mpeg&eid={}&view=view_video'.format(eid) + '&' + self.api.get_auth()
+ return url
+
+ def download_image(self, fid='snapshot', dir='.', show_progress=False):
+
+ """Downloads an image frame of the current event object
+
+ Args:
+ fid (str, optional): Frame ID. Defaults to 'snapshot'.
+ dir (str, optional): Path to save the image to. Defaults to '.'.
+ show_progress (bool, optional): If enabled shows a progress bar (if possible). Defaults to False.
+
+ Returns:
+ string: path+filename of downloaded image
+
+ """
+
+ url = self.get_image_url(fid)
+ f = self._download_file(url, str(self.id()) + '-' + fid + '.jpg', dir, show_progress)
+ g.logger.Info('File downloaded to {}'.format(f))
+ return f
+
+ def download_video(self, dir='.', show_progress=False):
+ """Downloads a video mp4 of the current event object
+ Only works if there an actual video
+
+ Args:
+ dir (str, optional): Path to save the image to. Defaults to '.'.
+ show_progress (bool, optional): If enabled shows a progress bar (if possible). Defaults to False.
+
+ Returns:
+ string: path+filename of downloaded video
+
+ """
+
+ url = self.get_video_url()
+ if not url:
+ return None
+ f = self._download_file(url, str(self.id()) + '-video' + '.mp4', dir, show_progress)
+ g.logger.Info('File downloaded to {}'.format(f))
+ return f
+
+ def delete(self):
+ """Deletes this event
+
+ Returns:
+ json: API response
+ """
+ url = self.api.api_url + '/events/{}.json'.format(self.id())
+ return self.api._make_request(url=url, type='delete')
+
+ def monitor_id(self):
+ """returns monitor ID of event object.
+
+ Returns:
+ int: monitor id
+ """
+ return int(self.event['Event']['MonitorId'])
+
+ def id(self):
+ """returns event id of event.
+
+ Returns:
+ int: event id
+ """
+ return int(self.event['Event']['Id'])
+
+ def name(self):
+ """returns name of event.
+
+ Returns:
+ string: name of event
+ """
+ return self.event['Event']['Name'] or None
+
+ def video_file(self):
+ """returns name of video file in which the event was stored.
+
+ Returns:
+ string: name of video file
+ """
+ return self.event['Event'].get('DefaultVideo')
+
+ def cause(self):
+ """returns event cause.
+
+ Returns:
+ string: event cause
+ """
+ return self.event['Event']['Cause'] or None
+
+ def notes(self):
+ """returns event notes.
+
+ Returns:
+ string: event notes
+ """
+ return self.event['Event']['Notes'] or None
+
+ def fspath(self):
+ """returns the filesystem path where the event is stored. Only
+ available in ZM 1.33+
+
+ Returns:
+ string: path
+ """
+ return self.event['Event'].get('FileSystemPath')
+
+ def duration(self):
+ """Returns duration of event in seconds.
+
+ Returns:
+ float: duration
+ """
+ return float(self.event['Event']['Length'])
+
+ def total_frames(self):
+ """Returns total frames in event.
+
+ Returns:
+ int: total frames
+ """
+ return int(self.event['Event']['Frames'])
+
+ def alarmed_frames(self):
+ """Returns total alarmed frames in event.
+
+ Returns:
+ int: total alarmed frames
+ """
+ return int(self.event['Event']['AlarmFrames'])
+
+ def score(self):
+ """Returns total, average and max scores of event.
+
+ Returns:
+ dict: As below::
+
+ {
+ 'total': float,
+ 'average': float,
+ 'max': float
+ }
+ """
+ return {
+ 'total': float(self.event['Event']['TotScore']),
+ 'average': float(self.event['Event']['AvgScore']),
+ 'max': float(self.event['Event']['MaxScore'])
+ }
+
+ def _download_file(self, url, file_name, dest_dir, show_progress=False, reauth=True):
+
+ if not os.path.exists(dest_dir):
+ os.makedirs(dest_dir)
+
+ full_path_to_file = dest_dir + os.path.sep + file_name
+
+ if os.path.exists(dest_dir + os.path.sep + file_name):
+ return full_path_to_file
+
+ g.logger.Info("Downloading " + file_name + " from " + url)
+
+ try:
+ req = requests
+ if self.api and self.api.get_session():
+ req = self.api.get_session()
+ # print ("OVERRIDING")
+ r = req.get(url, allow_redirects=True, stream=True)
+
+ # r = requests.get(url, allow_redirects=True, stream=True)
+ except requests.exceptions.HTTPError as err:
+ g.logger.Debug(1, 'Got download access error: {}'.format(err), 'error')
+ if err.response.status_code == 401 and reauth:
+ g.logger.Debug(1, 'Retrying login once')
+ self._relogin()
+ g.logger.Debug(1, 'Retrying failed request again...')
+ return self._download_file(url, file_name, dest_dir, show_progress, reauth=False)
+ else:
+ raise err
+ except Exception:
+ # e = sys.exc_info()[0]
+ # print(e)
+ g.logger.Error("Could not establish connection. Download failed")
+ return None
+
+ if r.headers.get('Content-Type') and "text/html" in r.headers.get('Content-Type'):
+ if reauth:
+ g.logger.Error('We got redirected to login while trying to download, trying one more time')
+ return self._download_file(url, file_name, dest_dir, show_progress, reauth=False)
+ else:
+ g.logger.Error('Failed doing reauth, not trying again')
+ return None
+
+ chunk_size = 1024
+
+ if show_progress:
+ g.logger.WarningG("Progress bar feature disabled in pyzm_client - progressbar dependency removed")
+ # Progress bar removed - not needed for our use case
+ # if r.headers.get('Content-Length'):
+ # file_size = int(r.headers['Content-Length'])
+ # if file_size:
+ # num_bars = round(file_size / chunk_size)
+ # bar = pb.ProgressBar(maxval=num_bars).start()
+ # else:
+ # bar = pb.ProgressBar().start()
+
+ if r.status_code != requests.codes.ok:
+ g.logger.Error("Error occurred while downloading file")
+ return None
+
+ count = 0
+
+ with open(full_path_to_file, 'wb') as fp:
+ for chunk in r.iter_content(chunk_size=chunk_size):
+ fp.write(chunk)
+ if show_progress:
+ # bar.update(count) # Progress bar disabled
+ count += 1
+ fp.close()
+
+ return full_path_to_file
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/Events.py b/src/hi/services/zoneminder/pyzm_client/helpers/Events.py
new file mode 100644
index 00000000..16a6bc93
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/helpers/Events.py
@@ -0,0 +1,144 @@
+"""
+Events
+=======
+Holds a list of Events for a ZM configuration
+You can pass different conditions to filter the events
+Each invocation results in a new API call as events are very dynamic
+
+You are not expected to use this module directly. It is instantiated when you use the :meth:`pyzm.api.ZMApi.events` method of :class:`pyzm.api`
+"""
+
+from .Base import Base
+from .Event import Event
+# import requests # Unused
+import dateparser
+from . import globals as g
+
+
+class Events(Base):
+ def __init__(self, api=None, options=None):
+
+ self.api = api
+ self.events = []
+ self.pagination = {}
+ self._load(options)
+
+ def list(self):
+ """Returns list of event
+
+ Returns:
+ list -- events of :class:`.Event`
+ """
+ return self.events
+
+ def count(self):
+ """Returns number of events retrieved in previous invocation
+
+ Returns:
+ int -- number of events
+ """
+ return int(self.pagination.get('count'))
+
+ def _load(self, options={}):
+ g.logger.Debug(2, 'Retrieving events via API')
+ url_filter = ''
+
+ tz = {}
+
+ if options.get('event_id'):
+ url_filter += '/Id=:' + str(options.get('event_id'))
+ if options.get('tz'):
+ tz = {'TIMEZONE': options.get('tz')}
+ # print ('USING ',tz)
+ if options.get('from'):
+ from_list = options.get('from').split(" to ", 1)
+ if len(from_list) == 2:
+ from_start = dateparser.parse(from_list[0], settings=tz)
+ from_end = dateparser.parse(from_list[1], settings=tz)
+ if from_start > from_end:
+ from_start, from_end = from_end, from_start
+
+ url_filter += '/StartTime >=:' + from_start.strftime('%Y-%m-%d %H:%M:%S')
+ url_filter += '/StartTime <=:' + from_end.strftime('%Y-%m-%d %H:%M:%S')
+ else:
+ url_filter += '/StartTime >=:' + dateparser.parse(from_list[0], settings=tz).strftime('%Y-%m-%d %H:%M:%S')
+ if options.get('to'):
+ to_list = options.get('to').split(" to ", 1)
+ if len(to_list) == 2:
+ to_start = dateparser.parse(to_list[0], settings=tz)
+ to_end = dateparser.parse(to_list[1], settings=tz)
+ if to_start > to_end:
+ to_start, to_end = to_end, to_start
+ url_filter += '/EndTime <=:' + to_end.strftime('%Y-%m-%d %H:%M:%S')
+ url_filter += '/EndTime >=:' + to_start.strftime('%Y-%m-%d %H:%M:%S')
+ else:
+ url_filter += '/EndTime <=:' + dateparser.parse(to_list[0], settings=tz).strftime('%Y-%m-%d %H:%M:%S')
+ if options.get('mid'):
+ url_filter += '/MonitorId =:' + str(options.get('mid'))
+ if options.get('min_alarmed_frames'):
+ url_filter += '/AlarmFrames >=:' + str(options.get('min_alarmed_frames'))
+ if options.get('max_alarmed_frames'):
+ url_filter += '/AlarmFrames <=:' + str(options.get('max_alarmed_frames'))
+ if options.get('object_only'):
+ url_filter += '/Notes REGEXP:detected:'
+
+ # catch all
+ if options.get('raw_filter'):
+ url_filter += options.get('raw_filter')
+
+ # print ('URL filter: ',url_filter)
+ # tbd - no need for url_prefix in options
+ url_prefix = options.get('url_prefix', self.api.api_url + '/events/index')
+
+ url = url_prefix + url_filter + '.json'
+ params = {
+ 'sort': 'StartTime',
+ 'direction': 'desc',
+ 'page': 1
+ }
+ for k in options:
+ if k in params:
+ params[k] = options[k]
+
+ numevents = 100
+ if options.get('max_events'):
+ numevents = options.get('max_events')
+ if options.get('limit'):
+ numevents = options.get('limit')
+
+ params['limit'] = numevents
+ currevents = 0
+ self.events = []
+ events = []
+ while True:
+ r = self.api._make_request(url=url, query=params)
+ events.extend(r.get('events'))
+ pagination = r.get('pagination')
+ self.pagination = pagination
+ if not pagination:
+ break
+ if not pagination.get('nextPage'):
+ break
+ currevents += int(pagination.get('current'))
+ if currevents >= numevents:
+ break
+ params['page'] += 1
+
+ for event in events:
+ self.events.append(Event(event=event, api=self.api))
+
+ def get(self, options={}):
+ """Returns the full list of events. Typically useful if you need access to data for which you don't have an easy getter
+
+ Keyword Arguments:
+
+ - options: dict with same parameters as the one you pass in :meth:`pyzm.api.ZMApi.events`. This is really a convenience instead of re-creating the instance.
+
+ Returns:
+ list -- of :class:`pyzm.helpers.Events`
+ """
+ self._load(options)
+ return self.events
+
+
+
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/Monitor.py b/src/hi/services/zoneminder/pyzm_client/helpers/Monitor.py
new file mode 100644
index 00000000..35a8122b
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/helpers/Monitor.py
@@ -0,0 +1,186 @@
+"""
+Monitor
+=======
+Each Monitor will hold a single ZoneMinder Monitor.
+It is basically a bunch of getters for each access to event data.
+If you don't see a specific getter, just use the generic get function to get
+the full object
+"""
+
+
+from .Base import Base
+
+
+class Monitor(Base):
+ def __init__(self, api=None, monitor=None):
+ self.monitor = monitor
+ self.api = api
+
+ def get(self):
+ """Returns monitor object
+
+ Returns:
+ :class:`pyzm.helpers.Monitor`: Monitor object
+ """
+ return self.monitor['Monitor']
+
+ def enabled(self):
+ """True if monitor is enabled
+
+ Returns:
+ bool: Enabled or not
+ """
+ return self.monitor['Monitor']['Enabled'] == '1'
+
+ def function(self):
+ """returns monitor function
+
+ Returns:
+ string: monitor function
+ """
+ return self.monitor['Monitor']['Function']
+
+ def name(self):
+ """Returns monitor name
+
+ Returns:
+ string: monitor name
+ """
+ return self.monitor['Monitor']['Name']
+
+ def id(self):
+ """Returns monitor Id
+
+ Returns:
+ int: Monitor Id
+ """
+ return int(self.monitor['Monitor']['Id'])
+
+ def type(self):
+ """Returns monitor type
+
+ Returns:
+ string: Monitor type
+ """
+ return self.monitor['Monitor']['Type']
+
+ def dimensions(self):
+ """Returns width and height of monitor
+
+ Returns:
+ dict: as below::
+
+ {
+ 'width': int,
+ 'height': int
+ }
+ """
+ return {'width': int(self.monitor['Monitor']['Width']),
+ 'height': int(self.monitor['Monitor']['Height'])}
+
+ def events(self, options={}):
+ """Returns events associated to the monitor, subject to filters in options
+
+ Args:
+ options (dict, optional): Same as options for :class:`pyzm.helpers.Event`. Defaults to {}.
+
+ Returns:
+ :class:`pyzm.helpers.Events`
+ """
+ options['mid'] = self.id()
+ return self.api.events(options=options)
+
+ def eventcount(self, options={}):
+ """Returns count of events for monitor
+
+ Args:
+ options (dict, optional): Same as options for :class:`pyzm.helpers.Event`. Defaults to {}.
+
+ Returns:
+ int: count
+ """
+ # regular events API is more powerful than
+ # console events as it allows us flexible timings
+ # making limit=1 keeps the processing limited
+ options['mid'] = self.id()
+ options['max_events'] = 1
+ return self.api.events(options=options).count()
+ # print (s)
+
+ def delete(self):
+ """Deletes monitor
+
+ Returns:
+ json: API response
+ """
+ url = self.api.api_url + '/monitors/{}.json'.format(self.id())
+ return self.api._make_request(url=url, type='delete')
+
+ def set_parameter(self, options={}):
+ """Changes monitor parameters
+
+ Args:
+ options (dict, optional): As below. Defaults to {}::
+
+ {
+ 'function': string # function of monitor
+ 'name': string # name of monitor
+ 'enabled': boolean
+ 'raw': {
+ # Any other monitor value that is not exposed above. Example:
+ 'Monitor[Colours]': '4',
+ 'Monitor[Method]': 'simple'
+ }
+
+ }
+
+
+ Returns:
+ json: API Response
+ """
+ url = self.api.api_url + '/monitors/{}.json'.format(self.id())
+ payload = {}
+ if options.get('function'):
+ payload['Monitor[Function]'] = options.get('function')
+ if options.get('name'):
+ payload['Monitor[Name]'] = options.get('name')
+ if options.get('enabled') is not None:
+ enabled = '1' if options.get('enabled') else '0'
+ payload['Monitor[Enabled]'] = enabled
+
+ if options.get('raw'):
+ for k in options.get('raw'):
+ payload[k] = options.get('raw')[k]
+
+ if payload:
+ return self.api._make_request(url=url, payload=payload, type='post')
+
+ def arm(self):
+ """Arms monitor (forces alarm)
+
+ Returns:
+ json: API response
+ """
+ return self._set_alarm(type='on')
+
+ def disarm(self):
+ """Disarm monito (removes alarm)
+
+ Returns:
+ json: API response
+ """
+ return self._set_alarm(type='off')
+
+ def _set_alarm(self, type='on'):
+ url = self.api.api_url + '/monitors/alarm/id:{}/command:{}.json'.format(self.id(), type)
+ return self.api._make_request(url=url)
+
+ def status(self):
+ """Returns status of monitor, as reported by zmdc
+ TBD: crappy return, need to normalize
+
+ Returns:
+ json: API response
+ """
+ url = self.api.api_url + '/monitors/daemonStatus/id:{}/daemon:zmc.json'.format(self.id())
+ return self.api._make_request(url=url)
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/Monitors.py b/src/hi/services/zoneminder/pyzm_client/helpers/Monitors.py
new file mode 100644
index 00000000..97dcd6aa
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/helpers/Monitors.py
@@ -0,0 +1,108 @@
+"""
+Monitors
+=========
+Holds a list of Monitors for a ZM configuration
+Given monitors are fairly static, maintains a cache of monitors
+which can be overriden
+"""
+
+
+from .Monitor import Monitor
+from .Base import Base
+from . import globals as g
+
+
+class Monitors(Base):
+ def __init__(self, api=None):
+ self.api = api
+ self._load()
+
+ def _load(self, options={}):
+ g.logger.Debug(2, 'Retrieving monitors via API')
+ url = self.api.api_url + '/monitors.json'
+ r = self.api._make_request(url=url)
+ ms = r.get('monitors')
+ self.monitors = []
+ for m in ms:
+ self.monitors.append(Monitor(monitor=m, api=self.api))
+
+ def list(self):
+ return self.monitors
+
+ def add(self, options={}):
+ """Adds a new monitor
+
+ Args:
+ options (dict): Set of attributes that define the monitor::
+
+ {
+ 'function': string # function of monitor
+ 'name': string # name of monitor
+ 'enabled': boolean
+ 'protocol': string
+ 'host': string
+ 'port': int
+ 'path': string
+ 'width': int
+ 'height': int
+ 'raw': {
+ # Any other monitor value that is not exposed above. Example:
+ 'Monitor[Colours]': '4',
+ 'Monitor[Method]': 'simple'
+ }
+
+ }
+
+ Returns:
+ json: json response of API request
+ """
+ url = self.api.api_url + '/monitors.json'
+ payload = {}
+ if options.get('function'):
+ payload['Monitor[Function]'] = options.get('function')
+ if options.get('name'):
+ payload['Monitor[Name]'] = options.get('name')
+ if options.get('enabled'):
+ enabled = '1' if options.get('enabled') else '0'
+ payload['Monitor[Enabled]'] = enabled
+ if options.get('protocol'):
+ payload['Monitor[Protocol]'] = options.get('protocol')
+ if options.get('host'):
+ payload['Monitor[Host]'] = options.get('host')
+ if options.get('port'):
+ payload['Monitor[Port]'] = str(options.get('port'))
+ if options.get('path'):
+ payload['Monitor[Path]'] = options.get('path')
+ if options.get('width'):
+ payload['Monitor[Width]'] = str(options.get('width'))
+ if options.get('height'):
+ payload['Monitor[Height]'] = str(options.get('height'))
+
+ if options.get('raw'):
+ for k in options.get('raw'):
+ payload[k] = options.get('raw')[k]
+
+ if payload:
+ return self.api._make_request(url=url, payload=payload, type='post')
+
+ def find(self, id=None, name=None):
+ """Given an id or name, returns matching monitor object
+
+ Args:
+ id (int, optional): MonitorId of monitor. Defaults to None.
+ name (string, optional): Monitor name of monitor. Defaults to None.
+
+ Returns:
+ :class:`pyzm.helpers.Monitor`: Matching monitor object
+ """
+ if not id and not name:
+ return None
+ match = None
+ for mon in self.monitors:
+ if id and mon.id() == id:
+ match = mon
+ break
+ if name and mon.name().lower() == name.lower():
+ match = mon
+ break
+ return match
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/State.py b/src/hi/services/zoneminder/pyzm_client/helpers/State.py
new file mode 100644
index 00000000..2fe42dad
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/helpers/State.py
@@ -0,0 +1,57 @@
+"""
+State
+======
+Each State will hold a single ZoneMinder State.
+It is basically a bunch of getters for each access to event data.
+If you don't see a specific getter, just use the generic get function to get
+the full object
+"""
+
+
+from .Base import Base
+
+
+class State(Base):
+ def __init__(self, api=None, state=None):
+ self.state = state
+ self.api = api
+
+ def get(self):
+ """Returns raw state object
+
+ Returns:
+ :class:`pyzm.helpers.State`: raw state object
+ """
+ return self.state['State']
+
+ def active(self):
+ """whether this state is active or not
+
+ Returns:
+ bool: True if active
+ """
+ return self.state['State']['IsActive'] == '1'
+
+ def definition(self):
+ """Returns the description text of this state
+
+ Returns:
+ string: description
+ """
+ return self.state['State']['Definition'] or None
+
+ def name(self):
+ """Name of this state
+
+ Returns:
+ string: name of this state
+ """
+ return self.state['State']['Name']
+
+ def id(self):
+ """Id of this state
+
+ Returns:
+ int: id of this state
+ """
+ return int(self.state['State']['Id'])
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/States.py b/src/hi/services/zoneminder/pyzm_client/helpers/States.py
new file mode 100644
index 00000000..b7bc70aa
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/helpers/States.py
@@ -0,0 +1,57 @@
+"""
+States
+=======
+Holds a list of States for a ZM configuration
+Given states are fairly static, maintains a cache of states
+which can be overriden
+"""
+
+
+from .State import State
+from .Base import Base
+from . import globals as g
+
+
+class States(Base):
+ def __init__(self, api=None):
+ self.api = api
+ self._load()
+
+ def _load(self, options={}):
+ g.logger.Debug(2, 'Retrieving states via API')
+ url = self.api.api_url + '/states.json'
+ r = self.api._make_request(url=url)
+ states = r.get('states')
+ self.states = []
+ for state in states:
+ self.states.append(State(state=state, api=self.api))
+
+ def list(self):
+ """Returns list of state objects
+
+ Returns:
+ list of `pyzm.helpers.State`: list of state objects
+ """
+ return self.states
+
+ def find(self, id=None, name=None):
+ """Return a state object that matches either and id or a
+
+ Args:
+ id (int, optional): Id of state. Defaults to None.
+ name (string, optional): name of state. Defaults to None.
+
+ Returns:
+ :class:`pyzm.helpers.State`: State object that matches
+ """
+ if not id and not name:
+ return None
+ match = None
+ for state in self.states:
+ if id and state.id() == id:
+ match = state
+ break
+ if name and state.name().lower() == name.lower():
+ match = state
+ break
+ return match
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/__init__.py b/src/hi/services/zoneminder/pyzm_client/helpers/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/services/zoneminder/pyzm_client/helpers/globals.py b/src/hi/services/zoneminder/pyzm_client/helpers/globals.py
new file mode 100644
index 00000000..cb440972
--- /dev/null
+++ b/src/hi/services/zoneminder/pyzm_client/helpers/globals.py
@@ -0,0 +1,2 @@
+from .Base import ConsoleLog
+logger = ConsoleLog()
diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.py
index 1f0005c6..01babf34 100644
--- a/src/hi/services/zoneminder/zm_manager.py
+++ b/src/hi/services/zoneminder/zm_manager.py
@@ -1,9 +1,9 @@
import logging
-from pyzm.api import ZMApi
-from pyzm.helpers.Event import Event as ZmEvent
-from pyzm.helpers.Monitor import Monitor as ZmMonitor
-from pyzm.helpers.State import State as ZmState
-from pyzm.helpers.globals import logger as pyzm_logger
+from .pyzm_client.api import ZMApi
+from .pyzm_client.helpers.Event import Event as ZmEvent
+from .pyzm_client.helpers.Monitor import Monitor as ZmMonitor
+from .pyzm_client.helpers.State import State as ZmState
+from .pyzm_client.helpers.globals import logger as pyzm_logger
from threading import Lock
from typing import Dict, List
diff --git a/src/hi/services/zoneminder/zm_models.py b/src/hi/services/zoneminder/zm_models.py
index e554f9bd..ffec95a2 100644
--- a/src/hi/services/zoneminder/zm_models.py
+++ b/src/hi/services/zoneminder/zm_models.py
@@ -5,7 +5,7 @@ from typing import Dict, List
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.entity.enums import EntityStateValue
-from pyzm.helpers.Event import Event as ZmApiEvent
+from .pyzm_client.helpers.Event import Event as ZmApiEvent
from .constants import ZmDetailKeys
from .zm_manager import ZoneMinderManager
diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.py
index f67eac37..b7766ced 100644
--- a/src/hi/services/zoneminder/zm_sync.py
+++ b/src/hi/services/zoneminder/zm_sync.py
@@ -1,5 +1,5 @@
import logging
-from pyzm.helpers.Monitor import Monitor as ZmMonitor
+from .pyzm_client.helpers.Monitor import Monitor as ZmMonitor
from typing import Dict
from django.db import transaction
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index 2c0dbc34..b4f05254 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -13,71 +13,71 @@ https://docs.djangoproject.com/en/4.2/ref/settings/
from pathlib import Path
import os
-from .helpers import EnvironmentSettings
+from hi.environment.server import EnvironmentSettings
-env_settings = EnvironmentSettings.get()
+ENV = EnvironmentSettings.get()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
-SECRET_KEY = env_settings.SECRET_KEY
+SECRET_KEY = ENV.SECRET_KEY
-DJANGO_SUPERUSER_EMAIL = env_settings.DJANGO_SUPERUSER_EMAIL
-DJANGO_SUPERUSER_PASSWORD = env_settings.DJANGO_SUPERUSER_PASSWORD
+DJANGO_SUPERUSER_EMAIL = ENV.DJANGO_SUPERUSER_EMAIL
+DJANGO_SUPERUSER_PASSWORD = ENV.DJANGO_SUPERUSER_PASSWORD
-SITE_ID = env_settings.SITE_ID
-SITE_DOMAIN = env_settings.SITE_DOMAIN
-SITE_NAME = env_settings.SITE_NAME
+SITE_ID = ENV.SITE_ID
+SITE_DOMAIN = ENV.SITE_DOMAIN
+SITE_NAME = ENV.SITE_NAME
-ALLOWED_HOSTS = env_settings.ALLOWED_HOSTS
+ALLOWED_HOSTS = ENV.ALLOWED_HOSTS
-CORS_ALLOWED_ORIGINS = env_settings.CORS_ALLOWED_ORIGINS
+CORS_ALLOWED_ORIGINS = ENV.CORS_ALLOWED_ORIGINS
CSP_DEFAULT_SRC = (
"'self'",
'data:',
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
CSP_CONNECT_SRC = (
"'self'",
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
CSP_FRAME_SRC = (
"'self'",
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
CSP_SCRIPT_SRC = (
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
CSP_STYLE_SRC = (
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
CSP_MEDIA_SRC = (
"'self'",
"'unsafe-inline'",
"'unsafe-eval'",
'data:',
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
CSP_IMG_SRC = (
"'self'",
'data:',
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
CSP_CHILD_SRC = (
"'self'",
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
CSP_FONT_SRC = (
"'self'",
'data:',
-) + env_settings.EXTRA_CSP_URLS
+) + ENV.EXTRA_CSP_URLS
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
@@ -99,6 +99,7 @@ INSTALLED_APPS = [
'django.contrib.humanize',
'constance',
'custom',
+ 'hi.environment',
'hi.apps.common',
'hi.apps.user',
'hi.apps.config',
@@ -153,6 +154,7 @@ TEMPLATES = [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'hi.context_processors.constants_context',
+ 'hi.environment.context_processors.client_config',
'hi.apps.console.context_processors.settings_context',
'hi.apps.audio.context_processors.audio_context',
],
@@ -169,7 +171,7 @@ WSGI_APPLICATION = 'hi.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': os.path.join( env_settings.DATABASES_NAME_PATH, 'hi.sqlite3' ),
+ 'NAME': os.path.join( ENV.DATABASES_NAME_PATH, 'hi.sqlite3' ),
}
}
@@ -219,13 +221,13 @@ STATICFILES_DIRS = (
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
-MEDIA_ROOT = env_settings.MEDIA_ROOT
+MEDIA_ROOT = ENV.MEDIA_ROOT
MEDIA_URL = '/media/'
PIPELINE = {
'DISABLE_WRAPPER': True, # Important since some scripts assume global scope
- 'CSS_COMPRESSOR': 'django_pipeline_csscompressor.CssCompressor',
+ 'CSS_COMPRESSOR': None, # Removed django-pipeline-csscompressor (unmaintained since 2016)
'JS_COMPRESSOR': None,
'STYLESHEETS': {
@@ -298,9 +300,9 @@ CONSTANCE_CONFIG = {
'DOWN_FOR_MAINTENANCE': ( False, 'Should we force the down for maintenance page to show?' ),
}
-REDIS_HOST = env_settings.REDIS_HOST
-REDIS_PORT = env_settings.REDIS_PORT
-REDIS_KEY_PREFIX = env_settings.REDIS_KEY_PREFIX
+REDIS_HOST = ENV.REDIS_HOST
+REDIS_PORT = ENV.REDIS_PORT
+REDIS_KEY_PREFIX = ENV.REDIS_KEY_PREFIX
CACHES = {
'default': {
@@ -315,31 +317,31 @@ CACHES = {
AUTH_USER_MODEL = "custom.CustomUser"
-SUPPRESS_AUTHENTICATION = env_settings.SUPPRESS_AUTHENTICATION
+SUPPRESS_AUTHENTICATION = ENV.SUPPRESS_AUTHENTICATION
# ====================
# Transactional Emails
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
-EMAIL_SUBJECT_PREFIX = "%s " % env_settings.EMAIL_SUBJECT_PREFIX
-DEFAULT_FROM_EMAIL = env_settings.DEFAULT_FROM_EMAIL
-SERVER_EMAIL = env_settings.SERVER_EMAIL
+EMAIL_SUBJECT_PREFIX = "%s " % ENV.EMAIL_SUBJECT_PREFIX
+DEFAULT_FROM_EMAIL = ENV.DEFAULT_FROM_EMAIL
+SERVER_EMAIL = ENV.SERVER_EMAIL
FROM_EMAIL_NAME = "Home Information"
# Normal Settings
-EMAIL_HOST = env_settings.EMAIL_HOST
+EMAIL_HOST = ENV.EMAIL_HOST
try:
- EMAIL_PORT = env_settings.EMAIL_PORT
+ EMAIL_PORT = ENV.EMAIL_PORT
except (TypeError, ValueError):
EMAIL_PORT = 587
-EMAIL_HOST_USER = env_settings.EMAIL_HOST_USER
-EMAIL_HOST_PASSWORD = env_settings.EMAIL_HOST_PASSWORD
+EMAIL_HOST_USER = ENV.EMAIL_HOST_USER
+EMAIL_HOST_PASSWORD = ENV.EMAIL_HOST_PASSWORD
EMAIL_TIMEOUT = 10 # In seconds
-EMAIL_USE_TLS = env_settings.EMAIL_USE_TLS
-EMAIL_USE_SSL = env_settings.EMAIL_USE_SSL
+EMAIL_USE_TLS = ENV.EMAIL_USE_TLS
+EMAIL_USE_SSL = ENV.EMAIL_USE_SSL
# Needed when sending emails in background tasks since HttpRequest not
# available. Override this for development/testing/staging.
diff --git a/src/hi/settings/simulator.py b/src/hi/settings/simulator.py
index d75a37b8..b8364130 100644
--- a/src/hi/settings/simulator.py
+++ b/src/hi/settings/simulator.py
@@ -53,6 +53,6 @@ TEMPLATES = [
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': os.path.join( env_settings.DATABASES_NAME_PATH, 'simulator.sqlite3' ),
+ 'NAME': os.path.join( ENV.DATABASES_NAME_PATH, 'simulator.sqlite3' ),
}
}
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index 9374e12b..e5cc642e 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -30,7 +30,7 @@
// 3. js-cookie library (for CSRF token handling)
// 4. Include antinode.js after the above libraries:
// <script src="{% static 'js/antinode.js' %}"></script>
-// 5. (Optional) Set AN_VERSION variable before loading for version compatibility
+// 5. (Optional) Set window.AN_VERSION variable before loading for version compatibility
// ====================
// DECLARATIVE USAGE (HTML Attributes)
@@ -135,7 +135,7 @@
//
// To help the server-side deal with this, this module will add a custom HTTP
// header to every asynchronous call with the version number. To enable this
-// feature, you need to ensure that the javascript variable AN_VERSION is
+// feature, you need to ensure that the javascript variable window.AN_VERSION is
// set to the current version somewhere before this module loads. When
// that variable exists, this module will add the header "X-AN-Version"
// with the value of that variable.
@@ -255,8 +255,8 @@
beforeSend: function(jqXHR, ajaxSettings) {
// Add version header if available
- if ( typeof AN_VERSION !== 'undefined' ) {
- jqXHR.setRequestHeader('X-AN-Version', AN_VERSION);
+ if ( typeof window.AN_VERSION !== 'undefined' ) {
+ jqXHR.setRequestHeader('X-AN-Version', window.AN_VERSION);
}
// Call custom beforeSend if provided
@@ -377,8 +377,8 @@ function asyncSubmitHandlerHelper( $form ) {
processData: processData,
beforeSend: function (jqXHR, settings) {
- if ( typeof AN_VERSION !== 'undefined' ) {
- jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );
+ if ( typeof window.AN_VERSION !== 'undefined' ) {
+ jqXHR.setRequestHeader('X-AN-Version', window.AN_VERSION );
}
},
@@ -442,8 +442,8 @@ function asyncClickHandler(event) {
url: url,
beforeSend: function (jqXHR, settings) {
- if ( typeof AN_VERSION !== 'undefined' ) {
- jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );
+ if ( typeof window.AN_VERSION !== 'undefined' ) {
+ jqXHR.setRequestHeader('X-AN-Version', window.AN_VERSION );
}
},
@@ -889,8 +889,8 @@ function asyncRedirect( $target, $mode, url ) {
url: url,
beforeSend: function (jqXHR, settings) {
- if ( typeof AN_VERSION !== 'undefined' ) {
- jqXHR.setRequestHeader('X-AN-Version', AN_VERSION );
+ if ( typeof window.AN_VERSION !== 'undefined' ) {
+ jqXHR.setRequestHeader('X-AN-Version', window.AN_VERSION );
}
},
success: function(data, status, xhr) {
diff --git a/src/hi/static/js/attr.js b/src/hi/static/js/attr.js
index 3c4985ec..d71e3333 100644
--- a/src/hi/static/js/attr.js
+++ b/src/hi/static/js/attr.js
@@ -290,7 +290,7 @@
// Handle redirects first - if redirect is present, do it immediately
if (data.redirect) {
- console.log('Form response contains redirect, navigating to:', data.redirect);
+ if ( Hi.DEBUG ) { console.log('Form response contains redirect, navigating to:', data.redirect); }
window.location.href = data.redirect;
return;
}
diff --git a/src/hi/static/js/audio.js b/src/hi/static/js/audio.js
index 419dd099..c8e65133 100644
--- a/src/hi/static/js/audio.js
+++ b/src/hi/static/js/audio.js
@@ -516,7 +516,7 @@
} else {
buttonState = AudioButtonState.ENABLED;
}
- console.log(`Button showing: ${buttonState} (permission: ${permissionState}, user: ${userSetting}, baseline: ${baselineAudioState}, current: ${currentAudioState}, status: ${changeStatus})`);
+ if ( Hi.DEBUG ) { console.log(`Button showing: ${buttonState} (permission: ${permissionState}, user: ${userSetting}, baseline: ${baselineAudioState}, current: ${currentAudioState}, status: ${changeStatus})`); }
}
} catch (error) {
@@ -593,16 +593,18 @@
/*
DIAGNOSTIC BACKGROUND AUDIO TESTING
- - Controlled by Hi.DEBUG_AUDIO flag
- Plays sound every 10 seconds to test autoplay capability
- Useful for verifying baseline state detection
*/
+
+ // Moule level tracing (w/overall DEBUG safety check)
+ const TRACE_AUDIO = false && window.Hi?.Config?.DEBUG;
let diagnosticAudioTimer = null;
let diagnosticCounter = 0;
function _startDiagnosticAudio() {
- if (!Hi.DEBUG_AUDIO) return;
+ if ( ! TRACE_AUDIO ) return;
if (Hi.DEBUG) { console.log('πŸ”Š Starting diagnostic background audio (every 10 seconds)'); }
diff --git a/src/hi/static/js/edit-dragdrop.js b/src/hi/static/js/edit-dragdrop.js
index e88fe43b..2ac29f56 100644
--- a/src/hi/static/js/edit-dragdrop.js
+++ b/src/hi/static/js/edit-dragdrop.js
@@ -28,23 +28,23 @@
$(document).ready(function() {
$(DRAGGABLE_SELECTOR).on('dragstart', function(event) {
- if ( gHiViewMode != 'edit' ) { return; }
+ if ( !Hi.isEditMode ) { return; }
handleDragStart( event );
});
$(DRAGGABLE_SELECTOR).on('dragend', function(event) {
- if ( gHiViewMode != 'edit' ) { return; }
+ if ( !Hi.isEditMode ) { return; }
handleDragEnd( event );
});
$(DRAGGABLE_SELECTOR).on('dragover', function(event) {
- if ( gHiViewMode != 'edit' ) { return; }
+ if ( !Hi.isEditMode ) { return; }
handleDragOver( event );
});
$(DRAGGABLE_SELECTOR).on('dragenter', function(event) {
- if ( gHiViewMode != 'edit' ) { return; }
+ if ( !Hi.isEditMode ) { return; }
handleDragEnter( event );
});
$(DRAGGABLE_SELECTOR).on('dragleave', function(event) {
- if ( gHiViewMode != 'edit' ) { return; }
+ if ( !Hi.isEditMode ) { return; }
handleDragLeave( event );
});
});
@@ -57,7 +57,7 @@
// Hide the dragged element during the drag operation for better visuals
setTimeout(() => {
$(gDraggedElement).hide();
- console.log('Hidden class added');
+ if ( Hi.DEBUG ) { console.log('Hidden class added'); }
}, 0);
}
diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.js
index c3fed6b4..51f943e2 100644
--- a/src/hi/static/js/main.js
+++ b/src/hi/static/js/main.js
@@ -2,9 +2,16 @@
const Hi = {
- DEBUG: true,
- DEBUG_AUDIO: false, // Enable diagnostic background audio testing
- isEditMode: ( gHiViewMode == 'edit' ), // Set by server to keep front-end in sync with back-end
+ // HiClientConfig comes from server-side template injection. This module
+ // (main.css) should be the only Javaacript that knows about
+ // HiClientConfig and the coordination mechanism with those
+ // server-delivered config settings. All other JS modules should
+ // look to this module to relay any needed config settings (via
+ // variable below).
+ //
+ DEBUG: window.HiClientConfig?.DEBUG ?? false,
+ isEditMode: window.HiClientConfig?.IS_EDIT_MODE ?? false,
+
MAIN_AREA_SELECTOR: '#hi-main-content',
LOCATION_VIEW_AREA_SELECTOR: '#hi-location-view-main',
LOCATION_VIEW_SVG_CLASS: 'hi-location-view-svg',
@@ -221,7 +228,7 @@
}
return null;
}
-
+
function _getRotationAngle( centerX, centerY, startX, startY, endX, endY ) {
const startVectorX = startX - centerX;
@@ -309,5 +316,5 @@
${rectStr}`) ;
}
-
+
})();
diff --git a/src/hi/static/js/status.js b/src/hi/static/js/status.js
index 9b9cf486..05b74a36 100644
--- a/src/hi/static/js/status.js
+++ b/src/hi/static/js/status.js
@@ -172,13 +172,18 @@
console.log('Alert Status Data: ', JSON.stringify(alertStatusData) );
}
+ // Clear audio if no alert data at all
if ( ! alertStatusData ) {
Hi.audio.clearAudibleSignal();
return;
}
- if (( MaxAudioSignalNameAttr in alertStatusData )
- && ( alertStatusData[MaxAudioSignalNameAttr] )) {
+ // Clear audio if no active signal (when alerts are acknowledged)
+ // Check both existence and value for safety
+ if ( ! (MaxAudioSignalNameAttr in alertStatusData)
+ || ! alertStatusData[MaxAudioSignalNameAttr] ) {
+ Hi.audio.clearAudibleSignal();
+ } else {
Hi.audio.setActiveSignalName( alertStatusData[MaxAudioSignalNameAttr] );
}
diff --git a/src/hi/static/js/svg-icon.js b/src/hi/static/js/svg-icon.js
index fb9a8158..ab395de5 100644
--- a/src/hi/static/js/svg-icon.js
+++ b/src/hi/static/js/svg-icon.js
@@ -283,7 +283,7 @@
const isSvgIcon = ( svgDataType == Hi.DATA_TYPE_ICON_VALUE );
const svgItemId = enclosingSvgGroup.attr('id');
if ( isSvgIcon && svgItemId ) {
- console.log( `Click [${MODULE_NAME}]`, event );
+ if ( Hi.DEBUG ) { console.log( `Click [${MODULE_NAME}]`, event ); }
if ( Hi.DEBUG ) { console.log( 'SVG Target Element', enclosingSvgGroup ); }
handleSvgIconClick( event, enclosingSvgGroup );
return true;
@@ -482,7 +482,7 @@
if ( e.deltaY > 0 ) {
scaleMultiplier = 1.0 - ( MOUSE_WHEEL_ZOOM_SCALE_FACTOR_PERCENT / 100.0 );
}
- console.log( `Scale multiplier = ${scaleMultiplier} [${gSvgIconActionEditData.isScaling}]` );
+ if ( Hi.DEBUG ) { console.log( `Scale multiplier = ${scaleMultiplier} [${gSvgIconActionEditData.isScaling}]` ); }
updateScale( gSvgIconActionEditData.element, scaleMultiplier );
saveIconSvgPositionDebouncer( gSelectedIconSvgGroup );
}
diff --git a/src/hi/static/js/svg-path.js b/src/hi/static/js/svg-path.js
index 10aac1c7..8f89f6df 100644
--- a/src/hi/static/js/svg-path.js
+++ b/src/hi/static/js/svg-path.js
@@ -220,7 +220,7 @@
function clearSelectedPathSvgGroup() {
if ( gSelectedPathSvgGroup ) {
- console.log('Clearing svg path selection');
+ if ( Hi.DEBUG ) { console.log('Clearing svg path selection'); }
collapseSvgPath( );
gSelectedPathSvgGroup = null;
}
@@ -373,7 +373,7 @@
function extendProxyPath( event ) {
- console.log( 'Extending proxy path' );
+ if ( Hi.DEBUG ) { console.log( 'Extending proxy path' ); }
const baseSvgElement = $(Hi.BASE_SVG_SELECTOR);
const svgViewBox = Hi.svgUtils.getSvgViewBox( baseSvgElement );
let svgPoint = Hi.svgUtils.toSvgPoint( baseSvgElement, event.clientX, event.clientY );
@@ -406,7 +406,7 @@
} else if ( $(referenceElement).hasClass( PROXY_LINE_CLASS ) ) {
newProxyPoint = insertNewProxyPoint( svgPoint, referenceElement );
} else {
- console.log( 'Unrecognized reference proxy element.' );
+ if ( Hi.DEBUG ) { console.log( 'Unrecognized reference proxy element.' ); }
return;
}
@@ -710,7 +710,7 @@
addProxyPointEventHandler( bottomLeftProxyPoint, bottomProxyLine, leftProxyLine );
} else {
- console.log( `Unknown proxy path type: ${proxyPathType}` );
+ if ( Hi.DEBUG ) { console.log( `Unknown proxy path type: ${proxyPathType}` ); }
}
saveSvgPath();
}
@@ -911,7 +911,7 @@
});
- console.log( `PATH = ${pathString}` );
+ if ( Hi.DEBUG ) { console.log( `PATH = ${pathString}` ); }
return pathString;
}
diff --git a/src/hi/templates/pages/base.html b/src/hi/templates/pages/base.html
index 3664d3a4..7ac77148 100644
--- a/src/hi/templates/pages/base.html
+++ b/src/hi/templates/pages/base.html
@@ -19,8 +19,8 @@
</head>
<body>
<script>
- const AN_VERSION = "{{ AN_VERSION }}";
- const gHiViewMode = "{{ request.view_parameters.view_mode }}";
+ window.HiClientConfig = {{ hi_client_config.to_json_dict|safe }};
+ window.AN_VERSION = window.HiClientConfig.VERSION;
</script>
{% javascript 'js_before_content' %}
{% block header_post_javascript %}{% endblock %}
diff --git a/src/hi/testing/base_test_case.py b/src/hi/testing/base_test_case.py
index cf7d92aa..8ae6df84 100644
--- a/src/hi/testing/base_test_case.py
+++ b/src/hi/testing/base_test_case.py
@@ -4,10 +4,11 @@ from typing import Dict
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import User as UserType
-
-from django.test import TestCase
+from django.test import TestCase, RequestFactory
import hi.apps.common.datetimeproxy as datetimeproxy
+from hi.view_parameters import ViewParameters
+from hi.enums import ViewMode, ViewType
class BaseTestCase(TestCase):
@@ -31,6 +32,64 @@ class BaseTestCase(TestCase):
}
return
+ def create_hi_request(self, method='GET', path='/test/', data=None, files=None,
+ view_mode: ViewMode = None, view_type: ViewType = None,
+ location_view_id: int = None, collection_id: int = None):
+ """
+ Create a properly configured test request with view_parameters attached.
+
+ This simulates what ViewMiddleware does in real requests, ensuring that
+ context processors and views have access to view_parameters.
+
+ Args:
+ method: HTTP method ('GET', 'POST', etc.)
+ path: Request path
+ data: POST/GET data dictionary
+ files: Files dictionary for file uploads (POST only)
+ view_mode: ViewMode enum (defaults to ViewMode.default())
+ view_type: ViewType enum (defaults to ViewType.default())
+ location_view_id: Optional location view ID
+ collection_id: Optional collection ID
+
+ Returns:
+ HttpRequest with view_parameters properly attached
+ """
+ # Create request using Django's RequestFactory for realism
+ factory = RequestFactory()
+
+ if method.upper() == 'GET':
+ request = factory.get(path, data or {})
+ elif method.upper() == 'POST':
+ if files:
+ # When files are present, pass both data and files to POST
+ request = factory.post(path, data=data or {}, files=files)
+ else:
+ request = factory.post(path, data or {})
+ elif method.upper() == 'PUT':
+ request = factory.put(path, data or {})
+ elif method.upper() == 'DELETE':
+ request = factory.delete(path, data or {})
+ else:
+ request = factory.generic(method.upper(), path, data or {})
+
+ # Set up session with view parameter data
+ session = MockSession()
+ if view_mode:
+ session['view_mode'] = view_mode.name
+ if view_type:
+ session['view_type'] = view_type.name
+ if location_view_id:
+ session['location_view_id'] = str(location_view_id)
+ if collection_id:
+ session['collection_id'] = str(collection_id)
+
+ request.session = session
+
+ # CRUCIAL: Simulate what ViewMiddleware does - attach view_parameters
+ request.view_parameters = ViewParameters.from_session(request)
+
+ return request
+
@dataclass
class MockSession(dict):
diff --git a/src/hi/units.py b/src/hi/units.py
index 49b216a6..e48d01cb 100644
--- a/src/hi/units.py
+++ b/src/hi/units.py
@@ -51,7 +51,6 @@ DisplayUnitsConversionMaps = {
def get_display_quantity( quantity : UnitQuantity, display_units : DisplayUnits ):
- global DisplayUnitsConversionMaps
assert isinstance( quantity, UnitQuantity )
conversion_map = DisplayUnitsConversionMaps.get( display_units, IMPERIAL_TO_METRIC_UNITS )
diff --git a/src/hi/urls.py b/src/hi/urls.py
index c2ac4ca9..e086e0da 100644
--- a/src/hi/urls.py
+++ b/src/hi/urls.py
@@ -28,6 +28,7 @@ urlpatterns = [
re_path( r'^start$', views.StartView.as_view(), name='start' ),
re_path( r'^health$', views.HealthView.as_view(), name='health' ),
+ re_path( r'^env/', include('hi.environment.urls' )),
re_path( r'^user/', include('hi.apps.user.urls' )),
re_path( r'^api/', include('hi.apps.api.urls' )),
re_path( r'^config/', include('hi.apps.config.urls' )),
diff --git a/update.sh b/update.sh
new file mode 100755
index 00000000..1fa58c91
--- /dev/null
+++ b/update.sh
@@ -0,0 +1,158 @@
+#!/bin/bash
+set -e # Exit on any error
+
+# Home Information - Update Script
+# Updates an existing Home Information installation to the latest version
+# Requires: Docker and existing installation
+
+# Configuration
+DOCKER_IMAGE="ghcr.io/cassandra/home-information"
+DOCKER_TAG="${1:-latest}" # Allow override for testing (default: latest)
+CONTAINER_NAME="hi"
+EXTERNAL_PORT="9411"
+HI_HOME="${HOME}/.hi"
+ENV_FILE="${HI_HOME}/env/local.env"
+DATABASE_DIR="${HI_HOME}/database"
+MEDIA_DIR="${HI_HOME}/media"
+
+# Colors for output
+GREEN='\033[0;32m'
+BLUE='\033[0;34m'
+YELLOW='\033[1;33m'
+RED='\033[0;31m'
+NC='\033[0m' # No Color
+
+print_header() {
+ echo -e "${BLUE}================================${NC}"
+ echo -e "${BLUE} Home Information Updater${NC}"
+ echo -e "${BLUE}================================${NC}"
+}
+
+print_success() {
+ echo -e "${GREEN}βœ“ $1${NC}"
+}
+
+print_info() {
+ echo -e "${BLUE}β€’ $1${NC}"
+}
+
+print_warning() {
+ echo -e "${YELLOW}⚠ $1${NC}"
+}
+
+print_error() {
+ echo -e "${RED}βœ— $1${NC}"
+ exit 1
+}
+
+# Check prerequisites
+check_prerequisites() {
+ print_info "Checking prerequisites..."
+
+ # Check Docker
+ if ! command -v docker &> /dev/null; then
+ print_error "Docker is not installed. Please install Docker first."
+ fi
+
+ if ! docker info &> /dev/null; then
+ print_error "Docker is not running. Please start Docker and try again."
+ fi
+
+ # Check existing installation
+ if [[ ! -f "${ENV_FILE}" ]]; then
+ print_error "No existing installation found. Please run install.sh first."
+ fi
+
+ print_success "Prerequisites verified"
+}
+
+# Pull latest Docker image
+pull_latest_image() {
+ print_info "Pulling latest Docker image..."
+
+ if docker pull "${DOCKER_IMAGE}:${DOCKER_TAG}"; then
+ print_success "Latest image pulled successfully"
+ else
+ print_error "Failed to pull latest image. Please check your internet connection."
+ fi
+}
+
+# Stop and remove old container
+stop_old_container() {
+ if docker ps --format 'table {{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
+ print_info "Stopping current container..."
+ docker stop "${CONTAINER_NAME}"
+ print_success "Container stopped"
+ fi
+
+ if docker ps -a --format 'table {{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
+ print_info "Removing old container..."
+ docker rm "${CONTAINER_NAME}"
+ print_success "Old container removed"
+ fi
+}
+
+# Start new container with latest image
+start_new_container() {
+ print_info "Starting updated container..."
+
+ docker run -d \
+ --name "${CONTAINER_NAME}" \
+ --restart unless-stopped \
+ --env-file "${ENV_FILE}" \
+ -v "${DATABASE_DIR}:/data/database" \
+ -v "${MEDIA_DIR}:/data/media" \
+ -p "${EXTERNAL_PORT}:8000" \
+ "${DOCKER_IMAGE}:${DOCKER_TAG}"
+
+ print_success "Updated container started"
+}
+
+# Wait for application to be ready
+wait_for_app() {
+ print_info "Waiting for application to start..."
+
+ # Wait up to 30 seconds for the app to be ready
+ for i in {1..30}; do
+ if curl -s "http://localhost:${EXTERNAL_PORT}" > /dev/null 2>&1; then
+ print_success "Application is ready!"
+ return 0
+ fi
+ sleep 1
+ done
+
+ print_warning "Application may still be starting. Check 'docker logs hi' for details."
+}
+
+# Display success message
+show_success() {
+ echo
+ echo -e "${GREEN}================================${NC}"
+ echo -e "${GREEN} Update Complete!${NC}"
+ echo -e "${GREEN}================================${NC}"
+ echo
+ echo -e "${BLUE}🌐 Access your updated Home Information system:${NC}"
+ echo -e " ${BLUE}http://localhost:${EXTERNAL_PORT}${NC}"
+ echo
+ echo -e "${BLUE}πŸ“Š Status check:${NC}"
+ echo -e " View logs: docker logs hi"
+ echo -e " Container status: docker ps"
+ echo
+ echo -e "${GREEN}Your data and settings have been preserved.${NC}"
+ echo
+}
+
+# Main update function
+main() {
+ print_header
+
+ check_prerequisites
+ pull_latest_image
+ stop_old_container
+ start_new_container
+ wait_for_app
+ show_success
+}
+
+# Run main function
+main "$@"
\ No newline at end of file