diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..78131a9f40bb778f88c3649d5175e5ea7f0524ee --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +web/public/HttpSms.apk filter=lfs diff=lfs merge=lfs -text +web/public/*.png filter=lfs diff=lfs merge=lfs -text +web/public/img/**/*.png filter=lfs diff=lfs merge=lfs -text diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..6893dc38e3f19cb401533a98f163cc7e45060410 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Require review/approval for any changes to GitHub Actions workflows +/.github/workflows/ @AchoArnold diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..b4110688de7d2cf4ee042afa19bf1028a55435ea --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: [NdoleStudio] diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..d1a887310c8e6ba7fb4dfdcaba99c8d73475dbd2 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,146 @@ +# Copilot Instructions for httpSMS + +httpSMS is a service that turns an Android phone into an SMS gateway via an HTTP API. This is a monorepo with three components: + +- **`api/`** — Go backend (Fiber, GORM, PostgreSQL) +- **`web/`** — Nuxt 2 frontend (Vue 2, Vuetify 2, TypeScript) +- **`android/`** — Native Android app (Kotlin) + +## Build, Test, and Lint Commands + +### API (Go) + +```bash +cd api + +# Development with hot-reload +air + +# Build +go build -o ./tmp/main.exe . + +# Run tests +go test ./... + +# Run a single test +go test ./pkg/services/ -run TestMessageService + +# Generate Swagger docs (required after changing API annotations) +swag init --requiredByDefault --parseDependency --parseInternal + +# Pre-commit hooks run: go-fumpt, go-imports, go-lint, go-mod-tidy +``` + +### Web (Nuxt/Vue) + +```bash +cd web + +# Install dependencies +pnpm install + +# Development server (port 3000) +pnpm dev + +# Lint (eslint + stylelint + prettier) +pnpm lint + +# Auto-fix lint issues +pnpm lintfix + +# Run tests (Jest) +pnpm test + +# Static site generation (production build) +pnpm run generate + +# Regenerate TypeScript API models from Swagger +pnpm api:models +``` + +### Android (Kotlin) + +```bash +cd android + +# Build +./gradlew build + +# Debug APK +./gradlew assembleDebug + +# Release APK +./gradlew assembleRelease +``` + +### Docker (full stack) + +```bash +# Start all services (PostgreSQL, Redis, API, Web) +docker compose up --build +# API at localhost:8000, Web at localhost:3000 +``` + +## Architecture + +### API — Layered Architecture with Event-Driven Processing + +The API uses a **DI container** (`pkg/di/container.go`) that lazily initializes all services as singletons. The layered architecture flows as: + +**Handlers → Services → Repositories → GORM/PostgreSQL** + +- **Handlers** (`pkg/handlers/`) — Fiber HTTP handlers. Each has a `RegisterRoutes()` method and embeds a base `handler` struct with standardized response methods (`responseBadRequest`, `responseNotFound`, etc.). +- **Services** (`pkg/services/`) — Business logic. Orchestrate repositories and dispatch events. +- **Repositories** (`pkg/repositories/`) — Data access via GORM. Interfaces defined alongside GORM implementations (prefixed `gorm*`). +- **Validators** (`pkg/validators/`) — One validator per handler, return `url.Values` for field errors. +- **Entities** (`pkg/entities/`) — Domain models, auto-migrated by GORM. + +**Event system**: Uses CloudEvents spec (`cloudevents/sdk-go`). Events defined in `pkg/events/` (31 event types). Listeners in `pkg/listeners/` process events either synchronously or via Google Cloud Tasks queue (emulator mode for local dev). + +**Entry point**: `main.go` loads `.env` in local mode, creates the DI container, and starts Fiber on `APP_PORT`. + +### Web — Nuxt 2 Static SPA + +- **State management**: Single Vuex store (`store/index.ts`) — actions make API calls via Axios, mutations update state, getters expose computed values. +- **Components**: Use `vue-property-decorator` class syntax with `@Component`, `@Prop`, `@Watch` decorators. +- **API client**: Axios configured in `plugins/axios.ts` with Firebase bearer token auth and `x-api-key` header support. +- **API models**: TypeScript types in `models/` are auto-generated from the Swagger spec via `swagger-typescript-api`. +- **Auth**: Firebase Authentication (Email/Password, Google, GitHub) with `auth` and `guest` middleware for route guards. +- **Real-time**: Pusher.js for live message updates. + +### Android — Task-Oriented, Event-Driven + +- **No MVVM/Clean Architecture** — uses a flat package structure with Activities, Services, BroadcastReceivers, and WorkManager tasks. +- **FCM integration**: `MyFirebaseMessagingService` receives push notifications → schedules `SendSmsWorker` via WorkManager → fetches message from API → sends SMS. +- **Dual SIM support**: Independent settings per SIM via `Settings` singleton (SharedPreferences). +- **HTTP client**: OkHttp with `x-api-key` authentication against the API. +- **Encryption**: AES-256/CFB with SHA-256 key derivation (`Encrypter.kt`). + +## Documentation & PR Workflow + +- **Superpowers docs (`docs/superpowers/`) are never committed to git** — the directory is gitignored. Do not remove it from `.gitignore` or add its files with `git add -f`. +- When a change is driven by a superpowers SPEC, include a **summarized version of the SPEC in the PR description** (goal, key decisions, scope) instead of the full doc, so reviewers/agents can understand the change without needing the uncommitted file. + +## Key Conventions + +### API (Go) + +- **Error handling**: Use `github.com/palantir/stacktrace` — wrap errors with `stacktrace.Propagate(err, "context")` or `stacktrace.PropagateWithCode()`. Never return bare errors. +- **Database queries**: Always use GORM query builder with context propagation (`repository.db.WithContext(ctx)`). No raw SQL. +- **Route registration**: Each handler defines `RegisterRoutes()` called from the DI container. Routes follow REST conventions under `/v1/`. +- **Middleware chain**: HTTP Logger → OpenTelemetry → CORS → Request Logger → Bearer Auth → API Key Auth. +- **Observability**: All layers are instrumented with OpenTelemetry (Fiber, GORM, Redis). Pass `logger` and `tracer` to constructors. +- **Code formatting**: `go-fumpt` (not `gofmt`), enforced via pre-commit hooks. + +### Web (Vue/TypeScript) + +- **Formatting**: No semicolons, single quotes, 2-space indentation (Prettier + ESLint). +- **Component style**: Class-based with `vue-property-decorator`, not Options API (though some pages use `Vue.extend()`). +- **Store pattern**: Actions handle async API calls and commit mutations. Access store from components via `this.$store`. + +### Android (Kotlin) + +- **API calls**: Use `HttpSmsApiService` singleton (static `create()` factory). OkHttp client with `x-api-key` header. +- **Background work**: Use WorkManager for tasks that must survive process death. Direct `Thread { }` for lightweight background ops. +- **State**: `Settings` object (SharedPreferences singleton) for all persistent state. +- **Phone number formatting**: Use `libphonenumber` for E.164 format validation. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..26bbbb041545384f4d3296b3d4b60ccca9862187 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,51 @@ +version: 2 +updates: + # Fetch and update latest `npm` packages + - package-ecosystem: npm + directory: "/web" + schedule: + interval: monthly + time: "00:00" + # Keep version updates beyond pnpm's 24-hour release-age guard. + # Security updates bypass cooldown; transitive resolution also needs the workspace gate. + cooldown: + default-days: 3 + open-pull-requests-limit: 10 + reviewers: + - AchoArnold + assignees: + - AchoArnold + commit-message: + prefix: fix + prefix-development: chore + include: scope + # Fetch and update latest `github-actions` pkgs + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: monthly + time: "00:00" + open-pull-requests-limit: 10 + reviewers: + - AchoArnold + assignees: + - AchoArnold + commit-message: + prefix: fix + prefix-development: chore + include: scope + # Fetch and update latest `go` packages + - package-ecosystem: gomod + directory: "/api" + schedule: + interval: monthly + time: "00:00" + open-pull-requests-limit: 10 + reviewers: + - AchoArnold + assignees: + - AchoArnold + commit-message: + prefix: fix + prefix-development: chore + include: scope diff --git a/.github/ghbadge.png b/.github/ghbadge.png new file mode 100644 index 0000000000000000000000000000000000000000..326d25476dea62db86752291368cc2b9da095e68 Binary files /dev/null and b/.github/ghbadge.png differ diff --git a/.github/workflows/api.yml b/.github/workflows/api.yml new file mode 100644 index 0000000000000000000000000000000000000000..7d3a8a4eabf5b2015636e18fb69d80fcc69bfe7a --- /dev/null +++ b/.github/workflows/api.yml @@ -0,0 +1,135 @@ +name: api + +on: + push: + branches: + - main + pull_request: + branches: + - main + +permissions: + contents: read + id-token: write + +jobs: + test: + name: Integration Tests + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Set up Go + uses: actions/setup-go@v7 + with: + go-version: stable + + - name: Generate Firebase credentials + run: | + bash tests/generate-firebase-credentials.sh tests/firebase-credentials.json + echo "FIREBASE_CREDENTIALS=$(jq -c . tests/firebase-credentials.json)" >> $GITHUB_ENV + + - name: Generate adapter certificates + run: bash tests/generate-adapter-certificates.sh tests/certs + + - name: Start Services + working-directory: ./tests + run: docker compose up -d --build + + - name: Wait for services to be healthy + working-directory: ./tests + run: | + echo "Waiting for MongoDB to be healthy..." + for i in $(seq 1 20); do + if docker compose exec mongodb mongosh --eval "db.runCommand('ping').ok" --quiet >/dev/null 2>&1; then + echo "MongoDB is healthy!" + break + fi + if [ $i -eq 20 ]; then + echo "MongoDB failed to become healthy" + docker compose logs mongodb + exit 1 + fi + echo "MongoDB attempt $i/20 - waiting 3s..." + sleep 3 + done + + echo "Waiting for API to be healthy..." + for i in $(seq 1 40); do + if docker compose exec api curl -sf http://localhost:8000/health >/dev/null 2>&1; then + echo "API is healthy!" + break + fi + if [ $i -eq 40 ]; then + echo "API failed to become healthy" + docker compose logs api + exit 1 + fi + echo "Attempt $i/40 - waiting 5s..." + sleep 5 + done + + - name: Seed Database + working-directory: ./tests + run: | + echo "Waiting for seed container to finish..." + docker compose wait seed || true + sleep 2 + + - name: Run Handler Integration Tests + working-directory: ./api + env: + USER_API_KEY: test-user-api-key + run: go test -tags integration -v -timeout 60s ./pkg/handlers + + - name: Run Integration Tests + working-directory: ./tests + run: go test -v -timeout 300s ./... + + - name: Collect Logs on Failure + if: failure() + working-directory: ./tests + run: | + docker compose logs --tail 200 + + - name: Stop Services + if: always() + working-directory: ./tests + run: docker compose down -v + + deploy: + name: Deploy + runs-on: ubuntu-latest + needs: test + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + steps: + - name: Authenticate to Google Cloud + uses: google-github-actions/auth@v3 + with: + workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }} + service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }} + + - name: Set up Cloud SDK + uses: google-github-actions/setup-gcloud@v3 + + - name: Trigger Cloud Build Deploy + run: | + BUILD_ID=$(gcloud builds triggers run api-httpsms-com \ + --region=global \ + --project=httpsms-86c51 \ + --sha=${{ github.sha }} \ + --format="value(metadata.build.id)") + echo -e "Cloud Build: \033[34mhttps://console.cloud.google.com/cloud-build/builds/$BUILD_ID?project=httpsms-86c51\033[0m" + echo "" + echo "Polling Cloud Build Status..." + while true; do + STATUS=$(gcloud builds describe "$BUILD_ID" --region=global --project=httpsms-86c51 --format="value(status)") + LOCAL_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC') + echo -e " \033[90m${LOCAL_TIME}\033[0m status=\033[36m${STATUS}\033[0m" + case "$STATUS" in + SUCCESS) echo -e "\033[32mBuild succeeded!\033[0m"; exit 0 ;; + FAILURE|TIMEOUT|CANCELLED|EXPIRED|INTERNAL_ERROR) echo -e "\033[31mBuild failed with status: $STATUS\033[0m"; exit 1 ;; + esac + sleep 30 + done diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml new file mode 100644 index 0000000000000000000000000000000000000000..50813d1534f0d3586e0df2c7afd7c1432feb555b --- /dev/null +++ b/.github/workflows/web.yml @@ -0,0 +1,92 @@ +name: web + +on: + push: + branches: + - main + pull_request: + branches: + - main + +permissions: + contents: read + pull-requests: write + deployments: write + +defaults: + run: + working-directory: ./web + +jobs: + validate: + name: Validate + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ubuntu-latest] + node: [24] + + steps: + - name: Checkout 🛎 + uses: actions/checkout@master + + - uses: pnpm/action-setup@v6 + name: Install pnpm + with: + version: 11.11.0 + + - name: Install dependencies 📦 + run: pnpm install --trust-lockfile + + - name: Run linter 👀 + run: pnpm lint + + - name: Run tests 🧪 + run: pnpm test + + - name: Build 🏗️ + run: mv .env.production .env && echo "GITHUB_SHA=${GITHUB_SHA}" >> .env && pnpm run generate + + deploy: + name: Deploy + needs: validate + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + + steps: + - name: Checkout 🛎 + uses: actions/checkout@master + + - name: Setup Node 🟢 + uses: actions/setup-node@v7 + with: + node-version: '24.18' + + - uses: pnpm/action-setup@v6 + name: Install pnpm + with: + version: 11.11.0 + + - name: Install dependencies 📦 + run: pnpm install --trust-lockfile + + - name: Build 🏗️ + run: mv .env.production .env && echo "GITHUB_SHA=${GITHUB_SHA}" >> .env && pnpm run generate + + - name: Cloudflare Deploy 🚀 + uses: cloudflare/wrangler-action@v4 + with: + apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} + accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + command: pages deploy web/.output/public --project-name=httpsms + gitHubToken: ${{ secrets.GITHUB_TOKEN }} + + - name: Firebase Deploy 🚀 + uses: FirebaseExtended/action-hosting-deploy@500ac625ca2dd40cbd15f7659af953801858032a + with: + repoToken: "${{ secrets.GITHUB_TOKEN }}" + channelId: live + entryPoint: "./web" + firebaseServiceAccount: "${{ secrets.FIREBASE_SERVICE_ACCOUNT_HTTPSMS_86C51 }}" + projectId: httpsms-86c51 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7e92a7f39edd1079007e8f9ecca90b0e0f8c6001 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +.idea +.env* +!.env.docker +!.env.production +*serviceAccountKey.json +android/app/debug/ +*main.exe* +android/app/release/ + +tests/firebase-credentials.json +tests/certs/ +tests/emulator/emulator.exe +SECURITY_AUDIT_REPORT.md + +*.exe + +.output +.agents/ +skills-lock.json +.worktrees/ +docs/superpowers +# --- httpsms HF deployment additions --- +firebase-credentials.json +*.jks +*.keystore diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..d4cd93959e5b118ce6ca101da35dde2adcdd46bf --- /dev/null +++ b/.mcp.json @@ -0,0 +1,9 @@ +{ + "mcpServers": { + "context7": { + "type": "stdio", + "command": "npx", + "args": ["@upstash/context7-mcp@latest"] + } + } +} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8aa228d71093eb075ab476d389a2eb2393714259 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,20 @@ +repos: + - repo: https://github.com/tekwizely/pre-commit-golang + rev: v1.0.0-rc.4 + hooks: + - id: go-fumpt + - id: go-mod-tidy + - id: go-lint + - id: go-imports + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + + - repo: https://github.com/pre-commit/mirrors-prettier + rev: v4.0.0-alpha.8 + hooks: + - id: prettier + exclude: ^web/ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..a538c777a86c3641241e3a6a354e1c89ef45fea9 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,131 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or advances of + any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, + without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at arnold@httpsms.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff0ca4b825d9c26ac7627f0eb02a6af591bb8e09 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,42 @@ +# syntax=docker/dockerfile:1 +# ============================================================ +# Stage 1 — Nuxt 3 static SPA build (web/) +# ============================================================ +FROM node:22-alpine AS web-builder +WORKDIR /build +COPY web/ ./ +RUN npm install -g pnpm@11.11.0 \ + && pnpm install --frozen-lockfile +# web/.env (committed, public build-time config: API_BASE_URL, Firebase web config, Turnstile site key) +RUN pnpm generate +# -> /build/.output/public (static SPA) + +# ============================================================ +# Stage 2 — Go Fiber API build (api/) +# ============================================================ +FROM golang:1.26-alpine AS api-builder +WORKDIR /build +COPY api/ ./ +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "-s -w" -o /httpsms-api . + +# ============================================================ +# Stage 3 — runtime: nginx :7860 + API :8000 + psql seeding +# ============================================================ +FROM alpine:3.20 +RUN apk add --no-cache nginx postgresql postgresql-client redis ca-certificates curl tzdata \ + && adduser -D -u 1000 user \ + && mkdir -p /usr/share/nginx/html /var/log/nginx /var/lib/nginx \ + && chown -R user:user /usr/share/nginx/html /var/log/nginx /var/lib/nginx /etc/nginx /tmp + +COPY --from=web-builder --chown=user:user /build/.output/public/ /usr/share/nginx/html/ +COPY --from=api-builder --chown=user:user /httpsms-api /usr/local/bin/httpsms-api +COPY --chown=user:user nginx.hf.conf /etc/nginx/nginx.conf +COPY --chown=user:user entrypoint.sh /entrypoint.sh + +RUN chmod +x /entrypoint.sh + +USER user +ENV HOME=/home/user +WORKDIR /home/user +EXPOSE 7860 +ENTRYPOINT ["/entrypoint.sh"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0ad25db4bd1d86c452db3f9602ccdbe172438f52 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2512f208e16b321b9c1af2474e5cdd07dd922033 --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +--- +title: httpSMS Bulk Android Gateway +emoji: 📱 +colorFrom: blue +colorTo: indigo +sdk: docker +app_port: 7860 +pinned: false +--- + +[![Built with ML Intern](https://huggingface.co/datasets/huggingface/badges/resolve/main/built-with-ml-intern-sm.svg)](https://hf.co/chat?mode=ml-intern) + +# httpSMS Gateway — self-hosted on Hugging Face Spaces + +Production-hardened, single-origin deployment of the open-source [httpSMS](https://github.com/NdoleStudio/httpsms) Android SMS gateway: Go Fiber REST API + Nuxt 3 web dashboard behind a non-root nginx reverse proxy on a Hugging Face Docker Space. + +- **Live dashboard:** https://red-kit-httpsms-gateway.hf.space +- **REST API base URL:** https://red-kit-httpsms-gateway.hf.space/v1 +- **Android APK (direct download):** https://red-kit-httpsms-gateway.hf.space/HttpSms.apk + +## Bootstrap mode + +If the `DATABASE_URL` / `REDIS_URL` Space secrets are **not** set, `entrypoint.sh` starts ephemeral in-container PostgreSQL and Redis so the gateway is live out of the box. Data resets on restart. Set the two secrets to switch to a managed database (Neon/Supabase/Upstash) — no rebuild needed. + +## Architecture + +- nginx (uid 1000, non-root) listens on `:7860`, proxies `/v1/*` and heartbeat/health routes to the Go Fiber API on `127.0.0.1:8000`, and serves the static Nuxt SPA plus the APK. +- State lives in external managed PostgreSQL and Redis (injected as Space secrets, never committed). +- `entrypoint.sh` starts the API for GORM auto-migration, idempotently seeds the internal CloudEvents queue system user (`ON CONFLICT DO UPDATE`), then supervises the API and runs nginx. +- WebSocket/SSE upgrade headers, `X-Real-IP`, `X-Forwarded-For`, `X-Forwarded-Proto: https` are set by nginx on API routes. + +## Quick start — REST API + +Get your API key from the web dashboard after login, then: + +```bash +export HTTPSMS_API_KEY="" + +# Send a single SMS +curl -X POST https://red-kit-httpsms-gateway.hf.space/v1/messages/send \ + -H "X-API-Key: ${HTTPSMS_API_KEY}" \ + -H "Content-Type: application/json" \ + -d '{"from": "+18005550199", "to": "+18005550100", "content": "Hello from httpSMS"}' + +# Bulk-send to many recipients +curl -X POST https://red-kit-httpsms-gateway.hf.space/v1/messages/bulk-send \ + -H "X-API-Key: ${HTTPSMS_API_KEY}" \ + -H "Content-Type: application/json" \ + -d '{"from": "+18005550199", "to": ["+18005550100", "+18005550101"], "content": "Hello from httpSMS"}' +``` + +Messages are delivered through the connected Android phone running the httpSMS app (install the APK above; its default server URL points at this Space). + +Upstream source: https://github.com/NdoleStudio/httpsms · Docs: https://docs.httpsms.com diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..35c692f8c4804d971c6eb06abf9ce4326e9a90ee --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +## Supported Versions + +As of today, I only support the latest version of httpSMS in the `main` branch of github. Please make sure you stay up-to-date. + +| Version | Supported | +| ------- | ------------------ | +| main | :white_check_mark: | + +## Reporting a Vulnerability + +Please report severe security issues privately via arnold@httpsms.com or by sending me a private message on [Discord](https://discord.gg/kGk8HVqeEZ). diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6c13541ca6f1832b1bfd0543d6532b96c4171ea9 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,16 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +.kotlin/sessions/ +local.properties diff --git a/android/app/.gitignore b/android/app/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..796b96d1c402326528b4ba3c12ee9d92d0e212e9 --- /dev/null +++ b/android/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..f670b8bb7a308ebb037980d5d9f134c1e0bff80a --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,79 @@ +plugins { + id("com.android.application") + id("com.google.gms.google-services") + id("io.sentry.android.gradle") version "6.14.0" + id("org.jetbrains.kotlin.plugin.compose") +} + +val gitHash = providers.exec { + commandLine("git", "rev-parse", "--short", "HEAD") +}.standardOutput.asText.map { it.trim() } + +android { + compileSdk = 37 + + defaultConfig { + applicationId = "com.httpsms" + minSdk = 28 + targetSdk = 37 + versionCode = 1 + versionName = gitHash.getOrElse("unknown") + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + getByName("debug") { + manifestPlaceholders["sentryEnvironment"] = "development" + } + getByName("release") { + manifestPlaceholders["sentryEnvironment"] = "production" + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + namespace = "com.httpsms" + + buildFeatures { + buildConfig = true + compose = true + } +} + +dependencies { + val composeBom = platform("androidx.compose:compose-bom:2026.06.01") + implementation(composeBom) + androidTestImplementation(composeBom) + + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.ui:ui-graphics") + implementation("androidx.compose.ui:ui-tooling-preview") + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.material:material-icons-extended") + implementation("androidx.activity:activity-compose:1.13.0") + implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0") + + implementation(platform("com.google.firebase:firebase-bom:34.16.0")) + implementation("com.journeyapps:zxing-android-embedded:4.3.0") + implementation("com.google.firebase:firebase-analytics") + implementation("com.google.firebase:firebase-messaging") + implementation("com.squareup.okhttp3:okhttp:5.4.0") + implementation("com.jakewharton.timber:timber:5.0.1") + implementation("androidx.preference:preference-ktx:1.2.1") + implementation("androidx.work:work-runtime-ktx:2.11.2") + implementation("androidx.core:core-ktx:1.19.0") + implementation("androidx.cardview:cardview:1.0.0") + implementation("com.beust:klaxon:5.6") + implementation("androidx.appcompat:appcompat:1.7.1") + implementation("org.apache.commons:commons-text:1.15.0") + implementation("com.google.android.material:material:1.14.0") + implementation("androidx.constraintlayout:constraintlayout:2.2.1") + implementation("com.googlecode.libphonenumber:libphonenumber:9.0.34") + implementation("com.klinkerapps:android-smsmms:5.2.6") + testImplementation("junit:junit:4.13.2") + androidTestImplementation("androidx.test.ext:junit:1.3.0") + androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0") +} diff --git a/android/app/google-services.json b/android/app/google-services.json new file mode 100644 index 0000000000000000000000000000000000000000..474790f73ad8c2e99d1f850adf3490f7ead81834 --- /dev/null +++ b/android/app/google-services.json @@ -0,0 +1,29 @@ +{ + "project_info": { + "project_number": "533003867471", + "project_id": "httpsms-66180", + "storage_bucket": "httpsms-66180.firebasestorage.app" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:533003867471:android:36f4e532bc408fe798a13a", + "android_client_info": { + "package_name": "com.httpsms" + } + }, + "oauth_client": [], + "api_key": [ + { + "current_key": "AIzaSyCaqEuBeLoHw7CzVW9cgecAk84JcgpiBKM" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [] + } + } + } + ], + "configuration_version": "1" +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..f1b424510da51fd82143bc74a0a801ae5a1e2fcd --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/android/app/src/androidTest/java/com/httpsms/ExampleInstrumentedTest.kt b/android/app/src/androidTest/java/com/httpsms/ExampleInstrumentedTest.kt new file mode 100644 index 0000000000000000000000000000000000000000..0ac3d882fa48bf3b2ac629c75bda757888551e46 --- /dev/null +++ b/android/app/src/androidTest/java/com/httpsms/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.httpsms + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.httpsms", appContext.packageName) + } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..86ca0a51463a55f3c8c8a13d43cc5747b58f8f2e --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/ic_launcher-playstore.png b/android/app/src/main/ic_launcher-playstore.png new file mode 100644 index 0000000000000000000000000000000000000000..e6dc20cec0a7ba79d6b9b8e7e9ffdae0dcbc13c9 Binary files /dev/null and b/android/app/src/main/ic_launcher-playstore.png differ diff --git a/android/app/src/main/java/com/httpsms/Constants.kt b/android/app/src/main/java/com/httpsms/Constants.kt new file mode 100644 index 0000000000000000000000000000000000000000..ba3e15840156bb57ef6b6f65cde1445f4b4b45d6 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/Constants.kt @@ -0,0 +1,25 @@ +package com.httpsms + +class Constants { + companion object { + const val KEY_MESSAGE_ID = "KEY_MESSAGE_ID" + const val KEY_MESSAGE_FROM = "KEY_MESSAGE_FROM" + const val KEY_MESSAGE_TO = "KEY_MESSAGE_TO" + const val KEY_MESSAGE_SIM = "KEY_MESSAGE_SIM" + const val KEY_MESSAGE_CONTENT = "KEY_MESSAGE_CONTENT" + const val KEY_MESSAGE_TIMESTAMP = "KEY_MESSAGE_TIMESTAMP" + const val KEY_MESSAGE_REASON = "KEY_MESSAGE_REASON" + const val KEY_MESSAGE_ENCRYPTED = "KEY_MESSAGE_ENCRYPTED" + const val KEY_MESSAGE_ATTACHMENTS = "KEY_MESSAGE_ATTACHMENTS" + + + const val KEY_HEARTBEAT_ID = "KEY_HEARTBEAT_ID" + + const val SIM1 = "SIM1" + const val SIM2 = "SIM2" + + const val TIMESTAMP_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'000000'ZZZZZ" + + const val MAX_MMS_ATTACHMENT_SIZE: Long = (3L * 1024 * 1024) / 2 + } +} diff --git a/android/app/src/main/java/com/httpsms/DeliveredReceiver.kt b/android/app/src/main/java/com/httpsms/DeliveredReceiver.kt new file mode 100644 index 0000000000000000000000000000000000000000..5d8ad85b98c1cedd7faf3bc9ac86cb61d4c2b310 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/DeliveredReceiver.kt @@ -0,0 +1,110 @@ +package com.httpsms + +import android.app.Activity +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import androidx.work.Constraints +import androidx.work.Data +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequest +import androidx.work.WorkManager +import androidx.work.Worker +import androidx.work.WorkerParameters +import androidx.work.workDataOf +import timber.log.Timber + + +internal class DeliveredReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + when (resultCode) { + Activity.RESULT_OK -> handleMessageDelivered(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID)) + else -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID)) + } + } + + private fun handleMessageDelivered(context: Context, messageId: String?) { + if (!Receiver.isValid(context, messageId)) { + return + } + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val inputData: Data = workDataOf( + Constants.KEY_MESSAGE_ID to messageId, + Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp() + ) + + val work = OneTimeWorkRequest + .Builder(DeliveredMessageWorker::class.java) + .setConstraints(constraints) + .setInputData(inputData) + .build() + + WorkManager + .getInstance(context) + .enqueue(work) + + Timber.d("work enqueued with ID [${work.id}] for [DELIVERED] message with ID [${messageId}]") + } + + private fun handleMessageFailed(context: Context, messageId: String?) { + if (!Receiver.isValid(context, messageId)) { + return + } + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val inputData: Data = workDataOf( + Constants.KEY_MESSAGE_ID to messageId, + Constants.KEY_MESSAGE_REASON to "CANNOT BE DELIVERED", + Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp() + ) + + val work = OneTimeWorkRequest + .Builder(FailedMessageWorker::class.java) + .setConstraints(constraints) + .setInputData(inputData) + .build() + + WorkManager + .getInstance(context) + .enqueue(work) + + Timber.d("work enqueued with ID [${work.id}] for [FAILED] message with ID [${messageId}]") + } + + + internal class DeliveredMessageWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { + override fun doWork(): Result { + val messageId = this.inputData.getString(Constants.KEY_MESSAGE_ID) + val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP) + + Timber.i("[${timestamp}] sending [DELIVERED] message event with ID [${messageId}]") + + if (HttpSmsApiService.create(applicationContext).sendDeliveredEvent(messageId!!, timestamp!!)){ + return Result.success() + } + return Result.retry() + } + } + + internal class FailedMessageWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { + override fun doWork(): Result { + val messageId = this.inputData.getString(Constants.KEY_MESSAGE_ID) + val reason = this.inputData.getString(Constants.KEY_MESSAGE_REASON) + val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP) + + Timber.i("[${timestamp}] sending [FAILED] message event with ID [${messageId}] and reason [$reason]") + + if (HttpSmsApiService.create(applicationContext).sendFailedEvent(messageId!!, timestamp!!, reason!!)){ + return Result.success() + } + return Result.retry() + } + } +} diff --git a/android/app/src/main/java/com/httpsms/Encrypter.kt b/android/app/src/main/java/com/httpsms/Encrypter.kt new file mode 100644 index 0000000000000000000000000000000000000000..970ea0678490e9506d813480ebc45cd193182856 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/Encrypter.kt @@ -0,0 +1,44 @@ +package com.httpsms + +import timber.log.Timber +import java.security.MessageDigest +import java.util.Base64 +import java.util.Random +import javax.crypto.Cipher +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +object Encrypter { + private const val ALGORITHM = "AES/CFB/NoPadding" + private const val IV_SIZE = 16 + + fun decrypt(key: String, cipherText: String): String { + val cipher = Cipher.getInstance(ALGORITHM) + val cipherBytes = Base64.getDecoder().decode(cipherText) + Timber.d("iv = ${Base64.getEncoder().encodeToString(cipherBytes.take(IV_SIZE).toByteArray())}") + Timber.d("cipher = ${Base64.getEncoder().encodeToString(cipherBytes.drop(IV_SIZE).toByteArray())}") + cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(hash(key), "AES"), IvParameterSpec(cipherBytes.take(IV_SIZE).toByteArray())) + val plainText = cipher.doFinal(cipherBytes.drop(IV_SIZE).toByteArray()) + return String(plainText) + } + + fun encrypt(key: String, inputText: String): String { + val cipher = Cipher.getInstance(ALGORITHM) + val iv = generateIv() + cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(hash(key),"AES"), IvParameterSpec(iv)) + val cipherBytes = iv + cipher.doFinal(inputText.toByteArray()) + return Base64.getEncoder().encodeToString(cipherBytes) + } + + private fun generateIv(): ByteArray { + val b = ByteArray(IV_SIZE) + Random().nextBytes(b) + return b + } + + private fun hash(key: String): ByteArray { + val bytes = key.toByteArray() + val md = MessageDigest.getInstance("SHA-256") + return md.digest(bytes) + } +} diff --git a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt new file mode 100644 index 0000000000000000000000000000000000000000..244b68cf833d0c6aaf7318c88ee41e31f0618935 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt @@ -0,0 +1,451 @@ +package com.httpsms + +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import androidx.work.* +import com.google.firebase.messaging.FirebaseMessagingService +import com.google.firebase.messaging.RemoteMessage +import com.httpsms.SentReceiver.FailedMessageWorker +import timber.log.Timber + +import com.google.android.mms.pdu_alt.CharacterSets +import com.google.android.mms.pdu_alt.EncodedStringValue +import com.google.android.mms.pdu_alt.PduBody +import com.google.android.mms.pdu_alt.PduComposer +import com.google.android.mms.pdu_alt.PduPart +import com.google.android.mms.pdu_alt.SendReq +import okhttp3.MediaType +import java.io.File + +class MyFirebaseMessagingService : FirebaseMessagingService() { + // [START receive_message] + override fun onMessageReceived(remoteMessage: RemoteMessage) { + initTimber() + Timber.d(MyFirebaseMessagingService::onMessageReceived.name) + + if (remoteMessage.data.containsKey(Constants.KEY_HEARTBEAT_ID)) { + Timber.w("received heartbeat message with ID [${remoteMessage.data[Constants.KEY_HEARTBEAT_ID]}] and priority [${remoteMessage.priority}] and original priority [${remoteMessage.originalPriority}]") + sendHeartbeat() + return + } + + val messageID = remoteMessage.data[Constants.KEY_MESSAGE_ID] + if (messageID == null) { + Timber.e("cannot get message id from notification data with key [${Constants.KEY_MESSAGE_ID}]") + return + } + + scheduleJob(messageID) + } + // [END receive_message] + + // [START on_new_token] + /** + * Called if the FCM registration token is updated. This may occur if the security of + * the previous token had been compromised. Note that this is called when the + * FCM registration token is initially generated so this is where you would retrieve the token. + */ + override fun onNewToken(token: String) { + initTimber() + Timber.d("Refreshed token: $token") + + // If you want to send messages to this application instance or + // manage this apps subscriptions on the server side, send the + // FCM registration token to your app server. + sendRegistrationToServer(token) + } + // [END on_new_token] + + private fun sendHeartbeat() { + Timber.d("sending heartbeat from FCM notification") + if (!Settings.isLoggedIn(applicationContext)) { + Timber.w("user is not logged in, not sending heartbeat") + return + } + Thread { + try { + val phoneNumbers = mutableListOf() + phoneNumbers.add(Settings.getSIM1PhoneNumber(applicationContext)) + if (Settings.getActiveStatus(applicationContext, Constants.SIM2)) { + phoneNumbers.add(Settings.getSIM2PhoneNumber(applicationContext)) + } + + HttpSmsApiService.create(applicationContext).storeHeartbeat(phoneNumbers.toTypedArray(), Settings.isCharging(applicationContext)) + Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis()) + } catch (exception: Exception) { + Timber.e(exception) + } + Timber.d("finished sending pulse") + }.start() + } + + private fun scheduleJob(messageID: String) { + // [START dispatch_job] + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val inputData: Data = workDataOf(Constants.KEY_MESSAGE_ID to messageID) + val work = OneTimeWorkRequest + .Builder(SendSmsWorker::class.java) + .setConstraints(constraints) + .setInputData(inputData) + .addTag(messageID) + .build() + + WorkManager + .getInstance(this) + .enqueue(work) + + Timber.d("work enqueued with ID [${work.id}] for messageID [${messageID}]") + // [END dispatch_job] + } + private fun sendRegistrationToServer(token: String) { + Timber.d("sendRegistrationTokenToServer($token)") + Settings.setFcmTokenAsync(this, token) + + if (Settings.isLoggedIn(this)) { + Timber.d("updating SIM1 phone with new fcm token") + val response = HttpSmsApiService.create(this).updateFcmToken(Settings.getSIM1PhoneNumber(this), Constants.SIM1, token) + if (response.first != null) { + Settings.setUserID(this, response.first!!.userID) + } + } + + if(Settings.isDualSIM(this)) { + Timber.d("updating SIM2 phone with new fcm token") + HttpSmsApiService.create(this).updateFcmToken(Settings.getSIM2PhoneNumber(this), Constants.SIM2, token) + } + } + + private fun initTimber() { + if (Timber.treeCount > 1) { + Timber.d("timber is already initialized with count [${Timber.treeCount}]") + return + } + + if(Settings.isDebugLogEnabled(this)) { + Timber.plant(Timber.DebugTree()) + Timber.plant(LogzTree(this.applicationContext)) + } + } + + internal class SendSmsWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { + override fun doWork(): Result { + if (!Settings.isLoggedIn(applicationContext)) { + Timber.w("user is not logged in, stopping processing") + return Result.failure() + } + + val messageID = this.inputData.getString(Constants.KEY_MESSAGE_ID) + if (messageID == null) { + Timber.e("cannot get outstanding message for work [${this.id}]") + return Result.failure() + } + + val message = getMessage(applicationContext, messageID) ?: return Result.failure() + + if (message.contact.isBlank()) { + Timber.w("message contact is blank, stopping processing") + handleFailed(applicationContext, messageID, "The contact phone number is empty.") + return Result.failure() + } + + if (!Settings.getActiveStatus(applicationContext, message.sim)) { + Timber.w("[${message.sim}] SIM is not active, stopping processing") + handleFailed(applicationContext, messageID, "Outgoing messages have been disabled on the mobile app") + return Result.failure() + } + + if (message.encrypted && Settings.getEncryptionKey(applicationContext).isNullOrEmpty()) { + Timber.w("[${message.sim}] message is encrypted but the encryption key is empty") + handleFailed(applicationContext, messageID, "Outgoing message is encrypted but mobile app has no encryption key") + return Result.failure() + } + if (message.encrypted) { + try { + Encrypter.decrypt(Settings.getEncryptionKey(applicationContext)!!, message.content) + } catch (exception: Exception) { + Timber.e(exception) + handleFailed(applicationContext, messageID, "Cannot decrypt the outgoing message. Check your encryption key on the Android app.") + return Result.failure() + } + } + + Receiver.register(applicationContext) + + if (message.attachments != null && message.attachments.isNotEmpty()) { + return handleMmsMessage(message) + } + + val parts = getMessageParts(applicationContext, message) + if (parts.size == 1) { + return handleSingleMessage(message, parts.first()) + } + return handleMultipartMessage(message, parts) + } + + fun extractFileName(url: String, prefix: String, mimeType: String? = null): String { + val fileName = url.substringAfterLast("/") + .substringBefore("?") + .takeIf { it.isNotBlank() && it.contains(".") } + ?: run { + val extension = mimeType?.let { mime -> + val ext = mime.substringAfterLast("/") + if (ext.isNotBlank()) ".$ext" else ".bin" + } ?: "" + "attachment$extension" + } + + return "${prefix}_$fileName" + } + + private fun handleMmsMessage(message: Message): Result { + Timber.d("Processing MMS for message ID [${message.id}]") + val apiService = HttpSmsApiService.create(applicationContext) + + val downloadedFiles = mutableListOf>() + + try { + for ((index, attachment) in message.attachments!!.withIndex()) { + val file = apiService.downloadAttachment(applicationContext, attachment, message.id, index) + if (file.first == null || file.second == null) { + handleFailed(applicationContext, message.id, "Failed to download attachment or file size exceeded 1.5MB.") + return Result.failure() + } + downloadedFiles.add(Pair(file.first!!, file.second!!)) + } + + val sendReq = SendReq() + + val encodedContact = EncodedStringValue(message.contact) + sendReq.to = arrayOf(encodedContact) + + val pduBody = PduBody() + + if (message.content.isNotEmpty()) { + val textPart = PduPart() + textPart.setCharset(CharacterSets.UTF_8) + textPart.contentType = "text/plain".toByteArray() + textPart.name = "text".toByteArray() + textPart.contentId = "text".toByteArray() + textPart.contentLocation = "text".toByteArray() + + var messageBody = message.content + val encryptionKey = Settings.getEncryptionKey(applicationContext) + if (message.encrypted && !encryptionKey.isNullOrEmpty()) { + messageBody = Encrypter.decrypt(encryptionKey, messageBody) + } + textPart.data = messageBody.toByteArray(Charsets.UTF_8) + + pduBody.addPart(textPart) + } + + for ((index, file) in downloadedFiles.withIndex()) { + val fileBytes = file.first.readBytes() + + val mediaPart = PduPart() + mediaPart.contentType = file.second.toString().toByteArray() + + + val fileName = extractFileName(message.attachments[index], index.toString(), file.second.toString()) + mediaPart.name = fileName.toByteArray() + mediaPart.contentId = fileName.toByteArray() + mediaPart.contentLocation = fileName.toByteArray() + mediaPart.data = fileBytes + + Timber.d("Adding MMS attachment with name [$fileName] and size [${fileBytes.size}] and type [${file.second}]") + + pduBody.addPart(mediaPart) + } + + sendReq.body = pduBody + + val pduComposer = PduComposer(applicationContext, sendReq) + val pduBytes = pduComposer.make() + + if (pduBytes == null) { + Timber.e("PduComposer failed to generate PDU byte array") + handleFailed(applicationContext, message.id, "Failed to compose MMS PDU.") + return Result.failure() + } + + val mmsDir = java.io.File(applicationContext.cacheDir, "mms_attachments") + if (!mmsDir.exists()) { + mmsDir.mkdirs() + } + + val pduFile = java.io.File(mmsDir, "pdu_${message.id}.dat") + java.io.FileOutputStream(pduFile).use { it.write(pduBytes) } + + val pduUri = androidx.core.content.FileProvider.getUriForFile( + applicationContext, + "${BuildConfig.APPLICATION_ID}.fileprovider", + pduFile + ) + + val sentIntent = createPendingIntent(message.id, SmsManagerService.sentAction()) + SmsManagerService().sendMultimediaMessage(applicationContext, pduUri, message.sim, sentIntent) + + Timber.d("Successfully dispatched MMS for message ID [${message.id}]") + return Result.success() + + } catch (e: Exception) { + Timber.e(e, "Failed to send MMS for message ID [${message.id}]") + handleFailed(applicationContext, message.id, e.message ?: "Internal error while building or sending MMS.") + return Result.failure() + } finally { + // Clean up any downloaded temporary files + downloadedFiles.forEach { file -> + if (file.first.exists()) { + file.first.delete() + } + } + + // Also clean up the MMS PDU file to avoid cache buildup in cases where + // sendMultimediaMessage fails before the sent broadcast is delivered. + try { + // The PDU file is stored under the "mms_attachments" cache subdirectory; + // delete it from the same location to ensure cleanup is effective. + val pduDir = File(applicationContext.cacheDir, "mms_attachments") + val pduFile = File(pduDir, "pdu_${message.id}.dat") + if (pduFile.exists()) { + val deleted = pduFile.delete() + if (!deleted) { + Timber.w("Failed to delete MMS PDU file for message ID [${message.id}] at [${pduFile.absolutePath}]") + } + } + } catch (cleanupException: Exception) { + // Best-effort cleanup; log but do not change the original result. + Timber.w(cleanupException, "Error while cleaning up MMS PDU file for message ID [${message.id}]") + } + } + } + + private fun handleMultipartMessage(message:Message, parts: ArrayList): Result { + Timber.d("sending multipart SMS for message with ID [${message.id}]") + return try { + val sentIntents = ArrayList() + val deliveredIntents = ArrayList() + + for (i in 0 until parts.size) { + var id = "${message.id}.$i" + + // Listen for 'delivered' and 'sent' intents only on the last part in the + // multipart SMS message + if (i == parts.size -1) { + id = message.id + } + + sentIntents.add(createPendingIntent(id, SmsManagerService.sentAction())) + deliveredIntents.add(createPendingIntent(id, SmsManagerService.deliveredAction())) + } + SmsManagerService().sendMultipartMessage(this.applicationContext,message.contact, parts, message.sim, sentIntents, deliveredIntents) + Timber.d("sent SMS for message with ID [${message.id}] in [${parts.size}] parts") + Result.success() + } catch (e: Exception) { + Timber.e(e) + Timber.d("could not send SMS for message with ID [${message.id}] in [${parts.size}] parts") + handleFailed(this.applicationContext, message.id, e.message ?: e.javaClass.simpleName) + Result.failure() + } + } + + private fun handleSingleMessage(message:Message, content: String): Result { + sendMessage( + message, + content, + createPendingIntent(message.id, SmsManagerService.sentAction()), + createPendingIntent(message.id, SmsManagerService.deliveredAction()) + ) + return Result.success() + } + + private fun handleFailed(context: Context, messageID: String, reason: String) { + Timber.d("sending [FAILED] event for message with ID [${messageID}]") + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val inputData: Data = workDataOf( + Constants.KEY_MESSAGE_ID to messageID, + Constants.KEY_MESSAGE_REASON to reason, + Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp() + ) + + val work = OneTimeWorkRequest + .Builder(FailedMessageWorker::class.java) + .setConstraints(constraints) + .setInputData(inputData) + .build() + + WorkManager + .getInstance(context) + .enqueue(work) + + Timber.d("work enqueued with ID [${work.id}] for [FAILED] message with ID [${messageID}]") + } + + private fun getMessage(context: Context, messageID: String): Message? { + Timber.d("fetching message with ID [${messageID}]") + val message = HttpSmsApiService.create(context).getOutstandingMessage(messageID) + + if (message != null) { + Timber.d("fetched message with ID [${message.id}]") + return message + } + + Timber.e("cannot get message from API with ID [${messageID}]") + return null + } + + private fun sendMessage(message: Message, content: String, sentIntent: PendingIntent, deliveredIntent: PendingIntent) { + Timber.d("sending SMS for message with ID [${message.id}]") + try { + SmsManagerService().sendTextMessage(this.applicationContext,message.contact, content, message.sim, sentIntent, deliveredIntent) + } catch (e: Exception) { + Timber.e(e) + Timber.d("could not send SMS for message with ID [${message.id}]") + handleFailed(this.applicationContext, message.id, e.message ?: e.javaClass.simpleName) + return + } + Timber.d("sent SMS for message with ID [${message.id}]") + } + + private fun getMessageParts(context: Context, message: Message): ArrayList { + Timber.d("getting parts for message with ID [${message.id}]") + + var messageBody = message.content + val encryptionKey = Settings.getEncryptionKey(context) + if (message.encrypted && !encryptionKey.isNullOrEmpty()) { + messageBody = Encrypter.decrypt(encryptionKey, messageBody) + } + + return try { + val parts = SmsManagerService().messageParts(context, messageBody) + Timber.d("message with ID [${message.id}] has [${parts.size}] parts") + parts + } catch (e: Exception) { + Timber.e(e) + Timber.d("could not get parts message with ID [${message.id}] returning [1] part with entire content") + val list = ArrayList() + list.add(messageBody) + list + } + } + + private fun createPendingIntent(id: String, action: String): PendingIntent { + val intent = Intent(action) + intent.putExtra(Constants.KEY_MESSAGE_ID, id) + + return PendingIntent.getBroadcast( + this.applicationContext, + id.hashCode(), + intent, + PendingIntent.FLAG_IMMUTABLE + ) + } + } +} diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt new file mode 100644 index 0000000000000000000000000000000000000000..51fa21cdc67dcbdc16e904e4d91503bcdc57d700 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt @@ -0,0 +1,300 @@ +package com.httpsms + +import android.content.Context +import com.httpsms.Constants.Companion.MAX_MMS_ATTACHMENT_SIZE +import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import timber.log.Timber +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.net.URI +import java.net.URL +import java.util.logging.Level +import java.util.logging.Logger.getLogger + + +class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) { + private val apiKeyHeader = "x-api-key" + private val clientVersionHeader = "X-Client-Version" + private val jsonMediaType = "application/json; charset=utf-8".toMediaType() + private val client = OkHttpClient.Builder().retryOnConnectionFailure(true).build() + + init { + getLogger(OkHttpClient::class.java.name).level = Level.FINE + } + + companion object { + fun create(context: Context): HttpSmsApiService { + return HttpSmsApiService( + Settings.getApiKeyOrDefault(context), + Settings.getServerUrlOrDefault(context) + ) + } + } + + fun getOutstandingMessage(messageID: String): Message? { + val request: Request = Request.Builder() + .url(resolveURL("/v1/messages/outstanding?message_id=${messageID}")) + .header(apiKeyHeader, apiKey) + .header(clientVersionHeader, BuildConfig.VERSION_NAME) + .build() + + val response = client.newCall(request).execute() + if (response.isSuccessful) { + val payload = ResponseMessage.fromJson(response.body!!.string())?.data + if (payload == null) { + response.close() + Timber.e("cannot decode payload [${response.body}]") + return null + } + response.close() + return payload + } + + Timber.e("invalid response with code [${response.code}]") + response.close() + return null + } + + fun sendDeliveredEvent(messageId: String, timestamp: String): Boolean { + return sendEvent(messageId, "DELIVERED", timestamp) + } + + fun sendSentEvent(messageId: String, timestamp: String): Boolean { + return sendEvent(messageId, "SENT", timestamp) + } + + fun sendFailedEvent(messageId: String, timestamp: String, reason: String): Boolean { + return sendEvent(messageId, "FAILED", timestamp, reason) + } + + fun receive(requestPayload: ReceivedMessageRequest): Boolean { + val body = com.beust.klaxon.Klaxon().toJsonString(requestPayload) + + val request: Request = Request.Builder() + .url(resolveURL("/v1/messages/receive")) + .post(body.toRequestBody(jsonMediaType)) + .header(apiKeyHeader, apiKey) + .header(clientVersionHeader, BuildConfig.VERSION_NAME) + .build() + + val response = try { + client.newCall(request).execute() + } catch (e: Exception) { + Timber.e(e, "Exception while sending received message request") + return false + } + + if (!response.isSuccessful) { + Timber.e("error response [${response.body?.string()}] with code [${response.code}] while receiving message") + response.close() + return response.code in 400..499 + } + + response.close() + Timber.i("received message stored successfully") + return true + } + + fun sendMissedCallEvent(sim: String, from: String, to: String, timestamp: String): Boolean { + val body = """ + { + "sim": "$sim", + "from": "$from", + "timestamp": "$timestamp", + "to": "$to" + } + """.trimIndent() + + val request: Request = Request.Builder() + .url(resolveURL("/v1/messages/calls/missed")) + .post(body.toRequestBody(jsonMediaType)) + .header(apiKeyHeader, apiKey) + .header(clientVersionHeader, BuildConfig.VERSION_NAME) + .build() + + val response = client.newCall(request).execute() + if (!response.isSuccessful) { + Timber.e("error response [${response.body?.string()}] with code [${response.code}] while sending missed call event [${body}]") + response.close() + return response.code in 400..499 + } + + response.close() + Timber.i("missed call from [${from}] to [${to}] sent successfully with timestamp [${timestamp}]" ) + return true + } + + fun storeHeartbeat(phoneNumbers: Array, charging: Boolean): Boolean { + val body = """ + { + "charging": $charging, + "phone_numbers": ${phoneNumbers.joinToString(prefix = "[", postfix = "]") { "\"$it\"" }} + } + """.trimIndent() + + val request: Request = Request.Builder() + .url(resolveURL("/v1/heartbeats")) + .post(body.toRequestBody(jsonMediaType)) + .header(apiKeyHeader, apiKey) + .header(clientVersionHeader, BuildConfig.VERSION_NAME) + .build() + + val response = client.newCall(request).execute() + if (!response.isSuccessful) { + Timber.e("error response [${response.body?.string()}] with code [${response.code}] while sending heartbeat [$body] for phone numbers [${phoneNumbers.joinToString()}]") + response.close() + return false + } + + response.close() + Timber.i( "heartbeat stored successfully for phone numbers [${phoneNumbers.joinToString()}]" ) + return true + } + + fun InputStream.copyToWithLimit( + out: OutputStream, + limit: Long, + bufferSize: Int = DEFAULT_BUFFER_SIZE + ): Long { + var bytesCopied: Long = 0 + val buffer = ByteArray(bufferSize) + var bytes = read(buffer) + + while (bytes >= 0) { + bytesCopied += bytes + + if (bytesCopied > limit) { + throw IOException("Download aborted: File exceeded maximum allowed size of $limit bytes.") + } + + out.write(buffer, 0, bytes) + bytes = read(buffer) + } + return bytesCopied + } + + fun downloadAttachment(context: Context, urlString: String, messageId: String, attachmentIndex: Int): Pair { + val request = Request.Builder().url(urlString).build() + + try { + client.newCall(request).execute().use { response -> + if (!response.isSuccessful) { + Timber.e("Failed to download attachment: ${response.code}") + return Pair(null, null) + } + + val body = response.body + val contentLength = body.contentLength() + if (contentLength > MAX_MMS_ATTACHMENT_SIZE) { + Timber.e("Attachment is too large ($contentLength bytes).") + return Pair(null, null) + } + + val mmsDir = File(context.cacheDir, "mms_attachments") + if (!mmsDir.exists()) { + mmsDir.mkdirs() + } + + val tempFile = File(mmsDir, "mms_${messageId}_$attachmentIndex") + val inputStream = body.byteStream() + FileOutputStream(tempFile).use { outputStream -> + inputStream.use { input -> + input.copyToWithLimit(outputStream, MAX_MMS_ATTACHMENT_SIZE) + } + } + + return Pair(tempFile, body.contentType()) + } + } catch (e: Exception) { + Timber.e(e, "Exception while download attachment") + return Pair(null, null) + } + } + + private fun sendEvent(messageId: String, event: String, timestamp: String, reason: String? = null): Boolean { + var reasonString = "null" + if (reason != null) { + reasonString = "\"$reason\"" + } + + val body = """ + { + "event_name": "$event", + "reason": $reasonString, + "timestamp": "$timestamp" + } + """.trimIndent() + + val request: Request = Request.Builder() + .url(resolveURL("/v1/messages/${messageId}/events")) + .post(body.toRequestBody(jsonMediaType)) + .header(apiKeyHeader, apiKey) + .header(clientVersionHeader, BuildConfig.VERSION_NAME) + .build() + + val response = client.newCall(request).execute() + if (response.code == 404) { + response.close() + Timber.i( "[$event] event sent successfully but message with ID [$messageId] has been deleted" ) + return true + } + + if (!response.isSuccessful) { + Timber.e("error response [${response.body.string()}] with code [${response.code}] while sending [${event}] event [${body}] for message with ID [${messageId}]") + response.close() + return false + } + + response.close() + Timber.i( "[$event] event sent successfully for message with ID [$messageId]" ) + return true + } + + fun updateFcmToken(phoneNumber: String, sim: String, fcmToken: String): Triple { + val body = """ + { + "fcm_token": "$fcmToken", + "phone_number": "$phoneNumber", + "sim": "$sim" + } + """.trimIndent() + + val request: Request = Request.Builder() + .url(resolveURL("/v1/phones/fcm-token")) + .put(body.toRequestBody(jsonMediaType)) + .header(apiKeyHeader, apiKey) + .header(clientVersionHeader, BuildConfig.VERSION_NAME) + .build() + + try { + val response = client.newCall(request).execute() + if (!response.isSuccessful) { + Timber.e("error response [${response.body?.string()}] with code [${response.code}] while updating FCM token [$fcmToken] with apiKey [$apiKey]") + response.close() + if (response.code == 401) { + Timber.e("invalid API key [$apiKey]") + return Triple(null, "Cannot validate the API key. Check if it is correct and try again.", null) + } + return Triple(null,null, "Cannot login to the server, Make sure the phone number is in international format e.g +18005550100") + } + + Timber.i("FCM token submitted correctly with API key [$apiKey] and server url [$baseURL]" ) + val payload = ResponsePhone.fromJson(response.body!!.string())?.data + response.close() + return Triple(payload, null, null) + } catch (ex: Exception) { + return Triple(null, null, ex.message) + } + } + + private fun resolveURL(path: String): URL { + return baseURL.resolve(baseURL.path + path).toURL() + } +} diff --git a/android/app/src/main/java/com/httpsms/LoginActivity.kt b/android/app/src/main/java/com/httpsms/LoginActivity.kt new file mode 100644 index 0000000000000000000000000000000000000000..17bd6db66d62a5c6ff1a4e28b904e2434b4a5d8e --- /dev/null +++ b/android/app/src/main/java/com/httpsms/LoginActivity.kt @@ -0,0 +1,178 @@ +package com.httpsms + +import android.Manifest +import android.annotation.SuppressLint +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import android.os.Bundle +import android.telephony.TelephonyManager +import android.widget.Toast +import androidx.activity.compose.setContent +import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.viewModels +import androidx.appcompat.app.AppCompatActivity +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.core.app.ActivityCompat +import com.google.android.gms.common.ConnectionResult +import com.google.android.gms.common.GoogleApiAvailability +import com.httpsms.ui.login.LoginScreen +import com.httpsms.ui.login.LoginViewModel +import com.httpsms.ui.theme.HttpSmsTheme +import com.journeyapps.barcodescanner.ScanContract +import com.journeyapps.barcodescanner.ScanOptions +import timber.log.Timber + +class LoginActivity : AppCompatActivity() { + private val viewModel: LoginViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + redirectToMain() + + viewModel.initialize(this, getString(R.string.default_server_url)) + + setContent { + HttpSmsTheme { + val uiState by viewModel.uiState.collectAsState() + + LaunchedEffect(uiState.loginSuccess) { + if (uiState.loginSuccess) { + redirectToMain() + } + } + + LoginScreen( + viewModel = viewModel, + onQrScanClick = { startQrCodeScan() }, + onLoginClick = { + val error = isGooglePlayServicesAvailable() + if (error != null) { + Toast.makeText(this@LoginActivity, error, Toast.LENGTH_SHORT).show() + } else { + viewModel.login( + context = this@LoginActivity, + countryCode = getCountryCode(), + onGooglePlayServicesError = { + Toast.makeText(this@LoginActivity, it, Toast.LENGTH_SHORT).show() + }, + onFcmTokenMissing = { + Toast.makeText( + this@LoginActivity, + "Cannot find FCM token. Make sure you have Google Play Services installed", + Toast.LENGTH_LONG + ).show() + } + ) + } + } + ) + } + } + } + + private val barcodeLauncher = registerForActivityResult(ScanContract()) { result -> + if (result.contents != null) { + viewModel.onApiKeyChange(result.contents) + Toast.makeText(this, "Scanned: ${result.contents}", Toast.LENGTH_LONG).show() + } else { + Toast.makeText(this, "Scan cancelled", Toast.LENGTH_SHORT).show() + } + } + + private fun startQrCodeScan() { + val options = ScanOptions() + options.setPrompt("Scan a QR code") + options.setBeepEnabled(true) + options.setOrientationLocked(false) + options.setCameraId(0) + barcodeLauncher.launch(options) + } + + override fun onStart() { + super.onStart() + Timber.i("on start") + requestPermissions() + } + + @SuppressLint("HardwareIds") + @Suppress("DEPRECATION") + private fun getPhoneNumber(context: Context): String? { + val telephonyManager = this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + if (ActivityCompat.checkSelfPermission( + this, + Manifest.permission.READ_SMS + ) != PackageManager.PERMISSION_GRANTED + ) { + Timber.e("cannot get owner because permissions are not granted") + return Settings.getSIM1PhoneNumber(this) + } + + if (telephonyManager.line1Number != null && telephonyManager.line1Number != "") { + Settings.setSIM1PhoneNumber(context, telephonyManager.line1Number) + } + + return telephonyManager.line1Number + } + + private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -> + permissions.entries.forEach { + Timber.d("${it.key} = ${it.value}") + } + // Try to auto-detect phone numbers after permissions are granted + viewModel.autoDetectPhoneNumbers(this) + } + + private fun requestPermissions() { + Timber.d("requesting permissions") + + var permissions = arrayOf( + Manifest.permission.SEND_SMS, + Manifest.permission.RECEIVE_SMS, + Manifest.permission.READ_PHONE_STATE, + Manifest.permission.READ_SMS, + ) + + if(Build.VERSION.SDK_INT >= 33) { + permissions += Manifest.permission.POST_NOTIFICATIONS + } + + requestPermissionLauncher.launch(permissions) + + Timber.d("creating permissions launcher") + } + + private fun isGooglePlayServicesAvailable(): String? { + val googleApiAvailability = GoogleApiAvailability.getInstance() + val status = googleApiAvailability.isGooglePlayServicesAvailable(this) + if (status != ConnectionResult.SUCCESS) { + if (googleApiAvailability.isUserResolvableError(status)) { + googleApiAvailability.getErrorDialog(this, status, 2404)?.show() + } + return googleApiAvailability.getErrorString(status) + } + return null + } + + private fun redirectToMain() { + if (!Settings.isLoggedIn(this)) { + return + } + finish() + + val switchActivityIntent = Intent(this, MainActivity::class.java) + startActivity(switchActivityIntent) + } + + private fun getCountryCode() : String { + val tm = this.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + val code = tm.networkCountryIso.uppercase() + if (code.isEmpty()) { + return this.resources.configuration.locales.get(0).country.uppercase() + } + return code + } +} diff --git a/android/app/src/main/java/com/httpsms/LogzTree.kt b/android/app/src/main/java/com/httpsms/LogzTree.kt new file mode 100644 index 0000000000000000000000000000000000000000..68a81c8ee036cd8b7f0e3d0b764b9160c062f146 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/LogzTree.kt @@ -0,0 +1,82 @@ +package com.httpsms + +import android.content.Context +import android.os.Build +import com.beust.klaxon.Json +import com.beust.klaxon.Klaxon +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import timber.log.Timber +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import io.sentry.Sentry + +class LogzTree(val context: Context): Timber.DebugTree() { + private val client = OkHttpClient() + + override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { + val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + val logEntry = LogEntry( + BuildConfig.APPLICATION_ID, + BuildConfig.VERSION_NAME, + priority, + severity(priority), + tag, + message, + Build.MODEL, + Build.BRAND, + Build.DEVICE, + Build.VERSION.SDK_INT, + ZonedDateTime.now(ZoneOffset.UTC).format(formatter), + Settings.getUserID(context), + t + ) + + val body = Klaxon().toJsonString(listOf(logEntry)).toRequestBody("application/json".toMediaType()) + val request: Request = Request.Builder() + .url("https://api.axiom.co/v1/datasets/production/ingest") + .post(body) + .header("Content-Type", "application/json") + .header("Authorization", "Bearer xaat-2a2e0b73-3702-4971-a80f-be3956934950") + .build() + + Thread { + try { + val response = client.newCall(request).execute() + response.body?.close() + } catch(ex: Exception) { + Sentry.captureException(ex) + } + }.start() + } + + private fun severity(priority: Int): String { + return when(priority) { + 3 -> "DEBUG" + 4 -> "INFO" + 5 -> "WARNING" + 6 -> "ERROR" + 7 -> "ASSERT" + else -> "VERBOSE" + } + } + + class LogEntry( + val name: String, + val release: String, + val priority: Int, + val severity: String, + val tag: String?, + val message: String, + val model: String, + val brand: String, + val device: String, + val version: Int, + @Json(name = "@timestamp") + val dt: String, + val userID: String, + val throwable: Throwable?) +} diff --git a/android/app/src/main/java/com/httpsms/MainActivity.kt b/android/app/src/main/java/com/httpsms/MainActivity.kt new file mode 100644 index 0000000000000000000000000000000000000000..ff7587db28cc39d70bb5e946d0dc42243086c528 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/MainActivity.kt @@ -0,0 +1,245 @@ +package com.httpsms + +import android.Manifest +import android.annotation.SuppressLint +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.provider.Settings as ProviderSettings +import android.widget.Toast +import androidx.activity.compose.setContent +import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.viewModels +import androidx.appcompat.app.AppCompatActivity +import androidx.work.Constraints +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.NetworkType +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import com.httpsms.services.StickyNotificationService +import com.httpsms.ui.main.MainScreen +import com.httpsms.ui.main.MainViewModel +import com.httpsms.ui.theme.HttpSmsTheme +import com.httpsms.worker.HeartbeatWorker +import timber.log.Timber +import java.util.concurrent.TimeUnit + + +class MainActivity : AppCompatActivity() { + private val viewModel: MainViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + initTimber() + + redirectToLogin() + + viewModel.initialize(this, getString(R.string.app_version, BuildConfig.VERSION_NAME)) + + setContent { + HttpSmsTheme { + MainScreen( + viewModel = viewModel, + onSettingsClick = { onSettingsClick() }, + onSmsPermissionClick = { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://httpsms.com/blog/grant-send-and-read-sms-permissions-on-android")) + startActivity(intent) + }, + onBatteryOptimizationClick = { + val intent = Intent() + intent.action = ProviderSettings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS + intent.data = Uri.parse("package:$packageName") + startActivity(intent) + }, + onHeartbeatClick = { + viewModel.sendHeartbeat(this) { error -> + if (error != null) { + Timber.w("heartbeat sending failed with [$error]") + Toast.makeText(this, error, Toast.LENGTH_LONG).show() + } else { + Toast.makeText(this, "Heartbeat sent successfully", Toast.LENGTH_SHORT).show() + } + } + } + ) + } + } + + createChannel() + refreshToken(this) + + startStickyNotification(this) + scheduleHeartbeatWorker(this) + } + + override fun onStart() { + super.onStart() + requestPermissions(this) + } + + override fun onResume() { + super.onResume() + Timber.d( "on activity resume") + redirectToLogin() + refreshToken(this) + viewModel.updateState(this, getString(R.string.app_version, BuildConfig.VERSION_NAME)) + } + + private fun requestPermissions(context:Context) { + Timber.d("requesting permissions") + val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -> + permissions.entries.forEach { + Timber.d("${it.key} = ${it.value}") + if (it.key == Manifest.permission.READ_CALL_LOG && !it.value) { + Timber.w("disabling incoming call events since for SIM1 and SIM2") + Settings.setIncomingCallEventsEnabled(context, Constants.SIM1, false) + Settings.setIncomingCallEventsEnabled(context, Constants.SIM2, false) + } + } + viewModel.updateState(context, getString(R.string.app_version, BuildConfig.VERSION_NAME)) + } + + var permissions = arrayOf( + Manifest.permission.SEND_SMS, + Manifest.permission.RECEIVE_SMS, + Manifest.permission.READ_SMS + ) + + if(Build.VERSION.SDK_INT >= 33) { + permissions += Manifest.permission.POST_NOTIFICATIONS + } + + if(Settings.isIncomingCallEventsEnabled(context,Constants.SIM1) || Settings.isIncomingCallEventsEnabled(context,Constants.SIM2) ) { + permissions += Manifest.permission.READ_CALL_LOG + permissions += Manifest.permission.READ_PHONE_STATE + } + + requestPermissionLauncher.launch(permissions) + + Timber.d("creating permissions launcher") + } + + private fun scheduleHeartbeatWorker(context: Context) { + val tag = "TAG_HEARTBEAT_WORKER" + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val heartbeatWorker = + PeriodicWorkRequestBuilder(15, TimeUnit.MINUTES) + .setConstraints(constraints) + .addTag(tag) + .build() + + WorkManager + .getInstance(context) + .enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP, heartbeatWorker) + + Timber.d("finished scheduling heartbeat worker with ID [${heartbeatWorker.id}]") + } + + private fun startStickyNotification(context: Context) { + Timber.d("starting foreground service") + if(!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) { + Timber.d("active status is false, not starting foreground service") + return + } + val notificationIntent = Intent(context, StickyNotificationService::class.java) + val service = context.startForegroundService(notificationIntent) + Timber.d("foreground service started [${service?.className}]") + } + + private fun refreshToken(context: Context) { + if(!Settings.isLoggedIn(context)) { + Timber.w("cannot refresh token because owner is not logged in") + return + } + + if(!Settings.hasOwner(context)) { + Timber.w("cannot refresh token because owner does not exist") + return + } + + if (Settings.getFcmToken(context) == null) { + Timber.w("cannot refresh token because token does not exist") + return + } + + val updateTimestamp = Settings.getFcmTokenLastUpdateTimestamp(context) + Timber.d("FCM_TOKEN_UPDATE_TIMESTAMP: $updateTimestamp") + + val interval = 24 * 60 * 60 * 1000 // 1 day + val currentTimeStamp = System.currentTimeMillis() + + if (currentTimeStamp - updateTimestamp < interval) { + Timber.i("update interval [${currentTimeStamp - updateTimestamp}] < 24 hours [$interval]") + return + } + + sendFCMToken(currentTimeStamp, context, Settings.getSIM1PhoneNumber(context), Constants.SIM1) + if (Settings.isDualSIM(context)) { + sendFCMToken(currentTimeStamp, context, Settings.getSIM2PhoneNumber(context), Constants.SIM2) + } + } + + private fun sendFCMToken(timestamp: Long, context:Context, phoneNumber: String, sim: String) { + Thread { + val response = HttpSmsApiService.create(context).updateFcmToken(phoneNumber, sim,Settings.getFcmToken(context) ?: "") + if (response.first != null) { + Settings.setUserID(context, response.first!!.userID) + Settings.setFcmTokenLastUpdateTimestampAsync(context, timestamp) + Timber.i("[${sim}] FCM token uploaded successfully") + return@Thread + } else { + Timber.e("[${sim}] could not update FCM token") + } + }.start() + } + + private fun initTimber() { + if (Timber.treeCount > 1) { + Timber.d("timber is already initialized with count [${Timber.treeCount}]") + return + } + + if(Settings.isDebugLogEnabled(this)) { + Timber.plant(Timber.DebugTree()) + Timber.plant(LogzTree(this.applicationContext)) + } + } + + private fun onSettingsClick() { + Timber.d("settings button clicked") + val switchActivityIntent = Intent(this, SettingsActivity::class.java) + startActivity(switchActivityIntent) + } + + private fun redirectToLogin():Boolean { + if (Settings.isLoggedIn(this)) { + return false + } + val switchActivityIntent = Intent(this, LoginActivity::class.java) + startActivity(switchActivityIntent) + return true + } + + private fun createChannel() { + // Create the NotificationChannel + val name = getString(R.string.notification_channel_default) + val descriptionText = getString(R.string.notification_channel_default) + val importance = NotificationManager.IMPORTANCE_DEFAULT + val mChannel = NotificationChannel(name, name, importance) + mChannel.description = descriptionText + // Register the channel with the system; you can't change the importance + // or other notification behaviors after this + val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager + notificationManager.createNotificationChannel(mChannel) + } +} diff --git a/android/app/src/main/java/com/httpsms/Models.kt b/android/app/src/main/java/com/httpsms/Models.kt new file mode 100644 index 0000000000000000000000000000000000000000..b4bf5464e5041f63a22a47064c197183ebb90505 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/Models.kt @@ -0,0 +1,91 @@ +package com.httpsms + +import com.beust.klaxon.Json +import com.beust.klaxon.Klaxon + +data class ResponseMessage ( + val data: Message, + val message: String, + val status: String +) { + companion object { + fun fromJson(json: String) = Klaxon().parse(json) + } +} +data class ResponsePhone ( + val data: Phone, + val message: String, + val status: String, +) { + companion object { + fun fromJson(json: String) = Klaxon().parse(json) + } +} + +data class Phone ( + val id: String, + + @Json(name = "user_id") + val userID: String, +) + +data class Message ( + val contact: String, + val content: String, + val sim: String, + + @Json(name = "created_at") + val createdAt: String, + + @Json(name = "failure_reason") + val failureReason: String?, + + val id: String, + + @Json(name = "last_attempted_at") + val lastAttemptedAt: String?, + + @Json(name = "order_timestamp") + val orderTimestamp: String, + + val owner: String, + + @Json(name = "received_at") + val receivedAt: String?, + + val encrypted: Boolean, + + @Json(name = "request_received_at") + val requestReceivedAt: String, + + @Json(name = "send_time") + val sendTime: Long?, + + @Json(name = "sent_at") + val sentAt: String?, + + val status: String, + val type: String, + + @Json(name = "updated_at") + val updatedAt: String, + + val attachments: List? = null +) + +data class ReceivedAttachment( + val name: String, + @Json(name = "content_type") + val contentType: String, + val content: String +) + +data class ReceivedMessageRequest( + val sim: String, + val from: String, + val to: String, + val content: String, + val encrypted: Boolean, + val timestamp: String, + val attachments: List? = null +) diff --git a/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt b/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt new file mode 100644 index 0000000000000000000000000000000000000000..3edc30e2d919ce3d587e71c7959b92b314c8ec23 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ReceivedReceiver.kt @@ -0,0 +1,229 @@ +package com.httpsms + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.provider.Telephony +import android.util.Base64 +import androidx.work.Constraints +import androidx.work.Data +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequest +import androidx.work.WorkManager +import androidx.work.Worker +import androidx.work.WorkerParameters +import androidx.work.workDataOf +import com.google.android.mms.pdu_alt.CharacterSets +import com.google.android.mms.pdu_alt.MultimediaMessagePdu +import com.google.android.mms.pdu_alt.PduParser +import com.google.android.mms.pdu_alt.RetrieveConf +import timber.log.Timber +import java.io.File +import java.io.FileOutputStream +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter + +class ReceivedReceiver: BroadcastReceiver() +{ + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == Telephony.Sms.Intents.SMS_RECEIVED_ACTION) { + handleSmsReceived(context, intent) + } else if (intent.action == Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION) { + handleMmsReceived(context, intent) + } else { + Timber.e("received invalid intent with action [${intent.action}]") + } + } + + private fun handleSmsReceived(context: Context, intent: Intent) { + var smsSender = "" + var smsBody = "" + + for (smsMessage in Telephony.Sms.Intents.getMessagesFromIntent(intent)) { + smsSender = smsMessage.displayOriginatingAddress + smsBody += smsMessage.messageBody + } + + val (sim, owner) = getSimAndOwner(context, intent) + + if (!Settings.isIncomingMessageEnabled(context, sim)) { + Timber.w("[${sim}] is not active for incoming messages") + return + } + + handleMessageReceived( + context, + sim, + smsSender, + owner, + smsBody + ) + } + + private fun handleMmsReceived(context: Context, intent: Intent) { + val pushData = intent.getByteArrayExtra("data") ?: return + val pdu = PduParser(pushData, true).parse() ?: return + + if (pdu !is MultimediaMessagePdu) { + Timber.d("Received PDU is not a MultimediaMessagePdu, ignoring.") + return + } + + val from = pdu.from?.string ?: "" + var content = "" + val attachmentFiles = mutableListOf() + + // Check if it's a RetrieveConf (which contains the actual message body) + if (pdu is RetrieveConf) { + val body = pdu.body + if (body != null) { + for (i in 0 until body.partsNum) { + val part = body.getPart(i) + val partData = part.data ?: continue + val contentType = String(part.contentType ?: "application/octet-stream".toByteArray()) + + if (contentType.startsWith("text/plain")) { + content += String(partData, charset(CharacterSets.getMimeName(part.charset))) + } else { + // Save attachment to a temporary file + val fileName = String(part.name ?: part.contentLocation ?: part.contentId ?: "attachment_$i".toByteArray()) + val tempFile = File(context.cacheDir, "received_mms_${System.currentTimeMillis()}_$i") + FileOutputStream(tempFile).use { it.write(partData) } + attachmentFiles.add("${tempFile.absolutePath}|${contentType}|${fileName}") + } + } + } + } else { + Timber.d("Received PDU is of type [${pdu.javaClass.simpleName}], body extraction not implemented.") + } + + val (sim, owner) = getSimAndOwner(context, intent) + + if (!Settings.isIncomingMessageEnabled(context, sim)) { + Timber.w("[${sim}] is not active for incoming messages") + return + } + + handleMessageReceived( + context, + sim, + from, + owner, + content, + attachmentFiles.toTypedArray() + ) + } + + private fun getSimAndOwner(context: Context, intent: Intent): Pair { + var sim = Constants.SIM1 + var owner = Settings.getSIM1PhoneNumber(context) + if (intent.getIntExtra("android.telephony.extra.SLOT_INDEX", 0) > 0 && Settings.isDualSIM(context)) { + owner = Settings.getSIM2PhoneNumber(context) + sim = Constants.SIM2 + } + return Pair(sim, owner) + } + + private fun handleMessageReceived(context: Context, sim: String, from: String, to : String, content: String, attachments: Array? = null) { + val timestamp = ZonedDateTime.now(ZoneOffset.UTC) + + if (!Settings.isLoggedIn(context)) { + Timber.w("[${sim}] user is not logged in") + return + } + + if (!Settings.getActiveStatus(context, sim)) { + Timber.w("[${sim}] user is not active") + return + } + + var body = content; + if (Settings.encryptReceivedMessages(context)) { + body = Encrypter.encrypt(Settings.getEncryptionKey(context)!!, content) + } + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val inputData: Data = workDataOf( + Constants.KEY_MESSAGE_FROM to from, + Constants.KEY_MESSAGE_TO to to, + Constants.KEY_MESSAGE_SIM to sim, + Constants.KEY_MESSAGE_CONTENT to body, + Constants.KEY_MESSAGE_ENCRYPTED to Settings.encryptReceivedMessages(context), + Constants.KEY_MESSAGE_TIMESTAMP to DateTimeFormatter.ofPattern(Constants.TIMESTAMP_PATTERN).format(timestamp).replace("+", "Z"), + Constants.KEY_MESSAGE_ATTACHMENTS to attachments + ) + + val work = OneTimeWorkRequest + .Builder(ReceivedSmsWorker::class.java) + .setConstraints(constraints) + .setInputData(inputData) + .build() + + WorkManager + .getInstance(context) + .enqueue(work) + + Timber.d("work enqueued with ID [${work.id}] for received message from [${from}] to [${to}]") + } + + internal class ReceivedSmsWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { + override fun doWork(): Result { + Timber.i("[${this.inputData.getString(Constants.KEY_MESSAGE_SIM)}] forwarding received message from [${this.inputData.getString(Constants.KEY_MESSAGE_FROM)}] to [${this.inputData.getString(Constants.KEY_MESSAGE_TO)}]") + + val sim = this.inputData.getString(Constants.KEY_MESSAGE_SIM)!! + val from = this.inputData.getString(Constants.KEY_MESSAGE_FROM)!! + val to = this.inputData.getString(Constants.KEY_MESSAGE_TO)!! + val content = this.inputData.getString(Constants.KEY_MESSAGE_CONTENT)!! + val encrypted = this.inputData.getBoolean(Constants.KEY_MESSAGE_ENCRYPTED, false) + val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)!! + + val attachmentsData = inputData.getStringArray(Constants.KEY_MESSAGE_ATTACHMENTS) + val attachments = attachmentsData?.mapNotNull { + val parts = it.split("|") + val file = File(parts[0]) + if (file.exists()) { + val bytes = file.readBytes() + val base64Content = Base64.encodeToString(bytes, Base64.NO_WRAP) + ReceivedAttachment( + name = parts[2], + contentType = parts[1], + content = base64Content + ) + } else { + null + } + } + + val request = ReceivedMessageRequest( + sim = sim, + from = from, + to = to, + content = content, + encrypted = encrypted, + timestamp = timestamp, + attachments = attachments + ) + + val success = HttpSmsApiService.create(applicationContext).receive(request) + + // Cleanup temp files + attachmentsData?.forEach { + val path = it.split("|")[0] + val file = File(path) + if (file.exists()) { + file.delete() + } + } + + if (success) { + return Result.success() + } + + return Result.retry() + } + } +} diff --git a/android/app/src/main/java/com/httpsms/Receiver.kt b/android/app/src/main/java/com/httpsms/Receiver.kt new file mode 100644 index 0000000000000000000000000000000000000000..a54f363f5acd2e26a16e44f30a1b4d132b4e091c --- /dev/null +++ b/android/app/src/main/java/com/httpsms/Receiver.kt @@ -0,0 +1,73 @@ +package com.httpsms + +import android.content.Context +import android.content.Context.RECEIVER_EXPORTED +import android.content.IntentFilter +import android.os.Build +import androidx.annotation.RequiresApi +import timber.log.Timber + +object Receiver { + private var sentReceiver: SentReceiver? = null; + private var deliveredReceiver: DeliveredReceiver? = null; + + fun register(context: Context) { + if(sentReceiver == null) { + Timber.d("registering [sent] receiver for intent [${SmsManagerService.sentAction()}]") + sentReceiver = SentReceiver() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.registerReceiver( + sentReceiver, + IntentFilter(SmsManagerService.sentAction()), + RECEIVER_EXPORTED + ) + } else { + context.registerReceiver( + sentReceiver, + IntentFilter(SmsManagerService.sentAction()) + ) + } + } + + if(deliveredReceiver == null) { + Timber.d("registering [delivered] receiver for intent [${SmsManagerService.deliveredAction()}]") + deliveredReceiver = DeliveredReceiver() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.registerReceiver( + deliveredReceiver, + IntentFilter(SmsManagerService.deliveredAction()), + RECEIVER_EXPORTED + ) + } else { + context.registerReceiver( + deliveredReceiver, + IntentFilter(SmsManagerService.deliveredAction()) + ) + } + } + } + + fun isValid(context: Context, messageId: String?): Boolean { + if (messageId == null) { + Timber.e("cannot handle event because the message ID is null") + return false + } + + if (!Settings.isLoggedIn(context)) { + Timber.w("cannot handle message with id [$messageId] because the user is not logged in") + return false + } + + if (!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) { + Timber.w("cannot handle message with id [$messageId] because the user is not active") + return false + } + + if(messageId.contains(".")) { + Timber.d("message id [${messageId}] is for multipart segment [${messageId.split(".")[1]}]") + return false + } + + return true + } +} diff --git a/android/app/src/main/java/com/httpsms/SentReceiver.kt b/android/app/src/main/java/com/httpsms/SentReceiver.kt new file mode 100644 index 0000000000000000000000000000000000000000..2b5bfd1292ed33bac85cb4146d6298f1c051295e --- /dev/null +++ b/android/app/src/main/java/com/httpsms/SentReceiver.kt @@ -0,0 +1,137 @@ +package com.httpsms + +import android.app.Activity +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.telephony.SmsManager +import androidx.work.Constraints +import androidx.work.Data +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequest +import androidx.work.WorkManager +import androidx.work.Worker +import androidx.work.WorkerParameters +import androidx.work.workDataOf +import timber.log.Timber +import java.io.File + +internal class SentReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val messageId = intent.getStringExtra(Constants.KEY_MESSAGE_ID) + cleanupPduFile(context, messageId) + when (resultCode) { + Activity.RESULT_OK -> handleMessageSent(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID)) + SmsManager.RESULT_ERROR_GENERIC_FAILURE -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "GENERIC_FAILURE") + SmsManager.RESULT_ERROR_NO_SERVICE -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "NO_SERVICE") + SmsManager.RESULT_ERROR_NULL_PDU -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "NULL_PDU") + SmsManager.RESULT_ERROR_RADIO_OFF -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "RADIO_OFF") + SmsManager.RESULT_ERROR_LIMIT_EXCEEDED -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "LIMIT_EXCEEDED") + else -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "UNKNOWN:${resultCode}") + } + } + + private fun cleanupPduFile(context: Context, messageId: String?) { + if (messageId == null) return + + try { + val baseMessageId = messageId.substringBefore(".") + val mmsDir = File(context.cacheDir, "mms_attachments") + val pduFile = File(mmsDir, "pdu_$baseMessageId.dat") + + if (pduFile.exists()) { + if (pduFile.delete()) { + Timber.d("Cleaned up PDU file for message ID [$baseMessageId]") + } else { + Timber.w("Failed to delete PDU file for message ID [$baseMessageId]") + } + } + } catch (e: Exception) { + Timber.e(e, "Error cleaning up PDU file for message ID [$messageId]") + } + } + + private fun handleMessageSent(context: Context, messageId: String?) { + if (!Receiver.isValid(context, messageId)) { + return + } + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val inputData: Data = workDataOf( + Constants.KEY_MESSAGE_ID to messageId, + Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp() + ) + + val work = OneTimeWorkRequest + .Builder(SentMessageWorker::class.java) + .setConstraints(constraints) + .setInputData(inputData) + .build() + + WorkManager + .getInstance(context) + .enqueue(work) + + Timber.d("work enqueued with ID [${work.id}] for [SENT] message with ID [${messageId}]") + } + + private fun handleMessageFailed(context: Context, messageId: String?, reason: String) { + if (!Receiver.isValid(context, messageId)) { + return + } + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val inputData: Data = workDataOf( + Constants.KEY_MESSAGE_ID to messageId, + Constants.KEY_MESSAGE_REASON to reason, + Constants.KEY_MESSAGE_TIMESTAMP to Settings.currentTimestamp() + ) + + val work = OneTimeWorkRequest + .Builder(FailedMessageWorker::class.java) + .setConstraints(constraints) + .setInputData(inputData) + .build() + + WorkManager + .getInstance(context) + .enqueue(work) + + Timber.d("work enqueued with ID [${work.id}] for [FAILED] message with ID [${messageId}]") + } + + internal class SentMessageWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { + override fun doWork(): Result { + val messageId = this.inputData.getString(Constants.KEY_MESSAGE_ID) + val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP) + + Timber.i("[${timestamp}] sending [SENT] message event with ID [${messageId}]") + + if (HttpSmsApiService.create(applicationContext).sendSentEvent(messageId!!, timestamp!!)){ + return Result.success() + } + return Result.retry() + } + } + + internal class FailedMessageWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { + override fun doWork(): Result { + val messageId = this.inputData.getString(Constants.KEY_MESSAGE_ID) + val reason = this.inputData.getString(Constants.KEY_MESSAGE_REASON) + val timestamp = this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP) + + Timber.i("[${timestamp}] sending [FAILED] message event with ID [${messageId}] and reason [$reason]") + + if (HttpSmsApiService.create(applicationContext).sendFailedEvent(messageId!!, timestamp!!, reason!!)){ + return Result.success() + } + return Result.retry() + } + } +} diff --git a/android/app/src/main/java/com/httpsms/Settings.kt b/android/app/src/main/java/com/httpsms/Settings.kt new file mode 100644 index 0000000000000000000000000000000000000000..abf13c59e6762193bbd5161d6d82a2983dbf3197 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/Settings.kt @@ -0,0 +1,380 @@ +package com.httpsms + +import android.content.Context +import android.os.BatteryManager +import androidx.preference.PreferenceManager +import timber.log.Timber +import java.net.URI +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter + +object Settings { + private const val SETTINGS_SIM1_PHONE_NUMBER = "SETTINGS_SIM1_PHONE_NUMBER" + private const val SETTINGS_SIM2_PHONE_NUMBER = "SETTINGS_SIM2_PHONE_NUMBER" + private const val SETTINGS_SIM1_ACTIVE = "SETTINGS_SIM1_ACTIVE_STATUS" + private const val SETTINGS_SIM2_ACTIVE = "SETTINGS_SIM2_ACTIVE_STATUS" + private const val SETTINGS_SIM1_INCOMING_ACTIVE = "SETTINGS_SIM1_INCOMING_ACTIVE" + private const val SETTINGS_SIM2_INCOMING_ACTIVE = "SETTINGS_SIM2_INCOMING_ACTIVE" + private const val SETTINGS_SIM1_INCOMING_CALL_ACTIVE = "SETTINGS_SIM1_INCOMING_CALL_ACTIVE" + private const val SETTINGS_SIM2_INCOMING_CALL_ACTIVE = "SETTINGS_SIM2_INCOMING_CALL_ACTIVE" + private const val SETTINGS_DEBUG_LOG_ENABLED = "SETTINGS_DEBUG_LOG_ENABLED" + private const val SETTINGS_API_KEY = "SETTINGS_API_KEY" + private const val SETTINGS_SERVER_URL = "SETTINGS_SERVER_URL" + private const val SETTINGS_FCM_TOKEN = "SETTINGS_FCM_TOKEN" + private const val SETTINGS_USER_ID = "SETTINGS_USER_ID" + private const val SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP = "SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP" + private const val SETTINGS_HEARTBEAT_TIMESTAMP = "SETTINGS_HEARTBEAT_TIMESTAMP" + private const val SETTINGS_ENCRYPTION_KEY = "SETTINGS_ENCRYPTION_KEY" + private const val SETTINGS_ENCRYPT_RECEIVED_MESSAGES = "SETTINGS_ENCRYPT_RECEIVED_MESSAGES" + + fun getPhoneNumber(context:Context, sim: String): String { + if (sim == Constants.SIM2) { + return getSIM2PhoneNumber(context) + } + return getSIM1PhoneNumber(context) + } + + fun getSIM1PhoneNumber(context: Context): String { + Timber.d(Settings::getSIM1PhoneNumber.name) + + val owner = PreferenceManager + .getDefaultSharedPreferences(context) + .getString(this.SETTINGS_SIM1_PHONE_NUMBER, null) + + if (owner == null) { + Timber.i("cannot get owner from preference [${this.SETTINGS_SIM1_PHONE_NUMBER}]") + return "" + } + + Timber.d("SETTINGS_SIM1_PHONE_NUMBER: [$owner]") + return owner + } + + fun getSIM2PhoneNumber(context: Context): String { + Timber.d(Settings::getSIM2PhoneNumber.name) + + val owner = PreferenceManager + .getDefaultSharedPreferences(context) + .getString(this.SETTINGS_SIM2_PHONE_NUMBER, null) + + if (owner == null) { + Timber.i("cannot get owner from preference [${this.SETTINGS_SIM2_PHONE_NUMBER}]") + return "" + } + + Timber.d("SETTINGS_SIM2_PHONE_NUMBER: [$owner]") + return owner + } + + fun hasOwner(context: Context): Boolean { + return getSIM1PhoneNumber(context) != "" + } + + fun getFcmTokenLastUpdateTimestamp(context: Context): Long { + Timber.d(Settings::getFcmTokenLastUpdateTimestamp.name) + + val timestamp = PreferenceManager + .getDefaultSharedPreferences(context) + .getLong(this.SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP,0) + + Timber.d("SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP: [$timestamp]") + return timestamp + } + + + fun setFcmTokenLastUpdateTimestampAsync(context: Context, timestamp: Long) { + Timber.d(Settings::setFcmTokenLastUpdateTimestampAsync.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putLong(this.SETTINGS_FCM_TOKEN_UPDATE_TIMESTAMP, timestamp) + .apply() + } + + fun setSIM1PhoneNumber(context: Context, owner: String?) { + Timber.d(Settings::setSIM1PhoneNumber.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putString(this.SETTINGS_SIM1_PHONE_NUMBER, owner) + .apply() + } + + fun setSIM2PhoneNumber(context: Context, owner: String?) { + Timber.d(Settings::setSIM2PhoneNumber.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putString(this.SETTINGS_SIM2_PHONE_NUMBER, owner) + .apply() + } + + fun isIncomingMessageEnabled(context: Context, sim: String): Boolean { + var setting = this.SETTINGS_SIM1_INCOMING_ACTIVE + if (sim == Constants.SIM2) { + setting = this.SETTINGS_SIM2_INCOMING_ACTIVE + } + val activeStatus = PreferenceManager + .getDefaultSharedPreferences(context) + .getBoolean(setting,true) + + Timber.d("SETTINGS_${sim}_INCOMING_ACTIVE: [$activeStatus]") + return activeStatus + } + + fun isIncomingCallEventsEnabled(context: Context, sim: String): Boolean { + var setting = this.SETTINGS_SIM1_INCOMING_CALL_ACTIVE + if (sim == Constants.SIM2) { + setting = this.SETTINGS_SIM2_INCOMING_CALL_ACTIVE + } + val activeStatus = PreferenceManager + .getDefaultSharedPreferences(context) + .getBoolean(setting,false) + + Timber.d("SETTINGS_${sim}_INCOMING_CALL_ACTIVE: [$activeStatus]") + return activeStatus + } + + fun setIncomingCallEventsEnabled(context: Context, sim: String, enabled: Boolean) { + var setting = this.SETTINGS_SIM1_INCOMING_CALL_ACTIVE + if (sim == Constants.SIM2) { + setting = this.SETTINGS_SIM2_INCOMING_CALL_ACTIVE + } + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putBoolean(setting, enabled) + .apply() + } + + + fun isDebugLogEnabled(context: Context) : Boolean { + Timber.d(Settings::isDebugLogEnabled.name) + + return PreferenceManager + .getDefaultSharedPreferences(context) + .getBoolean(this.SETTINGS_DEBUG_LOG_ENABLED, false) + } + + fun setDebugLogEnabled(context: Context, status: Boolean) { + Timber.d(Settings::setDebugLogEnabled.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putBoolean(this.SETTINGS_DEBUG_LOG_ENABLED, status) + .apply() + } + + fun setIncomingActiveSIM1(context: Context, status: Boolean) { + Timber.d(Settings::setIncomingActiveSIM1.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putBoolean(this.SETTINGS_SIM1_INCOMING_ACTIVE, status) + .apply() + } + + fun setEncryptReceivedMessages(context: Context, status: Boolean) { + Timber.d(Settings::setEncryptReceivedMessages.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putBoolean(this.SETTINGS_ENCRYPT_RECEIVED_MESSAGES, status) + .apply() + } + + fun encryptReceivedMessages(context: Context): Boolean { + Timber.d(Settings::encryptReceivedMessages.name) + + val encryptReceivedMessages = PreferenceManager + .getDefaultSharedPreferences(context) + .getBoolean(this.SETTINGS_ENCRYPT_RECEIVED_MESSAGES,false) + + Timber.d("SETTINGS_ENCRYPT_RECEIVED_MESSAGES: [$encryptReceivedMessages]") + return encryptReceivedMessages && !getEncryptionKey(context).isNullOrEmpty() + } + + fun setEncryptionKey(context: Context, key: String?) { + Timber.d(Settings::setEncryptionKey.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putString(this.SETTINGS_ENCRYPTION_KEY, key) + .apply() + } + + fun getEncryptionKey(context: Context): String? { + Timber.d(Settings::getEncryptionKey.name) + + return PreferenceManager + .getDefaultSharedPreferences(context) + .getString(this.SETTINGS_ENCRYPTION_KEY, "") + } + + fun setIncomingActiveSIM2(context: Context, status: Boolean) { + Timber.d(Settings::setIncomingActiveSIM2.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putBoolean(this.SETTINGS_SIM2_INCOMING_ACTIVE, status) + .apply() + } + + + fun getActiveStatus(context: Context, sim: String): Boolean { + var setting = this.SETTINGS_SIM1_ACTIVE + if (sim == Constants.SIM2) { + setting = this.SETTINGS_SIM2_ACTIVE + } + var activeStatus = PreferenceManager + .getDefaultSharedPreferences(context) + .getBoolean(setting,true) + + if (sim == Constants.SIM2) { + activeStatus = activeStatus && isDualSIM(context) + } + + Timber.d("SETTINGS_${sim}_ACTIVE: [$activeStatus]") + return activeStatus + } + + fun setActiveStatusAsync(context: Context, status: Boolean, sim: String) { + Timber.d(Settings::setActiveStatusAsync.name) + + var setting = this.SETTINGS_SIM1_ACTIVE + if (sim == Constants.SIM2) { + setting = this.SETTINGS_SIM2_ACTIVE + } + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putBoolean(setting, status) + .apply() + } + + fun isLoggedIn(context: Context): Boolean { + return getApiKey(context) != null && hasOwner(context) + } + + fun isDualSIM(context: Context): Boolean { + return getSIM1PhoneNumber(context) != "" && getSIM2PhoneNumber(context) != "" + } + + private fun getApiKey(context: Context): String?{ + Timber.d(Settings::getApiKey.name) + + val apiKey = PreferenceManager + .getDefaultSharedPreferences(context) + .getString(this.SETTINGS_API_KEY,null) + + Timber.d("SETTINGS_API_KEY: [$apiKey]") + return apiKey + } + + fun getApiKeyOrDefault(context:Context): String { + return getApiKey(context) ?: "" + } + + fun isCharging(context: Context): Boolean { + val myBatteryManager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager + return myBatteryManager.isCharging + } + + fun setUserID(context:Context, userID: String?) { + Timber.d(Settings::setUserID.name) + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putString(this.SETTINGS_USER_ID, userID) + .apply() + } + + // getUserID don't log here as this will create recursion on the LogTail sink + fun getUserID(context:Context): String { + val userID = PreferenceManager + .getDefaultSharedPreferences(context) + .getString(this.SETTINGS_USER_ID,null) + return userID ?: "" + } + + fun getServerUrlOrDefault(context:Context): URI { + val urlString = getServerUrl(context) ?: "https://red-kit-httpsms-gateway.hf.space" + return URI(urlString) + } + + private fun getServerUrl(context: Context): String? { + Timber.d(Settings::getServerUrl.name) + + val serverUrl = PreferenceManager + .getDefaultSharedPreferences(context) + .getString(this.SETTINGS_SERVER_URL,null) + + Timber.d("SETTINGS_SERVER_URL: [$serverUrl]") + return serverUrl + } + + fun setServerUrlAsync(context: Context, serverURL: String?) { + Timber.d(Settings::SETTINGS_SERVER_URL.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putString(this.SETTINGS_SERVER_URL, serverURL) + .apply() + } + + fun setApiKeyAsync(context: Context, apiKey: String?) { + Timber.d(Settings::setApiKeyAsync.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putString(this.SETTINGS_API_KEY, apiKey) + .apply() + } + + fun getFcmToken(context: Context): String?{ + Timber.d(Settings::getFcmToken.name) + + val activeStatus = PreferenceManager + .getDefaultSharedPreferences(context) + .getString(this.SETTINGS_FCM_TOKEN,null) + + Timber.d("SETTINGS_FCM_TOKEN: [$activeStatus]") + return activeStatus + } + + fun setFcmTokenAsync(context: Context, apiKey: String) { + Timber.d(Settings::setApiKeyAsync.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putString(this.SETTINGS_FCM_TOKEN, apiKey) + .apply() + } + + fun getHeartbeatTimestamp(context: Context): Long { + Timber.d(Settings::getHeartbeatTimestamp.name) + + val timestamp = PreferenceManager + .getDefaultSharedPreferences(context) + .getLong(this.SETTINGS_HEARTBEAT_TIMESTAMP,0) + + Timber.d("SETTINGS_HEARTBEAT_TIMESTAMP: [$timestamp]") + return timestamp + } + + fun currentTimestamp(): String { + return DateTimeFormatter.ofPattern(Constants.TIMESTAMP_PATTERN).format( + ZonedDateTime.now(ZoneOffset.UTC) + ).replace("+", "Z") + } + + + fun setHeartbeatTimestampAsync(context: Context, timestamp: Long) { + Timber.d(Settings::setHeartbeatTimestampAsync.name) + + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putLong(this.SETTINGS_HEARTBEAT_TIMESTAMP, timestamp) + .apply() + } +} diff --git a/android/app/src/main/java/com/httpsms/SettingsActivity.kt b/android/app/src/main/java/com/httpsms/SettingsActivity.kt new file mode 100644 index 0000000000000000000000000000000000000000..37a8b3523e2d61f391c54f50688e8e83e71b43a2 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/SettingsActivity.kt @@ -0,0 +1,67 @@ +package com.httpsms + +import android.content.Intent +import android.os.Bundle +import androidx.activity.compose.setContent +import androidx.activity.viewModels +import androidx.appcompat.app.AppCompatActivity +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.httpsms.ui.settings.SettingsScreen +import com.httpsms.ui.settings.SettingsViewModel +import com.httpsms.ui.theme.HttpSmsTheme +import timber.log.Timber + +class SettingsActivity : AppCompatActivity() { + private val viewModel: SettingsViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + viewModel.initialize(this) + + setContent { + HttpSmsTheme { + SettingsScreen( + viewModel = viewModel, + onBackClick = { onBackClicked() }, + onLogoutClick = { onLogoutClick() } + ) + } + } + } + + private fun onBackClicked() { + Timber.d("back button clicked") + redirectToMain() + } + + private fun redirectToMain() { + finish() + val switchActivityIntent = Intent(this, MainActivity::class.java) + startActivity(switchActivityIntent) + } + + private fun onLogoutClick() { + Timber.d("logout button clicked") + MaterialAlertDialogBuilder(this) + .setTitle("Confirm") + .setMessage("Are you sure you want to logout of the httpSMS App?") + .setNeutralButton("Cancel"){ _, _ -> Timber.d("logout dialog canceled") } + .setPositiveButton("Logout"){_, _ -> + Timber.d("logging out user") + viewModel.logout(this) { + redirectToLogin() + } + } + .show() + } + + private fun redirectToLogin():Boolean { + if (Settings.isLoggedIn(this)) { + return false + } + val switchActivityIntent = Intent(this, LoginActivity::class.java) + startActivity(switchActivityIntent) + return true + } +} diff --git a/android/app/src/main/java/com/httpsms/SmsManagerService.kt b/android/app/src/main/java/com/httpsms/SmsManagerService.kt new file mode 100644 index 0000000000000000000000000000000000000000..1236bb54b7ab14f7dee23c3860534add7527c943 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/SmsManagerService.kt @@ -0,0 +1,122 @@ +package com.httpsms + +import android.Manifest +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.telephony.SmsManager +import android.telephony.SubscriptionManager +import androidx.core.app.ActivityCompat +import timber.log.Timber + + +class SmsManagerService { + companion object { + private const val ACTION_SMS_SENT = "SMS_SENT" + private const val ACTION_SMS_DELIVERED = "SMS_DELIVERED" + + fun sentAction(): String { + return "${BuildConfig.APPLICATION_ID}.$ACTION_SMS_SENT" + } + + fun deliveredAction(): String { + return "${BuildConfig.APPLICATION_ID}.$ACTION_SMS_DELIVERED" + } + + fun isDualSIM(context: Context) : Boolean { + if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED + ) { + Timber.w("cannot check if dual sim, no permission") + return false + } + val localSubscriptionManager: SubscriptionManager = if (Build.VERSION.SDK_INT < 31) { + SubscriptionManager.from(context) + } else { + context.getSystemService(SubscriptionManager::class.java) + } + return (localSubscriptionManager.activeSubscriptionInfoList?.size ?: 0) > 1 + } + } + + fun messageParts(context: Context, content: String): ArrayList { + return getSmsManager(context).divideMessage(content) + } + + fun sendMultipartMessage(context: Context, contact: String, parts: ArrayList, sim: String, sendIntents: ArrayList, deliveryIntents: ArrayList) { + runSmsAction(context, sim) { smsManager -> + smsManager.sendMultipartTextMessage(contact, null, parts, sendIntents, deliveryIntents) + } + } + + fun sendTextMessage(context: Context, contact: String, content: String, sim: String, sentIntent: PendingIntent, deliveryIntent: PendingIntent) { + runSmsAction(context, sim) { smsManager -> + smsManager.sendTextMessage(contact, null, content, sentIntent, deliveryIntent) + } + } + + // Wrapper for the smsManager's sendMultimediaMessage + fun sendMultimediaMessage(context: Context, pduUri: android.net.Uri, sim: String, sentIntent: PendingIntent) { + runSmsAction(context, sim) { smsManager -> + smsManager.sendMultimediaMessage(context, pduUri, null, null, sentIntent) + } + } + + private fun runSmsAction(context: Context, sim: String, action: (SmsManager) -> Unit) { + try { + action(getSmsManager(context, sim)) + } catch (e: NullPointerException) { + if (e.isEmergencyNumberBug()) { + Timber.w(e, "Caught EmergencyNumber NPE, falling back to default SmsManager") + action(getDefaultSmsManager(context)) + } else { + throw e + } + } + } + + private fun Throwable.isEmergencyNumberBug(): Boolean { + return this is NullPointerException && this.message?.contains("EmergencyNumber.getNumber()") == true + } + + @Suppress("DEPRECATION") + private fun getDefaultSmsManager(context: Context): SmsManager { + return if (Build.VERSION.SDK_INT >= 31) { + context.getSystemService(SmsManager::class.java) + } else { + SmsManager.getDefault() + } + } + + @Suppress("DEPRECATION") + @SuppressLint("MissingPermission") + private fun getSmsManager(context: Context, sim: String = Constants.SIM1): SmsManager { + val localSubscriptionManager: SubscriptionManager = if (Build.VERSION.SDK_INT < 31) { + SubscriptionManager.from(context) + } else { + context.getSystemService(SubscriptionManager::class.java) + } + + val infoList = localSubscriptionManager.activeSubscriptionInfoList + Timber.d("active subscription info size: [${infoList?.size ?: 0}]") + + val subscriptionId = if (sim == Constants.SIM1 && !infoList.isNullOrEmpty()) { + infoList[0].subscriptionId + } else if (sim == Constants.SIM2 && (infoList?.size ?: 0) > 1) { + infoList!![1].subscriptionId + } else{ + SubscriptionManager.getDefaultSmsSubscriptionId() + } + + if (subscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) { + return getDefaultSmsManager(context) + } + + return if (Build.VERSION.SDK_INT < 31) { + SmsManager.getSmsManagerForSubscriptionId(subscriptionId) + } else { + context.getSystemService(SmsManager::class.java).createForSubscriptionId(subscriptionId) + } + } +} diff --git a/android/app/src/main/java/com/httpsms/receivers/BootReceiver.kt b/android/app/src/main/java/com/httpsms/receivers/BootReceiver.kt new file mode 100644 index 0000000000000000000000000000000000000000..299c3f2456b0c474ef180d354dee9bd72b9f6149 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/receivers/BootReceiver.kt @@ -0,0 +1,31 @@ +package com.httpsms.receivers + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import com.httpsms.Constants +import com.httpsms.Settings +import com.httpsms.services.StickyNotificationService +import timber.log.Timber + + +class BootReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == Intent.ACTION_BOOT_COMPLETED) { + startStickyNotification(context) + } else { + Timber.e("invalid intent [${intent.action}]") + } + } + private fun startStickyNotification(context: Context) { + if(!Settings.getActiveStatus(context, Constants.SIM1) && !Settings.getActiveStatus(context, Constants.SIM2)) { + Timber.d("active status is false, not starting foreground service") + return + } + + Timber.d("starting foreground service") + val notificationIntent = Intent(context, StickyNotificationService::class.java) + val service = context.startForegroundService(notificationIntent) + Timber.d("foreground service started [${service?.className}]") + } +} diff --git a/android/app/src/main/java/com/httpsms/receivers/PhoneStateReceiver.kt b/android/app/src/main/java/com/httpsms/receivers/PhoneStateReceiver.kt new file mode 100644 index 0000000000000000000000000000000000000000..98ea8780075db9be1aea601c997f49a596c4245d --- /dev/null +++ b/android/app/src/main/java/com/httpsms/receivers/PhoneStateReceiver.kt @@ -0,0 +1,174 @@ +package com.httpsms.receivers + +import android.annotation.SuppressLint +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.Build +import android.provider.CallLog +import android.telephony.SubscriptionManager +import android.telephony.TelephonyManager +import androidx.work.Constraints +import androidx.work.Data +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequest +import androidx.work.WorkManager +import androidx.work.Worker +import androidx.work.WorkerParameters +import androidx.work.workDataOf +import com.httpsms.Constants +import com.httpsms.HttpSmsApiService +import com.httpsms.Settings +import timber.log.Timber +import java.time.Instant +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter + + +class PhoneStateReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + Timber.d("onReceive: ${intent.action}") + val stateStr = intent.extras!!.getString(TelephonyManager.EXTRA_STATE) + + @Suppress("DEPRECATION") + val number = intent.extras!!.getString(TelephonyManager.EXTRA_INCOMING_NUMBER) + if (stateStr != "IDLE" || number == null) { + Timber.d("event is not a missed call or permission is not granted state = [${stateStr}]") + return + } + + // Sleep so that the call gets added into the call log + Thread.sleep(200) + + val lastCall = getCallLog(context, number) + if (lastCall == null) { + Timber.d("The call from [${number}] was not a missed call.") + return + } + + handleMissedCallEvent(context, number, lastCall) + } + + private fun handleMissedCallEvent(context: Context, contact: String, callLog: Pair) { + val (timestamp, sim) = callLog + val owner = Settings.getPhoneNumber(context, sim) + + if (!Settings.isLoggedIn(context)) { + Timber.w("[${sim}] user is not logged in") + return + } + + if (!Settings.isIncomingCallEventsEnabled(context, callLog.second)) { + Timber.w("[${sim}] incoming call events is not enabled") + return + } + + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + val inputData: Data = workDataOf( + Constants.KEY_MESSAGE_FROM to contact, + Constants.KEY_MESSAGE_SIM to sim, + Constants.KEY_MESSAGE_TO to owner, + Constants.KEY_MESSAGE_TIMESTAMP to DateTimeFormatter.ofPattern(Constants.TIMESTAMP_PATTERN).format(timestamp).replace("+", "Z") + ) + + val work = OneTimeWorkRequest + .Builder(MissedCallWorker::class.java) + .setConstraints(constraints) + .setInputData(inputData) + .build() + + WorkManager + .getInstance(context) + .enqueue(work) + + Timber.d("work enqueued with ID [${work.id}] for missed phone call from [${contact}] to [${owner}] in [${sim}]") + } + + @SuppressLint("MissingPermission") + private fun getSlotIndexFromSubscriptionId(context: Context, subscriptionId: Int): String { + val localSubscriptionManager: SubscriptionManager = if (Build.VERSION.SDK_INT < 31) { + @Suppress("DEPRECATION") + SubscriptionManager.from(context) + } else { + context.getSystemService(SubscriptionManager::class.java) + } + + var sim = Constants.SIM1 + localSubscriptionManager.activeSubscriptionInfoList!!.forEach { + if (it.subscriptionId == subscriptionId) { + if (it.simSlotIndex > 0){ + sim = Constants.SIM2 + } + } + } + return sim + } + + private fun getCallLog(context: Context, phoneNumber: String): Pair? { + // Specify the columns you want to retrieve from the call log + val projection = arrayOf(CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.TYPE, CallLog.Calls.PHONE_ACCOUNT_ID) + + // Query the call log content provider + val cursor = context.contentResolver.query( + CallLog.Calls.CONTENT_URI, + projection, + null, + null, + CallLog.Calls.DATE + " DESC" // Order by date in descending order + ) + + // Check if the cursor is not null and contains at least one entry + if (cursor != null && cursor.moveToFirst()) { + val number = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER)) + if (number != phoneNumber) { + Timber.w("last phone call has phone number [${number}] but the expected phone number was [${phoneNumber}]") + return null + } + + if (cursor.getInt(cursor.getColumnIndexOrThrow(CallLog.Calls.TYPE)) != CallLog.Calls.MISSED_TYPE) { + Timber.w("last phone call from phone number was [${phoneNumber}] was not a missed call") + return null + } + + val date = cursor.getLong(cursor.getColumnIndexOrThrow(CallLog.Calls.DATE)) + val sim = getSlotIndexFromSubscriptionId(context, cursor.getInt(cursor.getColumnIndexOrThrow(CallLog.Calls.PHONE_ACCOUNT_ID))) + + // Convert date to a readable format (optional) + val dateString = java.text.DateFormat.getDateTimeInstance().format(date) + Timber.d("missed call date is [${dateString}], SIM = [${sim}]") + + // Close the cursor to free up resources + cursor.close() + + // Construct a string representing the last call + return Pair(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneOffset.UTC), sim) + } + + // Close the cursor if it's not null even if it doesn't contain any data + cursor?.close() + + // Return null if no calls are found + return null + } + + internal class MissedCallWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { + override fun doWork(): Result { + Timber.i("[${this.inputData.getString(Constants.KEY_MESSAGE_SIM)}] forwarding missed call from [${this.inputData.getString(Constants.KEY_MESSAGE_FROM)}] to [${this.inputData.getString(Constants.KEY_MESSAGE_TO)}]") + + if (HttpSmsApiService.create(applicationContext).sendMissedCallEvent( + this.inputData.getString(Constants.KEY_MESSAGE_SIM)!!, + this.inputData.getString(Constants.KEY_MESSAGE_FROM)!!, + this.inputData.getString(Constants.KEY_MESSAGE_TO)!!, + this.inputData.getString(Constants.KEY_MESSAGE_TIMESTAMP)!!, + )) { + return Result.success() + } + + return Result.retry() + } + } +} diff --git a/android/app/src/main/java/com/httpsms/services/StickyNotificationService.kt b/android/app/src/main/java/com/httpsms/services/StickyNotificationService.kt new file mode 100644 index 0000000000000000000000000000000000000000..a2be58a345593408806d3197d53fa4b7c6a8451b --- /dev/null +++ b/android/app/src/main/java/com/httpsms/services/StickyNotificationService.kt @@ -0,0 +1,75 @@ +package com.httpsms.services + +import android.app.* +import android.content.Context +import android.content.Intent +import android.os.IBinder +import android.widget.Toast +import com.httpsms.MainActivity +import com.httpsms.R +import timber.log.Timber + +class StickyNotificationService: Service() { + override fun onBind(intent: Intent?): IBinder? { + Timber.d("Some component want to bind with the service [${intent?.action}]") + return null + } + + override fun onCreate() { + Timber.d("The service has been created") + super.onCreate() + val notification = createNotification() + startForeground(1, notification) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + Timber.d("onStartCommand executed with startId: $startId") + // by returning this we make sure the service is restarted if the system kills the service + return START_STICKY + } + + override fun onDestroy() { + super.onDestroy() + Timber.d("The service has been destroyed") + Toast.makeText(this, "Service destroyed", Toast.LENGTH_SHORT).show() + } + + + private fun createNotification(): Notification { + val notificationChannelId = "sticky_notification_channel" + + // depending on the Android API that we're dealing with we will have + // to use a specific method to create the notification + val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val channel = NotificationChannel( + notificationChannelId, + notificationChannelId, + NotificationManager.IMPORTANCE_HIGH + ).apply { + enableVibration(false) + setShowBadge(false) + } + notificationManager.createNotificationChannel(channel) + + val pendingIntent: PendingIntent = Intent(this, MainActivity::class.java).let { + notificationIntent -> PendingIntent.getActivity( + this, + 0, + notificationIntent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + } + + val builder: Notification.Builder = Notification.Builder( + this, + notificationChannelId + ) + + return builder + .setContentTitle("httpSMS Listener") + .setContentText("httpSMS is listening for sent and received SMS messages in the background.") + .setContentIntent(pendingIntent) + .setOngoing(true) + .setSmallIcon(R.drawable.ic_stat_name) + .build() + } +} diff --git a/android/app/src/main/java/com/httpsms/ui/login/LoginActivityContent.kt b/android/app/src/main/java/com/httpsms/ui/login/LoginActivityContent.kt new file mode 100644 index 0000000000000000000000000000000000000000..0fc5e4c9d5a86c2c097223a2b7758f9b0cfcb1ab --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ui/login/LoginActivityContent.kt @@ -0,0 +1,217 @@ +package com.httpsms.ui.login + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.ClickableText +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.QrCodeScanner +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.httpsms.R +import com.httpsms.ui.theme.Blue500 +import com.httpsms.ui.theme.Pink500 + +@Composable +fun LoginScreen( + viewModel: LoginViewModel, + onQrScanClick: () -> Unit, + onLoginClick: () -> Unit +) { + val uiState by viewModel.uiState.collectAsState() + val uriHandler = LocalUriHandler.current + + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(16.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Spacer(modifier = Modifier.height(64.dp)) + + Image( + painter = painterResource(id = R.drawable.logo_cropped), + contentDescription = stringResource(id = R.string.img_http_sms_logo), + modifier = Modifier.size(100.dp) + ) + + Spacer(modifier = Modifier.height(32.dp)) + + val annotatedString = buildAnnotatedString { + val text = stringResource(id = R.string.get_your_api_key) + val linkText = "httpsms.com/settings" + val startIndex = text.indexOf(linkText) + + if (startIndex >= 0) { + append(text.substring(0, startIndex)) + + pushStringAnnotation(tag = "URL", annotation = "https://httpsms.com/settings") + withStyle(style = SpanStyle(color = Blue500, fontWeight = FontWeight.Bold)) { + append(linkText) + } + pop() + + append(text.substring(startIndex + linkText.length)) + } else { + append(text) + } + } + + ClickableText( + text = annotatedString, + onClick = { offset -> + annotatedString.getStringAnnotations(tag = "URL", start = offset, end = offset) + .firstOrNull()?.let { annotation -> + uriHandler.openUri(annotation.item) + } + }, + style = MaterialTheme.typography.bodyLarge.copy( + textAlign = TextAlign.Center, + fontSize = 20.sp, + lineHeight = 28.sp, + color = MaterialTheme.colorScheme.onBackground + ), + modifier = Modifier.fillMaxWidth() + ) + + Spacer(modifier = Modifier.height(24.dp)) + + OutlinedTextField( + value = uiState.apiKey, + onValueChange = { viewModel.onApiKeyChange(it) }, + label = { Text(stringResource(id = R.string.text_area_api_key)) }, + modifier = Modifier.fillMaxWidth(), + isError = uiState.apiKeyError != null, + supportingText = uiState.apiKeyError?.let { { Text(it) } }, + trailingIcon = { + IconButton(onClick = onQrScanClick) { + Icon( + imageVector = Icons.Default.QrCodeScanner, + contentDescription = "Scan QR Code" + ) + } + }, + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Text, + imeAction = ImeAction.Done + ), + enabled = !uiState.isLoading + ) + + Spacer(modifier = Modifier.height(8.dp)) + + OutlinedTextField( + value = uiState.phoneNumberSIM1, + onValueChange = { viewModel.onPhoneNumberSIM1Change(it) }, + label = { Text(stringResource(id = R.string.login_phone_number_sim1)) }, + placeholder = { Text(stringResource(id = R.string.login_phone_number_hint)) }, + modifier = Modifier.fillMaxWidth(), + isError = uiState.phoneNumberSIM1Error != null, + supportingText = uiState.phoneNumberSIM1Error?.let { { Text(it) } }, + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Phone, + imeAction = ImeAction.Done + ), + enabled = !uiState.isLoading + ) + + if (uiState.isDualSim) { + Spacer(modifier = Modifier.height(8.dp)) + OutlinedTextField( + value = uiState.phoneNumberSIM2, + onValueChange = { viewModel.onPhoneNumberSIM2Change(it) }, + label = { Text(stringResource(id = R.string.login_phone_number_sim2)) }, + placeholder = { Text(stringResource(id = R.string.login_phone_number_hint)) }, + modifier = Modifier.fillMaxWidth(), + isError = uiState.phoneNumberSIM2Error != null, + supportingText = uiState.phoneNumberSIM2Error?.let { { Text(it) } }, + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Phone, + imeAction = ImeAction.Done + ), + enabled = !uiState.isLoading + ) + } + + Spacer(modifier = Modifier.height(8.dp)) + + OutlinedTextField( + value = uiState.serverUrl, + onValueChange = { viewModel.onServerUrlChange(it) }, + label = { Text(stringResource(id = R.string.server_url)) }, + placeholder = { Text(stringResource(id = R.string.login_server_url_hint)) }, + modifier = Modifier.fillMaxWidth(), + isError = uiState.serverUrlError != null, + supportingText = uiState.serverUrlError?.let { { Text(it) } }, + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Uri, + imeAction = ImeAction.Done + ), + enabled = !uiState.isLoading + ) + + Spacer(modifier = Modifier.height(16.dp)) + + Button( + onClick = onLoginClick, + enabled = !uiState.isLoading, + modifier = Modifier.align(Alignment.CenterHorizontally), + colors = ButtonDefaults.buttonColors(containerColor = Blue500), + contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp) + ) { + Icon( + painter = painterResource(id = R.drawable.ic_login), + contentDescription = null, + modifier = Modifier.padding(end = 8.dp), + tint = Color.White + ) + Text( + text = stringResource(id = R.string.sign_in_button), + color = Color.White, + fontSize = 18.sp + ) + } + + if (uiState.isLoading) { + Spacer(modifier = Modifier.height(16.dp)) + CircularProgressIndicator( + modifier = Modifier.size(24.dp), + color = Pink500 + ) + } + } +} diff --git a/android/app/src/main/java/com/httpsms/ui/login/LoginViewModel.kt b/android/app/src/main/java/com/httpsms/ui/login/LoginViewModel.kt new file mode 100644 index 0000000000000000000000000000000000000000..a4803e41ef778ee7ce32760f5ec279fe87234bea --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ui/login/LoginViewModel.kt @@ -0,0 +1,221 @@ +package com.httpsms.ui.login + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.telephony.SubscriptionManager +import android.telephony.TelephonyManager +import android.webkit.URLUtil +import androidx.core.content.ContextCompat +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.httpsms.Constants +import com.httpsms.HttpSmsApiService +import com.httpsms.Settings +import com.httpsms.SmsManagerService +import com.httpsms.validators.PhoneNumberValidator +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import timber.log.Timber +import java.net.URI +import java.net.URISyntaxException + +data class LoginUiState( + val apiKey: String = "", + val phoneNumberSIM1: String = "", + val phoneNumberSIM2: String = "", + val serverUrl: String = "", + val isLoading: Boolean = false, + val apiKeyError: String? = null, + val phoneNumberSIM1Error: String? = null, + val phoneNumberSIM2Error: String? = null, + val serverUrlError: String? = null, + val isDualSim: Boolean = false, + val loginSuccess: Boolean = false +) + +class LoginViewModel : ViewModel() { + private val _uiState = MutableStateFlow(LoginUiState()) + val uiState = _uiState.asStateFlow() + + fun initialize(context: Context, defaultServerUrl: String) { + val isDualSim = SmsManagerService.isDualSIM(context) + val phoneNumberSIM1 = Settings.getSIM1PhoneNumber(context) + val phoneNumberSIM2 = Settings.getSIM2PhoneNumber(context) + + _uiState.value = _uiState.value.copy( + isDualSim = isDualSim, + phoneNumberSIM1 = phoneNumberSIM1, + phoneNumberSIM2 = phoneNumberSIM2, + serverUrl = defaultServerUrl + ) + + // Try to auto-detect if fields are empty + if (phoneNumberSIM1.isEmpty() || (isDualSim && phoneNumberSIM2.isEmpty())) { + autoDetectPhoneNumbers(context) + } + } + + fun autoDetectPhoneNumbers(context: Context) { + if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { + Timber.d("READ_PHONE_STATE permission not granted for auto-detecting phone numbers") + return + } + + val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + + var detectedSIM1 = _uiState.value.phoneNumberSIM1 + var detectedSIM2 = _uiState.value.phoneNumberSIM2 + + try { + val subscriptionManager = if (Build.VERSION.SDK_INT >= 31) { + context.getSystemService(SubscriptionManager::class.java) + } else { + SubscriptionManager.from(context) + } + + val activeSubscriptions = try { subscriptionManager.activeSubscriptionInfoList } catch (e: Exception) { null } + + if (detectedSIM1.isEmpty()) { + val line1Number = try { telephonyManager.line1Number } catch (e: Exception) { null } + if (!line1Number.isNullOrEmpty()) { + detectedSIM1 = line1Number + } else if (activeSubscriptions != null && activeSubscriptions.isNotEmpty()) { + detectedSIM1 = activeSubscriptions[0].number ?: "" + } + } + + if (detectedSIM2.isEmpty() && activeSubscriptions != null && activeSubscriptions.size >= 2) { + detectedSIM2 = activeSubscriptions[1].number ?: "" + } + + Timber.d("Auto-detected numbers - SIM1: $detectedSIM1, SIM2: $detectedSIM2") + + } catch (e: SecurityException) { + Timber.e(e, "Security exception while auto-detecting phone numbers") + } + + _uiState.value = _uiState.value.copy( + phoneNumberSIM1 = detectedSIM1, + phoneNumberSIM2 = detectedSIM2, + isDualSim = SmsManagerService.isDualSIM(context) + ) + } + + fun onApiKeyChange(value: String) { + _uiState.value = _uiState.value.copy(apiKey = value, apiKeyError = null) + } + + fun onPhoneNumberSIM1Change(value: String) { + _uiState.value = _uiState.value.copy(phoneNumberSIM1 = value, phoneNumberSIM1Error = null) + } + + fun onPhoneNumberSIM2Change(value: String) { + _uiState.value = _uiState.value.copy(phoneNumberSIM2 = value, phoneNumberSIM2Error = null) + } + + fun onServerUrlChange(value: String) { + _uiState.value = _uiState.value.copy(serverUrl = value, serverUrlError = null) + } + + fun login(context: Context, countryCode: String, onGooglePlayServicesError: (String) -> Unit, onFcmTokenMissing: () -> Unit) { + val currentState = _uiState.value + + // Validation logic from LoginActivity.onLoginClick + if (Settings.getFcmToken(context) == null) { + onFcmTokenMissing() + return + } + + _uiState.value = currentState.copy(isLoading = true) + + viewModelScope.launch { + val apiKey = currentState.apiKey.trim() + val serverUrl = currentState.serverUrl.trim() + val phone1 = currentState.phoneNumberSIM1.trim() + val phone2 = currentState.phoneNumberSIM2.trim() + + if (!PhoneNumberValidator.isValidPhoneNumber(phone1, countryCode)) { + _uiState.value = _uiState.value.copy( + isLoading = false, + phoneNumberSIM1Error = "Enter an international phone number in the E.164 format" + ) + return@launch + } + + if (currentState.isDualSim && !PhoneNumberValidator.isValidPhoneNumber(phone2, countryCode)) { + _uiState.value = _uiState.value.copy( + isLoading = false, + phoneNumberSIM2Error = "Enter an international phone number in the E.164 format" + ) + return@launch + } + + if (!URLUtil.isValidUrl(serverUrl)) { + _uiState.value = _uiState.value.copy( + isLoading = false, + serverUrlError = "Server URL [$serverUrl] is invalid" + ) + return@launch + } + + if (!URLUtil.isHttpsUrl(serverUrl)) { + _uiState.value = _uiState.value.copy( + isLoading = false, + serverUrlError = "Server URL [$serverUrl] must be HTTPS" + ) + return@launch + } + + val authResult = try { + withContext(Dispatchers.IO) { + val service = HttpSmsApiService(apiKey, URI(serverUrl)) + val e164Phone1 = PhoneNumberValidator.formatE164(phone1, countryCode) + val response1 = service.updateFcmToken(e164Phone1, Constants.SIM1, Settings.getFcmToken(context) ?: "") + + if (response1.second != null || response1.third != null) { + return@withContext Pair(response1.second, response1.third) + } + + if (currentState.isDualSim) { + val e164Phone2 = PhoneNumberValidator.formatE164(phone2, countryCode) + val response2 = service.updateFcmToken(e164Phone2, Constants.SIM2, Settings.getFcmToken(context) ?: "") + return@withContext Pair(response2.second, response2.third) + } + + Pair(null, null) + } + } catch (e: URISyntaxException) { + Timber.e(e, "Invalid URI: $serverUrl") + Pair(null, "Server URL [$serverUrl] is invalid") + } catch (e: Exception) { + Timber.e(e, "Login error") + Pair(null, "An unexpected error occurred: ${e.message}") + } + + if (authResult.first != null) { + _uiState.value = _uiState.value.copy(isLoading = false, apiKeyError = authResult.first) + return@launch + } + + if (authResult.second != null) { + _uiState.value = _uiState.value.copy(isLoading = false, serverUrlError = authResult.second) + return@launch + } + + // Save settings + Settings.setApiKeyAsync(context, apiKey) + Settings.setServerUrlAsync(context, serverUrl) + Settings.setSIM1PhoneNumber(context, PhoneNumberValidator.formatE164(phone1, countryCode)) + if (currentState.isDualSim) { + Settings.setSIM2PhoneNumber(context, PhoneNumberValidator.formatE164(phone2, countryCode)) + } + + _uiState.value = _uiState.value.copy(isLoading = false, loginSuccess = true) + } + } +} diff --git a/android/app/src/main/java/com/httpsms/ui/main/MainActivityContent.kt b/android/app/src/main/java/com/httpsms/ui/main/MainActivityContent.kt new file mode 100644 index 0000000000000000000000000000000000000000..087bf7921c66a2b5fd313f1b13039adc9e4014c6 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ui/main/MainActivityContent.kt @@ -0,0 +1,243 @@ +package com.httpsms.ui.main + +import android.telephony.PhoneNumberUtils +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.BatteryAlert +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Favorite +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.httpsms.R +import com.httpsms.ui.theme.Blue500 +import com.httpsms.ui.theme.Pink500 +import java.util.Locale + +@Composable +fun MainScreen( + viewModel: MainViewModel, + onSettingsClick: () -> Unit, + onSmsPermissionClick: () -> Unit, + onBatteryOptimizationClick: () -> Unit, + onHeartbeatClick: () -> Unit +) { + val uiState by viewModel.uiState.collectAsState() + + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(16.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Spacer(modifier = Modifier.height(64.dp)) + + Image( + painter = painterResource(id = R.drawable.logo_cropped), + contentDescription = stringResource(id = R.string.img_http_sms_logo), + modifier = Modifier + .width(147.dp) + .height(92.dp) + ) + + Spacer(modifier = Modifier.height(24.dp)) + + PhoneCard( + phoneNumber = uiState.phoneNumberSIM1, + isActive = uiState.isActiveSIM1, + refreshTime = uiState.lastHeartbeatTime + ) + + if (uiState.isDualSim) { + Spacer(modifier = Modifier.height(24.dp)) + PhoneCard( + phoneNumber = uiState.phoneNumberSIM2, + isActive = uiState.isActiveSIM2, + refreshTime = uiState.lastHeartbeatTime + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + + if (!uiState.isSmsPermissionGranted || !uiState.isBatteryOptimizationDisabled) { + Column(modifier = Modifier.fillMaxWidth()) { + if (!uiState.isSmsPermissionGranted) { + Button( + onClick = onSmsPermissionClick, + modifier = Modifier.align(Alignment.CenterHorizontally), + colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4CAF50)), + contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp) + ) { + Text( + stringResource(id = R.string.enable_sms_permission), + color = Color.White, + fontSize = 18.sp + ) + Spacer(modifier = Modifier.width(8.dp)) + Icon( + painter = painterResource(id = R.drawable.open_in_new_24), + contentDescription = null, + tint = Color.White + ) + } + Spacer(modifier = Modifier.height(8.dp)) + } + + if (!uiState.isBatteryOptimizationDisabled) { + Button( + onClick = onBatteryOptimizationClick, + modifier = Modifier.align(Alignment.CenterHorizontally), + colors = ButtonDefaults.buttonColors(containerColor = Pink500), + contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp) + ) { + Icon( + imageVector = Icons.Default.BatteryAlert, + contentDescription = null, + tint = Color.White + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + stringResource(id = R.string.disable_battery_optimization), + color = Color.White, + fontSize = 18.sp + ) + } + } + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + Column( + modifier = Modifier.width(IntrinsicSize.Max), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Button( + onClick = onHeartbeatClick, + modifier = Modifier.fillMaxWidth(), + enabled = !uiState.isHeartbeatLoading, + colors = ButtonDefaults.buttonColors(containerColor = Blue500), + contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp) + ) { + Icon( + imageVector = Icons.Default.Favorite, + contentDescription = null, + tint = if (uiState.isHeartbeatLoading) LocalContentColor.current else Pink500 + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + stringResource(id = R.string.send_heartbeat), + color = Color.White, + fontSize = 18.sp + ) + } + + if (uiState.isHeartbeatLoading) { + LinearProgressIndicator( + modifier = Modifier + .fillMaxWidth() + .padding(top = 4.dp), + color = Pink500 + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + Text( + text = uiState.appVersion, + fontSize = 14.sp, + color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f) + ) + + Spacer(modifier = Modifier.weight(1f)) + Spacer(modifier = Modifier.height(16.dp)) + + Button( + onClick = onSettingsClick, + colors = ButtonDefaults.buttonColors(containerColor = Color.Black), + contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp) + ) { + Icon(Icons.Default.Settings, contentDescription = null, tint = Color.White) + Spacer(modifier = Modifier.width(8.dp)) + Text( + stringResource(id = R.string.main_app_settings), + color = Color.White, + fontSize = 18.sp + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + } +} + +@Composable +fun PhoneCard( + phoneNumber: String, + isActive: Boolean, + refreshTime: String +) { + Card( + modifier = Modifier.fillMaxWidth(), + elevation = CardDefaults.cardElevation(defaultElevation = 8.dp) + ) { + Column(modifier = Modifier.padding(16.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = PhoneNumberUtils.formatNumber(phoneNumber, Locale.getDefault().country) ?: phoneNumber, + fontSize = 28.sp, + fontWeight = FontWeight.Medium, + modifier = Modifier.weight(1f), + color = MaterialTheme.colorScheme.onSurface + ) + if (isActive) { + Icon( + imageVector = Icons.Default.CheckCircle, + contentDescription = "Active", + tint = Color(0xFF70AB5C), + modifier = Modifier.size(24.dp) + ) + } + } + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = refreshTime, + fontSize = 16.sp, + color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f) + ) + } + } +} diff --git a/android/app/src/main/java/com/httpsms/ui/main/MainViewModel.kt b/android/app/src/main/java/com/httpsms/ui/main/MainViewModel.kt new file mode 100644 index 0000000000000000000000000000000000000000..273cfe7865840bb513726d232b1e8973e3a30d0c --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ui/main/MainViewModel.kt @@ -0,0 +1,116 @@ +package com.httpsms.ui.main + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.os.PowerManager +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.httpsms.Constants +import com.httpsms.HttpSmsApiService +import com.httpsms.Settings +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import timber.log.Timber +import java.time.Instant +import java.time.ZoneId +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter + +data class MainUiState( + val phoneNumberSIM1: String = "", + val isActiveSIM1: Boolean = false, + val phoneNumberSIM2: String = "", + val isActiveSIM2: Boolean = false, + val isDualSim: Boolean = false, + val lastHeartbeatTime: String = "--", + val isSmsPermissionGranted: Boolean = true, + val isBatteryOptimizationDisabled: Boolean = true, + val isHeartbeatLoading: Boolean = false, + val appVersion: String = "" +) + +class MainViewModel : ViewModel() { + private val _uiState = MutableStateFlow(MainUiState()) + val uiState = _uiState.asStateFlow() + + fun initialize(context: Context, appVersion: String) { + updateState(context, appVersion) + } + + fun updateState(context: Context, appVersion: String) { + val isDualSim = Settings.isDualSIM(context) + val phone1 = Settings.getSIM1PhoneNumber(context) ?: "" + val active1 = Settings.getActiveStatus(context, Constants.SIM1) + val phone2 = Settings.getSIM2PhoneNumber(context) ?: "" + val active2 = Settings.getActiveStatus(context, Constants.SIM2) + + val timestamp = Settings.getHeartbeatTimestamp(context) + val lastHeartbeat = if (timestamp == 0L) { + "--" + } else { + val timestampZdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC) + val localTime = timestampZdt.withZoneSameInstant(ZoneId.systemDefault()) + localTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + } + + val smsPermissions = arrayOf( + Manifest.permission.SEND_SMS, + Manifest.permission.RECEIVE_SMS, + Manifest.permission.READ_SMS + ) + val allGranted = smsPermissions.all { + context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED + } + + val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager + val batteryOptimized = pm.isIgnoringBatteryOptimizations(context.packageName) + + _uiState.value = _uiState.value.copy( + phoneNumberSIM1 = phone1, + isActiveSIM1 = active1, + phoneNumberSIM2 = phone2, + isActiveSIM2 = active2, + isDualSim = isDualSim, + lastHeartbeatTime = lastHeartbeat, + isSmsPermissionGranted = allGranted, + isBatteryOptimizationDisabled = batteryOptimized, + appVersion = appVersion + ) + } + + fun sendHeartbeat(context: Context, onComplete: (String?) -> Unit) { + _uiState.value = _uiState.value.copy(isHeartbeatLoading = true) + + viewModelScope.launch { + val result = withContext(Dispatchers.IO) { + val charging = Settings.isCharging(context) + try { + val phoneNumbers = mutableListOf() + phoneNumbers.add(Settings.getSIM1PhoneNumber(context)) + if (Settings.getActiveStatus(context, Constants.SIM2)) { + phoneNumbers.add(Settings.getSIM2PhoneNumber(context)) + } + val isStored = HttpSmsApiService.create(context).storeHeartbeat(phoneNumbers.toTypedArray(), charging) + if (!isStored) { + "Could not send heartbeat make sure the phone is connected to the internet" + } else { + Settings.setHeartbeatTimestampAsync(context, System.currentTimeMillis()) + null + } + } catch (exception: Exception) { + Timber.e(exception) + exception.javaClass.simpleName + } + } + + _uiState.value = _uiState.value.copy(isHeartbeatLoading = false) + updateState(context, _uiState.value.appVersion) + onComplete(result) + } + } +} diff --git a/android/app/src/main/java/com/httpsms/ui/settings/SettingsActivityContent.kt b/android/app/src/main/java/com/httpsms/ui/settings/SettingsActivityContent.kt new file mode 100644 index 0000000000000000000000000000000000000000..3335eb2c285bcb4a65a0785b18048e232416cfb1 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ui/settings/SettingsActivityContent.kt @@ -0,0 +1,221 @@ +package com.httpsms.ui.settings + +import android.app.Activity +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.Logout +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.core.view.WindowCompat +import com.httpsms.R +import com.httpsms.ui.theme.LogoGreen + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen( + viewModel: SettingsViewModel, + onBackClick: () -> Unit, + onLogoutClick: () -> Unit +) { + val uiState by viewModel.uiState.collectAsState() + val context = LocalContext.current + val isDarkTheme = isSystemInDarkTheme() + val primaryColor = if (isDarkTheme) Color.Black else LogoGreen + + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + val window = (view.context as Activity).window + window.statusBarColor = primaryColor.toArgb() + WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = false + } + } + + Scaffold( + topBar = { + TopAppBar( + title = { Text("App Settings") }, + navigationIcon = { + IconButton(onClick = onBackClick) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = primaryColor, + titleContentColor = Color.White, + navigationIconContentColor = Color.White + ) + ) + } + ) { paddingValues -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(paddingValues) + .verticalScroll(rememberScrollState()) + .padding(16.dp) + ) { + // SIM 1 Settings + OutlinedTextField( + value = uiState.phoneNumberSIM1, + onValueChange = { }, + label = { Text(stringResource(id = R.string.settings_sim1)) }, + modifier = Modifier.fillMaxWidth(), + enabled = false + ) + + SwitchSetting( + text = stringResource(id = R.string.settings_outgoing_messages_sim1), + checked = uiState.isActiveSIM1, + onCheckedChange = { viewModel.setActiveSIM1(context, it) } + ) + + SwitchSetting( + text = stringResource(id = R.string.settings_incoming_messages_sim1), + checked = uiState.isIncomingSIM1Enabled, + onCheckedChange = { viewModel.setIncomingSIM1Enabled(context, it) } + ) + + SwitchSetting( + text = stringResource(id = R.string.enable_incoming_call_events_sim1), + checked = uiState.isIncomingCallEventsSIM1Enabled, + onCheckedChange = { viewModel.setIncomingCallEventsSIM1Enabled(context, it) } + ) + + if (uiState.isDualSim) { + Spacer(modifier = Modifier.height(16.dp)) + // SIM 2 Settings + OutlinedTextField( + value = uiState.phoneNumberSIM2, + onValueChange = { }, + label = { Text(stringResource(id = R.string.settings_sim_2)) }, + modifier = Modifier.fillMaxWidth(), + enabled = false + ) + + SwitchSetting( + text = stringResource(id = R.string.settings_outgoing_messages_sim2), + checked = uiState.isActiveSIM2, + onCheckedChange = { viewModel.setActiveSIM2(context, it) } + ) + + SwitchSetting( + text = stringResource(id = R.string.settings_incoming_messages_sim2), + checked = uiState.isIncomingSIM2Enabled, + onCheckedChange = { viewModel.setIncomingSIM2Enabled(context, it) } + ) + + SwitchSetting( + text = stringResource(id = R.string.enable_sim2_incoming_call_events), + checked = uiState.isIncomingCallEventsSIM2Enabled, + onCheckedChange = { viewModel.setIncomingCallEventsSIM2Enabled(context, it) } + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + + OutlinedTextField( + value = uiState.encryptionKey, + onValueChange = { viewModel.setEncryptionKey(context, it) }, + label = { Text(stringResource(id = R.string.encryption_key)) }, + modifier = Modifier.fillMaxWidth() + ) + + SwitchSetting( + text = stringResource(id = R.string.encrypt_received_messages), + checked = uiState.isEncryptReceivedMessagesEnabled, + onCheckedChange = { viewModel.setEncryptReceivedMessagesEnabled(context, it) }, + enabled = uiState.encryptionKey.isNotEmpty() + ) + + SwitchSetting( + text = stringResource(id = R.string.enable_debug_logs), + checked = uiState.isDebugLogEnabled, + onCheckedChange = { viewModel.setDebugLogEnabled(context, it) } + ) + + Spacer(modifier = Modifier.height(24.dp)) + + Button( + onClick = onLogoutClick, + modifier = Modifier.align(Alignment.CenterHorizontally), + colors = ButtonDefaults.buttonColors(containerColor = Color.Black), + contentPadding = PaddingValues(horizontal = 32.dp, vertical = 16.dp) + ) { + Icon( + imageVector = Icons.AutoMirrored.Filled.Logout, + contentDescription = null, + tint = Color.White + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + stringResource(id = R.string.main_log_out), + color = Color.White, + fontSize = 18.sp + ) + } + } + } +} + +@Composable +fun SwitchSetting( + text: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + enabled: Boolean = true +) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = text, + modifier = Modifier.weight(1f), + fontSize = 18.sp, + color = if (enabled) MaterialTheme.colorScheme.onBackground else MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f) + ) + Switch( + checked = checked, + onCheckedChange = onCheckedChange, + enabled = enabled + ) + } +} diff --git a/android/app/src/main/java/com/httpsms/ui/settings/SettingsViewModel.kt b/android/app/src/main/java/com/httpsms/ui/settings/SettingsViewModel.kt new file mode 100644 index 0000000000000000000000000000000000000000..33a23e57498ed5fcf0b9c3c49e2e121341fc4f83 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ui/settings/SettingsViewModel.kt @@ -0,0 +1,114 @@ +package com.httpsms.ui.settings + +import android.content.Context +import androidx.lifecycle.ViewModel +import com.httpsms.Constants +import com.httpsms.Settings +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow + +data class SettingsUiState( + val isDebugLogEnabled: Boolean = false, + val phoneNumberSIM1: String = "", + val isIncomingSIM1Enabled: Boolean = false, + val isActiveSIM1: Boolean = false, + val isIncomingCallEventsSIM1Enabled: Boolean = false, + val isDualSim: Boolean = false, + val phoneNumberSIM2: String = "", + val isIncomingSIM2Enabled: Boolean = false, + val isActiveSIM2: Boolean = false, + val isIncomingCallEventsSIM2Enabled: Boolean = false, + val encryptionKey: String = "", + val isEncryptReceivedMessagesEnabled: Boolean = false +) + +class SettingsViewModel : ViewModel() { + private val _uiState = MutableStateFlow(SettingsUiState()) + val uiState = _uiState.asStateFlow() + + fun initialize(context: Context) { + _uiState.value = SettingsUiState( + isDebugLogEnabled = Settings.isDebugLogEnabled(context), + phoneNumberSIM1 = Settings.getSIM1PhoneNumber(context) ?: "", + isIncomingSIM1Enabled = Settings.isIncomingMessageEnabled(context, Constants.SIM1), + isActiveSIM1 = Settings.getActiveStatus(context, Constants.SIM1), + isIncomingCallEventsSIM1Enabled = Settings.isIncomingCallEventsEnabled(context, Constants.SIM1), + isDualSim = Settings.isDualSIM(context), + phoneNumberSIM2 = Settings.getSIM2PhoneNumber(context) ?: "", + isIncomingSIM2Enabled = Settings.isIncomingMessageEnabled(context, Constants.SIM2), + isActiveSIM2 = Settings.getActiveStatus(context, Constants.SIM2), + isIncomingCallEventsSIM2Enabled = Settings.isIncomingCallEventsEnabled(context, Constants.SIM2), + encryptionKey = Settings.getEncryptionKey(context) ?: "", + isEncryptReceivedMessagesEnabled = Settings.encryptReceivedMessages(context) + ) + } + + fun setDebugLogEnabled(context: Context, enabled: Boolean) { + Settings.setDebugLogEnabled(context, enabled) + _uiState.value = _uiState.value.copy(isDebugLogEnabled = enabled) + } + + fun setIncomingSIM1Enabled(context: Context, enabled: Boolean) { + Settings.setIncomingActiveSIM1(context, enabled) + _uiState.value = _uiState.value.copy(isIncomingSIM1Enabled = enabled) + } + + fun setActiveSIM1(context: Context, enabled: Boolean) { + Settings.setActiveStatusAsync(context, enabled, Constants.SIM1) + _uiState.value = _uiState.value.copy(isActiveSIM1 = enabled) + } + + fun setIncomingCallEventsSIM1Enabled(context: Context, enabled: Boolean) { + Settings.setIncomingCallEventsEnabled(context, Constants.SIM1, enabled) + _uiState.value = _uiState.value.copy(isIncomingCallEventsSIM1Enabled = enabled) + } + + fun setIncomingSIM2Enabled(context: Context, enabled: Boolean) { + Settings.setIncomingActiveSIM2(context, enabled) + _uiState.value = _uiState.value.copy(isIncomingSIM2Enabled = enabled) + } + + fun setActiveSIM2(context: Context, enabled: Boolean) { + Settings.setActiveStatusAsync(context, enabled, Constants.SIM2) + _uiState.value = _uiState.value.copy(isActiveSIM2 = enabled) + } + + fun setIncomingCallEventsSIM2Enabled(context: Context, enabled: Boolean) { + Settings.setIncomingCallEventsEnabled(context, Constants.SIM2, enabled) + _uiState.value = _uiState.value.copy(isIncomingCallEventsSIM2Enabled = enabled) + } + + fun setEncryptionKey(context: Context, key: String) { + val trimmedKey = key.trim() + if (trimmedKey.isEmpty()) { + Settings.setEncryptionKey(context, null) + Settings.setEncryptReceivedMessages(context, false) + _uiState.value = _uiState.value.copy(encryptionKey = "", isEncryptReceivedMessagesEnabled = false) + } else { + Settings.setEncryptionKey(context, trimmedKey) + _uiState.value = _uiState.value.copy(encryptionKey = trimmedKey) + } + } + + fun setEncryptReceivedMessagesEnabled(context: Context, enabled: Boolean) { + Settings.setEncryptReceivedMessages(context, enabled) + _uiState.value = _uiState.value.copy(isEncryptReceivedMessagesEnabled = enabled) + } + + fun logout(context: Context, onLogoutComplete: () -> Unit) { + Settings.setApiKeyAsync(context, null) + Settings.setSIM1PhoneNumber(context, null) + Settings.setSIM2PhoneNumber(context, null) + Settings.setActiveStatusAsync(context, true, Constants.SIM1) + Settings.setActiveStatusAsync(context, true, Constants.SIM2) + Settings.setIncomingActiveSIM1(context, true) + Settings.setIncomingActiveSIM2(context, true) + Settings.setUserID(context, null) + Settings.setEncryptionKey(context, null) + Settings.setEncryptReceivedMessages(context, false) + Settings.setFcmTokenLastUpdateTimestampAsync(context, 0) + Settings.setIncomingCallEventsEnabled(context, Constants.SIM1, false) + Settings.setIncomingCallEventsEnabled(context, Constants.SIM2, false) + onLogoutComplete() + } +} diff --git a/android/app/src/main/java/com/httpsms/ui/theme/Theme.kt b/android/app/src/main/java/com/httpsms/ui/theme/Theme.kt new file mode 100644 index 0000000000000000000000000000000000000000..88c032fa6296a9436a0b3eca9b1002f56b5e97e8 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ui/theme/Theme.kt @@ -0,0 +1,75 @@ +package com.httpsms.ui.theme + +import android.app.Activity +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.core.view.WindowCompat + +val Blue500 = Color(0xFF2196F3) +val Pink500 = Color(0xFFE91E63) +val LogoGreen = Color(0xFF70AB5C) + +private val DarkColorScheme = darkColorScheme( + primary = Blue500, + secondary = Pink500, + tertiary = Color.White +) + +private val LightColorScheme = lightColorScheme( + primary = Blue500, + secondary = Pink500, + tertiary = Color.Black + + /* Other default colors to override + background = Color(0xFFFFFBFE), + surface = Color(0xFFFFFBFE), + onPrimary = Color.White, + onSecondary = Color.White, + onTertiary = Color.White, + onBackground = Color(0xFF1C1B1F), + onSurface = Color(0xFF1C1B1F), + */ +) + +@Composable +fun HttpSmsTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + // Dynamic color is available on Android 12+ + dynamicColor: Boolean = true, + content: @Composable () -> Unit +) { + val colorScheme = when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + val context = LocalContext.current + if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + + darkTheme -> DarkColorScheme + else -> LightColorScheme + } + val view = LocalView.current + if (!view.isInEditMode) { + SideEffect { + val window = (view.context as Activity).window + window.statusBarColor = colorScheme.background.toArgb() + WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme + } + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} diff --git a/android/app/src/main/java/com/httpsms/ui/theme/Typography.kt b/android/app/src/main/java/com/httpsms/ui/theme/Typography.kt new file mode 100644 index 0000000000000000000000000000000000000000..d8030fef1d4466749803f038dc83be062071bc02 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/ui/theme/Typography.kt @@ -0,0 +1,17 @@ +package com.httpsms.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) +) diff --git a/android/app/src/main/java/com/httpsms/validators/PhoneNumberValidator.kt b/android/app/src/main/java/com/httpsms/validators/PhoneNumberValidator.kt new file mode 100644 index 0000000000000000000000000000000000000000..7e9d2c4270a6f9b56cbfeefe19daa654c6fbcbbe --- /dev/null +++ b/android/app/src/main/java/com/httpsms/validators/PhoneNumberValidator.kt @@ -0,0 +1,37 @@ +package com.httpsms.validators + +import com.google.i18n.phonenumbers.PhoneNumberUtil +import timber.log.Timber + +class PhoneNumberValidator { + companion object { + private val phoneNumberUtil = PhoneNumberUtil.getInstance() + fun isValidPhoneNumber(phoneNumber: String, countryCode: String): Boolean { + Timber.e(countryCode) + return try { + if (phoneNumber.isEmpty()) { + return false + } + val number = phoneNumberUtil.parse(fixNumber(phoneNumber), countryCode) + phoneNumberUtil.isValidNumber(number) + } catch (e: Exception) { + false + } + } + fun formatE164(phoneNumber: String, countryCode: String): String { + return try { + val number = phoneNumberUtil.parse(fixNumber(phoneNumber), countryCode) + phoneNumberUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164) + } catch (e: Exception) { + phoneNumber + } + } + + private fun fixNumber(phoneNumber: String): String { + if (phoneNumber.length >= 11 && !phoneNumber.startsWith("+")) { + return "+${phoneNumber}" + } + return phoneNumber + } + } +} diff --git a/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt b/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt new file mode 100644 index 0000000000000000000000000000000000000000..174f274252845f915a8cd6cef73b29fe5dbd1997 --- /dev/null +++ b/android/app/src/main/java/com/httpsms/worker/HeartbeatWorker.kt @@ -0,0 +1,45 @@ +package com.httpsms.worker + +import android.content.Context +import androidx.work.Worker +import androidx.work.WorkerParameters +import com.httpsms.Constants +import com.httpsms.HttpSmsApiService +import com.httpsms.Settings +import timber.log.Timber + +class HeartbeatWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { + override fun doWork(): Result { + Timber.d("executing heartbeat worker") + if (!Settings.isLoggedIn(applicationContext)) { + Timber.w("user is not logged in, stopping processing") + return Result.failure() + } + + val phoneNumbers = mutableListOf() + if (Settings.getActiveStatus(applicationContext, Constants.SIM1)) { + phoneNumbers.add(Settings.getSIM1PhoneNumber(applicationContext)) + } + if (Settings.getActiveStatus(applicationContext, Constants.SIM2)) { + phoneNumbers.add(Settings.getSIM2PhoneNumber(applicationContext)) + } + + if (phoneNumbers.isEmpty()) { + Timber.w("both [SIM1] and [SIM2] are inactive stopping processing.") + return Result.success() + } + + try{ + HttpSmsApiService.create(applicationContext).storeHeartbeat(phoneNumbers.toTypedArray(), Settings.isCharging(applicationContext)) + Timber.d("finished sending heartbeats to server") + + Settings.setHeartbeatTimestampAsync(applicationContext, System.currentTimeMillis()) + Timber.d("Set the heartbeat timestamp") + } catch (exception: Exception) { + Timber.e(exception, "Failed to send [${phoneNumbers.joinToString()}] heartbeats to server") + return Result.failure() + } + + return Result.success() + } +} diff --git a/android/app/src/main/res/drawable-anydpi/ic_stat_name.xml b/android/app/src/main/res/drawable-anydpi/ic_stat_name.xml new file mode 100644 index 0000000000000000000000000000000000000000..fee2652bc2331113f58b43816cc07ce15d7f5b17 --- /dev/null +++ b/android/app/src/main/res/drawable-anydpi/ic_stat_name.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable-hdpi/ic_stat_name.png b/android/app/src/main/res/drawable-hdpi/ic_stat_name.png new file mode 100644 index 0000000000000000000000000000000000000000..f4208fe75199099e491e283485ff26f3468be160 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_stat_name.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_stat_name.png b/android/app/src/main/res/drawable-mdpi/ic_stat_name.png new file mode 100644 index 0000000000000000000000000000000000000000..bfad7a23bfcb2a2e9ef0430096ee750046b6770b Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_stat_name.png differ diff --git a/android/app/src/main/res/drawable-xhdpi/ic_stat_name.png b/android/app/src/main/res/drawable-xhdpi/ic_stat_name.png new file mode 100644 index 0000000000000000000000000000000000000000..95b8e1fd9d9e8132f4436a32bd9bc3b372f76f77 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_stat_name.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_stat_name.png b/android/app/src/main/res/drawable-xxhdpi/ic_stat_name.png new file mode 100644 index 0000000000000000000000000000000000000000..ecadd65c9f4950b5a38c97163f2b49a5d564f4b1 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_stat_name.png differ diff --git a/android/app/src/main/res/drawable/baseline_check_circle_24.xml b/android/app/src/main/res/drawable/baseline_check_circle_24.xml new file mode 100644 index 0000000000000000000000000000000000000000..0a828cc9a591c3fd2eeaae27aee5e91eac1a48b7 --- /dev/null +++ b/android/app/src/main/res/drawable/baseline_check_circle_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/android/app/src/main/res/drawable/baseline_settings_24.xml b/android/app/src/main/res/drawable/baseline_settings_24.xml new file mode 100644 index 0000000000000000000000000000000000000000..b240b83007995d9b07881f4466f9bed8ffd7c9d8 --- /dev/null +++ b/android/app/src/main/res/drawable/baseline_settings_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/android/app/src/main/res/drawable/ic_colored_logo.xml b/android/app/src/main/res/drawable/ic_colored_logo.xml new file mode 100644 index 0000000000000000000000000000000000000000..46df67e5edd86e5477c1624b7081605a7ebab168 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_colored_logo.xml @@ -0,0 +1,13 @@ + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000000000000000000000000000000000000..07d5da9cbf141911847041df5d7b87f0dd5ef9d4 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000000000000000000000000000000000000..b9f0f4619f96b912da4c98c5baf5bd1f330924aa --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_login.xml b/android/app/src/main/res/drawable/ic_login.xml new file mode 100644 index 0000000000000000000000000000000000000000..998a88f677579253aa674d437fe30e7a890ea6a3 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_login.xml @@ -0,0 +1,9 @@ + + + diff --git a/android/app/src/main/res/drawable/ic_pulse.xml b/android/app/src/main/res/drawable/ic_pulse.xml new file mode 100644 index 0000000000000000000000000000000000000000..f3228f4b1455dc220846aa70276d734708c9e2c1 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_pulse.xml @@ -0,0 +1,9 @@ + + + diff --git a/android/app/src/main/res/drawable/logo_cropped.xml b/android/app/src/main/res/drawable/logo_cropped.xml new file mode 100644 index 0000000000000000000000000000000000000000..22515a362e9ccf6821b910aaef4211777f68e913 --- /dev/null +++ b/android/app/src/main/res/drawable/logo_cropped.xml @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/android/app/src/main/res/drawable/logo_mono_cropped.xml b/android/app/src/main/res/drawable/logo_mono_cropped.xml new file mode 100644 index 0000000000000000000000000000000000000000..6939d8783df2580d8d530b0d9476d48c454d004f --- /dev/null +++ b/android/app/src/main/res/drawable/logo_mono_cropped.xml @@ -0,0 +1,27 @@ + + + + + + + + + diff --git a/android/app/src/main/res/drawable/open_in_new_24.xml b/android/app/src/main/res/drawable/open_in_new_24.xml new file mode 100644 index 0000000000000000000000000000000000000000..b257c344764abab6fa24d2b79ea58f6f206bfd01 --- /dev/null +++ b/android/app/src/main/res/drawable/open_in_new_24.xml @@ -0,0 +1,9 @@ + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000000000000000000000000000000000000..5ed0a2df70488dcb1594ccf43cc7dd1d3f498275 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000000000000000000000000000000000000..5ed0a2df70488dcb1594ccf43cc7dd1d3f498275 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..51365e727e879221a5993d4d03860f258201fb0e Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..908082cb2da01b71e8986f6d34d910b5962dccc9 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..f082a496900fbfa979067d387a08afc9e5a4fb29 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..13e28fffaa226854bf8d9b9e63a620c78d258189 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..94922c81a2a2439a436e5fac9edb29e55df32bd1 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..a5eb961bd19a750f1ecd6003bf58f89295ae1166 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..247689deb13806fe87be239a65fd85a8543e04d3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..0ea1c127681c9f0ef768a047820ba24d0ba02b2f Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000000000000000000000000000000000000..4f469b6124ec247e84d1a698b1ba183d57766281 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000000000000000000000000000000000000..65563f8f36efdcf0e99c05afbfb6a5e7315dc4e1 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/values-night/themes.xml b/android/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000000000000000000000000000000000000..dd456a18bb3347febb207d4dfa15f8f554ef1b42 --- /dev/null +++ b/android/app/src/main/res/values-night/themes.xml @@ -0,0 +1,17 @@ + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000000000000000000000000000000000000..87a7453644bc47ae61ecc2fadcc72429fb42d697 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,15 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + #90CAF9 + #2196F3 + #1976D2 + #F50057 + #E91E63 + diff --git a/android/app/src/main/res/values/ic_launcher_background.xml b/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000000000000000000000000000000000000..81b4d761bec3fa879bd6520d48a8361802fe7aae --- /dev/null +++ b/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #000000 + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000000000000000000000000000000000000..d5a3480cf33384436e841ec93860f0c3bd13bf23 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,35 @@ + + httpSMS + 23/06/2022 18:58:30 + Menu Icon + More + com.httpsms.notification.default + Login With API Key + API Key + HTTP Sms Logo + Get Your API Key at\nhttpsms.com/settings + Log Out + e.g +18005550199 (international format) + e.g https://red-kit-httpsms-gateway.hf.space + Phone Number + Send Heartbeat + Server URL + https://red-kit-httpsms-gateway.hf.space + httpsms.com - %s + Disable Battery Optimization + Enable SMS Permission + App Settings + SIM1 + SIM2 + Enable SIM1 outgoing messages + Enable SIM1 incoming messages + Enable SIM2 incoming messages + Enable SIM2 outgoing messages + Phone number (SIM1) + Phone number (SIM2) + Encryption Key + Encrypt received messages + Enable debug logs + Enable SIM1 missed call events + Enable SIM2 missed call events + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000000000000000000000000000000000000..5914acccae34907deccc259b2630ada4f1a53a44 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/android/app/src/main/res/xml/backup_rules.xml b/android/app/src/main/res/xml/backup_rules.xml new file mode 100644 index 0000000000000000000000000000000000000000..148c18b6593d922c6d96567bb22251a151668f5b --- /dev/null +++ b/android/app/src/main/res/xml/backup_rules.xml @@ -0,0 +1,13 @@ + + + + diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000000000000000000000000000000000000..0c4f95cab912665e8bfd0f0856471908c4d10d5b --- /dev/null +++ b/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/android/app/src/main/res/xml/file_paths.xml b/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000000000000000000000000000000000000..0df3af4145974bc6f992cf7fb8a00f244ff7302a --- /dev/null +++ b/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/android/app/src/test/java/com/httpsms/ExampleUnitTest.kt b/android/app/src/test/java/com/httpsms/ExampleUnitTest.kt new file mode 100644 index 0000000000000000000000000000000000000000..406748db926d798011922682af9d0ec04a6287da --- /dev/null +++ b/android/app/src/test/java/com/httpsms/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package com.httpsms + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..3be829b64e9f0326a3c4fbc2ef7f85bf4d82f96d --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,21 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath("com.google.gms:google-services:4.5.0") + } +} + +plugins { + id("com.android.application") version "9.2.1" apply false + id("com.android.library") version "9.2.1" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false + id("org.jetbrains.kotlin.plugin.compose") version "2.4.0" apply false +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..1f12454655ba3539920acceacb900a2b0ddfb3b0 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,32 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app"s APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true +android.nonFinalResIds=false +android.defaults.buildfeatures.resvalues=true +android.sdk.defaultTargetSdkToCompileSdkIfUnset=false +android.enableAppCompileTimeRClass=false +android.usesSdkInManifest.disallowed=false +android.uniquePackageNames=false +android.dependency.useConstraints=true +android.r8.strictFullModeForKeepRules=false +android.r8.optimizedResourceShrinking=false diff --git a/android/gradle/gradle-daemon-jvm.properties b/android/gradle/gradle-daemon-jvm.properties new file mode 100644 index 0000000000000000000000000000000000000000..8b5316926f97c0b593e472b76acc1b652b299c9f --- /dev/null +++ b/android/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,13 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/5c55020ad1e1758e65cf84d78a6991d9/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/057be4d72513d094c747045acda26562/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/5c55020ad1e1758e65cf84d78a6991d9/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/057be4d72513d094c747045acda26562/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/690f22c7d5fabdba81db34b2bcbdfd40/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/19d7c2d18fdc600f184666745a0567c4/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/5c55020ad1e1758e65cf84d78a6991d9/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/057be4d72513d094c747045acda26562/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/38d4fc46de6f02af9912aa3f66104600/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/34480c4bfcee5d3bd65f2a0592c5217b/redirect +toolchainVendor=JETBRAINS +toolchainVersion=25 diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..e708b1c023ec8b20f512888fe07c5bd3ff77bb8f Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..731777d4ab3298433398592f562a88b2617854c8 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Aug 23 12:56:53 EEST 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 0000000000000000000000000000000000000000..4f906e0c811fc9e230eb44819f509cd0627f2600 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000000000000000000000000000000000000..ac1b06f93825db68fb0c0b5150917f340eaa5d02 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..e3069c2181e0894a6cfc89737762833be1a42dcd --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,19 @@ +pluginManagement { + repositories { + gradlePluginPortal() + google() + mavenCentral() + } +} +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = "httpSMS" +include(":app") diff --git a/api/.env.docker b/api/.env.docker new file mode 100644 index 0000000000000000000000000000000000000000..235972f4dbc26d09f06483fea9d70e1b990d7a60 --- /dev/null +++ b/api/.env.docker @@ -0,0 +1,75 @@ +ENV=local + +# This is the project-id of the firebase project you created in the setup instructions +GCP_PROJECT_ID=httpsms-docker + +USE_HTTP_LOGGER=true + +# Set to "true" to enable feature entitlement checks (limits for free users). +# Defaults to "false" for self-hosted deployments (no limits). +ENTITLEMENT_ENABLED=false + +EVENTS_QUEUE_TYPE=emulator +EVENTS_QUEUE_NAME=events-local +EVENTS_QUEUE_ENDPOINT=http://localhost:8000/v1/events + +# This is the user API key for the system admin user that is used to authenticate requests to the /v1/events endpoint +# You need to create a system user in the `users` table in your database and put the API key and ID of this user here +EVENTS_QUEUE_USER_API_KEY=system-user-api-key +EVENTS_QUEUE_USER_ID=system-user-id + +# This is the actual conetnt of your service account firebase-credentials.json file that you downloaded in the setup instructions +# e.g FIREBASE_CREDENTIALS='{ "type": "service_account", "project_id": "httpsms-docker", "private_key_id":..... +FIREBASE_CREDENTIALS= + +# This is the from name for your emails +SMTP_FROM_NAME=httpSMS +# This is the address where your email messages should come from. You should make sure this matches what is configured on your SMTP service +SMTP_FROM_EMAIL=httpsms@local.com + +# These are the credentials for your SMTP email service +SMTP_USERNAME= +SMTP_PASSWORD= +SMTP_HOST=smtp.mailtrap.io +SMTP_PORT=2525 + +# This is the URL of the application UI and it's used to generate links in emails +APP_URL=http://localhost:3000 + +# The name of the application you can set it to whatever you like +APP_NAME=httpSMS + +# This is the port where the API server will run on +APP_PORT=8000 + +# Host for the swagger UI +SWAGGER_HOST=localhost:8000 + +# Postgresql Database connection string +DATABASE_URL=postgresql://dbusername:dbpassword@postgres:5432/httpsms +DATABASE_URL_DEDICATED=postgresql://dbusername:dbpassword@postgres:5432/httpsms + +# Redis connection string +REDIS_URL=redis://@redis:6379 + +# Google Cloud Storage bucket for MMS attachments. Leave empty to use in-memory storage. +GCS_BUCKET_NAME= + +# [Optional] Axiom observability configuration +# API token for Axiom (required for logging, traces, and metrics in production) +AXIOM_TOKEN= +# Dataset for logs and traces (e.g. "events") +AXIOM_DATASET_EVENTS= +# Dataset for metrics (e.g. "metrics") +AXIOM_DATASET_METRICS= + + +# [optional] Websocket configuration for https://pusher.com if you will like to frontend to update in real time +PUSHER_APP_ID= +PUSHER_KEY= +PUSHER_SECRET= +PUSHER_CLUSTER= + +# Cloudflare Turnstile secret key for validating captcha tokens on the /v1/messages/search route +# Get your secret key at https://developers.cloudflare.com/turnstile/get-started/ +CLOUDFLARE_TURNSTILE_SECRET_KEY= diff --git a/api/.env.production b/api/.env.production new file mode 100644 index 0000000000000000000000000000000000000000..49226775e02d37b0c0d5f293e2e59cb8d0102ccb --- /dev/null +++ b/api/.env.production @@ -0,0 +1,32 @@ +ENV=production + +GCP_PROJECT_ID= + +APP_HTTP_LOGGER= + +EVENTS_QUEUE_TYPE= +EVENTS_QUEUE_USER_API_KEY= +EVENTS_QUEUE_NAME= +EVENTS_QUEUE_USER_ID= +EVENTS_QUEUE_ENDPOINT= + +FIREBASE_CREDENTIALS= + +SMTP_FROM_NAME= +SMTP_FROM_EMAIL= +SMTP_USERNAME= +SMTP_PASSWORD= +SMTP_HOST= +SMTP_PORT= + +APP_URL= +APP_NAME= +APP_PORT=8000 +APP_HOST= + +DATABASE_URL= + +REDIS_URL= + +LEMONSQUEEZY_API_KEY= +LEMONSQUEEZY_SIGNING_SECRET= diff --git a/api/.gitignore b/api/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..19bdf4df018498ff9df3a712a7dec982c00ad6d6 --- /dev/null +++ b/api/.gitignore @@ -0,0 +1,11 @@ +.env.local +*main.exe +tmp +$path + +.env* +.flaskenv* +!.env.project +!.env.vault +!.env.docker +cmd/experiments/* diff --git a/api/Dockerfile b/api/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e6423b1d198656332ec2d138019fe73ff6357a1 --- /dev/null +++ b/api/Dockerfile @@ -0,0 +1,37 @@ +FROM golang AS builder + +ARG GIT_COMMIT +ENV GIT_COMMIT=$GIT_COMMIT + +WORKDIR /http-sms + +COPY go.mod . +COPY go.sum . + +RUN go mod download + +COPY . . + +RUN go get github.com/swaggo/swag/gen@latest +RUN go get github.com/swaggo/swag/cmd/swag@latest +RUN go install github.com/swaggo/swag/cmd/swag +RUN swag init --requiredByDefault --parseDependency --parseInternal + +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X main.Version=$GIT_COMMIT" -o /bin/http-sms . + +FROM alpine:latest + +RUN apk add --no-cache curl && addgroup -S http-sms && adduser -S http-sms -G http-sms + +USER http-sms +WORKDIR /home/http-sms + +COPY --from=builder /usr/local/go/lib/time/zoneinfo.zip /zoneinfo.zip +COPY --from=builder /bin/http-sms ./ +COPY --from=builder /http-sms/root.crt ./ + +ENV ZONEINFO=/zoneinfo.zip + +EXPOSE 8000 + +ENTRYPOINT ["./http-sms", "--dotenv=false"] diff --git a/api/cloudbuild.yaml b/api/cloudbuild.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3abc9e5d381b6e5ffb4c1780eefd926c96d93434 --- /dev/null +++ b/api/cloudbuild.yaml @@ -0,0 +1,28 @@ +steps: + - name: "gcr.io/kaniko-project/executor:v1.23.2" + id: "Build image and push" + dir: "api" + args: + - "--destination=us.gcr.io/$PROJECT_ID/$_SERVICE_NAME:$SHORT_SHA" + - "--destination=us.gcr.io/$PROJECT_ID/$_SERVICE_NAME:latest" + - "--dockerfile=Dockerfile" + - "--context=." + - "--build-arg=GIT_COMMIT=$SHORT_SHA" + - "--snapshot-mode=time" + + - id: "Deploy to cloud run" + name: "gcr.io/cloud-builders/gcloud" + entrypoint: "bash" + args: + - "-c" + - | + gcloud run deploy $_SERVICE_NAME \ + --image=us.gcr.io/$PROJECT_ID/$_SERVICE_NAME:$SHORT_SHA \ + --region=$_REGION --platform managed --allow-unauthenticated \ + --port=8000 +options: + substitutionOption: ALLOW_LOOSE + +substitutions: + _SERVICE_NAME: http-sms-api + _REGION: us-east1 diff --git a/api/docs/docs.go b/api/docs/docs.go new file mode 100644 index 0000000000000000000000000000000000000000..04729b6e2229869ecd1a7ccb23e9ee9afbe7d1da --- /dev/null +++ b/api/docs/docs.go @@ -0,0 +1,6108 @@ +// Package docs Code generated by swaggo/swag. DO NOT EDIT +package docs + +import "github.com/swaggo/swag" + +const docTemplate = `{ + "schemes": {{ marshal .Schemes }}, + "swagger": "2.0", + "info": { + "description": "{{escape .Description}}", + "title": "{{.Title}}", + "contact": { + "name": "support@httpsms.com", + "email": "support@httpsms.com" + }, + "license": { + "name": "AGPL-3.0", + "url": "https://raw.githubusercontent.com/NdoleStudio/http-sms-manager/main/LICENSE" + }, + "version": "{{.Version}}" + }, + "host": "{{.Host}}", + "basePath": "{{.BasePath}}", + "paths": { + "/billing/usage": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get the summary of sent and received messages for a user in the current month", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Billing" + ], + "summary": "Get Billing Usage.", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.BillingUsageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/billing/usage-history": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get billing usage records of sent and received messages for a user in the past. It will be sorted by timestamp in descending order.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Billing" + ], + "summary": "Get billing usage history.", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of heartbeats to skip", + "name": "skip", + "in": "query" + }, + { + "maximum": 100, + "minimum": 1, + "type": "integer", + "description": "number of heartbeats to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.BillingUsagesResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/bulk-messages": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Fetches the last 10 bulk message order summaries for the authenticated user showing counts per status.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "BulkSMS" + ], + "summary": "List bulk message orders", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.BulkMessagesResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Sends bulk SMS messages to multiple users based on our [CSV template](https://httpsms.com/templates/httpsms-bulk.csv) or our [Excel template](https://httpsms.com/templates/httpsms-bulk.xlsx).", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "tags": [ + "BulkSMS" + ], + "summary": "Store bulk SMS file", + "parameters": [ + { + "type": "file", + "description": "The Excel or CSV file containing the messages to be sent.", + "name": "document", + "in": "formData", + "required": true + } + ], + "responses": { + "202": { + "description": "Accepted", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/contacts": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Returns the paginated list of contacts for the authenticated user. The top-level \"total\" field is the number of contacts matching the query filter, independent of skip/limit, so clients can drive server-side pagination.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "List contacts", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of contacts to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter contacts containing query", + "name": "query", + "in": "query" + }, + { + "enum": [ + "name", + "updated_at" + ], + "type": "string", + "description": "field to sort contacts by", + "name": "sort_by", + "in": "query" + }, + { + "type": "boolean", + "description": "sort contacts in descending order", + "name": "sort_descending", + "in": "query" + }, + { + "maximum": 100, + "minimum": 1, + "type": "integer", + "description": "number of contacts to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.ContactsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Creates a single contact or a batch of contacts. Accepts a JSON array or an object with a \"contacts\" array.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "Create one or many contacts", + "parameters": [ + { + "description": "Contact(s) to create", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.ContactStoreRequest" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.ContactsCreatedResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "402": { + "description": "Payment Required", + "schema": { + "$ref": "#/definitions/responses.PaymentRequired" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/contacts/upload": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Uploads a CSV file (multipart field \"document\") of contacts. Columns: Name, Emails, PhoneNumbers (multi-values separated by \";\").", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "Import contacts from CSV", + "parameters": [ + { + "type": "file", + "description": "CSV file of contacts", + "name": "document", + "in": "formData", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.ContactsCreatedResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "402": { + "description": "Payment Required", + "schema": { + "$ref": "#/definitions/responses.PaymentRequired" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/contacts/{contactID}": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates the details of a single contact.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "Update a contact", + "parameters": [ + { + "type": "string", + "description": "ID of the contact", + "name": "contactID", + "in": "path", + "required": true + }, + { + "description": "Contact details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.ContactUpdateRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.ContactResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Deletes a single contact from the database.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "Delete a contact", + "parameters": [ + { + "type": "string", + "description": "ID of the contact", + "name": "contactID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/discord-integrations": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get the discord integrations of a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "DiscordIntegration" + ], + "summary": "Get discord integrations of a user", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of discord integrations to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter discord integrations containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of discord integrations to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.DiscordsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Store a discord integration for the authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "DiscordIntegration" + ], + "summary": "Store discord integration", + "parameters": [ + { + "description": "Payload of the discord integration request", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.DiscordStore" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.DiscordResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/discord-integrations/{discordID}": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Update a discord integration for the currently authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "DiscordIntegration" + ], + "summary": "Update a discord integration", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the discord integration", + "name": "discordID", + "in": "path", + "required": true + }, + { + "description": "Payload of discord integration to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.DiscordUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.DiscordResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a discord integration for a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Delete discord integration", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the discord integration", + "name": "discordID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/discord/event": { + "post": { + "description": "Publish a discord event to the registered listeners", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Discord" + ], + "summary": "Consume a discord event", + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/heartbeats": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get the last time a phone number requested for outstanding messages. It will be sorted by timestamp in descending order.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Heartbeats" + ], + "summary": "Get heartbeats of an owner phone number", + "parameters": [ + { + "type": "string", + "default": "+18005550199", + "description": "the owner's phone number", + "name": "owner", + "in": "query", + "required": true + }, + { + "minimum": 0, + "type": "integer", + "description": "number of heartbeats to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of heartbeats to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.HeartbeatsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Store the heartbeat to make notify that a phone number is still active", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Heartbeats" + ], + "summary": "Register heartbeat of an owner phone number", + "parameters": [ + { + "description": "Payload of the heartbeat request", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.HeartbeatStore" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.HeartbeatResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/integration/3cx/messages": { + "post": { + "description": "Sends an SMS message from the 3CX platform", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "3CXIntegration" + ], + "summary": "Sends a 3CX SMS message", + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/message-threads": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get list of contacts which a phone number has communicated with (threads). It will be sorted by timestamp in descending order.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "MessageThreads" + ], + "summary": "Get message threads for a phone number", + "parameters": [ + { + "type": "string", + "default": "+18005550199", + "description": "owner phone number", + "name": "owner", + "in": "query", + "required": true + }, + { + "minimum": 0, + "type": "integer", + "description": "number of messages to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter message threads containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of messages to return", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "include matching contact details", + "name": "contacts", + "in": "query" + }, + { + "type": "boolean", + "default": false, + "description": "only include threads with unread messages", + "name": "unread_only", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageThreadsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/message-threads/{messageThreadID}": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Returns a conversation belonging to the authenticated user, including matching contact details when available.", + "produces": [ + "application/json" + ], + "tags": [ + "MessageThreads" + ], + "summary": "Get a message thread", + "parameters": [ + { + "type": "string", + "description": "ID of the message thread", + "name": "messageThreadID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageThreadResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates the details of a message thread", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "MessageThreads" + ], + "summary": "Update a message thread", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message thread", + "name": "messageThreadID", + "in": "path", + "required": true + }, + { + "description": "Payload of message thread details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageThreadUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageThreadResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a message thread from the database and also deletes all the messages in the thread.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "MessageThreads" + ], + "summary": "Delete a message thread from the database.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message thread", + "name": "messageThreadID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get list of messages which are sent between 2 phone numbers. It will be sorted by timestamp in descending order.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Get messages which are sent between 2 phone numbers", + "parameters": [ + { + "type": "string", + "default": "+18005550199", + "description": "the owner's phone number", + "name": "owner", + "in": "query", + "required": true + }, + { + "type": "string", + "default": "+18005550100", + "description": "the contact's phone number", + "name": "contact", + "in": "query", + "required": true + }, + { + "minimum": 0, + "type": "integer", + "description": "number of messages to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter messages containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of messages to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessagesResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/bulk-send": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Add bulk SMS messages to be sent by the android phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Send bulk SMS messages", + "parameters": [ + { + "description": "Bulk send message request payload", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageBulkSend" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/responses.MessagesResponse" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/calls/missed": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "This endpoint is called by the httpSMS android app to register a missed call event on the mobile phone.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Register a missed call event on the mobile phone", + "parameters": [ + { + "description": "Payload of the missed call event.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageCallMissed" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/outstanding": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get an outstanding message to be sent by an android phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Get an outstanding message", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703cb", + "description": "The ID of the message", + "name": "message_id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/receive": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Add a new message received from a mobile phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Receive a new SMS message from a mobile phone", + "parameters": [ + { + "description": "Received message request payload", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageReceive" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/search": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "This returns the list of all messages based on the filter criteria including missed calls", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Search all messages of a user", + "parameters": [ + { + "type": "string", + "description": "Cloudflare turnstile token https://www.cloudflare.com/en-gb/application-services/products/turnstile/", + "name": "token", + "in": "header", + "required": true + }, + { + "type": "string", + "default": "+18005550199,+18005550100", + "description": "the owner's phone numbers", + "name": "owners", + "in": "query", + "required": true + }, + { + "minimum": 0, + "type": "integer", + "description": "number of messages to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter messages containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 200, + "minimum": 1, + "type": "integer", + "description": "number of messages to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessagesResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/send": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Add a new SMS message to be sent by your Android phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Send an SMS message", + "parameters": [ + { + "description": "Send message request payload", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageSend" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/{messageID}": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get a message from the database by the message ID.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Get a message from the database.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message", + "name": "messageID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a message from the database and removes the message content from the list of threads.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Delete a message from the database.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message", + "name": "messageID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/{messageID}/events": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Use this endpoint to send events for a message when it is failed, sent or delivered by the mobile phone.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Upsert an event for a message on the mobile phone", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message", + "name": "messageID", + "in": "path", + "required": true + }, + { + "description": "Payload of the event emitted.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageEvent" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phone-api-keys": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get list phone API keys which a user has registered on the httpSMS application", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "PhoneAPIKeys" + ], + "summary": "Get the phone API keys of a user", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of phone api keys to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter phone api keys with name containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 100, + "minimum": 1, + "type": "integer", + "description": "number of phone api keys to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneAPIKeysResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Creates a new phone API key which can be used to log in to the httpSMS app on your Android phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "PhoneAPIKeys" + ], + "summary": "Store phone API key", + "parameters": [ + { + "description": "Payload of new phone API key.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.PhoneAPIKeyStoreRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneAPIKeyResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "402": { + "description": "Payment Required", + "schema": { + "$ref": "#/definitions/responses.PaymentRequired" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phone-api-keys/{phoneAPIKeyID}": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a phone API Key from the database and cannot be used for authentication anymore.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "PhoneAPIKeys" + ], + "summary": "Delete a phone API key from the database.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the phone API key", + "name": "phoneAPIKeyID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phone-api-keys/{phoneAPIKeyID}/phones/{phoneID}": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "You will need to login again to the httpSMS app on your Android phone with a new phone API key.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "PhoneAPIKeys" + ], + "summary": "Remove the association of a phone from the phone API key.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the phone API key", + "name": "phoneAPIKeyID", + "in": "path", + "required": true + }, + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the phone", + "name": "phoneID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phones": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get list of phones which a user has registered on the http sms application", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Phones" + ], + "summary": "Get phones of a user", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of heartbeats to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter phones containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of phones to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhonesResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates properties of a user's phone. If the phone with this number does not exist, a new one will be created. Think of this method like an 'upsert'. URL-backed phone gateways receive FCM-compatible HTTP wake-ups.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Phones" + ], + "summary": "Upsert Phone", + "parameters": [ + { + "description": "Payload of new phone number.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.PhoneUpsert" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phones/fcm-token": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates the FCM token or adapter callback URL of a phone. If the phone with this number does not exist, a new one will be created. Think of this method like an 'upsert'. URL-backed phone gateways receive FCM-compatible HTTP wake-ups.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Phones" + ], + "summary": "Upserts the FCM token of a phone", + "parameters": [ + { + "description": "Payload of new FCM token.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.PhoneFCMToken" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phones/{phoneID}": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a phone that has been sored in the database", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Phones" + ], + "summary": "Delete Phone", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the phone", + "name": "phoneID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/send-schedules": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "List all send schedules owned by the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "SendSchedules" + ], + "summary": "List send schedules", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageSendSchedulesResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Create a new send schedule for the authenticated user.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "SendSchedules" + ], + "summary": "Create send schedule", + "parameters": [ + { + "description": "Payload of new send schedule.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageSendScheduleStore" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.MessageSendScheduleResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "402": { + "description": "Payment Required", + "schema": { + "$ref": "#/definitions/responses.PaymentRequired" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/send-schedules/{scheduleID}": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Update a send schedule owned by the authenticated user.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "SendSchedules" + ], + "summary": "Update send schedule", + "parameters": [ + { + "type": "string", + "description": "Schedule ID", + "name": "scheduleID", + "in": "path", + "required": true + }, + { + "description": "Payload of updated send schedule.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageSendScheduleStore" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageSendScheduleResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a send schedule owned by the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "SendSchedules" + ], + "summary": "Delete send schedule", + "parameters": [ + { + "type": "string", + "description": "Schedule ID", + "name": "scheduleID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/me": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get details of the currently authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Get current user", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.UserResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates the details of the currently authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Update a user", + "parameters": [ + { + "description": "Payload of user details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.UserUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Deletes the currently authenticated user together with all their data.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Delete a user", + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/subscription": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Cancel the subscription of the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Cancel the user's subscription", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/subscription-update-url": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Fetches the subscription URL of the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Currently authenticated user subscription update URL", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.OkString" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/subscription/invoices/{subscriptionInvoiceID}": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Generates a new invoice PDF file for the given subscription payment with given parameters.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/pdf" + ], + "tags": [ + "Users" + ], + "summary": "Generate a subscription payment invoice", + "parameters": [ + { + "description": "Generate subscription payment invoice parameters", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.UserPaymentInvoice" + } + }, + { + "type": "string", + "description": "ID of the subscription invoice to generate the PDF for", + "name": "subscriptionInvoiceID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "file" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/subscription/payments": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Subscription payments are generated throughout the lifecycle of a subscription, typically there is one at the time of purchase and then one for each renewal.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Get the last 10 subscription payments.", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.UserSubscriptionPaymentsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/{userID}/api-keys": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Rotate the user's API key in case the current API Key is compromised", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Rotate the user's API Key", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the user to update", + "name": "userID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.UserResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/{userID}/notifications": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Update the email notification settings for a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Update notification settings", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the user to update", + "name": "userID", + "in": "path", + "required": true + }, + { + "description": "User notification details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.UserNotificationUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.UserResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/v1/attachments/{userID}/{messageID}/{attachmentIndex}/{filename}": { + "get": { + "description": "Download an MMS attachment by its path components", + "produces": [ + "application/octet-stream" + ], + "tags": [ + "Attachments" + ], + "summary": "Download a message attachment", + "parameters": [ + { + "type": "string", + "description": "User ID", + "name": "userID", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Message ID", + "name": "messageID", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Attachment index", + "name": "attachmentIndex", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Filename with extension", + "name": "filename", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "file" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/webhooks": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get the webhooks of a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Get webhooks of a user", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of webhooks to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter webhooks containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of webhooks to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.WebhooksResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Store a webhook for the authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Store a webhook", + "parameters": [ + { + "description": "Payload of the webhook request", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.WebhookStore" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.WebhookResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/webhooks/{webhookID}": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Update a webhook for the currently authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Update a webhook", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the webhook", + "name": "webhookID", + "in": "path", + "required": true + }, + { + "description": "Payload of webhook details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.WebhookUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.WebhookResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a webhook for a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Delete webhook", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the webhook", + "name": "webhookID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + } + }, + "definitions": { + "entities.BillingUsage": { + "type": "object", + "required": [ + "created_at", + "end_timestamp", + "id", + "received_messages", + "sent_messages", + "start_timestamp", + "total_cost", + "updated_at", + "user_id" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "end_timestamp": { + "type": "string", + "example": "2022-01-31T23:59:59+00:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "received_messages": { + "type": "integer", + "example": 465 + }, + "sent_messages": { + "type": "integer", + "example": 321 + }, + "start_timestamp": { + "type": "string", + "example": "2022-01-01T00:00:00+00:00" + }, + "total_cost": { + "type": "integer", + "example": 0 + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.BulkMessage": { + "type": "object", + "required": [ + "created_at", + "delivered_count", + "expired_count", + "failed_count", + "pending_count", + "request_id", + "scheduled_count", + "sent_count", + "total" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "delivered_count": { + "type": "integer", + "example": 25 + }, + "expired_count": { + "type": "integer", + "example": 3 + }, + "failed_count": { + "type": "integer", + "example": 5 + }, + "pending_count": { + "type": "integer", + "example": 30 + }, + "request_id": { + "type": "string", + "example": "bulk-httpsms-file.csv" + }, + "scheduled_count": { + "type": "integer", + "example": 50 + }, + "sent_count": { + "type": "integer", + "example": 40 + }, + "total": { + "type": "integer", + "example": 150 + } + } + }, + "entities.Contact": { + "type": "object", + "required": [ + "created_at", + "emails", + "id", + "name", + "phone_numbers", + "properties", + "updated_at", + "user_id" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "emails": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "alice@example.com" + ] + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "name": { + "type": "string", + "example": "Alice Smith" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550199", + "+18005550100" + ] + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.Discord": { + "type": "object", + "required": [ + "created_at", + "id", + "incoming_channel_id", + "name", + "server_id", + "updated_at", + "user_id" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "incoming_channel_id": { + "type": "string", + "example": "1095780203256627291" + }, + "name": { + "type": "string", + "example": "Game Server" + }, + "server_id": { + "type": "string", + "example": "1095778291488653372" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.Heartbeat": { + "type": "object", + "required": [ + "charging", + "id", + "owner", + "timestamp", + "user_id", + "version" + ], + "properties": { + "charging": { + "type": "boolean", + "example": true + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "owner": { + "type": "string", + "example": "+18005550199" + }, + "timestamp": { + "type": "string", + "example": "2022-06-05T14:26:01.520828+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + }, + "version": { + "type": "string", + "example": "344c10f" + } + } + }, + "entities.Message": { + "type": "object", + "required": [ + "attachments", + "contact", + "content", + "created_at", + "encrypted", + "id", + "max_send_attempts", + "order_timestamp", + "owner", + "request_received_at", + "send_attempt_count", + "sim", + "status", + "type", + "updated_at", + "user_id" + ], + "properties": { + "attachments": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "https://example.com/image.jpg", + "https://example.com/video.mp4" + ] + }, + "contact": { + "type": "string", + "example": "+18005550100" + }, + "content": { + "type": "string", + "example": "This is a sample text message" + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "delivered_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "encrypted": { + "type": "boolean", + "example": false + }, + "expired_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "failed_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "failure_reason": { + "type": "string", + "example": "UNKNOWN" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "last_attempted_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "max_send_attempts": { + "type": "integer", + "example": 1 + }, + "order_timestamp": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "owner": { + "type": "string", + "example": "+18005550199" + }, + "received_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "request_id": { + "type": "string", + "example": "153554b5-ae44-44a0-8f4f-7bbac5657ad4" + }, + "request_received_at": { + "type": "string", + "example": "2022-06-05T14:26:01.520828+03:00" + }, + "scheduled_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "scheduled_send_time": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "send_attempt_count": { + "type": "integer", + "example": 0 + }, + "send_time": { + "description": "SendDuration is the number of nanoseconds from when the request was received until when the mobile phone send the message", + "type": "integer", + "example": 133414 + }, + "sent_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "sim": { + "description": "SIM is the SIM card to use to send the message\n* SMS1: use the SIM card in slot 1\n* SMS2: use the SIM card in slot 2\n* DEFAULT: used the default communication SIM card", + "allOf": [ + { + "$ref": "#/definitions/entities.SIM" + } + ], + "example": "DEFAULT" + }, + "status": { + "type": "string", + "example": "pending" + }, + "type": { + "type": "string", + "example": "mobile-terminated" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.MessageSendSchedule": { + "type": "object", + "required": [ + "created_at", + "id", + "name", + "timezone", + "updated_at", + "user_id", + "windows" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "name": { + "type": "string", + "example": "Business Hours" + }, + "timezone": { + "type": "string", + "example": "Europe/Tallinn" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + }, + "windows": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.MessageSendScheduleWindow" + } + } + } + }, + "entities.MessageSendScheduleWindow": { + "type": "object", + "required": [ + "day_of_week", + "end_minute", + "start_minute" + ], + "properties": { + "day_of_week": { + "type": "integer", + "example": 1 + }, + "end_minute": { + "type": "integer", + "example": 1020 + }, + "start_minute": { + "type": "integer", + "example": 540 + } + } + }, + "entities.MessageThread": { + "type": "object", + "required": [ + "color", + "contact", + "created_at", + "id", + "is_archived", + "last_message_content", + "last_message_id", + "order_timestamp", + "owner", + "status", + "unread_count", + "updated_at", + "user_id" + ], + "properties": { + "color": { + "type": "string", + "example": "indigo" + }, + "contact": { + "type": "string", + "example": "+18005550100" + }, + "contact_details": { + "description": "ContactDetails is resolved at read time and never persisted.", + "allOf": [ + { + "$ref": "#/definitions/entities.Contact" + } + ] + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703ca" + }, + "is_archived": { + "type": "boolean", + "example": false + }, + "last_message_content": { + "type": "string", + "example": "This is a sample message content" + }, + "last_message_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703ca" + }, + "order_timestamp": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "owner": { + "type": "string", + "example": "+18005550199" + }, + "status": { + "type": "string", + "example": "PENDING" + }, + "unread_count": { + "type": "integer", + "example": 0 + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.Phone": { + "type": "object", + "required": [ + "archive_new_outgoing_message_threads", + "created_at", + "id", + "max_send_attempts", + "message_expiration_seconds", + "messages_per_minute", + "phone_number", + "sim", + "unarchive_thread", + "updated_at", + "user_id" + ], + "properties": { + "archive_new_outgoing_message_threads": { + "description": "ArchiveNewOutgoingMessageThreads archives new conversations started by an outgoing message on this phone.", + "type": "boolean", + "example": false + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "fcm_token": { + "type": "string", + "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "max_send_attempts": { + "description": "MaxSendAttempts determines how many times to retry sending an SMS message", + "type": "integer", + "example": 2 + }, + "message_expiration_seconds": { + "description": "MessageExpirationSeconds is the duration in seconds after sending a message when it is considered to be expired.", + "type": "integer" + }, + "message_send_schedule_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "messages_per_minute": { + "type": "integer", + "example": 1 + }, + "missed_call_auto_reply": { + "type": "string", + "example": "This phone cannot receive calls. Please send an SMS instead." + }, + "phone_number": { + "type": "string", + "example": "+18005550199" + }, + "sim": { + "$ref": "#/definitions/entities.SIM" + }, + "unarchive_thread": { + "description": "UnarchiveThread moves an archived message thread back to the inbox when a new message is received on this phone.", + "type": "boolean", + "example": false + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.PhoneAPIKey": { + "type": "object", + "required": [ + "api_key", + "created_at", + "id", + "name", + "phone_ids", + "phone_numbers", + "updated_at", + "user_email", + "user_id" + ], + "properties": { + "api_key": { + "type": "string", + "example": "pk_DGW8NwQp7mxKaSZ72Xq9v6xxxxx" + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "name": { + "type": "string", + "example": "Business Phone Key" + }, + "phone_ids": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "32343a19-da5e-4b1b-a767-3298a73703cb", + "32343a19-da5e-4b1b-a767-3298a73703cc" + ] + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550199", + "+18005550100" + ] + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "user_email": { + "type": "string", + "example": "user@gmail.com" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.SIM": { + "type": "string", + "enum": [ + "SIM1", + "SIM2" + ], + "x-enum-varnames": [ + "SIM1", + "SIM2" + ] + }, + "entities.SubscriptionName": { + "type": "string", + "enum": [ + "free", + "pro-monthly", + "pro-yearly", + "ultra-monthly", + "ultra-yearly", + "pro-lifetime", + "20k-monthly", + "100k-monthly", + "50k-monthly", + "200k-monthly", + "20k-yearly" + ], + "x-enum-varnames": [ + "SubscriptionNameFree", + "SubscriptionNameProMonthly", + "SubscriptionNameProYearly", + "SubscriptionNameUltraMonthly", + "SubscriptionNameUltraYearly", + "SubscriptionNameProLifetime", + "SubscriptionName20KMonthly", + "SubscriptionName100KMonthly", + "SubscriptionName50KMonthly", + "SubscriptionName200KMonthly", + "SubscriptionName20KYearly" + ] + }, + "entities.User": { + "type": "object", + "required": [ + "api_key", + "created_at", + "email", + "id", + "notification_heartbeat_enabled", + "notification_message_status_enabled", + "notification_newsletter_enabled", + "notification_webhook_enabled", + "subscription_id", + "subscription_name", + "timezone", + "updated_at" + ], + "properties": { + "active_phone_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "api_key": { + "type": "string", + "example": "x-api-key" + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "email": { + "type": "string", + "example": "name@email.com" + }, + "id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + }, + "notification_heartbeat_enabled": { + "type": "boolean", + "example": true + }, + "notification_message_status_enabled": { + "type": "boolean", + "example": true + }, + "notification_newsletter_enabled": { + "type": "boolean", + "example": true + }, + "notification_webhook_enabled": { + "type": "boolean", + "example": true + }, + "subscription_ends_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "subscription_id": { + "type": "string", + "example": "8f9c71b8-b84e-4417-8408-a62274f65a08" + }, + "subscription_name": { + "allOf": [ + { + "$ref": "#/definitions/entities.SubscriptionName" + } + ], + "example": "free" + }, + "subscription_renews_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "subscription_status": { + "type": "string", + "example": "on_trial" + }, + "timezone": { + "type": "string", + "example": "Europe/Helsinki" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + } + } + }, + "entities.Webhook": { + "type": "object", + "required": [ + "created_at", + "events", + "id", + "phone_numbers", + "signing_key", + "updated_at", + "url", + "user_id" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "events": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "message.phone.received" + ] + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550199", + "+18005550100" + ] + }, + "signing_key": { + "type": "string", + "example": "DGW8NwQp7mxKaSZ72Xq9v67SLqSbWQvckzzmK8D6rvd7NywSEkdMJtuxKyEkYnCY" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "url": { + "type": "string", + "example": "https://example.com" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "requests.ContactItem": { + "type": "object", + "required": [ + "name", + "phone_numbers" + ], + "properties": { + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "name": { + "type": "string", + "example": "Alice Smith" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + } + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "requests.ContactStoreRequest": { + "type": "object", + "required": [ + "contacts" + ], + "properties": { + "contacts": { + "type": "array", + "items": { + "$ref": "#/definitions/requests.ContactItem" + } + } + } + }, + "requests.ContactUpdateRequest": { + "type": "object", + "required": [ + "name", + "phone_numbers" + ], + "properties": { + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "name": { + "type": "string", + "example": "Alice Smith" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + } + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "requests.DiscordStore": { + "type": "object", + "required": [ + "incoming_channel_id", + "name", + "server_id" + ], + "properties": { + "incoming_channel_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "server_id": { + "type": "string" + } + } + }, + "requests.DiscordUpdate": { + "type": "object", + "required": [ + "incoming_channel_id", + "name", + "server_id" + ], + "properties": { + "incoming_channel_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "server_id": { + "type": "string" + } + } + }, + "requests.HeartbeatStore": { + "type": "object", + "required": [ + "charging", + "phone_numbers" + ], + "properties": { + "charging": { + "type": "boolean" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "requests.MessageAttachment": { + "type": "object", + "required": [ + "content", + "content_type", + "name" + ], + "properties": { + "content": { + "description": "Content is the base64-encoded attachment data", + "type": "string", + "example": "base64data..." + }, + "content_type": { + "description": "ContentType is the MIME type of the attachment", + "type": "string", + "example": "image/jpeg" + }, + "name": { + "description": "Name is the original filename of the attachment", + "type": "string", + "example": "photo.jpg" + } + } + }, + "requests.MessageBulkSend": { + "type": "object", + "required": [ + "content", + "from", + "to" + ], + "properties": { + "attachments": { + "description": "Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS", + "type": "array", + "items": { + "type": "string" + } + }, + "content": { + "type": "string", + "example": "This is a sample text message" + }, + "encrypted": { + "description": "Encrypted is used to determine if the content is end-to-end encrypted. Make sure to set the encryption key on the httpSMS mobile app", + "type": "boolean", + "example": false + }, + "from": { + "type": "string", + "example": "+18005550199" + }, + "request_id": { + "description": "RequestID is an optional parameter used to track a request from the client's perspective", + "type": "string", + "example": "153554b5-ae44-44a0-8f4f-7bbac5657ad4" + }, + "to": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550100", + "+18005550100" + ] + } + } + }, + "requests.MessageCallMissed": { + "type": "object", + "required": [ + "from", + "sim", + "timestamp", + "to" + ], + "properties": { + "from": { + "type": "string", + "example": "+18005550199" + }, + "sim": { + "type": "string", + "example": "SIM1" + }, + "timestamp": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "to": { + "type": "string", + "example": "+18005550100" + } + } + }, + "requests.MessageEvent": { + "type": "object", + "required": [ + "event_name", + "reason", + "timestamp" + ], + "properties": { + "event_name": { + "description": "EventName is the type of event\n* SENT: is emitted when a message is sent by the mobile phone\n* FAILED: is event is emitted when the message could not be sent by the mobile phone\n* DELIVERED: is event is emitted when a delivery report has been received by the mobile phone", + "type": "string", + "example": "SENT" + }, + "reason": { + "description": "Reason is the exact error message in case the event is an error", + "type": "string" + }, + "timestamp": { + "description": "Timestamp is the time when the event was emitted, Please send the timestamp in UTC with as much precision as possible", + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + } + } + }, + "requests.MessageReceive": { + "type": "object", + "required": [ + "content", + "encrypted", + "from", + "sim", + "timestamp", + "to" + ], + "properties": { + "attachments": { + "description": "Attachments is the list of MMS attachments received with the message", + "type": "array", + "items": { + "$ref": "#/definitions/requests.MessageAttachment" + } + }, + "content": { + "type": "string", + "example": "This is a sample text message received on a phone" + }, + "encrypted": { + "description": "Encrypted is used to determine if the content is end-to-end encrypted. Make sure to set the encryption key on the httpSMS mobile app", + "type": "boolean", + "example": false + }, + "from": { + "type": "string", + "example": "+18005550199" + }, + "sim": { + "description": "SIM card that received the message", + "allOf": [ + { + "$ref": "#/definitions/entities.SIM" + } + ], + "example": "SIM1" + }, + "timestamp": { + "description": "Timestamp is the time when the event was emitted, Please send the timestamp in UTC with as much precision as possible", + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "to": { + "type": "string", + "example": "+18005550100" + } + } + }, + "requests.MessageSend": { + "type": "object", + "required": [ + "content", + "from", + "to" + ], + "properties": { + "attachments": { + "description": "Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS", + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "https://example.com/image.jpg", + "https://example.com/video.mp4" + ] + }, + "content": { + "type": "string", + "example": "This is a sample text message" + }, + "encrypted": { + "description": "Encrypted is an optional parameter used to determine if the content is end-to-end encrypted. Make sure to set the encryption key on the httpSMS mobile app", + "type": "boolean", + "example": false + }, + "from": { + "type": "string", + "example": "+18005550199" + }, + "request_id": { + "description": "RequestID is an optional parameter used to track a request from the client's perspective", + "type": "string", + "example": "153554b5-ae44-44a0-8f4f-7bbac5657ad4" + }, + "send_at": { + "description": "SendAt is an optional parameter used to schedule a message to be sent in the future. The time is considered to be in your profile's local timezone and you can queue messages for up to 20 days (480 hours) in the future.", + "type": "string", + "example": "2025-12-19T16:39:57-08:00" + }, + "to": { + "type": "string", + "example": "+18005550100" + } + } + }, + "requests.MessageSendScheduleStore": { + "type": "object", + "required": [ + "name", + "timezone", + "windows" + ], + "properties": { + "name": { + "type": "string" + }, + "timezone": { + "type": "string" + }, + "windows": { + "type": "array", + "items": { + "$ref": "#/definitions/requests.MessageSendScheduleWindow" + } + } + } + }, + "requests.MessageSendScheduleWindow": { + "type": "object", + "required": [ + "day_of_week", + "end_minute", + "start_minute" + ], + "properties": { + "day_of_week": { + "type": "integer" + }, + "end_minute": { + "type": "integer" + }, + "start_minute": { + "type": "integer" + } + } + }, + "requests.MessageThreadUpdate": { + "type": "object", + "properties": { + "is_archived": { + "type": "boolean", + "example": true + }, + "unread_count": { + "type": "integer", + "example": 0 + } + } + }, + "requests.PhoneAPIKeyStoreRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "example": "My Phone API Key" + } + } + }, + "requests.PhoneFCMToken": { + "type": "object", + "required": [ + "fcm_token", + "phone_number", + "sim" + ], + "properties": { + "fcm_token": { + "description": "FcmToken is either a Firebase registration token or a public HTTPS adapter callback URL.", + "type": "string", + "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." + }, + "phone_number": { + "type": "string", + "example": "[+18005550199]" + }, + "sim": { + "description": "SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot", + "type": "string", + "example": "SIM1" + } + } + }, + "requests.PhoneUpsert": { + "type": "object", + "required": [ + "fcm_token", + "max_send_attempts", + "message_expiration_seconds", + "messages_per_minute", + "missed_call_auto_reply", + "phone_number", + "sim", + "unarchive_thread" + ], + "properties": { + "archive_new_outgoing_message_threads": { + "description": "ArchiveNewOutgoingMessageThreads archives new conversations started by an outgoing message on this phone.", + "type": "boolean", + "example": false + }, + "fcm_token": { + "description": "FcmToken is either a Firebase registration token or a public HTTPS adapter callback URL.", + "type": "string", + "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." + }, + "max_send_attempts": { + "description": "MaxSendAttempts is the number of attempts when sending an SMS message to handle the case where the phone is offline.", + "type": "integer", + "example": 2 + }, + "message_expiration_seconds": { + "description": "MessageExpirationSeconds is the duration in seconds after sending a message when it is considered to be expired.", + "type": "integer", + "example": 12345 + }, + "message_send_schedule_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "messages_per_minute": { + "type": "integer", + "example": 1 + }, + "missed_call_auto_reply": { + "type": "string", + "example": "e.g. This phone cannot receive calls. Please send an SMS instead." + }, + "phone_number": { + "type": "string", + "example": "+18005550199" + }, + "sim": { + "description": "SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot", + "type": "string", + "example": "SIM1" + }, + "unarchive_thread": { + "description": "UnarchiveThread moves an archived thread back to the inbox when a new message is received on this phone.", + "type": "boolean", + "example": false + } + } + }, + "requests.UserNotificationUpdate": { + "type": "object", + "required": [ + "heartbeat_enabled", + "message_status_enabled", + "newsletter_enabled", + "webhook_enabled" + ], + "properties": { + "heartbeat_enabled": { + "type": "boolean", + "example": true + }, + "message_status_enabled": { + "type": "boolean", + "example": true + }, + "newsletter_enabled": { + "type": "boolean", + "example": true + }, + "webhook_enabled": { + "type": "boolean", + "example": true + } + } + }, + "requests.UserPaymentInvoice": { + "type": "object", + "required": [ + "address", + "city", + "country", + "name", + "notes", + "state", + "zip_code" + ], + "properties": { + "address": { + "type": "string", + "example": "221B Baker Street, London" + }, + "city": { + "type": "string", + "example": "Los Angeles" + }, + "country": { + "type": "string", + "example": "US" + }, + "name": { + "type": "string", + "example": "Acme Corp" + }, + "notes": { + "type": "string", + "example": "Thank you for your business!" + }, + "state": { + "type": "string", + "example": "CA" + }, + "zip_code": { + "type": "string", + "example": "9800" + } + } + }, + "requests.UserUpdate": { + "type": "object", + "required": [ + "active_phone_id", + "timezone" + ], + "properties": { + "active_phone_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "timezone": { + "type": "string", + "example": "Europe/Helsinki" + } + } + }, + "requests.WebhookStore": { + "type": "object", + "required": [ + "events", + "phone_numbers", + "signing_key", + "url" + ], + "properties": { + "events": { + "type": "array", + "items": { + "type": "string" + } + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550100", + "+18005550100" + ] + }, + "signing_key": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "requests.WebhookUpdate": { + "type": "object", + "required": [ + "events", + "phone_numbers", + "signing_key", + "url" + ], + "properties": { + "events": { + "type": "array", + "items": { + "type": "string" + } + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550100", + "+18005550100" + ] + }, + "signing_key": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "responses.BadRequest": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "string", + "example": "The request body is not a valid JSON string" + }, + "message": { + "type": "string", + "example": "The request isn't properly formed" + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.BillingUsageResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.BillingUsage" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.BillingUsagesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.BillingUsage" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.BulkMessagesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.BulkMessage" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.ContactResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Contact" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.ContactsCreatedResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Contact" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.ContactsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status", + "total" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Contact" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + }, + "total": { + "description": "Total is the number of contacts matching the request filter for the\nuser, independent of the pagination skip/limit applied to Data.", + "type": "integer", + "example": 57 + } + } + }, + "responses.DiscordResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Discord" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.DiscordsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Discord" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.HeartbeatResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Heartbeat" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.HeartbeatsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Heartbeat" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.InternalServerError": { + "type": "object", + "required": [ + "message", + "status" + ], + "properties": { + "message": { + "type": "string", + "example": "We ran into an internal error while handling the request." + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.MessageResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Message" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessageSendScheduleResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.MessageSendSchedule" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessageSendSchedulesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.MessageSendSchedule" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessageThreadResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.MessageThread" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessageThreadsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.MessageThread" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessagesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Message" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.NoContent": { + "type": "object", + "required": [ + "message", + "status" + ], + "properties": { + "message": { + "type": "string", + "example": "action performed successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.NotFound": { + "type": "object", + "required": [ + "message", + "status" + ], + "properties": { + "message": { + "type": "string", + "example": "cannot find message with ID [32343a19-da5e-4b1b-a767-3298a73703ca]" + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.OkString": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "string" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.PaymentRequired": { + "type": "object", + "required": [ + "message", + "status" + ], + "properties": { + "message": { + "type": "string", + "example": "You have reached the maximum number of allowed resources. Please upgrade your plan." + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.PhoneAPIKeyResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.PhoneAPIKey" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.PhoneAPIKeysResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.PhoneAPIKey" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.PhoneResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Phone" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.PhonesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Phone" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.Unauthorized": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "string", + "example": "Make sure your API key is set in the [X-API-Key] header in the request" + }, + "message": { + "type": "string", + "example": "You are not authorized to carry out this request." + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.UnprocessableEntity": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "message": { + "type": "string", + "example": "validation errors while handling request" + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.UserResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.User" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.UserSubscriptionPaymentsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "type": "object", + "required": [ + "attributes", + "id", + "type" + ], + "properties": { + "attributes": { + "type": "object", + "required": [ + "billing_reason", + "card_brand", + "card_last_four", + "created_at", + "currency", + "currency_rate", + "discount_total", + "discount_total_formatted", + "discount_total_usd", + "refunded", + "refunded_amount", + "refunded_amount_formatted", + "refunded_amount_usd", + "refunded_at", + "status", + "status_formatted", + "subtotal", + "subtotal_formatted", + "subtotal_usd", + "tax", + "tax_formatted", + "tax_inclusive", + "tax_usd", + "total", + "total_formatted", + "total_usd", + "updated_at" + ], + "properties": { + "billing_reason": { + "type": "string" + }, + "card_brand": { + "type": "string" + }, + "card_last_four": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "currency": { + "type": "string" + }, + "currency_rate": { + "type": "string" + }, + "discount_total": { + "type": "integer" + }, + "discount_total_formatted": { + "type": "string" + }, + "discount_total_usd": { + "type": "integer" + }, + "refunded": { + "type": "boolean" + }, + "refunded_amount": { + "type": "integer" + }, + "refunded_amount_formatted": { + "type": "string" + }, + "refunded_amount_usd": { + "type": "integer" + }, + "refunded_at": {}, + "status": { + "type": "string" + }, + "status_formatted": { + "type": "string" + }, + "subtotal": { + "type": "integer" + }, + "subtotal_formatted": { + "type": "string" + }, + "subtotal_usd": { + "type": "integer" + }, + "tax": { + "type": "integer" + }, + "tax_formatted": { + "type": "string" + }, + "tax_inclusive": { + "type": "boolean" + }, + "tax_usd": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "total_formatted": { + "type": "string" + }, + "total_usd": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "id": { + "type": "string" + }, + "type": { + "type": "string" + } + } + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.WebhookResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Webhook" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.WebhooksResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Webhook" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + } + }, + "securityDefinitions": { + "ApiKeyAuth": { + "type": "apiKey", + "name": "x-api-Key", + "in": "header" + } + } +}` + +// SwaggerInfo holds exported Swagger Info so clients can modify it +var SwaggerInfo = &swag.Spec{ + Version: "1.0", + Host: "api.httpsms.com", + BasePath: "/v1", + Schemes: []string{"https"}, + Title: "httpSMS API Reference", + Description: "Use your Android phone to send and receive SMS messages via a simple programmable API with end-to-end encryption.", + InfoInstanceName: "swagger", + SwaggerTemplate: docTemplate, + LeftDelim: "{{", + RightDelim: "}}", +} + +func init() { + swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) +} diff --git a/api/docs/swagger.json b/api/docs/swagger.json new file mode 100644 index 0000000000000000000000000000000000000000..a24b2c520c70766eb0b82b6f3a88bde177ada263 --- /dev/null +++ b/api/docs/swagger.json @@ -0,0 +1,6087 @@ +{ + "schemes": [ + "https" + ], + "swagger": "2.0", + "info": { + "description": "Use your Android phone to send and receive SMS messages via a simple programmable API with end-to-end encryption.", + "title": "httpSMS API Reference", + "contact": { + "name": "support@httpsms.com", + "email": "support@httpsms.com" + }, + "license": { + "name": "AGPL-3.0", + "url": "https://raw.githubusercontent.com/NdoleStudio/http-sms-manager/main/LICENSE" + }, + "version": "1.0" + }, + "host": "api.httpsms.com", + "basePath": "/v1", + "paths": { + "/billing/usage": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get the summary of sent and received messages for a user in the current month", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Billing" + ], + "summary": "Get Billing Usage.", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.BillingUsageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/billing/usage-history": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get billing usage records of sent and received messages for a user in the past. It will be sorted by timestamp in descending order.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Billing" + ], + "summary": "Get billing usage history.", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of heartbeats to skip", + "name": "skip", + "in": "query" + }, + { + "maximum": 100, + "minimum": 1, + "type": "integer", + "description": "number of heartbeats to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.BillingUsagesResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/bulk-messages": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Fetches the last 10 bulk message order summaries for the authenticated user showing counts per status.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "BulkSMS" + ], + "summary": "List bulk message orders", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.BulkMessagesResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Sends bulk SMS messages to multiple users based on our [CSV template](https://httpsms.com/templates/httpsms-bulk.csv) or our [Excel template](https://httpsms.com/templates/httpsms-bulk.xlsx).", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "tags": [ + "BulkSMS" + ], + "summary": "Store bulk SMS file", + "parameters": [ + { + "type": "file", + "description": "The Excel or CSV file containing the messages to be sent.", + "name": "document", + "in": "formData", + "required": true + } + ], + "responses": { + "202": { + "description": "Accepted", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/contacts": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Returns the paginated list of contacts for the authenticated user. The top-level \"total\" field is the number of contacts matching the query filter, independent of skip/limit, so clients can drive server-side pagination.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "List contacts", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of contacts to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter contacts containing query", + "name": "query", + "in": "query" + }, + { + "enum": [ + "name", + "updated_at" + ], + "type": "string", + "description": "field to sort contacts by", + "name": "sort_by", + "in": "query" + }, + { + "type": "boolean", + "description": "sort contacts in descending order", + "name": "sort_descending", + "in": "query" + }, + { + "maximum": 100, + "minimum": 1, + "type": "integer", + "description": "number of contacts to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.ContactsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Creates a single contact or a batch of contacts. Accepts a JSON array or an object with a \"contacts\" array.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "Create one or many contacts", + "parameters": [ + { + "description": "Contact(s) to create", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.ContactStoreRequest" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.ContactsCreatedResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "402": { + "description": "Payment Required", + "schema": { + "$ref": "#/definitions/responses.PaymentRequired" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/contacts/upload": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Uploads a CSV file (multipart field \"document\") of contacts. Columns: Name, Emails, PhoneNumbers (multi-values separated by \";\").", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "Import contacts from CSV", + "parameters": [ + { + "type": "file", + "description": "CSV file of contacts", + "name": "document", + "in": "formData", + "required": true + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.ContactsCreatedResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "402": { + "description": "Payment Required", + "schema": { + "$ref": "#/definitions/responses.PaymentRequired" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/contacts/{contactID}": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates the details of a single contact.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "Update a contact", + "parameters": [ + { + "type": "string", + "description": "ID of the contact", + "name": "contactID", + "in": "path", + "required": true + }, + { + "description": "Contact details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.ContactUpdateRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.ContactResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Deletes a single contact from the database.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Contacts" + ], + "summary": "Delete a contact", + "parameters": [ + { + "type": "string", + "description": "ID of the contact", + "name": "contactID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/discord-integrations": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get the discord integrations of a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "DiscordIntegration" + ], + "summary": "Get discord integrations of a user", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of discord integrations to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter discord integrations containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of discord integrations to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.DiscordsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Store a discord integration for the authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "DiscordIntegration" + ], + "summary": "Store discord integration", + "parameters": [ + { + "description": "Payload of the discord integration request", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.DiscordStore" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.DiscordResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/discord-integrations/{discordID}": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Update a discord integration for the currently authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "DiscordIntegration" + ], + "summary": "Update a discord integration", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the discord integration", + "name": "discordID", + "in": "path", + "required": true + }, + { + "description": "Payload of discord integration to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.DiscordUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.DiscordResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a discord integration for a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Delete discord integration", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the discord integration", + "name": "discordID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/discord/event": { + "post": { + "description": "Publish a discord event to the registered listeners", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Discord" + ], + "summary": "Consume a discord event", + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/heartbeats": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get the last time a phone number requested for outstanding messages. It will be sorted by timestamp in descending order.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Heartbeats" + ], + "summary": "Get heartbeats of an owner phone number", + "parameters": [ + { + "type": "string", + "default": "+18005550199", + "description": "the owner's phone number", + "name": "owner", + "in": "query", + "required": true + }, + { + "minimum": 0, + "type": "integer", + "description": "number of heartbeats to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of heartbeats to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.HeartbeatsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Store the heartbeat to make notify that a phone number is still active", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Heartbeats" + ], + "summary": "Register heartbeat of an owner phone number", + "parameters": [ + { + "description": "Payload of the heartbeat request", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.HeartbeatStore" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.HeartbeatResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/integration/3cx/messages": { + "post": { + "description": "Sends an SMS message from the 3CX platform", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "3CXIntegration" + ], + "summary": "Sends a 3CX SMS message", + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/message-threads": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get list of contacts which a phone number has communicated with (threads). It will be sorted by timestamp in descending order.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "MessageThreads" + ], + "summary": "Get message threads for a phone number", + "parameters": [ + { + "type": "string", + "default": "+18005550199", + "description": "owner phone number", + "name": "owner", + "in": "query", + "required": true + }, + { + "minimum": 0, + "type": "integer", + "description": "number of messages to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter message threads containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of messages to return", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "include matching contact details", + "name": "contacts", + "in": "query" + }, + { + "type": "boolean", + "default": false, + "description": "only include threads with unread messages", + "name": "unread_only", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageThreadsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/message-threads/{messageThreadID}": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Returns a conversation belonging to the authenticated user, including matching contact details when available.", + "produces": [ + "application/json" + ], + "tags": [ + "MessageThreads" + ], + "summary": "Get a message thread", + "parameters": [ + { + "type": "string", + "description": "ID of the message thread", + "name": "messageThreadID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageThreadResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates the details of a message thread", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "MessageThreads" + ], + "summary": "Update a message thread", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message thread", + "name": "messageThreadID", + "in": "path", + "required": true + }, + { + "description": "Payload of message thread details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageThreadUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageThreadResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a message thread from the database and also deletes all the messages in the thread.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "MessageThreads" + ], + "summary": "Delete a message thread from the database.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message thread", + "name": "messageThreadID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get list of messages which are sent between 2 phone numbers. It will be sorted by timestamp in descending order.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Get messages which are sent between 2 phone numbers", + "parameters": [ + { + "type": "string", + "default": "+18005550199", + "description": "the owner's phone number", + "name": "owner", + "in": "query", + "required": true + }, + { + "type": "string", + "default": "+18005550100", + "description": "the contact's phone number", + "name": "contact", + "in": "query", + "required": true + }, + { + "minimum": 0, + "type": "integer", + "description": "number of messages to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter messages containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of messages to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessagesResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/bulk-send": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Add bulk SMS messages to be sent by the android phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Send bulk SMS messages", + "parameters": [ + { + "description": "Bulk send message request payload", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageBulkSend" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/responses.MessagesResponse" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/calls/missed": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "This endpoint is called by the httpSMS android app to register a missed call event on the mobile phone.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Register a missed call event on the mobile phone", + "parameters": [ + { + "description": "Payload of the missed call event.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageCallMissed" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/outstanding": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get an outstanding message to be sent by an android phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Get an outstanding message", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703cb", + "description": "The ID of the message", + "name": "message_id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/receive": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Add a new message received from a mobile phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Receive a new SMS message from a mobile phone", + "parameters": [ + { + "description": "Received message request payload", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageReceive" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/search": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "This returns the list of all messages based on the filter criteria including missed calls", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Search all messages of a user", + "parameters": [ + { + "type": "string", + "description": "Cloudflare turnstile token https://www.cloudflare.com/en-gb/application-services/products/turnstile/", + "name": "token", + "in": "header", + "required": true + }, + { + "type": "string", + "default": "+18005550199,+18005550100", + "description": "the owner's phone numbers", + "name": "owners", + "in": "query", + "required": true + }, + { + "minimum": 0, + "type": "integer", + "description": "number of messages to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter messages containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 200, + "minimum": 1, + "type": "integer", + "description": "number of messages to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessagesResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/send": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Add a new SMS message to be sent by your Android phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Send an SMS message", + "parameters": [ + { + "description": "Send message request payload", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageSend" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/{messageID}": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get a message from the database by the message ID.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Get a message from the database.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message", + "name": "messageID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a message from the database and removes the message content from the list of threads.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Delete a message from the database.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message", + "name": "messageID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/messages/{messageID}/events": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Use this endpoint to send events for a message when it is failed, sent or delivered by the mobile phone.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Messages" + ], + "summary": "Upsert an event for a message on the mobile phone", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the message", + "name": "messageID", + "in": "path", + "required": true + }, + { + "description": "Payload of the event emitted.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageEvent" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phone-api-keys": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get list phone API keys which a user has registered on the httpSMS application", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "PhoneAPIKeys" + ], + "summary": "Get the phone API keys of a user", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of phone api keys to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter phone api keys with name containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 100, + "minimum": 1, + "type": "integer", + "description": "number of phone api keys to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneAPIKeysResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Creates a new phone API key which can be used to log in to the httpSMS app on your Android phone", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "PhoneAPIKeys" + ], + "summary": "Store phone API key", + "parameters": [ + { + "description": "Payload of new phone API key.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.PhoneAPIKeyStoreRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneAPIKeyResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "402": { + "description": "Payment Required", + "schema": { + "$ref": "#/definitions/responses.PaymentRequired" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phone-api-keys/{phoneAPIKeyID}": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a phone API Key from the database and cannot be used for authentication anymore.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "PhoneAPIKeys" + ], + "summary": "Delete a phone API key from the database.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the phone API key", + "name": "phoneAPIKeyID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phone-api-keys/{phoneAPIKeyID}/phones/{phoneID}": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "You will need to login again to the httpSMS app on your Android phone with a new phone API key.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "PhoneAPIKeys" + ], + "summary": "Remove the association of a phone from the phone API key.", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the phone API key", + "name": "phoneAPIKeyID", + "in": "path", + "required": true + }, + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the phone", + "name": "phoneID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phones": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get list of phones which a user has registered on the http sms application", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Phones" + ], + "summary": "Get phones of a user", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of heartbeats to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter phones containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of phones to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhonesResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates properties of a user's phone. If the phone with this number does not exist, a new one will be created. Think of this method like an 'upsert'. URL-backed phone gateways receive FCM-compatible HTTP wake-ups.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Phones" + ], + "summary": "Upsert Phone", + "parameters": [ + { + "description": "Payload of new phone number.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.PhoneUpsert" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phones/fcm-token": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates the FCM token or adapter callback URL of a phone. If the phone with this number does not exist, a new one will be created. Think of this method like an 'upsert'. URL-backed phone gateways receive FCM-compatible HTTP wake-ups.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Phones" + ], + "summary": "Upserts the FCM token of a phone", + "parameters": [ + { + "description": "Payload of new FCM token.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.PhoneFCMToken" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/phones/{phoneID}": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a phone that has been sored in the database", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Phones" + ], + "summary": "Delete Phone", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the phone", + "name": "phoneID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/send-schedules": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "List all send schedules owned by the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "SendSchedules" + ], + "summary": "List send schedules", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageSendSchedulesResponse" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Create a new send schedule for the authenticated user.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "SendSchedules" + ], + "summary": "Create send schedule", + "parameters": [ + { + "description": "Payload of new send schedule.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageSendScheduleStore" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.MessageSendScheduleResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "402": { + "description": "Payment Required", + "schema": { + "$ref": "#/definitions/responses.PaymentRequired" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/send-schedules/{scheduleID}": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Update a send schedule owned by the authenticated user.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "SendSchedules" + ], + "summary": "Update send schedule", + "parameters": [ + { + "type": "string", + "description": "Schedule ID", + "name": "scheduleID", + "in": "path", + "required": true + }, + { + "description": "Payload of updated send schedule.", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.MessageSendScheduleStore" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.MessageSendScheduleResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a send schedule owned by the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "SendSchedules" + ], + "summary": "Delete send schedule", + "parameters": [ + { + "type": "string", + "description": "Schedule ID", + "name": "scheduleID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/me": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get details of the currently authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Get current user", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.UserResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Updates the details of the currently authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Update a user", + "parameters": [ + { + "description": "Payload of user details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.UserUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.PhoneResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Deletes the currently authenticated user together with all their data.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Delete a user", + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/subscription": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Cancel the subscription of the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Cancel the user's subscription", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/subscription-update-url": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Fetches the subscription URL of the authenticated user.", + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Currently authenticated user subscription update URL", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.OkString" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/subscription/invoices/{subscriptionInvoiceID}": { + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Generates a new invoice PDF file for the given subscription payment with given parameters.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/pdf" + ], + "tags": [ + "Users" + ], + "summary": "Generate a subscription payment invoice", + "parameters": [ + { + "description": "Generate subscription payment invoice parameters", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.UserPaymentInvoice" + } + }, + { + "type": "string", + "description": "ID of the subscription invoice to generate the PDF for", + "name": "subscriptionInvoiceID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "file" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/subscription/payments": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Subscription payments are generated throughout the lifecycle of a subscription, typically there is one at the time of purchase and then one for each renewal.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Get the last 10 subscription payments.", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.UserSubscriptionPaymentsResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/{userID}/api-keys": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Rotate the user's API key in case the current API Key is compromised", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Rotate the user's API Key", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the user to update", + "name": "userID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.UserResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/users/{userID}/notifications": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Update the email notification settings for a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Users" + ], + "summary": "Update notification settings", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the user to update", + "name": "userID", + "in": "path", + "required": true + }, + { + "description": "User notification details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.UserNotificationUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.UserResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/v1/attachments/{userID}/{messageID}/{attachmentIndex}/{filename}": { + "get": { + "description": "Download an MMS attachment by its path components", + "produces": [ + "application/octet-stream" + ], + "tags": [ + "Attachments" + ], + "summary": "Download a message attachment", + "parameters": [ + { + "type": "string", + "description": "User ID", + "name": "userID", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Message ID", + "name": "messageID", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Attachment index", + "name": "attachmentIndex", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Filename with extension", + "name": "filename", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "file" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/responses.NotFound" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/webhooks": { + "get": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Get the webhooks of a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Get webhooks of a user", + "parameters": [ + { + "minimum": 0, + "type": "integer", + "description": "number of webhooks to skip", + "name": "skip", + "in": "query" + }, + { + "type": "string", + "description": "filter webhooks containing query", + "name": "query", + "in": "query" + }, + { + "maximum": 20, + "minimum": 1, + "type": "integer", + "description": "number of webhooks to return", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.WebhooksResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Store a webhook for the authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Store a webhook", + "parameters": [ + { + "description": "Payload of the webhook request", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.WebhookStore" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.WebhookResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + }, + "/webhooks/{webhookID}": { + "put": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Update a webhook for the currently authenticated user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Update a webhook", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the webhook", + "name": "webhookID", + "in": "path", + "required": true + }, + { + "description": "Payload of webhook details to update", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/requests.WebhookUpdate" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/responses.WebhookResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + }, + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Delete a webhook for a user", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Webhooks" + ], + "summary": "Delete webhook", + "parameters": [ + { + "type": "string", + "default": "32343a19-da5e-4b1b-a767-3298a73703ca", + "description": "ID of the webhook", + "name": "webhookID", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content", + "schema": { + "$ref": "#/definitions/responses.NoContent" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.BadRequest" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/responses.Unauthorized" + } + }, + "422": { + "description": "Unprocessable Entity", + "schema": { + "$ref": "#/definitions/responses.UnprocessableEntity" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.InternalServerError" + } + } + } + } + } + }, + "definitions": { + "entities.BillingUsage": { + "type": "object", + "required": [ + "created_at", + "end_timestamp", + "id", + "received_messages", + "sent_messages", + "start_timestamp", + "total_cost", + "updated_at", + "user_id" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "end_timestamp": { + "type": "string", + "example": "2022-01-31T23:59:59+00:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "received_messages": { + "type": "integer", + "example": 465 + }, + "sent_messages": { + "type": "integer", + "example": 321 + }, + "start_timestamp": { + "type": "string", + "example": "2022-01-01T00:00:00+00:00" + }, + "total_cost": { + "type": "integer", + "example": 0 + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.BulkMessage": { + "type": "object", + "required": [ + "created_at", + "delivered_count", + "expired_count", + "failed_count", + "pending_count", + "request_id", + "scheduled_count", + "sent_count", + "total" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "delivered_count": { + "type": "integer", + "example": 25 + }, + "expired_count": { + "type": "integer", + "example": 3 + }, + "failed_count": { + "type": "integer", + "example": 5 + }, + "pending_count": { + "type": "integer", + "example": 30 + }, + "request_id": { + "type": "string", + "example": "bulk-httpsms-file.csv" + }, + "scheduled_count": { + "type": "integer", + "example": 50 + }, + "sent_count": { + "type": "integer", + "example": 40 + }, + "total": { + "type": "integer", + "example": 150 + } + } + }, + "entities.Contact": { + "type": "object", + "required": [ + "created_at", + "emails", + "id", + "name", + "phone_numbers", + "properties", + "updated_at", + "user_id" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "emails": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "alice@example.com" + ] + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "name": { + "type": "string", + "example": "Alice Smith" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550199", + "+18005550100" + ] + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.Discord": { + "type": "object", + "required": [ + "created_at", + "id", + "incoming_channel_id", + "name", + "server_id", + "updated_at", + "user_id" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "incoming_channel_id": { + "type": "string", + "example": "1095780203256627291" + }, + "name": { + "type": "string", + "example": "Game Server" + }, + "server_id": { + "type": "string", + "example": "1095778291488653372" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.Heartbeat": { + "type": "object", + "required": [ + "charging", + "id", + "owner", + "timestamp", + "user_id", + "version" + ], + "properties": { + "charging": { + "type": "boolean", + "example": true + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "owner": { + "type": "string", + "example": "+18005550199" + }, + "timestamp": { + "type": "string", + "example": "2022-06-05T14:26:01.520828+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + }, + "version": { + "type": "string", + "example": "344c10f" + } + } + }, + "entities.Message": { + "type": "object", + "required": [ + "attachments", + "contact", + "content", + "created_at", + "encrypted", + "id", + "max_send_attempts", + "order_timestamp", + "owner", + "request_received_at", + "send_attempt_count", + "sim", + "status", + "type", + "updated_at", + "user_id" + ], + "properties": { + "attachments": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "https://example.com/image.jpg", + "https://example.com/video.mp4" + ] + }, + "contact": { + "type": "string", + "example": "+18005550100" + }, + "content": { + "type": "string", + "example": "This is a sample text message" + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "delivered_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "encrypted": { + "type": "boolean", + "example": false + }, + "expired_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "failed_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "failure_reason": { + "type": "string", + "example": "UNKNOWN" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "last_attempted_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "max_send_attempts": { + "type": "integer", + "example": 1 + }, + "order_timestamp": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "owner": { + "type": "string", + "example": "+18005550199" + }, + "received_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "request_id": { + "type": "string", + "example": "153554b5-ae44-44a0-8f4f-7bbac5657ad4" + }, + "request_received_at": { + "type": "string", + "example": "2022-06-05T14:26:01.520828+03:00" + }, + "scheduled_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "scheduled_send_time": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "send_attempt_count": { + "type": "integer", + "example": 0 + }, + "send_time": { + "description": "SendDuration is the number of nanoseconds from when the request was received until when the mobile phone send the message", + "type": "integer", + "example": 133414 + }, + "sent_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "sim": { + "description": "SIM is the SIM card to use to send the message\n* SMS1: use the SIM card in slot 1\n* SMS2: use the SIM card in slot 2\n* DEFAULT: used the default communication SIM card", + "allOf": [ + { + "$ref": "#/definitions/entities.SIM" + } + ], + "example": "DEFAULT" + }, + "status": { + "type": "string", + "example": "pending" + }, + "type": { + "type": "string", + "example": "mobile-terminated" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.MessageSendSchedule": { + "type": "object", + "required": [ + "created_at", + "id", + "name", + "timezone", + "updated_at", + "user_id", + "windows" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "name": { + "type": "string", + "example": "Business Hours" + }, + "timezone": { + "type": "string", + "example": "Europe/Tallinn" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + }, + "windows": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.MessageSendScheduleWindow" + } + } + } + }, + "entities.MessageSendScheduleWindow": { + "type": "object", + "required": [ + "day_of_week", + "end_minute", + "start_minute" + ], + "properties": { + "day_of_week": { + "type": "integer", + "example": 1 + }, + "end_minute": { + "type": "integer", + "example": 1020 + }, + "start_minute": { + "type": "integer", + "example": 540 + } + } + }, + "entities.MessageThread": { + "type": "object", + "required": [ + "color", + "contact", + "created_at", + "id", + "is_archived", + "last_message_content", + "last_message_id", + "order_timestamp", + "owner", + "status", + "unread_count", + "updated_at", + "user_id" + ], + "properties": { + "color": { + "type": "string", + "example": "indigo" + }, + "contact": { + "type": "string", + "example": "+18005550100" + }, + "contact_details": { + "description": "ContactDetails is resolved at read time and never persisted.", + "allOf": [ + { + "$ref": "#/definitions/entities.Contact" + } + ] + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703ca" + }, + "is_archived": { + "type": "boolean", + "example": false + }, + "last_message_content": { + "type": "string", + "example": "This is a sample message content" + }, + "last_message_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703ca" + }, + "order_timestamp": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "owner": { + "type": "string", + "example": "+18005550199" + }, + "status": { + "type": "string", + "example": "PENDING" + }, + "unread_count": { + "type": "integer", + "example": 0 + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.Phone": { + "type": "object", + "required": [ + "archive_new_outgoing_message_threads", + "created_at", + "id", + "max_send_attempts", + "message_expiration_seconds", + "messages_per_minute", + "phone_number", + "sim", + "unarchive_thread", + "updated_at", + "user_id" + ], + "properties": { + "archive_new_outgoing_message_threads": { + "description": "ArchiveNewOutgoingMessageThreads archives new conversations started by an outgoing message on this phone.", + "type": "boolean", + "example": false + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "fcm_token": { + "type": "string", + "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "max_send_attempts": { + "description": "MaxSendAttempts determines how many times to retry sending an SMS message", + "type": "integer", + "example": 2 + }, + "message_expiration_seconds": { + "description": "MessageExpirationSeconds is the duration in seconds after sending a message when it is considered to be expired.", + "type": "integer" + }, + "message_send_schedule_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "messages_per_minute": { + "type": "integer", + "example": 1 + }, + "missed_call_auto_reply": { + "type": "string", + "example": "This phone cannot receive calls. Please send an SMS instead." + }, + "phone_number": { + "type": "string", + "example": "+18005550199" + }, + "sim": { + "$ref": "#/definitions/entities.SIM" + }, + "unarchive_thread": { + "description": "UnarchiveThread moves an archived message thread back to the inbox when a new message is received on this phone.", + "type": "boolean", + "example": false + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.PhoneAPIKey": { + "type": "object", + "required": [ + "api_key", + "created_at", + "id", + "name", + "phone_ids", + "phone_numbers", + "updated_at", + "user_email", + "user_id" + ], + "properties": { + "api_key": { + "type": "string", + "example": "pk_DGW8NwQp7mxKaSZ72Xq9v6xxxxx" + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "name": { + "type": "string", + "example": "Business Phone Key" + }, + "phone_ids": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "32343a19-da5e-4b1b-a767-3298a73703cb", + "32343a19-da5e-4b1b-a767-3298a73703cc" + ] + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550199", + "+18005550100" + ] + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "user_email": { + "type": "string", + "example": "user@gmail.com" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "entities.SIM": { + "type": "string", + "enum": [ + "SIM1", + "SIM2" + ], + "x-enum-varnames": [ + "SIM1", + "SIM2" + ] + }, + "entities.SubscriptionName": { + "type": "string", + "enum": [ + "free", + "pro-monthly", + "pro-yearly", + "ultra-monthly", + "ultra-yearly", + "pro-lifetime", + "20k-monthly", + "100k-monthly", + "50k-monthly", + "200k-monthly", + "20k-yearly" + ], + "x-enum-varnames": [ + "SubscriptionNameFree", + "SubscriptionNameProMonthly", + "SubscriptionNameProYearly", + "SubscriptionNameUltraMonthly", + "SubscriptionNameUltraYearly", + "SubscriptionNameProLifetime", + "SubscriptionName20KMonthly", + "SubscriptionName100KMonthly", + "SubscriptionName50KMonthly", + "SubscriptionName200KMonthly", + "SubscriptionName20KYearly" + ] + }, + "entities.User": { + "type": "object", + "required": [ + "api_key", + "created_at", + "email", + "id", + "notification_heartbeat_enabled", + "notification_message_status_enabled", + "notification_newsletter_enabled", + "notification_webhook_enabled", + "subscription_id", + "subscription_name", + "timezone", + "updated_at" + ], + "properties": { + "active_phone_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "api_key": { + "type": "string", + "example": "x-api-key" + }, + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "email": { + "type": "string", + "example": "name@email.com" + }, + "id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + }, + "notification_heartbeat_enabled": { + "type": "boolean", + "example": true + }, + "notification_message_status_enabled": { + "type": "boolean", + "example": true + }, + "notification_newsletter_enabled": { + "type": "boolean", + "example": true + }, + "notification_webhook_enabled": { + "type": "boolean", + "example": true + }, + "subscription_ends_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "subscription_id": { + "type": "string", + "example": "8f9c71b8-b84e-4417-8408-a62274f65a08" + }, + "subscription_name": { + "allOf": [ + { + "$ref": "#/definitions/entities.SubscriptionName" + } + ], + "example": "free" + }, + "subscription_renews_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "subscription_status": { + "type": "string", + "example": "on_trial" + }, + "timezone": { + "type": "string", + "example": "Europe/Helsinki" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + } + } + }, + "entities.Webhook": { + "type": "object", + "required": [ + "created_at", + "events", + "id", + "phone_numbers", + "signing_key", + "updated_at", + "url", + "user_id" + ], + "properties": { + "created_at": { + "type": "string", + "example": "2022-06-05T14:26:02.302718+03:00" + }, + "events": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "message.phone.received" + ] + }, + "id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550199", + "+18005550100" + ] + }, + "signing_key": { + "type": "string", + "example": "DGW8NwQp7mxKaSZ72Xq9v67SLqSbWQvckzzmK8D6rvd7NywSEkdMJtuxKyEkYnCY" + }, + "updated_at": { + "type": "string", + "example": "2022-06-05T14:26:10.303278+03:00" + }, + "url": { + "type": "string", + "example": "https://example.com" + }, + "user_id": { + "type": "string", + "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" + } + } + }, + "requests.ContactItem": { + "type": "object", + "required": [ + "name", + "phone_numbers" + ], + "properties": { + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "name": { + "type": "string", + "example": "Alice Smith" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + } + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "requests.ContactStoreRequest": { + "type": "object", + "required": [ + "contacts" + ], + "properties": { + "contacts": { + "type": "array", + "items": { + "$ref": "#/definitions/requests.ContactItem" + } + } + } + }, + "requests.ContactUpdateRequest": { + "type": "object", + "required": [ + "name", + "phone_numbers" + ], + "properties": { + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "name": { + "type": "string", + "example": "Alice Smith" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + } + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "requests.DiscordStore": { + "type": "object", + "required": [ + "incoming_channel_id", + "name", + "server_id" + ], + "properties": { + "incoming_channel_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "server_id": { + "type": "string" + } + } + }, + "requests.DiscordUpdate": { + "type": "object", + "required": [ + "incoming_channel_id", + "name", + "server_id" + ], + "properties": { + "incoming_channel_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "server_id": { + "type": "string" + } + } + }, + "requests.HeartbeatStore": { + "type": "object", + "required": [ + "charging", + "phone_numbers" + ], + "properties": { + "charging": { + "type": "boolean" + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "requests.MessageAttachment": { + "type": "object", + "required": [ + "content", + "content_type", + "name" + ], + "properties": { + "content": { + "description": "Content is the base64-encoded attachment data", + "type": "string", + "example": "base64data..." + }, + "content_type": { + "description": "ContentType is the MIME type of the attachment", + "type": "string", + "example": "image/jpeg" + }, + "name": { + "description": "Name is the original filename of the attachment", + "type": "string", + "example": "photo.jpg" + } + } + }, + "requests.MessageBulkSend": { + "type": "object", + "required": [ + "content", + "from", + "to" + ], + "properties": { + "attachments": { + "description": "Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS", + "type": "array", + "items": { + "type": "string" + } + }, + "content": { + "type": "string", + "example": "This is a sample text message" + }, + "encrypted": { + "description": "Encrypted is used to determine if the content is end-to-end encrypted. Make sure to set the encryption key on the httpSMS mobile app", + "type": "boolean", + "example": false + }, + "from": { + "type": "string", + "example": "+18005550199" + }, + "request_id": { + "description": "RequestID is an optional parameter used to track a request from the client's perspective", + "type": "string", + "example": "153554b5-ae44-44a0-8f4f-7bbac5657ad4" + }, + "to": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550100", + "+18005550100" + ] + } + } + }, + "requests.MessageCallMissed": { + "type": "object", + "required": [ + "from", + "sim", + "timestamp", + "to" + ], + "properties": { + "from": { + "type": "string", + "example": "+18005550199" + }, + "sim": { + "type": "string", + "example": "SIM1" + }, + "timestamp": { + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "to": { + "type": "string", + "example": "+18005550100" + } + } + }, + "requests.MessageEvent": { + "type": "object", + "required": [ + "event_name", + "reason", + "timestamp" + ], + "properties": { + "event_name": { + "description": "EventName is the type of event\n* SENT: is emitted when a message is sent by the mobile phone\n* FAILED: is event is emitted when the message could not be sent by the mobile phone\n* DELIVERED: is event is emitted when a delivery report has been received by the mobile phone", + "type": "string", + "example": "SENT" + }, + "reason": { + "description": "Reason is the exact error message in case the event is an error", + "type": "string" + }, + "timestamp": { + "description": "Timestamp is the time when the event was emitted, Please send the timestamp in UTC with as much precision as possible", + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + } + } + }, + "requests.MessageReceive": { + "type": "object", + "required": [ + "content", + "encrypted", + "from", + "sim", + "timestamp", + "to" + ], + "properties": { + "attachments": { + "description": "Attachments is the list of MMS attachments received with the message", + "type": "array", + "items": { + "$ref": "#/definitions/requests.MessageAttachment" + } + }, + "content": { + "type": "string", + "example": "This is a sample text message received on a phone" + }, + "encrypted": { + "description": "Encrypted is used to determine if the content is end-to-end encrypted. Make sure to set the encryption key on the httpSMS mobile app", + "type": "boolean", + "example": false + }, + "from": { + "type": "string", + "example": "+18005550199" + }, + "sim": { + "description": "SIM card that received the message", + "allOf": [ + { + "$ref": "#/definitions/entities.SIM" + } + ], + "example": "SIM1" + }, + "timestamp": { + "description": "Timestamp is the time when the event was emitted, Please send the timestamp in UTC with as much precision as possible", + "type": "string", + "example": "2022-06-05T14:26:09.527976+03:00" + }, + "to": { + "type": "string", + "example": "+18005550100" + } + } + }, + "requests.MessageSend": { + "type": "object", + "required": [ + "content", + "from", + "to" + ], + "properties": { + "attachments": { + "description": "Attachments are optional. When you provide a list of attachments, the message will be sent out as an MMS", + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "https://example.com/image.jpg", + "https://example.com/video.mp4" + ] + }, + "content": { + "type": "string", + "example": "This is a sample text message" + }, + "encrypted": { + "description": "Encrypted is an optional parameter used to determine if the content is end-to-end encrypted. Make sure to set the encryption key on the httpSMS mobile app", + "type": "boolean", + "example": false + }, + "from": { + "type": "string", + "example": "+18005550199" + }, + "request_id": { + "description": "RequestID is an optional parameter used to track a request from the client's perspective", + "type": "string", + "example": "153554b5-ae44-44a0-8f4f-7bbac5657ad4" + }, + "send_at": { + "description": "SendAt is an optional parameter used to schedule a message to be sent in the future. The time is considered to be in your profile's local timezone and you can queue messages for up to 20 days (480 hours) in the future.", + "type": "string", + "example": "2025-12-19T16:39:57-08:00" + }, + "to": { + "type": "string", + "example": "+18005550100" + } + } + }, + "requests.MessageSendScheduleStore": { + "type": "object", + "required": [ + "name", + "timezone", + "windows" + ], + "properties": { + "name": { + "type": "string" + }, + "timezone": { + "type": "string" + }, + "windows": { + "type": "array", + "items": { + "$ref": "#/definitions/requests.MessageSendScheduleWindow" + } + } + } + }, + "requests.MessageSendScheduleWindow": { + "type": "object", + "required": [ + "day_of_week", + "end_minute", + "start_minute" + ], + "properties": { + "day_of_week": { + "type": "integer" + }, + "end_minute": { + "type": "integer" + }, + "start_minute": { + "type": "integer" + } + } + }, + "requests.MessageThreadUpdate": { + "type": "object", + "properties": { + "is_archived": { + "type": "boolean", + "example": true + }, + "unread_count": { + "type": "integer", + "example": 0 + } + } + }, + "requests.PhoneAPIKeyStoreRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "example": "My Phone API Key" + } + } + }, + "requests.PhoneFCMToken": { + "type": "object", + "required": [ + "fcm_token", + "phone_number", + "sim" + ], + "properties": { + "fcm_token": { + "description": "FcmToken is either a Firebase registration token or a public HTTPS adapter callback URL.", + "type": "string", + "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." + }, + "phone_number": { + "type": "string", + "example": "[+18005550199]" + }, + "sim": { + "description": "SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot", + "type": "string", + "example": "SIM1" + } + } + }, + "requests.PhoneUpsert": { + "type": "object", + "required": [ + "fcm_token", + "max_send_attempts", + "message_expiration_seconds", + "messages_per_minute", + "missed_call_auto_reply", + "phone_number", + "sim", + "unarchive_thread" + ], + "properties": { + "archive_new_outgoing_message_threads": { + "description": "ArchiveNewOutgoingMessageThreads archives new conversations started by an outgoing message on this phone.", + "type": "boolean", + "example": false + }, + "fcm_token": { + "description": "FcmToken is either a Firebase registration token or a public HTTPS adapter callback URL.", + "type": "string", + "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." + }, + "max_send_attempts": { + "description": "MaxSendAttempts is the number of attempts when sending an SMS message to handle the case where the phone is offline.", + "type": "integer", + "example": 2 + }, + "message_expiration_seconds": { + "description": "MessageExpirationSeconds is the duration in seconds after sending a message when it is considered to be expired.", + "type": "integer", + "example": 12345 + }, + "message_send_schedule_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "messages_per_minute": { + "type": "integer", + "example": 1 + }, + "missed_call_auto_reply": { + "type": "string", + "example": "e.g. This phone cannot receive calls. Please send an SMS instead." + }, + "phone_number": { + "type": "string", + "example": "+18005550199" + }, + "sim": { + "description": "SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot", + "type": "string", + "example": "SIM1" + }, + "unarchive_thread": { + "description": "UnarchiveThread moves an archived thread back to the inbox when a new message is received on this phone.", + "type": "boolean", + "example": false + } + } + }, + "requests.UserNotificationUpdate": { + "type": "object", + "required": [ + "heartbeat_enabled", + "message_status_enabled", + "newsletter_enabled", + "webhook_enabled" + ], + "properties": { + "heartbeat_enabled": { + "type": "boolean", + "example": true + }, + "message_status_enabled": { + "type": "boolean", + "example": true + }, + "newsletter_enabled": { + "type": "boolean", + "example": true + }, + "webhook_enabled": { + "type": "boolean", + "example": true + } + } + }, + "requests.UserPaymentInvoice": { + "type": "object", + "required": [ + "address", + "city", + "country", + "name", + "notes", + "state", + "zip_code" + ], + "properties": { + "address": { + "type": "string", + "example": "221B Baker Street, London" + }, + "city": { + "type": "string", + "example": "Los Angeles" + }, + "country": { + "type": "string", + "example": "US" + }, + "name": { + "type": "string", + "example": "Acme Corp" + }, + "notes": { + "type": "string", + "example": "Thank you for your business!" + }, + "state": { + "type": "string", + "example": "CA" + }, + "zip_code": { + "type": "string", + "example": "9800" + } + } + }, + "requests.UserUpdate": { + "type": "object", + "required": [ + "active_phone_id", + "timezone" + ], + "properties": { + "active_phone_id": { + "type": "string", + "example": "32343a19-da5e-4b1b-a767-3298a73703cb" + }, + "timezone": { + "type": "string", + "example": "Europe/Helsinki" + } + } + }, + "requests.WebhookStore": { + "type": "object", + "required": [ + "events", + "phone_numbers", + "signing_key", + "url" + ], + "properties": { + "events": { + "type": "array", + "items": { + "type": "string" + } + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550100", + "+18005550100" + ] + }, + "signing_key": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "requests.WebhookUpdate": { + "type": "object", + "required": [ + "events", + "phone_numbers", + "signing_key", + "url" + ], + "properties": { + "events": { + "type": "array", + "items": { + "type": "string" + } + }, + "phone_numbers": { + "type": "array", + "items": { + "type": "string" + }, + "example": [ + "+18005550100", + "+18005550100" + ] + }, + "signing_key": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "responses.BadRequest": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "string", + "example": "The request body is not a valid JSON string" + }, + "message": { + "type": "string", + "example": "The request isn't properly formed" + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.BillingUsageResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.BillingUsage" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.BillingUsagesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.BillingUsage" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.BulkMessagesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.BulkMessage" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.ContactResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Contact" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.ContactsCreatedResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Contact" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.ContactsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status", + "total" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Contact" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + }, + "total": { + "description": "Total is the number of contacts matching the request filter for the\nuser, independent of the pagination skip/limit applied to Data.", + "type": "integer", + "example": 57 + } + } + }, + "responses.DiscordResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Discord" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.DiscordsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Discord" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.HeartbeatResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Heartbeat" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.HeartbeatsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Heartbeat" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.InternalServerError": { + "type": "object", + "required": [ + "message", + "status" + ], + "properties": { + "message": { + "type": "string", + "example": "We ran into an internal error while handling the request." + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.MessageResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Message" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessageSendScheduleResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.MessageSendSchedule" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessageSendSchedulesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.MessageSendSchedule" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessageThreadResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.MessageThread" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessageThreadsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.MessageThread" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.MessagesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Message" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.NoContent": { + "type": "object", + "required": [ + "message", + "status" + ], + "properties": { + "message": { + "type": "string", + "example": "action performed successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.NotFound": { + "type": "object", + "required": [ + "message", + "status" + ], + "properties": { + "message": { + "type": "string", + "example": "cannot find message with ID [32343a19-da5e-4b1b-a767-3298a73703ca]" + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.OkString": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "string" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.PaymentRequired": { + "type": "object", + "required": [ + "message", + "status" + ], + "properties": { + "message": { + "type": "string", + "example": "You have reached the maximum number of allowed resources. Please upgrade your plan." + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.PhoneAPIKeyResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.PhoneAPIKey" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.PhoneAPIKeysResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.PhoneAPIKey" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.PhoneResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Phone" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.PhonesResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Phone" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.Unauthorized": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "string", + "example": "Make sure your API key is set in the [X-API-Key] header in the request" + }, + "message": { + "type": "string", + "example": "You are not authorized to carry out this request." + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.UnprocessableEntity": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "message": { + "type": "string", + "example": "validation errors while handling request" + }, + "status": { + "type": "string", + "example": "error" + } + } + }, + "responses.UserResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.User" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.UserSubscriptionPaymentsResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "type": "object", + "required": [ + "attributes", + "id", + "type" + ], + "properties": { + "attributes": { + "type": "object", + "required": [ + "billing_reason", + "card_brand", + "card_last_four", + "created_at", + "currency", + "currency_rate", + "discount_total", + "discount_total_formatted", + "discount_total_usd", + "refunded", + "refunded_amount", + "refunded_amount_formatted", + "refunded_amount_usd", + "refunded_at", + "status", + "status_formatted", + "subtotal", + "subtotal_formatted", + "subtotal_usd", + "tax", + "tax_formatted", + "tax_inclusive", + "tax_usd", + "total", + "total_formatted", + "total_usd", + "updated_at" + ], + "properties": { + "billing_reason": { + "type": "string" + }, + "card_brand": { + "type": "string" + }, + "card_last_four": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "currency": { + "type": "string" + }, + "currency_rate": { + "type": "string" + }, + "discount_total": { + "type": "integer" + }, + "discount_total_formatted": { + "type": "string" + }, + "discount_total_usd": { + "type": "integer" + }, + "refunded": { + "type": "boolean" + }, + "refunded_amount": { + "type": "integer" + }, + "refunded_amount_formatted": { + "type": "string" + }, + "refunded_amount_usd": { + "type": "integer" + }, + "refunded_at": {}, + "status": { + "type": "string" + }, + "status_formatted": { + "type": "string" + }, + "subtotal": { + "type": "integer" + }, + "subtotal_formatted": { + "type": "string" + }, + "subtotal_usd": { + "type": "integer" + }, + "tax": { + "type": "integer" + }, + "tax_formatted": { + "type": "string" + }, + "tax_inclusive": { + "type": "boolean" + }, + "tax_usd": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "total_formatted": { + "type": "string" + }, + "total_usd": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "id": { + "type": "string" + }, + "type": { + "type": "string" + } + } + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.WebhookResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "$ref": "#/definitions/entities.Webhook" + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + }, + "responses.WebhooksResponse": { + "type": "object", + "required": [ + "data", + "message", + "status" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/entities.Webhook" + } + }, + "message": { + "type": "string", + "example": "Request handled successfully" + }, + "status": { + "type": "string", + "example": "success" + } + } + } + }, + "securityDefinitions": { + "ApiKeyAuth": { + "type": "apiKey", + "name": "x-api-Key", + "in": "header" + } + } +} \ No newline at end of file diff --git a/api/docs/swagger.yaml b/api/docs/swagger.yaml new file mode 100644 index 0000000000000000000000000000000000000000..838e3673895d01a99fe500da41f85310620c229f --- /dev/null +++ b/api/docs/swagger.yaml @@ -0,0 +1,4214 @@ +basePath: /v1 +definitions: + entities.BillingUsage: + properties: + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + end_timestamp: + example: "2022-01-31T23:59:59+00:00" + type: string + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + received_messages: + example: 465 + type: integer + sent_messages: + example: 321 + type: integer + start_timestamp: + example: "2022-01-01T00:00:00+00:00" + type: string + total_cost: + example: 0 + type: integer + updated_at: + example: "2022-06-05T14:26:10.303278+03:00" + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + required: + - created_at + - end_timestamp + - id + - received_messages + - sent_messages + - start_timestamp + - total_cost + - updated_at + - user_id + type: object + entities.BulkMessage: + properties: + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + delivered_count: + example: 25 + type: integer + expired_count: + example: 3 + type: integer + failed_count: + example: 5 + type: integer + pending_count: + example: 30 + type: integer + request_id: + example: bulk-httpsms-file.csv + type: string + scheduled_count: + example: 50 + type: integer + sent_count: + example: 40 + type: integer + total: + example: 150 + type: integer + required: + - created_at + - delivered_count + - expired_count + - failed_count + - pending_count + - request_id + - scheduled_count + - sent_count + - total + type: object + entities.Contact: + properties: + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + emails: + example: + - alice@example.com + items: + type: string + type: array + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + name: + example: Alice Smith + type: string + phone_numbers: + example: + - "+18005550199" + - "+18005550100" + items: + type: string + type: array + properties: + additionalProperties: + type: string + type: object + updated_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + required: + - created_at + - emails + - id + - name + - phone_numbers + - properties + - updated_at + - user_id + type: object + entities.Discord: + properties: + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + incoming_channel_id: + example: "1095780203256627291" + type: string + name: + example: Game Server + type: string + server_id: + example: "1095778291488653372" + type: string + updated_at: + example: "2022-06-05T14:26:10.303278+03:00" + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + required: + - created_at + - id + - incoming_channel_id + - name + - server_id + - updated_at + - user_id + type: object + entities.Heartbeat: + properties: + charging: + example: true + type: boolean + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + owner: + example: "+18005550199" + type: string + timestamp: + example: "2022-06-05T14:26:01.520828+03:00" + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + version: + example: 344c10f + type: string + required: + - charging + - id + - owner + - timestamp + - user_id + - version + type: object + entities.Message: + properties: + attachments: + example: + - https://example.com/image.jpg + - https://example.com/video.mp4 + items: + type: string + type: array + contact: + example: "+18005550100" + type: string + content: + example: This is a sample text message + type: string + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + delivered_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + encrypted: + example: false + type: boolean + expired_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + failed_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + failure_reason: + example: UNKNOWN + type: string + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + last_attempted_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + max_send_attempts: + example: 1 + type: integer + order_timestamp: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + owner: + example: "+18005550199" + type: string + received_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + request_id: + example: 153554b5-ae44-44a0-8f4f-7bbac5657ad4 + type: string + request_received_at: + example: "2022-06-05T14:26:01.520828+03:00" + type: string + scheduled_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + scheduled_send_time: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + send_attempt_count: + example: 0 + type: integer + send_time: + description: SendDuration is the number of nanoseconds from when the request + was received until when the mobile phone send the message + example: 133414 + type: integer + sent_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + sim: + allOf: + - $ref: '#/definitions/entities.SIM' + description: |- + SIM is the SIM card to use to send the message + * SMS1: use the SIM card in slot 1 + * SMS2: use the SIM card in slot 2 + * DEFAULT: used the default communication SIM card + example: DEFAULT + status: + example: pending + type: string + type: + example: mobile-terminated + type: string + updated_at: + example: "2022-06-05T14:26:10.303278+03:00" + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + required: + - attachments + - contact + - content + - created_at + - encrypted + - id + - max_send_attempts + - order_timestamp + - owner + - request_received_at + - send_attempt_count + - sim + - status + - type + - updated_at + - user_id + type: object + entities.MessageSendSchedule: + properties: + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + name: + example: Business Hours + type: string + timezone: + example: Europe/Tallinn + type: string + updated_at: + example: "2022-06-05T14:26:10.303278+03:00" + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + windows: + items: + $ref: '#/definitions/entities.MessageSendScheduleWindow' + type: array + required: + - created_at + - id + - name + - timezone + - updated_at + - user_id + - windows + type: object + entities.MessageSendScheduleWindow: + properties: + day_of_week: + example: 1 + type: integer + end_minute: + example: 1020 + type: integer + start_minute: + example: 540 + type: integer + required: + - day_of_week + - end_minute + - start_minute + type: object + entities.MessageThread: + properties: + color: + example: indigo + type: string + contact: + example: "+18005550100" + type: string + contact_details: + allOf: + - $ref: '#/definitions/entities.Contact' + description: ContactDetails is resolved at read time and never persisted. + created_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + id: + example: 32343a19-da5e-4b1b-a767-3298a73703ca + type: string + is_archived: + example: false + type: boolean + last_message_content: + example: This is a sample message content + type: string + last_message_id: + example: 32343a19-da5e-4b1b-a767-3298a73703ca + type: string + order_timestamp: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + owner: + example: "+18005550199" + type: string + status: + example: PENDING + type: string + unread_count: + example: 0 + type: integer + updated_at: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + required: + - color + - contact + - created_at + - id + - is_archived + - last_message_content + - last_message_id + - order_timestamp + - owner + - status + - unread_count + - updated_at + - user_id + type: object + entities.Phone: + properties: + archive_new_outgoing_message_threads: + description: ArchiveNewOutgoingMessageThreads archives new conversations started + by an outgoing message on this phone. + example: false + type: boolean + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + fcm_token: + example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd..... + type: string + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + max_send_attempts: + description: MaxSendAttempts determines how many times to retry sending an + SMS message + example: 2 + type: integer + message_expiration_seconds: + description: MessageExpirationSeconds is the duration in seconds after sending + a message when it is considered to be expired. + type: integer + message_send_schedule_id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + messages_per_minute: + example: 1 + type: integer + missed_call_auto_reply: + example: This phone cannot receive calls. Please send an SMS instead. + type: string + phone_number: + example: "+18005550199" + type: string + sim: + $ref: '#/definitions/entities.SIM' + unarchive_thread: + description: UnarchiveThread moves an archived message thread back to the + inbox when a new message is received on this phone. + example: false + type: boolean + updated_at: + example: "2022-06-05T14:26:10.303278+03:00" + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + required: + - archive_new_outgoing_message_threads + - created_at + - id + - max_send_attempts + - message_expiration_seconds + - messages_per_minute + - phone_number + - sim + - unarchive_thread + - updated_at + - user_id + type: object + entities.PhoneAPIKey: + properties: + api_key: + example: pk_DGW8NwQp7mxKaSZ72Xq9v6xxxxx + type: string + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + name: + example: Business Phone Key + type: string + phone_ids: + example: + - 32343a19-da5e-4b1b-a767-3298a73703cb + - 32343a19-da5e-4b1b-a767-3298a73703cc + items: + type: string + type: array + phone_numbers: + example: + - "+18005550199" + - "+18005550100" + items: + type: string + type: array + updated_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + user_email: + example: user@gmail.com + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + required: + - api_key + - created_at + - id + - name + - phone_ids + - phone_numbers + - updated_at + - user_email + - user_id + type: object + entities.SIM: + enum: + - SIM1 + - SIM2 + type: string + x-enum-varnames: + - SIM1 + - SIM2 + entities.SubscriptionName: + enum: + - free + - pro-monthly + - pro-yearly + - ultra-monthly + - ultra-yearly + - pro-lifetime + - 20k-monthly + - 100k-monthly + - 50k-monthly + - 200k-monthly + - 20k-yearly + type: string + x-enum-varnames: + - SubscriptionNameFree + - SubscriptionNameProMonthly + - SubscriptionNameProYearly + - SubscriptionNameUltraMonthly + - SubscriptionNameUltraYearly + - SubscriptionNameProLifetime + - SubscriptionName20KMonthly + - SubscriptionName100KMonthly + - SubscriptionName50KMonthly + - SubscriptionName200KMonthly + - SubscriptionName20KYearly + entities.User: + properties: + active_phone_id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + api_key: + example: x-api-key + type: string + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + email: + example: name@email.com + type: string + id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + notification_heartbeat_enabled: + example: true + type: boolean + notification_message_status_enabled: + example: true + type: boolean + notification_newsletter_enabled: + example: true + type: boolean + notification_webhook_enabled: + example: true + type: boolean + subscription_ends_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + subscription_id: + example: 8f9c71b8-b84e-4417-8408-a62274f65a08 + type: string + subscription_name: + allOf: + - $ref: '#/definitions/entities.SubscriptionName' + example: free + subscription_renews_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + subscription_status: + example: on_trial + type: string + timezone: + example: Europe/Helsinki + type: string + updated_at: + example: "2022-06-05T14:26:10.303278+03:00" + type: string + required: + - api_key + - created_at + - email + - id + - notification_heartbeat_enabled + - notification_message_status_enabled + - notification_newsletter_enabled + - notification_webhook_enabled + - subscription_id + - subscription_name + - timezone + - updated_at + type: object + entities.Webhook: + properties: + created_at: + example: "2022-06-05T14:26:02.302718+03:00" + type: string + events: + example: + - message.phone.received + items: + type: string + type: array + id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + phone_numbers: + example: + - "+18005550199" + - "+18005550100" + items: + type: string + type: array + signing_key: + example: DGW8NwQp7mxKaSZ72Xq9v67SLqSbWQvckzzmK8D6rvd7NywSEkdMJtuxKyEkYnCY + type: string + updated_at: + example: "2022-06-05T14:26:10.303278+03:00" + type: string + url: + example: https://example.com + type: string + user_id: + example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC + type: string + required: + - created_at + - events + - id + - phone_numbers + - signing_key + - updated_at + - url + - user_id + type: object + requests.ContactItem: + properties: + emails: + items: + type: string + type: array + name: + example: Alice Smith + type: string + phone_numbers: + items: + type: string + type: array + properties: + additionalProperties: + type: string + type: object + required: + - name + - phone_numbers + type: object + requests.ContactStoreRequest: + properties: + contacts: + items: + $ref: '#/definitions/requests.ContactItem' + type: array + required: + - contacts + type: object + requests.ContactUpdateRequest: + properties: + emails: + items: + type: string + type: array + name: + example: Alice Smith + type: string + phone_numbers: + items: + type: string + type: array + properties: + additionalProperties: + type: string + type: object + required: + - name + - phone_numbers + type: object + requests.DiscordStore: + properties: + incoming_channel_id: + type: string + name: + type: string + server_id: + type: string + required: + - incoming_channel_id + - name + - server_id + type: object + requests.DiscordUpdate: + properties: + incoming_channel_id: + type: string + name: + type: string + server_id: + type: string + required: + - incoming_channel_id + - name + - server_id + type: object + requests.HeartbeatStore: + properties: + charging: + type: boolean + phone_numbers: + items: + type: string + type: array + required: + - charging + - phone_numbers + type: object + requests.MessageAttachment: + properties: + content: + description: Content is the base64-encoded attachment data + example: base64data... + type: string + content_type: + description: ContentType is the MIME type of the attachment + example: image/jpeg + type: string + name: + description: Name is the original filename of the attachment + example: photo.jpg + type: string + required: + - content + - content_type + - name + type: object + requests.MessageBulkSend: + properties: + attachments: + description: Attachments are optional. When you provide a list of attachments, + the message will be sent out as an MMS + items: + type: string + type: array + content: + example: This is a sample text message + type: string + encrypted: + description: Encrypted is used to determine if the content is end-to-end encrypted. + Make sure to set the encryption key on the httpSMS mobile app + example: false + type: boolean + from: + example: "+18005550199" + type: string + request_id: + description: RequestID is an optional parameter used to track a request from + the client's perspective + example: 153554b5-ae44-44a0-8f4f-7bbac5657ad4 + type: string + to: + example: + - "+18005550100" + - "+18005550100" + items: + type: string + type: array + required: + - content + - from + - to + type: object + requests.MessageCallMissed: + properties: + from: + example: "+18005550199" + type: string + sim: + example: SIM1 + type: string + timestamp: + example: "2022-06-05T14:26:09.527976+03:00" + type: string + to: + example: "+18005550100" + type: string + required: + - from + - sim + - timestamp + - to + type: object + requests.MessageEvent: + properties: + event_name: + description: |- + EventName is the type of event + * SENT: is emitted when a message is sent by the mobile phone + * FAILED: is event is emitted when the message could not be sent by the mobile phone + * DELIVERED: is event is emitted when a delivery report has been received by the mobile phone + example: SENT + type: string + reason: + description: Reason is the exact error message in case the event is an error + type: string + timestamp: + description: Timestamp is the time when the event was emitted, Please send + the timestamp in UTC with as much precision as possible + example: "2022-06-05T14:26:09.527976+03:00" + type: string + required: + - event_name + - reason + - timestamp + type: object + requests.MessageReceive: + properties: + attachments: + description: Attachments is the list of MMS attachments received with the + message + items: + $ref: '#/definitions/requests.MessageAttachment' + type: array + content: + example: This is a sample text message received on a phone + type: string + encrypted: + description: Encrypted is used to determine if the content is end-to-end encrypted. + Make sure to set the encryption key on the httpSMS mobile app + example: false + type: boolean + from: + example: "+18005550199" + type: string + sim: + allOf: + - $ref: '#/definitions/entities.SIM' + description: SIM card that received the message + example: SIM1 + timestamp: + description: Timestamp is the time when the event was emitted, Please send + the timestamp in UTC with as much precision as possible + example: "2022-06-05T14:26:09.527976+03:00" + type: string + to: + example: "+18005550100" + type: string + required: + - content + - encrypted + - from + - sim + - timestamp + - to + type: object + requests.MessageSend: + properties: + attachments: + description: Attachments are optional. When you provide a list of attachments, + the message will be sent out as an MMS + example: + - https://example.com/image.jpg + - https://example.com/video.mp4 + items: + type: string + type: array + content: + example: This is a sample text message + type: string + encrypted: + description: Encrypted is an optional parameter used to determine if the content + is end-to-end encrypted. Make sure to set the encryption key on the httpSMS + mobile app + example: false + type: boolean + from: + example: "+18005550199" + type: string + request_id: + description: RequestID is an optional parameter used to track a request from + the client's perspective + example: 153554b5-ae44-44a0-8f4f-7bbac5657ad4 + type: string + send_at: + description: SendAt is an optional parameter used to schedule a message to + be sent in the future. The time is considered to be in your profile's local + timezone and you can queue messages for up to 20 days (480 hours) in the + future. + example: "2025-12-19T16:39:57-08:00" + type: string + to: + example: "+18005550100" + type: string + required: + - content + - from + - to + type: object + requests.MessageSendScheduleStore: + properties: + name: + type: string + timezone: + type: string + windows: + items: + $ref: '#/definitions/requests.MessageSendScheduleWindow' + type: array + required: + - name + - timezone + - windows + type: object + requests.MessageSendScheduleWindow: + properties: + day_of_week: + type: integer + end_minute: + type: integer + start_minute: + type: integer + required: + - day_of_week + - end_minute + - start_minute + type: object + requests.MessageThreadUpdate: + properties: + is_archived: + example: true + type: boolean + unread_count: + example: 0 + type: integer + type: object + requests.PhoneAPIKeyStoreRequest: + properties: + name: + example: My Phone API Key + type: string + required: + - name + type: object + requests.PhoneFCMToken: + properties: + fcm_token: + description: FcmToken is either a Firebase registration token or a public + HTTPS adapter callback URL. + example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd..... + type: string + phone_number: + example: '[+18005550199]' + type: string + sim: + description: SIM is the SIM slot of the phone in case the phone has more than + 1 SIM slot + example: SIM1 + type: string + required: + - fcm_token + - phone_number + - sim + type: object + requests.PhoneUpsert: + properties: + archive_new_outgoing_message_threads: + description: ArchiveNewOutgoingMessageThreads archives new conversations started + by an outgoing message on this phone. + example: false + type: boolean + fcm_token: + description: FcmToken is either a Firebase registration token or a public + HTTPS adapter callback URL. + example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd..... + type: string + max_send_attempts: + description: MaxSendAttempts is the number of attempts when sending an SMS + message to handle the case where the phone is offline. + example: 2 + type: integer + message_expiration_seconds: + description: MessageExpirationSeconds is the duration in seconds after sending + a message when it is considered to be expired. + example: 12345 + type: integer + message_send_schedule_id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + messages_per_minute: + example: 1 + type: integer + missed_call_auto_reply: + example: e.g. This phone cannot receive calls. Please send an SMS instead. + type: string + phone_number: + example: "+18005550199" + type: string + sim: + description: SIM is the SIM slot of the phone in case the phone has more than + 1 SIM slot + example: SIM1 + type: string + unarchive_thread: + description: UnarchiveThread moves an archived thread back to the inbox when + a new message is received on this phone. + example: false + type: boolean + required: + - fcm_token + - max_send_attempts + - message_expiration_seconds + - messages_per_minute + - missed_call_auto_reply + - phone_number + - sim + - unarchive_thread + type: object + requests.UserNotificationUpdate: + properties: + heartbeat_enabled: + example: true + type: boolean + message_status_enabled: + example: true + type: boolean + newsletter_enabled: + example: true + type: boolean + webhook_enabled: + example: true + type: boolean + required: + - heartbeat_enabled + - message_status_enabled + - newsletter_enabled + - webhook_enabled + type: object + requests.UserPaymentInvoice: + properties: + address: + example: 221B Baker Street, London + type: string + city: + example: Los Angeles + type: string + country: + example: US + type: string + name: + example: Acme Corp + type: string + notes: + example: Thank you for your business! + type: string + state: + example: CA + type: string + zip_code: + example: "9800" + type: string + required: + - address + - city + - country + - name + - notes + - state + - zip_code + type: object + requests.UserUpdate: + properties: + active_phone_id: + example: 32343a19-da5e-4b1b-a767-3298a73703cb + type: string + timezone: + example: Europe/Helsinki + type: string + required: + - active_phone_id + - timezone + type: object + requests.WebhookStore: + properties: + events: + items: + type: string + type: array + phone_numbers: + example: + - "+18005550100" + - "+18005550100" + items: + type: string + type: array + signing_key: + type: string + url: + type: string + required: + - events + - phone_numbers + - signing_key + - url + type: object + requests.WebhookUpdate: + properties: + events: + items: + type: string + type: array + phone_numbers: + example: + - "+18005550100" + - "+18005550100" + items: + type: string + type: array + signing_key: + type: string + url: + type: string + required: + - events + - phone_numbers + - signing_key + - url + type: object + responses.BadRequest: + properties: + data: + example: The request body is not a valid JSON string + type: string + message: + example: The request isn't properly formed + type: string + status: + example: error + type: string + required: + - data + - message + - status + type: object + responses.BillingUsageResponse: + properties: + data: + $ref: '#/definitions/entities.BillingUsage' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.BillingUsagesResponse: + properties: + data: + items: + $ref: '#/definitions/entities.BillingUsage' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.BulkMessagesResponse: + properties: + data: + items: + $ref: '#/definitions/entities.BulkMessage' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.ContactResponse: + properties: + data: + $ref: '#/definitions/entities.Contact' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.ContactsCreatedResponse: + properties: + data: + items: + $ref: '#/definitions/entities.Contact' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.ContactsResponse: + properties: + data: + items: + $ref: '#/definitions/entities.Contact' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + total: + description: |- + Total is the number of contacts matching the request filter for the + user, independent of the pagination skip/limit applied to Data. + example: 57 + type: integer + required: + - data + - message + - status + - total + type: object + responses.DiscordResponse: + properties: + data: + $ref: '#/definitions/entities.Discord' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.DiscordsResponse: + properties: + data: + items: + $ref: '#/definitions/entities.Discord' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.HeartbeatResponse: + properties: + data: + $ref: '#/definitions/entities.Heartbeat' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.HeartbeatsResponse: + properties: + data: + items: + $ref: '#/definitions/entities.Heartbeat' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.InternalServerError: + properties: + message: + example: We ran into an internal error while handling the request. + type: string + status: + example: error + type: string + required: + - message + - status + type: object + responses.MessageResponse: + properties: + data: + $ref: '#/definitions/entities.Message' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.MessageSendScheduleResponse: + properties: + data: + $ref: '#/definitions/entities.MessageSendSchedule' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.MessageSendSchedulesResponse: + properties: + data: + items: + $ref: '#/definitions/entities.MessageSendSchedule' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.MessageThreadResponse: + properties: + data: + $ref: '#/definitions/entities.MessageThread' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.MessageThreadsResponse: + properties: + data: + items: + $ref: '#/definitions/entities.MessageThread' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.MessagesResponse: + properties: + data: + items: + $ref: '#/definitions/entities.Message' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.NoContent: + properties: + message: + example: action performed successfully + type: string + status: + example: success + type: string + required: + - message + - status + type: object + responses.NotFound: + properties: + message: + example: cannot find message with ID [32343a19-da5e-4b1b-a767-3298a73703ca] + type: string + status: + example: error + type: string + required: + - message + - status + type: object + responses.OkString: + properties: + data: + type: string + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.PaymentRequired: + properties: + message: + example: You have reached the maximum number of allowed resources. Please + upgrade your plan. + type: string + status: + example: error + type: string + required: + - message + - status + type: object + responses.PhoneAPIKeyResponse: + properties: + data: + $ref: '#/definitions/entities.PhoneAPIKey' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.PhoneAPIKeysResponse: + properties: + data: + items: + $ref: '#/definitions/entities.PhoneAPIKey' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.PhoneResponse: + properties: + data: + $ref: '#/definitions/entities.Phone' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.PhonesResponse: + properties: + data: + items: + $ref: '#/definitions/entities.Phone' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.Unauthorized: + properties: + data: + example: Make sure your API key is set in the [X-API-Key] header in the request + type: string + message: + example: You are not authorized to carry out this request. + type: string + status: + example: error + type: string + required: + - data + - message + - status + type: object + responses.UnprocessableEntity: + properties: + data: + additionalProperties: + items: + type: string + type: array + type: object + message: + example: validation errors while handling request + type: string + status: + example: error + type: string + required: + - data + - message + - status + type: object + responses.UserResponse: + properties: + data: + $ref: '#/definitions/entities.User' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.UserSubscriptionPaymentsResponse: + properties: + data: + items: + properties: + attributes: + properties: + billing_reason: + type: string + card_brand: + type: string + card_last_four: + type: string + created_at: + type: string + currency: + type: string + currency_rate: + type: string + discount_total: + type: integer + discount_total_formatted: + type: string + discount_total_usd: + type: integer + refunded: + type: boolean + refunded_amount: + type: integer + refunded_amount_formatted: + type: string + refunded_amount_usd: + type: integer + refunded_at: {} + status: + type: string + status_formatted: + type: string + subtotal: + type: integer + subtotal_formatted: + type: string + subtotal_usd: + type: integer + tax: + type: integer + tax_formatted: + type: string + tax_inclusive: + type: boolean + tax_usd: + type: integer + total: + type: integer + total_formatted: + type: string + total_usd: + type: integer + updated_at: + type: string + required: + - billing_reason + - card_brand + - card_last_four + - created_at + - currency + - currency_rate + - discount_total + - discount_total_formatted + - discount_total_usd + - refunded + - refunded_amount + - refunded_amount_formatted + - refunded_amount_usd + - refunded_at + - status + - status_formatted + - subtotal + - subtotal_formatted + - subtotal_usd + - tax + - tax_formatted + - tax_inclusive + - tax_usd + - total + - total_formatted + - total_usd + - updated_at + type: object + id: + type: string + type: + type: string + required: + - attributes + - id + - type + type: object + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.WebhookResponse: + properties: + data: + $ref: '#/definitions/entities.Webhook' + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object + responses.WebhooksResponse: + properties: + data: + items: + $ref: '#/definitions/entities.Webhook' + type: array + message: + example: Request handled successfully + type: string + status: + example: success + type: string + required: + - data + - message + - status + type: object +host: api.httpsms.com +info: + contact: + email: support@httpsms.com + name: support@httpsms.com + description: Use your Android phone to send and receive SMS messages via a simple + programmable API with end-to-end encryption. + license: + name: AGPL-3.0 + url: https://raw.githubusercontent.com/NdoleStudio/http-sms-manager/main/LICENSE + title: httpSMS API Reference + version: "1.0" +paths: + /billing/usage: + get: + consumes: + - application/json + description: Get the summary of sent and received messages for a user in the + current month + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.BillingUsageResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get Billing Usage. + tags: + - Billing + /billing/usage-history: + get: + consumes: + - application/json + description: Get billing usage records of sent and received messages for a user + in the past. It will be sorted by timestamp in descending order. + parameters: + - description: number of heartbeats to skip + in: query + minimum: 0 + name: skip + type: integer + - description: number of heartbeats to return + in: query + maximum: 100 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.BillingUsagesResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get billing usage history. + tags: + - Billing + /bulk-messages: + get: + consumes: + - application/json + description: Fetches the last 10 bulk message order summaries for the authenticated + user showing counts per status. + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.BulkMessagesResponse' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: List bulk message orders + tags: + - BulkSMS + post: + consumes: + - multipart/form-data + description: Sends bulk SMS messages to multiple users based on our [CSV template](https://httpsms.com/templates/httpsms-bulk.csv) + or our [Excel template](https://httpsms.com/templates/httpsms-bulk.xlsx). + parameters: + - description: The Excel or CSV file containing the messages to be sent. + in: formData + name: document + required: true + type: file + produces: + - application/json + responses: + "202": + description: Accepted + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Store bulk SMS file + tags: + - BulkSMS + /contacts: + get: + consumes: + - application/json + description: Returns the paginated list of contacts for the authenticated user. + The top-level "total" field is the number of contacts matching the query filter, + independent of skip/limit, so clients can drive server-side pagination. + parameters: + - description: number of contacts to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter contacts containing query + in: query + name: query + type: string + - description: field to sort contacts by + enum: + - name + - updated_at + in: query + name: sort_by + type: string + - description: sort contacts in descending order + in: query + name: sort_descending + type: boolean + - description: number of contacts to return + in: query + maximum: 100 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.ContactsResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: List contacts + tags: + - Contacts + post: + consumes: + - application/json + description: Creates a single contact or a batch of contacts. Accepts a JSON + array or an object with a "contacts" array. + parameters: + - description: Contact(s) to create + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.ContactStoreRequest' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/responses.ContactsCreatedResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "402": + description: Payment Required + schema: + $ref: '#/definitions/responses.PaymentRequired' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Create one or many contacts + tags: + - Contacts + /contacts/{contactID}: + delete: + consumes: + - application/json + description: Deletes a single contact from the database. + parameters: + - description: ID of the contact + in: path + name: contactID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete a contact + tags: + - Contacts + put: + consumes: + - application/json + description: Updates the details of a single contact. + parameters: + - description: ID of the contact + in: path + name: contactID + required: true + type: string + - description: Contact details to update + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.ContactUpdateRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.ContactResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Update a contact + tags: + - Contacts + /contacts/upload: + post: + consumes: + - multipart/form-data + description: 'Uploads a CSV file (multipart field "document") of contacts. Columns: + Name, Emails, PhoneNumbers (multi-values separated by ";").' + parameters: + - description: CSV file of contacts + in: formData + name: document + required: true + type: file + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/responses.ContactsCreatedResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "402": + description: Payment Required + schema: + $ref: '#/definitions/responses.PaymentRequired' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Import contacts from CSV + tags: + - Contacts + /discord-integrations: + get: + consumes: + - application/json + description: Get the discord integrations of a user + parameters: + - description: number of discord integrations to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter discord integrations containing query + in: query + name: query + type: string + - description: number of discord integrations to return + in: query + maximum: 20 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.DiscordsResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get discord integrations of a user + tags: + - DiscordIntegration + post: + consumes: + - application/json + description: Store a discord integration for the authenticated user + parameters: + - description: Payload of the discord integration request + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.DiscordStore' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/responses.DiscordResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Store discord integration + tags: + - DiscordIntegration + /discord-integrations/{discordID}: + delete: + consumes: + - application/json + description: Delete a discord integration for a user + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the discord integration + in: path + name: discordID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete discord integration + tags: + - Webhooks + put: + consumes: + - application/json + description: Update a discord integration for the currently authenticated user + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the discord integration + in: path + name: discordID + required: true + type: string + - description: Payload of discord integration to update + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.DiscordUpdate' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.DiscordResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Update a discord integration + tags: + - DiscordIntegration + /discord/event: + post: + consumes: + - application/json + description: Publish a discord event to the registered listeners + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + summary: Consume a discord event + tags: + - Discord + /heartbeats: + get: + consumes: + - application/json + description: Get the last time a phone number requested for outstanding messages. + It will be sorted by timestamp in descending order. + parameters: + - default: "+18005550199" + description: the owner's phone number + in: query + name: owner + required: true + type: string + - description: number of heartbeats to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter containing query + in: query + name: query + type: string + - description: number of heartbeats to return + in: query + maximum: 20 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.HeartbeatsResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get heartbeats of an owner phone number + tags: + - Heartbeats + post: + consumes: + - application/json + description: Store the heartbeat to make notify that a phone number is still + active + parameters: + - description: Payload of the heartbeat request + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.HeartbeatStore' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.HeartbeatResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Register heartbeat of an owner phone number + tags: + - Heartbeats + /integration/3cx/messages: + post: + consumes: + - application/json + description: Sends an SMS message from the 3CX platform + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + summary: Sends a 3CX SMS message + tags: + - 3CXIntegration + /message-threads: + get: + consumes: + - application/json + description: Get list of contacts which a phone number has communicated with + (threads). It will be sorted by timestamp in descending order. + parameters: + - default: "+18005550199" + description: owner phone number + in: query + name: owner + required: true + type: string + - description: number of messages to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter message threads containing query + in: query + name: query + type: string + - description: number of messages to return + in: query + maximum: 20 + minimum: 1 + name: limit + type: integer + - description: include matching contact details + in: query + name: contacts + type: boolean + - default: false + description: only include threads with unread messages + in: query + name: unread_only + type: boolean + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageThreadsResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get message threads for a phone number + tags: + - MessageThreads + /message-threads/{messageThreadID}: + delete: + consumes: + - application/json + description: Delete a message thread from the database and also deletes all + the messages in the thread. + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the message thread + in: path + name: messageThreadID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete a message thread from the database. + tags: + - MessageThreads + get: + description: Returns a conversation belonging to the authenticated user, including + matching contact details when available. + parameters: + - description: ID of the message thread + in: path + name: messageThreadID + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageThreadResponse' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get a message thread + tags: + - MessageThreads + put: + consumes: + - application/json + description: Updates the details of a message thread + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the message thread + in: path + name: messageThreadID + required: true + type: string + - description: Payload of message thread details to update + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.MessageThreadUpdate' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageThreadResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Update a message thread + tags: + - MessageThreads + /messages: + get: + consumes: + - application/json + description: Get list of messages which are sent between 2 phone numbers. It + will be sorted by timestamp in descending order. + parameters: + - default: "+18005550199" + description: the owner's phone number + in: query + name: owner + required: true + type: string + - default: "+18005550100" + description: the contact's phone number + in: query + name: contact + required: true + type: string + - description: number of messages to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter messages containing query + in: query + name: query + type: string + - description: number of messages to return + in: query + maximum: 20 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessagesResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get messages which are sent between 2 phone numbers + tags: + - Messages + /messages/{messageID}: + delete: + consumes: + - application/json + description: Delete a message from the database and removes the message content + from the list of threads. + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the message + in: path + name: messageID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete a message from the database. + tags: + - Messages + get: + consumes: + - application/json + description: Get a message from the database by the message ID. + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the message + in: path + name: messageID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.MessageResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get a message from the database. + tags: + - Messages + /messages/{messageID}/events: + post: + consumes: + - application/json + description: Use this endpoint to send events for a message when it is failed, + sent or delivered by the mobile phone. + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the message + in: path + name: messageID + required: true + type: string + - description: Payload of the event emitted. + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.MessageEvent' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Upsert an event for a message on the mobile phone + tags: + - Messages + /messages/bulk-send: + post: + consumes: + - application/json + description: Add bulk SMS messages to be sent by the android phone + parameters: + - description: Bulk send message request payload + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.MessageBulkSend' + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/responses.MessagesResponse' + type: array + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Send bulk SMS messages + tags: + - Messages + /messages/calls/missed: + post: + consumes: + - application/json + description: This endpoint is called by the httpSMS android app to register + a missed call event on the mobile phone. + parameters: + - description: Payload of the missed call event. + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.MessageCallMissed' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Register a missed call event on the mobile phone + tags: + - Messages + /messages/outstanding: + get: + consumes: + - application/json + description: Get an outstanding message to be sent by an android phone + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703cb + description: The ID of the message + in: query + name: message_id + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get an outstanding message + tags: + - Messages + /messages/receive: + post: + consumes: + - application/json + description: Add a new message received from a mobile phone + parameters: + - description: Received message request payload + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.MessageReceive' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Receive a new SMS message from a mobile phone + tags: + - Messages + /messages/search: + get: + consumes: + - application/json + description: This returns the list of all messages based on the filter criteria + including missed calls + parameters: + - description: Cloudflare turnstile token https://www.cloudflare.com/en-gb/application-services/products/turnstile/ + in: header + name: token + required: true + type: string + - default: +18005550199,+18005550100 + description: the owner's phone numbers + in: query + name: owners + required: true + type: string + - description: number of messages to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter messages containing query + in: query + name: query + type: string + - description: number of messages to return + in: query + maximum: 200 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessagesResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Search all messages of a user + tags: + - Messages + /messages/send: + post: + consumes: + - application/json + description: Add a new SMS message to be sent by your Android phone + parameters: + - description: Send message request payload + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.MessageSend' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Send an SMS message + tags: + - Messages + /phone-api-keys: + get: + consumes: + - application/json + description: Get list phone API keys which a user has registered on the httpSMS + application + parameters: + - description: number of phone api keys to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter phone api keys with name containing query + in: query + name: query + type: string + - description: number of phone api keys to return + in: query + maximum: 100 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.PhoneAPIKeysResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get the phone API keys of a user + tags: + - PhoneAPIKeys + post: + consumes: + - application/json + description: Creates a new phone API key which can be used to log in to the + httpSMS app on your Android phone + parameters: + - description: Payload of new phone API key. + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.PhoneAPIKeyStoreRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.PhoneAPIKeyResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "402": + description: Payment Required + schema: + $ref: '#/definitions/responses.PaymentRequired' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Store phone API key + tags: + - PhoneAPIKeys + /phone-api-keys/{phoneAPIKeyID}: + delete: + consumes: + - application/json + description: Delete a phone API Key from the database and cannot be used for + authentication anymore. + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the phone API key + in: path + name: phoneAPIKeyID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete a phone API key from the database. + tags: + - PhoneAPIKeys + /phone-api-keys/{phoneAPIKeyID}/phones/{phoneID}: + delete: + consumes: + - application/json + description: You will need to login again to the httpSMS app on your Android + phone with a new phone API key. + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the phone API key + in: path + name: phoneAPIKeyID + required: true + type: string + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the phone + in: path + name: phoneID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Remove the association of a phone from the phone API key. + tags: + - PhoneAPIKeys + /phones: + get: + consumes: + - application/json + description: Get list of phones which a user has registered on the http sms + application + parameters: + - description: number of heartbeats to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter phones containing query + in: query + name: query + type: string + - description: number of phones to return + in: query + maximum: 20 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.PhonesResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get phones of a user + tags: + - Phones + put: + consumes: + - application/json + description: Updates properties of a user's phone. If the phone with this number + does not exist, a new one will be created. Think of this method like an 'upsert'. + URL-backed phone gateways receive FCM-compatible HTTP wake-ups. + parameters: + - description: Payload of new phone number. + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.PhoneUpsert' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.PhoneResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Upsert Phone + tags: + - Phones + /phones/{phoneID}: + delete: + consumes: + - application/json + description: Delete a phone that has been sored in the database + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the phone + in: path + name: phoneID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete Phone + tags: + - Phones + /phones/fcm-token: + put: + consumes: + - application/json + description: Updates the FCM token or adapter callback URL of a phone. If the + phone with this number does not exist, a new one will be created. Think of + this method like an 'upsert'. URL-backed phone gateways receive FCM-compatible + HTTP wake-ups. + parameters: + - description: Payload of new FCM token. + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.PhoneFCMToken' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.PhoneResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Upserts the FCM token of a phone + tags: + - Phones + /send-schedules: + get: + description: List all send schedules owned by the authenticated user. + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageSendSchedulesResponse' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: List send schedules + tags: + - SendSchedules + post: + consumes: + - application/json + description: Create a new send schedule for the authenticated user. + parameters: + - description: Payload of new send schedule. + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.MessageSendScheduleStore' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/responses.MessageSendScheduleResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "402": + description: Payment Required + schema: + $ref: '#/definitions/responses.PaymentRequired' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Create send schedule + tags: + - SendSchedules + /send-schedules/{scheduleID}: + delete: + description: Delete a send schedule owned by the authenticated user. + parameters: + - description: Schedule ID + in: path + name: scheduleID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete send schedule + tags: + - SendSchedules + put: + consumes: + - application/json + description: Update a send schedule owned by the authenticated user. + parameters: + - description: Schedule ID + in: path + name: scheduleID + required: true + type: string + - description: Payload of updated send schedule. + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.MessageSendScheduleStore' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.MessageSendScheduleResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Update send schedule + tags: + - SendSchedules + /users/{userID}/api-keys: + delete: + consumes: + - application/json + description: Rotate the user's API key in case the current API Key is compromised + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the user to update + in: path + name: userID + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.UserResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Rotate the user's API Key + tags: + - Users + /users/{userID}/notifications: + put: + consumes: + - application/json + description: Update the email notification settings for a user + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the user to update + in: path + name: userID + required: true + type: string + - description: User notification details to update + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.UserNotificationUpdate' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.UserResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Update notification settings + tags: + - Users + /users/me: + delete: + consumes: + - application/json + description: Deletes the currently authenticated user together with all their + data. + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/responses.NoContent' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete a user + tags: + - Users + get: + consumes: + - application/json + description: Get details of the currently authenticated user + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.UserResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get current user + tags: + - Users + put: + consumes: + - application/json + description: Updates the details of the currently authenticated user + parameters: + - description: Payload of user details to update + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.UserUpdate' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.PhoneResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Update a user + tags: + - Users + /users/subscription: + delete: + description: Cancel the subscription of the authenticated user. + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Cancel the user's subscription + tags: + - Users + /users/subscription-update-url: + get: + description: Fetches the subscription URL of the authenticated user. + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.OkString' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Currently authenticated user subscription update URL + tags: + - Users + /users/subscription/invoices/{subscriptionInvoiceID}: + post: + consumes: + - application/json + description: Generates a new invoice PDF file for the given subscription payment + with given parameters. + parameters: + - description: Generate subscription payment invoice parameters + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.UserPaymentInvoice' + - description: ID of the subscription invoice to generate the PDF for + in: path + name: subscriptionInvoiceID + required: true + type: string + produces: + - application/pdf + responses: + "200": + description: OK + schema: + type: file + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Generate a subscription payment invoice + tags: + - Users + /users/subscription/payments: + get: + consumes: + - application/json + description: Subscription payments are generated throughout the lifecycle of + a subscription, typically there is one at the time of purchase and then one + for each renewal. + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.UserSubscriptionPaymentsResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get the last 10 subscription payments. + tags: + - Users + /v1/attachments/{userID}/{messageID}/{attachmentIndex}/{filename}: + get: + description: Download an MMS attachment by its path components + parameters: + - description: User ID + in: path + name: userID + required: true + type: string + - description: Message ID + in: path + name: messageID + required: true + type: string + - description: Attachment index + in: path + name: attachmentIndex + required: true + type: string + - description: Filename with extension + in: path + name: filename + required: true + type: string + produces: + - application/octet-stream + responses: + "200": + description: OK + schema: + type: file + "404": + description: Not Found + schema: + $ref: '#/definitions/responses.NotFound' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + summary: Download a message attachment + tags: + - Attachments + /webhooks: + get: + consumes: + - application/json + description: Get the webhooks of a user + parameters: + - description: number of webhooks to skip + in: query + minimum: 0 + name: skip + type: integer + - description: filter webhooks containing query + in: query + name: query + type: string + - description: number of webhooks to return + in: query + maximum: 20 + minimum: 1 + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.WebhooksResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Get webhooks of a user + tags: + - Webhooks + post: + consumes: + - application/json + description: Store a webhook for the authenticated user + parameters: + - description: Payload of the webhook request + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.WebhookStore' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.WebhookResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Store a webhook + tags: + - Webhooks + /webhooks/{webhookID}: + delete: + consumes: + - application/json + description: Delete a webhook for a user + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the webhook + in: path + name: webhookID + required: true + type: string + produces: + - application/json + responses: + "204": + description: No Content + schema: + $ref: '#/definitions/responses.NoContent' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Delete webhook + tags: + - Webhooks + put: + consumes: + - application/json + description: Update a webhook for the currently authenticated user + parameters: + - default: 32343a19-da5e-4b1b-a767-3298a73703ca + description: ID of the webhook + in: path + name: webhookID + required: true + type: string + - description: Payload of webhook details to update + in: body + name: payload + required: true + schema: + $ref: '#/definitions/requests.WebhookUpdate' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/responses.WebhookResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.BadRequest' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/responses.Unauthorized' + "422": + description: Unprocessable Entity + schema: + $ref: '#/definitions/responses.UnprocessableEntity' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.InternalServerError' + security: + - ApiKeyAuth: [] + summary: Update a webhook + tags: + - Webhooks +schemes: +- https +securityDefinitions: + ApiKeyAuth: + in: header + name: x-api-Key + type: apiKey +swagger: "2.0" diff --git a/api/go.mod b/api/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..9c7418bf0e3f0b3245e02e75cae43ba5f41026d5 --- /dev/null +++ b/api/go.mod @@ -0,0 +1,214 @@ +module github.com/NdoleStudio/httpsms + +go 1.26.0 + +require ( + cloud.google.com/go/cloudtasks v1.21.1 + cloud.google.com/go/compute/metadata v0.10.0 + cloud.google.com/go/storage v1.70.0 + firebase.google.com/go v3.13.0+incompatible + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace v1.38.0 + github.com/NdoleStudio/go-otelroundtripper v0.0.15 + github.com/NdoleStudio/lemonsqueezy-go v1.3.2 + github.com/NdoleStudio/plunk-go v0.0.2 + github.com/NdoleStudio/stacktrace v1.1.0 + github.com/avast/retry-go/v5 v5.0.0 + github.com/axiomhq/axiom-go v0.32.0 + github.com/carlmjohnson/requests v0.26.1 + github.com/cloudevents/sdk-go/v2 v2.16.2 + github.com/cockroachdb/cockroach-go/v2 v2.4.3 + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc + github.com/dgraph-io/ristretto/v2 v2.4.2 + github.com/dustin/go-humanize v1.1.0 + github.com/gertd/go-pluralize v0.2.1 + github.com/go-hermes/hermes/v2 v2.6.2 + github.com/gofiber/contrib/v3/otel v1.2.5 + github.com/gofiber/contrib/v3/swaggo v1.0.8 + github.com/gofiber/fiber/v3 v3.5.0 + github.com/golang-jwt/jwt/v5 v5.3.1 + github.com/google/uuid v1.6.0 + github.com/hashicorp/go-retryablehttp v0.7.8 + github.com/hirosassa/zerodriver v0.1.4 + github.com/jaswdr/faker/v2 v2.9.1 + github.com/joho/godotenv v1.5.1 + github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible + github.com/jszwec/csvutil v1.10.1 + github.com/lib/pq v1.12.3 + github.com/nyaruka/phonenumbers v1.8.1 + github.com/patrickmn/go-cache v2.1.0+incompatible + github.com/pkg/errors v0.9.1 + github.com/pusher/pusher-http-go/v5 v5.1.1 + github.com/redis/go-redis/extra/redisotel/v9 v9.22.0 + github.com/redis/go-redis/v9 v9.22.0 + github.com/rs/zerolog v1.35.1 + github.com/stretchr/testify v1.12.1 + github.com/swaggo/swag v1.16.6 + github.com/thedevsaddam/govalidator v1.9.10 + github.com/uptrace/uptrace-go v1.47.0 + github.com/xuri/excelize/v2 v2.11.0 + go.mongodb.org/mongo-driver/v2 v2.9.2 + go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo v0.0.0-20260624193928-df9c7a836708 + go.opentelemetry.io/otel v1.47.0 + go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 + go.opentelemetry.io/otel/metric v1.47.0 + go.opentelemetry.io/otel/sdk v1.47.0 + go.opentelemetry.io/otel/sdk/metric v1.47.0 + go.opentelemetry.io/otel/trace v1.47.0 + golang.org/x/sync v0.24.0 + google.golang.org/api v0.310.0 + google.golang.org/protobuf v1.36.12 + gorm.io/driver/postgres v1.6.0 + gorm.io/gorm v1.31.2 + gorm.io/plugin/opentelemetry v0.1.16 +) + +require ( + github.com/Masterminds/semver/v3 v3.5.0 // indirect + github.com/Masterminds/sprig/v3 v3.3.0 // indirect + github.com/inbucket/html2text v1.0.0 // indirect + github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 // indirect + github.com/olekukonko/errors v1.3.0 // indirect + github.com/olekukonko/ll v0.1.8 // indirect + github.com/sirupsen/logrus v1.9.4 // indirect + github.com/spf13/cast v1.10.0 // indirect + github.com/yuin/goldmark v1.8.2 // indirect +) + +require ( + cel.dev/expr v0.25.2 // indirect + cloud.google.com/go v0.123.0 // indirect + cloud.google.com/go/auth v0.24.1 // indirect + cloud.google.com/go/auth/oauth2adapt v0.3.0 // indirect + cloud.google.com/go/firestore v1.24.0 // indirect + cloud.google.com/go/iam v1.14.0 // indirect + cloud.google.com/go/longrunning v1.3.0 // indirect + cloud.google.com/go/monitoring v1.30.0 // indirect + cloud.google.com/go/trace v1.16.0 // indirect + dario.cat/mergo v1.0.2 // indirect + filippo.io/edwards25519 v1.2.0 // indirect + github.com/ClickHouse/ch-go v0.72.0 // indirect + github.com/ClickHouse/clickhouse-go/v2 v2.46.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 // indirect + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/Masterminds/goutils v1.1.1 // indirect + github.com/PuerkitoBio/goquery v1.12.0 // indirect + github.com/andybalholm/brotli v1.2.2 // indirect + github.com/andybalholm/cascadia v1.3.4 // indirect + github.com/buger/jsonparser v1.2.0 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect + github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect + github.com/fatih/color v1.19.0 // indirect + github.com/felixge/httpsnoop v1.1.0 // indirect + github.com/go-faster/city v1.0.1 // indirect + github.com/go-faster/errors v0.7.1 // indirect + github.com/go-jose/go-jose/v4 v4.1.6 // indirect + github.com/go-logr/logr v1.4.4 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-openapi/jsonpointer v1.0.1 // indirect + github.com/go-openapi/jsonreference v1.0.1 // indirect + github.com/go-openapi/spec v1.0.0 // indirect + github.com/go-openapi/swag/conv v0.29.2 // indirect + github.com/go-openapi/swag/jsonutils v0.29.2 // indirect + github.com/go-openapi/swag/loading v0.29.2 // indirect + github.com/go-openapi/swag/pools v0.29.2 // indirect + github.com/go-openapi/swag/stringutils v0.29.2 // indirect + github.com/go-openapi/swag/typeutils v0.29.2 // indirect + github.com/go-openapi/swag/yamlutils v0.29.2 // indirect + github.com/go-sql-driver/mysql v1.10.0 // indirect + github.com/goccy/go-json v0.10.6 // indirect + github.com/gofiber/schema v1.8.6 // indirect + github.com/gofiber/utils/v2 v2.5.1 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/go-querystring v1.2.0 // indirect + github.com/google/s2a-go v0.1.11 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.24 // indirect + github.com/googleapis/gax-go/v2 v2.27.0 // indirect + github.com/gorilla/css v1.0.1 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-version v1.9.0 // indirect + github.com/huandu/xstrings v1.5.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.10.0 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/compress v1.20.0 // indirect + github.com/mattn/go-colorable v0.1.15 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/mattn/go-runewidth v0.0.24 // indirect + github.com/mattn/go-sqlite3 v1.14.44 // indirect + github.com/mitchellh/copystructure v1.2.0 // indirect + github.com/mitchellh/reflectwalk v1.0.2 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/molecule-man/go-brrr v1.0.1 // indirect + github.com/olekukonko/tablewriter v1.1.4 // indirect + github.com/paulmach/orb v0.13.0 // indirect + github.com/philhofer/fwd v1.2.0 // indirect + github.com/pierrec/lz4/v4 v4.1.27 // indirect + github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect + github.com/redis/go-redis/extra/rediscmd/v9 v9.22.0 // indirect + github.com/richardlehane/mscfb v1.0.7 // indirect + github.com/richardlehane/msoleps v1.0.6 // indirect + github.com/segmentio/asm v1.2.1 // indirect + github.com/shopspring/decimal v1.4.0 // indirect + github.com/spiffe/go-spiffe/v2 v2.8.1 // indirect + github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect + github.com/swaggo/files/v2 v2.0.2 // indirect + github.com/tiendc/go-deepcopy v1.7.2 // indirect + github.com/tinylib/msgp v1.6.4 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasthttp v1.74.0 // indirect + github.com/vanng822/css v1.0.1 // indirect + github.com/vanng822/go-premailer v1.34.0 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.2.0 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/xuri/efp v0.0.1 // indirect + github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect + github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib v1.46.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.45.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 // indirect + go.opentelemetry.io/contrib/instrumentation/runtime v0.72.0 // indirect + go.opentelemetry.io/contrib/processors/minsev v0.17.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect + go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/sdk/log v1.47.0 // indirect + go.opentelemetry.io/proto/otlp v1.11.1 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.28.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/crypto v0.58.0 // indirect + golang.org/x/mod v0.42.0 // indirect + golang.org/x/net v0.61.0 // indirect + golang.org/x/oauth2 v0.37.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect + golang.org/x/time v0.16.0 // indirect + golang.org/x/tools v0.51.0 // indirect + google.golang.org/appengine v1.6.8 // indirect + google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b // indirect + google.golang.org/grpc v1.84.0 // indirect + gorm.io/driver/clickhouse v0.7.0 // indirect + gorm.io/driver/mysql v1.6.0 // indirect +) diff --git a/api/go.sum b/api/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..91671aa4b9a177d7efb6b12b53a6017d0f5c27ba --- /dev/null +++ b/api/go.sum @@ -0,0 +1,528 @@ +bou.ke/monkey v1.0.2 h1:kWcnsrCNUatbxncxR/ThdYqbytgOIArtYWqcQLQzKLI= +bou.ke/monkey v1.0.2/go.mod h1:OqickVX3tNx6t33n1xvtTtu85YN5s6cKwVug+oHMaIA= +cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= +cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= +cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= +cloud.google.com/go/auth v0.24.1 h1:NTmd2iJb4DsGIav0KiqFMYI88nMshA2wnFMBatRmoCs= +cloud.google.com/go/auth v0.24.1/go.mod h1:1dmBXa9xfBvBr39ZnDUDkaaA91ccq9CcqENDgJA4d7c= +cloud.google.com/go/auth/oauth2adapt v0.3.0 h1:FY8oSZpCYoUNv6QxVODuMjQz4IlSOVeiQtZ08vLPz88= +cloud.google.com/go/auth/oauth2adapt v0.3.0/go.mod h1:7+2uCm7++XFO+/lN06c2HXpDXb/NMNn2/UwyBPbTnkk= +cloud.google.com/go/cloudtasks v1.21.1 h1:1lmHhUXtVKfgTl3VQ9zRqZWttOraVKnevyqGSsKojmM= +cloud.google.com/go/cloudtasks v1.21.1/go.mod h1:ptoxuPEvja+bgW1QC2V25tchfaySWTAlvefPySPMrDg= +cloud.google.com/go/compute/metadata v0.10.0 h1:pyKMUQSwchgkIBBJGdILqQbs/BNJXqwSA7Ej6LAvvtY= +cloud.google.com/go/compute/metadata v0.10.0/go.mod h1:rGFHRrIif570kSibjFTMbt6/4/tzgJWFGI/HVol4GIk= +cloud.google.com/go/firestore v1.24.0 h1:x0Z3hrgjYgo2wI9whuBRQcNc2hYwzZDQy/7pkUXbXcs= +cloud.google.com/go/firestore v1.24.0/go.mod h1:5aojyjN4olKUnBZDCRWwM+NsdrrCX3t1qfyERZGOonM= +cloud.google.com/go/iam v1.14.0 h1:YRIB1/4xxwJ+NfI6RQr1WaOoHHeV0MizJEj940nBXJA= +cloud.google.com/go/iam v1.14.0/go.mod h1:JTPZfbHdGXJrOYREtkRoFzCDGaBdbA7ILLKO/DDuav0= +cloud.google.com/go/logging v1.20.0 h1:l7yzCB8/JSY5PHT9RsaqdT1jaBGbM6KlSJDX210HlXM= +cloud.google.com/go/logging v1.20.0/go.mod h1:ALUaJQZM691Eeujy9kFx0xREq3AMPuGd+pTRZuTYv+w= +cloud.google.com/go/longrunning v1.3.0 h1:lZ6c8SJJBmILp/Wnr3vGnBLa0q+cYfSHRCcUfVI2hpI= +cloud.google.com/go/longrunning v1.3.0/go.mod h1:wpgLxCn+UA3/TZ1bj/fW39mfDpwVlMPu1xKJyoMt7V0= +cloud.google.com/go/monitoring v1.30.0 h1:r/d+JUbyKmJ8b07iznuKfzVzrIXTWxHQ3lBRm3x2LlY= +cloud.google.com/go/monitoring v1.30.0/go.mod h1:htlUR0QWVMrjFzZmN4LGnMAve9xB/eduwjmINxVZ8RM= +cloud.google.com/go/storage v1.70.0 h1:LQNHn0rRF94jVFfF3e416IzdQqIufa5GfF6HilQxb80= +cloud.google.com/go/storage v1.70.0/go.mod h1:W84cNa070TZIegvTW67CBY+f5rxux8EJMb7YyiHdrls= +cloud.google.com/go/trace v1.16.0 h1:GmQovzFc5F0CNfl0VLgL64aoTtu7xsM0YajW2GlG9+E= +cloud.google.com/go/trace v1.16.0/go.mod h1:r+bdAn16dKLSV1G2D5v3e58IlQlizfxWrUfjx7kM7X0= +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= +firebase.google.com/go v3.13.0+incompatible h1:3TdYC3DDi6aHn20qoRkxwGqNgdjtblwVAyRLQwGn/+4= +firebase.google.com/go v3.13.0+incompatible/go.mod h1:xlah6XbEyW6tbfSklcfe5FHJIwjt8toICdV5Wh9ptHs= +github.com/ClickHouse/ch-go v0.72.0 h1:DSyUd4kuxisOVXlZSXyIQYBAajSErZWC379651DpAMU= +github.com/ClickHouse/ch-go v0.72.0/go.mod h1:eeWlJavWDsMf5fZzLNCYaBiMxVoREJYK00aiZ9FJ3E0= +github.com/ClickHouse/clickhouse-go/v2 v2.46.0 h1:s3eRy+hYmu5uzotB6ZhDofgHu8kDgGN/fpmjxRkqSpk= +github.com/ClickHouse/clickhouse-go/v2 v2.46.0/go.mod h1:giJfUVlMkcfUEPVfRpt51zZaGEx9i17gCos8gBl392c= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 h1:bN1gA3of5bXtbnLsRPrwfmbbe7A5UWFlcTHseujLnpc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 h1:5y2LR2pripbccOte6BpZ+guv5O5W0OQIfKvUYZrGaAQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0/go.mod h1:b3f7EifFRqkVt142USoGIP62uUeZm7ALCPrs1ZjWXYo= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace v1.38.0 h1:Smjr+Zjtrz0GEI2AxvHxew0V1vkDlvcm+0hyArVNkKY= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace v1.38.0/go.mod h1:Ov3/u9CUq4/paK8CRyJyvGY7N5YWeneZVLLtiL2sx8E= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.62.0 h1:tRsXhJnn0w0TNwJpVrB94wsrimzjWKFzdQlUhRdNUzc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.62.0/go.mod h1:ifhe5teRNcbxg9p353DhOkOgczzL/IBLYFqT1cm1zpM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 h1:aPMa5qZU9dp4fU34o+jQgVIPFIOi20oxYg8TLigmZLg= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0/go.mod h1:sg6Wqbl0BKKZ5zKnQj2q0qic/3ziF894SCx1LpbX37Y= +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= +github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs= +github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= +github.com/NdoleStudio/go-otelroundtripper v0.0.15 h1:lClvnSNRKfdPejUcMaFa3vv9nkIdONJOzO/WSNBVY2w= +github.com/NdoleStudio/go-otelroundtripper v0.0.15/go.mod h1:YkRryIMC2i4a/6S86isXH+bht3Qp4RRB0rOnnnHBPjU= +github.com/NdoleStudio/lemonsqueezy-go v1.3.2 h1:XUNOzpMriXErxRQRW0dQT0OvkNBP6VAyZKlFWypyGrc= +github.com/NdoleStudio/lemonsqueezy-go v1.3.2/go.mod h1:xKRsRX1jSI6mLrVXyWh2sF/1isxTioZrSjWy6HpA3xQ= +github.com/NdoleStudio/plunk-go v0.0.2 h1:afPW7MHK4Z3rsybpJBnmTmxKCLKF1M7sPI+BNGPf35A= +github.com/NdoleStudio/plunk-go v0.0.2/go.mod h1:pqG3zKhpn/A2bL1K+WsWzvfTpOeSkYgXhNk5H65uEc8= +github.com/NdoleStudio/stacktrace v1.1.0 h1:Ai0j//4tDo/So3nR8bZgS3pQ4NYmViHlarpIReiyb5k= +github.com/NdoleStudio/stacktrace v1.1.0/go.mod h1:WOBcbXShYu+v8JtjFEM+rRV9GJW50m+dwIvp4sLuVTg= +github.com/PuerkitoBio/goquery v1.12.0 h1:pAcL4g3WRXekcB9AU/y1mbKez2dbY2AajVhtkO8RIBo= +github.com/PuerkitoBio/goquery v1.12.0/go.mod h1:802ej+gV2y7bbIhOIoPY5sT183ZW0YFofScC4q/hIpQ= +github.com/andybalholm/brotli v1.2.2 h1:HzTuoo2ErYQqf5qvcJInB8uvqSVxRttzkFexPWtnceM= +github.com/andybalholm/brotli v1.2.2/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg= +github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM= +github.com/avast/retry-go/v5 v5.0.0 h1:kf1Qc2UsTZ4qq8elDymqfbISvkyMuhgRxuJqX2NHP7k= +github.com/avast/retry-go/v5 v5.0.0/go.mod h1://d+usmKWio1agtZfS1H/ltTqwtIfBnRq9zEwjc3eH8= +github.com/axiomhq/axiom-go v0.32.0 h1:aRpbqUAn01hY8aJXQftvWHyXfnrNB2KzN5ZquBWvFcE= +github.com/axiomhq/axiom-go v0.32.0/go.mod h1:3Gmr5M4tINm7Ti00GVfzAduO92Uhd0pghr4ZehIhFxc= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/buger/jsonparser v1.2.0 h1:4EFcvK1kD4jyj6YqNK6skK6w+y7FHHBR+XBCtxwu/6g= +github.com/buger/jsonparser v1.2.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= +github.com/carlmjohnson/requests v0.26.1 h1:kFt5j1XsynNKoladW2qJdP9S+UdigvGLW+53DXbN5F4= +github.com/carlmjohnson/requests v0.26.1/go.mod h1:qMGUsG9/8MbvYRMGwvMBVSQQmRswVcVMAzexVyy038g= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/cloudevents/sdk-go/v2 v2.16.2 h1:ZYDFrYke4FD+jM8TZTJJO6JhKHzOQl2oqpFK1D+NnQM= +github.com/cloudevents/sdk-go/v2 v2.16.2/go.mod h1:laOcGImm4nVJEU+PHnUrKL56CKmRL65RlQF0kRmW/kg= +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik= +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4= +github.com/cockroachdb/cockroach-go/v2 v2.4.3 h1:LJO3K3jC5WXvMePRQSJE1NsIGoFGcEx1LW83W6RAlhw= +github.com/cockroachdb/cockroach-go/v2 v2.4.3/go.mod h1:9U179XbCx4qFWtNhc7BiWLPfuyMVQ7qdAhfrwLz1vH0= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgraph-io/ristretto/v2 v2.4.2 h1:x0cvjmUKxt764Yxdk2nr94we1AvPPAMh1rh5TQ+Jo80= +github.com/dgraph-io/ristretto/v2 v2.4.2/go.mod h1:0KsrXtXvnv0EqnzyowllbVJB8yBonswa2lTCK2gGo9E= +github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da h1:aIftn67I1fkbMa512G+w+Pxci9hJPB8oMnkcP3iZF38= +github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= +github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= +github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ= +github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= +github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds= +github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= +github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= +github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fxamacker/cbor/v2 v2.9.3 h1:oQBnFATpNdY8gJHTndDDv5Xl4QqNaz51G5LLEPhng3Q= +github.com/fxamacker/cbor/v2 v2.9.3/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/gertd/go-pluralize v0.2.1 h1:M3uASbVjMnTsPb0PNqg+E/24Vwigyo/tvyMTtAlLgiA= +github.com/gertd/go-pluralize v0.2.1/go.mod h1:rbYaKDbsXxmRfr8uygAEKhOWsjyrrqrkHVpZvoOp8zk= +github.com/go-faster/city v1.0.1 h1:4WAxSZ3V2Ws4QRDrscLEDcibJY8uf41H6AhXDrNDcGw= +github.com/go-faster/city v1.0.1/go.mod h1:jKcUJId49qdW3L1qKHH/3wPeUstCVpVSXTM6vO3VcTw= +github.com/go-faster/errors v0.7.1 h1:MkJTnDoEdi9pDabt1dpWf7AA8/BaSYZqibYyhZ20AYg= +github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo= +github.com/go-hermes/hermes/v2 v2.6.2 h1:RuGQlICVtIHixfxtYwN7hAoqGyGxr+D3kE42oE6emcw= +github.com/go-hermes/hermes/v2 v2.6.2/go.mod h1:RLVNk31/1KqF35vK3mAaQVuJvMH+K5//6OTGJk+j/80= +github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= +github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-openapi/jsonpointer v1.0.1 h1:2KxywRmNwJkT/FMBa3iRNHEaAxSJvjqoufQZy3au1Mg= +github.com/go-openapi/jsonpointer v1.0.1/go.mod h1:wI7ZYsFmbIi9nBXOZqgDaS/bqOchRGZjqxFli7FBYxY= +github.com/go-openapi/jsonreference v1.0.1 h1:4zJ7AmYDKNmD3aSpfPnFNCFA5E80/xMHUNKgydaLh38= +github.com/go-openapi/jsonreference v1.0.1/go.mod h1:dYplQXa6p5lXprLcJ8LE2iU7vNpXsAHDQ5ZAgL+Qx3A= +github.com/go-openapi/spec v1.0.0 h1:JtB/GHOj+eetjse6YvxqLze88oEekl/4uPBethvzRrA= +github.com/go-openapi/spec v1.0.0/go.mod h1:boj1PRhqS0x5jylgcNp9BRWxenphrh7vVNYZ90IRCoo= +github.com/go-openapi/swag v0.29.2 h1:9n8frkcsuQRA0INU31VbxNxt1zBaHxrHYGEf5BUjFi4= +github.com/go-openapi/swag/conv v0.29.2 h1:8c9shoB8l0QRSR6ymq1llHdBWDqpIgJfjTGHx3Vuhm0= +github.com/go-openapi/swag/conv v0.29.2/go.mod h1:AZS0YigTNf8qNtD6WqJz/N4RUNmpr76SyjFGkq4+p6Q= +github.com/go-openapi/swag/jsonutils v0.29.2 h1:uZNSD2/rJDYAfvsLYkykTzXuyxM3QpDKV9jhRHrMu6k= +github.com/go-openapi/swag/jsonutils v0.29.2/go.mod h1:ONTdNvj3Y+IXRzfa17E+Rgt2ns/qiSOYjIo2K7v2yDs= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2 h1:w+Fd6EBOMGlC74GYGHqCLGyb3Bpams8TtNrgM/SG4jo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2/go.mod h1:HC2egPORFzbj/gf05Zrfgz8Mgplx3oW7hgGi7pjZVhM= +github.com/go-openapi/swag/loading v0.29.2 h1:QU1ry24e6r6Shoxe380Nx0X5iKkpRO+hJffsyJ2dVlY= +github.com/go-openapi/swag/loading v0.29.2/go.mod h1:DqilDjuiJKETecsS4TRopWG1acUDsfqN39ZmQhPu6uI= +github.com/go-openapi/swag/pools v0.29.2 h1:PlGoDRF8WtSyXkedZZkpW3f9wDhFf3u8KtaBcmgmh8c= +github.com/go-openapi/swag/pools v0.29.2/go.mod h1:V3lhxVT4qDYRqc2MRSSbLsTYIYV/2HlHafhyEkmzLIc= +github.com/go-openapi/swag/stringutils v0.29.2 h1:lcnBxwAaysT3bMUVBfn9V/PkfVqkurpqufKU6rTUMGk= +github.com/go-openapi/swag/stringutils v0.29.2/go.mod h1:i9cdh7sGaa0nm3CqIvH5IM5h2QClk1wns2ktKeILvRI= +github.com/go-openapi/swag/typeutils v0.29.2 h1:O7aVvkTs3pXwikgtrPLenigEMdQFgONKRooQA9pgf2I= +github.com/go-openapi/swag/typeutils v0.29.2/go.mod h1:7+GDG+uz9Ke+eVt4rClZg7wklSDp8hT/mKNh/pC26TE= +github.com/go-openapi/swag/yamlutils v0.29.2 h1:IFKFFeDnuIwzfsuWRQU+rI8iL3g4XyAYjV/RlnlxPLM= +github.com/go-openapi/swag/yamlutils v0.29.2/go.mod h1:7MGqtcrK73sxQ4ceiyIf8qiXS/s09JLMdR5esK5euYQ= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0 h1:wPW6YRgx3+SID1yUy/Xwa17L8kFEaEKod2VRbJDZNUs= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0/go.mod h1:mI1M88etYbc3PhgHsWQK2kwvNwW5aGFqMPbmib+SGIs= +github.com/go-openapi/testify/v2 v2.7.0 h1:bycOreEj6wfBvijg3YFogZ/sFjTCDmQnwSodSzHa3X8= +github.com/go-openapi/testify/v2 v2.7.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw= +github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= +github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= +github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/gofiber/contrib/v3/otel v1.2.5 h1:1zvCRB5Qreey12RCSPZUlawcTvYb3wb4QRKzJXk+V9M= +github.com/gofiber/contrib/v3/otel v1.2.5/go.mod h1:YPPFGXIr/SLAVI2+u0Kq9ET6C9Hwdfh8CXRZbQZIDs0= +github.com/gofiber/contrib/v3/swaggo v1.0.8 h1:11YmMVbkMO7zv6YR0gdNfRWcs5ZVUkDpR21AhjhbK00= +github.com/gofiber/contrib/v3/swaggo v1.0.8/go.mod h1:7jyBZxqQ4MjOxIidOvLQ9jNAxNk05yKpid40OYb3pLE= +github.com/gofiber/fiber/v3 v3.5.0 h1:dk7TOUH6DXJGtOLsN2XEG+0ZML7cznzHILTVozbNEK8= +github.com/gofiber/fiber/v3 v3.5.0/go.mod h1:GOVDTW+gjJvfe0iJyVujbQ1Lnx+JUjFySJRI/9/xX/w= +github.com/gofiber/schema v1.8.6 h1:xVlbSg3vsyKVlfzRBps2tJ7pHx1d8mSgiaJye6Lb3xs= +github.com/gofiber/schema v1.8.6/go.mod h1:Cxh3loYVG3FLA7FzW4C5G83pL/pmCmAnuaIJ5y2HwkU= +github.com/gofiber/utils/v2 v2.5.1 h1:Yrt/ljbfsgnDSHymoMvVX5PFrb9kCV/OJnDu6sYuT4A= +github.com/gofiber/utils/v2 v2.5.1/go.mod h1:5GyHTNQA1I6Qwlw7BWxQsZl8iuFS4yPjLFck+wYR304= +github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw= +github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfhIxNtP0= +github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= +github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= +github.com/google/s2a-go v0.1.11 h1:7v1V1TraNGP63WptsAkNqr2w8jgm4vM6A6qx6Lsw9iM= +github.com/google/s2a-go v0.1.11/go.mod h1:pz4tyvwXvJLLbyrkh6FW1eS2zPUXMaTmyNhYtyP2tNw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.24 h1:G9iCJIY+AYVmUskKdjX8FVy7sG+nbzjOQ41cvlmhcvg= +github.com/googleapis/enterprise-certificate-proxy v0.3.24/go.mod h1:hEjCmnoakQzv5ImLUp6alkY7XgLlNoAxwTXmhHHNIsI= +github.com/googleapis/gax-go/v2 v2.27.0 h1:qe2iQOUzxb3fd6x6ewpIEixPQhJ+0Ihc/RRZhKA/2g0= +github.com/googleapis/gax-go/v2 v2.27.0/go.mod h1:RofiqDw3ehcG4L0H1zO3D2Itpwd3/uS/7wdmbNDF1DE= +github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= +github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 h1:Bd7KaOxzULLxtZ/K5s1aLbWhR0+5RToO65TXHsf3bqQ= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0/go.mod h1:nN7ts3dFXKtCZWc//yfkpcQNKJABg16/uDVAZpLDalo= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= +github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48= +github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw= +github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA= +github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hirosassa/zerodriver v0.1.4 h1:8bzamKUOHHq03aEk12qi/lnji2dM+IhFOe+RpKpIZFM= +github.com/hirosassa/zerodriver v0.1.4/go.mod h1:hHOOAQvVGwBV1iVVYujM6vwOBBqQcBIFpJxCD9mJU7Y= +github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI= +github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/inbucket/html2text v1.0.0 h1:N5kza++4uBBDJ2Z3KUnTRyPNoBcW+YfOgNiNmNB+sgs= +github.com/inbucket/html2text v1.0.0/go.mod h1:5TrhXQKGU+LXurODaSm55Y9eXoPBRnYiOz4x2XfUoJU= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= +github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jaswdr/faker/v2 v2.9.1 h1:J0Rjqb2/FquZnoZplzkGVL5LmhNkeIpvsSMoJKzn+8E= +github.com/jaswdr/faker/v2 v2.9.1/go.mod h1:jZq+qzNQr8/P+5fHd9t3txe2GNPnthrTfohtnJ7B+68= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA= +github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jszwec/csvutil v1.10.1 h1:a5RRa4Wr3hP4CUkyL7JJDv9mym00JBVl4QchpfXKRDI= +github.com/jszwec/csvutil v1.10.1/go.mod h1:/E4ONrmGkwmWsk9ae9jpXnv9QT8pLHEPcCirMFhxG9I= +github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA= +github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= +github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ= +github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= +github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= +github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU= +github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8= +github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= +github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= +github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= +github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= +github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/molecule-man/go-brrr v1.0.1 h1:cEjgx8hgNw6UGdhQ94SPDbPkKuRbkUcxBO3IzbGpA/o= +github.com/molecule-man/go-brrr v1.0.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4= +github.com/nyaruka/phonenumbers v1.8.1 h1:2K9YMQuv1dCGqjjzB1DwmdCe89khT4KPBQb2CxAMMlU= +github.com/nyaruka/phonenumbers v1.8.1/go.mod h1:fsKPJ70O9JetEA4ggnJadYTFWwtGPvu/lETTXNXq6Cs= +github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6 h1:zrbMGy9YXpIeTnGj4EljqMiZsIcE09mmF8XsD5AYOJc= +github.com/olekukonko/cat v0.0.0-20250911104152-50322a0618f6/go.mod h1:rEKTHC9roVVicUIfZK7DYrdIoM0EOr8mK1Hj5s3JjH0= +github.com/olekukonko/errors v1.3.0 h1:teJvgLGUEqMzBUms+Dj3/3szNqCG/Jdw9iDbum8fR6U= +github.com/olekukonko/errors v1.3.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= +github.com/olekukonko/ll v0.1.8 h1:ysHCJRGHYKzmBSdz9w5AySztx7lG8SQY+naTGYUbsz8= +github.com/olekukonko/ll v0.1.8/go.mod h1:RPRC6UcscfFZgjo1nulkfMH5IM0QAYim0LfnMvUuozw= +github.com/olekukonko/tablewriter v1.1.4 h1:ORUMI3dXbMnRlRggJX3+q7OzQFDdvgbN9nVWj1drm6I= +github.com/olekukonko/tablewriter v1.1.4/go.mod h1:+kedxuyTtgoZLwif3P1Em4hARJs+mVnzKxmsCL/C5RY= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/paulmach/orb v0.13.0 h1:r7n7mQGGF+cj/CbcivEj9J3HGK+XR+yXnvzRdq9saIw= +github.com/paulmach/orb v0.13.0/go.mod h1:6scRWINywA2Jf05dcjOfLfxrUIMECvTSG2MVbRLxu/k= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk= +github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pusher/pusher-http-go/v5 v5.1.1 h1:ZLUGdLA8yXMvByafIkS47nvuXOHrYmlh4bsQvuZnYVQ= +github.com/pusher/pusher-http-go/v5 v5.1.1/go.mod h1:Ibji4SGoUDtOy7CVRhCiEpgy+n5Xv6hSL/QqYOhmWW8= +github.com/redis/go-redis/extra/rediscmd/v9 v9.22.0 h1:MQPzEEnpD0BMPufBLABnMYLJVwM7xi7vZ+srO8Nr0s8= +github.com/redis/go-redis/extra/rediscmd/v9 v9.22.0/go.mod h1:eve0JFcLRwFVj3RA85rrrV5+UJ+K9LDyU7kf2UdSueM= +github.com/redis/go-redis/extra/redisotel/v9 v9.22.0 h1:t5ul1Gl0o1rYQj5f5bK12G9xcg1niq2ON4yZFjvy1kA= +github.com/redis/go-redis/extra/redisotel/v9 v9.22.0/go.mod h1:hcS9L2RBBjYXkrfSOF26ZGejgo+yOC+28ZD2fkk3sGs= +github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0= +github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4= +github.com/richardlehane/mscfb v1.0.7 h1:oeoiM0WE79vHwE8RpIYYvIAc8ajTH2mb6UZm55/+EB0= +github.com/richardlehane/mscfb v1.0.7/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo= +github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg= +github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= +github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc= +github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs= +github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI= +github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw= +github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0= +github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= +github.com/shamaton/msgpack/v3 v3.2.2 h1:lZITRsXLQkdJ9J2qvh6gjGpWxci/dwuiUf+jm9AudJM= +github.com/shamaton/msgpack/v3 v3.2.2/go.mod h1:sgBYvEiyz8JR1NC3yGRoPVME9xXovpnh3l/plW1nfRo= +github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= +github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spiffe/go-spiffe/v2 v2.8.1 h1:eXZMLsu+3MLEPJyGJkolqtVrteZfQdUpOWj6LTiDl/E= +github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= +github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= +github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/swaggo/files/v2 v2.0.2 h1:Bq4tgS/yxLB/3nwOMcul5oLEUKa877Ykgz3CJMVbQKU= +github.com/swaggo/files/v2 v2.0.2/go.mod h1:TVqetIzZsO9OhHX1Am9sRf9LdrFZqoK49N37KON/jr0= +github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI= +github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg= +github.com/thedevsaddam/govalidator v1.9.10 h1:m3dLRbSZ5Hts3VUWYe+vxLMG+FdyQuWOjzTeQRiMCvU= +github.com/thedevsaddam/govalidator v1.9.10/go.mod h1:Ilx8u7cg5g3LXbSS943cx5kczyNuUn7LH/cK5MYuE90= +github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= +github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM= +github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44= +github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ= +github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ= +github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= +github.com/uptrace/uptrace-go v1.47.0 h1:FQgpAx/DdfDEaJ9xX03RaAc7BXVraBz0qC15oynFDpI= +github.com/uptrace/uptrace-go v1.47.0/go.mod h1:xVJgZjczsSa94/pdg5HrtWTY/HyfCXxL7f+MienUh7Y= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.74.0 h1:wMS9fnO2QTALozYx5pId2Vi7ZwU/epUkY8i/KPWCHoU= +github.com/valyala/fasthttp v1.74.0/go.mod h1:3ARmLamUcw7ElxVtC8PXaGzQ6VEuvnetlkrwIklQBSE= +github.com/vanng822/css v1.0.1 h1:10yiXc4e8NI8ldU6mSrWmSWMuyWgPr9DZ63RSlsgDw8= +github.com/vanng822/css v1.0.1/go.mod h1:tcnB1voG49QhCrwq1W0w5hhGasvOg+VQp9i9H1rCM1w= +github.com/vanng822/go-premailer v1.34.0 h1:CW7RUnjCfXrkuCbgC2wi/Cub7IwKslJWD/OkIBlcQUk= +github.com/vanng822/go-premailer v1.34.0/go.mod h1:LGYI7ym6FQ7KcHN16LiQRF+tlan7qwhP1KEhpTINFpo= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs= +github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8= +github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/excelize/v2 v2.11.0 h1:HxaEFl6sRN2+8J5a8HaKq+0M4FsjBGMnWWtjOCPSG88= +github.com/xuri/excelize/v2 v2.11.0/go.mod h1:jxFLbzaIwGQ5ufFNvYfUOHqXhfPaNmP14KWfmNz2Uak= +github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE= +github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ= +github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= +github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE= +github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.mongodb.org/mongo-driver/v2 v2.9.2 h1:OCAdjI37pC/SVxucz/9CM8zD4jCdegtsY5QcKzYFCgE= +go.mongodb.org/mongo-driver/v2 v2.9.2/go.mod h1:SHKN0IWkKmEVGHLjXnni6s4wPKX4v86FTgOeJJFuXcA= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib v1.46.0 h1:PVrao7T/FJZ814/+QbMcIMIIpdjQXC3pi3V11+6DT40= +go.opentelemetry.io/contrib v1.46.0/go.mod h1:1DF/GVJ9wpq32v0EOs2sbV77TFtM3IRzgAVPyjGSe88= +go.opentelemetry.io/contrib/detectors/gcp v1.45.0 h1:9jR0ZPRok9ryaOQ2Wx8rg5F7Aon59mxrqbVI60/vlBk= +go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA= +go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo v0.0.0-20260624193928-df9c7a836708 h1:s5k/FTgmE4Mj2jFG38Dj5TQgxDRMG92fRK3puTdMHew= +go.opentelemetry.io/contrib/instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo v0.0.0-20260624193928-df9c7a836708/go.mod h1:VgtIsrVXKo8KmG2sFvQazHcQ98P2FHQ+ZePXtpTPjqs= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 h1:B2h3uqicet1CT2N5TOFhS+Gq++9i0/CLmaxvhmhtP5s= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0/go.mod h1:dylvB+ZiiwMvsDij9O84Uy7SijLgHMX4mbkncds+4Sw= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU= +go.opentelemetry.io/contrib/instrumentation/runtime v0.72.0 h1:rv8t3kKjyC2/9D99L1MZt4tJSZO4aYUmHus7L//iKKg= +go.opentelemetry.io/contrib/instrumentation/runtime v0.72.0/go.mod h1:ZzG+JmzLLvKzx6tMeLrw2l7F8ik2GeRZJALoPBqnM0c= +go.opentelemetry.io/contrib/processors/minsev v0.17.0 h1:8Am2/je8uZLXKqXgMgKknKk72aG2bm3aa/npmSCNvhY= +go.opentelemetry.io/contrib/processors/minsev v0.17.0/go.mod h1:sD5q0j6QoMiDTYws/ikKx60/yFFseDlxSIrInpd3Bew= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0/go.mod h1:59nH0RYCGHRlwt15WyioeSYINBbuObeBpTowPhEKWHY= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 h1:7kszRN4Ze5GeAkUnBjBSUIunVBMA+mZIG04auueqguM= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0/go.mod h1:CLzakYy8jOdkBfcveCWYkeKJxujcF4xPhh2Z7IfE98U= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.45.0 h1:dm9iyzn6tioYZtwqaiBSU0TSI8Yu/8dTIbfG0+B49DY= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.45.0/go.mod h1:xAvxYjYK28qvt+yu4BYZ/zMmAjwMXINXD6JiMyeB8iI= +go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.47.0 h1:N3YQCxjxQ/bMjyc3heladfRm9t9RTksGQH8z4w6yU/0= +go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.47.0/go.mod h1:Mp8HOFqcaUyypCuGv9IhDdTHnJ56lSudSHMd+pVSCEA= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM= +go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/sdk/log v1.47.0 h1:W4N/ZfgpkRRnmARnqYoQ6BrWA0mrj8IzVDNLlpmUJZY= +go.opentelemetry.io/otel/sdk/log v1.47.0/go.mod h1:Wu74Z2EmOKXi2FleSNAb0Hyau2G+r5kubSEMJw5aAMs= +go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 h1:j3pm42QCrKYYLLkI6OrV1QHFkUfDA6/4EP+Y1PzggLg= +go.opentelemetry.io/otel/sdk/log/logtest v0.23.0/go.mod h1:zt0gEnuTZgDvqvczHwYswz93eqMaIr6upTTsdV/HUlU= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= +go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw= +go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= +go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE= +golang.org/x/image v0.38.0/go.mod h1:/3f6vaXC+6CEanU4KJxbcUZyEePbyKbaLoDOe4ehFYY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/api v0.310.0 h1:537ccDDmbwuwX1iof3Vtdz9vow6uJCgrSZJWedAWM0I= +google.golang.org/api v0.310.0/go.mod h1:5NUthU+LmGMKzYgRaScb+TTe1Lo7x4A+J7g+Yj8BRzA= +google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= +google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= +google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941 h1:CXq2XEi5aEyLjjPZIwqrmQH8ZY4ctUwK7uyAx3mjX/U= +google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941/go.mod h1:3gK0ehnhP0V7/x3ypGoLyT3d0n6TSi/EcsphIjHrcz4= +google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 h1:DS/w3N8rsfrwxwgGSj6WhMsPo7aNQGmDx74J81zd0NQ= +google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941/go.mod h1:AuGAdi9KnXss7xbLxIKhCvk+Ro/SxpET/iS45DNYN+M= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b h1:6WNWHZk91dp4gZ25642OALkuG1UVNZbwENJD19DnB8k= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0= +google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/stretchr/testify.v1 v1.2.2 h1:yhQC6Uy5CqibAIlk1wlusa/MJ3iAN49/BsR/dCCKz3M= +gopkg.in/stretchr/testify.v1 v1.2.2/go.mod h1:QI5V/q6UbPmuhtm10CaFZxED9NreB8PnFYN9JcR6TxU= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/clickhouse v0.7.0 h1:BCrqvgONayvZRgtuA6hdya+eAW5P2QVagV3OlEp1vtA= +gorm.io/driver/clickhouse v0.7.0/go.mod h1:TmNo0wcVTsD4BBObiRnCahUgHJHjBIwuRejHwYt3JRs= +gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg= +gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo= +gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4= +gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo= +gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= +gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= +gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= +gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= +gorm.io/plugin/opentelemetry v0.1.16 h1:Kypj2YYAliJqkIczDZDde6P6sFMhKSlG5IpngMFQGpc= +gorm.io/plugin/opentelemetry v0.1.16/go.mod h1:P3RmTeZXT+9n0F1ccUqR5uuTvEXDxF8k2UpO7mTIB2Y= diff --git a/api/main.go b/api/main.go new file mode 100644 index 0000000000000000000000000000000000000000..5b7539c9c143f9648418f9a904ead8e09b071cd7 --- /dev/null +++ b/api/main.go @@ -0,0 +1,46 @@ +package main + +import ( + "fmt" + "os" + "strings" + + "github.com/NdoleStudio/httpsms/docs" + "github.com/NdoleStudio/httpsms/pkg/di" +) + +// Version is injected at runtime +var Version string + +// @title httpSMS API Reference +// @version 1.0 +// @description Use your Android phone to send and receive SMS messages via a simple programmable API with end-to-end encryption. +// +// @contact.name support@httpsms.com +// @contact.email support@httpsms.com +// +// @license.name AGPL-3.0 +// @license.url https://raw.githubusercontent.com/NdoleStudio/http-sms-manager/main/LICENSE +// +// @host api.httpsms.com +// @schemes https +// @BasePath /v1 +// +// @securitydefinitions.apikey ApiKeyAuth +// @in header +// @name x-api-Key +func main() { + if len(os.Args) == 1 { + di.LoadEnv() + } + + if host := strings.TrimSpace(os.Getenv("SWAGGER_HOST")); len(host) > 0 { + docs.SwaggerInfo.Host = host + } + if len(Version) > 0 { + docs.SwaggerInfo.Version = Version + } + + container := di.NewContainer(os.Getenv("GCP_PROJECT_ID"), Version) + container.Logger().Info(container.App().Listen(fmt.Sprintf("%s:%s", os.Getenv("APP_HOST"), os.Getenv("APP_PORT"))).Error()) +} diff --git a/api/pkg/cache/cache.go b/api/pkg/cache/cache.go new file mode 100644 index 0000000000000000000000000000000000000000..bb9a829cd8f551b7fcbda08595a2c5fbeac74794 --- /dev/null +++ b/api/pkg/cache/cache.go @@ -0,0 +1,12 @@ +package cache + +import ( + "context" + "time" +) + +// Cache stores items temporarily +type Cache interface { + Set(ctx context.Context, key string, value string, ttl time.Duration) error + Get(ctx context.Context, key string) (value string, err error) +} diff --git a/api/pkg/cache/memory_cache.go b/api/pkg/cache/memory_cache.go new file mode 100644 index 0000000000000000000000000000000000000000..a5b0487d76f29c72ee9c29606448d512b255bc56 --- /dev/null +++ b/api/pkg/cache/memory_cache.go @@ -0,0 +1,46 @@ +package cache + +import ( + "context" + "time" + + "github.com/NdoleStudio/httpsms/pkg/telemetry" + "github.com/NdoleStudio/stacktrace" + ttlCache "github.com/patrickmn/go-cache" +) + +// memoryCache is the Cache implementation in memory +type memoryCache struct { + tracer telemetry.Tracer + store *ttlCache.Cache +} + +// NewMemoryCache creates a new instance of memoryCache +func NewMemoryCache(tracer telemetry.Tracer, store *ttlCache.Cache) Cache { + return &memoryCache{ + tracer: tracer, + store: store, + } +} + +// Get an item from the redis cache +func (cache *memoryCache) Get(ctx context.Context, key string) (value string, err error) { + ctx, span := cache.tracer.Start(ctx) + defer span.End() + + response, ok := cache.store.Get(key) + if !ok { + return "", stacktrace.NewErrorf("no item found in cache with key [%s]", key) + } + + return response.(string), nil +} + +// Set an item in the redis cache +func (cache *memoryCache) Set(ctx context.Context, key string, value string, ttl time.Duration) error { + ctx, span := cache.tracer.Start(ctx) + defer span.End() + + cache.store.Set(key, value, ttl) + return nil +} diff --git a/api/pkg/cache/redis_cache.go b/api/pkg/cache/redis_cache.go new file mode 100644 index 0000000000000000000000000000000000000000..46d9044bde1ed10c08cccc6969c3ae8f6d5b2369 --- /dev/null +++ b/api/pkg/cache/redis_cache.go @@ -0,0 +1,52 @@ +package cache + +import ( + "context" + "errors" + "time" + + "github.com/NdoleStudio/httpsms/pkg/telemetry" + "github.com/NdoleStudio/stacktrace" + "github.com/redis/go-redis/v9" +) + +// redisCache is the Cache implementation in redis +type redisCache struct { + tracer telemetry.Tracer + client *redis.Client +} + +// NewRedisCache creates a new instance of RedisCache +func NewRedisCache(tracer telemetry.Tracer, client *redis.Client) Cache { + return &redisCache{ + tracer: tracer, + client: client, + } +} + +// Get an item from the redis cache +func (cache *redisCache) Get(ctx context.Context, key string) (value string, err error) { + ctx, span := cache.tracer.Start(ctx) + defer span.End() + + response, err := cache.client.Get(ctx, key).Result() + if errors.Is(err, redis.Nil) { + return "", stacktrace.Propagatef(err, "no item found in redis with key [%s]", key) + } + if err != nil { + return "", stacktrace.Propagatef(err, "cannot get item in redis with key [%s]", key) + } + return response, nil +} + +// Set an item in the redis cache +func (cache *redisCache) Set(ctx context.Context, key string, value string, ttl time.Duration) error { + ctx, span := cache.tracer.Start(ctx) + defer span.End() + + err := cache.client.Set(ctx, key, value, ttl).Err() + if err != nil { + return cache.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot set item in redis")) + } + return nil +} diff --git a/api/pkg/di/config.go b/api/pkg/di/config.go new file mode 100644 index 0000000000000000000000000000000000000000..0c6b868005ade6d1809e4af06a039df94bd66f10 --- /dev/null +++ b/api/pkg/di/config.go @@ -0,0 +1,38 @@ +package di + +import ( + "log" + "os" + "strings" + + "github.com/joho/godotenv" +) + +// LoadEnv will read your .env file(s) and load them into ENV for this process. +func LoadEnv(filenames ...string) { + err := godotenv.Load(filenames...) + if err != nil { + log.Fatalf("Fatal: cannot load .env file: %v", err) + } +} + +func getEnvWithDefault(key, defaultValue string) string { + value := os.Getenv(key) + if value == "" { + return defaultValue + } + + return value +} + +func splitCommaEnv(key, defaultValue string) []string { + value := getEnvWithDefault(key, defaultValue) + parts := strings.Split(value, ",") + result := make([]string, 0, len(parts)) + for _, part := range parts { + if trimmed := strings.TrimSpace(part); trimmed != "" { + result = append(result, trimmed) + } + } + return result +} diff --git a/api/pkg/di/container.go b/api/pkg/di/container.go new file mode 100644 index 0000000000000000000000000000000000000000..e7ca20d283ae6afe8120f31a5f9c8b12587ef9da --- /dev/null +++ b/api/pkg/di/container.go @@ -0,0 +1,2101 @@ +package di + +import ( + "context" + "crypto/tls" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "cloud.google.com/go/compute/metadata" + "github.com/NdoleStudio/httpsms/docs" + plunk "github.com/NdoleStudio/plunk-go" + "github.com/pusher/pusher-http-go/v5" + + otelMetric "go.opentelemetry.io/otel/metric" + + "github.com/dgraph-io/ristretto/v2" + + otelfiber "github.com/gofiber/contrib/v3/otel" + "gorm.io/plugin/opentelemetry/tracing" + + "github.com/NdoleStudio/httpsms/pkg/discord" + + "cloud.google.com/go/storage" + mexporter "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric" + cloudtrace "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace" + "github.com/NdoleStudio/httpsms/pkg/cache" + "github.com/NdoleStudio/lemonsqueezy-go" + "github.com/hashicorp/go-retryablehttp" + "github.com/redis/go-redis/extra/redisotel/v9" + "github.com/redis/go-redis/v9" + "go.opentelemetry.io/otel/sdk/metric" + + "github.com/NdoleStudio/go-otelroundtripper" + + "github.com/uptrace/uptrace-go/uptrace" + + "github.com/NdoleStudio/httpsms/pkg/emails" + + cloudtasks "cloud.google.com/go/cloudtasks/apiv2" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/sdk/resource" + semconv "go.opentelemetry.io/otel/semconv/v1.10.0" + + axiomzerolog "github.com/axiomhq/axiom-go/adapters/zerolog" + "github.com/hirosassa/zerodriver" + "github.com/rs/zerolog" + "go.opentelemetry.io/otel/sdk/trace" + + firebase "firebase.google.com/go" + "firebase.google.com/go/auth" + "github.com/NdoleStudio/httpsms/pkg/middlewares" + "google.golang.org/api/option" + + "github.com/gofiber/fiber/v3/middleware/compress" + "github.com/gofiber/fiber/v3/middleware/cors" + + "github.com/NdoleStudio/httpsms/pkg/entities" + "github.com/NdoleStudio/httpsms/pkg/listeners" + "github.com/NdoleStudio/httpsms/pkg/repositories" + "github.com/NdoleStudio/httpsms/pkg/services" + "github.com/NdoleStudio/stacktrace" + swagger "github.com/gofiber/contrib/v3/swaggo" + "github.com/gofiber/fiber/v3" + fiberLogger "github.com/gofiber/fiber/v3/middleware/logger" + ttlCache "github.com/patrickmn/go-cache" + "gorm.io/gorm" + + "github.com/NdoleStudio/httpsms/pkg/handlers" + "github.com/NdoleStudio/httpsms/pkg/telemetry" + "github.com/NdoleStudio/httpsms/pkg/validators" + mongoDriver "go.mongodb.org/mongo-driver/v2/mongo" + "gorm.io/driver/postgres" + gormLogger "gorm.io/gorm/logger" +) + +// Container is used to resolve services at runtime +type Container struct { + projectID string + db *gorm.DB + dedicatedDB *gorm.DB + mongoDB *mongoDriver.Database + version string + app *fiber.App + eventDispatcher *services.EventDispatcher + logger telemetry.Logger + attachmentRepository repositories.AttachmentRepository + contactService *services.ContactService + userRistrettoCache *ristretto.Cache[string, entities.AuthContext] + phoneRistrettoCache *ristretto.Cache[string, *entities.Phone] + contactRistrettoCache *ristretto.Cache[string, services.ContactCacheEntry] + inMemoryCache cache.Cache +} + +// NewLiteContainer creates a Container without any routes or listeners +func NewLiteContainer() (container *Container) { + return &Container{ + logger: logger(3).WithService(fmt.Sprintf("%T", container)), + } +} + +// NewContainer creates a new dependency injection container +func NewContainer(projectID string, version string) (container *Container) { + container = &Container{ + projectID: projectID, + version: version, + logger: logger(3).WithService(fmt.Sprintf("%T", container)), + } + + container.InitializeTraceProvider() + + container.RegisterMessageListeners() + container.RegisterMessageRoutes() + container.RegisterAttachmentRoutes() + container.RegisterBulkMessageRoutes() + + container.RegisterMessageThreadRoutes() + container.RegisterMessageThreadListeners() + + container.RegisterContactRoutes() + container.RegisterContactListeners() + + container.RegisterHeartbeatRoutes() + container.RegisterHeartbeatListeners() + + container.RegisterUserRoutes() + container.RegisterMessageSendScheduleRoutes() + container.RegisterMessageSendScheduleListeners() + container.RegisterUserListeners() + + container.RegisterPhoneRoutes() + container.RegisterPhoneListeners() + + container.RegisterEventRoutes() + + container.RegisterNotificationListeners() + container.RegisterEmailNotificationListeners() + + container.RegisterBillingRoutes() + container.RegisterBillingListeners() + + container.RegisterWebhookRoutes() + container.RegisterWebhookListeners() + + container.RegisterLemonsqueezyRoutes() + + container.RegisterIntegration3CXRoutes() + container.RegisterIntegration3CXListeners() + + container.RegisterDiscordRoutes() + container.RegisterDiscordListeners() + + container.RegisterPhoneAPIKeyRoutes() + container.RegisterPhoneAPIKeyListeners() + + container.RegisterMarketingListeners() + container.RegisterWebsocketListeners() + + // this has to be last since it registers the /* route + container.RegisterSwaggerRoutes() + + return container +} + +// App creates a new instance of fiber.App +func (container *Container) App() (app *fiber.App) { + if container.app != nil { + return container.app + } + + container.logger.Debug(fmt.Sprintf("creating %T", app)) + + app = fiber.New() + + // Health check endpoint registered before middleware for reliable Docker health checks + app.Get("/health", func(c fiber.Ctx) error { + return c.SendStatus(fiber.StatusOK) + }) + + app.Use(compress.New(compress.Config{ + Level: compress.LevelBestCompression, + })) + + if os.Getenv("USE_HTTP_LOGGER") == "true" { + app.Use(fiberLogger.New()) + } + + app.Use(otelfiber.Middleware()) + app.Use( + cors.New( + cors.Config{ + AllowOrigins: splitCommaEnv("CORS_ALLOW_ORIGINS", "*"), + AllowHeaders: splitCommaEnv("CORS_ALLOW_HEADERS", "*"), + AllowMethods: splitCommaEnv("CORS_ALLOW_METHODS", "GET,POST,PUT,DELETE,OPTIONS"), + AllowCredentials: false, + ExposeHeaders: splitCommaEnv("CORS_EXPOSE_HEADERS", "*"), + }, + ), + ) + app.Use(middlewares.HTTPRequestLogger(container.Tracer(), container.Logger())) + app.Use(middlewares.BearerAuth(container.Logger(), container.Tracer(), container.FirebaseAuthClient())) + app.Use(middlewares.APIKeyAuth(container.Logger(), container.Tracer(), container.UserRepository())) + + container.app = app + return app +} + +// BearerAPIKeyMiddleware creates a new instance of middlewares.BearerAPIKeyAuth +func (container *Container) BearerAPIKeyMiddleware() fiber.Handler { + container.logger.Debug("creating middlewares.BearerAPIKeyAuth") + return middlewares.BearerAPIKeyAuth(container.Logger(), container.Tracer(), container.UserRepository()) +} + +// PhoneAPIKeyMiddleware creates a new instance of middlewares.BearerAPIKeyAuth +func (container *Container) PhoneAPIKeyMiddleware() fiber.Handler { + container.logger.Debug("creating middlewares.PhoneAPIKeyMiddleware") + return middlewares.PhoneAPIKeyAuth(container.Logger(), container.Tracer(), container.PhoneAPIKeyRepository()) +} + +// AuthenticatedMiddleware creates a new instance of middlewares.Authenticated +func (container *Container) AuthenticatedMiddleware() fiber.Handler { + container.logger.Debug("creating middlewares.Authenticated") + return middlewares.Authenticated(container.Tracer()) +} + +// Logger creates a new instance of telemetry.Logger +func (container *Container) Logger(skipFrameCount ...int) telemetry.Logger { + container.logger.Debug("creating telemetry.Logger") + if len(skipFrameCount) > 0 { + return logger(skipFrameCount[0]) + } + return logger(3) +} + +// GormLogger creates a new instance of gormLogger.Interface +func (container *Container) GormLogger() gormLogger.Interface { + container.logger.Debug("creating gormLogger.Interface") + return telemetry.NewGormLogger( + container.Tracer(), + container.Logger(6), + ) +} + +func (container *Container) connect(dsn string, config *gorm.Config) (db *gorm.DB, err error) { + return gorm.Open(postgres.Open(dsn), config) +} + +// DedicatedDB creates an instance of gorm.DB if it has not been created already +func (container *Container) DedicatedDB() (db *gorm.DB) { + container.logger.Debug(fmt.Sprintf("creating %T", db)) + if container.dedicatedDB != nil { + return container.dedicatedDB + } + + config := &gorm.Config{ + TranslateError: true, + } + if isLocal() { + config = &gorm.Config{Logger: container.GormLogger()} + } + + db, err := container.connect(os.Getenv("DATABASE_URL_DEDICATED"), config) + if err != nil { + container.logger.Fatal(err) + } + + if err = db.Use(tracing.NewPlugin()); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot use GORM tracing plugin")) + } + + container.dedicatedDB = db + if os.Getenv("DATABASE_MIGRATION_SKIP") != "" { + container.logger.Debug(fmt.Sprintf("skipping migrations for [%T]", db)) + return container.dedicatedDB + } + + container.logger.Debug(fmt.Sprintf("Running migrations for dedicated [%T]", db)) + if err = db.AutoMigrate(&entities.Heartbeat{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Heartbeat{})) + } + + if err = db.AutoMigrate(&entities.HeartbeatMonitor{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.HeartbeatMonitor{})) + } + + return container.dedicatedDB +} + +// MongoDB creates a *mongo.Database connection to MongoDB Atlas +func (container *Container) MongoDB() *mongoDriver.Database { + if container.mongoDB != nil { + return container.mongoDB + } + + container.logger.Debug("creating MongoDB *mongo.Database connection") + + db, err := repositories.NewMongoDB(os.Getenv("MONGODB_URI")) + if err != nil { + container.logger.Fatal(err) + } + + container.mongoDB = db + return container.mongoDB +} + +// DBWithoutMigration creates an instance of gorm.DB if it has not been created already +func (container *Container) DBWithoutMigration() (db *gorm.DB) { + if container.db != nil { + return container.db + } + + container.logger.Debug(fmt.Sprintf("creating %T", db)) + + config := &gorm.Config{ + TranslateError: true, + Logger: container.GormLogger(), + } + + db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), config) + if err != nil { + container.logger.Fatal(err) + } + container.db = db + + if err = db.Use(tracing.NewPlugin()); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot use GORM tracing plugin")) + } + return container.db +} + +// DB creates an instance of gorm.DB if it has not been created already +func (container *Container) DB() (db *gorm.DB) { + if container.db != nil { + return container.db + } + + container.logger.Debug(fmt.Sprintf("creating %T", db)) + + config := &gorm.Config{ + TranslateError: true, + Logger: container.GormLogger(), + } + + db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), config) + if err != nil { + container.logger.Fatal(err) + } + container.db = db + + if err = db.Use(tracing.NewPlugin()); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot use GORM tracing plugin")) + } + + if os.Getenv("DATABASE_MIGRATION_SKIP") != "" { + container.logger.Debug(fmt.Sprintf("skipping migrations for [%T]", db)) + return container.db + } + + container.logger.Debug(fmt.Sprintf("Running migrations for %T", db)) + + // This prevents a bug in the Gorm AutoMigrate where it tries to delete this no existent constraints + // This is only applicable to PROD on cockroachDB + if os.Getenv("DATABASE_MIGRATION_CONSTRAINT_FIX") == "1" { + db.Exec(` +ALTER TABLE users ADD CONSTRAINT IF NOT EXISTS uni_users_api_key CHECK (api_key IS NOT NULL); +ALTER TABLE phone_api_keys ADD CONSTRAINT IF NOT EXISTS uni_phone_api_keys_api_key CHECK (api_key IS NOT NULL); +ALTER TABLE discords ADD CONSTRAINT IF NOT EXISTS uni_discords_server_id CHECK (server_id IS NOT NULL);`) + } + + if err = db.AutoMigrate(&entities.Message{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Message{})) + } + + if err = db.AutoMigrate(&entities.MessageThread{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.MessageThread{})) + } + + if err = db.AutoMigrate(&entities.User{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.User{})) + } + + if err = db.AutoMigrate(&entities.MessageSendSchedule{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.MessageSendSchedule{})) + } + + if err = db.AutoMigrate(&entities.Phone{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Phone{})) + } + + if err = db.AutoMigrate(&entities.PhoneNotification{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.PhoneNotification{})) + } + + if err = db.AutoMigrate(&entities.BillingUsage{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.BillingUsage{})) + } + + if err = db.AutoMigrate(&entities.Webhook{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Webhook{})) + } + + if err = db.AutoMigrate(&entities.Discord{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Discord{})) + } + + if err = db.AutoMigrate(&entities.Integration3CX{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Integration3CX{})) + } + + if err = db.AutoMigrate(&entities.PhoneAPIKey{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.PhoneAPIKey{})) + } + + if err = db.AutoMigrate(&entities.Contact{}); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Contact{})) + } + + return container.db +} + +// FirebaseApp creates a new instance of firebase.App +func (container *Container) FirebaseApp() (app *firebase.App) { + container.logger.Debug(fmt.Sprintf("creating %T", app)) + + app, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsJSON(container.FirebaseCredentials())) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot initialize firebase application")) + } + return app +} + +// InMemoryCache returns the shared in-memory cache.Cache, creating it on the first call. +func (container *Container) InMemoryCache() cache.Cache { + if container.inMemoryCache != nil { + return container.inMemoryCache + } + container.logger.Debug("creating an in memory cache") + c := ttlCache.New(time.Hour, time.Hour*2) + container.inMemoryCache = cache.NewMemoryCache(container.Tracer(), c) + return container.inMemoryCache +} + +// Cache creates a new instance of cache.Cache +func (container *Container) Cache() cache.Cache { + container.logger.Debug("creating cache.Cache") + opt, err := redis.ParseURL(os.Getenv("REDIS_URL")) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot parse redis url [%s]", os.Getenv("REDIS_URL"))) + } + if strings.HasPrefix(os.Getenv("REDIS_URL"), "rediss://") { + opt.TLSConfig = &tls.Config{ + MinVersion: tls.VersionTLS12, + } + } + + redisClient := redis.NewClient(opt) + + // Enable tracing instrumentation. + if err = redisotel.InstrumentTracing(redisClient); err != nil { + container.logger.Error(stacktrace.Propagatef(err, "cannot instrument redis tracing")) + } + + // Enable metrics instrumentation. + if err = redisotel.InstrumentMetrics(redisClient); err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot instrument redis metrics")) + } + + return cache.NewRedisCache(container.Tracer(), redisClient) +} + +// FirebaseAuthClient creates a new instance of auth.Client +func (container *Container) FirebaseAuthClient() (client *auth.Client) { + container.logger.Debug(fmt.Sprintf("creating %T", client)) + authClient, err := container.FirebaseApp().Auth(context.Background()) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot initialize firebase auth client")) + } + return authClient +} + +// CloudTasksClient creates a new instance of cloudtasks.Client +func (container *Container) CloudTasksClient() (client *cloudtasks.Client) { + container.logger.Debug(fmt.Sprintf("creating %T", client)) + + client, err := cloudtasks.NewClient(context.Background(), option.WithCredentialsJSON(container.FirebaseCredentials())) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot initialize cloud tasks client")) + } + + return client +} + +// EventsQueueConfiguration creates a new instance of services.PushQueueConfig +func (container *Container) EventsQueueConfiguration() (config services.PushQueueConfig) { + container.logger.Debug(fmt.Sprintf("creating %T", config)) + + return services.PushQueueConfig{ + UserAPIKey: os.Getenv("EVENTS_QUEUE_USER_API_KEY"), + Name: os.Getenv("EVENTS_QUEUE_NAME"), + UserID: entities.UserID(os.Getenv("EVENTS_QUEUE_USER_ID")), + ConsumerEndpoint: os.Getenv("EVENTS_QUEUE_ENDPOINT"), + } +} + +// EventsQueue creates a new instance of services.PushQueue +func (container *Container) EventsQueue() (queue services.PushQueue) { + container.logger.Debug("creating events services.PushQueue") + + if os.Getenv("EVENTS_QUEUE_TYPE") == "emulator" { + return container.EmulatorEventsQueue() + } + + return container.CloudTaskEventsQueue() +} + +// EmulatorEventsQueue creates an in process instance of events services.PushQueue +func (container *Container) EmulatorEventsQueue() (queue services.PushQueue) { + container.logger.Debug("creating emulator events services.PushQueue") + return services.EmulatorPushQueue( + container.Logger(), + container.Tracer(), + container.HTTPClient("emulator_events_queue"), + container.EventsQueueConfiguration(), + ) +} + +// CloudTaskEventsQueue creates a Google cloud task instance of events services.PushQueue +func (container *Container) CloudTaskEventsQueue() (queue services.PushQueue) { + container.logger.Debug("creating cloud task events services.PushQueue") + return services.NewGooglePushQueue( + container.Logger(), + container.Tracer(), + container.CloudTasksClient(), + container.EventsQueueConfiguration(), + ) +} + +// FCMClient creates the appropriate FCM client based on configuration. +// When FCM_ENDPOINT is set, it returns an EmulatorFCMClient that sends +// notifications directly to the phone emulator via HTTP. +// Otherwise, it returns a FirebaseFCMClient that uses the real Firebase SDK. +func (container *Container) FCMClient() services.FCMClient { + if fcmEndpoint := os.Getenv("FCM_ENDPOINT"); fcmEndpoint != "" { + container.logger.Info(fmt.Sprintf("using emulator FCM client with endpoint: %s", fcmEndpoint)) + return services.NewEmulatorFCMClient( + container.HTTPClient("emulator_fcm"), + fcmEndpoint, + container.Logger(), + ) + } + + container.logger.Debug("creating FirebaseFCMClient") + messagingClient, err := container.FirebaseApp().Messaging(context.Background()) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot initialize firebase messaging client")) + } + return services.NewFirebaseFCMClient(messagingClient) +} + +// NotificationHTTPClient creates the OpenTelemetry-instrumented client for phone notification adapters. +func (container *Container) NotificationHTTPClient() *http.Client { + return &http.Client{ + Transport: container.HTTPRoundTripperWithoutRetry("phone_notification_http"), + } +} + +// PhoneNotificationClients creates notification clients keyed by phone transport. +func (container *Container) PhoneNotificationClients() map[entities.NotificationTransport]services.FCMClient { + return map[entities.NotificationTransport]services.FCMClient{ + entities.NotificationTransportFCM: container.FCMClient(), + entities.NotificationTransportHTTP: services.NewHTTPNotificationSender( + container.Logger(), + container.NotificationHTTPClient(), + ), + } +} + +// FirebaseCredentials returns firebase credentials as bytes. +func (container *Container) FirebaseCredentials() []byte { + container.logger.Debug("creating firebase credentials") + return []byte(os.Getenv("FIREBASE_CREDENTIALS")) +} + +// Tracer creates a new instance of telemetry.Tracer +func (container *Container) Tracer() (t telemetry.Tracer) { + container.logger.Debug("creating telemetry.Tracer") + return telemetry.NewOtelLogger( + container.projectID, + container.Logger(), + ) +} + +// MessageHandlerValidator creates a new instance of validators.MessageHandlerValidator +func (container *Container) MessageHandlerValidator() (validator *validators.MessageHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewMessageHandlerValidator( + container.Logger(), + container.Tracer(), + container.PhoneService(), + container.TurnstileTokenValidator(), + ) +} + +// TurnstileTokenValidator creates a new instance of validators.TurnstileTokenValidator +func (container *Container) TurnstileTokenValidator() (validator *validators.TurnstileTokenValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewTurnstileTokenValidator( + container.Logger(), + container.Tracer(), + os.Getenv("CLOUDFLARE_TURNSTILE_SECRET_KEY"), + container.HTTPClient("turnstile"), + ) +} + +// BulkMessageHandlerValidator creates a new instance of validators.BulkMessageHandlerValidator +func (container *Container) BulkMessageHandlerValidator() (validator *validators.BulkMessageHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewBulkMessageHandlerValidator( + container.Logger(), + container.Tracer(), + container.PhoneService(), + container.UserService(), + ) +} + +// HeartbeatHandler creates a new instance of handlers.HeartbeatHandler +func (container *Container) HeartbeatHandler() (h *handlers.HeartbeatHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", h)) + return handlers.NewHeartbeatHandler( + container.Logger(), + container.Tracer(), + container.HeartbeatHandlerValidator(), + container.HeartbeatService(), + ) +} + +// BillingHandler creates a new instance of handlers.BillingHandler +func (container *Container) BillingHandler() (h *handlers.BillingHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", h)) + return handlers.NewBillingHandler( + container.Logger(), + container.Tracer(), + container.BillingHandlerValidator(), + container.BillingService(), + ) +} + +// WebhookHandler creates a new instance of handlers.WebhookHandler +func (container *Container) WebhookHandler() (h *handlers.WebhookHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", h)) + return handlers.NewWebhookHandler( + container.Logger(), + container.Tracer(), + container.WebhookService(), + container.WebhookHandlerValidator(), + ) +} + +// HeartbeatHandlerValidator creates a new instance of validators.HeartbeatHandlerValidator +func (container *Container) HeartbeatHandlerValidator() (validator *validators.HeartbeatHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewHeartbeatHandlerValidator( + container.Logger(), + container.Tracer(), + ) +} + +// BillingHandlerValidator creates a new instance of validators.BillingHandlerValidator +func (container *Container) BillingHandlerValidator() (validator *validators.BillingHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewBillingHandlerValidator( + container.Logger(), + container.Tracer(), + ) +} + +// DiscordHandlerValidator creates a new instance of validators.DiscordHandlerValidator +func (container *Container) DiscordHandlerValidator() (validator *validators.DiscordHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewDiscordHandlerValidator( + container.Logger(), + container.Tracer(), + container.DiscordClient(), + ) +} + +// WebhookHandlerValidator creates a new instance of validators.WebhookHandlerValidator +func (container *Container) WebhookHandlerValidator() (validator *validators.WebhookHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewWebhookHandlerValidator( + container.Logger(), + container.Tracer(), + container.PhoneService(), + ) +} + +// MessageThreadHandler creates a new instance of handlers.MessageThreadHandler +func (container *Container) MessageThreadHandler() (h *handlers.MessageThreadHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", h)) + return handlers.NewMessageThreadHandler( + container.Logger(), + container.Tracer(), + container.MessageThreadHandlerValidator(), + container.MessageThreadService(), + ) +} + +// MessageThreadHandlerValidator creates a new instance of validators.MessageThreadHandlerValidator +func (container *Container) MessageThreadHandlerValidator() (validator *validators.MessageThreadHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewMessageThreadHandlerValidator( + container.Logger(), + container.Tracer(), + ) +} + +// ContactHandlerValidator creates a new instance of validators.ContactHandlerValidator +func (container *Container) ContactHandlerValidator() (validator *validators.ContactHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewContactHandlerValidator( + container.Logger(), + container.Tracer(), + ) +} + +// ContactHandler creates a new instance of handlers.ContactHandler +func (container *Container) ContactHandler() (h *handlers.ContactHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", h)) + return handlers.NewContactHandler( + container.Logger(), + container.Tracer(), + container.ContactHandlerValidator(), + container.ContactService(), + container.EntitlementService(), + ) +} + +// PhoneHandlerValidator creates a new instance of validators.PhoneHandlerValidator +func (container *Container) PhoneHandlerValidator() (validator *validators.PhoneHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewPhoneHandlerValidator( + container.Logger(), + container.Tracer(), + container.MessageSendScheduleService(), + ) +} + +// UserHandlerValidator creates a new instance of validators.UserHandlerValidator +func (container *Container) UserHandlerValidator() (validator *validators.UserHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewUserHandlerValidator( + container.Logger(), + container.Tracer(), + container.UserService(), + ) +} + +// EventDispatcher creates a new instance of services.EventDispatcher +func (container *Container) EventDispatcher() (dispatcher *services.EventDispatcher) { + if container.eventDispatcher != nil { + return container.eventDispatcher + } + + container.logger.Debug(fmt.Sprintf("creating %T", dispatcher)) + dispatcher = services.NewEventDispatcher( + container.Logger(), + container.Tracer(), + container.Float64Histogram("event.publisher.duration", "ms", "measures the duration of processing CloudEvents"), + container.EventsQueue(), + container.EventsQueueConfiguration(), + ) + + container.eventDispatcher = dispatcher + return dispatcher +} + +// Float64Histogram creates a new instance of metric.Float64Histogram +func (container *Container) Float64Histogram(name, unit, description string) otelMetric.Float64Histogram { + container.logger.Debug("creating GORM repositories.MessageRepository") + meter := otel.GetMeterProvider().Meter( + container.projectID, + otelMetric.WithInstrumentationVersion(otel.Version()), + ) + histogram, err := meter.Float64Histogram(name, otelMetric.WithUnit(unit), otelMetric.WithDescription(description)) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create float64 histogram")) + } + return histogram +} + +// MessageRepository creates a new instance of repositories.MessageRepository +func (container *Container) MessageRepository() (repository repositories.MessageRepository) { + container.logger.Debug("creating GORM repositories.MessageRepository") + return repositories.NewGormMessageRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) +} + +// PhoneAPIKeyRepository creates a new instance of repositories.PhoneAPIKeyRepository +func (container *Container) PhoneAPIKeyRepository() (repository repositories.PhoneAPIKeyRepository) { + container.logger.Debug("creating GORM repositories.PhoneAPIKeyRepository") + return repositories.NewGormPhoneAPIKeyRepository( + container.Logger(), + container.Tracer(), + container.DB(), + container.UserRistrettoCache(), + ) +} + +// Integration3CXRepository creates a new instance of repositories.Integration3CxRepository +func (container *Container) Integration3CXRepository() (repository repositories.Integration3CxRepository) { + container.logger.Debug("creating GORM repositories.Integration3CxRepository") + return repositories.NewGormIntegration3CXRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) +} + +// PhoneRepository creates a new instance of repositories.PhoneRepository +func (container *Container) PhoneRepository() (repository repositories.PhoneRepository) { + container.logger.Debug("creating GORM repositories.PhoneRepository") + return repositories.NewGormPhoneRepository( + container.Logger(), + container.Tracer(), + container.DB(), + container.PhoneRistrettoCache(), + ) +} + +// MessageSendScheduleRepository creates a new instance of repositories.MessageSendScheduleRepository +func (container *Container) MessageSendScheduleRepository() repositories.MessageSendScheduleRepository { + container.logger.Debug("creating GORM repositories.MessageSendScheduleRepository") + return repositories.NewGormMessageSendScheduleRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) +} + +// MessageSendScheduleService creates a new instance of services.MessageSendScheduleService +func (container *Container) MessageSendScheduleService() *services.MessageSendScheduleService { + container.logger.Debug("creating services.MessageSendScheduleService") + return services.NewMessageSendScheduleService( + container.Logger(), + container.Tracer(), + container.MessageSendScheduleRepository(), + container.EventDispatcher(), + ) +} + +// MessageSendScheduleHandlerValidator creates a new instance of validators.MessageSendScheduleHandlerValidator +func (container *Container) MessageSendScheduleHandlerValidator() *validators.MessageSendScheduleHandlerValidator { + container.logger.Debug("creating validators.MessageSendScheduleHandlerValidator") + return validators.NewMessageSendScheduleHandlerValidator( + container.Logger(), + container.Tracer(), + ) +} + +// MessageSendScheduleHandler creates a new instance of handlers.MessageSendScheduleHandler +func (container *Container) MessageSendScheduleHandler() *handlers.MessageSendScheduleHandler { + container.logger.Debug("creating handlers.MessageSendScheduleHandler") + return handlers.NewMessageSendScheduleHandler( + container.Logger(), + container.Tracer(), + container.MessageSendScheduleHandlerValidator(), + container.MessageSendScheduleService(), + container.EntitlementService(), + ) +} + +// BillingUsageRepository creates a new instance of repositories.BillingUsageRepository +func (container *Container) BillingUsageRepository() (repository repositories.BillingUsageRepository) { + container.logger.Debug("creating GORM repositories.BillingUsageRepository") + return repositories.NewGormBillingUsageRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) +} + +// EntitlementService creates a new instance of services.EntitlementService +func (container *Container) EntitlementService() *services.EntitlementService { + container.logger.Debug("creating services.EntitlementService") + return services.NewEntitlementService( + container.Logger(), + container.Tracer(), + os.Getenv("ENTITLEMENT_ENABLED") == "true", + container.UserRepository(), + ) +} + +// DiscordRepository creates a new instance of repositories.DiscordRepository +func (container *Container) DiscordRepository() (repository repositories.DiscordRepository) { + container.logger.Debug("creating GORM repositories.DiscordRepository") + return repositories.NewGormDiscordRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) +} + +// WebhookRepository creates a new instance of repositories.WebhookRepository +func (container *Container) WebhookRepository() (repository repositories.WebhookRepository) { + container.logger.Debug("creating GORM repositories.WebhookRepository") + return repositories.NewGormWebhookRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) +} + +// PhoneNotificationRepository creates a new instance of repositories.PhoneNotificationRepository +func (container *Container) PhoneNotificationRepository() (repository repositories.PhoneNotificationRepository) { + container.logger.Debug("creating GORM repositories.PhoneNotificationRepository") + return repositories.NewGormPhoneNotificationRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) +} + +// MessageThreadRepository creates a new instance of repositories.MessageThreadRepository +func (container *Container) MessageThreadRepository() (repository repositories.MessageThreadRepository) { + container.logger.Debug("creating GORM repositories.MessageThreadRepository") + return repositories.NewGormMessageThreadRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) +} + +// ContactRepository creates a new instance of repositories.ContactRepository +func (container *Container) ContactRepository() (repository repositories.ContactRepository) { + switch os.Getenv("CONTACT_DB_BACKEND") { + case "mongodb": + container.logger.Debug("creating MongoDB repositories.ContactRepository") + return repositories.NewMongoContactRepository( + container.Logger(), + container.Tracer(), + container.MongoDB(), + ) + default: + container.logger.Debug("creating GORM repositories.ContactRepository") + return repositories.NewGormContactRepository( + container.Logger(), + container.Tracer(), + container.DB(), + ) + } +} + +// HeartbeatMonitorRepository creates a new instance of repositories.HeartbeatMonitorRepository +func (container *Container) HeartbeatMonitorRepository() (repository repositories.HeartbeatMonitorRepository) { + switch os.Getenv("HEARTBEAT_DB_BACKEND") { + case "mongodb": + container.logger.Debug("creating MongoDB repositories.HeartbeatMonitorRepository") + return repositories.NewMongoHeartbeatMonitorRepository( + container.Logger(), + container.Tracer(), + container.MongoDB(), + ) + default: + container.logger.Debug("creating GORM repositories.HeartbeatMonitorRepository") + return repositories.NewGormHeartbeatMonitorRepository( + container.Logger(), + container.Tracer(), + container.DedicatedDB(), + ) + } +} + +// HeartbeatService creates a new instance of services.HeartbeatService +func (container *Container) HeartbeatService() (service *services.HeartbeatService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewHeartbeatService( + container.Logger(), + container.Tracer(), + container.HeartbeatRepository(), + container.HeartbeatMonitorRepository(), + container.EventDispatcher(), + ) +} + +// BillingService creates a new instance of services.BillingService +func (container *Container) BillingService() (service *services.BillingService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewBillingService( + container.Logger(), + container.Tracer(), + container.InMemoryCache(), + container.Mailer(), + container.UserEmailFactory(), + container.BillingUsageRepository(), + container.UserRepository(), + ) +} + +// DiscordService creates a new instance of services.DiscordService +func (container *Container) DiscordService() (service *services.DiscordService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewDiscordService( + container.Logger(), + container.Tracer(), + container.DiscordClient(), + container.DiscordRepository(), + container.EventDispatcher(), + ) +} + +// WebhookService creates a new instance of services.WebhookService +func (container *Container) WebhookService() (service *services.WebhookService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewWebhookService( + container.Logger(), + container.Tracer(), + &http.Client{ + Timeout: 6 * time.Second, + Transport: container.HTTPRoundTripperWithoutRetry("webhook"), + }, + container.WebhookRepository(), + container.EventDispatcher(), + ) +} + +// Integration3CXService creates a new instance of services.Integration3CXService +func (container *Container) Integration3CXService() (service *services.Integration3CXService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewIntegration3CXService( + container.Logger(), + container.Tracer(), + container.HTTPClient("integration_3cx"), + container.Integration3CXRepository(), + ) +} + +// HTTPClient creates a new http.Client +func (container *Container) HTTPClient(name string) *http.Client { + container.logger.Debug(fmt.Sprintf("creating %s %T", name, http.DefaultClient)) + return &http.Client{ + Timeout: 60 * time.Second, + Transport: container.HTTPRoundTripper(name), + } +} + +// HTTPRoundTripper creates an open telemetry http.RoundTripper +func (container *Container) HTTPRoundTripper(name string) http.RoundTripper { + container.logger.Debug(fmt.Sprintf("Debug: initializing %s %T", name, http.DefaultTransport)) + return otelroundtripper.New( + otelroundtripper.WithName(name), + otelroundtripper.WithParent(container.RetryHTTPRoundTripper()), + otelroundtripper.WithMeter(otel.GetMeterProvider().Meter(container.projectID)), + ) +} + +// HTTPRoundTripperWithoutRetry creates an open telemetry http.RoundTripper without retry +func (container *Container) HTTPRoundTripperWithoutRetry(name string) http.RoundTripper { + container.logger.Debug(fmt.Sprintf("Debug: initializing %s %T", name, http.DefaultTransport)) + return otelroundtripper.New( + otelroundtripper.WithName(name), + otelroundtripper.WithMeter(otel.GetMeterProvider().Meter(container.projectID)), + ) +} + +// OtelResources generates default open telemetry resources +func (container *Container) OtelResources(version string, namespace string) *resource.Resource { + return resource.NewWithAttributes( + semconv.SchemaURL, + semconv.ServiceNameKey.String(namespace), + semconv.ServiceVersionKey.String(version), + semconv.ServiceInstanceIDKey.String(instanceID()), + semconv.DeploymentEnvironmentKey.String(os.Getenv("ENV")), + ) +} + +// RetryHTTPRoundTripper creates a retryable http.RoundTripper +func (container *Container) RetryHTTPRoundTripper() http.RoundTripper { + container.logger.Debug(fmt.Sprintf("initializing retry %T", http.DefaultTransport)) + retryClient := retryablehttp.NewClient() + retryClient.Logger = container.Logger() + retryClient.RetryMax = 2 + return retryClient.StandardClient().Transport +} + +// PhoneService creates a new instance of services.PhoneService +func (container *Container) PhoneService() (service *services.PhoneService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewPhoneService( + container.Logger(), + container.Tracer(), + container.PhoneRepository(), + container.EventDispatcher(), + ) +} + +// MarketingService creates a new instance of services.MarketingService +func (container *Container) MarketingService() (service *services.MarketingService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewMarketingService( + container.Logger(), + container.Tracer(), + container.FirebaseAuthClient(), + container.PlunkClient(), + ) +} + +// UserService creates a new instance of services.UserService +func (container *Container) UserService() (service *services.UserService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewUserService( + container.Logger(), + container.Tracer(), + container.UserRepository(), + container.Mailer(), + container.UserEmailFactory(), + container.LemonsqueezyClient(), + container.EventDispatcher(), + container.FirebaseAuthClient(), + container.HTTPClient("lemonsqueezy"), + ) +} + +// Mailer creates a new instance of emails.Mailer +func (container *Container) Mailer() (mailer emails.Mailer) { + container.logger.Debug("creating emails.Mailer") + return emails.NewSMTPEmailService( + container.Tracer(), + emails.SMTPConfig{ + FromName: os.Getenv("SMTP_FROM_NAME"), + FromEmail: os.Getenv("SMTP_FROM_EMAIL"), + Username: os.Getenv("SMTP_USERNAME"), + Password: os.Getenv("SMTP_PASSWORD"), + Hostname: os.Getenv("SMTP_HOST"), + Port: os.Getenv("SMTP_PORT"), + }, + ) +} + +// UserEmailFactory creates a new instance of emails.UserEmailFactory +func (container *Container) UserEmailFactory() (factory emails.UserEmailFactory) { + container.logger.Debug("creating emails.UserEmailFactory") + return emails.NewHermesUserEmailFactory(&emails.HermesGeneratorConfig{ + AppURL: os.Getenv("APP_URL"), + AppName: os.Getenv("APP_NAME"), + AppLogoURL: os.Getenv("APP_LOGO_URL"), + }) +} + +// NotificationEmailFactory creates a new instance of emails.NotificationEmailFactory +func (container *Container) NotificationEmailFactory() (factory emails.NotificationEmailFactory) { + container.logger.Debug("creating emails.UserEmailFactory") + return emails.NewHermesNotificationEmailFactory(&emails.HermesGeneratorConfig{ + AppURL: os.Getenv("APP_URL"), + AppName: os.Getenv("APP_NAME"), + AppLogoURL: os.Getenv("APP_LOGO_URL"), + }) +} + +// MessageThreadService creates a new instance of services.MessageService +func (container *Container) MessageThreadService() (service *services.MessageThreadService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewMessageThreadService( + container.Logger(), + container.Tracer(), + container.MessageThreadRepository(), + container.PhoneRepository(), + container.EventDispatcher(), + container.ContactService(), + ) +} + +// ContactService creates a new instance of services.ContactService +func (container *Container) ContactService() (service *services.ContactService) { + if container.contactService != nil { + return container.contactService + } + container.logger.Debug(fmt.Sprintf("creating %T", service)) + container.contactService = services.NewContactService( + container.Logger(), + container.Tracer(), + container.ContactRepository(), + container.ContactRistrettoCache(), + ) + return container.contactService +} + +// EmailNotificationService creates a new instance of services.EmailNotificationService +func (container *Container) EmailNotificationService() (service *services.EmailNotificationService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewEmailNotificationService( + container.Logger(), + container.Tracer(), + container.UserRepository(), + container.NotificationEmailFactory(), + container.Mailer(), + container.Cache(), + ) +} + +// MessageHandler creates a new instance of handlers.MessageHandler +func (container *Container) MessageHandler() (handler *handlers.MessageHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + return handlers.NewMessageHandler( + container.Logger(), + container.Tracer(), + container.MessageHandlerValidator(), + container.BillingService(), + container.MessageService(), + ) +} + +// BulkMessageHandler creates a new instance of handlers.BulkMessageHandler +func (container *Container) BulkMessageHandler() (handler *handlers.BulkMessageHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + return handlers.NewBulkMessageHandler( + container.Logger(), + container.Tracer(), + container.BulkMessageHandlerValidator(), + container.BillingService(), + container.MessageService(), + ) +} + +// UserHandler creates a new instance of handlers.MessageHandler +func (container *Container) UserHandler() (handler *handlers.UserHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + return handlers.NewUserHandler( + container.Logger(), + container.Tracer(), + container.UserHandlerValidator(), + container.UserService(), + ) +} + +// PhoneHandler creates a new instance of handlers.PhoneHandler +func (container *Container) PhoneHandler() (handler *handlers.PhoneHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + return handlers.NewPhoneHandler( + container.Logger(), + container.Tracer(), + container.PhoneService(), + container.PhoneHandlerValidator(), + ) +} + +// EventsHandler creates a new instance of handlers.EventsHandler +func (container *Container) EventsHandler() (handler *handlers.EventsHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + + return handlers.NewEventsHandler( + container.Logger(), + container.Tracer(), + container.EventsQueueConfiguration(), + container.EventDispatcher(), + ) +} + +// RegisterMessageListeners registers event listeners for listeners.MessageListener +func (container *Container) RegisterMessageListeners() { + container.logger.Debug(fmt.Sprintf("registering listners for %T", listeners.MessageListener{})) + _, routes := listeners.NewMessageListener( + container.Logger(), + container.Tracer(), + container.MessageService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterMessageSendScheduleListeners registers event listeners for listeners.MessageSendScheduleListener +func (container *Container) RegisterMessageSendScheduleListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.MessageSendScheduleListener{})) + _, routes := listeners.NewMessageSendScheduleListener( + container.Logger(), + container.Tracer(), + container.MessageSendScheduleService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// LemonsqueezyService creates a new instance of services.LemonsqueezyService +func (container *Container) LemonsqueezyService() (service *services.LemonsqueezyService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewLemonsqueezyService( + container.Logger(), + container.Tracer(), + container.UserRepository(), + container.EventDispatcher(), + ) +} + +// LemonsqueezyHandler creates a new instance of handlers.LemonsqueezyHandler +func (container *Container) LemonsqueezyHandler() (handler *handlers.LemonsqueezyHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + + return handlers.NewLemonsqueezyHandler( + container.Logger(), + container.Tracer(), + container.LemonsqueezyService(), + container.LemonsqueezyHandlerValidator(), + ) +} + +// Integration3CXHandler creates a new instance of handlers.Integration3CXHandler +func (container *Container) Integration3CXHandler() (handler *handlers.Integration3CXHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + + return handlers.NewIntegration3CxHandler( + container.Logger(), + container.Tracer(), + container.MessageService(), + container.BillingService(), + ) +} + +// PhoneAPIKeyHandler creates a new instance of handlers.PhoneAPIKeyHandler +func (container *Container) PhoneAPIKeyHandler() (handler *handlers.PhoneAPIKeyHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + + return handlers.NewPhoneAPIKeyHandler( + container.Logger(), + container.Tracer(), + container.PhoneAPIKeyHandlerValidator(), + container.PhoneAPIKeyService(), + container.EntitlementService(), + ) +} + +// DiscordHandler creates a new instance of handlers.DiscordHandler +func (container *Container) DiscordHandler() (handler *handlers.DiscordHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + + return handlers.NewDiscordHandler( + container.Logger(), + container.Tracer(), + container.DiscordHandlerValidator(), + container.DiscordService(), + container.MessageService(), + container.BillingService(), + container.MessageHandlerValidator(), + ) +} + +// LemonsqueezyHandlerValidator creates a new instance of validators.LemonsqueezyHandlerValidator +func (container *Container) LemonsqueezyHandlerValidator() (validator *validators.LemonsqueezyHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewLemonsqueezyHandlerValidator( + container.Logger(), + container.Tracer(), + container.LemonsqueezyClient(), + ) +} + +// PhoneAPIKeyHandlerValidator creates a new instance of validators.PhoneAPIKeyHandlerValidator +func (container *Container) PhoneAPIKeyHandlerValidator() (validator *validators.PhoneAPIKeyHandlerValidator) { + container.logger.Debug(fmt.Sprintf("creating %T", validator)) + return validators.NewPhoneAPIKeyHandlerValidator( + container.Logger(), + container.Tracer(), + ) +} + +// LemonsqueezyClient creates a new instance of lemonsqueezy.Client +func (container *Container) LemonsqueezyClient() (client *lemonsqueezy.Client) { + container.logger.Debug(fmt.Sprintf("creating %T", client)) + return lemonsqueezy.New( + lemonsqueezy.WithHTTPClient(container.HTTPClient("lemonsqueezy")), + lemonsqueezy.WithAPIKey(os.Getenv("LEMONSQUEEZY_API_KEY")), + lemonsqueezy.WithSigningSecret(os.Getenv("LEMONSQUEEZY_SIGNING_SECRET")), + ) +} + +// PusherClient creates a new instance of pusher.Client +func (container *Container) PusherClient() (client *pusher.Client) { + container.logger.Debug(fmt.Sprintf("creating %T", client)) + return &pusher.Client{ + AppID: os.Getenv("PUSHER_APP_ID"), + Key: os.Getenv("PUSHER_KEY"), + Secret: os.Getenv("PUSHER_SECRET"), + Cluster: os.Getenv("PUSHER_CLUSTER"), + Secure: true, + } +} + +// DiscordClient creates a new instance of discord.Client +func (container *Container) DiscordClient() (client *discord.Client) { + container.logger.Debug(fmt.Sprintf("creating %T", client)) + return discord.New( + discord.WithHTTPClient(container.HTTPClient("discord")), + discord.WithApplicationID(os.Getenv("DISCORD_APPLICATION_ID")), + discord.WithBotToken(os.Getenv("DISCORD_BOT_TOKEN")), + ) +} + +// PlunkClient creates a new instance of plunk.Client +func (container *Container) PlunkClient() (client *plunk.Client) { + container.logger.Debug(fmt.Sprintf("creating %T", client)) + return plunk.New( + plunk.WithHTTPClient(container.HTTPClient("plunk")), + plunk.WithSecretKey(os.Getenv("PLUNK_SECRET_KEY")), + plunk.WithPublicKey(os.Getenv("PLUNK_PUBLIC_KEY")), + ) +} + +// RegisterLemonsqueezyRoutes registers routes for the /lemonsqueezy prefix +func (container *Container) RegisterLemonsqueezyRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.LemonsqueezyHandler{})) + container.LemonsqueezyHandler().RegisterRoutes(container.App()) +} + +// RegisterIntegration3CXRoutes registers routes for the /integration/3cx prefix +func (container *Container) RegisterIntegration3CXRoutes() { + container.logger.Debug(fmt.Sprintf("registering [%T] routes", &handlers.Integration3CXHandler{})) + container.Integration3CXHandler().RegisterRoutes(container.App(), container.BearerAPIKeyMiddleware(), container.AuthenticatedMiddleware()) +} + +// RegisterPhoneAPIKeyRoutes registers routes for the /phone-api-key prefix +func (container *Container) RegisterPhoneAPIKeyRoutes() { + container.logger.Debug(fmt.Sprintf("registering [%T] routes", &handlers.Integration3CXHandler{})) + container.PhoneAPIKeyHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterDiscordRoutes registers routes for the /discord prefix +func (container *Container) RegisterDiscordRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.DiscordHandler{})) + container.DiscordHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterMessageThreadListeners registers event listeners for listeners.MessageThreadListener +func (container *Container) RegisterMessageThreadListeners() { + container.logger.Debug(fmt.Sprintf("registering listners for %T", listeners.MessageThreadListener{})) + _, routes := listeners.NewMessageThreadListener( + container.Logger(), + container.Tracer(), + container.MessageThreadService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterContactListeners registers event listeners for listeners.ContactListener. +func (container *Container) RegisterContactListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.ContactListener{})) + _, routes := listeners.NewContactListener( + container.Logger(), + container.Tracer(), + container.ContactService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterEmailNotificationListeners registers event listeners for listeners.EmailNotificationListener +func (container *Container) RegisterEmailNotificationListeners() { + container.logger.Debug(fmt.Sprintf("registering listners for %T", listeners.EmailNotificationListener{})) + _, routes := listeners.NewEmailNotificationListener( + container.Logger(), + container.Tracer(), + container.EmailNotificationService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterNotificationListeners registers event listeners for listeners.PhoneNotificationListener +func (container *Container) RegisterNotificationListeners() { + container.logger.Debug(fmt.Sprintf("registering listners for %T", listeners.PhoneNotificationListener{})) + _, routes := listeners.NewNotificationListener( + container.Logger(), + container.Tracer(), + container.NotificationService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterHeartbeatListeners registers event listeners for listeners.HeartbeatListener +func (container *Container) RegisterHeartbeatListeners() { + container.logger.Debug(fmt.Sprintf("registering listners for %T", listeners.HeartbeatListener{})) + _, routes := listeners.NewHeartbeatListener( + container.Logger(), + container.Tracer(), + container.HeartbeatService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterUserListeners registers event listeners for listeners.UserListener +func (container *Container) RegisterUserListeners() { + container.logger.Debug(fmt.Sprintf("registering listners for %T", listeners.UserListener{})) + _, routes := listeners.NewUserListener( + container.Logger(), + container.Tracer(), + container.UserService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterBillingListeners registers event listeners for listeners.BillingListener +func (container *Container) RegisterBillingListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.BillingListener{})) + _, routes := listeners.NewBillingListener( + container.Logger(), + container.Tracer(), + container.BillingService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterDiscordListeners registers event listeners for listeners.DiscordListener +func (container *Container) RegisterDiscordListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.DiscordListener{})) + _, routes := listeners.NewDiscordListener( + container.Logger(), + container.Tracer(), + container.DiscordService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterMarketingListeners registers event listeners for listeners.MarketingListener +func (container *Container) RegisterMarketingListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.MarketingListener{})) + + if os.Getenv("PLUNK_SECRET_KEY") == "" { + container.logger.Debug("skipping marketing listeners because the PLUNK_SECRET_KEY env variable is not set") + return + } + + _, routes := listeners.NewMarketingListener( + container.Logger(), + container.Tracer(), + container.MarketingService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterIntegration3CXListeners registers event listeners for listeners.Integration3CXListener +func (container *Container) RegisterIntegration3CXListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.Integration3CXListener{})) + _, routes := listeners.NewIntegration3CXListener( + container.Logger(), + container.Tracer(), + container.Integration3CXService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterPhoneAPIKeyListeners registers event listeners for listeners.PhoneAPIKeyListener +func (container *Container) RegisterPhoneAPIKeyListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.PhoneAPIKeyListener{})) + _, routes := listeners.NewPhoneAPIKeyListener( + container.Logger(), + container.Tracer(), + container.PhoneAPIKeyService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterPhoneListeners registers event listeners for listeners.PhoneListener +func (container *Container) RegisterPhoneListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.PhoneListener{})) + _, routes := listeners.NewPhoneListener( + container.Logger(), + container.Tracer(), + container.PhoneService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterWebsocketListeners registers event listeners for listeners.WebsocketListener +func (container *Container) RegisterWebsocketListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.WebsocketListener{})) + + if os.Getenv("PUSHER_SECRET") == "" { + container.logger.Warn(stacktrace.NewErrorf("skipping websocket listeners because the PUSHER_SECRET env variable is not set")) + return + } + + _, routes := listeners.NewWebsocketListener( + container.Logger(), + container.Tracer(), + container.PusherClient(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// RegisterWebhookListeners registers event listeners for listeners.WebhookListener +func (container *Container) RegisterWebhookListeners() { + container.logger.Debug(fmt.Sprintf("registering listeners for %T", listeners.WebhookListener{})) + _, routes := listeners.NewWebhookListener( + container.Logger(), + container.Tracer(), + container.WebhookService(), + ) + + for event, handler := range routes { + container.EventDispatcher().Subscribe(event, handler) + } +} + +// MessageService creates a new instance of services.MessageService +func (container *Container) MessageService() (service *services.MessageService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewMessageService( + container.Logger(), + container.Tracer(), + container.MessageRepository(), + container.EventDispatcher(), + container.PhoneService(), + container.AttachmentRepository(), + container.APIBaseURL(), + ) +} + +// AttachmentRepository creates a cached AttachmentRepository based on configuration +func (container *Container) AttachmentRepository() repositories.AttachmentRepository { + if container.attachmentRepository != nil { + return container.attachmentRepository + } + + bucket := os.Getenv("GCS_BUCKET_NAME") + if bucket != "" { + container.logger.Debug("creating GoogleCloudStorageAttachmentRepository") + client, err := storage.NewClient(context.Background(), option.WithAuthCredentialsJSON(option.ServiceAccount, container.FirebaseCredentials())) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create GCS client")) + } + container.attachmentRepository = repositories.NewGoogleCloudStorageAttachmentRepository( + container.Logger(), + container.Tracer(), + client, + bucket, + ) + } else { + container.logger.Debug("creating MemoryAttachmentRepository (GCS_BUCKET_NAME not set)") + container.attachmentRepository = repositories.NewMemoryAttachmentRepository( + container.Logger(), + container.Tracer(), + ) + } + + return container.attachmentRepository +} + +// APIBaseURL returns the API base URL derived from EVENTS_QUEUE_ENDPOINT +func (container *Container) APIBaseURL() string { + endpoint := os.Getenv("EVENTS_QUEUE_ENDPOINT") + return strings.TrimSuffix(endpoint, "/v1/events") +} + +// AttachmentHandler creates a new AttachmentHandler +func (container *Container) AttachmentHandler() (handler *handlers.AttachmentHandler) { + container.logger.Debug(fmt.Sprintf("creating %T", handler)) + return handlers.NewAttachmentHandler( + container.Logger(), + container.Tracer(), + container.AttachmentRepository(), + ) +} + +// RegisterAttachmentRoutes registers routes for the /attachments prefix +func (container *Container) RegisterAttachmentRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.AttachmentHandler{})) + container.AttachmentHandler().RegisterRoutes(container.App()) +} + +// PhoneAPIKeyService creates a new instance of services.PhoneAPIKeyService +func (container *Container) PhoneAPIKeyService() (service *services.PhoneAPIKeyService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewPhoneAPIKeyService( + container.Logger(), + container.Tracer(), + container.PhoneRepository(), + container.PhoneAPIKeyRepository(), + ) +} + +// NotificationService creates a new instance of services.PhoneNotificationService +func (container *Container) NotificationService() (service *services.PhoneNotificationService) { + container.logger.Debug(fmt.Sprintf("creating %T", service)) + return services.NewNotificationService( + container.Logger(), + container.Tracer(), + container.PhoneNotificationClients(), + container.PhoneRepository(), + container.PhoneNotificationRepository(), + container.MessageSendScheduleRepository(), + container.EventDispatcher(), + ) +} + +// RegisterMessageRoutes registers routes for the /messages prefix +func (container *Container) RegisterMessageRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.MessageHandler{})) + container.MessageHandler().RegisterPhoneAPIKeyRoutes(container.App(), container.PhoneAPIKeyMiddleware(), container.AuthenticatedMiddleware()) + container.MessageHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterBulkMessageRoutes registers routes for the /bulk-messages prefix +func (container *Container) RegisterBulkMessageRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.BulkMessageHandler{})) + container.BulkMessageHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterMessageThreadRoutes registers routes for the /message-threads prefix +func (container *Container) RegisterMessageThreadRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.MessageThreadHandler{})) + container.MessageThreadHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterContactRoutes registers routes for the /contacts prefix +func (container *Container) RegisterContactRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.ContactHandler{})) + container.ContactHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterHeartbeatRoutes registers routes for the /heartbeats prefix +func (container *Container) RegisterHeartbeatRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.HeartbeatHandler{})) + container.HeartbeatHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) + container.HeartbeatHandler().RegisterPhoneAPIKeyRoutes(container.App(), container.PhoneAPIKeyMiddleware(), container.AuthenticatedMiddleware()) +} + +// RegisterBillingRoutes registers routes for the /billing prefix +func (container *Container) RegisterBillingRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.BillingHandler{})) + container.BillingHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterWebhookRoutes registers routes for the /webhooks prefix +func (container *Container) RegisterWebhookRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.WebhookHandler{})) + container.WebhookHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterPhoneRoutes registers routes for the /phone prefix +func (container *Container) RegisterPhoneRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.PhoneHandler{})) + container.PhoneHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) + container.PhoneHandler().RegisterPhoneAPIKeyRoutes(container.App(), container.PhoneAPIKeyMiddleware(), container.AuthenticatedMiddleware()) +} + +// RegisterUserRoutes registers routes for the /users prefix +func (container *Container) RegisterUserRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.UserHandler{})) + container.UserHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterMessageSendScheduleRoutes registers routes for the /send-schedules prefix +func (container *Container) RegisterMessageSendScheduleRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.MessageSendScheduleHandler{})) + container.MessageSendScheduleHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterEventRoutes registers routes for the /events prefix +func (container *Container) RegisterEventRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.EventsHandler{})) + container.EventsHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware()) +} + +// RegisterSwaggerRoutes registers routes for swagger +func (container *Container) RegisterSwaggerRoutes() { + container.logger.Debug(fmt.Sprintf("registering %T routes", swagger.HandlerDefault)) + container.App().Get("/*", swagger.New(swagger.Config{ + Title: docs.SwaggerInfo.Title, + CustomScript: ` + document.addEventListener("DOMContentLoaded", function(event) { + document.body.style.margin = '0'; + var links = document.querySelectorAll("link[rel~='icon']"); + links.forEach(function (link) { + link.href = 'https://httpsms.com/favicon.ico'; + }); + });`, + })) +} + +// HeartbeatRepository registers a new instance of repositories.HeartbeatRepository +func (container *Container) HeartbeatRepository() repositories.HeartbeatRepository { + switch os.Getenv("HEARTBEAT_DB_BACKEND") { + case "mongodb": + container.logger.Debug("creating MongoDB repositories.HeartbeatRepository") + return repositories.NewMongoHeartbeatRepository( + container.Logger(), + container.Tracer(), + container.MongoDB(), + ) + default: + container.logger.Debug("creating GORM repositories.HeartbeatRepository") + return repositories.NewGormHeartbeatRepository( + container.Logger(), + container.Tracer(), + container.DedicatedDB(), + ) + } +} + +// UserRepository registers a new instance of repositories.UserRepository +func (container *Container) UserRepository() repositories.UserRepository { + container.logger.Debug("creating GORM repositories.UserRepository") + return repositories.NewGormUserRepository( + container.Logger(), + container.Tracer(), + container.UserRistrettoCache(), + container.DB(), + ) +} + +// PhoneRistrettoCache creates an in-memory *ristretto.Cache[string, *entities.Phone] +func (container *Container) PhoneRistrettoCache() *ristretto.Cache[string, *entities.Phone] { + if container.phoneRistrettoCache != nil { + return container.phoneRistrettoCache + } + container.logger.Debug(fmt.Sprintf("creating %T", container.phoneRistrettoCache)) + ristrettoCache, err := ristretto.NewCache[string, *entities.Phone](&ristretto.Config[string, *entities.Phone]{ + MaxCost: 5000, + NumCounters: 5000 * 10, + BufferItems: 64, + }) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create phone ristretto cache")) + } + container.phoneRistrettoCache = ristrettoCache + return container.phoneRistrettoCache +} + +// ContactRistrettoCache creates an in-memory cache keyed by user and phone number. +func (container *Container) ContactRistrettoCache() *ristretto.Cache[string, services.ContactCacheEntry] { + if container.contactRistrettoCache != nil { + return container.contactRistrettoCache + } + container.logger.Debug(fmt.Sprintf("creating %T", container.contactRistrettoCache)) + ristrettoCache, err := ristretto.NewCache[string, services.ContactCacheEntry](&ristretto.Config[string, services.ContactCacheEntry]{ + MaxCost: 5000, + NumCounters: 5000 * 10, + BufferItems: 64, + }) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create contact ristretto cache")) + } + container.contactRistrettoCache = ristrettoCache + return container.contactRistrettoCache +} + +// UserRistrettoCache creates an in-memory *ristretto.Cache[string, entities.AuthContext] +func (container *Container) UserRistrettoCache() *ristretto.Cache[string, entities.AuthContext] { + if container.userRistrettoCache != nil { + return container.userRistrettoCache + } + container.logger.Debug(fmt.Sprintf("creating %T", container.userRistrettoCache)) + ristrettoCache, err := ristretto.NewCache[string, entities.AuthContext](&ristretto.Config[string, entities.AuthContext]{ + MaxCost: 5000, + NumCounters: 5000 * 10, + BufferItems: 64, + }) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create user ristretto cache")) + } + container.userRistrettoCache = ristrettoCache + return ristrettoCache +} + +// InitializeTraceProvider initializes the open telemetry trace provider +func (container *Container) InitializeTraceProvider() func() { + return container.initializeAxiomTraceProvider(container.version, container.projectID) +} + +func (container *Container) initializeGoogleTraceProvider(version string, namespace string) func() { + container.logger.Debug("initializing google trace meterProvider") + + traceExporter, err := cloudtrace.New(cloudtrace.WithProjectID(os.Getenv("GCP_PROJECT_ID"))) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create cloud trace traceExporter")) + } + + tp := trace.NewTracerProvider( + trace.WithSpanProcessor(telemetry.NewSamplingSpanProcessor(traceExporter)), + trace.WithSampler(trace.AlwaysSample()), + trace.WithResource(container.OtelResources(version, namespace)), + ) + otel.SetTracerProvider(tp) + + metricExporter, err := mexporter.New(mexporter.WithProjectID(os.Getenv("GCP_PROJECT_ID"))) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create cloud metric traceExporter")) + } + + meterProvider := metric.NewMeterProvider( + metric.WithReader(metric.NewPeriodicReader(metricExporter)), + metric.WithExemplarFilter(telemetry.SampledTraceExemplarFilter), + metric.WithResource(container.OtelResources(version, namespace)), + ) + otel.SetMeterProvider(meterProvider) + + return func() { + if err = metricExporter.Shutdown(context.Background()); err != nil { + container.logger.Error(stacktrace.Propagatef(err, "cannot shutdown cloud metric metric exporter")) + } + if err = traceExporter.Shutdown(context.Background()); err != nil { + container.logger.Error(stacktrace.Propagatef(err, "cannot shutdown cloud trace trace exporter")) + } + } +} + +func (container *Container) initializeAxiomTraceProvider(version string, namespace string) func() { + container.logger.Debug("initializing axiom trace provider") + + traceHeaders := map[string]string{ + "Authorization": "Bearer " + os.Getenv("AXIOM_TOKEN"), + "X-Axiom-Dataset": os.Getenv("AXIOM_DATASET_EVENTS"), + } + + traceExporter, err := otlptracehttp.New( + context.Background(), + otlptracehttp.WithEndpoint("us-east-1.aws.edge.axiom.co"), + otlptracehttp.WithHeaders(traceHeaders), + ) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create axiom OTLP trace exporter")) + } + + tp := trace.NewTracerProvider( + trace.WithSpanProcessor(telemetry.NewSamplingSpanProcessor(traceExporter)), + trace.WithSampler(trace.AlwaysSample()), + trace.WithResource(container.OtelResources(version, namespace)), + ) + otel.SetTracerProvider(tp) + + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( + propagation.TraceContext{}, + propagation.Baggage{}, + )) + + metricHeaders := map[string]string{ + "Authorization": "Bearer " + os.Getenv("AXIOM_TOKEN"), + "X-Axiom-Dataset": os.Getenv("AXIOM_DATASET_METRICS"), + } + + metricExporter, err := otlpmetrichttp.New( + context.Background(), + otlpmetrichttp.WithEndpoint("us-east-1.aws.edge.axiom.co"), + otlpmetrichttp.WithHeaders(metricHeaders), + ) + if err != nil { + container.logger.Fatal(stacktrace.Propagatef(err, "cannot create axiom OTLP metric exporter")) + } + + meterProvider := metric.NewMeterProvider( + metric.WithReader(metric.NewPeriodicReader(metricExporter)), + metric.WithExemplarFilter(telemetry.SampledTraceExemplarFilter), + metric.WithResource(container.OtelResources(version, namespace)), + ) + otel.SetMeterProvider(meterProvider) + + return func() { + if err := tp.Shutdown(context.Background()); err != nil { + container.logger.Error(stacktrace.Propagatef(err, "cannot shutdown axiom trace provider")) + } + if err := meterProvider.Shutdown(context.Background()); err != nil { + container.logger.Error(stacktrace.Propagatef(err, "cannot shutdown axiom meter provider")) + } + } +} + +func (container *Container) initializeUptraceProvider(version string, namespace string) (flush func()) { + container.logger.Debug("initializing uptrace provider") + // Configure OpenTelemetry with sensible defaults. + uptrace.ConfigureOpentelemetry( + uptrace.WithDSN(os.Getenv("UPTRACE_DSN")), + uptrace.WithServiceName(namespace), + uptrace.WithServiceVersion(version), + uptrace.WithDeploymentEnvironment(os.Getenv("ENV")), + ) + + // Send buffered spans and free resources. + return func() { + err := uptrace.Shutdown(context.Background()) + if err != nil { + container.logger.Error(err) + } + } +} + +func logger(skipFrameCount int) telemetry.Logger { + fields := map[string]string{ + string(semconv.ServiceInstanceIDKey): instanceID(), + string(semconv.DeploymentEnvironmentKey): os.Getenv("ENV"), + } + + return telemetry.NewZerologLogger( + os.Getenv("GCP_PROJECT_ID"), + fields, + logDriver(skipFrameCount), + nil, + ) +} + +func logDriver(skipFrameCount int) *zerodriver.Logger { + if isLocal() { + return consoleLogger(skipFrameCount) + } + return axiomLogger(skipFrameCount) +} + +func axiomLogger(skipFrameCount int) *zerodriver.Logger { + axiomWriter, err := axiomzerolog.New( + axiomzerolog.SetLevels([]zerolog.Level{zerolog.TraceLevel, zerolog.DebugLevel, zerolog.InfoLevel, zerolog.WarnLevel, zerolog.ErrorLevel, zerolog.PanicLevel, zerolog.FatalLevel, zerolog.NoLevel}), + axiomzerolog.SetDataset(os.Getenv("AXIOM_DATASET_EVENTS")), + ) + if err != nil { + log.Fatal(stacktrace.Propagatef(err, "cannot create axiom zerolog writer")) + } + + zl := zerolog.New(axiomWriter).With().Timestamp().CallerWithSkipFrameCount(skipFrameCount).Logger() + return &zerodriver.Logger{Logger: &zl} +} + +func instanceID() string { + h, err := os.Hostname() + if err != nil { + h = strconv.Itoa(os.Getpid()) + } + if metadata.OnGCE() { + return getGCEInstanceID(h) + } + return h +} + +func getGCEInstanceID(hostname string) string { + instanceID, err := metadata.InstanceIDWithContext(context.Background()) + if err != nil { + return hostname + } + return instanceID +} + +func consoleLogger(skipFrameCount int) *zerodriver.Logger { + l := zerolog.New( + zerolog.ConsoleWriter{ + Out: os.Stderr, + }, + ).With().Timestamp().CallerWithSkipFrameCount(skipFrameCount).Logger() + return &zerodriver.Logger{ + Logger: &l, + } +} + +func isLocal() bool { + return os.Getenv("ENV") == "local" +} diff --git a/api/pkg/di/container_test.go b/api/pkg/di/container_test.go new file mode 100644 index 0000000000000000000000000000000000000000..611708d31df9d7c1b1efedb632037d1c156d8506 --- /dev/null +++ b/api/pkg/di/container_test.go @@ -0,0 +1,36 @@ +package di + +import ( + "reflect" + "testing" + + "github.com/NdoleStudio/httpsms/pkg/entities" + "github.com/NdoleStudio/httpsms/pkg/services" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNotificationHTTPClientUsesOTelRoundTripperWithoutRetries(t *testing.T) { + t.Setenv("ENV", "local") + client := NewLiteContainer().NotificationHTTPClient() + + assert.Zero(t, client.Timeout) + assert.Equal(t, "*otelroundtripper.otelRoundTripper", reflect.TypeOf(client.Transport).String()) + assert.Nil(t, client.CheckRedirect) +} + +func TestPhoneNotificationClientsMapsConfiguredTransports(t *testing.T) { + t.Setenv("ENV", "local") + t.Setenv("FCM_ENDPOINT", "http://localhost") + + clients := NewLiteContainer().PhoneNotificationClients() + + require.Len(t, clients, 2) + assert.IsType(t, &services.EmulatorFCMClient{}, clients[entities.NotificationTransportFCM]) + httpSender, ok := clients[entities.NotificationTransportHTTP].(*services.HTTPNotificationSender) + require.True(t, ok) + client := reflect.ValueOf(httpSender).Elem().FieldByName("client").Elem() + transport := client.FieldByName("Transport").Elem() + + assert.Equal(t, "*otelroundtripper.otelRoundTripper", transport.Type().String()) +} diff --git a/api/pkg/discord/application.go b/api/pkg/discord/application.go new file mode 100644 index 0000000000000000000000000000000000000000..c6fae57c80377bbd36b6ef50568fee35343d6fdf --- /dev/null +++ b/api/pkg/discord/application.go @@ -0,0 +1,43 @@ +package discord + +// CommandCreateRequest is the request for creating a new command +type CommandCreateRequest struct { + Name string `json:"name"` + Type int `json:"type"` + Description string `json:"description"` + Options []CommandCreateRequestOption `json:"options"` +} + +// CommandCreateRequestOption are options for creating a command +type CommandCreateRequestOption struct { + Name string `json:"name"` + Description string `json:"description"` + Type int `json:"type"` + Required bool `json:"required"` +} + +// CommandCreateResponse is the response after creating a command +type CommandCreateResponse struct { + ID string `json:"id"` + ApplicationID string `json:"application_id"` + Version string `json:"version"` + DefaultMemberPermissions any `json:"default_member_permissions"` + Type int `json:"type"` + Name string `json:"name"` + NameLocalizations any `json:"name_localizations"` + Description string `json:"description"` + DescriptionLocalizations any `json:"description_localizations"` + GuildID string `json:"guild_id"` + Options []CommandCreateResponseOption `json:"options"` + Nsfw bool `json:"nsfw"` +} + +// CommandCreateResponseOption are options after creating a command +type CommandCreateResponseOption struct { + Type int `json:"type"` + Name string `json:"name"` + NameLocalizations any `json:"name_localizations"` + Description string `json:"description"` + DescriptionLocalizations any `json:"description_localizations"` + Required bool `json:"required"` +} diff --git a/api/pkg/discord/application_service.go b/api/pkg/discord/application_service.go new file mode 100644 index 0000000000000000000000000000000000000000..33368d151ef3575ae82542d670b8b26fa149b653 --- /dev/null +++ b/api/pkg/discord/application_service.go @@ -0,0 +1,34 @@ +package discord + +import ( + "context" + "encoding/json" + "fmt" + "net/http" +) + +// ApplicationService is the API client for the interacting with commands +type ApplicationService service + +// CreateCommand creates a new guild command +// +// API Docs: https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command +func (service *ApplicationService) CreateCommand(ctx context.Context, serverID string, params *CommandCreateRequest) (*CommandCreateResponse, *Response, error) { + url := fmt.Sprintf("/applications/%s/guilds/%s/commands", service.client.applicationID, serverID) + request, err := service.client.newRequest(ctx, http.MethodPost, url, params) + if err != nil { + return nil, nil, err + } + + response, err := service.client.do(request) + if err != nil { + return nil, response, err + } + + message := new(CommandCreateResponse) + if err = json.Unmarshal(*response.Body, message); err != nil { + return nil, response, err + } + + return message, response, nil +} diff --git a/api/pkg/discord/channel_service.go b/api/pkg/discord/channel_service.go new file mode 100644 index 0000000000000000000000000000000000000000..9df0ff2510a5962e4035b244e14b679704ee3643 --- /dev/null +++ b/api/pkg/discord/channel_service.go @@ -0,0 +1,55 @@ +package discord + +import ( + "context" + "encoding/json" + "fmt" + "net/http" +) + +// ChannelService is the API client for interacting with channels +type ChannelService service + +// CreateMessage sends a message to a guild text or DM channel. +// +// API Docs: https://discord.com/developers/docs/resources/channel#create-message +func (service *ChannelService) CreateMessage(ctx context.Context, channelID string, payload map[string]any) (map[string]any, *Response, error) { + request, err := service.client.newRequest(ctx, http.MethodPost, fmt.Sprintf("/channels/%s/messages", channelID), payload) + if err != nil { + return nil, nil, err + } + + response, err := service.client.do(request) + if err != nil { + return nil, response, err + } + + message := map[string]any{} + if err = json.Unmarshal(*response.Body, &message); err != nil { + return nil, response, err + } + + return message, response, nil +} + +// Get a channel by ID +// +// API Docs: https://discord.com/developers/docs/resources/channel#get-channel +func (service *ChannelService) Get(ctx context.Context, channelID string) (map[string]any, *Response, error) { + request, err := service.client.newRequest(ctx, http.MethodGet, fmt.Sprintf("/channels/%s", channelID), nil) + if err != nil { + return nil, nil, err + } + + response, err := service.client.do(request) + if err != nil { + return nil, response, err + } + + channel := map[string]any{} + if err = json.Unmarshal(*response.Body, &channel); err != nil { + return nil, response, err + } + + return channel, response, nil +} diff --git a/api/pkg/discord/client.go b/api/pkg/discord/client.go new file mode 100644 index 0000000000000000000000000000000000000000..8aa13fd7cb6db57b2a5ffe7418e7d813e2443918 --- /dev/null +++ b/api/pkg/discord/client.go @@ -0,0 +1,123 @@ +package discord + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" +) + +type service struct { + client *Client +} + +// Client is the campay API client. +// Do not instantiate this client with Client{}. Use the New method instead. +type Client struct { + httpClient *http.Client + common service + baseURL string + applicationID string + botToken string + + Channel *ChannelService + Guild *GuildService + Application *ApplicationService +} + +// New creates and returns a new campay.Client from a slice of campay.ClientOption. +func New(options ...Option) *Client { + config := defaultClientConfig() + + for _, option := range options { + option.apply(config) + } + + client := &Client{ + httpClient: config.httpClient, + botToken: config.botToken, + baseURL: config.baseURL, + applicationID: config.applicationID, + } + + client.common.client = client + + client.Channel = (*ChannelService)(&client.common) + client.Application = (*ApplicationService)(&client.common) + client.Guild = (*GuildService)(&client.common) + + return client +} + +// newRequest creates an API request. A relative URL can be provided in uri, +// in which case it is resolved relative to the BaseURL of the Client. +// URI's should always be specified without a preceding slash. +func (client *Client) newRequest(ctx context.Context, method, uri string, body any) (*http.Request, error) { + var buf io.ReadWriter + if body != nil { + buf = &bytes.Buffer{} + enc := json.NewEncoder(buf) + enc.SetEscapeHTML(false) + err := enc.Encode(body) + if err != nil { + return nil, err + } + } + + req, err := http.NewRequestWithContext(ctx, method, client.baseURL+uri, buf) + if err != nil { + return nil, err + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + req.Header.Set("Authorization", "Bot "+client.botToken) + + return req, nil +} + +// do carries out an HTTP request and returns a Response +func (client *Client) do(req *http.Request) (*Response, error) { + if req == nil { + return nil, fmt.Errorf("%T cannot be nil", req) + } + + httpResponse, err := client.httpClient.Do(req) + if err != nil { + return nil, err + } + + defer func() { _ = httpResponse.Body.Close() }() + + resp, err := client.newResponse(httpResponse) + if err != nil { + return resp, err + } + + _, err = io.Copy(io.Discard, httpResponse.Body) + if err != nil { + return resp, err + } + + return resp, nil +} + +// newResponse converts an *http.Response to *Response +func (client *Client) newResponse(httpResponse *http.Response) (*Response, error) { + if httpResponse == nil { + return nil, fmt.Errorf("%T cannot be nil", httpResponse) + } + + resp := new(Response) + resp.HTTPResponse = httpResponse + + buf, err := io.ReadAll(resp.HTTPResponse.Body) + if err != nil { + return nil, err + } + resp.Body = &buf + + return resp, resp.Error() +} diff --git a/api/pkg/discord/client_config.go b/api/pkg/discord/client_config.go new file mode 100644 index 0000000000000000000000000000000000000000..736e03f611bcfad931cbed64594056db30ca161a --- /dev/null +++ b/api/pkg/discord/client_config.go @@ -0,0 +1,19 @@ +package discord + +import "net/http" + +type clientConfig struct { + httpClient *http.Client + botToken string + applicationID string + baseURL string +} + +func defaultClientConfig() *clientConfig { + return &clientConfig{ + httpClient: http.DefaultClient, + botToken: "", + applicationID: "", + baseURL: "https://discord.com/api", + } +} diff --git a/api/pkg/discord/client_option.go b/api/pkg/discord/client_option.go new file mode 100644 index 0000000000000000000000000000000000000000..6f2008d405b526edc0d21b75c7b2aa7b3d4a437e --- /dev/null +++ b/api/pkg/discord/client_option.go @@ -0,0 +1,50 @@ +package discord + +import ( + "net/http" + "strings" +) + +// Option is options for constructing a client +type Option interface { + apply(config *clientConfig) +} + +type clientOptionFunc func(config *clientConfig) + +func (fn clientOptionFunc) apply(config *clientConfig) { + fn(config) +} + +// WithHTTPClient sets the underlying HTTP client used for API requests. +// By default, http.DefaultClient is used. +func WithHTTPClient(httpClient *http.Client) Option { + return clientOptionFunc(func(config *clientConfig) { + if httpClient != nil { + config.httpClient = httpClient + } + }) +} + +// WithBaseURL set's the base url for the discord API +func WithBaseURL(baseURL string) Option { + return clientOptionFunc(func(config *clientConfig) { + if baseURL != "" { + config.baseURL = strings.TrimRight(baseURL, "/") + } + }) +} + +// WithApplicationID sets the discord bot application ID +func WithApplicationID(applicationID string) Option { + return clientOptionFunc(func(config *clientConfig) { + config.applicationID = applicationID + }) +} + +// WithBotToken sets the discord bot token +func WithBotToken(botToken string) Option { + return clientOptionFunc(func(config *clientConfig) { + config.botToken = botToken + }) +} diff --git a/api/pkg/discord/client_option_test.go b/api/pkg/discord/client_option_test.go new file mode 100644 index 0000000000000000000000000000000000000000..bd48d3b150ff5202b4d518e27bb46d5f6609f06b --- /dev/null +++ b/api/pkg/discord/client_option_test.go @@ -0,0 +1,72 @@ +package discord + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestWithHTTPClient(t *testing.T) { + t.Run("httpClient is not set when the httpClient is nil", func(t *testing.T) { + // Setup + t.Parallel() + + // Arrange + config := defaultClientConfig() + + // Act + WithHTTPClient(nil).apply(config) + + // Assert + assert.NotNil(t, config.httpClient) + }) + + t.Run("httpClient is set when the httpClient is not nil", func(t *testing.T) { + // Setup + t.Parallel() + + // Arrange + config := defaultClientConfig() + newClient := &http.Client{Timeout: 300} + + // Act + WithHTTPClient(newClient).apply(config) + + // Assert + assert.NotNil(t, config.httpClient) + assert.Equal(t, newClient.Timeout, config.httpClient.Timeout) + }) +} + +func TestWithBaseURL(t *testing.T) { + t.Run("baseURL is set successfully", func(t *testing.T) { + // Setup + t.Parallel() + + // Arrange + baseURL := "https://example.com" + config := defaultClientConfig() + + // Act + WithBaseURL(baseURL).apply(config) + + // Assert + assert.Equal(t, config.baseURL, config.baseURL) + }) + + t.Run("tailing / is trimmed from baseURL", func(t *testing.T) { + // Setup + t.Parallel() + + // Arrange + baseURL := "https://example.com/" + config := defaultClientConfig() + + // Act + WithBaseURL(baseURL).apply(config) + + // Assert + assert.Equal(t, "https://example.com", config.baseURL) + }) +} diff --git a/api/pkg/discord/guild_service.go b/api/pkg/discord/guild_service.go new file mode 100644 index 0000000000000000000000000000000000000000..25f8421df70e03f4c85980ea98ff327adbb3053c --- /dev/null +++ b/api/pkg/discord/guild_service.go @@ -0,0 +1,33 @@ +package discord + +import ( + "context" + "encoding/json" + "fmt" + "net/http" +) + +// GuildService is the API client for interacting with guilds +type GuildService service + +// Get the guild object for the given id. +// +// API Docs: https://discord.com/developers/docs/resources/guild#get-guild +func (service *GuildService) Get(ctx context.Context, guildID string) (*map[string]any, *Response, error) { + request, err := service.client.newRequest(ctx, http.MethodGet, fmt.Sprintf("/guilds/%s", guildID), nil) + if err != nil { + return nil, nil, err + } + + response, err := service.client.do(request) + if err != nil { + return nil, response, err + } + + channel := new(map[string]any) + if err = json.Unmarshal(*response.Body, channel); err != nil { + return nil, response, err + } + + return channel, response, nil +} diff --git a/api/pkg/discord/response.go b/api/pkg/discord/response.go new file mode 100644 index 0000000000000000000000000000000000000000..6143867f1dcef80da23effe227c1fd7b0b9a0201 --- /dev/null +++ b/api/pkg/discord/response.go @@ -0,0 +1,35 @@ +package discord + +import ( + "bytes" + "errors" + "net/http" + "strconv" +) + +// Response captures the http response +type Response struct { + HTTPResponse *http.Response + Body *[]byte +} + +// Error ensures that the response can be decoded into a string inc ase it's an error response +func (r *Response) Error() error { + switch r.HTTPResponse.StatusCode { + case 200, 201, 202, 204, 205: + return nil + default: + return errors.New(r.errorMessage()) + } +} + +func (r *Response) errorMessage() string { + var buf bytes.Buffer + buf.WriteString(strconv.Itoa(r.HTTPResponse.StatusCode)) + buf.WriteString(": ") + buf.WriteString(http.StatusText(r.HTTPResponse.StatusCode)) + buf.WriteString(", Body: ") + buf.Write(*r.Body) + + return buf.String() +} diff --git a/api/pkg/emails/event_payload_formatter.go b/api/pkg/emails/event_payload_formatter.go new file mode 100644 index 0000000000000000000000000000000000000000..0a863854045d185a16792be9d3c7479db4df519c --- /dev/null +++ b/api/pkg/emails/event_payload_formatter.go @@ -0,0 +1,128 @@ +package emails + +import ( + "bytes" + "encoding/json" + "html" + "html/template" + "strings" +) + +const ( + eventPayloadCodeBlockStyle = "margin:0;padding:12px;border:1px solid #D0D7DE;border-radius:6px;background:#F6F8FA;color:#24292F;font-family:Consolas,Monaco,'Courier New',monospace;font-size:13px;line-height:1.5;white-space:pre-wrap;word-break:break-word;overflow-wrap:anywhere;" + jsonKeyStyle = "color:#0550AE;font-weight:600;" + jsonStringStyle = "color:#0A3069;" + jsonNumberStyle = "color:#953800;" + jsonLiteralStyle = "color:#8250DF;" +) + +func formatEventPayload(payload string) (string, template.HTML) { + formattedPayload, isJSON := indentEventPayloadJSON(payload) + content := html.EscapeString(formattedPayload) + if isJSON { + content = highlightEventPayloadJSON(formattedPayload) + } + + // #nosec G203 -- every dynamic payload token is escaped before the static wrapper is added. + richPayload := template.HTML(`
` + content + `
`) + return formattedPayload, richPayload +} + +func indentEventPayloadJSON(payload string) (string, bool) { + var formatted bytes.Buffer + if err := json.Indent(&formatted, []byte(payload), "", " "); err != nil { + return payload, false + } + + return formatted.String(), true +} + +func highlightEventPayloadJSON(payload string) string { + var highlighted strings.Builder + highlighted.Grow(len(payload)) + + for index := 0; index < len(payload); { + switch { + case payload[index] == '"': + end := eventPayloadJSONStringEnd(payload, index) + style := jsonStringStyle + if eventPayloadNextNonSpace(payload, end) == ':' { + style = jsonKeyStyle + } + writeEventPayloadToken(&highlighted, style, payload[index:end]) + index = end + case payload[index] == '-' || isEventPayloadDigit(payload[index]): + end := index + 1 + // json.Indent already validated this as JSON, so this continuation set only sees JSON number bytes. + for end < len(payload) && isEventPayloadNumberCharacter(payload[end]) { + end++ + } + writeEventPayloadToken(&highlighted, jsonNumberStyle, payload[index:end]) + index = end + case strings.HasPrefix(payload[index:], "true"): + writeEventPayloadToken(&highlighted, jsonLiteralStyle, "true") + index += len("true") + case strings.HasPrefix(payload[index:], "false"): + writeEventPayloadToken(&highlighted, jsonLiteralStyle, "false") + index += len("false") + case strings.HasPrefix(payload[index:], "null"): + writeEventPayloadToken(&highlighted, jsonLiteralStyle, "null") + index += len("null") + default: + highlighted.WriteString(html.EscapeString(payload[index : index+1])) + index++ + } + } + + return highlighted.String() +} + +func eventPayloadJSONStringEnd(payload string, start int) int { + escaped := false + for index := start + 1; index < len(payload); index++ { + switch { + case escaped: + escaped = false + case payload[index] == '\\': + escaped = true + case payload[index] == '"': + return index + 1 + } + } + + return len(payload) +} + +func eventPayloadNextNonSpace(payload string, start int) byte { + for index := start; index < len(payload); index++ { + switch payload[index] { + case ' ', '\n', '\r', '\t': + continue + default: + return payload[index] + } + } + + return 0 +} + +func isEventPayloadDigit(value byte) bool { + return value >= '0' && value <= '9' +} + +func isEventPayloadNumberCharacter(value byte) bool { + return isEventPayloadDigit(value) || + value == '-' || + value == '+' || + value == '.' || + value == 'e' || + value == 'E' +} + +func writeEventPayloadToken(builder *strings.Builder, style string, token string) { + builder.WriteString(``) + builder.WriteString(html.EscapeString(token)) + builder.WriteString(``) +} diff --git a/api/pkg/emails/event_payload_formatter_test.go b/api/pkg/emails/event_payload_formatter_test.go new file mode 100644 index 0000000000000000000000000000000000000000..9617ebb0ea0a2bb4b873fcaa81fcebbbf82e4915 --- /dev/null +++ b/api/pkg/emails/event_payload_formatter_test.go @@ -0,0 +1,113 @@ +package emails + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestFormatEventPayloadIndentsAndHighlightsJSON(t *testing.T) { + payload := `{"message":"hello","count":2,"ratio":1.5,"enabled":true,"disabled":false,"missing":null,"nested":{"value":"ok"}}` + + plain, rich := formatEventPayload(payload) + html := string(rich) + + assert.Equal(t, `{ + "message": "hello", + "count": 2, + "ratio": 1.5, + "enabled": true, + "disabled": false, + "missing": null, + "nested": { + "value": "ok" + } +}`, plain) + assert.Contains(t, html, `"message"`) + assert.Contains(t, html, `"hello"`) + assert.Contains(t, html, `2`) + assert.Contains(t, html, `1.5`) + assert.Contains(t, html, `true`) + assert.Contains(t, html, `false`) + assert.Contains(t, html, `null`) + assert.Contains(t, html, `white-space:pre-wrap`) +} + +func TestFormatEventPayloadEscapesPayloadHTML(t *testing.T) { + plain, rich := formatEventPayload(`{"message":"&"}`) + html := string(rich) + + assert.Contains(t, plain, ` + + diff --git a/web/app/components/BackButton.vue b/web/app/components/BackButton.vue new file mode 100644 index 0000000000000000000000000000000000000000..94ca0f625aa3940f3c4fdc44f4864e43af006fd2 --- /dev/null +++ b/web/app/components/BackButton.vue @@ -0,0 +1,43 @@ + + + diff --git a/web/app/components/BillingDateOrdinal.vue b/web/app/components/BillingDateOrdinal.vue new file mode 100644 index 0000000000000000000000000000000000000000..05efadec915ce73dd58eeec06bb153e296d21c1f --- /dev/null +++ b/web/app/components/BillingDateOrdinal.vue @@ -0,0 +1,15 @@ + + + diff --git a/web/app/components/BlogAuthorBio.vue b/web/app/components/BlogAuthorBio.vue new file mode 100644 index 0000000000000000000000000000000000000000..0051e4d66a33b317e93283736553e20c7bd3e867 --- /dev/null +++ b/web/app/components/BlogAuthorBio.vue @@ -0,0 +1,24 @@ + + + diff --git a/web/app/components/BlogInfo.vue b/web/app/components/BlogInfo.vue new file mode 100644 index 0000000000000000000000000000000000000000..d1eac607a51738cea13417f2e3a721d3fedb73ef --- /dev/null +++ b/web/app/components/BlogInfo.vue @@ -0,0 +1,14 @@ + + + diff --git a/web/app/components/BlogSidebar.vue b/web/app/components/BlogSidebar.vue new file mode 100644 index 0000000000000000000000000000000000000000..81111cac1c417a92407b16e6f1a3f2ed33e776f6 --- /dev/null +++ b/web/app/components/BlogSidebar.vue @@ -0,0 +1,30 @@ + + + diff --git a/web/app/components/ContactDialog.vue b/web/app/components/ContactDialog.vue new file mode 100644 index 0000000000000000000000000000000000000000..65e5595212891c60ab8ad8962765617b967f3575 --- /dev/null +++ b/web/app/components/ContactDialog.vue @@ -0,0 +1,411 @@ + + + diff --git a/web/app/components/CopyButton.vue b/web/app/components/CopyButton.vue new file mode 100644 index 0000000000000000000000000000000000000000..ca3c30c21ad54bb70123bd0ff43396be621972e6 --- /dev/null +++ b/web/app/components/CopyButton.vue @@ -0,0 +1,52 @@ + + + diff --git a/web/app/components/FirebaseAuth.vue b/web/app/components/FirebaseAuth.vue new file mode 100644 index 0000000000000000000000000000000000000000..659b426aa59458596b64bb490a5a32a227dcd261 --- /dev/null +++ b/web/app/components/FirebaseAuth.vue @@ -0,0 +1,533 @@ + + + + + diff --git a/web/app/components/FixedHeader.vue b/web/app/components/FixedHeader.vue new file mode 100644 index 0000000000000000000000000000000000000000..b1311f23cca1794098515556add3556fc70508a1 --- /dev/null +++ b/web/app/components/FixedHeader.vue @@ -0,0 +1,34 @@ + + + diff --git a/web/app/components/LoadingButton.vue b/web/app/components/LoadingButton.vue new file mode 100644 index 0000000000000000000000000000000000000000..3b67d9875f4aeeedc5fec2ea9fe94078a28eb383 --- /dev/null +++ b/web/app/components/LoadingButton.vue @@ -0,0 +1,77 @@ + + + diff --git a/web/app/components/LoadingDashboard.vue b/web/app/components/LoadingDashboard.vue new file mode 100644 index 0000000000000000000000000000000000000000..93997aeecea432bb51bdb7b813cddf995abb75ff --- /dev/null +++ b/web/app/components/LoadingDashboard.vue @@ -0,0 +1,36 @@ + + + diff --git a/web/app/components/MessageThread.vue b/web/app/components/MessageThread.vue new file mode 100644 index 0000000000000000000000000000000000000000..b0a01dd0c3f7eb5898c46cb95dfcbdc3aadc0f9b --- /dev/null +++ b/web/app/components/MessageThread.vue @@ -0,0 +1,275 @@ + + + diff --git a/web/app/components/MessageThreadHeader.vue b/web/app/components/MessageThreadHeader.vue new file mode 100644 index 0000000000000000000000000000000000000000..e1a8a318b0a6d3ca58a50ec803c38aa196f3c948 --- /dev/null +++ b/web/app/components/MessageThreadHeader.vue @@ -0,0 +1,276 @@ + + + diff --git a/web/app/components/NuxtLogo.vue b/web/app/components/NuxtLogo.vue new file mode 100644 index 0000000000000000000000000000000000000000..66daa93fe9804f6eeccc4c2dd3c78eeec59bf9a2 --- /dev/null +++ b/web/app/components/NuxtLogo.vue @@ -0,0 +1,3 @@ + diff --git a/web/app/components/RedirectPromptPopover.vue b/web/app/components/RedirectPromptPopover.vue new file mode 100644 index 0000000000000000000000000000000000000000..c2de182004343686f649507c4ee7f9725d1f75dd --- /dev/null +++ b/web/app/components/RedirectPromptPopover.vue @@ -0,0 +1,58 @@ + + + diff --git a/web/app/composables/useApi.ts b/web/app/composables/useApi.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c6e9a836187876d1b097e22a8558337806a8ed5 --- /dev/null +++ b/web/app/composables/useApi.ts @@ -0,0 +1,43 @@ +let authToken: string | null = null +let apiKey: string | null = null + +export function setAuthHeader(token: string | null) { + authToken = token +} + +export function setApiKey(key: string | null) { + apiKey = key +} + +function createApiFetch() { + const config = useRuntimeConfig() + const publicConfig = config.public as Record + const baseURL = publicConfig.apiBaseUrl + + return $fetch.create({ + baseURL, + headers: { + 'X-Client-Version': publicConfig.clientVersion || 'dev', + }, + onRequest({ options }) { + const headers = new Headers(options.headers) + if (authToken) { + headers.set('Authorization', `Bearer ${authToken}`) + } + if (apiKey) { + headers.set('x-api-key', apiKey) + } + options.headers = headers + }, + }) +} + +export function useApi() { + return { apiFetch: createApiFetch(), setAuthHeader, setApiKey } +} + +export function useApiComposable() { + return { + useApi: createApiFetch, + } +} diff --git a/web/app/composables/useFilters.ts b/web/app/composables/useFilters.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b54bbb43b7ed117e90c4e455c95c49075ff67e7 --- /dev/null +++ b/web/app/composables/useFilters.ts @@ -0,0 +1,29 @@ +import { + formatPhoneNumber, + phoneCountry, + formatTimestamp, + formatMoney, + formatDecimal, + formatBillingPeriod, + formatBillingPeriodDateOrdinal, + humanizeTime, + humanizeTimeShort, + startsWithLetter, +} from '../utils/filters' +import { capitalize } from '../utils/capitalize' + +export function useFilters() { + return { + formatPhoneNumber, + phoneCountry, + formatTimestamp, + formatMoney, + formatDecimal, + formatBillingPeriod, + humanizeTimeShort, + formatBillingPeriodDateOrdinal, + humanizeTime, + startsWithLetter, + capitalize, + } +} diff --git a/web/app/layouts/blank.vue b/web/app/layouts/blank.vue new file mode 100644 index 0000000000000000000000000000000000000000..a9edc5c6b733fb80fc26b6ca134044eadf693d9f --- /dev/null +++ b/web/app/layouts/blank.vue @@ -0,0 +1,7 @@ + diff --git a/web/app/layouts/default.vue b/web/app/layouts/default.vue new file mode 100644 index 0000000000000000000000000000000000000000..12f3dfc52b02ee26272f4573933665fca58f250b --- /dev/null +++ b/web/app/layouts/default.vue @@ -0,0 +1,127 @@ + + + + + diff --git a/web/app/layouts/error.vue b/web/app/layouts/error.vue new file mode 100644 index 0000000000000000000000000000000000000000..c9b50eb2d211b88e1941eb30bf0b275e5c13b9bc --- /dev/null +++ b/web/app/layouts/error.vue @@ -0,0 +1,20 @@ + + + diff --git a/web/app/layouts/website.vue b/web/app/layouts/website.vue new file mode 100644 index 0000000000000000000000000000000000000000..3b6565a5aaed32c831f769d92d18205f93c354ff --- /dev/null +++ b/web/app/layouts/website.vue @@ -0,0 +1,319 @@ + + + + + diff --git a/web/app/middleware/auth.ts b/web/app/middleware/auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..33c9c9e2c7e7589a5d6891660cebaf491be8620d --- /dev/null +++ b/web/app/middleware/auth.ts @@ -0,0 +1,24 @@ +import { useAuthStore } from '../stores/auth' + +export default defineNuxtRouteMiddleware(async (to: { path: string }) => { + const authStore = useAuthStore() + + if (!authStore.authStateChanged) { + await new Promise((resolve) => { + const stop = watch( + () => authStore.authStateChanged, + (changed) => { + if (changed) { + stop() + resolve() + } + }, + { immediate: true }, + ) + }) + } + + if (authStore.authUser === null) { + return navigateTo({ path: '/login', query: { to: to.path } }) + } +}) diff --git a/web/app/middleware/guest.ts b/web/app/middleware/guest.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1c4cc80956c2b00b25e24610a0cec16fbcd9d3d --- /dev/null +++ b/web/app/middleware/guest.ts @@ -0,0 +1,22 @@ +export default defineNuxtRouteMiddleware(async () => { + const authStore = useAuthStore() + + if (!authStore.authStateChanged) { + await new Promise((resolve) => { + const stop = watch( + () => authStore.authStateChanged, + (changed) => { + if (changed) { + stop() + resolve() + } + }, + { immediate: true }, + ) + }) + } + + if (authStore.authUser !== null) { + return navigateTo('/threads') + } +}) diff --git a/web/app/middleware/redirectToThreads.ts b/web/app/middleware/redirectToThreads.ts new file mode 100644 index 0000000000000000000000000000000000000000..a605286fb31df5f5003f8bc583516f2ed664ada2 --- /dev/null +++ b/web/app/middleware/redirectToThreads.ts @@ -0,0 +1,11 @@ +import { STORAGE_KEY } from '~/stores/redirectPreference' + +export default defineNuxtRouteMiddleware(() => { + try { + if (localStorage.getItem(STORAGE_KEY) === 'true') { + return navigateTo('/threads', { replace: true }) + } + } catch (error) { + console.error(error) + } +}) diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..8a22aed2374c8f8f4d351554a65e46743f44e220 --- /dev/null +++ b/web/app/pages/billing/index.vue @@ -0,0 +1,801 @@ + + + diff --git a/web/app/pages/blog/end-to-end-encryption-to-sms-messages.vue b/web/app/pages/blog/end-to-end-encryption-to-sms-messages.vue new file mode 100644 index 0000000000000000000000000000000000000000..bda47bca9eaee1a61efd34bc67498f4ff222ac37 --- /dev/null +++ b/web/app/pages/blog/end-to-end-encryption-to-sms-messages.vue @@ -0,0 +1,317 @@ + + + diff --git a/web/app/pages/blog/forward-incoming-sms-from-phone-to-webhook.vue b/web/app/pages/blog/forward-incoming-sms-from-phone-to-webhook.vue new file mode 100644 index 0000000000000000000000000000000000000000..dd0306b6dc079e77d3081a5fb121bf9a529d3714 --- /dev/null +++ b/web/app/pages/blog/forward-incoming-sms-from-phone-to-webhook.vue @@ -0,0 +1,126 @@ + + + diff --git a/web/app/pages/blog/grant-send-and-read-sms-permissions-on-android.vue b/web/app/pages/blog/grant-send-and-read-sms-permissions-on-android.vue new file mode 100644 index 0000000000000000000000000000000000000000..e953aaca20a13e44ebf6b51a76cf8c4dd9fdea4d --- /dev/null +++ b/web/app/pages/blog/grant-send-and-read-sms-permissions-on-android.vue @@ -0,0 +1,113 @@ + + + diff --git a/web/app/pages/blog/how-to-send-sms-messages-from-excel.vue b/web/app/pages/blog/how-to-send-sms-messages-from-excel.vue new file mode 100644 index 0000000000000000000000000000000000000000..f55f922a52ff4c2a0e44301edb8746c67134c6d7 --- /dev/null +++ b/web/app/pages/blog/how-to-send-sms-messages-from-excel.vue @@ -0,0 +1,156 @@ + + + diff --git a/web/app/pages/blog/index.vue b/web/app/pages/blog/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..ec1a620c01c3713551f26e5ee168b71baeee4a0e --- /dev/null +++ b/web/app/pages/blog/index.vue @@ -0,0 +1,209 @@ + + + + + diff --git a/web/app/pages/blog/send-bulk-sms-from-csv-file-with-no-code.vue b/web/app/pages/blog/send-bulk-sms-from-csv-file-with-no-code.vue new file mode 100644 index 0000000000000000000000000000000000000000..9166d40efc3a5a5db91bf48a447b0c2d0c3a417a --- /dev/null +++ b/web/app/pages/blog/send-bulk-sms-from-csv-file-with-no-code.vue @@ -0,0 +1,166 @@ + + + diff --git a/web/app/pages/blog/send-sms-from-android-phone-with-python.vue b/web/app/pages/blog/send-sms-from-android-phone-with-python.vue new file mode 100644 index 0000000000000000000000000000000000000000..400f9caaae60388513dbefab25eabb9d374f7646 --- /dev/null +++ b/web/app/pages/blog/send-sms-from-android-phone-with-python.vue @@ -0,0 +1,182 @@ + + + diff --git a/web/app/pages/blog/send-sms-when-new-row-is-added-to-google-sheets-using-zapier.vue b/web/app/pages/blog/send-sms-when-new-row-is-added-to-google-sheets-using-zapier.vue new file mode 100644 index 0000000000000000000000000000000000000000..e8a3d9b1dbb9cda8c52f3fef40360762f44dc02d --- /dev/null +++ b/web/app/pages/blog/send-sms-when-new-row-is-added-to-google-sheets-using-zapier.vue @@ -0,0 +1,172 @@ + + + diff --git a/web/app/pages/bulk-messages/index.vue b/web/app/pages/bulk-messages/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..cc3bf02dd1727b6f6a85222148acb9dcda98aae2 --- /dev/null +++ b/web/app/pages/bulk-messages/index.vue @@ -0,0 +1,273 @@ + + + + + diff --git a/web/app/pages/contacts/index.vue b/web/app/pages/contacts/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..a44865ff5ebc383f54f24a16dd42755e3aa09aa5 --- /dev/null +++ b/web/app/pages/contacts/index.vue @@ -0,0 +1,535 @@ + + + diff --git a/web/app/pages/heartbeats/[id].vue b/web/app/pages/heartbeats/[id].vue new file mode 100644 index 0000000000000000000000000000000000000000..3ef5d212c2d58bd103cc25887200969666ad0202 --- /dev/null +++ b/web/app/pages/heartbeats/[id].vue @@ -0,0 +1,251 @@ + + + + + diff --git a/web/app/pages/index.vue b/web/app/pages/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..b0077847a4005d29aa9967e432a07268f9b26d61 --- /dev/null +++ b/web/app/pages/index.vue @@ -0,0 +1,1189 @@ + + +