# Gemini Code Assistant Context This document provides a comprehensive overview of the **Location Tracker** project, designed to give the Gemini code assistant the necessary context to understand the codebase, its architecture, and its conventions. ## 1. Project Overview This is a full-stack web application for real-time location tracking, built with Next.js 14. Its primary purpose is to receive location data from [OwnTracks](https://owntracks.org/) mobile clients via an MQTT broker and display the tracks on an interactive map. ### Key Technologies - **Framework**: Next.js 14 (App Router) - **Language**: TypeScript - **Database**: Dual SQLite databases using `better-sqlite3`. - `data/database.sqlite`: For core application data like users, devices, and settings. - `data/locations.sqlite`: For high-volume, time-series location data. - **Data Ingestion**: An MQTT subscriber (`lib/mqtt-subscriber.ts`) connects to a Mosquitto broker to receive location updates from OwnTracks clients. An HTTP endpoint (`/api/locations/ingest`) is also available for manual data pushes. - **Authentication**: `next-auth` (v5) with a credentials (username/password) provider. It supports `ADMIN` and `VIEWER` roles. - **Frontend**: React, [React Leaflet](https://react-leaflet.js.org/) for mapping, and Tailwind CSS for styling. - **Deployment**: The project includes a `Dockerfile` and `docker-compose.yml` for containerized deployment alongside a Mosquitto MQTT broker. ### Core Features - Interactive map displaying real-time location data. - Filtering by device and time range. - Admin dashboard for user and device management. - Secure authentication with role-based access control. - Database maintenance tasks (cleanup, optimization) via API or scripts. ## 2. Building and Running the Project ### Prerequisites - Node.js 18+ - npm ### Development Mode 1. **Install dependencies:** ```bash npm install ``` 2. **Initialize the databases:** This command creates the two SQLite databases in the `data/` directory and seeds them with a default admin user (`admin` / `admin123`). ```bash npm run db:init ``` 3. **Run the development server:** This starts the Next.js application on `http://localhost:3000`. It also starts the MQTT subscriber service. ```bash npm run dev ``` ### Production Mode - **Build the application:** ```bash npm run build ``` - **Start the application:** ```bash npm run start ``` ### Docker Compose The most straightforward way to run the application and its dependent MQTT broker is using Docker Compose. 1. **Create an environment file:** Copy `.env.example` to `.env` and fill in the required secrets, especially `AUTH_SECRET`. 2. **Start the services:** ```bash docker-compose up --build ``` This will build the Next.js app image and start both the application container and the Mosquitto container. The `data` directory is mounted as a volume to persist the SQLite databases. ## 3. Architecture and Data Flow The application follows a clean, decoupled architecture. **Data Ingestion Flow:** 1. An OwnTracks client publishes a location update to a specific MQTT topic (e.g., `owntracks/device_12_4397af93/12` where `device_12_4397af93` is the MQTT username). 2. The Mosquitto broker receives the message. 3. The Next.js application's MQTT Subscriber (`lib/mqtt-subscriber.ts`), which is started on server boot via `instrumentation.ts`, is subscribed to the `owntracks/+/+` topic with admin credentials. 4. Upon receiving a message, the subscriber parses the payload, transforms it into the application's `Location` format, and saves it to `data/locations.sqlite` using the functions in `lib/db.ts`. **Data Retrieval Flow:** 1. The user's browser, viewing the map page, periodically fetches data from the `/api/locations` endpoint. 2. This API route queries the `data/locations.sqlite` database, applying any user-specified filters for device or time. 3. The API returns the location data as a JSON response. 4. The frontend `MapView.tsx` component renders the received data as markers and polylines on the Leaflet map. **Authentication & Authorization:** - Users log in via the `/login` page, which uses the NextAuth.js `Credentials` provider. - The `lib/auth.ts` file contains the NextAuth configuration, validating credentials against the `User` table in `data/database.sqlite`. - The `middleware.ts` file protects the `/admin` and `/map` routes, checking for a valid session and enforcing role-based access (`ADMIN` vs. `VIEWER`). ## 4. Development Conventions - **Database Access**: All direct database operations are encapsulated within the `lib/db.ts` file. This provides a single, consistent interface (`userDb`, `deviceDb`, `locationDb`) for interacting with the data layer. - **Authentication**: All authentication and session logic is centralized in `lib/auth.ts`. The `auth()` object exported from this file is the primary entry point for accessing session data on the server. - **Background Services**: Long-running background services, like the MQTT subscriber, should be initialized in `lib/startup.ts` and triggered from the `instrumentation.ts` file. This is the standard Next.js way to run code on server startup. - **Configuration**: Environment variables are used for configuration (see `.env.example`). - **Scripts**: The `scripts/` directory contains Node.js scripts for various administrative tasks, such as database initialization (`init-database.js`), cleanup (`cleanup-old-locations.js`), and testing. They should be run using `node scripts/.js`. - **Styling**: Utility-first CSS using Tailwind CSS. - **Types**: TypeScript types are used throughout. Core application types are defined in files like `lib/db.ts` and `types/location.ts`.