Compare commits
50
Commits
0b5416df45
...
prod
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85977cb7af | ||
|
|
742b88183b | ||
|
|
2032837aad | ||
|
|
21640ffd9e | ||
|
|
7f761a0f0e | ||
|
|
30b26340a0 | ||
|
|
7272d0f1f3 | ||
|
|
b53cadcd8c | ||
|
|
a097cf4311 | ||
|
|
e004ea696b | ||
|
|
0bd5c39080 | ||
|
|
b77dafdb26 | ||
|
|
86d5dc5503 | ||
|
|
bf7fb937d2 | ||
|
|
0ba80abb47 | ||
|
|
a8ce5490c8 | ||
|
|
ae9b1b31a9 | ||
|
|
786696bb1e | ||
|
|
0791998c13 | ||
|
|
fef1605848 | ||
|
|
50875c0006 | ||
|
|
0e01f88f31 | ||
|
|
1e95459671 | ||
|
|
afa113ceca | ||
|
|
b0b0347b04 | ||
|
|
d2a24ca42d | ||
|
|
7d961fd70b | ||
|
|
a75712a60a | ||
|
|
90fd87ab4a | ||
|
|
e08b6121a2 | ||
|
|
e5cfbd6cdd | ||
|
|
85337f2c79 | ||
|
|
a937b6f0ff | ||
|
|
24f9024d24 | ||
|
|
163612e527 | ||
|
|
3cfbe439dd | ||
|
|
dbbe41a41e | ||
|
|
3c58a52725 | ||
|
|
d79df2cf76 | ||
|
|
13cc1e6e7b | ||
|
|
ce3d3804a7 | ||
|
|
450174c273 | ||
|
|
269e3167e2 | ||
|
|
e789e5a981 | ||
|
|
1f177f859e | ||
|
|
4aabb7343c | ||
|
|
b30a6c8fb1 | ||
|
|
812b2d4f73 | ||
|
|
771ece41b1 | ||
|
|
3a84110565 |
@@ -0,0 +1,35 @@
|
||||
---
|
||||
name: code-refactorer
|
||||
description: Improves existing code quality by cleaning up messy code, extracting duplicated logic, simplifying complex functions, improving naming, and removing dead code. Use when the user asks to rewrite, refactor, simplify, or clean up code without adding new functionality.
|
||||
model: sonnet
|
||||
color: pink
|
||||
---
|
||||
|
||||
You are a code refactoring specialist. You improve existing code quality while preserving exact behavior. Follow the principles and code style defined in CLAUDE.md.
|
||||
|
||||
## Hard Rules
|
||||
|
||||
- NEVER add new features, parameters, or functionality
|
||||
- NEVER change external behavior or API contracts
|
||||
- NEVER implement TODOs or feature requests
|
||||
- If scope is unclear, ASK before proceeding
|
||||
|
||||
## Code Smells to Target
|
||||
|
||||
- Functions >30 lines or >3 nesting levels
|
||||
- Magic numbers/strings without constants
|
||||
- Long parameter lists (>4 params)
|
||||
- God objects doing too much
|
||||
- Data clumps (same group of variables passed together repeatedly)
|
||||
- Feature envy (function uses another object's data excessively)
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Read** the target code and understand its responsibilities and dependencies
|
||||
2. **Identify** specific improvements (prioritize: dead code removal > naming > deduplication > simplification > type safety)
|
||||
3. **Refactor** incrementally — one logical change at a time, preserving behavior
|
||||
4. **Validate** — run `pnpm lint` and `pnpm type-check` from the repo root, then `pnpm format`. There is no test runner in this repo; never invent `pnpm test`.
|
||||
|
||||
## After Refactoring
|
||||
|
||||
Summarize what changed: lines removed/added, functions extracted, types improved, duplications consolidated.
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Use this agent when the user requests a code review, code check, or quality assessment. This includes reviewing functions, refactored code, pull request changes, or any code segment. Do NOT call this agent proactively after completing tasks - only when the user asks for a review.
|
||||
tools: Glob, Grep, Read, WebFetch, TodoWrite, WebSearch, BashOutput, KillShell, mcp__ide__getDiagnostics, mcp__ide__executeCode, Bash, AskUserQuestion, Skill, SlashCommand
|
||||
model: opus
|
||||
color: purple
|
||||
---
|
||||
|
||||
You are a Code Review Expert for a **Next.js 15 / React 19 / TypeScript** frontend monorepo (Turborepo + pnpm, Tailwind v4, react-query, NextAuth v5). The NestJS backend lives in a separate repo (`../bwnet-backend`) — do not review this code as if it were backend code, and do not flag the absence of tests: no test runner is configured here.
|
||||
|
||||
Read the project's CLAUDE.md for architecture, conventions and coding standards before reviewing.
|
||||
|
||||
## Review Lenses
|
||||
|
||||
Analyze code through these lenses (in priority order):
|
||||
|
||||
1. **Correctness** — logic errors, off-by-one, null access, race conditions, edge cases, stale closures
|
||||
2. **Security** — auth checks on new routes and server actions, tokens or secrets reaching the client bundle / logs / URLs, unvalidated input rendered as HTML
|
||||
3. **Type Safety** — unsafe `any`, missing narrowing, risky assertions, backend DTOs hand-redefined instead of using `@bwnet/api` models
|
||||
4. **Performance** — needless re-renders, unstable react-query keys or effect deps, missing cleanup on subscriptions and timers
|
||||
5. **Maintainability** — readability, DRY/KISS/YAGNI adherence, function size
|
||||
6. **Next.js / React patterns** — server vs. client component boundary and `"use client"` placement, App Router file conventions, awaited `params` / `searchParams` (Next 15), react-query mutation invalidation, hook rules
|
||||
|
||||
## Project Conventions
|
||||
|
||||
Weigh these alongside the lenses above:
|
||||
|
||||
- Generated `@bwnet/api` hooks, models and schemas reused instead of hand-written DTOs or duplicate fetch logic; imports from the `@bwnet/api` barrel, never deep `src/gen/...` paths; `src/gen/` never hand-edited.
|
||||
- Generated hooks called with no config argument — auth and `baseURL` come from the global axios interceptor in `@bwnet/auth`.
|
||||
- New UI primitives added to `packages/ui` (shadcn-style), not duplicated per app; Tailwind v4 tokens from `@bwnet/tailwind-config`, no `tailwind.config.js`.
|
||||
- New user-facing copy added to **both** `packages/i18n/messages/en/*.json` and `packages/i18n/messages/hu/*.json`; UI copy Hungarian, currency HUF / `hu-HU` formatting.
|
||||
- `import type` for type-only imports; no `any`; modern component props syntax over `React.FC`.
|
||||
- No leftover legacy code (unused exports, commented-out blocks, back-compat re-exports); TODO comments left intact unless the task is verifiably complete.
|
||||
- Changes crossing the domain model (phased services, resource allocation, catalog layering, billing) follow the snapshot principle: booked and purchased records freeze their effective values. See the "Domain model" section of CLAUDE.md.
|
||||
|
||||
## Review Output Format:
|
||||
|
||||
Structure your review as follows:
|
||||
|
||||
### Summary
|
||||
|
||||
Brief overall assessment (1-2 sentences)
|
||||
|
||||
### Critical Issues 🔴
|
||||
|
||||
Must-fix problems that could cause bugs, security vulnerabilities, or data loss
|
||||
|
||||
### Important Improvements 🟡
|
||||
|
||||
Significant issues affecting maintainability, performance, or code quality
|
||||
|
||||
### Suggestions 🟢
|
||||
|
||||
Optional enhancements and best practice recommendations
|
||||
|
||||
### Positive Observations ✨
|
||||
|
||||
Well-implemented patterns worth highlighting
|
||||
|
||||
## Guidelines
|
||||
|
||||
- Clarify scope first if unclear (staged changes, specific files, full PR)
|
||||
- Provide line-level feedback with concrete fix suggestions
|
||||
- Explain consequences, not just "this is wrong"
|
||||
- Prioritize high-impact issues; don't nitpick style
|
||||
- Skip anything the linter, formatter or `tsc` would catch — those run separately
|
||||
- Acknowledge good patterns alongside issues
|
||||
@@ -0,0 +1,123 @@
|
||||
---
|
||||
name: test
|
||||
description: Use this agent for writing automated tests for NestJS controllers, services, and e2e API routes. Generates unit and integration tests with proper mocking of services, database, and external dependencies.
|
||||
model: sonnet
|
||||
color: green
|
||||
---
|
||||
|
||||
# Test Generation Agent
|
||||
|
||||
You write automated tests for a **NestJS 11** backend using **Jest 30**, **TypeORM 0.3**, and **class-validator**. Tests may be written **TDD-style** (before implementation) or **after implementation** — follow the user's lead. Before writing tests, always read the source file being tested (if it exists) AND the existing test files in the project to match established patterns.
|
||||
|
||||
## Stack
|
||||
|
||||
- **NestJS 11** with `@nestjs/testing`
|
||||
- **Jest 30** with `ts-jest`
|
||||
- **TypeORM 0.3** with PostgreSQL
|
||||
- **supertest 7** for e2e tests
|
||||
- **class-validator 0.14** / **class-transformer** for DTO validation
|
||||
|
||||
## Principles
|
||||
|
||||
1. **Test behavior, not implementation** — assert on return values and thrown exceptions, not on which internal methods were called. Verify side effects only when they ARE the behavior (e.g., "service.create was called with correct DTO" in a thin controller test).
|
||||
2. **One behavior per test** — each `it()` block verifies exactly one scenario.
|
||||
3. **Arrange-Act-Assert** — clear separation within each test.
|
||||
4. **No `any` types** — mock data and variables must use proper TypeScript types.
|
||||
5. **Clean up between tests** — always use `afterEach(() => { jest.clearAllMocks(); })` to prevent state leaking.
|
||||
6. **Descriptive test names** — `it('throws NotFoundException when attraction not found')` not `it('should work')`.
|
||||
|
||||
## File Organization
|
||||
|
||||
- Unit tests: co-located as `src/[feature]/[feature].[controller|service].spec.ts`
|
||||
- E2e tests: `test/[feature].e2e-spec.ts`
|
||||
- DTO tests (when needed): `src/[feature]/dto/[dto-name].spec.ts`
|
||||
|
||||
## Unit Tests — Services
|
||||
|
||||
Services contain business logic and are the primary unit test target.
|
||||
|
||||
### TypeORM Repository Mocking
|
||||
|
||||
- Use `getRepositoryToken(Entity)` to provide mock repositories via `useValue`
|
||||
- Type mocks with `jest.Mocked<Pick<Repository<Entity>, 'method1' | 'method2'>>` — only mock the methods the service actually calls
|
||||
- Instantiate mock objects inside `beforeEach`, not at module scope
|
||||
- Use the real service class in providers — only the repository is mocked
|
||||
|
||||
### QueryBuilder Mocking
|
||||
|
||||
- Mock all intermediate chain methods (where, orderBy, skip, take, leftJoinAndSelect) with `mockReturnThis()`
|
||||
- Only terminal methods (getMany, getOne, getManyAndCount) use `mockResolvedValue()`
|
||||
- Provide the QueryBuilder mock via the repository's `createQueryBuilder` method
|
||||
|
||||
### Transaction Mocking
|
||||
|
||||
- Mock `DataSource.createQueryRunner()` returning an object with `connect`, `startTransaction`, `commitTransaction`, `rollbackTransaction`, `release`, and a `manager` with the needed find/save methods
|
||||
- Provide via `{ provide: DataSource, useValue: mockDataSource }`
|
||||
|
||||
### Common Service Test Scenarios
|
||||
|
||||
Always cover these for each service method:
|
||||
|
||||
**CRUD operations:**
|
||||
|
||||
- Happy path — returns expected data
|
||||
- Not found — throws `NotFoundException`
|
||||
- Duplicate/unique violation — throws `ConflictException` (PostgreSQL error code `23505`)
|
||||
- Invalid input — throws `BadRequestException`
|
||||
|
||||
**Specific to this project:**
|
||||
|
||||
- Unique violation detection via `isUniqueViolationError()` from `src/common/utils/`
|
||||
- Date range validation via `validateDateRange()` from `src/common/validators/`
|
||||
- Pessimistic locking in update operations (mock `QueryRunner` with `manager.findOne`)
|
||||
|
||||
### Mocking Injected Services
|
||||
|
||||
When a service depends on other services (not just repositories), mock them with the same `jest.Mocked<Pick<>>` pattern and provide via `useValue`.
|
||||
|
||||
## Unit Tests — Controllers
|
||||
|
||||
Controllers should be thin — they delegate to services. Controller tests verify:
|
||||
|
||||
- Correct service method is called with correct arguments
|
||||
- Return value is passed through unchanged
|
||||
- Route parameters and DTOs are forwarded correctly
|
||||
|
||||
Mock only the service, not the repository. Follow the same `jest.Mocked<Pick<>>` typing pattern.
|
||||
|
||||
## DTO Validation Tests
|
||||
|
||||
Test DTOs directly with `class-validator` only when they have non-trivial validation rules (custom validators, conditional validation, complex constraints). Skip for simple DTOs with only basic decorators.
|
||||
|
||||
- Use `plainToInstance()` from class-transformer to create a typed DTO instance from plain data
|
||||
- Use `validate()` from class-validator and assert on the returned errors array
|
||||
- Test valid data (expect zero errors), invalid data (expect errors on specific properties), and optional/nullable fields
|
||||
|
||||
## E2e Tests
|
||||
|
||||
E2e tests verify the full HTTP request lifecycle: routing, validation pipes, guards, service logic, and response format.
|
||||
|
||||
### Setup Rules
|
||||
|
||||
- Use `beforeAll` for app setup (not `beforeEach` — creating the app is expensive)
|
||||
- Always apply the same `ValidationPipe` config as `main.ts`: `whitelist: true`, `forbidNonWhitelisted: true`, `transform: true`
|
||||
- Use `.overrideProvider()` on the test module builder to swap real services/repositories with mocks
|
||||
- Always call `app.close()` in `afterAll`
|
||||
- Use `import request from 'supertest'` and `import { App } from 'supertest/types'` for proper typing
|
||||
|
||||
### What to Test in E2e
|
||||
|
||||
- **Paginated endpoints** — assert on response shape (`data` array + `meta` object with page, limit, totalItems, totalPages)
|
||||
- **Validation rejection** — send invalid bodies and assert 400 status with meaningful error messages
|
||||
- **Unknown properties** — send extra fields and assert 400 (forbidNonWhitelisted)
|
||||
- **Not found** — request non-existent resources and assert 404
|
||||
|
||||
## Anti-Patterns to Avoid
|
||||
|
||||
- **Over-mocking** — don't mock simple utilities or value objects. Only mock I/O boundaries (database, HTTP, file system).
|
||||
- **Testing framework behavior** — don't test that NestJS DI works or that decorators apply. Test YOUR code.
|
||||
- **Shared mutable state** — always reset mocks with `jest.clearAllMocks()`. Never share mock instances across `describe` blocks without resetting.
|
||||
- **Testing private methods** — test through the public API. If a private method needs direct testing, it should be extracted into its own service/utility.
|
||||
- **Snapshot tests for API responses** — use explicit assertions. Snapshots hide intent and break on irrelevant changes.
|
||||
- **`beforeEach` for app creation in e2e** — use `beforeAll`. Recreating the app per test is slow and unnecessary.
|
||||
- **Forgetting `async/await`** — all NestJS service calls are async. Missing `await` causes tests to pass incorrectly.
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(PATH=\"$HOME/.cargo/bin:$PATH\" wasm-pack build --target web)",
|
||||
"Read(//Users/ferencsagi/.nvm/versions/node/v18.17.0/bin/**)",
|
||||
"Read(//Users/ferencsagi/**)",
|
||||
"Bash(/opt/homebrew/bin/npm create:*)",
|
||||
"Bash(/opt/homebrew/bin/node --version)",
|
||||
"Bash(PATH=\"/opt/homebrew/bin:$PATH\" npm create vite@latest frontend -- --template react)",
|
||||
"Bash(wasm-pack build:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
---
|
||||
name: fable-tackle
|
||||
description: >-
|
||||
Multi-model orchestration policy for tackling a task: Fable 5.1 orchestrates,
|
||||
exploration/research is delegated to Sonnet 5 at high thinking, and
|
||||
coding/implementation is delegated to Opus 5.5 at high thinking. Use whenever
|
||||
the user invokes /fable-tackle, or asks to "tackle" a task with the fable
|
||||
multi-model split, or wants exploration on Sonnet, coding on Opus, and the
|
||||
orchestration/planning on Fable — all three at high thinking. Visual work
|
||||
(screenshots, image reading, UI/preview verification) also goes to Sonnet 5.
|
||||
Also trigger on phrasings like "fable-tackle ezt", "fable-vel szervezd",
|
||||
"sonnet exploráljon, opus kódoljon".
|
||||
---
|
||||
|
||||
# Fable Tackle
|
||||
|
||||
A task-execution policy that assigns each phase of work to the model best suited
|
||||
for it. You are the orchestrator; you delegate the two heavy phases (exploration
|
||||
and coding) to subagents running specific models at high reasoning effort, and
|
||||
you keep the planning/synthesis for yourself.
|
||||
|
||||
The point: exploration is search-heavy and cheap to parallelize (Sonnet 5, high
|
||||
thinking), implementation demands the strongest coder (Opus 5.5, high thinking),
|
||||
and stitching it together — deciding what to explore, what to build, and whether
|
||||
it's correct — is orchestration (Fable 5.1). Anything _visual_ — reading
|
||||
screenshots, image content, or driving/verifying the UI in the browser preview —
|
||||
also goes to Sonnet 5, which handles vision and screenshot-based checks well.
|
||||
|
||||
## The model split (the core of this skill)
|
||||
|
||||
| Phase | What it covers | Model | Agent model | Thinking |
|
||||
| ------------- | -------------------------------------------------------------------------------- | ---------------------------- | ----------- | -------- |
|
||||
| _Explore_ | search code, locate files, gather constraints, read docs, research — _read-only_ | Sonnet 5 (claude-sonnet-5) | sonnet | high |
|
||||
| _Visual / UI_ | read screenshots & images, drive the browser preview, verify the rendered UI | Sonnet 5 (claude-sonnet-5) | sonnet | high |
|
||||
| _Code_ | write/edit/refactor/fix, implement the change | Opus 5.5 (claude-opus-5-5) | opus | high |
|
||||
| _Orchestrate_ | decompose the task, sequence steps, synthesize findings, review, verify | Fable 5.1 (claude-fable-5-1) | fable | high |
|
||||
|
||||
Orchestration runs in the main loop — that's you. It works best if this session
|
||||
is on _Fable 5.1 at high thinking_. If it isn't, say so once (the user can switch
|
||||
model / raise the thinking level / toggle /fast), then proceed anyway — the
|
||||
subagent assignments below are what matter most, and you can still orchestrate on
|
||||
the current model. Since the main loop inherits the session's thinking level,
|
||||
Fable's "high thinking" comes from the session being set to high effort.
|
||||
|
||||
## How to run it
|
||||
|
||||
Pick the mechanism by task size.
|
||||
|
||||
### Multi-step tasks → use the Workflow tool (preferred)
|
||||
|
||||
Workflow is the only mechanism that lets you set _both_ the model and the
|
||||
thinking effort per subagent, so it honors "high thinking" precisely. Invoking
|
||||
it here is explicitly sanctioned — this skill's instructions tell you to.
|
||||
|
||||
- Orchestration is the script itself (runs on the session model — keep the
|
||||
session on Fable 5.1 at high thinking).
|
||||
- Exploration stages: `agent(prompt, { model: 'sonnet', effort: 'high', agentType: 'Explore' })`
|
||||
- Coding stages: `agent(prompt, { model: 'opus', effort: 'high' })`
|
||||
|
||||
Template — explore each area on Sonnet, then implement on Opus, pipelined so each
|
||||
area starts coding as soon as its exploration lands:
|
||||
|
||||
```js
|
||||
export const meta = {
|
||||
name: "fable-tackle",
|
||||
description:
|
||||
"Explore on Sonnet 5, implement on Opus 5.5, orchestrate on Fable 5.1",
|
||||
phases: [{ title: "Explore" }, { title: "Implement" }],
|
||||
};
|
||||
|
||||
// `args` = the list of sub-tasks/areas the orchestrator (you) carved out.
|
||||
const areas = args?.areas ?? args ?? [];
|
||||
|
||||
const results = await pipeline(
|
||||
areas,
|
||||
(area) =>
|
||||
agent(`Explore (read-only), reason at high effort: ${area.explore}`, {
|
||||
label: `explore:${area.name}`,
|
||||
phase: "Explore",
|
||||
model: "sonnet",
|
||||
effort: "high",
|
||||
agentType: "Explore",
|
||||
schema: area.exploreSchema,
|
||||
}),
|
||||
(findings, area) =>
|
||||
agent(
|
||||
`Implement, reason at high effort. Findings from exploration:\n${JSON.stringify(findings)}\n\nTask: ${area.code}`,
|
||||
{
|
||||
label: `code:${area.name}`,
|
||||
phase: "Implement",
|
||||
model: "opus",
|
||||
effort: "high",
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
return results.filter(Boolean);
|
||||
```
|
||||
|
||||
You (Fable) decide areas before calling Workflow, and you review/verify the
|
||||
returned work after — that decomposition and review is the orchestration phase.
|
||||
|
||||
### Quick / single-step tasks → use the Agent tool
|
||||
|
||||
For a one-shot explore or one-shot edit, spawn a single subagent:
|
||||
|
||||
- Explore: `Agent(subagent_type: "Explore", model: "sonnet", prompt: "...")`
|
||||
- Code: `Agent(model: "opus", prompt: "...")`
|
||||
|
||||
The Agent tool has _no_ thinking/effort parameter, so a subagent inherits the
|
||||
session's effort. To still get "high thinking," put an explicit cue in the
|
||||
subagent prompt — e.g. _"Reason at high effort; think carefully step by step
|
||||
before answering."_ If precise high-effort control matters, prefer the Workflow
|
||||
route above.
|
||||
|
||||
## The loop
|
||||
|
||||
1. _Orchestrate (Fable 5.1):_ break the task into exploration questions and
|
||||
implementation steps.
|
||||
2. _Explore (Sonnet 5, high):_ delegate the read-only investigation. Use the
|
||||
Explore agent type so this pass locates and reads code but never edits it.
|
||||
3. _Implement (Opus 5.5, high):_ delegate the code changes, feeding in the
|
||||
exploration findings so Opus doesn't re-discover them.
|
||||
4. _Verify (Sonnet 5, high):_ when the change is visual or UI-facing, delegate
|
||||
the screenshot / preview-driving / rendered-UI check to a Sonnet 5 subagent —
|
||||
it reads images and screenshots well. Non-visual verification (running tests,
|
||||
reading logs) can stay with the orchestrator.
|
||||
5. _Orchestrate (Fable 5.1):_ integrate, review for correctness, fold in the
|
||||
verification results, and decide whether another explore→code→verify loop is
|
||||
needed.
|
||||
|
||||
Keep exploration and coding cleanly separated — the exploration pass is what lets
|
||||
the Opus coding pass stay focused on writing correct code instead of hunting for
|
||||
context.
|
||||
@@ -0,0 +1,7 @@
|
||||
# Build outputs and locally downloaded data (the image downloads its own)
|
||||
target/
|
||||
data/
|
||||
vendor/
|
||||
legacy/
|
||||
.git/
|
||||
**/*.md
|
||||
@@ -0,0 +1,162 @@
|
||||
# main: tests and image build (tags: commit hash, `main`).
|
||||
# prod: the same, then deployment to the server (tags: commit hash, `prod`, `latest`).
|
||||
#
|
||||
# Runs on the self-hosted runner in ci/runner (label `linux`). Jobs use the
|
||||
# host's Docker daemon, so image builds share its BuildKit cache; a commit
|
||||
# already built on main is rebuilt from cache in seconds.
|
||||
#
|
||||
# Repository settings (Settings → Actions):
|
||||
# secrets.REGISTRY_TOKEN Gitea access token with package write access
|
||||
# secrets.DEPLOY_SSH_KEY private key of the deploy user on the server
|
||||
# vars.DEPLOY_HOST user@host of the server
|
||||
# vars.DEPLOY_KNOWN_HOSTS `ssh-keyscan <host>` output
|
||||
# vars.DEPLOY_PATH directory on the server (default /opt/sorsfonalak)
|
||||
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, prod]
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REGISTRY: registry.sagifer.com
|
||||
IMAGE_PREFIX: registry.sagifer.com/sagifer/sorsfonalak
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: sh
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: linux
|
||||
container:
|
||||
image: rust:1.99-alpine
|
||||
# Kept between runs, so only changed crates are compiled again.
|
||||
volumes:
|
||||
- sorsfonalak-ci-cargo:/usr/local/cargo/registry
|
||||
- sorsfonalak-ci-target:/ci-target
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18-alpine
|
||||
env:
|
||||
POSTGRES_USER: sorsfonalak
|
||||
POSTGRES_PASSWORD: ci
|
||||
POSTGRES_DB: sorsfonalak
|
||||
env:
|
||||
CARGO_TARGET_DIR: /ci-target
|
||||
DATABASE_URL: postgres://sorsfonalak:ci@postgres:5432/sorsfonalak
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
apk add --no-cache -q git musl-dev
|
||||
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||
git fetch -q --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
|
||||
- name: Wait for Postgres
|
||||
run: |
|
||||
for i in $(seq 30); do nc -z postgres 5432 && exit 0; sleep 1; done
|
||||
echo "postgres did not start" >&2; exit 1
|
||||
# astro-engine and horoscope-api need the Swiss Ephemeris sources and
|
||||
# data (scripts/fetch-deps.sh); their tests run locally.
|
||||
- name: Test
|
||||
run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates
|
||||
|
||||
build:
|
||||
needs: test
|
||||
runs-on: linux
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
apk add --no-cache -q git
|
||||
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||
git fetch -q --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
|
||||
- name: Log in to the registry
|
||||
env:
|
||||
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
run: printf '%s' "$TOKEN" | docker login "$REGISTRY" -u "${{ github.repository_owner }}" --password-stdin
|
||||
# The frontend build also type-checks the TypeScript code.
|
||||
- name: Build and push images
|
||||
run: |
|
||||
set -eu
|
||||
tag=$(echo "${{ github.sha }}" | cut -c1-12)
|
||||
extra="${{ github.ref_name }}"
|
||||
[ "$extra" = prod ] && extra="prod latest"
|
||||
build() {
|
||||
image="$IMAGE_PREFIX-$1"; shift
|
||||
docker build --label sorsfonalak.ci=1 -t "$image:$tag" "$@"
|
||||
docker push -q "$image:$tag"
|
||||
for t in $extra; do
|
||||
docker tag "$image:$tag" "$image:$t"
|
||||
docker push -q "$image:$t"
|
||||
done
|
||||
}
|
||||
build horoscope-api -f services/horoscope-api/Dockerfile .
|
||||
build backend -f services/backend/Dockerfile .
|
||||
build worker -f services/worker/Dockerfile .
|
||||
build frontend services/frontend
|
||||
- name: Clean up
|
||||
if: always()
|
||||
run: |
|
||||
docker logout "$REGISTRY" || true
|
||||
docker image prune -f --filter label=sorsfonalak.ci=1 >/dev/null
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
if: github.ref == 'refs/heads/prod'
|
||||
runs-on: linux
|
||||
steps:
|
||||
- name: Check settings
|
||||
run: |
|
||||
[ -n "${{ vars.DEPLOY_HOST }}" ] || { echo "vars.DEPLOY_HOST is not set (Settings → Actions → Variables)" >&2; exit 1; }
|
||||
- name: Checkout
|
||||
run: |
|
||||
apk add --no-cache -q git openssh-client
|
||||
git init -q . && git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
|
||||
git fetch -q --depth 1 origin "${{ github.sha }}" && git checkout -q FETCH_HEAD
|
||||
- name: SSH key
|
||||
env:
|
||||
KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
KNOWN_HOSTS: ${{ vars.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||
(umask 077 && printf '%s\n' "$KEY" > ~/.ssh/id_ed25519)
|
||||
printf '%s\n' "$KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||
# Copies the compose files, pins TAG in the server's .env and restarts
|
||||
# the changed services. The database migrations run when the backend starts.
|
||||
- name: Deploy
|
||||
env:
|
||||
HOST: ${{ vars.DEPLOY_HOST }}
|
||||
DIR: ${{ vars.DEPLOY_PATH || '/opt/sorsfonalak' }}
|
||||
run: |
|
||||
set -eu
|
||||
tag=$(echo "${{ github.sha }}" | cut -c1-12)
|
||||
scp -q deploy/docker-compose.yml deploy/Caddyfile "$HOST:$DIR/"
|
||||
ssh "$HOST" "cd '$DIR' && \
|
||||
(grep -q '^TAG=' .env && sed -i 's/^TAG=.*/TAG=$tag/' .env || echo 'TAG=$tag' >> .env) && \
|
||||
docker compose pull -q && docker compose up -d --remove-orphans --wait && \
|
||||
docker compose exec -T caddy caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile && \
|
||||
docker image prune -f >/dev/null"
|
||||
# A release (and its tag, e.g. v2026.11.17-163612e) for every deployment,
|
||||
# listing the commits since the previous one.
|
||||
- name: Release
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
run: |
|
||||
set -eu
|
||||
apk add --no-cache -q curl jq
|
||||
git fetch -q --unshallow --tags origin
|
||||
short=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||
name="v$(date -u +%Y.%m.%d)-$short"
|
||||
if curl -fsS -o /dev/null -H "Authorization: token $TOKEN" "$API/releases/tags/$name" 2>/dev/null; then
|
||||
echo "release $name already exists (redeploy)"; exit 0
|
||||
fi
|
||||
prev=$(git describe --tags --abbrev=0 --match 'v*' HEAD 2>/dev/null || true)
|
||||
if [ -n "$prev" ]; then range="$prev..HEAD"; since="since $prev"; else range="-20 HEAD"; since="(last 20 commits)"; fi
|
||||
changes=$(git log --no-merges --pretty='- %s (%h)' $range)
|
||||
body=$(printf 'Deployed to production on %s UTC.\nImages: `registry.sagifer.com/sagifer/sorsfonalak-*:%s`\n\nChanges %s:\n%s\n' \
|
||||
"$(date -u '+%Y-%m-%d %H:%M')" "$(echo "${{ github.sha }}" | cut -c1-12)" "$since" "$changes")
|
||||
jq -n --arg tag "$name" --arg sha "${{ github.sha }}" --arg body "$body" \
|
||||
'{tag_name: $tag, target_commitish: $sha, name: $tag, body: $body}' \
|
||||
| curl -fsS -X POST -H "Authorization: token $TOKEN" -H 'Content-Type: application/json' -d @- "$API/releases" \
|
||||
| jq -r '"created release " + .name + ": " + .html_url'
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/target/
|
||||
# Downloaded by scripts/fetch-deps.sh
|
||||
/data/
|
||||
/vendor/
|
||||
# Generated sharing pages
|
||||
/exports/
|
||||
# macOS
|
||||
.DS_Store
|
||||
# Legacy Java build output
|
||||
/legacy/target/
|
||||
/legacy/*.war
|
||||
/legacy/**/*.war
|
||||
# Local Claude Code permissions
|
||||
/.claude/settings.local.json
|
||||
# Local secrets and editor swap files
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.swp
|
||||
*.swo
|
||||
Generated
+3009
File diff suppressed because it is too large
Load Diff
+60
@@ -0,0 +1,60 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = [
|
||||
"crates/swisseph-sys",
|
||||
"crates/astro-engine",
|
||||
"crates/geo-tz",
|
||||
"crates/service-kit",
|
||||
"crates/db",
|
||||
"crates/horoscope-client",
|
||||
"crates/analysis-prompt",
|
||||
"crates/email-templates",
|
||||
"services/horoscope-api",
|
||||
"services/backend",
|
||||
"services/worker",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
version = "0.1.0"
|
||||
license = "AGPL-3.0-or-later"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
swisseph-sys = { path = "crates/swisseph-sys" }
|
||||
astro-engine = { path = "crates/astro-engine" }
|
||||
geo-tz = { path = "crates/geo-tz" }
|
||||
service-kit = { path = "crates/service-kit" }
|
||||
db = { path = "crates/db" }
|
||||
horoscope-client = { path = "crates/horoscope-client" }
|
||||
analysis-prompt = { path = "crates/analysis-prompt" }
|
||||
email-templates = { path = "crates/email-templates" }
|
||||
|
||||
anyhow = "1"
|
||||
argon2 = { version = "0.5", features = ["std"] }
|
||||
axum = "0.8"
|
||||
axum-extra = { version = "0.10", features = ["cookie"] }
|
||||
base64 = "0.22"
|
||||
hmac = "0.12"
|
||||
jsonwebtoken = { version = "9", default-features = false }
|
||||
lettre = { version = "0.11", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls", "webpki-roots", "ring"] }
|
||||
rand = "0.9"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||
sha2 = "0.10"
|
||||
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "postgres", "macros", "migrate", "uuid", "time", "json"] }
|
||||
time = { version = "0.3", features = ["serde-well-known"] }
|
||||
uuid = { version = "1", features = ["v7", "serde"] }
|
||||
deunicode = "1"
|
||||
jiff = { version = "0.2", default-features = false, features = ["std", "tzdb-zoneinfo", "tz-fat"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal"] }
|
||||
tower-http = { version = "0.6", features = ["trace", "cors"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
strip = true
|
||||
@@ -6,6 +6,8 @@ Asztrológiai rendszer konténeres backendje. A frontenden kívül minden Rustba
|
||||
|---|---|
|
||||
| `services/horoscope-api` | HTTP API: születési adatokból születési horoszkóp (radix) és szinasztria |
|
||||
| `services/backend` | felhasználók, belépés, mentett képletek, szinasztriák, meghívók, elemzések, kreditek, megosztás. Részletek: [services/backend/README.md](services/backend/README.md) |
|
||||
| `services/worker` | háttérmunkák: e-mail-küldés, LLM-elemzések, takarítás. Részletek: [services/worker/README.md](services/worker/README.md) |
|
||||
| `services/frontend` | Next.js webes felület: Google-belépés, profil, születési adatok, admin. Részletek: [services/frontend/README.md](services/frontend/README.md) |
|
||||
| `crates/db` | PostgreSQL-séma (migrációk) és a szolgáltatások közös adatelérése |
|
||||
| `crates/horoscope-client` | a horoscope-api HTTP-kliense (a backend és később a worker használja) |
|
||||
| `crates/service-kit` | közös alapok: naplózás, listen cím, healthcheck, leállítás |
|
||||
@@ -20,11 +22,19 @@ Asztrológiai rendszer konténeres backendje. A frontenden kívül minden Rustba
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
docker compose up -d --build # horoscope-api :8080, backend :8081, postgres 127.0.0.1:5432
|
||||
docker compose up -d --build # horoscope-api :8080, backend :8081, worker, postgres 127.0.0.1:5432, mailpit :8025
|
||||
curl -s localhost:8080/healthz
|
||||
curl -s localhost:8081/healthz
|
||||
```
|
||||
|
||||
A `docker compose up` a `docker-compose.override.yml` fájlt is betölti. Ebben csak fejlesztői dolgok vannak: a **Mailpit**, ami minden kimenő e-mailt elkap (webes felület: `http://<szerver>:8025`), és a worker erre van irányítva. Élesben az override nélkül kell indítani, és az `SMTP_URL`-t meg kell adni:
|
||||
|
||||
```bash
|
||||
SMTP_URL=smtps://user:jelszo@smtp.example.com:465 docker compose -f docker-compose.yml up -d
|
||||
```
|
||||
|
||||
Az éles szerverre a CI telepít (Gitea Actions, Caddy és https): lásd [deploy/README.md](deploy/README.md).
|
||||
|
||||
A horoscope-api image önálló (`scratch` alapú, kb. 70 MB, nem root felhasználóval fut). Benne van a statikus bináris és az összes adat. A container induláskor ~2 mp alatt betölti az adatokat, és ~190 MB memóriát használ. Egy horoszkóp kiszámítása 2–3 ms.
|
||||
|
||||
Build-argumentumok (`docker compose build --build-arg …`):
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# act_runner configuration (see `act_runner generate-config` for every option).
|
||||
log:
|
||||
level: info
|
||||
|
||||
runner:
|
||||
file: .runner
|
||||
capacity: 1
|
||||
timeout: 1h
|
||||
# Jobs without their own `container:` run in the Docker CLI image.
|
||||
labels:
|
||||
- "linux:docker://docker:29.9.3-cli"
|
||||
|
||||
cache:
|
||||
# Not used: the cargo and BuildKit caches live in Docker volumes.
|
||||
enabled: false
|
||||
|
||||
container:
|
||||
network: ""
|
||||
privileged: false
|
||||
# The host's Docker socket is mounted into every job container (docker_host
|
||||
# empty), so `docker build` uses the host daemon and its build cache.
|
||||
docker_host: ""
|
||||
# Only the CI cache volumes may be mounted by workflows.
|
||||
valid_volumes:
|
||||
- "sorsfonalak-ci-*"
|
||||
force_pull: false
|
||||
@@ -0,0 +1,26 @@
|
||||
# Gitea Actions runner for this repository, on the dev server.
|
||||
#
|
||||
# First start (registers the runner; the token is only needed once):
|
||||
# GITEA_RUNNER_REGISTRATION_TOKEN=... docker compose up -d
|
||||
# Afterwards: docker compose up -d
|
||||
|
||||
name: sorsfonalak-runner
|
||||
|
||||
services:
|
||||
runner:
|
||||
image: gitea/act_runner:0.6.1
|
||||
environment:
|
||||
CONFIG_FILE: /config.yaml
|
||||
GITEA_INSTANCE_URL: ${GITEA_INSTANCE_URL:-http://10.0.0.114:30008}
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN: ${GITEA_RUNNER_REGISTRATION_TOKEN:-}
|
||||
GITEA_RUNNER_NAME: ${GITEA_RUNNER_NAME:-dev-195}
|
||||
volumes:
|
||||
- ./config.yaml:/config.yaml:ro
|
||||
# Registration (.runner) lives here.
|
||||
- runner-data:/data
|
||||
# Job containers are started on the host daemon.
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
runner-data:
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "analysis-prompt"
|
||||
description = "Prompts and answer schemas of the Sorsfonalak LLM analyses (shared by backend and worker)"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,383 @@
|
||||
//! Prompts and output schemas of the analyses (prompt version [`PROMPT_VERSION`]).
|
||||
//!
|
||||
//! The model answers with one JSON object (OpenRouter structured output);
|
||||
//! [`validate`] checks it against the same schema before it is stored.
|
||||
//!
|
||||
//! The system prompt ([`default_system`]) can be replaced by an admin-edited
|
||||
//! text; the user message (chart data, section list) and the schema stay fixed.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key).
|
||||
pub const PROMPT_VERSION: &str = "v2";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Natal,
|
||||
Synastry,
|
||||
/// A free teaser of a natal chart: a title and a few sentences.
|
||||
Summary,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub const ALL: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry];
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Natal => "natal",
|
||||
Kind::Synastry => "synastry",
|
||||
Kind::Summary => "summary",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Kind> {
|
||||
match s {
|
||||
"natal" => Some(Kind::Natal),
|
||||
"synastry" => Some(Kind::Synastry),
|
||||
"summary" => Some(Kind::Summary),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Prompt {
|
||||
pub system: String,
|
||||
pub user: String,
|
||||
pub schema_name: &'static str,
|
||||
pub schema: Value,
|
||||
}
|
||||
|
||||
/// (key, what the section covers) in reading order.
|
||||
const NATAL_SECTIONS: [(&str, &str); 6] = [
|
||||
("personality", "Core identity: the Sun, Moon, Ascendant and chart ruler read together"),
|
||||
("emotions", "Emotional needs, security and inner life (Moon, 4th house, water emphasis)"),
|
||||
("mind", "Thinking, communication and learning (Mercury, 3rd and 9th houses)"),
|
||||
("love", "Love, attraction and relationships (Venus, Mars, 5th and 7th houses, Descendant)"),
|
||||
("work", "Calling, career, money and daily work (MC, 10th, 2nd and 6th houses, Saturn, Jupiter)"),
|
||||
(
|
||||
"growth",
|
||||
"Main inner tensions, life lessons and the path of growth (tight squares and oppositions, Saturn, Chiron, Nodes)",
|
||||
),
|
||||
];
|
||||
|
||||
const SYNASTRY_SECTIONS: [(&str, &str); 5] = [
|
||||
("attraction", "What draws them together: Sun, Moon, Venus, Mars and Ascendant contacts"),
|
||||
("communication", "How they think and talk together (Mercury contacts, air emphasis, 3rd house overlays)"),
|
||||
("emotional_bond", "Emotional closeness, safety and care (Moon contacts, 4th and 8th house overlays)"),
|
||||
("friction", "Where they rub against each other and how to handle it (challenging aspects, Saturn, Pluto, Mars)"),
|
||||
("long_term", "Long-term potential and shared purpose, including the composite chart"),
|
||||
];
|
||||
|
||||
fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
|
||||
match kind {
|
||||
Kind::Natal => &NATAL_SECTIONS,
|
||||
Kind::Synastry => &SYNASTRY_SECTIONS,
|
||||
Kind::Summary => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON schema of the answer (strict mode: every property required).
|
||||
pub fn schema(kind: Kind) -> Value {
|
||||
if kind == Kind::Summary {
|
||||
return json!({
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["title", "summary"],
|
||||
"properties": {
|
||||
"title": {"type": "string", "description": "Short, evocative title for this chart (at most 6 words)"},
|
||||
"summary": {"type": "string", "description": "3-4 sentences, 60-100 words, one paragraph"}
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut props = serde_json::Map::new();
|
||||
for (key, about) in sections(kind) {
|
||||
props.insert(
|
||||
(*key).into(),
|
||||
json!({
|
||||
"type": "object",
|
||||
"description": about,
|
||||
"additionalProperties": false,
|
||||
"required": ["title", "body"],
|
||||
"properties": {
|
||||
"title": {"type": "string", "description": "Short, specific section title (not just the topic name)"},
|
||||
"body": {"type": "string", "description": "2-4 paragraphs separated by a blank line"}
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
let keys: Vec<&str> = sections(kind).iter().map(|(k, _)| *k).collect();
|
||||
json!({
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["title", "summary", "sections", "strengths", "challenges", "advice"],
|
||||
"properties": {
|
||||
"title": {"type": "string", "description": "Short, evocative title for this analysis (at most 8 words)"},
|
||||
"summary": {"type": "string", "description": "3-4 sentence overview"},
|
||||
"sections": {"type": "object", "additionalProperties": false, "required": keys, "properties": props},
|
||||
"strengths": {"type": "array", "items": {"type": "string"}, "description": "3-5 key strengths, one sentence each"},
|
||||
"challenges": {"type": "array", "items": {"type": "string"}, "description": "3-5 key challenges, one sentence each"},
|
||||
"advice": {"type": "string", "description": "A closing, encouraging paragraph with concrete guidance"}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const HUNGARIAN_STYLE: &str = "\
|
||||
Write natural, idiomatic Hungarian, as a native Hungarian author would; it must not read like a translation from English. \
|
||||
Use correct Hungarian suffixes and vowel harmony, Hungarian quotation marks („…”) and the en dash (–). \
|
||||
Use the usual Hungarian astrological terms:
|
||||
- signs: Kos, Bika, Ikrek, Rák, Oroszlán, Szűz, Mérleg, Skorpió, Nyilas, Bak, Vízöntő, Halak (\"a Nap a Rák jegyében\", \"Kos Aszcendens\");
|
||||
- planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \
|
||||
Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont;
|
||||
- aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, szembenállás (oppozíció);
|
||||
- elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó;
|
||||
Never leave English words (e.g. fire, earth, air, water) in the Hungarian text.
|
||||
- other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp.";
|
||||
|
||||
fn language_name(language: &str) -> &'static str {
|
||||
match language {
|
||||
"hu" => "Hungarian",
|
||||
_ => "English",
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in system prompt of an analysis kind in a language.
|
||||
pub fn default_system(kind: Kind, language: &str) -> String {
|
||||
let (role, reader) = match kind {
|
||||
Kind::Natal => (
|
||||
"a personal natal chart interpretation",
|
||||
"Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
|
||||
),
|
||||
Kind::Summary => (
|
||||
"a short free summary of a natal chart (a teaser shown before the detailed, paid analysis)",
|
||||
"Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
|
||||
),
|
||||
Kind::Synastry => (
|
||||
"a relationship (synastry) interpretation for two people",
|
||||
"Write for both people at once, in the informal second person plural (in Hungarian: \"ti\", \"kettőtök\"). \
|
||||
When you must tell them apart, call them Person 1 and Person 2 (in Hungarian: \"az első fél\" and \"a második fél\"). \
|
||||
Do not assume their genders or the type of relationship.",
|
||||
),
|
||||
};
|
||||
let mut text = format!(
|
||||
"You are an experienced, warm and psychologically minded astrologer. You write {role} for the Sorsfonalak app.
|
||||
|
||||
Write in {lang}.
|
||||
|
||||
Rules:
|
||||
- Base every statement on the chart data given. Never invent positions, aspects or houses that are not listed.
|
||||
- When you interpret a placement, name its astrological basis in a short clause, but keep the focus on the person, not on jargon.
|
||||
- Synthesize: weave signs, houses, aspects and rulers into one coherent portrait; show how tensions can be integrated. \
|
||||
Give the most weight to the Sun, Moon, Ascendant, chart ruler, tight aspects (orb under 3°) and strong emphases or gaps in elements and modalities.
|
||||
- If a birth time is unknown, do not mention houses, the Ascendant or the Midheaven for that chart, and be careful with the Moon's sign.
|
||||
- {reader}
|
||||
- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents or specific events, \
|
||||
and no medical, legal or financial advice.
|
||||
- Avoid generic horoscope clichés and filler: every paragraph must say something specific to this chart.
|
||||
- Texts are plain paragraphs separated by a blank line, without headings or lists inside; **bold** may be used sparingly.
|
||||
- {length}
|
||||
- Answer with a single JSON object that matches the given schema, and nothing else.",
|
||||
lang = language_name(language),
|
||||
length = match kind {
|
||||
Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \
|
||||
(if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \
|
||||
a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \
|
||||
no sales talk, and do not mention a longer analysis.",
|
||||
_ => "Length: each section 2-4 paragraphs (about 150-250 words); the whole analysis about 1300-1800 words.",
|
||||
},
|
||||
);
|
||||
if language == "hu" {
|
||||
text.push_str("\n\n");
|
||||
text.push_str(HUNGARIAN_STYLE);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Splits a stored prompt version (`v2` or `v2-r<id>`, the id of an admin-edited
|
||||
/// system prompt in `prompt_revisions`) into the code version and the revision id.
|
||||
pub fn split_version(version: &str) -> (&str, Option<i64>) {
|
||||
match version.rsplit_once("-r") {
|
||||
Some((base, id)) => match id.parse() {
|
||||
Ok(id) => (base, Some(id)),
|
||||
Err(_) => (version, None),
|
||||
},
|
||||
None => (version, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in text of the user message around the chart data, for showing
|
||||
/// next to the editable system prompt (`{chart data}` stands for the data).
|
||||
pub fn user_template(kind: Kind) -> String {
|
||||
build(kind, "hu", "{chart data}\n", None).user
|
||||
}
|
||||
|
||||
/// The prompt for one analysis; `system` replaces [`default_system`].
|
||||
pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>) -> Prompt {
|
||||
let mut user = String::from("Chart data:\n\n");
|
||||
user.push_str(chart_text);
|
||||
if kind == Kind::Summary {
|
||||
user.push_str("\nWrite the short summary now.");
|
||||
} else {
|
||||
user.push_str("\nSections to write, in this order:\n");
|
||||
for (key, about) in sections(kind) {
|
||||
user.push_str(&format!("- {key}: {about}\n"));
|
||||
}
|
||||
user.push_str("\nWrite the analysis now.");
|
||||
}
|
||||
Prompt {
|
||||
system: system.map_or_else(|| default_system(kind, language), str::to_owned),
|
||||
user,
|
||||
schema_name: match kind {
|
||||
Kind::Natal => "natal_analysis",
|
||||
Kind::Synastry => "synastry_analysis",
|
||||
Kind::Summary => "chart_summary",
|
||||
},
|
||||
schema: schema(kind),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks an answer against our schema subset (objects with required
|
||||
/// properties, strings with at least three letters, string arrays with at
|
||||
/// least two items). A placeholder such as "x" counts as missing.
|
||||
pub fn validate(schema: &Value, value: &Value) -> Result<(), String> {
|
||||
fn walk(schema: &Value, value: &Value, path: &str) -> Result<(), String> {
|
||||
match schema["type"].as_str() {
|
||||
Some("object") => {
|
||||
let obj = value.as_object().ok_or_else(|| format!("{path}: expected an object"))?;
|
||||
for key in schema["required"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
let child = obj.get(key).ok_or_else(|| format!("{path}.{key}: missing"))?;
|
||||
walk(&schema["properties"][key], child, &format!("{path}.{key}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some("array") => {
|
||||
let items = value.as_array().ok_or_else(|| format!("{path}: expected an array"))?;
|
||||
if items.len() < 2 {
|
||||
return Err(format!("{path}: too few items"));
|
||||
}
|
||||
items.iter().enumerate().try_for_each(|(i, v)| walk(&schema["items"], v, &format!("{path}[{i}]")))
|
||||
}
|
||||
Some("string") => match value.as_str() {
|
||||
Some(s) if s.chars().filter(|c| c.is_alphabetic()).nth(2).is_some() => Ok(()),
|
||||
_ => Err(format!("{path}: expected a non-empty string")),
|
||||
},
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
walk(schema, value, "$")
|
||||
}
|
||||
|
||||
/// Fixes typography the models often get wrong. In Hungarian, pairs of
|
||||
/// straight double quotes become „…” (only when they pair up evenly).
|
||||
pub fn polish(language: &str, content: &mut Value) {
|
||||
fn hungarian_quotes(text: &str) -> Option<String> {
|
||||
if !text.contains('"') || !text.matches('"').count().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
let mut open = true;
|
||||
Some(
|
||||
text.chars()
|
||||
.map(|c| match c {
|
||||
'"' => {
|
||||
let q = if open { '„' } else { '”' };
|
||||
open = !open;
|
||||
q
|
||||
}
|
||||
c => c,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
match content {
|
||||
Value::String(s) if language == "hu" => {
|
||||
if let Some(fixed) = hungarian_quotes(s) {
|
||||
*s = fixed;
|
||||
}
|
||||
}
|
||||
Value::Array(items) => items.iter_mut().for_each(|v| polish(language, v)),
|
||||
Value::Object(map) => map.values_mut().for_each(|v| polish(language, v)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The analysis as Markdown (for reading and comparing outputs).
|
||||
pub fn to_markdown(kind: Kind, language: &str, content: &Value) -> String {
|
||||
let (strengths, challenges, advice) = if language == "hu" {
|
||||
("Erősségek", "Kihívások", "Útravaló")
|
||||
} else {
|
||||
("Strengths", "Challenges", "Advice")
|
||||
};
|
||||
let mut md =
|
||||
format!("# {}\n\n_{}_\n\n", content["title"].as_str().unwrap_or(""), content["summary"].as_str().unwrap_or(""));
|
||||
if kind == Kind::Summary {
|
||||
return md;
|
||||
}
|
||||
for (key, _) in sections(kind) {
|
||||
let s = &content["sections"][*key];
|
||||
md.push_str(&format!("## {}\n\n{}\n\n", s["title"].as_str().unwrap_or(key), s["body"].as_str().unwrap_or("")));
|
||||
}
|
||||
for (title, key) in [(strengths, "strengths"), (challenges, "challenges")] {
|
||||
md.push_str(&format!("## {title}\n\n"));
|
||||
for item in content[key].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
md.push_str(&format!("- {item}\n"));
|
||||
}
|
||||
md.push('\n');
|
||||
}
|
||||
md.push_str(&format!("## {advice}\n\n{}\n", content["advice"].as_str().unwrap_or("")));
|
||||
md
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn summary_prompt_is_short() {
|
||||
let p = build(Kind::Summary, "hu", "SUN: Cancer", None);
|
||||
assert_eq!(p.schema_name, "chart_summary");
|
||||
assert!(p.system.contains("3-4 sentences") && p.system.contains("tegező"));
|
||||
assert!(!p.user.contains("Sections to write"));
|
||||
assert_eq!(validate(&p.schema, &json!({"title": "Érzékeny mag", "summary": "Rövid szöveg."})), Ok(()));
|
||||
assert!(validate(&p.schema, &json!({"title": "Érzékeny mag"})).is_err());
|
||||
let md = to_markdown(Kind::Summary, "hu", &json!({"title": "Cím", "summary": "Szöveg."}));
|
||||
assert_eq!(md, "# Cím\n\n_Szöveg._\n\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_system_replaces_only_the_rules() {
|
||||
let p = build(Kind::Natal, "hu", "SUN: Cancer", Some("Saját szabályok."));
|
||||
assert_eq!(p.system, "Saját szabályok.");
|
||||
assert!(p.user.contains("SUN: Cancer") && p.user.contains("- personality:"));
|
||||
assert_eq!(p.schema, schema(Kind::Natal));
|
||||
assert!(user_template(Kind::Natal).contains("{chart data}"));
|
||||
assert_eq!(split_version("v2-r12"), ("v2", Some(12)));
|
||||
assert_eq!(split_version("v2"), ("v2", None));
|
||||
assert!(Kind::ALL.iter().all(|k| Kind::parse(k.as_str()) == Some(*k)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_placeholder_titles() {
|
||||
let schema = schema(Kind::Synastry);
|
||||
let section = json!({"title": "Rák-szívek", "body": "Két bekezdés szöveg."});
|
||||
let mut answer = json!({
|
||||
"title": "Két Rák-szív", "summary": "Összefoglaló.", "advice": "Útravaló.",
|
||||
"strengths": ["Egyik erősség.", "Másik erősség."], "challenges": ["Egy kihívás.", "Még egy."],
|
||||
"sections": {"attraction": section, "communication": section, "emotional_bond": section,
|
||||
"friction": section, "long_term": section},
|
||||
});
|
||||
assert_eq!(validate(&schema, &answer), Ok(()));
|
||||
answer["sections"]["attraction"]["title"] = json!("x");
|
||||
assert_eq!(validate(&schema, &answer), Err("$.sections.attraction.title: expected a non-empty string".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polish_turns_straight_quotes_hungarian() {
|
||||
let mut v = json!({"a": "a \"hazai pálya\" és a \"sorok\"", "b": ["egy \" pár nélkül"], "c": {"d": "nincs"}});
|
||||
polish("hu", &mut v);
|
||||
assert_eq!(v["a"], "a „hazai pálya” és a „sorok”");
|
||||
assert_eq!(v["b"][0], "egy \" pár nélkül");
|
||||
assert_eq!(v["c"]["d"], "nincs");
|
||||
let mut en = json!({"a": "the \"home\" ground"});
|
||||
polish("en", &mut en);
|
||||
assert_eq!(en["a"], "the \"home\" ground");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "astro-engine"
|
||||
description = "Natal chart calculation on top of a replaceable ephemeris engine"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["swisseph"]
|
||||
swisseph = ["dep:swisseph-sys"]
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
swisseph-sys = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Angle helpers (all angles in degrees).
|
||||
|
||||
/// Normalizes an angle into `[0, 360)`.
|
||||
pub fn normalize(deg: f64) -> f64 {
|
||||
let r = deg.rem_euclid(360.0);
|
||||
// rem_euclid can return 360.0 for tiny negative inputs due to rounding
|
||||
if r >= 360.0 { 0.0 } else { r }
|
||||
}
|
||||
|
||||
/// Shortest angular distance between two longitudes, in `[0, 180]`.
|
||||
pub fn separation(a: f64, b: f64) -> f64 {
|
||||
let d = normalize(a - b);
|
||||
if d > 180.0 { 360.0 - d } else { d }
|
||||
}
|
||||
|
||||
/// Forward arc from `from` to `to` (counter-clockwise, increasing longitude), in `[0, 360)`.
|
||||
pub fn arc(from: f64, to: f64) -> f64 {
|
||||
normalize(to - from)
|
||||
}
|
||||
|
||||
/// Formats an unsigned angle as `DD°MM'SS"`.
|
||||
pub fn dms(deg: f64) -> String {
|
||||
let (d, m, s) = split_dms(deg.abs());
|
||||
format!("{d}°{m:02}'{s:02}\"")
|
||||
}
|
||||
|
||||
/// Formats a signed angle as `+DD°MM'SS"` / `-DD°MM'SS"`.
|
||||
pub fn signed_dms(deg: f64) -> String {
|
||||
let sign = if deg < 0.0 { '-' } else { '+' };
|
||||
format!("{sign}{}", dms(deg))
|
||||
}
|
||||
|
||||
/// Formats hours as `HH:MM:SS`.
|
||||
pub fn hms(hours: f64) -> String {
|
||||
let (h, m, s) = split_dms(hours.rem_euclid(24.0));
|
||||
format!("{:02}:{m:02}:{s:02}", h % 24)
|
||||
}
|
||||
|
||||
/// Splits a non-negative value into whole units, minutes and seconds, rounding
|
||||
/// to the nearest second without producing 60 minutes or seconds.
|
||||
fn split_dms(value: f64) -> (u32, u32, u32) {
|
||||
let total = (value * 3600.0).round() as u64;
|
||||
((total / 3600) as u32, ((total / 60) % 60) as u32, (total % 60) as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalizes() {
|
||||
assert_eq!(normalize(-10.0), 350.0);
|
||||
assert_eq!(normalize(720.5), 0.5);
|
||||
assert_eq!(normalize(-1e-15), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separations() {
|
||||
assert_eq!(separation(350.0, 10.0), 20.0);
|
||||
assert_eq!(separation(10.0, 190.0), 180.0);
|
||||
assert_eq!(arc(350.0, 10.0), 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats() {
|
||||
assert_eq!(dms(21.8866), "21°53'12\"");
|
||||
assert_eq!(dms(29.99999), "30°00'00\"");
|
||||
assert_eq!(signed_dms(-1.5), "-1°30'00\"");
|
||||
assert_eq!(hms(25.5), "01:30:00");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,921 @@
|
||||
//! Engine-independent natal chart construction.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::angle::{self, normalize, separation};
|
||||
use crate::engine::{BodyState, EngineError, Ephemeris, Frame, GeoPosition, HouseResult, Obliquity};
|
||||
use crate::types::{
|
||||
AspectSet, Ayanamsa, Body, Dignity, Element, HouseSystem, LilithType, Modality, NodeType, ZodiacSign, ZodiacType,
|
||||
dignities,
|
||||
};
|
||||
|
||||
/// Calculation options (all have sensible defaults).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct ChartOptions {
|
||||
pub house_system: HouseSystem,
|
||||
pub zodiac: ZodiacType,
|
||||
/// Used only with the sidereal zodiac.
|
||||
pub ayanamsa: Ayanamsa,
|
||||
pub node_type: NodeType,
|
||||
pub lilith_type: LilithType,
|
||||
pub aspect_set: AspectSet,
|
||||
/// Scales every orb (1.0 = default orbs).
|
||||
pub orb_multiplier: f64,
|
||||
/// Topocentric instead of geocentric positions (matters mostly for the Moon).
|
||||
pub topocentric: bool,
|
||||
/// Include Ceres, Pallas, Juno and Vesta.
|
||||
pub include_asteroids: bool,
|
||||
}
|
||||
|
||||
impl Default for ChartOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
house_system: HouseSystem::default(),
|
||||
zodiac: ZodiacType::default(),
|
||||
ayanamsa: Ayanamsa::default(),
|
||||
node_type: NodeType::default(),
|
||||
lilith_type: LilithType::default(),
|
||||
aspect_set: AspectSet::default(),
|
||||
orb_multiplier: 1.0,
|
||||
topocentric: false,
|
||||
include_asteroids: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ChartInput {
|
||||
/// Moment of birth as Julian Day (UT).
|
||||
pub jd_ut: f64,
|
||||
pub observer: GeoPosition,
|
||||
/// `false` when the birth time is unknown: houses, angles and lots are
|
||||
/// omitted and the Moon position is flagged as approximate.
|
||||
pub time_known: bool,
|
||||
pub options: ChartOptions,
|
||||
}
|
||||
|
||||
/// Identifier of a chart point (bodies, calculated points and angles).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PointId {
|
||||
Sun,
|
||||
Moon,
|
||||
Mercury,
|
||||
Venus,
|
||||
Mars,
|
||||
Jupiter,
|
||||
Saturn,
|
||||
Uranus,
|
||||
Neptune,
|
||||
Pluto,
|
||||
NorthNode,
|
||||
SouthNode,
|
||||
Lilith,
|
||||
Chiron,
|
||||
Ceres,
|
||||
Pallas,
|
||||
Juno,
|
||||
Vesta,
|
||||
Ascendant,
|
||||
Midheaven,
|
||||
}
|
||||
|
||||
impl PointId {
|
||||
fn from_planet(body: Body) -> PointId {
|
||||
match body {
|
||||
Body::Sun => PointId::Sun,
|
||||
Body::Moon => PointId::Moon,
|
||||
Body::Mercury => PointId::Mercury,
|
||||
Body::Venus => PointId::Venus,
|
||||
Body::Mars => PointId::Mars,
|
||||
Body::Jupiter => PointId::Jupiter,
|
||||
Body::Saturn => PointId::Saturn,
|
||||
Body::Uranus => PointId::Uranus,
|
||||
Body::Neptune => PointId::Neptune,
|
||||
Body::Pluto => PointId::Pluto,
|
||||
Body::Chiron => PointId::Chiron,
|
||||
Body::Ceres => PointId::Ceres,
|
||||
Body::Pallas => PointId::Pallas,
|
||||
Body::Juno => PointId::Juno,
|
||||
Body::Vesta => PointId::Vesta,
|
||||
Body::MeanNode | Body::TrueNode => PointId::NorthNode,
|
||||
Body::MeanLilith | Body::TrueLilith => PointId::Lilith,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_luminary(self) -> bool {
|
||||
matches!(self, PointId::Sun | PointId::Moon)
|
||||
}
|
||||
|
||||
/// Sensitive points that get reduced orbs.
|
||||
fn is_minor_point(self) -> bool {
|
||||
matches!(self, PointId::NorthNode | PointId::SouthNode | PointId::Lilith | PointId::Chiron)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PointKind {
|
||||
Luminary,
|
||||
Planet,
|
||||
LunarNode,
|
||||
LunarApogee,
|
||||
Centaur,
|
||||
Asteroid,
|
||||
}
|
||||
|
||||
/// Position on the ecliptic expressed in zodiac terms.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ZodiacPosition {
|
||||
/// Ecliptic longitude, degrees `[0, 360)`.
|
||||
pub longitude: f64,
|
||||
pub sign: ZodiacSign,
|
||||
/// Degrees within the sign `[0, 30)`.
|
||||
pub degree_in_sign: f64,
|
||||
/// Degrees within the sign as `DD°MM'SS"`.
|
||||
pub degree_in_sign_dms: String,
|
||||
/// Decan within the sign (1..=3).
|
||||
pub decan: u8,
|
||||
}
|
||||
|
||||
impl ZodiacPosition {
|
||||
pub fn new(longitude: f64) -> Self {
|
||||
let longitude = normalize(longitude);
|
||||
let sign = ZodiacSign::from_longitude(longitude);
|
||||
let degree_in_sign = longitude - sign.index() as f64 * 30.0;
|
||||
Self {
|
||||
longitude,
|
||||
sign,
|
||||
degree_in_sign,
|
||||
degree_in_sign_dms: angle::dms(degree_in_sign),
|
||||
decan: ((degree_in_sign / 10.0).floor() as u8 + 1).min(3),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Point {
|
||||
pub id: PointId,
|
||||
pub kind: PointKind,
|
||||
/// `"true"` / `"mean"` for lunar nodes and Lilith.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub variant: Option<&'static str>,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
/// Ecliptic latitude, degrees.
|
||||
pub latitude: f64,
|
||||
pub distance_au: f64,
|
||||
/// Daily motion in longitude, degrees/day.
|
||||
pub speed: f64,
|
||||
pub retrograde: bool,
|
||||
pub right_ascension: f64,
|
||||
pub declination: f64,
|
||||
/// Declination beyond the obliquity of the ecliptic.
|
||||
pub out_of_bounds: bool,
|
||||
/// House (1..=12); `null` when the birth time is unknown.
|
||||
pub house: Option<u8>,
|
||||
/// Essential dignities (planets only).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dignities: Option<Vec<Dignity>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AnglePoint {
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
/// Daily motion, degrees/day.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub speed: Option<f64>,
|
||||
}
|
||||
|
||||
impl AnglePoint {
|
||||
fn new(longitude: f64, speed: Option<f64>) -> Self {
|
||||
Self { position: ZodiacPosition::new(longitude), speed }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Angles {
|
||||
pub ascendant: AnglePoint,
|
||||
pub midheaven: AnglePoint,
|
||||
pub descendant: AnglePoint,
|
||||
pub imum_coeli: AnglePoint,
|
||||
pub vertex: AnglePoint,
|
||||
pub antivertex: AnglePoint,
|
||||
/// Equatorial ascendant ("East Point").
|
||||
pub east_point: AnglePoint,
|
||||
/// Right ascension of the MC, degrees.
|
||||
pub armc: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct HouseCusp {
|
||||
pub house: u8,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
/// Size of the house in degrees.
|
||||
pub size: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Houses {
|
||||
pub system: HouseSystem,
|
||||
pub requested_system: HouseSystem,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fallback_reason: Option<String>,
|
||||
pub cusps: Vec<HouseCusp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AspectKind {
|
||||
Conjunction,
|
||||
Semisextile,
|
||||
Semisquare,
|
||||
Sextile,
|
||||
Quintile,
|
||||
Square,
|
||||
Trine,
|
||||
Sesquiquadrate,
|
||||
Biquintile,
|
||||
Quincunx,
|
||||
Opposition,
|
||||
}
|
||||
|
||||
impl AspectKind {
|
||||
const MAJOR: [AspectKind; 5] =
|
||||
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
|
||||
const MINOR: [AspectKind; 6] = [
|
||||
AspectKind::Semisextile,
|
||||
AspectKind::Semisquare,
|
||||
AspectKind::Quintile,
|
||||
AspectKind::Sesquiquadrate,
|
||||
AspectKind::Biquintile,
|
||||
AspectKind::Quincunx,
|
||||
];
|
||||
|
||||
pub fn angle(self) -> f64 {
|
||||
match self {
|
||||
AspectKind::Conjunction => 0.0,
|
||||
AspectKind::Semisextile => 30.0,
|
||||
AspectKind::Semisquare => 45.0,
|
||||
AspectKind::Sextile => 60.0,
|
||||
AspectKind::Quintile => 72.0,
|
||||
AspectKind::Square => 90.0,
|
||||
AspectKind::Trine => 120.0,
|
||||
AspectKind::Sesquiquadrate => 135.0,
|
||||
AspectKind::Biquintile => 144.0,
|
||||
AspectKind::Quincunx => 150.0,
|
||||
AspectKind::Opposition => 180.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_major(self) -> bool {
|
||||
Self::MAJOR.contains(&self)
|
||||
}
|
||||
|
||||
/// Traditional character of the aspect.
|
||||
pub fn nature(self) -> AspectNature {
|
||||
match self {
|
||||
AspectKind::Sextile | AspectKind::Trine | AspectKind::Quintile | AspectKind::Biquintile => {
|
||||
AspectNature::Harmonious
|
||||
}
|
||||
AspectKind::Square
|
||||
| AspectKind::Opposition
|
||||
| AspectKind::Semisquare
|
||||
| AspectKind::Sesquiquadrate
|
||||
| AspectKind::Quincunx => AspectNature::Challenging,
|
||||
AspectKind::Conjunction | AspectKind::Semisextile => AspectNature::Neutral,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default orb between two planets.
|
||||
fn base_orb(self) -> f64 {
|
||||
match self {
|
||||
AspectKind::Conjunction | AspectKind::Opposition => 8.0,
|
||||
AspectKind::Trine | AspectKind::Square => 7.0,
|
||||
AspectKind::Sextile => 5.0,
|
||||
AspectKind::Quincunx => 3.0,
|
||||
_ => 2.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Orb for a concrete pair of points.
|
||||
pub(crate) fn orb_for(self, a: PointId, b: PointId, multiplier: f64) -> f64 {
|
||||
let mut orb = self.base_orb();
|
||||
if a.is_luminary() || b.is_luminary() {
|
||||
orb += if self.is_major() { 2.0 } else { 1.0 };
|
||||
}
|
||||
if a.is_minor_point() || b.is_minor_point() {
|
||||
orb = orb.min(if self.is_major() { 4.0 } else { 1.0 });
|
||||
}
|
||||
orb * multiplier
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AspectNature {
|
||||
Harmonious,
|
||||
Challenging,
|
||||
Neutral,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Aspect {
|
||||
pub point1: PointId,
|
||||
pub point2: PointId,
|
||||
pub aspect: AspectKind,
|
||||
pub major: bool,
|
||||
/// Exact angle of the aspect (e.g. 120 for a trine).
|
||||
pub exact_angle: f64,
|
||||
/// Actual angular separation of the two points.
|
||||
pub separation: f64,
|
||||
/// Deviation from exactness, degrees.
|
||||
pub orb: f64,
|
||||
/// Maximum orb allowed for this pair.
|
||||
pub max_orb: f64,
|
||||
/// `true` = applying (getting tighter), `false` = separating.
|
||||
pub applying: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct OrbEntry {
|
||||
pub aspect: AspectKind,
|
||||
pub angle: f64,
|
||||
pub orb: f64,
|
||||
pub orb_with_luminary: f64,
|
||||
pub orb_with_minor_point: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Lot {
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
pub house: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Lots {
|
||||
/// Pars Fortunae: day = Asc + Moon - Sun, night = Asc + Sun - Moon.
|
||||
pub fortune: Lot,
|
||||
/// Pars Spiritus: day = Asc + Sun - Moon, night = Asc + Moon - Sun.
|
||||
pub spirit: Lot,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MoonPhaseName {
|
||||
NewMoon,
|
||||
WaxingCrescent,
|
||||
FirstQuarter,
|
||||
WaxingGibbous,
|
||||
FullMoon,
|
||||
WaningGibbous,
|
||||
LastQuarter,
|
||||
WaningCrescent,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct MoonPhase {
|
||||
/// Moon longitude minus Sun longitude, degrees `[0, 360)`.
|
||||
pub elongation: f64,
|
||||
/// One of the eight 45° lunation phases.
|
||||
pub phase: MoonPhaseName,
|
||||
/// Illuminated fraction of the Moon's disc (0..1).
|
||||
pub illumination: f64,
|
||||
pub waxing: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Sect {
|
||||
Day,
|
||||
Night,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Tally {
|
||||
pub count: usize,
|
||||
pub points: Vec<PointId>,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
fn add(&mut self, id: PointId) {
|
||||
self.count += 1;
|
||||
self.points.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct ElementTally {
|
||||
pub fire: Tally,
|
||||
pub earth: Tally,
|
||||
pub air: Tally,
|
||||
pub water: Tally,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct ModalityTally {
|
||||
pub cardinal: Tally,
|
||||
pub fixed: Tally,
|
||||
pub mutable: Tally,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct HemisphereTally {
|
||||
pub above_horizon: Tally,
|
||||
pub below_horizon: Tally,
|
||||
pub eastern: Tally,
|
||||
pub western: Tally,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RulerInfo {
|
||||
pub planet: PointId,
|
||||
pub sign: ZodiacSign,
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ChartRuler {
|
||||
pub ascendant_sign: ZodiacSign,
|
||||
pub traditional: RulerInfo,
|
||||
pub modern: RulerInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Summary {
|
||||
/// Counted over the ten planets (Sun..Pluto).
|
||||
pub elements: ElementTally,
|
||||
pub modalities: ModalityTally,
|
||||
pub hemispheres: Option<HemisphereTally>,
|
||||
pub sect: Option<Sect>,
|
||||
pub chart_ruler: Option<ChartRuler>,
|
||||
pub retrograde: Vec<PointId>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Astronomy {
|
||||
pub julian_day_ut: f64,
|
||||
pub julian_day_tt: f64,
|
||||
pub delta_t_seconds: f64,
|
||||
/// Greenwich apparent sidereal time.
|
||||
pub greenwich_sidereal_time: f64,
|
||||
pub greenwich_sidereal_time_hms: String,
|
||||
/// Local apparent sidereal time.
|
||||
pub local_sidereal_time: f64,
|
||||
pub local_sidereal_time_hms: String,
|
||||
pub obliquity: Obliquity,
|
||||
/// Ayanamsa in degrees (sidereal zodiac only).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ayanamsa: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Settings {
|
||||
#[serde(flatten)]
|
||||
pub options: ChartOptions,
|
||||
pub orbs: Vec<OrbEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct NatalChart {
|
||||
pub settings: Settings,
|
||||
pub astronomy: Astronomy,
|
||||
pub points: Vec<Point>,
|
||||
pub angles: Option<Angles>,
|
||||
pub houses: Option<Houses>,
|
||||
pub aspects: Vec<Aspect>,
|
||||
pub lots: Option<Lots>,
|
||||
pub moon_phase: MoonPhase,
|
||||
pub summary: Summary,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Builds a complete natal chart.
|
||||
pub fn calculate_chart(engine: &dyn Ephemeris, input: &ChartInput) -> Result<NatalChart, EngineError> {
|
||||
let opts = input.options;
|
||||
let jd = input.jd_ut;
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
let sidereal = (opts.zodiac == ZodiacType::Sidereal).then_some(opts.ayanamsa);
|
||||
let frame = Frame { sidereal, topocentric: opts.topocentric.then_some(input.observer) };
|
||||
|
||||
// --- astronomy -----------------------------------------------------------
|
||||
let delta_t = engine.delta_t(jd);
|
||||
let obliquity = engine.obliquity(jd)?;
|
||||
let gast = engine.sidereal_time(jd);
|
||||
let last = (gast + input.observer.longitude / 15.0).rem_euclid(24.0);
|
||||
let astronomy = Astronomy {
|
||||
julian_day_ut: jd,
|
||||
julian_day_tt: jd + delta_t,
|
||||
delta_t_seconds: delta_t * 86_400.0,
|
||||
greenwich_sidereal_time: gast,
|
||||
greenwich_sidereal_time_hms: angle::hms(gast),
|
||||
local_sidereal_time: last,
|
||||
local_sidereal_time_hms: angle::hms(last),
|
||||
obliquity,
|
||||
ayanamsa: sidereal.map(|a| engine.ayanamsa(jd, a)).transpose()?,
|
||||
};
|
||||
|
||||
// --- houses and angles ---------------------------------------------------
|
||||
let house_result = if input.time_known {
|
||||
let h = engine.houses(jd, &input.observer, opts.house_system, &frame)?;
|
||||
if let Some(reason) = &h.fallback_reason {
|
||||
warnings.push(format!("{reason}; {:?} houses were used instead", h.used));
|
||||
}
|
||||
Some(h)
|
||||
} else {
|
||||
warnings.push(
|
||||
"Birth time unknown: the chart is calculated for 12:00 local time; houses, angles and lots are omitted \
|
||||
and the Moon may be off by up to ±7°."
|
||||
.into(),
|
||||
);
|
||||
None
|
||||
};
|
||||
|
||||
// --- bodies --------------------------------------------------------------
|
||||
let node_body = match opts.node_type {
|
||||
NodeType::True => Body::TrueNode,
|
||||
NodeType::Mean => Body::MeanNode,
|
||||
};
|
||||
let lilith_body = match opts.lilith_type {
|
||||
LilithType::Mean => Body::MeanLilith,
|
||||
LilithType::True => Body::TrueLilith,
|
||||
};
|
||||
let mut bodies: Vec<Body> = Body::PLANETS.to_vec();
|
||||
bodies.extend([node_body, lilith_body, Body::Chiron]);
|
||||
if opts.include_asteroids {
|
||||
bodies.extend(Body::ASTEROIDS);
|
||||
}
|
||||
|
||||
let mut points = Vec::with_capacity(bodies.len() + 1);
|
||||
let mut degraded = Vec::new();
|
||||
for body in bodies {
|
||||
let state = match engine.position(body, jd, &frame) {
|
||||
Ok(s) => s,
|
||||
// Chiron and the asteroids need data files that may not cover the date.
|
||||
Err(e) if matches!(body, Body::Chiron) || Body::ASTEROIDS.contains(&body) => {
|
||||
warnings.push(format!("{body:?} omitted: {e}"));
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if state.degraded_precision {
|
||||
degraded.push(format!("{body:?}"));
|
||||
}
|
||||
let point = make_point(body, &state, &obliquity, house_result.as_ref());
|
||||
let is_node = matches!(body, Body::TrueNode | Body::MeanNode);
|
||||
points.push(point);
|
||||
if is_node {
|
||||
points.push(south_node(points.last().expect("just pushed"), house_result.as_ref()));
|
||||
}
|
||||
}
|
||||
if !degraded.is_empty() {
|
||||
warnings.push(format!(
|
||||
"No ephemeris data file covers this date; reduced-precision analytical ephemeris used for: {}",
|
||||
degraded.join(", ")
|
||||
));
|
||||
}
|
||||
|
||||
// --- angles --------------------------------------------------------------
|
||||
let angles = house_result.as_ref().map(|h| Angles {
|
||||
ascendant: AnglePoint::new(h.ascendant, Some(h.ascendant_speed)),
|
||||
midheaven: AnglePoint::new(h.midheaven, Some(h.midheaven_speed)),
|
||||
descendant: AnglePoint::new(h.ascendant + 180.0, Some(h.ascendant_speed)),
|
||||
imum_coeli: AnglePoint::new(h.midheaven + 180.0, Some(h.midheaven_speed)),
|
||||
vertex: AnglePoint::new(h.vertex, Some(h.vertex_speed)),
|
||||
antivertex: AnglePoint::new(h.vertex + 180.0, Some(h.vertex_speed)),
|
||||
east_point: AnglePoint::new(h.equatorial_ascendant, None),
|
||||
armc: h.armc,
|
||||
});
|
||||
let houses = house_result.as_ref().map(|h| Houses {
|
||||
system: h.used,
|
||||
requested_system: h.requested,
|
||||
fallback_reason: h.fallback_reason.clone(),
|
||||
cusps: (0..12)
|
||||
.map(|i| HouseCusp {
|
||||
house: i as u8 + 1,
|
||||
position: ZodiacPosition::new(h.cusps[i]),
|
||||
size: angle::arc(h.cusps[i], h.cusps[(i + 1) % 12]),
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
|
||||
// --- aspects -------------------------------------------------------------
|
||||
let aspects = find_aspects(&aspect_points(&points, angles.as_ref()), opts.aspect_set, opts.orb_multiplier);
|
||||
|
||||
// --- sun / moon derived data --------------------------------------------
|
||||
let lon_of = |id: PointId| points.iter().find(|p| p.id == id).map(|p| p.position.longitude);
|
||||
let sun = lon_of(PointId::Sun).expect("sun is always calculated");
|
||||
let moon = lon_of(PointId::Moon).expect("moon is always calculated");
|
||||
|
||||
let elongation = normalize(moon - sun);
|
||||
let moon_phase = MoonPhase {
|
||||
elongation,
|
||||
phase: phase_name(elongation),
|
||||
illumination: engine.illumination(Body::Moon, jd)?,
|
||||
waxing: elongation < 180.0,
|
||||
};
|
||||
|
||||
let sect = house_result.as_ref().map(|h| if above_horizon(sun, h.ascendant) { Sect::Day } else { Sect::Night });
|
||||
let lots = house_result.as_ref().zip(sect).map(|(h, sect)| {
|
||||
let (fortune, spirit) = match sect {
|
||||
Sect::Day => (h.ascendant + moon - sun, h.ascendant + sun - moon),
|
||||
Sect::Night => (h.ascendant + sun - moon, h.ascendant + moon - sun),
|
||||
};
|
||||
let lot = |lon: f64| Lot { position: ZodiacPosition::new(lon), house: house_of(normalize(lon), &h.cusps) };
|
||||
Lots { fortune: lot(fortune), spirit: lot(spirit) }
|
||||
});
|
||||
|
||||
let summary = summarize(&points, house_result.as_ref(), sect);
|
||||
|
||||
Ok(NatalChart {
|
||||
settings: Settings { options: opts, orbs: orb_table(opts.aspect_set, opts.orb_multiplier) },
|
||||
astronomy,
|
||||
points,
|
||||
angles,
|
||||
houses,
|
||||
aspects,
|
||||
lots,
|
||||
moon_phase,
|
||||
summary,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
fn point_kind(body: Body) -> PointKind {
|
||||
match body {
|
||||
Body::Sun | Body::Moon => PointKind::Luminary,
|
||||
Body::MeanNode | Body::TrueNode => PointKind::LunarNode,
|
||||
Body::MeanLilith | Body::TrueLilith => PointKind::LunarApogee,
|
||||
Body::Chiron => PointKind::Centaur,
|
||||
Body::Ceres | Body::Pallas | Body::Juno | Body::Vesta => PointKind::Asteroid,
|
||||
_ => PointKind::Planet,
|
||||
}
|
||||
}
|
||||
|
||||
fn variant(body: Body) -> Option<&'static str> {
|
||||
match body {
|
||||
Body::TrueNode | Body::TrueLilith => Some("true"),
|
||||
Body::MeanNode | Body::MeanLilith => Some("mean"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn make_point(body: Body, s: &BodyState, obl: &Obliquity, houses: Option<&HouseResult>) -> Point {
|
||||
let position = ZodiacPosition::new(s.longitude);
|
||||
let sign = position.sign;
|
||||
Point {
|
||||
id: PointId::from_planet(body),
|
||||
kind: point_kind(body),
|
||||
variant: variant(body),
|
||||
house: houses.map(|h| house_of(s.longitude, &h.cusps)),
|
||||
position,
|
||||
latitude: s.latitude,
|
||||
distance_au: s.distance,
|
||||
speed: s.speed_longitude,
|
||||
retrograde: s.speed_longitude < 0.0,
|
||||
right_ascension: s.right_ascension,
|
||||
declination: s.declination,
|
||||
out_of_bounds: s.declination.abs() > obl.true_obliquity,
|
||||
dignities: body.is_planet().then(|| dignities(body, sign)),
|
||||
}
|
||||
}
|
||||
|
||||
/// South node: the point opposite the north node (antipodal on the sphere).
|
||||
fn south_node(north: &Point, houses: Option<&HouseResult>) -> Point {
|
||||
let lon = normalize(north.position.longitude + 180.0);
|
||||
Point {
|
||||
id: PointId::SouthNode,
|
||||
position: ZodiacPosition::new(lon),
|
||||
latitude: -north.latitude,
|
||||
right_ascension: normalize(north.right_ascension + 180.0),
|
||||
declination: -north.declination,
|
||||
house: houses.map(|h| house_of(lon, &h.cusps)),
|
||||
..north.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// House (1..=12) containing an ecliptic longitude.
|
||||
pub fn house_of(lon: f64, cusps: &[f64; 12]) -> u8 {
|
||||
for i in 0..12 {
|
||||
let start = cusps[i];
|
||||
let end = cusps[(i + 1) % 12];
|
||||
let width = angle::arc(start, end);
|
||||
if angle::arc(start, lon) < width {
|
||||
return i as u8 + 1;
|
||||
}
|
||||
}
|
||||
// Only reachable with degenerate cusps (all equal); fall back to house 1.
|
||||
1
|
||||
}
|
||||
|
||||
/// Whether an ecliptic point is above the horizon: houses 7..12 lie on the
|
||||
/// ecliptic arc from the descendant to the ascendant.
|
||||
fn above_horizon(lon: f64, ascendant: f64) -> bool {
|
||||
angle::arc(ascendant, lon) >= 180.0
|
||||
}
|
||||
|
||||
fn phase_name(elongation: f64) -> MoonPhaseName {
|
||||
use MoonPhaseName::*;
|
||||
[NewMoon, WaxingCrescent, FirstQuarter, WaxingGibbous, FullMoon, WaningGibbous, LastQuarter, WaningCrescent]
|
||||
[((elongation / 45.0).floor() as usize).min(7)]
|
||||
}
|
||||
|
||||
/// Points taking part in aspects as `(id, longitude, speed)`: everything but
|
||||
/// the asteroids and the south node (it mirrors the north node), plus the
|
||||
/// ascendant and the midheaven when known.
|
||||
pub(crate) fn aspect_points(points: &[Point], angles: Option<&Angles>) -> Vec<(PointId, f64, f64)> {
|
||||
let mut out: Vec<(PointId, f64, f64)> = points
|
||||
.iter()
|
||||
.filter(|p| !matches!(p.kind, PointKind::Asteroid) && p.id != PointId::SouthNode)
|
||||
.map(|p| (p.id, p.position.longitude, p.speed))
|
||||
.collect();
|
||||
if let Some(a) = angles {
|
||||
out.push((PointId::Ascendant, a.ascendant.position.longitude, a.ascendant.speed.unwrap_or(0.0)));
|
||||
out.push((PointId::Midheaven, a.midheaven.position.longitude, a.midheaven.speed.unwrap_or(0.0)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn aspect_kinds(set: AspectSet) -> Vec<AspectKind> {
|
||||
let mut kinds = AspectKind::MAJOR.to_vec();
|
||||
if set == AspectSet::Extended {
|
||||
kinds.extend(AspectKind::MINOR);
|
||||
}
|
||||
kinds
|
||||
}
|
||||
|
||||
pub(crate) fn orb_table(set: AspectSet, multiplier: f64) -> Vec<OrbEntry> {
|
||||
aspect_kinds(set)
|
||||
.into_iter()
|
||||
.map(|k| OrbEntry {
|
||||
aspect: k,
|
||||
angle: k.angle(),
|
||||
orb: k.orb_for(PointId::Mars, PointId::Venus, multiplier),
|
||||
orb_with_luminary: k.orb_for(PointId::Sun, PointId::Venus, multiplier),
|
||||
orb_with_minor_point: k.orb_for(PointId::NorthNode, PointId::Venus, multiplier),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The tightest aspect within orb between two points: `(kind, orb, max_orb)`.
|
||||
pub(crate) fn best_aspect(
|
||||
kinds: &[AspectKind],
|
||||
(id1, lon1): (PointId, f64),
|
||||
(id2, lon2): (PointId, f64),
|
||||
multiplier: f64,
|
||||
) -> Option<(AspectKind, f64, f64)> {
|
||||
let sep = separation(lon1, lon2);
|
||||
kinds
|
||||
.iter()
|
||||
.map(|&k| (k, (sep - k.angle()).abs(), k.orb_for(id1, id2, multiplier)))
|
||||
.filter(|&(_, orb, max)| orb <= max)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
}
|
||||
|
||||
/// Finds the tightest matching aspect for every pair of points.
|
||||
pub(crate) fn find_aspects(points: &[(PointId, f64, f64)], set: AspectSet, multiplier: f64) -> Vec<Aspect> {
|
||||
const DT: f64 = 1.0 / 1440.0; // one minute, in days
|
||||
let kinds = aspect_kinds(set);
|
||||
let mut out = Vec::new();
|
||||
for (i, &(id1, lon1, speed1)) in points.iter().enumerate() {
|
||||
for &(id2, lon2, speed2) in &points[i + 1..] {
|
||||
let sep = separation(lon1, lon2);
|
||||
let Some((kind, orb, max_orb)) = best_aspect(&kinds, (id1, lon1), (id2, lon2), multiplier) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let applying = (speed1 != 0.0 || speed2 != 0.0).then(|| {
|
||||
let later = separation(lon1 + speed1 * DT, lon2 + speed2 * DT);
|
||||
(later - kind.angle()).abs() < orb
|
||||
});
|
||||
out.push(Aspect {
|
||||
point1: id1,
|
||||
point2: id2,
|
||||
aspect: kind,
|
||||
major: kind.is_major(),
|
||||
exact_angle: kind.angle(),
|
||||
separation: sep,
|
||||
orb,
|
||||
max_orb,
|
||||
applying,
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.orb.total_cmp(&b.orb));
|
||||
out
|
||||
}
|
||||
|
||||
fn summarize(points: &[Point], houses: Option<&HouseResult>, sect: Option<Sect>) -> Summary {
|
||||
let mut elements = ElementTally::default();
|
||||
let mut modalities = ModalityTally::default();
|
||||
let mut hemispheres = houses.map(|_| HemisphereTally::default());
|
||||
|
||||
for p in points.iter().filter(|p| matches!(p.kind, PointKind::Luminary | PointKind::Planet)) {
|
||||
match p.position.sign.element() {
|
||||
Element::Fire => elements.fire.add(p.id),
|
||||
Element::Earth => elements.earth.add(p.id),
|
||||
Element::Air => elements.air.add(p.id),
|
||||
Element::Water => elements.water.add(p.id),
|
||||
}
|
||||
match p.position.sign.modality() {
|
||||
Modality::Cardinal => modalities.cardinal.add(p.id),
|
||||
Modality::Fixed => modalities.fixed.add(p.id),
|
||||
Modality::Mutable => modalities.mutable.add(p.id),
|
||||
}
|
||||
if let (Some(t), Some(h)) = (hemispheres.as_mut(), houses) {
|
||||
let lon = p.position.longitude;
|
||||
if above_horizon(lon, h.ascendant) {
|
||||
t.above_horizon.add(p.id)
|
||||
} else {
|
||||
t.below_horizon.add(p.id)
|
||||
}
|
||||
// Eastern half: from the MC through the ascendant to the IC.
|
||||
if angle::arc(h.midheaven, lon) < 180.0 { t.eastern.add(p.id) } else { t.western.add(p.id) }
|
||||
}
|
||||
}
|
||||
|
||||
let chart_ruler = houses.map(|h| {
|
||||
let asc_sign = ZodiacSign::from_longitude(h.ascendant);
|
||||
let info = |body: Body| {
|
||||
let id = PointId::from_planet(body);
|
||||
let p = points.iter().find(|p| p.id == id).expect("rulers are always calculated");
|
||||
RulerInfo { planet: id, sign: p.position.sign, house: p.house }
|
||||
};
|
||||
ChartRuler {
|
||||
ascendant_sign: asc_sign,
|
||||
traditional: info(asc_sign.traditional_ruler()),
|
||||
modern: info(asc_sign.modern_ruler()),
|
||||
}
|
||||
});
|
||||
|
||||
Summary {
|
||||
elements,
|
||||
modalities,
|
||||
hemispheres,
|
||||
sect,
|
||||
chart_ruler,
|
||||
retrograde: points
|
||||
.iter()
|
||||
.filter(|p| p.retrograde && !matches!(p.kind, PointKind::LunarNode | PointKind::LunarApogee))
|
||||
.map(|p| p.id)
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn house_lookup_wraps_around_aries() {
|
||||
// Cusps crossing 0° Aries between house 3 and 4.
|
||||
let cusps = [270.0, 300.0, 330.0, 10.0, 40.0, 70.0, 90.0, 120.0, 150.0, 190.0, 220.0, 250.0];
|
||||
assert_eq!(house_of(275.0, &cusps), 1);
|
||||
assert_eq!(house_of(359.0, &cusps), 3);
|
||||
assert_eq!(house_of(5.0, &cusps), 3);
|
||||
assert_eq!(house_of(10.0, &cusps), 4);
|
||||
assert_eq!(house_of(269.9, &cusps), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizon_and_phase() {
|
||||
// Ascendant at 0° Aries: Cancer (90°) is below (IC side), Capricorn (270°) above.
|
||||
assert!(!above_horizon(90.0, 0.0));
|
||||
assert!(above_horizon(270.0, 0.0));
|
||||
assert_eq!(phase_name(0.0), MoonPhaseName::NewMoon);
|
||||
assert_eq!(phase_name(185.0), MoonPhaseName::FullMoon);
|
||||
assert_eq!(phase_name(359.9), MoonPhaseName::WaningCrescent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aspects_choose_tightest_and_detect_applying() {
|
||||
let pts = [
|
||||
(PointId::Sun, 10.0, 1.0),
|
||||
(PointId::Moon, 132.0, 13.0), // trine, orb 2, separation growing past 120
|
||||
(PointId::Mars, 100.5, 0.5), // square to Sun, orb 0.5
|
||||
];
|
||||
let aspects = find_aspects(&pts, AspectSet::Major, 1.0);
|
||||
let sun_mars = aspects.iter().find(|a| a.point2 == PointId::Mars && a.point1 == PointId::Sun).unwrap();
|
||||
assert_eq!(sun_mars.aspect, AspectKind::Square);
|
||||
assert!((sun_mars.orb - 0.5).abs() < 1e-9);
|
||||
assert_eq!(sun_mars.applying, Some(true)); // faster Sun closes the 90.5° gap
|
||||
let sun_moon = aspects.iter().find(|a| a.point2 == PointId::Moon).unwrap();
|
||||
assert_eq!(sun_moon.aspect, AspectKind::Trine);
|
||||
assert_eq!(sun_moon.applying, Some(false));
|
||||
// sorted by orb
|
||||
assert!(aspects.windows(2).all(|w| w[0].orb <= w[1].orb));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minor_points_get_small_orbs() {
|
||||
assert_eq!(AspectKind::Conjunction.orb_for(PointId::Sun, PointId::Moon, 1.0), 10.0);
|
||||
assert_eq!(AspectKind::Conjunction.orb_for(PointId::Sun, PointId::NorthNode, 1.0), 4.0);
|
||||
assert_eq!(AspectKind::Quincunx.orb_for(PointId::Mars, PointId::Lilith, 1.0), 1.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The replaceable astronomical backend.
|
||||
//!
|
||||
//! Everything the chart logic needs from an ephemeris is behind the
|
||||
//! [`Ephemeris`] trait. A new engine (e.g. one based on JPL DE440 in pure Rust)
|
||||
//! only has to implement this trait.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::types::{Ayanamsa, Body, HouseSystem};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
#[error("{0}")]
|
||||
Calculation(String),
|
||||
#[error("ephemeris engine is not available: {0}")]
|
||||
Unavailable(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, EngineError>;
|
||||
|
||||
/// Geographic observer position.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
|
||||
pub struct GeoPosition {
|
||||
/// Degrees, north positive.
|
||||
pub latitude: f64,
|
||||
/// Degrees, east positive.
|
||||
pub longitude: f64,
|
||||
/// Meters above sea level.
|
||||
pub elevation: f64,
|
||||
}
|
||||
|
||||
/// Reference frame of ecliptic positions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Frame {
|
||||
/// `None` = tropical zodiac, `Some` = sidereal zodiac with this ayanamsa.
|
||||
pub sidereal: Option<Ayanamsa>,
|
||||
/// `Some` = topocentric positions for this observer, `None` = geocentric.
|
||||
pub topocentric: Option<GeoPosition>,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
pub const TROPICAL_GEOCENTRIC: Frame = Frame { sidereal: None, topocentric: None };
|
||||
}
|
||||
|
||||
/// Position and motion of a body.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BodyState {
|
||||
/// Ecliptic longitude, degrees `[0, 360)`.
|
||||
pub longitude: f64,
|
||||
/// Ecliptic latitude, degrees.
|
||||
pub latitude: f64,
|
||||
/// Distance in AU.
|
||||
pub distance: f64,
|
||||
/// Daily motion in longitude, degrees/day (negative = retrograde).
|
||||
pub speed_longitude: f64,
|
||||
pub speed_latitude: f64,
|
||||
pub speed_distance: f64,
|
||||
/// Right ascension (equator of date), degrees.
|
||||
pub right_ascension: f64,
|
||||
/// Declination (equator of date), degrees.
|
||||
pub declination: f64,
|
||||
/// The engine had to fall back to a less precise method (e.g. a data file
|
||||
/// does not cover the date).
|
||||
pub degraded_precision: bool,
|
||||
}
|
||||
|
||||
/// House cusps and angles.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct HouseResult {
|
||||
pub requested: HouseSystem,
|
||||
/// System actually used (differs from `requested` when the requested one is
|
||||
/// undefined at the given latitude and the engine fell back).
|
||||
pub used: HouseSystem,
|
||||
pub fallback_reason: Option<String>,
|
||||
/// Cusps of houses 1..=12, degrees.
|
||||
pub cusps: [f64; 12],
|
||||
pub ascendant: f64,
|
||||
pub midheaven: f64,
|
||||
/// Right ascension of the MC (sidereal time in degrees).
|
||||
pub armc: f64,
|
||||
pub vertex: f64,
|
||||
pub equatorial_ascendant: f64,
|
||||
pub co_ascendant_koch: f64,
|
||||
pub co_ascendant_munkasey: f64,
|
||||
pub polar_ascendant: f64,
|
||||
/// Daily motion of the ascendant / MC / vertex, degrees/day.
|
||||
pub ascendant_speed: f64,
|
||||
pub midheaven_speed: f64,
|
||||
pub vertex_speed: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
|
||||
pub struct Obliquity {
|
||||
/// True obliquity of the ecliptic (with nutation), degrees.
|
||||
pub true_obliquity: f64,
|
||||
pub mean_obliquity: f64,
|
||||
/// Nutation in longitude, degrees.
|
||||
pub nutation_longitude: f64,
|
||||
/// Nutation in obliquity, degrees.
|
||||
pub nutation_obliquity: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct EphemerisInfo {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
/// Years covered with full precision (data files), if limited.
|
||||
pub precise_years: Option<(i32, i32)>,
|
||||
pub license: String,
|
||||
}
|
||||
|
||||
pub trait Ephemeris: Send + Sync {
|
||||
fn info(&self) -> EphemerisInfo;
|
||||
|
||||
/// Delta T (TT - UT) in days.
|
||||
fn delta_t(&self, jd_ut: f64) -> f64;
|
||||
|
||||
/// Greenwich apparent sidereal time, hours.
|
||||
fn sidereal_time(&self, jd_ut: f64) -> f64;
|
||||
|
||||
fn obliquity(&self, jd_ut: f64) -> Result<Obliquity>;
|
||||
|
||||
fn position(&self, body: Body, jd_ut: f64, frame: &Frame) -> Result<BodyState>;
|
||||
|
||||
fn houses(&self, jd_ut: f64, observer: &GeoPosition, system: HouseSystem, frame: &Frame) -> Result<HouseResult>;
|
||||
|
||||
/// Illuminated fraction of the body's disc (0..1).
|
||||
fn illumination(&self, body: Body, jd_ut: f64) -> Result<f64>;
|
||||
|
||||
/// Ayanamsa value in degrees.
|
||||
fn ayanamsa(&self, jd_ut: f64, ayanamsa: Ayanamsa) -> Result<f64>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Natal chart calculation.
|
||||
//!
|
||||
//! The astronomical work is done by an [`Ephemeris`] implementation (currently
|
||||
//! Swiss Ephemeris, see [`swiss::SwissEphemeris`]); everything astrological on
|
||||
//! top of it (signs, houses, aspects, dignities, lots, summaries) lives in
|
||||
//! [`chart`] and is independent of the engine, so the engine can be replaced
|
||||
//! without touching the chart logic. [`synastry`] compares two charts.
|
||||
|
||||
pub mod angle;
|
||||
pub mod chart;
|
||||
pub mod engine;
|
||||
pub mod synastry;
|
||||
pub mod time;
|
||||
pub mod types;
|
||||
|
||||
#[cfg(feature = "swisseph")]
|
||||
pub mod swiss;
|
||||
|
||||
pub use chart::{ChartInput, ChartOptions, NatalChart, calculate_chart};
|
||||
pub use engine::{BodyState, EngineError, Ephemeris, EphemerisInfo, Frame, GeoPosition, HouseResult, Obliquity};
|
||||
pub use synastry::{Synastry, calculate_synastry};
|
||||
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
|
||||
@@ -0,0 +1,343 @@
|
||||
//! [`Ephemeris`] implementation backed by the Swiss Ephemeris C library.
|
||||
//!
|
||||
//! The C library keeps process-wide state (ephemeris path, sidereal mode,
|
||||
//! observer position, open files), so all calls go through one global lock.
|
||||
//! A chart needs a few dozen calls of microseconds each, so the lock is not a
|
||||
//! bottleneck for an HTTP service.
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::c_char;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
|
||||
use swisseph_sys as sys;
|
||||
|
||||
use crate::angle::normalize;
|
||||
use crate::engine::{
|
||||
BodyState, EngineError, Ephemeris, EphemerisInfo, Frame, GeoPosition, HouseResult, Obliquity, Result,
|
||||
};
|
||||
use crate::types::{Ayanamsa, Body, HouseSystem};
|
||||
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
static EPHE_PATH: OnceLock<PathBuf> = OnceLock::new();
|
||||
|
||||
pub struct SwissEphemeris {
|
||||
precise_years: Option<(i32, i32)>,
|
||||
version: String,
|
||||
}
|
||||
|
||||
impl SwissEphemeris {
|
||||
/// Initializes the library with the directory holding the `*.se1` files.
|
||||
/// The library is process-global: only one path can be used per process.
|
||||
pub fn new(ephe_dir: impl AsRef<Path>) -> Result<Self> {
|
||||
let dir = ephe_dir.as_ref().to_path_buf();
|
||||
if !dir.is_dir() {
|
||||
return Err(EngineError::Unavailable(format!("ephemeris directory {} does not exist", dir.display())));
|
||||
}
|
||||
let first = EPHE_PATH.get_or_init(|| dir.clone());
|
||||
if *first != dir {
|
||||
return Err(EngineError::Unavailable(format!(
|
||||
"Swiss Ephemeris already initialized with {}",
|
||||
first.display()
|
||||
)));
|
||||
}
|
||||
let c_path = CString::new(dir.to_string_lossy().as_bytes())
|
||||
.map_err(|_| EngineError::Unavailable("ephemeris path contains a NUL byte".into()))?;
|
||||
let version = {
|
||||
let _guard = lock();
|
||||
let mut buf = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: valid NUL-terminated path; buffers sized AS_MAXCH as required.
|
||||
unsafe {
|
||||
sys::swe_set_ephe_path(c_path.as_ptr());
|
||||
sys::swe_version(buf.as_mut_ptr());
|
||||
}
|
||||
c_string(&buf)
|
||||
};
|
||||
Ok(Self { precise_years: planet_file_coverage(&dir), version })
|
||||
}
|
||||
}
|
||||
|
||||
fn lock() -> MutexGuard<'static, ()> {
|
||||
// A panic while holding the lock cannot leave the C state inconsistent in
|
||||
// a way that matters for subsequent independent calls.
|
||||
LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
fn c_string(buf: &[c_char]) -> String {
|
||||
// SAFETY: the library always NUL-terminates within AS_MAXCH; the buffer is
|
||||
// zero-initialized so a terminator exists even if nothing was written.
|
||||
unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Year range covered by the planetary files (`sepl_18.se1` = 1800..2399,
|
||||
/// `seplm06.se1` = 600 BC..1 BC, ...).
|
||||
fn planet_file_coverage(dir: &Path) -> Option<(i32, i32)> {
|
||||
let mut range: Option<(i32, i32)> = None;
|
||||
for entry in std::fs::read_dir(dir).ok()?.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let Some(rest) = name.strip_prefix("sepl").and_then(|r| r.strip_suffix(".se1")) else { continue };
|
||||
let (negative, digits) = match rest.strip_prefix('m') {
|
||||
Some(d) => (true, d),
|
||||
None => (false, rest.trim_start_matches('_')),
|
||||
};
|
||||
let Ok(century) = digits.parse::<i32>() else { continue };
|
||||
let start = if negative { -century * 100 } else { century * 100 };
|
||||
let end = start + 599;
|
||||
range = Some(match range {
|
||||
Some((lo, hi)) => (lo.min(start), hi.max(end)),
|
||||
None => (start, end),
|
||||
});
|
||||
}
|
||||
range
|
||||
}
|
||||
|
||||
fn body_id(body: Body) -> i32 {
|
||||
match body {
|
||||
Body::Sun => sys::SE_SUN,
|
||||
Body::Moon => sys::SE_MOON,
|
||||
Body::Mercury => sys::SE_MERCURY,
|
||||
Body::Venus => sys::SE_VENUS,
|
||||
Body::Mars => sys::SE_MARS,
|
||||
Body::Jupiter => sys::SE_JUPITER,
|
||||
Body::Saturn => sys::SE_SATURN,
|
||||
Body::Uranus => sys::SE_URANUS,
|
||||
Body::Neptune => sys::SE_NEPTUNE,
|
||||
Body::Pluto => sys::SE_PLUTO,
|
||||
Body::MeanNode => sys::SE_MEAN_NODE,
|
||||
Body::TrueNode => sys::SE_TRUE_NODE,
|
||||
Body::MeanLilith => sys::SE_MEAN_APOG,
|
||||
Body::TrueLilith => sys::SE_OSCU_APOG,
|
||||
Body::Chiron => sys::SE_CHIRON,
|
||||
Body::Ceres => sys::SE_CERES,
|
||||
Body::Pallas => sys::SE_PALLAS,
|
||||
Body::Juno => sys::SE_JUNO,
|
||||
Body::Vesta => sys::SE_VESTA,
|
||||
}
|
||||
}
|
||||
|
||||
fn sid_mode(ayanamsa: Ayanamsa) -> i32 {
|
||||
match ayanamsa {
|
||||
Ayanamsa::Lahiri => sys::SE_SIDM_LAHIRI,
|
||||
Ayanamsa::FaganBradley => sys::SE_SIDM_FAGAN_BRADLEY,
|
||||
Ayanamsa::Raman => sys::SE_SIDM_RAMAN,
|
||||
Ayanamsa::Krishnamurti => sys::SE_SIDM_KRISHNAMURTI,
|
||||
Ayanamsa::DeLuce => sys::SE_SIDM_DELUCE,
|
||||
Ayanamsa::Yukteshwar => sys::SE_SIDM_YUKTESHWAR,
|
||||
Ayanamsa::TrueCitra => sys::SE_SIDM_TRUE_CITRA,
|
||||
Ayanamsa::GalacticCenter0Sag => sys::SE_SIDM_GALCENT_0SAG,
|
||||
}
|
||||
}
|
||||
|
||||
fn house_code(system: HouseSystem) -> u8 {
|
||||
match system {
|
||||
HouseSystem::Placidus => b'P',
|
||||
HouseSystem::Koch => b'K',
|
||||
HouseSystem::Porphyry => b'O',
|
||||
HouseSystem::Regiomontanus => b'R',
|
||||
HouseSystem::Campanus => b'C',
|
||||
HouseSystem::Equal => b'E',
|
||||
HouseSystem::WholeSign => b'W',
|
||||
HouseSystem::Alcabitius => b'B',
|
||||
HouseSystem::Morinus => b'M',
|
||||
HouseSystem::Topocentric => b'T',
|
||||
HouseSystem::Meridian => b'X',
|
||||
HouseSystem::Vehlow => b'V',
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the frame to the C library state and returns the matching flags.
|
||||
/// Must be called with the lock held.
|
||||
fn apply_frame(frame: &Frame) -> i32 {
|
||||
let mut flags = 0;
|
||||
if let Some(ayanamsa) = frame.sidereal {
|
||||
// SAFETY: plain value arguments.
|
||||
unsafe { sys::swe_set_sid_mode(sid_mode(ayanamsa), 0.0, 0.0) };
|
||||
flags |= sys::SEFLG_SIDEREAL;
|
||||
}
|
||||
if let Some(obs) = frame.topocentric {
|
||||
// SAFETY: plain value arguments.
|
||||
unsafe { sys::swe_set_topo(obs.longitude, obs.latitude, obs.elevation) };
|
||||
flags |= sys::SEFLG_TOPOCTR;
|
||||
}
|
||||
flags
|
||||
}
|
||||
|
||||
/// One `swe_calc_ut` call; returns the 6 result values and the returned flags.
|
||||
/// Must be called with the lock held.
|
||||
fn calc(jd_ut: f64, ipl: i32, flags: i32) -> Result<([f64; 6], i32)> {
|
||||
let mut xx = [0.0f64; 6];
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: xx has the 6 elements and serr the AS_MAXCH bytes the API requires.
|
||||
let ret = unsafe { sys::swe_calc_ut(jd_ut, ipl, flags, xx.as_mut_ptr(), serr.as_mut_ptr()) };
|
||||
if ret == sys::ERR {
|
||||
return Err(EngineError::Calculation(c_string(&serr)));
|
||||
}
|
||||
Ok((xx, ret))
|
||||
}
|
||||
|
||||
impl Ephemeris for SwissEphemeris {
|
||||
fn info(&self) -> EphemerisInfo {
|
||||
EphemerisInfo {
|
||||
name: "Swiss Ephemeris".into(),
|
||||
version: self.version.clone(),
|
||||
precise_years: self.precise_years,
|
||||
license: "AGPL-3.0 (or Swiss Ephemeris Professional License)".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn delta_t(&self, jd_ut: f64) -> f64 {
|
||||
let _guard = lock();
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: serr has AS_MAXCH bytes.
|
||||
unsafe { sys::swe_deltat_ex(jd_ut, sys::SEFLG_SWIEPH, serr.as_mut_ptr()) }
|
||||
}
|
||||
|
||||
fn sidereal_time(&self, jd_ut: f64) -> f64 {
|
||||
let _guard = lock();
|
||||
// SAFETY: plain value argument.
|
||||
unsafe { sys::swe_sidtime(jd_ut) }
|
||||
}
|
||||
|
||||
fn obliquity(&self, jd_ut: f64) -> Result<Obliquity> {
|
||||
let _guard = lock();
|
||||
let (xx, _) = calc(jd_ut, sys::SE_ECL_NUT, sys::SEFLG_SWIEPH)?;
|
||||
Ok(Obliquity {
|
||||
true_obliquity: xx[0],
|
||||
mean_obliquity: xx[1],
|
||||
nutation_longitude: xx[2],
|
||||
nutation_obliquity: xx[3],
|
||||
})
|
||||
}
|
||||
|
||||
fn position(&self, body: Body, jd_ut: f64, frame: &Frame) -> Result<BodyState> {
|
||||
let _guard = lock();
|
||||
let frame_flags = apply_frame(frame);
|
||||
let base = sys::SEFLG_SWIEPH | sys::SEFLG_SPEED;
|
||||
let ipl = body_id(body);
|
||||
|
||||
let (ecl, ret) = calc(jd_ut, ipl, base | frame_flags)?;
|
||||
// Equatorial coordinates are independent of the zodiac (no sidereal flag).
|
||||
let topo = frame_flags & sys::SEFLG_TOPOCTR;
|
||||
let (equ, _) = calc(jd_ut, ipl, base | topo | sys::SEFLG_EQUATORIAL)?;
|
||||
|
||||
Ok(BodyState {
|
||||
longitude: normalize(ecl[0]),
|
||||
latitude: ecl[1],
|
||||
distance: ecl[2],
|
||||
speed_longitude: ecl[3],
|
||||
speed_latitude: ecl[4],
|
||||
speed_distance: ecl[5],
|
||||
right_ascension: normalize(equ[0]),
|
||||
declination: equ[1],
|
||||
// The library silently switches to the Moshier ephemeris when no data
|
||||
// file covers the date.
|
||||
degraded_precision: ret & sys::SEFLG_MOSEPH != 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn houses(&self, jd_ut: f64, observer: &GeoPosition, system: HouseSystem, frame: &Frame) -> Result<HouseResult> {
|
||||
let _guard = lock();
|
||||
// Houses are always geocentric; only the zodiac matters here.
|
||||
let flags = apply_frame(&Frame { sidereal: frame.sidereal, topocentric: None });
|
||||
// 37 slots: large enough even for the Gauquelin sectors.
|
||||
let mut cusps = [0.0f64; 37];
|
||||
let mut ascmc = [0.0f64; 10];
|
||||
let mut cusp_speed = [0.0f64; 37];
|
||||
let mut ascmc_speed = [0.0f64; 10];
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: all buffers are at least as large as the API requires.
|
||||
let ret = unsafe {
|
||||
sys::swe_houses_ex2(
|
||||
jd_ut,
|
||||
flags,
|
||||
observer.latitude,
|
||||
observer.longitude,
|
||||
house_code(system) as i32,
|
||||
cusps.as_mut_ptr(),
|
||||
ascmc.as_mut_ptr(),
|
||||
cusp_speed.as_mut_ptr(),
|
||||
ascmc_speed.as_mut_ptr(),
|
||||
serr.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
// On failure (quadrant systems inside the polar circles) the library
|
||||
// returns ERR and fills the cusps with Porphyry houses.
|
||||
let (used, fallback_reason) = if ret == sys::ERR {
|
||||
let msg = c_string(&serr);
|
||||
let reason = if msg.is_empty() {
|
||||
format!("{system:?} houses are undefined at latitude {:.2}°", observer.latitude)
|
||||
} else {
|
||||
msg
|
||||
};
|
||||
(HouseSystem::Porphyry, Some(reason))
|
||||
} else {
|
||||
(system, None)
|
||||
};
|
||||
|
||||
let mut out = [0.0f64; 12];
|
||||
for (i, c) in out.iter_mut().enumerate() {
|
||||
*c = normalize(cusps[i + 1]);
|
||||
}
|
||||
Ok(HouseResult {
|
||||
requested: system,
|
||||
used,
|
||||
fallback_reason,
|
||||
cusps: out,
|
||||
ascendant: normalize(ascmc[0]),
|
||||
midheaven: normalize(ascmc[1]),
|
||||
armc: normalize(ascmc[2]),
|
||||
vertex: normalize(ascmc[3]),
|
||||
equatorial_ascendant: normalize(ascmc[4]),
|
||||
co_ascendant_koch: normalize(ascmc[5]),
|
||||
co_ascendant_munkasey: normalize(ascmc[6]),
|
||||
polar_ascendant: normalize(ascmc[7]),
|
||||
ascendant_speed: ascmc_speed[0],
|
||||
midheaven_speed: ascmc_speed[1],
|
||||
vertex_speed: ascmc_speed[3],
|
||||
})
|
||||
}
|
||||
|
||||
fn illumination(&self, body: Body, jd_ut: f64) -> Result<f64> {
|
||||
let _guard = lock();
|
||||
let mut attr = [0.0f64; 20];
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: attr has the 20 elements the API requires.
|
||||
let ret =
|
||||
unsafe { sys::swe_pheno_ut(jd_ut, body_id(body), sys::SEFLG_SWIEPH, attr.as_mut_ptr(), serr.as_mut_ptr()) };
|
||||
if ret == sys::ERR {
|
||||
return Err(EngineError::Calculation(c_string(&serr)));
|
||||
}
|
||||
Ok(attr[1])
|
||||
}
|
||||
|
||||
fn ayanamsa(&self, jd_ut: f64, ayanamsa: Ayanamsa) -> Result<f64> {
|
||||
let _guard = lock();
|
||||
let mut daya = 0.0f64;
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: plain values and buffers of the required size.
|
||||
let ret = unsafe {
|
||||
sys::swe_set_sid_mode(sid_mode(ayanamsa), 0.0, 0.0);
|
||||
sys::swe_get_ayanamsa_ex_ut(jd_ut, sys::SEFLG_SWIEPH, &mut daya, serr.as_mut_ptr())
|
||||
};
|
||||
if ret == sys::ERR {
|
||||
return Err(EngineError::Calculation(c_string(&serr)));
|
||||
}
|
||||
Ok(daya)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn coverage_from_file_names() {
|
||||
let dir = std::env::temp_dir().join(format!("swe-cov-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for f in ["sepl_18.se1", "sepl_12.se1", "semo_18.se1"] {
|
||||
std::fs::write(dir.join(f), b"").unwrap();
|
||||
}
|
||||
assert_eq!(planet_file_coverage(&dir), Some((1200, 2399)));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Relationship charts built from two natal charts: synastry (inter-chart
|
||||
//! aspects and house overlays) and the midpoint composite chart.
|
||||
//!
|
||||
//! Both charts must be calculated with the same [`ChartOptions`]; only
|
||||
//! `aspect_set` and `orb_multiplier` are read here.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::angle::{self, normalize, separation};
|
||||
use crate::chart::{
|
||||
Aspect, AspectKind, AspectNature, ChartOptions, HouseCusp, NatalChart, OrbEntry, PointId, ZodiacPosition,
|
||||
aspect_kinds, aspect_points, best_aspect, find_aspects, house_of, orb_table,
|
||||
};
|
||||
|
||||
/// Aspect between a point of the first chart and a point of the second.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct InterAspect {
|
||||
/// Point of the first person's chart.
|
||||
pub person1: PointId,
|
||||
/// Point of the second person's chart.
|
||||
pub person2: PointId,
|
||||
pub aspect: AspectKind,
|
||||
pub nature: AspectNature,
|
||||
pub major: bool,
|
||||
pub exact_angle: f64,
|
||||
pub separation: f64,
|
||||
/// Deviation from exactness, degrees.
|
||||
pub orb: f64,
|
||||
pub max_orb: f64,
|
||||
}
|
||||
|
||||
/// A point of one chart placed in the houses of the other.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct HouseOverlay {
|
||||
pub point: PointId,
|
||||
pub sign: crate::types::ZodiacSign,
|
||||
pub house: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct HouseOverlays {
|
||||
/// The first person's points in the second person's houses; `null` when
|
||||
/// the second person's birth time is unknown.
|
||||
pub person1_in_person2: Option<Vec<HouseOverlay>>,
|
||||
/// The second person's points in the first person's houses; `null` when
|
||||
/// the first person's birth time is unknown.
|
||||
pub person2_in_person1: Option<Vec<HouseOverlay>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct NatureTally {
|
||||
pub harmonious: usize,
|
||||
pub challenging: usize,
|
||||
pub neutral: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SynastrySummary {
|
||||
pub aspect_count: usize,
|
||||
/// Inter-chart aspects by character (harmonious: sextile, trine,
|
||||
/// quintile, biquintile; challenging: square, opposition, semisquare,
|
||||
/// sesquiquadrate, quincunx; neutral: conjunction, semisextile).
|
||||
pub by_nature: NatureTally,
|
||||
pub by_aspect: BTreeMap<AspectKind, usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CompositePoint {
|
||||
pub id: PointId,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
/// Composite house; `null` without composite houses.
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CompositeAngles {
|
||||
pub ascendant: ZodiacPosition,
|
||||
pub midheaven: ZodiacPosition,
|
||||
pub descendant: ZodiacPosition,
|
||||
pub imum_coeli: ZodiacPosition,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CompositeHouses {
|
||||
/// `midpoint_of_cusps`: each cusp is the midpoint of the two natal cusps.
|
||||
pub method: &'static str,
|
||||
pub cusps: Vec<HouseCusp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Composite {
|
||||
/// `midpoint`: every point is the nearer midpoint of the two natal points.
|
||||
pub method: &'static str,
|
||||
pub points: Vec<CompositePoint>,
|
||||
/// `null` unless both birth times are known.
|
||||
pub angles: Option<CompositeAngles>,
|
||||
/// `null` unless both birth times are known.
|
||||
pub houses: Option<CompositeHouses>,
|
||||
pub aspects: Vec<Aspect>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SynastrySettings {
|
||||
pub aspect_set: crate::types::AspectSet,
|
||||
pub orb_multiplier: f64,
|
||||
pub orbs: Vec<OrbEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Synastry {
|
||||
pub settings: SynastrySettings,
|
||||
/// Inter-chart aspects, tightest first.
|
||||
pub aspects: Vec<InterAspect>,
|
||||
pub house_overlays: HouseOverlays,
|
||||
pub summary: SynastrySummary,
|
||||
pub composite: Composite,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Compares two natal charts calculated with the same `options`.
|
||||
pub fn calculate_synastry(person1: &NatalChart, person2: &NatalChart, options: &ChartOptions) -> Synastry {
|
||||
let mut warnings = Vec::new();
|
||||
let aspects = inter_aspects(person1, person2, options);
|
||||
let house_overlays = HouseOverlays {
|
||||
person1_in_person2: overlays(person1, person2),
|
||||
person2_in_person1: overlays(person2, person1),
|
||||
};
|
||||
let (composite, composite_warning) = composite(person1, person2, options);
|
||||
warnings.extend(composite_warning);
|
||||
|
||||
let mut by_nature = NatureTally::default();
|
||||
let mut by_aspect = BTreeMap::new();
|
||||
for a in &aspects {
|
||||
match a.nature {
|
||||
AspectNature::Harmonious => by_nature.harmonious += 1,
|
||||
AspectNature::Challenging => by_nature.challenging += 1,
|
||||
AspectNature::Neutral => by_nature.neutral += 1,
|
||||
}
|
||||
*by_aspect.entry(a.aspect).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
Synastry {
|
||||
settings: SynastrySettings {
|
||||
aspect_set: options.aspect_set,
|
||||
orb_multiplier: options.orb_multiplier,
|
||||
orbs: orb_table(options.aspect_set, options.orb_multiplier),
|
||||
},
|
||||
summary: SynastrySummary { aspect_count: aspects.len(), by_nature, by_aspect },
|
||||
aspects,
|
||||
house_overlays,
|
||||
composite,
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every point of the first chart against every point of the second.
|
||||
fn inter_aspects(person1: &NatalChart, person2: &NatalChart, options: &ChartOptions) -> Vec<InterAspect> {
|
||||
let kinds = aspect_kinds(options.aspect_set);
|
||||
let points2 = aspect_points(&person2.points, person2.angles.as_ref());
|
||||
let mut out = Vec::new();
|
||||
for (id1, lon1, _) in aspect_points(&person1.points, person1.angles.as_ref()) {
|
||||
for &(id2, lon2, _) in &points2 {
|
||||
let Some((kind, orb, max_orb)) = best_aspect(&kinds, (id1, lon1), (id2, lon2), options.orb_multiplier)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
out.push(InterAspect {
|
||||
person1: id1,
|
||||
person2: id2,
|
||||
aspect: kind,
|
||||
nature: kind.nature(),
|
||||
major: kind.is_major(),
|
||||
exact_angle: kind.angle(),
|
||||
separation: separation(lon1, lon2),
|
||||
orb,
|
||||
max_orb,
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.orb.total_cmp(&b.orb));
|
||||
out
|
||||
}
|
||||
|
||||
fn cusps_of(chart: &NatalChart) -> Option<[f64; 12]> {
|
||||
let houses = chart.houses.as_ref()?;
|
||||
let mut cusps = [0.0; 12];
|
||||
for (c, h) in cusps.iter_mut().zip(&houses.cusps) {
|
||||
*c = h.position.longitude;
|
||||
}
|
||||
Some(cusps)
|
||||
}
|
||||
|
||||
/// The points of `guest` (planets, nodes, Lilith, Chiron, asteroids and the
|
||||
/// angles) in the houses of `host`.
|
||||
fn overlays(guest: &NatalChart, host: &NatalChart) -> Option<Vec<HouseOverlay>> {
|
||||
let cusps = cusps_of(host)?;
|
||||
let mut list: Vec<(PointId, f64)> = guest.points.iter().map(|p| (p.id, p.position.longitude)).collect();
|
||||
if let Some(a) = &guest.angles {
|
||||
list.push((PointId::Ascendant, a.ascendant.position.longitude));
|
||||
list.push((PointId::Midheaven, a.midheaven.position.longitude));
|
||||
}
|
||||
Some(
|
||||
list.into_iter()
|
||||
.map(|(point, lon)| HouseOverlay {
|
||||
point,
|
||||
sign: crate::types::ZodiacSign::from_longitude(lon),
|
||||
house: house_of(lon, &cusps),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Midpoint of two longitudes on the shorter arc between them.
|
||||
pub fn midpoint(a: f64, b: f64) -> f64 {
|
||||
let mut d = normalize(b - a);
|
||||
if d > 180.0 {
|
||||
d -= 360.0;
|
||||
}
|
||||
normalize(a + d / 2.0)
|
||||
}
|
||||
|
||||
/// Midpoints of the natal cusps, kept in zodiacal order: when two natal cusps
|
||||
/// are nearly opposite, the nearer midpoint may land on the wrong side, so a
|
||||
/// cusp that would lie more than 180° past its predecessor is flipped.
|
||||
/// Returns `None` when no consistent sequence exists.
|
||||
fn composite_cusps(c1: &[f64; 12], c2: &[f64; 12]) -> Option<[f64; 12]> {
|
||||
let mut cusps = [0.0; 12];
|
||||
for i in 0..12 {
|
||||
cusps[i] = midpoint(c1[i], c2[i]);
|
||||
}
|
||||
for i in 1..12 {
|
||||
if angle::arc(cusps[i - 1], cusps[i]) > 180.0 {
|
||||
cusps[i] = normalize(cusps[i] + 180.0);
|
||||
}
|
||||
}
|
||||
let total: f64 = (0..12).map(|i| angle::arc(cusps[i], cusps[(i + 1) % 12])).sum();
|
||||
((total - 360.0).abs() < 1e-6).then_some(cusps)
|
||||
}
|
||||
|
||||
fn composite(person1: &NatalChart, person2: &NatalChart, options: &ChartOptions) -> (Composite, Option<String>) {
|
||||
let mut warning = None;
|
||||
let cusps = match (cusps_of(person1), cusps_of(person2)) {
|
||||
(Some(c1), Some(c2)) => {
|
||||
let cusps = composite_cusps(&c1, &c2);
|
||||
if cusps.is_none() {
|
||||
warning =
|
||||
Some("The composite house cusps could not be put in order; composite houses are omitted.".into());
|
||||
}
|
||||
cusps
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let points: Vec<CompositePoint> = person1
|
||||
.points
|
||||
.iter()
|
||||
.filter_map(|p1| {
|
||||
let p2 = person2.points.iter().find(|p2| p2.id == p1.id)?;
|
||||
let lon = midpoint(p1.position.longitude, p2.position.longitude);
|
||||
Some(CompositePoint {
|
||||
id: p1.id,
|
||||
position: ZodiacPosition::new(lon),
|
||||
house: cusps.as_ref().map(|c| house_of(lon, c)),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let angles = cusps.map(|c| CompositeAngles {
|
||||
ascendant: ZodiacPosition::new(c[0]),
|
||||
midheaven: ZodiacPosition::new(c[9]),
|
||||
descendant: ZodiacPosition::new(c[0] + 180.0),
|
||||
imum_coeli: ZodiacPosition::new(c[9] + 180.0),
|
||||
});
|
||||
let houses = cusps.map(|c| CompositeHouses {
|
||||
method: "midpoint_of_cusps",
|
||||
cusps: (0..12)
|
||||
.map(|i| HouseCusp {
|
||||
house: i as u8 + 1,
|
||||
position: ZodiacPosition::new(c[i]),
|
||||
size: angle::arc(c[i], c[(i + 1) % 12]),
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
|
||||
// Same participants as natal aspects; composite points have no motion.
|
||||
let mut aspect_list: Vec<(PointId, f64, f64)> = points
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
!matches!(p.id, PointId::SouthNode | PointId::Ceres | PointId::Pallas | PointId::Juno | PointId::Vesta)
|
||||
})
|
||||
.map(|p| (p.id, p.position.longitude, 0.0))
|
||||
.collect();
|
||||
if let Some(a) = &angles {
|
||||
aspect_list.push((PointId::Ascendant, a.ascendant.longitude, 0.0));
|
||||
aspect_list.push((PointId::Midheaven, a.midheaven.longitude, 0.0));
|
||||
}
|
||||
let aspects = find_aspects(&aspect_list, options.aspect_set, options.orb_multiplier);
|
||||
|
||||
(Composite { method: "midpoint", points, angles, houses, aspects }, warning)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn midpoints_take_the_shorter_arc() {
|
||||
assert!((midpoint(10.0, 50.0) - 30.0).abs() < 1e-9);
|
||||
assert!((midpoint(350.0, 30.0) - 10.0).abs() < 1e-9);
|
||||
assert!((midpoint(30.0, 350.0) - 10.0).abs() < 1e-9);
|
||||
assert!((midpoint(100.0, 100.0) - 100.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composite_cusps_stay_in_order() {
|
||||
let c1 = [0.0, 30.0, 60.0, 90.0, 120.0, 150.0, 180.0, 210.0, 240.0, 270.0, 300.0, 330.0];
|
||||
// Nearly opposite second chart: some nearer midpoints fall on the far side.
|
||||
let c2 = c1.map(|c| normalize(c + 178.0 + if (120.0..300.0).contains(&c) { 4.0 } else { 0.0 }));
|
||||
let cusps = composite_cusps(&c1, &c2).expect("ordered");
|
||||
let total: f64 = (0..12).map(|i| angle::arc(cusps[i], cusps[(i + 1) % 12])).sum();
|
||||
assert!((total - 360.0).abs() < 1e-6);
|
||||
assert!((0..12).all(|i| angle::arc(cusps[i], cusps[(i + 1) % 12]) < 180.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Calendar and Julian Day helpers that do not depend on the ephemeris engine.
|
||||
|
||||
/// Julian Day of the Unix epoch (1970-01-01T00:00:00Z).
|
||||
const UNIX_EPOCH_JD: f64 = 2_440_587.5;
|
||||
|
||||
/// Julian Day (UT) for a Unix timestamp given in seconds.
|
||||
pub fn jd_from_unix_seconds(seconds: f64) -> f64 {
|
||||
UNIX_EPOCH_JD + seconds / 86_400.0
|
||||
}
|
||||
|
||||
/// Julian Day Number (at noon) of a Julian-calendar date.
|
||||
pub fn jdn_from_julian_calendar(year: i32, month: u32, day: u32) -> i64 {
|
||||
let a = (14 - month as i64) / 12;
|
||||
let y = year as i64 + 4800 - a;
|
||||
let m = month as i64 + 12 * a - 3;
|
||||
day as i64 + (153 * m + 2) / 5 + 365 * y + y.div_euclid(4) - 32083
|
||||
}
|
||||
|
||||
/// Proleptic Gregorian calendar date of a Julian Day Number.
|
||||
pub fn gregorian_from_jdn(jdn: i64) -> (i32, u32, u32) {
|
||||
let a = jdn + 32044;
|
||||
let b = (4 * a + 3).div_euclid(146_097);
|
||||
let c = a - (146_097 * b).div_euclid(4);
|
||||
let d = (4 * c + 3).div_euclid(1461);
|
||||
let e = c - (1461 * d).div_euclid(4);
|
||||
let m = (5 * e + 2).div_euclid(153);
|
||||
let day = e - (153 * m + 2).div_euclid(5) + 1;
|
||||
let month = m + 3 - 12 * m.div_euclid(10);
|
||||
let year = 100 * b + d - 4800 + m.div_euclid(10);
|
||||
(year as i32, month as u32, day as u32)
|
||||
}
|
||||
|
||||
/// Converts a Julian-calendar date (as recorded e.g. in Russia before 1918)
|
||||
/// to the proleptic Gregorian date of the same day.
|
||||
pub fn julian_to_gregorian(year: i32, month: u32, day: u32) -> (i32, u32, u32) {
|
||||
gregorian_from_jdn(jdn_from_julian_calendar(year, month, day))
|
||||
}
|
||||
|
||||
/// Validates a Julian-calendar date (every 4th year is a leap year).
|
||||
pub fn is_valid_julian_date(year: i32, month: u32, day: u32) -> bool {
|
||||
let leap = year.rem_euclid(4) == 0;
|
||||
let days = match month {
|
||||
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
|
||||
4 | 6 | 9 | 11 => 30,
|
||||
2 if leap => 29,
|
||||
2 => 28,
|
||||
_ => return false,
|
||||
};
|
||||
(1..=days).contains(&day)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unix_epoch() {
|
||||
assert_eq!(jd_from_unix_seconds(0.0), 2_440_587.5);
|
||||
// J2000.0 = 2000-01-01T12:00:00 = 946728000
|
||||
assert!((jd_from_unix_seconds(946_728_000.0) - 2_451_545.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn julian_calendar_conversion() {
|
||||
// Russian October Revolution: 25 Oct 1917 (Julian) = 7 Nov 1917 (Gregorian)
|
||||
assert_eq!(julian_to_gregorian(1917, 10, 25), (1917, 11, 7));
|
||||
// Last Julian day before the Gregorian reform: 4 Oct 1582 -> 14 Oct 1582
|
||||
assert_eq!(julian_to_gregorian(1582, 10, 4), (1582, 10, 14));
|
||||
assert!(is_valid_julian_date(1900, 2, 29));
|
||||
assert!(!is_valid_julian_date(1901, 2, 29));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Engine-independent astrological vocabulary.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A body or calculated point the ephemeris engine can compute.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Body {
|
||||
Sun,
|
||||
Moon,
|
||||
Mercury,
|
||||
Venus,
|
||||
Mars,
|
||||
Jupiter,
|
||||
Saturn,
|
||||
Uranus,
|
||||
Neptune,
|
||||
Pluto,
|
||||
MeanNode,
|
||||
TrueNode,
|
||||
/// Mean lunar apogee (Black Moon Lilith).
|
||||
MeanLilith,
|
||||
/// Osculating lunar apogee ("true" Lilith).
|
||||
TrueLilith,
|
||||
Chiron,
|
||||
Ceres,
|
||||
Pallas,
|
||||
Juno,
|
||||
Vesta,
|
||||
}
|
||||
|
||||
impl Body {
|
||||
pub const PLANETS: [Body; 10] = [
|
||||
Body::Sun,
|
||||
Body::Moon,
|
||||
Body::Mercury,
|
||||
Body::Venus,
|
||||
Body::Mars,
|
||||
Body::Jupiter,
|
||||
Body::Saturn,
|
||||
Body::Uranus,
|
||||
Body::Neptune,
|
||||
Body::Pluto,
|
||||
];
|
||||
pub const ASTEROIDS: [Body; 4] = [Body::Ceres, Body::Pallas, Body::Juno, Body::Vesta];
|
||||
|
||||
pub fn is_luminary(self) -> bool {
|
||||
matches!(self, Body::Sun | Body::Moon)
|
||||
}
|
||||
|
||||
pub fn is_planet(self) -> bool {
|
||||
Self::PLANETS.contains(&self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum NodeType {
|
||||
#[default]
|
||||
True,
|
||||
Mean,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum LilithType {
|
||||
#[default]
|
||||
Mean,
|
||||
True,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ZodiacType {
|
||||
#[default]
|
||||
Tropical,
|
||||
Sidereal,
|
||||
}
|
||||
|
||||
/// Sidereal zodiac reference (ayanamsa).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Ayanamsa {
|
||||
#[default]
|
||||
Lahiri,
|
||||
FaganBradley,
|
||||
Raman,
|
||||
Krishnamurti,
|
||||
DeLuce,
|
||||
Yukteshwar,
|
||||
TrueCitra,
|
||||
GalacticCenter0Sag,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AspectSet {
|
||||
/// Conjunction, sextile, square, trine, opposition.
|
||||
#[default]
|
||||
Major,
|
||||
/// Major aspects plus semisextile, semisquare, quintile, sesquiquadrate, biquintile, quincunx.
|
||||
Extended,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum HouseSystem {
|
||||
#[default]
|
||||
Placidus,
|
||||
Koch,
|
||||
Porphyry,
|
||||
Regiomontanus,
|
||||
Campanus,
|
||||
Equal,
|
||||
WholeSign,
|
||||
Alcabitius,
|
||||
Morinus,
|
||||
Topocentric,
|
||||
Meridian,
|
||||
Vehlow,
|
||||
}
|
||||
|
||||
impl HouseSystem {
|
||||
pub const ALL: [HouseSystem; 12] = [
|
||||
HouseSystem::Placidus,
|
||||
HouseSystem::Koch,
|
||||
HouseSystem::Porphyry,
|
||||
HouseSystem::Regiomontanus,
|
||||
HouseSystem::Campanus,
|
||||
HouseSystem::Equal,
|
||||
HouseSystem::WholeSign,
|
||||
HouseSystem::Alcabitius,
|
||||
HouseSystem::Morinus,
|
||||
HouseSystem::Topocentric,
|
||||
HouseSystem::Meridian,
|
||||
HouseSystem::Vehlow,
|
||||
];
|
||||
|
||||
/// Quadrant systems that are undefined inside the polar circles.
|
||||
pub fn fails_at_polar_latitudes(self) -> bool {
|
||||
matches!(self, HouseSystem::Placidus | HouseSystem::Koch | HouseSystem::Topocentric)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Element {
|
||||
Fire,
|
||||
Earth,
|
||||
Air,
|
||||
Water,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Modality {
|
||||
Cardinal,
|
||||
Fixed,
|
||||
Mutable,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ZodiacSign {
|
||||
Aries,
|
||||
Taurus,
|
||||
Gemini,
|
||||
Cancer,
|
||||
Leo,
|
||||
Virgo,
|
||||
Libra,
|
||||
Scorpio,
|
||||
Sagittarius,
|
||||
Capricorn,
|
||||
Aquarius,
|
||||
Pisces,
|
||||
}
|
||||
|
||||
impl ZodiacSign {
|
||||
pub const ALL: [ZodiacSign; 12] = [
|
||||
ZodiacSign::Aries,
|
||||
ZodiacSign::Taurus,
|
||||
ZodiacSign::Gemini,
|
||||
ZodiacSign::Cancer,
|
||||
ZodiacSign::Leo,
|
||||
ZodiacSign::Virgo,
|
||||
ZodiacSign::Libra,
|
||||
ZodiacSign::Scorpio,
|
||||
ZodiacSign::Sagittarius,
|
||||
ZodiacSign::Capricorn,
|
||||
ZodiacSign::Aquarius,
|
||||
ZodiacSign::Pisces,
|
||||
];
|
||||
|
||||
/// Sign at an ecliptic longitude.
|
||||
pub fn from_longitude(lon: f64) -> ZodiacSign {
|
||||
let idx = (crate::angle::normalize(lon) / 30.0).floor() as usize;
|
||||
Self::ALL[idx.min(11)]
|
||||
}
|
||||
|
||||
pub fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
|
||||
pub fn element(self) -> Element {
|
||||
[Element::Fire, Element::Earth, Element::Air, Element::Water][self.index() % 4]
|
||||
}
|
||||
|
||||
pub fn modality(self) -> Modality {
|
||||
[Modality::Cardinal, Modality::Fixed, Modality::Mutable][self.index() % 3]
|
||||
}
|
||||
|
||||
pub fn opposite(self) -> ZodiacSign {
|
||||
Self::ALL[(self.index() + 6) % 12]
|
||||
}
|
||||
|
||||
/// Traditional (pre-telescopic) ruler.
|
||||
pub fn traditional_ruler(self) -> Body {
|
||||
use ZodiacSign::*;
|
||||
match self {
|
||||
Aries | Scorpio => Body::Mars,
|
||||
Taurus | Libra => Body::Venus,
|
||||
Gemini | Virgo => Body::Mercury,
|
||||
Cancer => Body::Moon,
|
||||
Leo => Body::Sun,
|
||||
Sagittarius | Pisces => Body::Jupiter,
|
||||
Capricorn | Aquarius => Body::Saturn,
|
||||
}
|
||||
}
|
||||
|
||||
/// Modern ruler (outer planets for Scorpio, Aquarius, Pisces).
|
||||
pub fn modern_ruler(self) -> Body {
|
||||
match self {
|
||||
ZodiacSign::Scorpio => Body::Pluto,
|
||||
ZodiacSign::Aquarius => Body::Uranus,
|
||||
ZodiacSign::Pisces => Body::Neptune,
|
||||
other => other.traditional_ruler(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Essential dignity of a planet in a sign.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Dignity {
|
||||
Domicile,
|
||||
Exaltation,
|
||||
Detriment,
|
||||
Fall,
|
||||
}
|
||||
|
||||
/// Signs ruled by a planet (traditional and modern rulerships combined).
|
||||
fn domiciles(body: Body) -> &'static [ZodiacSign] {
|
||||
use ZodiacSign::*;
|
||||
match body {
|
||||
Body::Sun => &[Leo],
|
||||
Body::Moon => &[Cancer],
|
||||
Body::Mercury => &[Gemini, Virgo],
|
||||
Body::Venus => &[Taurus, Libra],
|
||||
Body::Mars => &[Aries, Scorpio],
|
||||
Body::Jupiter => &[Sagittarius, Pisces],
|
||||
Body::Saturn => &[Capricorn, Aquarius],
|
||||
Body::Uranus => &[Aquarius],
|
||||
Body::Neptune => &[Pisces],
|
||||
Body::Pluto => &[Scorpio],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Traditional exaltations (outer planets have no generally accepted one).
|
||||
fn exaltation(body: Body) -> Option<ZodiacSign> {
|
||||
use ZodiacSign::*;
|
||||
match body {
|
||||
Body::Sun => Some(Aries),
|
||||
Body::Moon => Some(Taurus),
|
||||
Body::Mercury => Some(Virgo),
|
||||
Body::Venus => Some(Pisces),
|
||||
Body::Mars => Some(Capricorn),
|
||||
Body::Jupiter => Some(Cancer),
|
||||
Body::Saturn => Some(Libra),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// All essential dignities/debilities of `body` in `sign`.
|
||||
pub fn dignities(body: Body, sign: ZodiacSign) -> Vec<Dignity> {
|
||||
let mut out = Vec::new();
|
||||
let homes = domiciles(body);
|
||||
if homes.contains(&sign) {
|
||||
out.push(Dignity::Domicile);
|
||||
}
|
||||
if exaltation(body) == Some(sign) {
|
||||
out.push(Dignity::Exaltation);
|
||||
}
|
||||
if homes.iter().any(|s| s.opposite() == sign) {
|
||||
out.push(Dignity::Detriment);
|
||||
}
|
||||
if exaltation(body).map(ZodiacSign::opposite) == Some(sign) {
|
||||
out.push(Dignity::Fall);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sign_properties() {
|
||||
assert_eq!(ZodiacSign::from_longitude(0.0), ZodiacSign::Aries);
|
||||
assert_eq!(ZodiacSign::from_longitude(359.999), ZodiacSign::Pisces);
|
||||
assert_eq!(ZodiacSign::from_longitude(-0.5), ZodiacSign::Pisces);
|
||||
assert_eq!(ZodiacSign::Leo.element(), Element::Fire);
|
||||
assert_eq!(ZodiacSign::Capricorn.modality(), Modality::Cardinal);
|
||||
assert_eq!(ZodiacSign::Pisces.modality(), Modality::Mutable);
|
||||
assert_eq!(ZodiacSign::Scorpio.traditional_ruler(), Body::Mars);
|
||||
assert_eq!(ZodiacSign::Scorpio.modern_ruler(), Body::Pluto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dignity_table() {
|
||||
assert_eq!(dignities(Body::Mercury, ZodiacSign::Virgo), vec![Dignity::Domicile, Dignity::Exaltation]);
|
||||
assert_eq!(dignities(Body::Sun, ZodiacSign::Libra), vec![Dignity::Fall]);
|
||||
assert_eq!(dignities(Body::Venus, ZodiacSign::Virgo), vec![Dignity::Fall]);
|
||||
assert_eq!(dignities(Body::Mars, ZodiacSign::Libra), vec![Dignity::Detriment]);
|
||||
assert!(dignities(Body::Jupiter, ZodiacSign::Leo).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Checks the Rust bindings against reference values produced by the upstream
|
||||
//! `swetest` program (built from the same vendored sources), e.g.
|
||||
//! `swetest -b14.7.1985 -ut12:30 -p0123456789tAD -fPls -house19.0402,47.4979,P`.
|
||||
//!
|
||||
//! Requires the ephemeris files from `scripts/fetch-deps.sh` (data/ephe).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use astro_engine::chart::{AspectKind, PointId, Sect};
|
||||
use astro_engine::swiss::SwissEphemeris;
|
||||
use astro_engine::{Body, ChartInput, ChartOptions, Ephemeris, Frame, GeoPosition, HouseSystem, calculate_chart};
|
||||
|
||||
/// 1985-07-14 12:30 UT
|
||||
const JD: f64 = 2_446_261.020_833_333_5;
|
||||
const BUDAPEST: GeoPosition = GeoPosition { latitude: 47.4979, longitude: 19.0402, elevation: 0.0 };
|
||||
|
||||
fn engine() -> &'static SwissEphemeris {
|
||||
static ENGINE: OnceLock<SwissEphemeris> = OnceLock::new();
|
||||
ENGINE.get_or_init(|| {
|
||||
let dir = std::env::var_os("ASTRO_EPHE_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../data/ephe"));
|
||||
SwissEphemeris::new(dir).expect("ephemeris files (run scripts/fetch-deps.sh)")
|
||||
})
|
||||
}
|
||||
|
||||
fn close(actual: f64, expected: f64, tol: f64) -> bool {
|
||||
(actual - expected).abs() <= tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_positions_match_swetest() {
|
||||
let expected = [
|
||||
(Body::Sun, 112.0007251, 0.9541281),
|
||||
(Body::Moon, 71.1646551, 12.2200994),
|
||||
(Body::Mercury, 138.5356993, 0.9265284),
|
||||
(Body::Venus, 68.8767351, 1.0967944),
|
||||
(Body::Mars, 113.0940242, 0.6506060),
|
||||
(Body::Jupiter, 314.6149088, -0.1098597),
|
||||
(Body::Saturn, 231.5708687, -0.0181844),
|
||||
(Body::Uranus, 254.5844730, -0.0296575),
|
||||
(Body::Neptune, 271.6955376, -0.0248706),
|
||||
(Body::Pluto, 211.9256159, 0.0012526),
|
||||
(Body::TrueNode, 46.1491385, -0.0664496),
|
||||
(Body::MeanLilith, 34.7361561, 0.1108111),
|
||||
(Body::Chiron, 72.1761740, 0.0654425),
|
||||
];
|
||||
for (body, lon, speed) in expected {
|
||||
let s = engine().position(body, JD, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
assert!(close(s.longitude, lon, 1e-6), "{body:?} longitude {} != {lon}", s.longitude);
|
||||
assert!(close(s.speed_longitude, speed, 1e-6), "{body:?} speed {} != {speed}", s.speed_longitude);
|
||||
assert!(!s.degraded_precision, "{body:?} should come from the data files");
|
||||
}
|
||||
let sun = engine().position(Body::Sun, JD, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
assert!(close(sun.distance, 1.016507864, 1e-8));
|
||||
assert!(close(sun.declination, 21.6455828, 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sun_at_j2000() {
|
||||
// Textbook value: apparent solar longitude at 2000-01-01 12:00 UT = 280.3689°
|
||||
let s = engine().position(Body::Sun, 2_451_545.0, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
assert!(close(s.longitude, 280.3689187, 1e-6), "{}", s.longitude);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placidus_houses_match_swetest() {
|
||||
let h = engine().houses(JD, &BUDAPEST, HouseSystem::Placidus, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
let cusps = [
|
||||
215.9678137,
|
||||
244.3181228,
|
||||
278.8086642,
|
||||
316.4009907,
|
||||
349.5231422,
|
||||
15.5954622,
|
||||
35.9678137,
|
||||
64.3181228,
|
||||
98.8086642,
|
||||
136.4009907,
|
||||
169.5231422,
|
||||
195.5954622,
|
||||
];
|
||||
for (i, (a, e)) in h.cusps.iter().zip(cusps).enumerate() {
|
||||
assert!(close(*a, e, 1e-6), "cusp {} {a} != {e}", i + 1);
|
||||
}
|
||||
assert_eq!(h.used, HouseSystem::Placidus);
|
||||
assert!(close(h.ascendant, 215.9678137, 1e-6));
|
||||
assert!(close(h.midheaven, 136.4009907, 1e-6));
|
||||
assert!(close(h.armc, 138.8578266, 1e-6));
|
||||
assert!(close(h.vertex, 72.3891351, 1e-6));
|
||||
assert!(close(h.equatorial_ascendant, 231.2864612, 1e-6));
|
||||
assert!(close(h.ascendant_speed, 264.1614525, 1e-4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placidus_falls_back_to_porphyry_in_polar_regions() {
|
||||
let arctic = GeoPosition { latitude: 75.0, ..BUDAPEST };
|
||||
let h = engine().houses(JD, &arctic, HouseSystem::Placidus, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
assert_eq!(h.used, HouseSystem::Porphyry);
|
||||
assert!(h.fallback_reason.is_some());
|
||||
// swetest: house 1 = 199°49'46.9801"
|
||||
assert!(close(h.cusps[0], 199.0 + 49.0 / 60.0 + 46.9801 / 3600.0, 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delta_t_1985() {
|
||||
// swetest: Delta T 54.6303394 s
|
||||
assert!(close(engine().delta_t(JD) * 86_400.0, 54.6303394, 1e-4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_chart() {
|
||||
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: true, options: ChartOptions::default() };
|
||||
let chart = calculate_chart(engine(), &input).unwrap();
|
||||
assert!(chart.warnings.is_empty(), "{:?}", chart.warnings);
|
||||
|
||||
// 10 planets + north/south node + Lilith + Chiron + 4 asteroids
|
||||
assert_eq!(chart.points.len(), 18);
|
||||
let get = |id| chart.points.iter().find(|p| p.id == id).unwrap();
|
||||
let sun = get(PointId::Sun);
|
||||
assert_eq!(sun.position.sign, astro_engine::ZodiacSign::Cancer);
|
||||
assert_eq!(sun.house, Some(9)); // 112.0° lies between cusp 9 (98.8°) and 10 (136.4°)
|
||||
let north = get(PointId::NorthNode);
|
||||
let south = get(PointId::SouthNode);
|
||||
assert!(close(south.position.longitude, north.position.longitude + 180.0, 1e-9));
|
||||
|
||||
// Sun 112.0007 and Mars 113.0940: conjunction with orb ~1.09°
|
||||
let conj = chart
|
||||
.aspects
|
||||
.iter()
|
||||
.find(|a| a.point1 == PointId::Sun && a.point2 == PointId::Mars)
|
||||
.expect("sun-mars conjunction");
|
||||
assert_eq!(conj.aspect, AspectKind::Conjunction);
|
||||
assert!(close(conj.orb, 1.0932991, 1e-6));
|
||||
|
||||
// Sun in house 9 is above the horizon -> day chart
|
||||
assert_eq!(chart.summary.sect, Some(Sect::Day));
|
||||
let lots = chart.lots.as_ref().unwrap();
|
||||
let expected_fortune = (215.9678137 + 71.1646551 - 112.0007251f64).rem_euclid(360.0);
|
||||
assert!(close(lots.fortune.position.longitude, expected_fortune, 1e-6));
|
||||
|
||||
let json = serde_json::to_value(&chart).unwrap();
|
||||
assert_eq!(json["points"][0]["id"], "sun");
|
||||
assert_eq!(json["houses"]["system"], "placidus");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_time_omits_houses() {
|
||||
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: false, options: ChartOptions::default() };
|
||||
let chart = calculate_chart(engine(), &input).unwrap();
|
||||
assert!(chart.houses.is_none() && chart.angles.is_none() && chart.lots.is_none());
|
||||
assert!(chart.points.iter().all(|p| p.house.is_none()));
|
||||
assert!(!chart.warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidereal_zodiac_subtracts_ayanamsa() {
|
||||
let tropical = engine().position(Body::Sun, JD, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
let frame = Frame { sidereal: Some(astro_engine::Ayanamsa::Lahiri), topocentric: None };
|
||||
let sidereal = engine().position(Body::Sun, JD, &frame).unwrap();
|
||||
let ayanamsa = engine().ayanamsa(JD, astro_engine::Ayanamsa::Lahiri).unwrap();
|
||||
assert!((23.0..24.5).contains(&ayanamsa), "lahiri ayanamsa {ayanamsa}");
|
||||
assert!(close(tropical.longitude - sidereal.longitude, ayanamsa, 1e-3));
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "db"
|
||||
description = "PostgreSQL schema (migrations) and shared data access for the Sorsfonalak services"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
sha2.workspace = true
|
||||
sqlx.workspace = true
|
||||
time.workspace = true
|
||||
uuid.workspace = true
|
||||
@@ -0,0 +1,4 @@
|
||||
// Rebuild when a migration is added or changed (`sqlx::migrate!` embeds them).
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=migrations");
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
-- Users, login, birth charts, synastries, text analyses, credits, sharing.
|
||||
-- Identifiers are UUIDv7 generated by the application (time-ordered).
|
||||
|
||||
-- --- users and login ----------------------------------------------------------
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
-- Always stored lower-case; unique.
|
||||
email text NOT NULL,
|
||||
email_verified_at timestamptz,
|
||||
display_name text,
|
||||
-- UI and analysis language (BCP 47 primary tag, e.g. 'hu', 'en').
|
||||
locale text NOT NULL DEFAULT 'hu',
|
||||
roles text[] NOT NULL DEFAULT ARRAY['user']::text[],
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_login_at timestamptz,
|
||||
CONSTRAINT users_email_lower CHECK (email = lower(email)),
|
||||
CONSTRAINT users_roles_valid CHECK (cardinality(roles) > 0 AND roles <@ ARRAY['admin', 'creator', 'user']::text[])
|
||||
);
|
||||
CREATE UNIQUE INDEX users_email_key ON users (email);
|
||||
|
||||
-- One row per login method of a user. 'password' keeps the Argon2id hash;
|
||||
-- external providers keep their stable subject id (Google 'sub').
|
||||
CREATE TABLE auth_identities (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
provider text NOT NULL CHECK (provider IN ('password', 'google', 'facebook', 'apple')),
|
||||
subject text NOT NULL,
|
||||
password_hash text,
|
||||
-- E-mail reported by the provider when the identity was linked.
|
||||
email text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_used_at timestamptz,
|
||||
UNIQUE (provider, subject),
|
||||
UNIQUE (user_id, provider),
|
||||
CONSTRAINT auth_identities_password CHECK ((provider = 'password') = (password_hash IS NOT NULL))
|
||||
);
|
||||
|
||||
-- Opaque session tokens; only their SHA-256 hash is stored.
|
||||
CREATE TABLE sessions (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
token_hash bytea NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
user_agent text
|
||||
);
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||
|
||||
-- One-time tokens sent by e-mail (verification, password reset).
|
||||
CREATE TABLE auth_tokens (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
purpose text NOT NULL CHECK (purpose IN ('verify_email', 'reset_password')),
|
||||
token_hash bytea NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
used_at timestamptz
|
||||
);
|
||||
CREATE INDEX auth_tokens_user_idx ON auth_tokens (user_id, purpose);
|
||||
|
||||
-- --- charts and synastries -------------------------------------------------------
|
||||
|
||||
-- A calculated natal chart. `birth_data` is the request sent to the
|
||||
-- horoscope service, `result` its full response.
|
||||
CREATE TABLE charts (
|
||||
id uuid PRIMARY KEY,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
label text NOT NULL,
|
||||
-- The owner's own chart (at most one per user).
|
||||
is_primary boolean NOT NULL DEFAULT false,
|
||||
birth_data jsonb NOT NULL,
|
||||
result jsonb NOT NULL,
|
||||
-- Hash of the resolved birth moment, place and options: same hash, same chart.
|
||||
chart_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX charts_one_primary ON charts (owner_id) WHERE is_primary;
|
||||
CREATE INDEX charts_owner_idx ON charts (owner_id, created_at DESC);
|
||||
|
||||
-- Comparison of two charts. Visible to `owner_id` and to the owners of both
|
||||
-- charts (an accepted invitation links two users this way).
|
||||
CREATE TABLE synastries (
|
||||
id uuid PRIMARY KEY,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
chart1_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||
chart2_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||
-- Synastry part of the horoscope service response (without the two charts).
|
||||
result jsonb NOT NULL,
|
||||
synastry_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT synastries_distinct CHECK (chart1_id <> chart2_id),
|
||||
UNIQUE (chart1_id, chart2_id)
|
||||
);
|
||||
CREATE INDEX synastries_chart2_idx ON synastries (chart2_id);
|
||||
CREATE INDEX synastries_owner_idx ON synastries (owner_id, created_at DESC);
|
||||
|
||||
-- "How compatible are we?" invitation link.
|
||||
CREATE TABLE synastry_invites (
|
||||
id uuid PRIMARY KEY,
|
||||
inviter_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
inviter_chart_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||
token_hash bytea NOT NULL UNIQUE,
|
||||
message text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
accepted_at timestamptz,
|
||||
accepted_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
synastry_id uuid REFERENCES synastries (id) ON DELETE SET NULL
|
||||
);
|
||||
CREATE INDEX synastry_invites_inviter_idx ON synastry_invites (inviter_id, created_at DESC);
|
||||
|
||||
-- --- text analyses (LLM) ---------------------------------------------------------
|
||||
|
||||
CREATE TABLE analyses (
|
||||
id uuid PRIMARY KEY,
|
||||
kind text NOT NULL CHECK (kind IN ('natal', 'synastry')),
|
||||
chart_id uuid REFERENCES charts (id) ON DELETE CASCADE,
|
||||
synastry_id uuid REFERENCES synastries (id) ON DELETE CASCADE,
|
||||
requested_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
language text NOT NULL,
|
||||
model text NOT NULL,
|
||||
prompt_version text NOT NULL,
|
||||
-- sha256(kind | chart/synastry hash | prompt version | model | language):
|
||||
-- a finished analysis with the same key is reused instead of a new LLM call.
|
||||
cache_key text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'running', 'done', 'failed')),
|
||||
-- Structured result: {"summary", "strengths": [], "challenges": [], "body"}.
|
||||
content jsonb,
|
||||
error text,
|
||||
input_tokens integer,
|
||||
output_tokens integer,
|
||||
credits_charged integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
started_at timestamptz,
|
||||
completed_at timestamptz,
|
||||
CONSTRAINT analyses_target CHECK (
|
||||
(kind = 'natal' AND chart_id IS NOT NULL AND synastry_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL)
|
||||
),
|
||||
CONSTRAINT analyses_done_has_content CHECK (status <> 'done' OR content IS NOT NULL)
|
||||
);
|
||||
CREATE INDEX analyses_chart_idx ON analyses (chart_id, created_at DESC) WHERE chart_id IS NOT NULL;
|
||||
CREATE INDEX analyses_synastry_idx ON analyses (synastry_id, created_at DESC) WHERE synastry_id IS NOT NULL;
|
||||
CREATE INDEX analyses_cache_idx ON analyses (cache_key) WHERE status = 'done';
|
||||
-- Work queue of the worker (SELECT ... FOR UPDATE SKIP LOCKED).
|
||||
CREATE INDEX analyses_pending_idx ON analyses (created_at) WHERE status = 'pending';
|
||||
|
||||
-- --- credits -----------------------------------------------------------------------
|
||||
|
||||
-- Append-only ledger; the balance is SUM(delta).
|
||||
CREATE TABLE credit_ledger (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
delta integer NOT NULL CHECK (delta <> 0),
|
||||
reason text NOT NULL CHECK (reason IN ('monthly_grant', 'analysis', 'chat', 'refund', 'admin_adjust', 'purchase')),
|
||||
-- 'YYYY-MM' of a monthly grant.
|
||||
period text,
|
||||
analysis_id uuid REFERENCES analyses (id) ON DELETE SET NULL,
|
||||
note text,
|
||||
created_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT credit_ledger_grant_period CHECK ((reason = 'monthly_grant') = (period IS NOT NULL))
|
||||
);
|
||||
CREATE UNIQUE INDEX credit_ledger_monthly_grant_once ON credit_ledger (user_id, period) WHERE reason = 'monthly_grant';
|
||||
CREATE INDEX credit_ledger_user_idx ON credit_ledger (user_id, created_at DESC);
|
||||
|
||||
-- --- public sharing -----------------------------------------------------------------
|
||||
|
||||
-- A public link (and OG card) to a chart, synastry or analysis.
|
||||
CREATE TABLE shares (
|
||||
id uuid PRIMARY KEY,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
-- Unguessable public identifier used in the URL.
|
||||
slug text NOT NULL UNIQUE,
|
||||
kind text NOT NULL CHECK (kind IN ('chart', 'synastry', 'analysis')),
|
||||
chart_id uuid REFERENCES charts (id) ON DELETE CASCADE,
|
||||
synastry_id uuid REFERENCES synastries (id) ON DELETE CASCADE,
|
||||
analysis_id uuid REFERENCES analyses (id) ON DELETE CASCADE,
|
||||
title text,
|
||||
-- Birth date, time and place are hidden unless the owner allows them.
|
||||
show_birth_data boolean NOT NULL DEFAULT false,
|
||||
view_count bigint NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
revoked_at timestamptz,
|
||||
CONSTRAINT shares_target CHECK (
|
||||
(kind = 'chart' AND chart_id IS NOT NULL AND synastry_id IS NULL AND analysis_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND analysis_id IS NULL)
|
||||
OR (kind = 'analysis' AND analysis_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
|
||||
)
|
||||
);
|
||||
CREATE INDEX shares_owner_idx ON shares (owner_id, created_at DESC);
|
||||
|
||||
-- --- outgoing e-mail -----------------------------------------------------------------
|
||||
|
||||
-- Written by the backend, sent by the worker.
|
||||
CREATE TABLE email_outbox (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid REFERENCES users (id) ON DELETE CASCADE,
|
||||
to_email text NOT NULL,
|
||||
template text NOT NULL,
|
||||
locale text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
sent_at timestamptz,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text
|
||||
);
|
||||
CREATE INDEX email_outbox_unsent_idx ON email_outbox (created_at) WHERE sent_at IS NULL;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- E-mail delivery by the worker: retries with backoff, permanent failure,
|
||||
-- and a notification so the worker sends new e-mails right away.
|
||||
|
||||
ALTER TABLE email_outbox
|
||||
ADD COLUMN next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
ADD COLUMN failed_at timestamptz;
|
||||
|
||||
DROP INDEX email_outbox_unsent_idx;
|
||||
CREATE INDEX email_outbox_due_idx ON email_outbox (next_attempt_at)
|
||||
WHERE sent_at IS NULL AND failed_at IS NULL;
|
||||
|
||||
CREATE FUNCTION notify_email_outbox() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM pg_notify('email_outbox', '');
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE TRIGGER email_outbox_notify
|
||||
AFTER INSERT ON email_outbox
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION notify_email_outbox();
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Text analyses written by the worker: retries with backoff, the model that
|
||||
-- actually answered (e.g. behind 'openrouter/auto'), cost, a notification for
|
||||
-- new requests, and at most one refund per analysis.
|
||||
|
||||
ALTER TABLE analyses
|
||||
ADD COLUMN attempts integer NOT NULL DEFAULT 0,
|
||||
ADD COLUMN next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
ADD COLUMN model_used text,
|
||||
ADD COLUMN cost_usd double precision;
|
||||
|
||||
COMMENT ON COLUMN analyses.content IS
|
||||
'Structured result: {title, summary, sections: {key: {title, body}}, strengths: [], challenges: [], advice}';
|
||||
|
||||
DROP INDEX analyses_pending_idx;
|
||||
CREATE INDEX analyses_due_idx ON analyses (next_attempt_at) WHERE status = 'pending';
|
||||
|
||||
CREATE UNIQUE INDEX credit_ledger_refund_once ON credit_ledger (analysis_id) WHERE reason = 'refund';
|
||||
|
||||
CREATE FUNCTION notify_analyses() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM pg_notify('analyses', '');
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE TRIGGER analyses_notify
|
||||
AFTER INSERT ON analyses
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION notify_analyses();
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Subscription tiers as roles: 'premium' and 'vip' unlock the models marked
|
||||
-- for them in the backend's LLM_MODELS.
|
||||
ALTER TABLE users DROP CONSTRAINT users_roles_valid;
|
||||
ALTER TABLE users ADD CONSTRAINT users_roles_valid
|
||||
CHECK (cardinality(roles) > 0 AND roles <@ ARRAY['admin', 'creator', 'premium', 'vip', 'user']::text[]);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Free short summaries: a few sentences about a natal chart, written by a
|
||||
-- cheap model when the chart is saved. The detailed analyses stay paid.
|
||||
|
||||
ALTER TABLE analyses DROP CONSTRAINT analyses_kind_check;
|
||||
ALTER TABLE analyses ADD CONSTRAINT analyses_kind_check CHECK (kind IN ('natal', 'synastry', 'summary'));
|
||||
|
||||
ALTER TABLE analyses DROP CONSTRAINT analyses_target;
|
||||
ALTER TABLE analyses ADD CONSTRAINT analyses_target CHECK (
|
||||
(kind IN ('natal', 'summary') AND chart_id IS NOT NULL AND synastry_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL)
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN analyses.content IS
|
||||
'Structured result. natal/synastry: {title, summary, sections: {key: {title, body}}, strengths: [], challenges: [], advice}; summary: {title, summary}';
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Paid analyses are counted per kind instead of generic credits: a
|
||||
-- detailed natal analysis uses one 'natal' unit, a synastry analysis one
|
||||
-- 'synastry' unit. Units are bought in packages (or granted by an admin).
|
||||
-- The free monthly credits are gone: the free part is the short summary.
|
||||
|
||||
DELETE FROM credit_ledger WHERE reason = 'monthly_grant';
|
||||
|
||||
ALTER TABLE credit_ledger ADD COLUMN unit text NOT NULL DEFAULT 'natal' CHECK (unit IN ('natal', 'synastry'));
|
||||
ALTER TABLE credit_ledger ALTER COLUMN unit DROP DEFAULT;
|
||||
|
||||
DROP INDEX credit_ledger_user_idx;
|
||||
CREATE INDEX credit_ledger_user_idx ON credit_ledger (user_id, unit, created_at DESC);
|
||||
|
||||
COMMENT ON COLUMN analyses.credits_charged IS 'Units of the analysis kind spent on it (0 or 1; 0 for summaries and copies)';
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Every time a user's own (primary) birth data is set or changed. The
|
||||
-- backend limits changes with it: after the first save, three corrections
|
||||
-- within an hour, then one per 24 hours (admins are not limited).
|
||||
|
||||
CREATE TABLE birth_data_changes (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
chart_id uuid REFERENCES charts (id) ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX birth_data_changes_user_idx ON birth_data_changes (user_id, created_at);
|
||||
|
||||
-- The current primary charts count as the first save.
|
||||
INSERT INTO birth_data_changes (id, user_id, chart_id, created_at)
|
||||
SELECT gen_random_uuid(), owner_id, id, created_at FROM charts WHERE is_primary;
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Charts of other people ("persons": name and birth data, with their own
|
||||
-- chart and analyses) next to the user's own chart.
|
||||
--
|
||||
-- kind 'own': the user's own chart, the current one (is_primary) and the
|
||||
-- earlier ones replaced by a correction (kept for their analyses, not listed).
|
||||
-- kind 'person': someone else. Each new person uses one 'person' unit of the
|
||||
-- user's package (deleting does not give it back); unlimited packages and
|
||||
-- admins have no limit.
|
||||
|
||||
ALTER TABLE charts ADD COLUMN kind text NOT NULL DEFAULT 'person' CHECK (kind IN ('own', 'person'));
|
||||
UPDATE charts SET kind = 'own'
|
||||
WHERE is_primary OR id IN (SELECT chart_id FROM birth_data_changes WHERE chart_id IS NOT NULL);
|
||||
ALTER TABLE charts ADD CONSTRAINT charts_primary_is_own CHECK (NOT is_primary OR kind = 'own');
|
||||
|
||||
ALTER TABLE credit_ledger DROP CONSTRAINT credit_ledger_unit_check;
|
||||
ALTER TABLE credit_ledger ADD CONSTRAINT credit_ledger_unit_check CHECK (unit IN ('natal', 'synastry', 'person'));
|
||||
ALTER TABLE credit_ledger DROP CONSTRAINT credit_ledger_reason_check;
|
||||
ALTER TABLE credit_ledger ADD CONSTRAINT credit_ledger_reason_check
|
||||
CHECK (reason IN ('monthly_grant', 'analysis', 'chat', 'refund', 'admin_adjust', 'purchase', 'person'));
|
||||
ALTER TABLE credit_ledger ADD COLUMN chart_id uuid REFERENCES charts (id) ON DELETE SET NULL;
|
||||
|
||||
-- Lasting rights from a package, e.g. any number of persons.
|
||||
CREATE TABLE entitlements (
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
entitlement text NOT NULL CHECK (entitlement IN ('unlimited_persons')),
|
||||
note text,
|
||||
created_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, entitlement)
|
||||
);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Admin-edited system prompts of the analyses. The newest row of a
|
||||
-- (kind, language) is in force; system NULL means the built-in default.
|
||||
-- An analysis records the revision it was written with in prompt_version
|
||||
-- ("v2-r<id>"), so the worker uses exactly that text.
|
||||
CREATE TABLE prompt_revisions (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
kind text NOT NULL CHECK (kind IN ('summary', 'natal', 'synastry')),
|
||||
language text NOT NULL,
|
||||
system text CHECK (system IS NULL OR length(system) BETWEEN 1 AND 50000),
|
||||
created_by uuid REFERENCES users ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX prompt_revisions_current ON prompt_revisions (kind, language, id DESC);
|
||||
@@ -0,0 +1,29 @@
|
||||
-- Test runs of an edited (not yet saved) system prompt on one of the admin's
|
||||
-- charts. Kept apart from analyses: never shown to users, never cached, no
|
||||
-- credits, one attempt. Removed after 30 days by the cleanup job.
|
||||
CREATE TABLE prompt_previews (
|
||||
id uuid PRIMARY KEY,
|
||||
kind text NOT NULL CHECK (kind IN ('summary', 'natal')),
|
||||
chart_id uuid NOT NULL REFERENCES charts ON DELETE CASCADE,
|
||||
language text NOT NULL,
|
||||
model text NOT NULL,
|
||||
system text NOT NULL CHECK (length(system) BETWEEN 1 AND 50000),
|
||||
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'running', 'done', 'failed')),
|
||||
content jsonb,
|
||||
error text,
|
||||
model_used text,
|
||||
input_tokens integer,
|
||||
output_tokens integer,
|
||||
cost_usd double precision,
|
||||
created_by uuid NOT NULL REFERENCES users ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
started_at timestamptz,
|
||||
completed_at timestamptz
|
||||
);
|
||||
|
||||
CREATE INDEX prompt_previews_pending_idx ON prompt_previews (created_at) WHERE status = 'pending';
|
||||
|
||||
-- Wakes the analysis worker, like a new analysis.
|
||||
CREATE TRIGGER prompt_previews_notify
|
||||
AFTER INSERT ON prompt_previews
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION notify_analyses();
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Prompt test runs of the relationship (synastry) analysis: on one of the
|
||||
-- admin's comparisons instead of a chart.
|
||||
ALTER TABLE prompt_previews DROP CONSTRAINT prompt_previews_kind_check;
|
||||
ALTER TABLE prompt_previews ALTER COLUMN chart_id DROP NOT NULL;
|
||||
ALTER TABLE prompt_previews
|
||||
ADD COLUMN synastry_id uuid REFERENCES synastries ON DELETE CASCADE,
|
||||
ADD CONSTRAINT prompt_previews_target CHECK (
|
||||
(kind IN ('summary', 'natal') AND chart_id IS NOT NULL AND synastry_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL)
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Packages: every purchase or admin grant of a package is an order; the units
|
||||
-- it gives are credit_ledger rows pointing at it (reason 'package'), and the
|
||||
-- unlimited package is a time-limited 'unlimited' entitlement.
|
||||
CREATE TABLE package_orders (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users ON DELETE CASCADE,
|
||||
package text NOT NULL,
|
||||
source text NOT NULL CHECK (source IN ('admin', 'mock', 'stripe')),
|
||||
price_huf integer NOT NULL DEFAULT 0 CHECK (price_huf >= 0),
|
||||
note text,
|
||||
created_by uuid REFERENCES users ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX package_orders_user_idx ON package_orders (user_id, created_at DESC);
|
||||
|
||||
ALTER TABLE credit_ledger DROP CONSTRAINT credit_ledger_reason_check;
|
||||
ALTER TABLE credit_ledger ADD CONSTRAINT credit_ledger_reason_check
|
||||
CHECK (reason IN ('monthly_grant', 'analysis', 'chat', 'refund', 'admin_adjust', 'purchase', 'person', 'package'));
|
||||
ALTER TABLE credit_ledger ADD COLUMN order_id uuid REFERENCES package_orders ON DELETE SET NULL;
|
||||
|
||||
-- 'unlimited': analyses and persons without limit until expires_at.
|
||||
ALTER TABLE entitlements DROP CONSTRAINT entitlements_entitlement_check;
|
||||
ALTER TABLE entitlements ADD CONSTRAINT entitlements_entitlement_check
|
||||
CHECK (entitlement IN ('unlimited_persons', 'unlimited'));
|
||||
ALTER TABLE entitlements ADD COLUMN expires_at timestamptz;
|
||||
@@ -0,0 +1,43 @@
|
||||
-- Invitations to the closed site. While SIGNUP_MODE=invite, a new account
|
||||
-- (Google or password) needs an open invitation for its address, or the
|
||||
-- invitation link itself (then any address will do).
|
||||
CREATE TABLE invitations (
|
||||
id uuid PRIMARY KEY,
|
||||
email text NOT NULL,
|
||||
message text CHECK (char_length(message) <= 300),
|
||||
locale text NOT NULL,
|
||||
invited_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
sent_count integer NOT NULL DEFAULT 1,
|
||||
last_sent_at timestamptz NOT NULL DEFAULT now(),
|
||||
accepted_at timestamptz,
|
||||
accepted_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
revoked_at timestamptz
|
||||
);
|
||||
-- At most one open invitation per address.
|
||||
CREATE UNIQUE INDEX invitations_open_email_idx ON invitations (email)
|
||||
WHERE accepted_at IS NULL AND revoked_at IS NULL;
|
||||
CREATE INDEX invitations_created_idx ON invitations (created_at DESC);
|
||||
|
||||
-- Link tokens (only their hashes). Every sending issues a new one, and the
|
||||
-- earlier links keep working while the invitation is open.
|
||||
CREATE TABLE invitation_tokens (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
invitation_id uuid NOT NULL REFERENCES invitations (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX invitation_tokens_invitation_idx ON invitation_tokens (invitation_id);
|
||||
|
||||
-- Addresses that asked for no more invitations (only the SHA-256 of the address).
|
||||
CREATE TABLE email_optouts (
|
||||
email_hash bytea PRIMARY KEY,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- "Tell me when it opens": people without an invitation.
|
||||
CREATE TABLE waitlist (
|
||||
email text PRIMARY KEY,
|
||||
locale text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Database schema and the data access shared by several services
|
||||
//! (sessions are validated by the backend and later by the chat engine).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use rand::RngCore;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub use sqlx;
|
||||
|
||||
/// All schema migrations, embedded at compile time.
|
||||
pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations");
|
||||
|
||||
/// Applies the pending migrations. Migrations newer than this binary (applied
|
||||
/// by an already updated service) are tolerated, so services can be rebuilt
|
||||
/// one at a time.
|
||||
pub async fn migrate(pool: &PgPool) -> Result<(), sqlx::migrate::MigrateError> {
|
||||
let mut migrator = sqlx::migrate!("./migrations");
|
||||
migrator.set_ignore_missing(true);
|
||||
migrator.run(pool).await
|
||||
}
|
||||
|
||||
pub async fn connect(url: &str) -> Result<PgPool, sqlx::Error> {
|
||||
PgPoolOptions::new().max_connections(20).acquire_timeout(Duration::from_secs(5)).connect(url).await
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Role {
|
||||
Admin,
|
||||
/// May write articles (phase 2).
|
||||
Creator,
|
||||
/// Paid tier: may use the models marked `@premium`.
|
||||
Premium,
|
||||
/// Top tier: may use the `@vip` and `@premium` models.
|
||||
Vip,
|
||||
User,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
pub const ALL: [Role; 5] = [Role::Admin, Role::Creator, Role::Premium, Role::Vip, Role::User];
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Role::Admin => "admin",
|
||||
Role::Creator => "creator",
|
||||
Role::Premium => "premium",
|
||||
Role::Vip => "vip",
|
||||
Role::User => "user",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| r.as_str() == s)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
pub email: String,
|
||||
pub email_verified_at: Option<OffsetDateTime>,
|
||||
pub display_name: Option<String>,
|
||||
pub locale: String,
|
||||
pub roles: Vec<String>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub last_login_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn has_role(&self, role: Role) -> bool {
|
||||
self.roles.iter().any(|r| r == role.as_str())
|
||||
}
|
||||
|
||||
/// Whether the user may use something that needs `role`: admins may use
|
||||
/// everything, and the VIP tier includes the premium one.
|
||||
pub fn has_access(&self, role: Role) -> bool {
|
||||
self.has_role(role) || self.has_role(Role::Admin) || (role == Role::Premium && self.has_role(Role::Vip))
|
||||
}
|
||||
|
||||
pub fn role_list(&self) -> Vec<Role> {
|
||||
self.roles.iter().filter_map(|r| Role::parse(r)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Columns selected into [`User`].
|
||||
pub const USER_COLUMNS: &str = "id, email, email_verified_at, display_name, locale, roles, created_at, last_login_at";
|
||||
|
||||
/// A new random secret token (256 bits, URL-safe base64).
|
||||
pub fn new_token() -> String {
|
||||
random_token(32)
|
||||
}
|
||||
|
||||
/// `bytes` random bytes as URL-safe base64.
|
||||
pub fn random_token(bytes: usize) -> String {
|
||||
let mut buf = vec![0u8; bytes];
|
||||
rand::rng().fill_bytes(&mut buf);
|
||||
URL_SAFE_NO_PAD.encode(buf)
|
||||
}
|
||||
|
||||
/// Stored form of a secret token.
|
||||
pub fn token_hash(token: &str) -> Vec<u8> {
|
||||
Sha256::digest(token.as_bytes()).to_vec()
|
||||
}
|
||||
|
||||
/// The session id and user of a valid (unexpired) session token.
|
||||
pub async fn user_by_session(pool: &PgPool, token: &str) -> Result<Option<(Uuid, User)>, sqlx::Error> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
session_id: Uuid,
|
||||
#[sqlx(flatten)]
|
||||
user: User,
|
||||
}
|
||||
let row: Option<Row> = sqlx::query_as(
|
||||
"SELECT s.id AS session_id, u.id, u.email, u.email_verified_at, u.display_name, u.locale, u.roles, \
|
||||
u.created_at, u.last_login_at \
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id \
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()",
|
||||
)
|
||||
.bind(token_hash(token))
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row.map(|r| (r.session_id, r.user)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tokens_are_random_and_hashed() {
|
||||
let a = new_token();
|
||||
let b = new_token();
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(a.len(), 43);
|
||||
assert_eq!(token_hash(&a), token_hash(&a));
|
||||
assert_ne!(token_hash(&a), token_hash(&b));
|
||||
assert_eq!(Role::parse("creator"), Some(Role::Creator));
|
||||
assert_eq!(Role::parse("root"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "email-templates"
|
||||
description = "E-mail texts of Sorsfonalak as HTML and plain text (sent by the worker, previewed by the backend)"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,482 @@
|
||||
//! E-mail texts (Hungarian and English), as plain text and HTML.
|
||||
//!
|
||||
//! The payloads are written by the backend; the validity periods in the
|
||||
//! texts match the token lifetimes there. The worker sends the result, the
|
||||
//! backend renders it for the admin preview.
|
||||
//!
|
||||
//! The layout is deliberately plain for spam filters: one column, inline
|
||||
//! styles, no images, no tracking, every link on the site's own domain, and
|
||||
//! a plain-text part with the same content.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Rendered {
|
||||
pub subject: String,
|
||||
pub text: String,
|
||||
pub html: String,
|
||||
/// One-click unsubscribe address for the `List-Unsubscribe` header (RFC 8058).
|
||||
pub unsubscribe_post_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum TemplateError {
|
||||
UnknownTemplate(String),
|
||||
MissingField(&'static str),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for TemplateError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
TemplateError::UnknownTemplate(t) => write!(f, "unknown e-mail template '{t}'"),
|
||||
TemplateError::MissingField(field) => write!(f, "e-mail payload has no '{field}'"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Lang {
|
||||
Hu,
|
||||
En,
|
||||
}
|
||||
|
||||
/// One e-mail: greeting, paragraphs, a button and a closing note.
|
||||
struct Content {
|
||||
subject: String,
|
||||
/// The line mail clients show after the subject in the inbox.
|
||||
preheader: Option<String>,
|
||||
greeting: String,
|
||||
intro: String,
|
||||
/// A personal message, shown as a quote.
|
||||
quote: Option<String>,
|
||||
/// A short list after the intro, with its heading.
|
||||
points: Option<(&'static str, Vec<&'static str>)>,
|
||||
button: &'static str,
|
||||
url: String,
|
||||
note: String,
|
||||
/// Why the recipient got this e-mail (for mails they did not ask for).
|
||||
reason: Option<String>,
|
||||
/// Label and page of the unsubscribe link in the footer.
|
||||
unsubscribe: Option<(&'static str, String)>,
|
||||
unsubscribe_post_url: Option<String>,
|
||||
}
|
||||
|
||||
impl Content {
|
||||
fn simple(subject: String, greeting: String, intro: String, button: &'static str, url: String, note: &str) -> Self {
|
||||
Self {
|
||||
subject,
|
||||
preheader: None,
|
||||
greeting,
|
||||
intro,
|
||||
quote: None,
|
||||
points: None,
|
||||
button,
|
||||
url,
|
||||
note: note.to_owned(),
|
||||
reason: None,
|
||||
unsubscribe: None,
|
||||
unsubscribe_post_url: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(template: &str, locale: &str, payload: &Value) -> Result<Rendered, TemplateError> {
|
||||
let lang = if locale.eq_ignore_ascii_case("hu") { Lang::Hu } else { Lang::En };
|
||||
let url = field(payload, "url")?;
|
||||
let greeting = |name: Option<String>| match (lang, name) {
|
||||
(Lang::Hu, Some(n)) => format!("Szia {n}!"),
|
||||
(Lang::Hu, None) => "Szia!".to_owned(),
|
||||
(Lang::En, Some(n)) => format!("Hi {n},"),
|
||||
(Lang::En, None) => "Hi,".to_owned(),
|
||||
};
|
||||
let content = match (template, lang) {
|
||||
("verify_email", Lang::Hu) => Content::simple(
|
||||
"Erősítsd meg az e-mail-címed".into(),
|
||||
greeting(name(payload, "display_name")),
|
||||
"Köszönjük, hogy regisztráltál a Sorsfonalakon! Az alábbi gombbal erősítsd meg az e-mail-címed.".into(),
|
||||
"E-mail-cím megerősítése",
|
||||
url,
|
||||
"A link 3 napig érvényes. Ha nem te regisztráltál, nyugodtan hagyd figyelmen kívül ezt a levelet.",
|
||||
),
|
||||
("verify_email", Lang::En) => Content::simple(
|
||||
"Confirm your e-mail address".into(),
|
||||
greeting(name(payload, "display_name")),
|
||||
"Thanks for signing up for Sorsfonalak! Please confirm your e-mail address with the button below.".into(),
|
||||
"Confirm e-mail address",
|
||||
url,
|
||||
"The link is valid for 3 days. If you did not sign up, you can safely ignore this e-mail.",
|
||||
),
|
||||
("reset_password", Lang::Hu) => Content::simple(
|
||||
"Új jelszó megadása".into(),
|
||||
greeting(name(payload, "display_name")),
|
||||
"Jelszó-visszaállítást kértél a Sorsfonalak-fiókodhoz. Az alábbi gombbal adhatsz meg új jelszót.".into(),
|
||||
"Új jelszó megadása",
|
||||
url,
|
||||
"A link 1 óráig érvényes, és csak egyszer használható. Ha nem te kérted, hagyd figyelmen kívül ezt a levelet: a jelszavad nem változik.",
|
||||
),
|
||||
("reset_password", Lang::En) => Content::simple(
|
||||
"Set a new password".into(),
|
||||
greeting(name(payload, "display_name")),
|
||||
"You asked to reset the password of your Sorsfonalak account. Use the button below to set a new one."
|
||||
.into(),
|
||||
"Set a new password",
|
||||
url,
|
||||
"The link is valid for 1 hour and can be used once. If you did not ask for this, ignore this e-mail: your password stays the same.",
|
||||
),
|
||||
("invite_accepted", Lang::Hu) => {
|
||||
let who = name(payload, "invitee_name");
|
||||
Content::simple(
|
||||
match &who {
|
||||
Some(n) => format!("{n} elfogadta a meghívásod"),
|
||||
None => "Elfogadták a meghívásod".into(),
|
||||
},
|
||||
greeting(None),
|
||||
format!(
|
||||
"{} elfogadta a „Mennyire illünk össze?” meghívásod, és elkészült a szinasztriátok.",
|
||||
who.as_deref().unwrap_or("A meghívott")
|
||||
),
|
||||
"Szinasztria megnyitása",
|
||||
url,
|
||||
"A szinasztriát mindketten látjátok, de egymás születési adatait nem.",
|
||||
)
|
||||
}
|
||||
("invite_accepted", Lang::En) => {
|
||||
let who = name(payload, "invitee_name");
|
||||
Content::simple(
|
||||
match &who {
|
||||
Some(n) => format!("{n} accepted your invitation"),
|
||||
None => "Your invitation was accepted".into(),
|
||||
},
|
||||
greeting(None),
|
||||
format!(
|
||||
"{} accepted your “How compatible are we?” invitation, and your synastry is ready.",
|
||||
who.as_deref().unwrap_or("Your invitee")
|
||||
),
|
||||
"Open synastry",
|
||||
url,
|
||||
"You both see the synastry, but not each other's birth data.",
|
||||
)
|
||||
}
|
||||
("invitation", _) => invitation(lang, payload, url)?,
|
||||
_ => return Err(TemplateError::UnknownTemplate(template.to_owned())),
|
||||
};
|
||||
Ok(content.render(lang))
|
||||
}
|
||||
|
||||
/// An invitation to the closed site (sent by an administrator).
|
||||
fn invitation(lang: Lang, payload: &Value, url: String) -> Result<Content, TemplateError> {
|
||||
let inviter = name(payload, "inviter_name");
|
||||
let message = message(payload);
|
||||
let until =
|
||||
payload["expires_on"].as_str().and_then(|d| date(lang, d)).ok_or(TemplateError::MissingField("expires_on"))?;
|
||||
// "2026. december 17." + "-ig" = "2026. december 17-ig"
|
||||
let until_hu = until.trim_end_matches('.');
|
||||
let unsubscribe_url = field(payload, "unsubscribe_url")?;
|
||||
let unsubscribe_post_url = field(payload, "unsubscribe_post_url")?;
|
||||
Ok(match lang {
|
||||
Lang::Hu => Content {
|
||||
subject: match &inviter {
|
||||
Some(n) => format!("{n} meghívott a Sorsfonalakra"),
|
||||
None => "Meghívót kaptál a Sorsfonalakra".into(),
|
||||
},
|
||||
preheader: Some(format!("Születési képlet és rövid elemzés ingyen. A meghívó {until_hu}-ig érvényes.")),
|
||||
greeting: "Szia!".into(),
|
||||
intro: match &inviter {
|
||||
Some(n) => {
|
||||
format!("{n} meghívott a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.")
|
||||
}
|
||||
None => {
|
||||
"Meghívót kaptál a Sorsfonalakra. Az oldal egyelőre zártkörű: csak meghívóval lehet belépni.".into()
|
||||
}
|
||||
},
|
||||
quote: message,
|
||||
points: Some((
|
||||
"Mit találsz ott?",
|
||||
vec![
|
||||
"a születési képleted kiszámolva és megrajzolva, ingyen,",
|
||||
"egy rövid, személyre szóló elemzést róla,",
|
||||
"összevetést a szeretteiddel: mennyire illetek össze.",
|
||||
],
|
||||
)),
|
||||
button: "Meghívás elfogadása",
|
||||
url,
|
||||
note: format!(
|
||||
"A meghívó {until_hu}-ig érvényes. Elfogadáskor Google-fiókkal lépsz be, és ezzel a linkkel bármelyik Google-fiókodat használhatod."
|
||||
),
|
||||
reason: Some(match &inviter {
|
||||
Some(n) => {
|
||||
format!("Ezt a levelet azért kaptad, mert {n} megadta az e-mail-címed a Sorsfonalak meghívójában.")
|
||||
}
|
||||
None => {
|
||||
"Ezt a levelet azért kaptad, mert valaki megadta az e-mail-címed a Sorsfonalak meghívójában.".into()
|
||||
}
|
||||
}),
|
||||
unsubscribe: Some(("Nem kérek több meghívót", unsubscribe_url)),
|
||||
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||
},
|
||||
Lang::En => Content {
|
||||
subject: match &inviter {
|
||||
Some(n) => format!("{n} invited you to Sorsfonalak"),
|
||||
None => "You are invited to Sorsfonalak".into(),
|
||||
},
|
||||
preheader: Some(format!(
|
||||
"Your birth chart and a short reading, free. The invitation is valid until {until}."
|
||||
)),
|
||||
greeting: "Hi,".into(),
|
||||
intro: match &inviter {
|
||||
Some(n) => format!("{n} invited you to Sorsfonalak. The site is invitation-only for now."),
|
||||
None => "You are invited to Sorsfonalak. The site is invitation-only for now.".into(),
|
||||
},
|
||||
quote: message,
|
||||
points: Some((
|
||||
"What you will find there:",
|
||||
vec![
|
||||
"your birth chart, calculated and drawn, for free,",
|
||||
"a short, personal reading of it,",
|
||||
"comparisons with your loved ones: how well you match.",
|
||||
],
|
||||
)),
|
||||
button: "Accept the invitation",
|
||||
url,
|
||||
note: format!(
|
||||
"The invitation is valid until {until}. You sign in with Google, and with this link any of your Google accounts will do."
|
||||
),
|
||||
reason: Some(match &inviter {
|
||||
Some(n) => format!("You got this e-mail because {n} entered your address in a Sorsfonalak invitation."),
|
||||
None => "You got this e-mail because someone entered your address in a Sorsfonalak invitation.".into(),
|
||||
}),
|
||||
unsubscribe: Some(("No more invitations, please", unsubscribe_url)),
|
||||
unsubscribe_post_url: Some(unsubscribe_post_url),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn field(payload: &Value, name: &'static str) -> Result<String, TemplateError> {
|
||||
payload[name].as_str().filter(|u| !u.is_empty()).map(str::to_owned).ok_or(TemplateError::MissingField(name))
|
||||
}
|
||||
|
||||
/// A user-supplied name, safe for a subject line.
|
||||
fn name(payload: &Value, field: &str) -> Option<String> {
|
||||
let name: String = payload[field].as_str()?.chars().filter(|c| !c.is_control()).take(60).collect();
|
||||
let name = name.trim();
|
||||
(!name.is_empty()).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// The personal message of an invitation: line breaks kept, other control characters dropped.
|
||||
fn message(payload: &Value) -> Option<String> {
|
||||
let text: String =
|
||||
payload["message"].as_str()?.chars().filter(|c| *c == '\n' || !c.is_control()).take(500).collect();
|
||||
let text = text.trim();
|
||||
(!text.is_empty()).then(|| text.to_owned())
|
||||
}
|
||||
|
||||
/// `2026-12-17` as "2026. december 17." or "17 December 2026".
|
||||
fn date(lang: Lang, iso: &str) -> Option<String> {
|
||||
const HU: [&str; 12] = [
|
||||
"január",
|
||||
"február",
|
||||
"március",
|
||||
"április",
|
||||
"május",
|
||||
"június",
|
||||
"július",
|
||||
"augusztus",
|
||||
"szeptember",
|
||||
"október",
|
||||
"november",
|
||||
"december",
|
||||
];
|
||||
const EN: [&str; 12] = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
];
|
||||
let mut parts = iso.splitn(3, '-');
|
||||
let (y, m, d) = (parts.next()?, parts.next()?, parts.next()?);
|
||||
let (y, m, d): (u32, usize, u32) = (y.parse().ok()?, m.parse().ok()?, d.get(..2)?.parse().ok()?);
|
||||
let month = m.checked_sub(1).filter(|&i| i < 12)?;
|
||||
Some(match lang {
|
||||
Lang::Hu => format!("{y}. {} {d}.", HU[month]),
|
||||
Lang::En => format!("{d} {} {y}", EN[month]),
|
||||
})
|
||||
}
|
||||
|
||||
fn escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const TEXT: &str = "#2a2620";
|
||||
const MUTED: &str = "#6b645a";
|
||||
const FAINT: &str = "#9b948a";
|
||||
const GOLD: &str = "#9a7b3c";
|
||||
|
||||
impl Content {
|
||||
fn render(self, lang: Lang) -> Rendered {
|
||||
let footer = match lang {
|
||||
Lang::Hu => "Ezt a levelet a Sorsfonalak küldte.",
|
||||
Lang::En => "This e-mail was sent by Sorsfonalak.",
|
||||
};
|
||||
|
||||
let mut text = format!("{}\n\n{}\n\n", self.greeting, self.intro);
|
||||
if let Some(q) = &self.quote {
|
||||
for line in q.lines() {
|
||||
text.push_str(&format!("> {line}\n"));
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
if let Some((heading, items)) = &self.points {
|
||||
text.push_str(heading);
|
||||
text.push('\n');
|
||||
for item in items {
|
||||
text.push_str(&format!("- {item}\n"));
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&format!("{}:\n{}\n\n{}\n\n-- \nSorsfonalak\n", self.button, self.url, self.note));
|
||||
if let Some(reason) = &self.reason {
|
||||
text.push_str(&format!("\n{reason}\n"));
|
||||
}
|
||||
if let Some((label, url)) = &self.unsubscribe {
|
||||
text.push_str(&format!("{label}: {url}\n"));
|
||||
}
|
||||
|
||||
let preheader = self.preheader.as_deref().map_or(String::new(), |p| {
|
||||
format!(
|
||||
r#"<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent">{}</div>"#,
|
||||
escape(p)
|
||||
)
|
||||
});
|
||||
let quote = self.quote.as_deref().map_or(String::new(), |q| {
|
||||
format!(
|
||||
r#"<tr><td style="padding-bottom:24px"><div style="border-left:3px solid {GOLD};padding:4px 0 4px 16px;font-size:16px;line-height:1.6;font-style:italic;color:{TEXT}">{}</div></td></tr>
|
||||
"#,
|
||||
escape(q).replace('\n', "<br>")
|
||||
)
|
||||
});
|
||||
let points = self.points.as_ref().map_or(String::new(), |(heading, items)| {
|
||||
let items: String = items
|
||||
.iter()
|
||||
.map(|i| format!(r#"<li style="margin:0 0 6px">{}</li>"#, escape(i)))
|
||||
.collect();
|
||||
format!(
|
||||
r#"<tr><td style="font-size:16px;line-height:1.6;padding-bottom:24px">{}<ul style="margin:8px 0 0;padding-left:20px">{items}</ul></td></tr>
|
||||
"#,
|
||||
escape(heading)
|
||||
)
|
||||
});
|
||||
let mut small = Vec::new();
|
||||
if let Some(reason) = &self.reason {
|
||||
small.push(escape(reason));
|
||||
}
|
||||
if let Some((label, url)) = &self.unsubscribe {
|
||||
small.push(format!(r#"<a href="{}" style="color:{FAINT}">{}</a>"#, escape(url), escape(label)));
|
||||
}
|
||||
small.push(escape(footer));
|
||||
let small = small.join("<br>");
|
||||
|
||||
let html = format!(
|
||||
r#"<!doctype html>
|
||||
<html lang="{lang}">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{subject}</title></head>
|
||||
<body style="margin:0;padding:0;background:#f4f1ea;font-family:Georgia,'Times New Roman',serif;color:{TEXT}">
|
||||
{preheader}<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f1ea;padding:32px 16px">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:520px;background:#ffffff;border-radius:8px;padding:32px">
|
||||
<tr><td style="font-size:20px;letter-spacing:2px;color:{GOLD};padding-bottom:24px">SORSFONALAK</td></tr>
|
||||
<tr><td style="font-size:16px;line-height:1.6;padding-bottom:12px">{greeting}</td></tr>
|
||||
<tr><td style="font-size:16px;line-height:1.6;padding-bottom:24px">{intro}</td></tr>
|
||||
{quote}{points}<tr><td style="padding-bottom:24px"><a href="{url}" style="display:inline-block;background:{GOLD};color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-size:16px">{button}</a></td></tr>
|
||||
<tr><td style="font-size:14px;line-height:1.6;color:{MUTED};padding-bottom:16px">{note}</td></tr>
|
||||
<tr><td style="font-size:12px;line-height:1.5;color:{FAINT};word-break:break-all">{url_text}</td></tr>
|
||||
</table>
|
||||
<p style="font-size:12px;line-height:1.5;color:{FAINT};max-width:520px">{small}</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
"#,
|
||||
lang = if lang == Lang::Hu { "hu" } else { "en" },
|
||||
subject = escape(&self.subject),
|
||||
greeting = escape(&self.greeting),
|
||||
intro = escape(&self.intro),
|
||||
url = escape(&self.url),
|
||||
button = escape(self.button),
|
||||
note = escape(&self.note),
|
||||
url_text = escape(&self.url),
|
||||
);
|
||||
Rendered { subject: self.subject, text, html, unsubscribe_post_url: self.unsubscribe_post_url }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn invitation_payload() -> Value {
|
||||
json!({
|
||||
"url": "https://sorsfonalak.test/meghivo/abc",
|
||||
"inviter_name": "Kata",
|
||||
"message": "Gyere, nézd meg!\n<b>Szia</b>",
|
||||
"expires_on": "2026-12-17",
|
||||
"unsubscribe_url": "https://sorsfonalak.test/leiratkozas?token=abc",
|
||||
"unsubscribe_post_url": "https://sorsfonalak.test/api/v1/public/invitations/unsubscribe?token=abc",
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invitation_has_both_parts() {
|
||||
let hu = render("invitation", "hu", &invitation_payload()).unwrap();
|
||||
assert_eq!(hu.subject, "Kata meghívott a Sorsfonalakra");
|
||||
assert!(hu.text.contains("> Gyere, nézd meg!\n> <b>Szia</b>"));
|
||||
assert!(hu.text.contains("A meghívó 2026. december 17-ig érvényes."));
|
||||
assert!(hu.text.contains("Nem kérek több meghívót: https://sorsfonalak.test/leiratkozas?token=abc"));
|
||||
assert!(hu.html.contains("Gyere, nézd meg!<br><b>Szia</b>"));
|
||||
assert!(hu.html.contains(r#"href="https://sorsfonalak.test/meghivo/abc""#));
|
||||
assert!(hu.html.contains("display:none"));
|
||||
assert_eq!(
|
||||
hu.unsubscribe_post_url.as_deref(),
|
||||
Some("https://sorsfonalak.test/api/v1/public/invitations/unsubscribe?token=abc")
|
||||
);
|
||||
|
||||
let mut anonymous = invitation_payload();
|
||||
anonymous["inviter_name"] = Value::Null;
|
||||
anonymous["message"] = Value::Null;
|
||||
let en = render("invitation", "en", &anonymous).unwrap();
|
||||
assert_eq!(en.subject, "You are invited to Sorsfonalak");
|
||||
assert!(en.text.contains("valid until 17 December 2026") && !en.text.contains("> "));
|
||||
assert!(!en.html.contains("border-left"));
|
||||
|
||||
let mut broken = invitation_payload();
|
||||
broken["unsubscribe_url"] = Value::Null;
|
||||
assert_eq!(render("invitation", "hu", &broken), Err(TemplateError::MissingField("unsubscribe_url")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates() {
|
||||
assert_eq!(date(Lang::Hu, "2027-01-05").as_deref(), Some("2027. január 5."));
|
||||
assert_eq!(date(Lang::En, "2027-01-05T10:00:00Z").as_deref(), Some("5 January 2027"));
|
||||
assert_eq!(date(Lang::Hu, "2027-13-05"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "geo-tz"
|
||||
description = "Offline place lookup (GeoNames) and historical time zone resolution (IANA tzdb with backzone)"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
deunicode.workspace = true
|
||||
jiff.workspace = true
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
jiff.workspace = true
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Offline geography and historical civil time.
|
||||
//!
|
||||
//! * [`places`]: country and populated-place lookup from GeoNames dumps.
|
||||
//! * [`tz`]: IANA time zone database (compiled with `backzone`, so every
|
||||
//! country keeps its own pre-1970 daylight saving history) and conversion of
|
||||
//! local civil time to UTC, including DST gaps and folds.
|
||||
//! * [`Atlas`]: both together, plus time zone selection for a birth place.
|
||||
|
||||
pub mod places;
|
||||
pub mod text;
|
||||
pub mod tz;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
pub use places::{Country, Place, PlaceIndex, PlaceMatch};
|
||||
pub use tz::{AmbiguityPolicy, LocalizedTime, TimeZones, TransitionKind};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum GeoError {
|
||||
#[error("failed to load {what}: {reason}")]
|
||||
Data { what: String, reason: String },
|
||||
#[error("unknown country: {0}")]
|
||||
UnknownCountry(String),
|
||||
#[error("no place named '{query}' found in {country}")]
|
||||
PlaceNotFound { query: String, country: String },
|
||||
#[error("unknown GeoNames id: {0}")]
|
||||
UnknownPlaceId(u64),
|
||||
#[error("place {place} (GeoNames {id}) is in {actual}, not in {expected}")]
|
||||
PlaceCountryMismatch { id: u64, place: String, actual: String, expected: String },
|
||||
#[error("unknown time zone: {0}")]
|
||||
UnknownTimeZone(String),
|
||||
#[error("no time zone could be determined for {0}")]
|
||||
NoTimeZone(String),
|
||||
#[error(
|
||||
"local time {datetime} occurs twice in {zone} (clocks were turned back): \
|
||||
offset {earlier} or {later}; set ambiguous_time to \"earlier\" or \"later\""
|
||||
)]
|
||||
AmbiguousTime { datetime: String, zone: String, earlier: String, later: String },
|
||||
#[error(
|
||||
"local time {datetime} does not exist in {zone} (clocks were turned forward from {earlier} to {later}); \
|
||||
set ambiguous_time to \"earlier\" or \"later\" to interpret it with the offset before or after the change"
|
||||
)]
|
||||
NonexistentTime { datetime: String, zone: String, earlier: String, later: String },
|
||||
#[error("invalid date/time: {0}")]
|
||||
InvalidDateTime(String),
|
||||
}
|
||||
|
||||
/// How the time zone of a chart was chosen.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ZoneSource {
|
||||
/// Given explicitly in the request.
|
||||
Request,
|
||||
/// Time zone of the matched GeoNames place.
|
||||
Place,
|
||||
/// The country has a single time zone.
|
||||
Country,
|
||||
/// Time zone of the nearest populated place in the same country.
|
||||
NearestPlace,
|
||||
/// Nearest reference location of the country's zones in `zone.tab`.
|
||||
ZoneTab,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ZoneChoice {
|
||||
pub zone: String,
|
||||
pub source: ZoneSource,
|
||||
}
|
||||
|
||||
pub struct Atlas {
|
||||
pub places: PlaceIndex,
|
||||
pub zones: TimeZones,
|
||||
}
|
||||
|
||||
impl Atlas {
|
||||
/// Loads `geonames/` and `zoneinfo/` from the data directory.
|
||||
pub fn load(data_dir: &Path) -> Result<Self, GeoError> {
|
||||
let zones = TimeZones::load(&data_dir.join("zoneinfo"))?;
|
||||
let places = PlaceIndex::load(&data_dir.join("geonames"))?;
|
||||
Ok(Self { places, zones })
|
||||
}
|
||||
|
||||
/// Chooses the time zone for a birth place.
|
||||
///
|
||||
/// Priority: explicit zone > zone of the matched place > the country's only
|
||||
/// zone > zone of the nearest populated place in the country > nearest
|
||||
/// `zone.tab` reference point of the country.
|
||||
pub fn choose_zone(
|
||||
&self,
|
||||
country: &Country,
|
||||
explicit: Option<&str>,
|
||||
place: Option<&Place>,
|
||||
coordinates: (f64, f64),
|
||||
) -> Result<ZoneChoice, GeoError> {
|
||||
if let Some(zone) = explicit {
|
||||
self.zones.get(zone)?;
|
||||
return Ok(ZoneChoice { zone: zone.to_string(), source: ZoneSource::Request });
|
||||
}
|
||||
if let Some(p) = place.filter(|p| self.zones.exists(&p.timezone)) {
|
||||
return Ok(ZoneChoice { zone: p.timezone.clone(), source: ZoneSource::Place });
|
||||
}
|
||||
let country_zones = self.zones.zones_of(&country.iso2);
|
||||
if let [only] = country_zones {
|
||||
return Ok(ZoneChoice { zone: only.name.clone(), source: ZoneSource::Country });
|
||||
}
|
||||
let (lat, lon) = coordinates;
|
||||
if let Some((nearest, _)) = self.places.nearest(&country.iso2, lat, lon, |p| self.zones.exists(&p.timezone)) {
|
||||
return Ok(ZoneChoice { zone: nearest.timezone.clone(), source: ZoneSource::NearestPlace });
|
||||
}
|
||||
country_zones
|
||||
.iter()
|
||||
.min_by(|a, b| {
|
||||
text::distance_km(lat, lon, a.latitude, a.longitude).total_cmp(&text::distance_km(
|
||||
lat,
|
||||
lon,
|
||||
b.latitude,
|
||||
b.longitude,
|
||||
))
|
||||
})
|
||||
.map(|z| ZoneChoice { zone: z.name.clone(), source: ZoneSource::ZoneTab })
|
||||
.ok_or_else(|| GeoError::NoTimeZone(country.name.clone()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Countries and populated places from GeoNames dumps (CC BY 4.0).
|
||||
//!
|
||||
//! Loaded files (see `scripts/fetch-deps.sh`):
|
||||
//! * `countryInfo.txt`, `admin1CodesASCII.txt`
|
||||
//! * `cities*.txt` (worldwide, e.g. cities500) and `full_XX.txt` (every
|
||||
//! populated place of country XX). Duplicates are merged by GeoNames id.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::GeoError;
|
||||
use crate::text::{distance_km, normalize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Country {
|
||||
/// ISO 3166-1 alpha-2 code.
|
||||
pub iso2: String,
|
||||
/// ISO 3166-1 alpha-3 code.
|
||||
pub iso3: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Place {
|
||||
pub geonames_id: u64,
|
||||
pub name: String,
|
||||
pub country_code: String,
|
||||
/// First-level administrative division (county, state, ...).
|
||||
pub region: Option<String>,
|
||||
pub latitude: f64,
|
||||
pub longitude: f64,
|
||||
pub elevation: Option<i32>,
|
||||
pub population: u64,
|
||||
/// GeoNames feature code (PPL, PPLA, PPLC, PPLX, PPLH, ...).
|
||||
pub feature_code: String,
|
||||
/// IANA time zone of the place.
|
||||
pub timezone: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PlaceMatch {
|
||||
#[serde(flatten)]
|
||||
pub place: Place,
|
||||
/// Which name matched the query.
|
||||
pub matched_name: String,
|
||||
/// Ranking score (higher is better).
|
||||
pub score: f64,
|
||||
}
|
||||
|
||||
pub struct PlaceIndex {
|
||||
countries: Vec<Country>,
|
||||
/// normalized ISO2 / ISO3 / name -> index into `countries`
|
||||
country_keys: HashMap<String, usize>,
|
||||
places: Vec<Place>,
|
||||
/// normalized name -> (place index, is primary name)
|
||||
names: HashMap<String, Vec<(u32, bool)>>,
|
||||
by_id: HashMap<u64, u32>,
|
||||
by_country: HashMap<String, Vec<u32>>,
|
||||
pub downloaded: Option<String>,
|
||||
}
|
||||
|
||||
fn data_err(what: &Path, reason: impl ToString) -> GeoError {
|
||||
GeoError::Data { what: what.display().to_string(), reason: reason.to_string() }
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<String, GeoError> {
|
||||
fs::read_to_string(path).map_err(|e| data_err(path, e))
|
||||
}
|
||||
|
||||
impl PlaceIndex {
|
||||
pub fn load(dir: &Path) -> Result<Self, GeoError> {
|
||||
let mut index = PlaceIndex {
|
||||
countries: Vec::new(),
|
||||
country_keys: HashMap::new(),
|
||||
places: Vec::new(),
|
||||
names: HashMap::new(),
|
||||
by_id: HashMap::new(),
|
||||
by_country: HashMap::new(),
|
||||
downloaded: fs::read_to_string(dir.join("DOWNLOADED")).ok().map(|s| s.trim().to_string()),
|
||||
};
|
||||
index.load_countries(&dir.join("countryInfo.txt"))?;
|
||||
let regions = load_regions(&dir.join("admin1CodesASCII.txt"))?;
|
||||
|
||||
let mut files: Vec<_> = fs::read_dir(dir)
|
||||
.map_err(|e| data_err(dir, e))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default();
|
||||
name.ends_with(".txt") && (name.starts_with("cities") || name.starts_with("full_"))
|
||||
})
|
||||
.collect();
|
||||
// Country files first: they are the most complete for their country.
|
||||
files.sort_by_key(|p| !p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("full_")));
|
||||
if files.is_empty() {
|
||||
return Err(data_err(dir, "no cities*.txt or full_*.txt GeoNames dump found"));
|
||||
}
|
||||
for file in files {
|
||||
index.load_places(&file, ®ions)?;
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
fn load_countries(&mut self, path: &Path) -> Result<(), GeoError> {
|
||||
for line in read(path)?.lines().filter(|l| !l.starts_with('#') && !l.is_empty()) {
|
||||
let f: Vec<&str> = line.split('\t').collect();
|
||||
if f.len() < 5 {
|
||||
continue;
|
||||
}
|
||||
let idx = self.countries.len();
|
||||
self.countries.push(Country { iso2: f[0].into(), iso3: f[1].into(), name: f[4].into() });
|
||||
for key in [f[0], f[1], f[4]] {
|
||||
self.country_keys.entry(normalize(key)).or_insert(idx);
|
||||
}
|
||||
}
|
||||
if self.countries.is_empty() {
|
||||
return Err(data_err(path, "no countries"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_places(&mut self, path: &Path, regions: &HashMap<String, String>) -> Result<(), GeoError> {
|
||||
let content = read(path)?;
|
||||
for line in content.lines() {
|
||||
let f: Vec<&str> = line.split('\t').collect();
|
||||
// geonameid name asciiname alternatenames lat lon fclass fcode cc cc2
|
||||
// admin1 admin2 admin3 admin4 population elevation dem timezone moddate
|
||||
if f.len() < 19 || f[6] != "P" {
|
||||
continue;
|
||||
}
|
||||
let Ok(id) = f[0].parse::<u64>() else { continue };
|
||||
if self.by_id.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
let (Ok(lat), Ok(lon)) = (f[4].parse::<f64>(), f[5].parse::<f64>()) else { continue };
|
||||
let idx = self.places.len() as u32;
|
||||
let country_code = f[8].to_string();
|
||||
let place = Place {
|
||||
geonames_id: id,
|
||||
name: f[1].to_string(),
|
||||
region: regions.get(&format!("{}.{}", f[8], f[10])).cloned(),
|
||||
latitude: lat,
|
||||
longitude: lon,
|
||||
elevation: f[15].parse().ok().or_else(|| f[16].parse().ok().filter(|&d: &i32| d > -9999)),
|
||||
population: f[14].parse().unwrap_or(0),
|
||||
feature_code: f[7].to_string(),
|
||||
timezone: f[17].to_string(),
|
||||
country_code: country_code.clone(),
|
||||
};
|
||||
|
||||
let mut keys: Vec<(String, bool)> = vec![(normalize(f[1]), true), (normalize(f[2]), true)];
|
||||
keys.extend(
|
||||
f[3].split(',')
|
||||
.filter(|n| n.len() > 1 && !n.contains("http") && !n.chars().all(|c| c.is_ascii_digit()))
|
||||
.map(|n| (normalize(n), false)),
|
||||
);
|
||||
keys.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
|
||||
keys.dedup_by(|a, b| a.0 == b.0);
|
||||
for (key, primary) in keys.into_iter().filter(|(k, _)| !k.is_empty()) {
|
||||
self.names.entry(key).or_default().push((idx, primary));
|
||||
}
|
||||
|
||||
self.by_id.insert(id, idx);
|
||||
self.by_country.entry(country_code).or_default().push(idx);
|
||||
self.places.push(place);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.places.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.places.is_empty()
|
||||
}
|
||||
|
||||
pub fn countries(&self) -> &[Country] {
|
||||
&self.countries
|
||||
}
|
||||
|
||||
/// Looks up a country by ISO alpha-2, alpha-3 or English name.
|
||||
pub fn country(&self, query: &str) -> Result<&Country, GeoError> {
|
||||
self.country_keys
|
||||
.get(&normalize(query))
|
||||
.map(|&i| &self.countries[i])
|
||||
.ok_or_else(|| GeoError::UnknownCountry(query.to_string()))
|
||||
}
|
||||
|
||||
pub fn by_id(&self, id: u64) -> Result<&Place, GeoError> {
|
||||
self.by_id.get(&id).map(|&i| &self.places[i as usize]).ok_or(GeoError::UnknownPlaceId(id))
|
||||
}
|
||||
|
||||
/// Searches populated places of a country by name. Exact (normalized)
|
||||
/// matches on any name come first; if there are none, prefix matches are
|
||||
/// returned. `region` optionally filters by first-level division name.
|
||||
pub fn search(&self, country: &Country, query: &str, region: Option<&str>, limit: usize) -> Vec<PlaceMatch> {
|
||||
let q = normalize(query);
|
||||
if q.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let region = region.map(normalize).filter(|r| !r.is_empty());
|
||||
let region_ok = |p: &Place| match (®ion, &p.region) {
|
||||
(None, _) => true,
|
||||
(Some(r), Some(pr)) => normalize(pr).contains(r.as_str()),
|
||||
(Some(_), None) => false,
|
||||
};
|
||||
|
||||
let mut matches: Vec<PlaceMatch> = self
|
||||
.names
|
||||
.get(&q)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|&(i, primary)| (&self.places[i as usize], primary))
|
||||
.filter(|(p, _)| p.country_code == country.iso2 && region_ok(p))
|
||||
.map(|(p, primary)| PlaceMatch {
|
||||
matched_name: query.trim().to_string(),
|
||||
score: score(p, if primary { 2.0 } else { 1.0 }),
|
||||
place: p.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
if matches.is_empty() {
|
||||
matches = self
|
||||
.by_country
|
||||
.get(&country.iso2)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|&i| &self.places[i as usize])
|
||||
.filter(|p| region_ok(p))
|
||||
.filter(|p| normalize(&p.name).starts_with(&q))
|
||||
.map(|p| PlaceMatch { matched_name: p.name.clone(), score: score(p, 0.0), place: p.clone() })
|
||||
.collect();
|
||||
}
|
||||
|
||||
matches.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.place.geonames_id.cmp(&b.place.geonames_id)));
|
||||
matches.dedup_by_key(|m| m.place.geonames_id);
|
||||
matches.truncate(limit);
|
||||
matches
|
||||
}
|
||||
|
||||
/// Nearest populated place of the country that satisfies `accept`.
|
||||
pub fn nearest(
|
||||
&self,
|
||||
country_iso2: &str,
|
||||
lat: f64,
|
||||
lon: f64,
|
||||
accept: impl Fn(&Place) -> bool,
|
||||
) -> Option<(&Place, f64)> {
|
||||
self.by_country
|
||||
.get(country_iso2)?
|
||||
.iter()
|
||||
.map(|&i| &self.places[i as usize])
|
||||
.filter(|p| accept(p))
|
||||
.map(|p| (p, distance_km(lat, lon, p.latitude, p.longitude)))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
}
|
||||
}
|
||||
|
||||
/// Ranking: name quality (primary > alternate > prefix), then administrative
|
||||
/// importance, then population.
|
||||
fn score(p: &Place, name_quality: f64) -> f64 {
|
||||
let importance = match p.feature_code.as_str() {
|
||||
"PPLC" => 6.0,
|
||||
"PPLA" => 5.0,
|
||||
"PPLA2" => 4.0,
|
||||
"PPLA3" | "PPLA4" | "PPLA5" | "PPLG" => 3.0,
|
||||
"PPL" => 2.0,
|
||||
"PPLX" | "PPLL" | "PPLS" | "PPLF" => 1.0,
|
||||
// historical/abandoned places last, but still findable (old birth records)
|
||||
"PPLH" | "PPLQ" | "PPLW" => 0.5,
|
||||
_ => 1.0,
|
||||
};
|
||||
name_quality * 100.0 + importance * 10.0 + (p.population as f64 + 1.0).log10()
|
||||
}
|
||||
|
||||
fn load_regions(path: &Path) -> Result<HashMap<String, String>, GeoError> {
|
||||
Ok(read(path)?
|
||||
.lines()
|
||||
.filter_map(|l| {
|
||||
let mut f = l.split('\t');
|
||||
Some((f.next()?.to_string(), f.next()?.to_string()))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Name normalization and geodesy helpers.
|
||||
|
||||
/// Normalizes a place or country name for matching: transliterates to ASCII,
|
||||
/// lowercases, and collapses everything that is not a letter or digit into
|
||||
/// single spaces ("Hódmezővásárhely" -> "hodmezovasarhely",
|
||||
/// "Budapest XIII. kerület" -> "budapest xiii kerulet").
|
||||
pub fn normalize(name: &str) -> String {
|
||||
let ascii = deunicode::deunicode(name);
|
||||
let mut out = String::with_capacity(ascii.len());
|
||||
let mut pending_space = false;
|
||||
for c in ascii.chars() {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
if pending_space && !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
pending_space = false;
|
||||
out.push(c.to_ascii_lowercase());
|
||||
} else {
|
||||
pending_space = true;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Great-circle distance in kilometers.
|
||||
pub fn distance_km(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
|
||||
const EARTH_RADIUS_KM: f64 = 6371.0;
|
||||
let (p1, p2) = (lat1.to_radians(), lat2.to_radians());
|
||||
let dp = (lat2 - lat1).to_radians();
|
||||
let dl = (lon2 - lon1).to_radians();
|
||||
let a = (dp / 2.0).sin().powi(2) + p1.cos() * p2.cos() * (dl / 2.0).sin().powi(2);
|
||||
2.0 * EARTH_RADIUS_KM * a.sqrt().min(1.0).asin()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalizes_names() {
|
||||
assert_eq!(normalize("Hódmezővásárhely"), "hodmezovasarhely");
|
||||
assert_eq!(normalize(" Budapest XIII. kerület "), "budapest xiii kerulet");
|
||||
assert_eq!(normalize("Kolozsvár"), "kolozsvar");
|
||||
assert_eq!(normalize("Москва"), "moskva");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distances() {
|
||||
// Budapest - Szeged ~ 161 km
|
||||
let d = distance_km(47.4979, 19.0402, 46.253, 20.14824);
|
||||
assert!((155.0..170.0).contains(&d), "{d}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//! IANA time zone database access and local-time resolution.
|
||||
//!
|
||||
//! The zoneinfo directory is compiled by `scripts/fetch-deps.sh` with
|
||||
//! `PACKRATDATA=backzone PACKRATLIST=zone.tab`: every zone listed in
|
||||
//! `zone.tab` keeps its own history before 1970 instead of being linked to
|
||||
//! a zone that merely agrees since 1970 (e.g. Europe/Oslo is not folded into
|
||||
//! Europe/Berlin, so Norway's 1959-1965 summer time is preserved).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use jiff::Timestamp;
|
||||
use jiff::civil::DateTime;
|
||||
use jiff::tz::{AmbiguousOffset, Offset, TimeZone, TimeZoneDatabase};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::GeoError;
|
||||
|
||||
/// What to do when a local time is ambiguous (clocks turned back, the hour
|
||||
/// happens twice) or does not exist (clocks turned forward).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AmbiguityPolicy {
|
||||
/// Return an error that explains both possibilities.
|
||||
#[default]
|
||||
Reject,
|
||||
/// Use the offset in effect before the transition (usually summer time in autumn).
|
||||
Earlier,
|
||||
/// Use the offset in effect after the transition.
|
||||
Later,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TransitionKind {
|
||||
/// The local time did not exist (clocks turned forward).
|
||||
Gap,
|
||||
/// The local time happened twice (clocks turned back).
|
||||
Fold,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Transition {
|
||||
pub kind: TransitionKind,
|
||||
pub offset_before: String,
|
||||
pub offset_after: String,
|
||||
pub resolved_with: AmbiguityPolicy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct LocalizedTime {
|
||||
/// IANA zone name; `None` for a fixed offset given in the request.
|
||||
pub zone: Option<String>,
|
||||
/// Local civil time as given.
|
||||
pub local: String,
|
||||
/// The same instant in UTC (RFC 3339).
|
||||
pub utc: String,
|
||||
#[serde(skip)]
|
||||
pub timestamp: Timestamp,
|
||||
pub utc_offset: String,
|
||||
pub utc_offset_seconds: i32,
|
||||
/// Daylight saving (summer) time was in effect.
|
||||
pub dst: bool,
|
||||
/// Zone abbreviation, e.g. CET, CEST, LMT.
|
||||
pub abbreviation: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub transition: Option<Transition>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ZoneTabEntry {
|
||||
pub name: String,
|
||||
/// Reference location of the zone (its principal city).
|
||||
pub latitude: f64,
|
||||
pub longitude: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
pub struct TimeZones {
|
||||
db: TimeZoneDatabase,
|
||||
pub version: String,
|
||||
zone_tab: HashMap<String, Vec<ZoneTabEntry>>,
|
||||
}
|
||||
|
||||
impl TimeZones {
|
||||
pub fn load(dir: &Path) -> Result<Self, GeoError> {
|
||||
let err = |reason: String| GeoError::Data { what: dir.display().to_string(), reason };
|
||||
let zone_tab_path = dir.join("zone.tab");
|
||||
let content = fs::read_to_string(&zone_tab_path).map_err(|e| err(format!("zone.tab: {e}")))?;
|
||||
let mut zone_tab: HashMap<String, Vec<ZoneTabEntry>> = HashMap::new();
|
||||
for line in content.lines().filter(|l| !l.starts_with('#') && !l.trim().is_empty()) {
|
||||
let f: Vec<&str> = line.split('\t').collect();
|
||||
if f.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let Some((latitude, longitude)) = parse_iso6709(f[1]) else { continue };
|
||||
zone_tab.entry(f[0].to_string()).or_default().push(ZoneTabEntry {
|
||||
name: f[2].to_string(),
|
||||
latitude,
|
||||
longitude,
|
||||
comment: f.get(3).map(|c| c.to_string()),
|
||||
});
|
||||
}
|
||||
let db = TimeZoneDatabase::from_dir(dir).map_err(|e| err(e.to_string()))?;
|
||||
let version = fs::read_to_string(dir.join("VERSION")).map(|s| s.trim().to_string()).unwrap_or_default();
|
||||
let tz = Self { db, version, zone_tab };
|
||||
// Fail fast on an empty or broken directory.
|
||||
tz.get("Europe/Budapest").map_err(|e| err(e.to_string()))?;
|
||||
Ok(tz)
|
||||
}
|
||||
|
||||
pub fn get(&self, name: &str) -> Result<TimeZone, GeoError> {
|
||||
self.db.get(name).map_err(|_| GeoError::UnknownTimeZone(name.to_string()))
|
||||
}
|
||||
|
||||
pub fn exists(&self, name: &str) -> bool {
|
||||
!name.is_empty() && self.db.get(name).is_ok()
|
||||
}
|
||||
|
||||
/// Zones of a country according to `zone.tab`.
|
||||
pub fn zones_of(&self, iso2: &str) -> &[ZoneTabEntry] {
|
||||
self.zone_tab.get(iso2).map(Vec::as_slice).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Converts local civil time in `zone` to an instant.
|
||||
pub fn localize(&self, zone: &str, local: DateTime, policy: AmbiguityPolicy) -> Result<LocalizedTime, GeoError> {
|
||||
let tz = self.get(zone)?;
|
||||
let ambiguous = tz.to_ambiguous_timestamp(local);
|
||||
let (timestamp, transition) = match ambiguous.offset() {
|
||||
AmbiguousOffset::Unambiguous { offset } => (to_timestamp(local, offset)?, None),
|
||||
AmbiguousOffset::Gap { before, after } | AmbiguousOffset::Fold { before, after } => {
|
||||
let kind = if matches!(ambiguous.offset(), AmbiguousOffset::Gap { .. }) {
|
||||
TransitionKind::Gap
|
||||
} else {
|
||||
TransitionKind::Fold
|
||||
};
|
||||
let offset = match policy {
|
||||
AmbiguityPolicy::Earlier => before,
|
||||
AmbiguityPolicy::Later => after,
|
||||
AmbiguityPolicy::Reject => {
|
||||
let (datetime, zone) = (local.to_string(), zone.to_string());
|
||||
let (earlier, later) = (format_offset(before), format_offset(after));
|
||||
return Err(match kind {
|
||||
TransitionKind::Fold => GeoError::AmbiguousTime { datetime, zone, earlier, later },
|
||||
TransitionKind::Gap => GeoError::NonexistentTime { datetime, zone, earlier, later },
|
||||
});
|
||||
}
|
||||
};
|
||||
let transition = Transition {
|
||||
kind,
|
||||
offset_before: format_offset(before),
|
||||
offset_after: format_offset(after),
|
||||
resolved_with: policy,
|
||||
};
|
||||
(to_timestamp(local, offset)?, Some(transition))
|
||||
}
|
||||
};
|
||||
|
||||
let info = tz.to_offset_info(timestamp);
|
||||
let offset = info.offset();
|
||||
Ok(LocalizedTime {
|
||||
zone: Some(zone.to_string()),
|
||||
local: local.to_string(),
|
||||
utc: timestamp.to_string(),
|
||||
timestamp,
|
||||
utc_offset: format_offset(offset),
|
||||
utc_offset_seconds: offset.seconds(),
|
||||
dst: info.dst().is_dst(),
|
||||
abbreviation: info.abbreviation().to_string(),
|
||||
transition,
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts local civil time with an explicitly given UTC offset.
|
||||
pub fn localize_fixed(&self, local: DateTime, offset_seconds: i32) -> Result<LocalizedTime, GeoError> {
|
||||
let offset = Offset::from_seconds(offset_seconds).map_err(|e| GeoError::InvalidDateTime(e.to_string()))?;
|
||||
let timestamp = to_timestamp(local, offset)?;
|
||||
Ok(LocalizedTime {
|
||||
zone: None,
|
||||
local: local.to_string(),
|
||||
utc: timestamp.to_string(),
|
||||
timestamp,
|
||||
utc_offset: format_offset(offset),
|
||||
utc_offset_seconds: offset_seconds,
|
||||
dst: false,
|
||||
abbreviation: format_offset(offset),
|
||||
transition: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn to_timestamp(local: DateTime, offset: Offset) -> Result<Timestamp, GeoError> {
|
||||
offset.to_timestamp(local).map_err(|e| GeoError::InvalidDateTime(e.to_string()))
|
||||
}
|
||||
|
||||
/// `+02:00`, or `+01:16:20` when the offset has seconds (local mean time).
|
||||
pub fn format_offset(offset: Offset) -> String {
|
||||
let total = offset.seconds();
|
||||
let sign = if total < 0 { '-' } else { '+' };
|
||||
let abs = total.unsigned_abs();
|
||||
let (h, m, s) = (abs / 3600, (abs / 60) % 60, abs % 60);
|
||||
if s == 0 { format!("{sign}{h:02}:{m:02}") } else { format!("{sign}{h:02}:{m:02}:{s:02}") }
|
||||
}
|
||||
|
||||
/// Parses an offset like `+02:00`, `-05:30`, `+01:16:20`, `+0200` or `Z`.
|
||||
pub fn parse_offset(text: &str) -> Option<i32> {
|
||||
let t = text.trim();
|
||||
if t.eq_ignore_ascii_case("z") || t.eq_ignore_ascii_case("utc") {
|
||||
return Some(0);
|
||||
}
|
||||
let (sign, rest) = match t.as_bytes().first()? {
|
||||
b'+' => (1, &t[1..]),
|
||||
b'-' => (-1, &t[1..]),
|
||||
_ => return None,
|
||||
};
|
||||
let parts: Vec<&str> = if rest.contains(':') {
|
||||
rest.split(':').collect()
|
||||
} else if rest.len() == 4 && rest.chars().all(|c| c.is_ascii_digit()) {
|
||||
vec![&rest[..2], &rest[2..]]
|
||||
} else {
|
||||
vec![rest]
|
||||
};
|
||||
let nums: Vec<i32> = parts.iter().map(|p| p.parse::<i32>().ok()).collect::<Option<_>>()?;
|
||||
let (h, m, s) = match nums.as_slice() {
|
||||
[h] => (*h, 0, 0),
|
||||
[h, m] => (*h, *m, 0),
|
||||
[h, m, s] => (*h, *m, *s),
|
||||
_ => return None,
|
||||
};
|
||||
if !(0..=18).contains(&h) || !(0..60).contains(&m) || !(0..60).contains(&s) {
|
||||
return None;
|
||||
}
|
||||
Some(sign * (h * 3600 + m * 60 + s))
|
||||
}
|
||||
|
||||
/// Parses ISO 6709 coordinates as used in zone.tab: `+4730+01905` or
|
||||
/// `+404251-0740023`.
|
||||
fn parse_iso6709(s: &str) -> Option<(f64, f64)> {
|
||||
let split = s[1..].find(['+', '-'])? + 1;
|
||||
let (lat, lon) = s.split_at(split);
|
||||
Some((parse_dms(lat, 2)?, parse_dms(lon, 3)?))
|
||||
}
|
||||
|
||||
fn parse_dms(s: &str, degree_digits: usize) -> Option<f64> {
|
||||
let sign = if s.starts_with('-') { -1.0 } else { 1.0 };
|
||||
let digits = &s[1..];
|
||||
let num = |r: std::ops::Range<usize>| digits.get(r).and_then(|d| d.parse::<f64>().ok());
|
||||
let d = num(0..degree_digits)?;
|
||||
let m = num(degree_digits..degree_digits + 2)?;
|
||||
let sec = if digits.len() > degree_digits + 2 { num(degree_digits + 2..degree_digits + 4)? } else { 0.0 };
|
||||
Some(sign * (d + m / 60.0 + sec / 3600.0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn iso6709() {
|
||||
let (lat, lon) = parse_iso6709("+4730+01905").unwrap();
|
||||
assert!((lat - 47.5).abs() < 1e-9 && (lon - (19.0 + 5.0 / 60.0)).abs() < 1e-9);
|
||||
let (lat, lon) = parse_iso6709("+404251-0740023").unwrap();
|
||||
assert!((lat - 40.714_166).abs() < 1e-5 && (lon + 74.006_388).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets() {
|
||||
assert_eq!(parse_offset("+02:00"), Some(7200));
|
||||
assert_eq!(parse_offset("-05:30"), Some(-19800));
|
||||
assert_eq!(parse_offset("+01:16:20"), Some(4580));
|
||||
assert_eq!(parse_offset("+0100"), Some(3600));
|
||||
assert_eq!(parse_offset("Z"), Some(0));
|
||||
assert_eq!(parse_offset("2"), None);
|
||||
assert_eq!(parse_offset("+25:00"), None);
|
||||
assert_eq!(format_offset(Offset::from_seconds(4580).unwrap()), "+01:16:20");
|
||||
assert_eq!(format_offset(Offset::from_seconds(-12600).unwrap()), "-03:30");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Tests against the real downloaded data (`scripts/fetch-deps.sh`).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use geo_tz::{AmbiguityPolicy, Atlas, GeoError, TransitionKind, ZoneSource};
|
||||
use jiff::civil::date;
|
||||
|
||||
fn atlas() -> &'static Atlas {
|
||||
static ATLAS: OnceLock<Atlas> = OnceLock::new();
|
||||
ATLAS.get_or_init(|| {
|
||||
let dir = std::env::var_os("ASTRO_DATA_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../data"));
|
||||
Atlas::load(&dir).expect("data directory (run scripts/fetch-deps.sh)")
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn country_lookup() {
|
||||
let a = atlas();
|
||||
assert_eq!(a.places.country("HU").unwrap().name, "Hungary");
|
||||
assert_eq!(a.places.country("hun").unwrap().iso2, "HU");
|
||||
assert_eq!(a.places.country("hungary").unwrap().iso2, "HU");
|
||||
assert!(matches!(a.places.country("XX"), Err(GeoError::UnknownCountry(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn place_search_handles_accents_villages_and_foreign_names() {
|
||||
let a = atlas();
|
||||
let hu = a.places.country("HU").unwrap();
|
||||
let szeged = &a.places.search(hu, "Szeged", None, 5)[0];
|
||||
assert_eq!(szeged.place.geonames_id, 715429);
|
||||
assert_eq!(szeged.place.timezone, "Europe/Budapest");
|
||||
|
||||
let hmv = a.places.search(hu, "hodmezovasarhely", None, 5);
|
||||
assert_eq!(hmv[0].place.name, "Hódmezővásárhely");
|
||||
|
||||
// a tiny village (population well below 500) from the full HU list
|
||||
let village = a.places.search(hu, "Iborfia", None, 5);
|
||||
assert!(!village.is_empty(), "small villages must be found");
|
||||
|
||||
// Hungarian name of a Romanian city
|
||||
let ro = a.places.country("RO").unwrap();
|
||||
let cluj = &a.places.search(ro, "Kolozsvár", None, 5)[0];
|
||||
assert_eq!(cluj.place.name, "Cluj-Napoca");
|
||||
assert_eq!(cluj.place.timezone, "Europe/Bucharest");
|
||||
|
||||
// prefix fallback
|
||||
assert!(!a.places.search(hu, "Hódmező", None, 5).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zone_choice() {
|
||||
let a = atlas();
|
||||
let hu = a.places.country("HU").unwrap();
|
||||
let z = a.choose_zone(hu, None, None, (47.5, 19.0)).unwrap();
|
||||
assert_eq!((z.zone.as_str(), z.source), ("Europe/Budapest", ZoneSource::Country));
|
||||
|
||||
// multi-zone country resolved from coordinates (Denver)
|
||||
let us = a.places.country("US").unwrap();
|
||||
let z = a.choose_zone(us, None, None, (39.74, -104.99)).unwrap();
|
||||
assert_eq!((z.zone.as_str(), z.source), ("America/Denver", ZoneSource::NearestPlace));
|
||||
|
||||
assert!(a.choose_zone(hu, Some("Mars/Olympus"), None, (0.0, 0.0)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hungarian_dst_history() {
|
||||
let tz = &atlas().zones;
|
||||
// 1985 summer: CEST
|
||||
let t = tz.localize("Europe/Budapest", date(1985, 7, 14).at(14, 30, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert_eq!((t.utc_offset.as_str(), t.dst, t.abbreviation.as_str()), ("+02:00", true, "CEST"));
|
||||
assert_eq!(t.utc, "1985-07-14T12:30:00Z");
|
||||
// 1970 summer: Hungary had no DST between 1958 and 1979
|
||||
let t = tz.localize("Europe/Budapest", date(1970, 7, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert_eq!((t.utc_offset.as_str(), t.dst), ("+01:00", false));
|
||||
// 1956 summer: DST was used
|
||||
let t = tz.localize("Europe/Budapest", date(1956, 7, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert_eq!((t.utc_offset.as_str(), t.dst), ("+02:00", true));
|
||||
// before 1890: local mean time of Budapest
|
||||
let t = tz.localize("Europe/Budapest", date(1880, 3, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert_eq!((t.utc_offset.as_str(), t.abbreviation.as_str()), ("+01:16:20", "LMT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backzone_keeps_national_history() {
|
||||
let tz = &atlas().zones;
|
||||
// Norway had summer time 1959-1965, Germany did not (1950-1979).
|
||||
let oslo = tz.localize("Europe/Oslo", date(1960, 7, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
let berlin = tz.localize("Europe/Berlin", date(1960, 7, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert!(oslo.dst && !berlin.dst, "oslo {oslo:?} berlin {berlin:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dst_gaps_and_folds() {
|
||||
let tz = &atlas().zones;
|
||||
// 2023-10-29 02:30 happened twice in Budapest
|
||||
let fold = date(2023, 10, 29).at(2, 30, 0, 0);
|
||||
assert!(matches!(
|
||||
tz.localize("Europe/Budapest", fold, AmbiguityPolicy::Reject),
|
||||
Err(GeoError::AmbiguousTime { .. })
|
||||
));
|
||||
let early = tz.localize("Europe/Budapest", fold, AmbiguityPolicy::Earlier).unwrap();
|
||||
let late = tz.localize("Europe/Budapest", fold, AmbiguityPolicy::Later).unwrap();
|
||||
assert_eq!((early.utc_offset.as_str(), late.utc_offset.as_str()), ("+02:00", "+01:00"));
|
||||
assert_eq!(early.transition.as_ref().unwrap().kind, TransitionKind::Fold);
|
||||
|
||||
// 2023-03-26 02:30 did not exist
|
||||
let gap = date(2023, 3, 26).at(2, 30, 0, 0);
|
||||
assert!(matches!(
|
||||
tz.localize("Europe/Budapest", gap, AmbiguityPolicy::Reject),
|
||||
Err(GeoError::NonexistentTime { .. })
|
||||
));
|
||||
let t = tz.localize("Europe/Budapest", gap, AmbiguityPolicy::Earlier).unwrap();
|
||||
assert_eq!(t.transition.unwrap().kind, TransitionKind::Gap);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_offset() {
|
||||
let t = atlas().zones.localize_fixed(date(1944, 5, 1).at(10, 0, 0, 0), 7200).unwrap();
|
||||
assert_eq!(t.utc, "1944-05-01T08:00:00Z");
|
||||
assert_eq!(t.zone, None);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "horoscope-client"
|
||||
description = "HTTP client of the horoscope-api service"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
reqwest.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Client of the horoscope-api service (`POST /v1/natal`, `POST /v1/synastry`).
|
||||
//!
|
||||
//! Requests and responses are passed as JSON: the horoscope service validates
|
||||
//! the birth data itself, and its error objects are handed back unchanged so
|
||||
//! callers can show them to the user.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum HoroscopeError {
|
||||
/// The service rejected the input (4xx); `body` is its `{"error": {...}}` object.
|
||||
#[error("horoscope service rejected the request ({status})")]
|
||||
Rejected { status: u16, body: Value },
|
||||
/// The service is unreachable or failed (5xx, timeout, invalid response).
|
||||
#[error("horoscope service unavailable: {0}")]
|
||||
Unavailable(String),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HoroscopeClient {
|
||||
base_url: String,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
impl HoroscopeClient {
|
||||
pub fn new(base_url: impl Into<String>) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(15))
|
||||
.build()
|
||||
.expect("static reqwest configuration is valid");
|
||||
Self { base_url: base_url.into().trim_end_matches('/').to_string(), http }
|
||||
}
|
||||
|
||||
/// `POST /v1/natal`
|
||||
pub async fn natal(&self, request: &Value) -> Result<Value, HoroscopeError> {
|
||||
self.post("/v1/natal", request).await
|
||||
}
|
||||
|
||||
/// `POST /v1/synastry`
|
||||
pub async fn synastry(&self, request: &Value) -> Result<Value, HoroscopeError> {
|
||||
self.post("/v1/synastry", request).await
|
||||
}
|
||||
|
||||
async fn post(&self, path: &str, body: &Value) -> Result<Value, HoroscopeError> {
|
||||
let response = self
|
||||
.http
|
||||
.post(format!("{}{path}", self.base_url))
|
||||
.json(body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| HoroscopeError::Unavailable(e.to_string()))?;
|
||||
let status = response.status();
|
||||
let body: Value = response.json().await.map_err(|e| HoroscopeError::Unavailable(e.to_string()))?;
|
||||
if status.is_success() {
|
||||
Ok(body)
|
||||
} else if status.is_client_error() {
|
||||
Err(HoroscopeError::Rejected { status: status.as_u16(), body })
|
||||
} else {
|
||||
Err(HoroscopeError::Unavailable(format!("{status}: {body}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "service-kit"
|
||||
description = "Shared plumbing for the HTTP services: logging, listen address, health check, shutdown"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Plumbing shared by every HTTP service.
|
||||
//!
|
||||
//! Environment:
|
||||
//! * `BIND_ADDR` listen address (each service has its own default)
|
||||
//! * `LOG_FORMAT` `text` (default) or `json`; `RUST_LOG` sets the level
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
|
||||
/// Initializes `tracing` from `RUST_LOG` and `LOG_FORMAT`.
|
||||
pub fn init_logging() {
|
||||
use tracing_subscriber::EnvFilter;
|
||||
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info,tower_http=info"));
|
||||
let builder = tracing_subscriber::fmt().with_env_filter(filter);
|
||||
if std::env::var("LOG_FORMAT").is_ok_and(|f| f.eq_ignore_ascii_case("json")) {
|
||||
builder.json().init();
|
||||
} else {
|
||||
builder.init();
|
||||
}
|
||||
}
|
||||
|
||||
/// Listen address from `BIND_ADDR`, or `default`.
|
||||
pub fn bind_addr(default: &str) -> anyhow::Result<SocketAddr> {
|
||||
let raw = std::env::var("BIND_ADDR").unwrap_or_else(|_| default.into());
|
||||
raw.parse().with_context(|| format!("invalid BIND_ADDR '{raw}'"))
|
||||
}
|
||||
|
||||
/// Minimal HTTP GET against `/healthz` of the local service, so scratch
|
||||
/// images need no curl. Used by the `healthcheck` subcommand.
|
||||
pub fn healthcheck(mut addr: SocketAddr) -> anyhow::Result<()> {
|
||||
use std::io::{Read, Write};
|
||||
if addr.ip().is_unspecified() {
|
||||
addr.set_ip([127, 0, 0, 1].into());
|
||||
}
|
||||
let mut stream = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(2))?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
stream.write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")?;
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response)?;
|
||||
anyhow::ensure!(response.starts_with("HTTP/1.1 200"), "unhealthy: {}", response.lines().next().unwrap_or(""));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolves on Ctrl+C or SIGTERM (graceful shutdown in Docker).
|
||||
pub async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
};
|
||||
#[cfg(unix)]
|
||||
let terminate = async {
|
||||
if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
||||
s.recv().await;
|
||||
}
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let terminate = std::future::pending::<()>();
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {},
|
||||
_ = terminate => {},
|
||||
}
|
||||
tracing::info!("shutting down");
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "swisseph-sys"
|
||||
description = "Raw FFI bindings to the Swiss Ephemeris C library (sources in vendor/swisseph)"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
links = "swe"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
@@ -0,0 +1,44 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Library objects as listed in the upstream Makefile (SWEOBJ).
|
||||
const SOURCES: &[&str] = &[
|
||||
"swedate.c",
|
||||
"swehouse.c",
|
||||
"swejpl.c",
|
||||
"swemmoon.c",
|
||||
"swemplan.c",
|
||||
"sweph.c",
|
||||
"swephlib.c",
|
||||
"swecl.c",
|
||||
"swehel.c",
|
||||
];
|
||||
|
||||
fn main() {
|
||||
let dir = std::env::var_os("SWISSEPH_SRC_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../vendor/swisseph"));
|
||||
if !dir.join("sweph.c").exists() {
|
||||
panic!(
|
||||
"Swiss Ephemeris sources not found in {}. Run scripts/fetch-deps.sh first \
|
||||
(or set SWISSEPH_SRC_DIR).",
|
||||
dir.display()
|
||||
);
|
||||
}
|
||||
|
||||
let mut build = cc::Build::new();
|
||||
build
|
||||
.include(&dir)
|
||||
// Globals are shared between threads; the Rust side serializes access.
|
||||
.define("TLSOFF", None)
|
||||
.opt_level(2)
|
||||
.warnings(false);
|
||||
for src in SOURCES {
|
||||
let path = dir.join(src);
|
||||
println!("cargo:rerun-if-changed={}", path.display());
|
||||
build.file(path);
|
||||
}
|
||||
build.compile("swe");
|
||||
|
||||
println!("cargo:rerun-if-env-changed=SWISSEPH_SRC_DIR");
|
||||
println!("cargo:rustc-link-lib=m");
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Raw FFI bindings to the subset of the Swiss Ephemeris API used by the
|
||||
//! services. The library keeps global state (ephemeris path, sidereal mode,
|
||||
//! open file handles) and is compiled with `TLSOFF`, so every call must be
|
||||
//! serialized by the caller.
|
||||
#![allow(non_upper_case_globals)]
|
||||
|
||||
use std::os::raw::{c_char, c_double, c_int};
|
||||
|
||||
pub const OK: i32 = 0;
|
||||
pub const ERR: i32 = -1;
|
||||
/// Size of the error string buffers (`AS_MAXCH`).
|
||||
pub const AS_MAXCH: usize = 256;
|
||||
|
||||
pub const SE_JUL_CAL: c_int = 0;
|
||||
pub const SE_GREG_CAL: c_int = 1;
|
||||
|
||||
pub const SE_ECL_NUT: i32 = -1;
|
||||
pub const SE_SUN: i32 = 0;
|
||||
pub const SE_MOON: i32 = 1;
|
||||
pub const SE_MERCURY: i32 = 2;
|
||||
pub const SE_VENUS: i32 = 3;
|
||||
pub const SE_MARS: i32 = 4;
|
||||
pub const SE_JUPITER: i32 = 5;
|
||||
pub const SE_SATURN: i32 = 6;
|
||||
pub const SE_URANUS: i32 = 7;
|
||||
pub const SE_NEPTUNE: i32 = 8;
|
||||
pub const SE_PLUTO: i32 = 9;
|
||||
pub const SE_MEAN_NODE: i32 = 10;
|
||||
pub const SE_TRUE_NODE: i32 = 11;
|
||||
pub const SE_MEAN_APOG: i32 = 12;
|
||||
pub const SE_OSCU_APOG: i32 = 13;
|
||||
pub const SE_CHIRON: i32 = 15;
|
||||
pub const SE_PHOLUS: i32 = 16;
|
||||
pub const SE_CERES: i32 = 17;
|
||||
pub const SE_PALLAS: i32 = 18;
|
||||
pub const SE_JUNO: i32 = 19;
|
||||
pub const SE_VESTA: i32 = 20;
|
||||
|
||||
pub const SEFLG_JPLEPH: i32 = 1;
|
||||
pub const SEFLG_SWIEPH: i32 = 2;
|
||||
pub const SEFLG_MOSEPH: i32 = 4;
|
||||
pub const SEFLG_TRUEPOS: i32 = 16;
|
||||
pub const SEFLG_NONUT: i32 = 64;
|
||||
pub const SEFLG_SPEED: i32 = 256;
|
||||
pub const SEFLG_EQUATORIAL: i32 = 2 * 1024;
|
||||
pub const SEFLG_TOPOCTR: i32 = 32 * 1024;
|
||||
pub const SEFLG_SIDEREAL: i32 = 64 * 1024;
|
||||
|
||||
pub const SE_SIDM_FAGAN_BRADLEY: i32 = 0;
|
||||
pub const SE_SIDM_LAHIRI: i32 = 1;
|
||||
pub const SE_SIDM_DELUCE: i32 = 2;
|
||||
pub const SE_SIDM_RAMAN: i32 = 3;
|
||||
pub const SE_SIDM_KRISHNAMURTI: i32 = 5;
|
||||
pub const SE_SIDM_YUKTESHWAR: i32 = 7;
|
||||
pub const SE_SIDM_GALCENT_0SAG: i32 = 17;
|
||||
pub const SE_SIDM_TRUE_CITRA: i32 = 27;
|
||||
|
||||
unsafe extern "C" {
|
||||
pub fn swe_version(s: *mut c_char) -> *mut c_char;
|
||||
pub fn swe_set_ephe_path(path: *const c_char);
|
||||
pub fn swe_close();
|
||||
pub fn swe_set_sid_mode(sid_mode: i32, t0: c_double, ayan_t0: c_double);
|
||||
pub fn swe_get_ayanamsa_ex_ut(tjd_ut: c_double, iflag: i32, daya: *mut c_double, serr: *mut c_char) -> i32;
|
||||
pub fn swe_set_topo(geolon: c_double, geolat: c_double, geoalt: c_double);
|
||||
|
||||
pub fn swe_calc_ut(tjd_ut: c_double, ipl: i32, iflag: i32, xx: *mut c_double, serr: *mut c_char) -> i32;
|
||||
pub fn swe_pheno_ut(tjd_ut: c_double, ipl: i32, iflag: i32, attr: *mut c_double, serr: *mut c_char) -> i32;
|
||||
|
||||
pub fn swe_houses_ex2(
|
||||
tjd_ut: c_double,
|
||||
iflag: i32,
|
||||
geolat: c_double,
|
||||
geolon: c_double,
|
||||
hsys: c_int,
|
||||
cusps: *mut c_double,
|
||||
ascmc: *mut c_double,
|
||||
cusp_speed: *mut c_double,
|
||||
ascmc_speed: *mut c_double,
|
||||
serr: *mut c_char,
|
||||
) -> c_int;
|
||||
pub fn swe_house_name(hsys: c_int) -> *const c_char;
|
||||
|
||||
pub fn swe_julday(year: c_int, month: c_int, day: c_int, hour: c_double, gregflag: c_int) -> c_double;
|
||||
pub fn swe_revjul(
|
||||
jd: c_double,
|
||||
gregflag: c_int,
|
||||
jyear: *mut c_int,
|
||||
jmon: *mut c_int,
|
||||
jday: *mut c_int,
|
||||
jut: *mut c_double,
|
||||
);
|
||||
pub fn swe_utc_to_jd(
|
||||
iyear: i32,
|
||||
imonth: i32,
|
||||
iday: i32,
|
||||
ihour: i32,
|
||||
imin: i32,
|
||||
dsec: c_double,
|
||||
gregflag: i32,
|
||||
dret: *mut c_double,
|
||||
serr: *mut c_char,
|
||||
) -> i32;
|
||||
pub fn swe_deltat_ex(tjd: c_double, iflag: i32, serr: *mut c_char) -> c_double;
|
||||
pub fn swe_sidtime(tjd_ut: c_double) -> c_double;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
# Copy to /opt/sorsfonalak/.env on the server and fill in.
|
||||
|
||||
# Public domain (Caddy gets the certificate for it and www.<domain>)
|
||||
DOMAIN=sorsfonalak.hu
|
||||
# Long random string: openssl rand -hex 24
|
||||
POSTGRES_PASSWORD=
|
||||
|
||||
# Google OAuth client ID(s), comma-separated
|
||||
GOOGLE_CLIENT_IDS=
|
||||
# These accounts become admins at their first login
|
||||
BOOTSTRAP_ADMIN_EMAILS=
|
||||
|
||||
# Outgoing mail: Amazon SES (docs/levelkuldes.md). The credentials go to .env.secrets:
|
||||
# SES_SMTP_USERNAME + SES_SMTP_PASSWORD, or AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY.
|
||||
SES_REGION=eu-central-1
|
||||
MAIL_FROM=Sorsfonalak <hello@sorsfonalak.hu>
|
||||
|
||||
# invite: new accounts need an invitation (default); open: anyone can sign up
|
||||
SIGNUP_MODE=invite
|
||||
|
||||
# Image version; every deployment rewrites it
|
||||
TAG=latest
|
||||
@@ -0,0 +1,22 @@
|
||||
# Behind the Cloudflare proxy. The certificate comes from Let's Encrypt
|
||||
# (HTTP-01 challenge through Cloudflare), so "Always Use HTTPS" must stay off
|
||||
# in Cloudflare; Caddy does the redirect itself. SSL mode: Full (strict).
|
||||
{
|
||||
servers {
|
||||
# Cloudflare ranges (https://www.cloudflare.com/ips): the visitor's
|
||||
# address is taken from CF-Connecting-IP and passed on in X-Forwarded-For.
|
||||
trusted_proxies static 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32
|
||||
client_ip_headers CF-Connecting-IP
|
||||
}
|
||||
}
|
||||
|
||||
{$DOMAIN} {
|
||||
# No basic auth any more: the site is open, and new accounts need an
|
||||
# invitation (SIGNUP_MODE=invite in the backend).
|
||||
encode zstd gzip
|
||||
reverse_proxy frontend:3000
|
||||
}
|
||||
|
||||
www.{$DOMAIN} {
|
||||
redir https://{$DOMAIN}{uri} permanent
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
# Build és telepítés
|
||||
|
||||
A `.gitea/workflows/ci.yml` (Gitea Actions) két ágra fut:
|
||||
|
||||
- **main**: tesztek, majd image-build. Címkék: a commit hash első 12 karaktere és `main`.
|
||||
- **prod**: ugyanez, majd telepítés a szerverre. Címkék: hash, `prod` és `latest`. Élesíteni tehát úgy kell, hogy a main-t a prod-ba mergeled (vagy pusholod).
|
||||
|
||||
A lépések:
|
||||
|
||||
1. **test**: `cargo test` a backendre, a workerre, a db-re, a horoscope-clientre és a service-kitre, egy Postgres szolgáltatás-konténerrel.
|
||||
2. **build**: megépíti a négy image-et, és feltölti őket a `registry.sagifer.com/sagifer/sorsfonalak-<szolgáltatás>` címre. A frontend buildje a TypeScript-típusokat is ellenőrzi. Egy main-en már megépült commit a cache-ből pár mp alatt újraépül.
|
||||
3. **deploy** (csak prod): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, beírja az új `TAG`-et a szerveren lévő `.env`-be, majd `docker compose pull && up -d`. Az adatbázis-migrációk a backend indulásakor futnak le.
|
||||
4. **release** (csak prod, a deploy után): létrehoz egy `v<év.hónap.nap>-<hash>` taget és Gitea-release-t az előző release óta bekerült commitok listájával (repó → Releases).
|
||||
|
||||
Kézzel is indítható a repó Actions oldaláról (workflow_dispatch).
|
||||
|
||||
## Runner (dev szerver)
|
||||
|
||||
A runner a `ci/runner` mappában van. A jobokat a gép Dockerén indítja, így az image-buildek a meglévő BuildKit cache-t használják. A tesztek cargo-cache-e a `sorsfonalak-ci-*` kötetekben marad meg.
|
||||
|
||||
1. Regisztrációs token: Gitea → repó → Beállítások → Actions → Runners → *Create new runner*.
|
||||
2. Indítás:
|
||||
```sh
|
||||
cd ci/runner
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN=<token> docker compose up -d
|
||||
```
|
||||
A regisztráció a `runner-data` kötetbe kerül. A későbbi indításokhoz már nem kell token.
|
||||
|
||||
A jobok elérik a gép Docker-socketjét, ez root-jogot jelent a dev szerveren. A workflow csak a repóba pusholt commitokra fut, forkból érkező pull requestekre nem.
|
||||
|
||||
## Repó-beállítások
|
||||
|
||||
Gitea → repó → Beállítások → Actions:
|
||||
|
||||
| Név | Fajta | Érték |
|
||||
|---|---|---|
|
||||
| `REGISTRY_TOKEN` | secret | a `sagifer` fiók access tokenje, `write:package` jogosultsággal |
|
||||
| `DEPLOY_SSH_KEY` | secret | a szerveren lévő deploy felhasználó privát kulcsa |
|
||||
| `DEPLOY_HOST` | variable | `deploy@<szerver IP>` |
|
||||
| `DEPLOY_KNOWN_HOSTS` | variable | az `ssh-keyscan <szerver IP>` kimenete |
|
||||
| `DEPLOY_PATH` | variable | nem kötelező, alapértéke `/opt/sorsfonalak` |
|
||||
|
||||
## Szerver (egyszeri beállítás)
|
||||
|
||||
Egy friss Ubuntu dropleten, rootként:
|
||||
|
||||
```sh
|
||||
# Docker
|
||||
curl -fsSL https://get.docker.com | sh
|
||||
# 2 GB swap a 2 GB RAM mellé
|
||||
fallocate -l 2G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile
|
||||
echo '/swapfile none swap sw 0 0' >> /etc/fstab
|
||||
# deploy felhasználó, aki dockert futtathat
|
||||
adduser --disabled-password --gecos '' deploy && usermod -aG docker deploy
|
||||
mkdir -p /home/deploy/.ssh && echo '<publikus kulcs>' > /home/deploy/.ssh/authorized_keys
|
||||
chown -R deploy: /home/deploy/.ssh && chmod 700 /home/deploy/.ssh && chmod 600 /home/deploy/.ssh/authorized_keys
|
||||
mkdir -p /opt/sorsfonalak && chown deploy: /opt/sorsfonalak
|
||||
# tűzfal: SSH bárhonnan, HTTP/HTTPS csak a Cloudflare felől
|
||||
ufw allow OpenSSH
|
||||
for net in $(curl -s https://www.cloudflare.com/ips-v4) $(curl -s https://www.cloudflare.com/ips-v6); do
|
||||
ufw allow from "$net" to any port 80,443 proto tcp
|
||||
done
|
||||
ufw enable
|
||||
```
|
||||
|
||||
A Docker által kinyitott portokat az ufw magától nem szűri, ezért a 80-as és a 443-as portot a DigitalOcean Cloud Firewall-ban is érdemes a Cloudflare tartományaira korlátozni: Networking → Firewalls, Inbound: SSH, és HTTP/HTTPS a Cloudflare IP-listával.
|
||||
|
||||
`deploy` felhasználóként, a `/opt/sorsfonalak` mappában:
|
||||
|
||||
- `.env`: az itteni `.env.example` kitöltve.
|
||||
- `.env.secrets`: `OPENROUTER_API_KEY=...`.
|
||||
- `docker login registry.sagifer.com` egy `read:package` jogú tokennel. Amíg a `sagifer` fiók nyilvános, erre nincs szükség.
|
||||
|
||||
### Cloudflare (sorsfonalak.hu)
|
||||
|
||||
- DNS: `A sorsfonalak.hu → 165.22.194.5` és `CNAME www → sorsfonalak.hu`, mindkettő proxyzva (narancs felhő).
|
||||
- SSL/TLS mód: **Full (strict)**.
|
||||
- **Always Use HTTPS: ki.** A Let's Encrypt a Cloudflare-en át, sima HTTP-n ellenőrzi a domaint, a tanúsítvány megújításakor is. A HTTP→HTTPS átirányítást a Caddy maga végzi.
|
||||
- A Caddy a Cloudflare címtartományaiban megbízik, ezért a naplókban és a backendnél a látogató valódi IP-címe látszik (`CF-Connecting-IP`).
|
||||
|
||||
A Google OAuth kliensnél a `https://sorsfonalak.hu` címet fel kell venni az engedélyezett JavaScript-források közé.
|
||||
|
||||
## Üzemeltetés
|
||||
|
||||
- Naplók: `docker compose logs -f backend worker`
|
||||
- Visszaállás korábbi verzióra: `.env`-ben `TAG=<régebbi hash>`, utána `docker compose up -d`
|
||||
- Mentés: naponta egy `pg_dump` a `/opt/sorsfonalak/backups` mappába, 14 napig megmarad. A mentéseket érdemes a szerverről is elvinni (DigitalOcean backup, vagy `rsync` otthonra).
|
||||
- Visszatöltés: `gunzip -c backups/sorsfonalak-<dátum>.sql.gz | docker compose exec -T postgres psql -U sorsfonalak sorsfonalak`
|
||||
@@ -0,0 +1,140 @@
|
||||
# Production stack on the server (copied there by the CI deploy job).
|
||||
#
|
||||
# Needs next to it: .env (see .env.example) and .env.secrets
|
||||
# (OPENROUTER_API_KEY). TAG in .env is set by every deployment.
|
||||
|
||||
x-logging: &logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
caddy:
|
||||
image: caddy:2.11.9-alpine
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
- "443:443/udp"
|
||||
environment:
|
||||
DOMAIN: ${DOMAIN:?set DOMAIN in .env}
|
||||
volumes:
|
||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||
- caddy-data:/data
|
||||
- caddy-config:/config
|
||||
depends_on:
|
||||
- frontend
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
horoscope-api:
|
||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-horoscope-api:${TAG:-latest}
|
||||
read_only: true
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
postgres:
|
||||
image: postgres:18-alpine
|
||||
environment:
|
||||
POSTGRES_USER: sorsfonalak
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_DB: sorsfonalak
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U sorsfonalak -d sorsfonalak"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
# Daily compressed dump into ./backups, kept for 14 days.
|
||||
backup:
|
||||
image: postgres:18-alpine
|
||||
environment:
|
||||
PGHOST: postgres
|
||||
PGUSER: sorsfonalak
|
||||
PGPASSWORD: ${POSTGRES_PASSWORD}
|
||||
PGDATABASE: sorsfonalak
|
||||
volumes:
|
||||
- ./backups:/backups
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
while true; do
|
||||
f=/backups/sorsfonalak-$$(date +%F).sql.gz
|
||||
pg_dump --no-owner | gzip > "$$f.tmp" && mv "$$f.tmp" "$$f"
|
||||
find /backups -name 'sorsfonalak-*.sql.gz' -mtime +14 -delete
|
||||
sleep 86400
|
||||
done
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
backend:
|
||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-backend:${TAG:-latest}
|
||||
environment:
|
||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
||||
HOROSCOPE_API_URL: http://horoscope-api:8080
|
||||
PUBLIC_BASE_URL: https://${DOMAIN}
|
||||
GOOGLE_CLIENT_IDS: ${GOOGLE_CLIENT_IDS:-}
|
||||
BOOTSTRAP_ADMIN_EMAILS: ${BOOTSTRAP_ADMIN_EMAILS:-}
|
||||
ANALYSIS_MODEL: ${ANALYSIS_MODEL:-}
|
||||
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
|
||||
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
|
||||
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
|
||||
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
|
||||
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
|
||||
UNLIMITED_DAILY_LIMIT: ${UNLIMITED_DAILY_LIMIT:-5}
|
||||
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
|
||||
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
horoscope-api:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
worker:
|
||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-worker:${TAG:-latest}
|
||||
environment:
|
||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD}@postgres:5432/sorsfonalak
|
||||
# SMTP_URL or the SES credentials come from .env.secrets (docs/levelkuldes.md);
|
||||
# listing them here with an empty default would override that file.
|
||||
SES_REGION: ${SES_REGION:-eu-central-1}
|
||||
MAIL_FROM: ${MAIL_FROM:-Sorsfonalak <hello@sorsfonalak.hu>}
|
||||
PUBLIC_BASE_URL: https://${DOMAIN}
|
||||
env_file:
|
||||
- path: .env.secrets
|
||||
required: false
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-frontend:${TAG:-latest}
|
||||
environment:
|
||||
BACKEND_URL: http://backend:8081
|
||||
HOROSCOPE_API_URL: http://horoscope-api:8080
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /app/.next/cache
|
||||
- /tmp
|
||||
logging: *logging
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
caddy-data:
|
||||
caddy-config:
|
||||
@@ -0,0 +1,23 @@
|
||||
# Development only: loaded automatically by `docker compose up`, left out in
|
||||
# production (`docker compose -f docker-compose.yml ...`).
|
||||
#
|
||||
# Mailpit catches every e-mail the worker sends; nothing leaves the machine.
|
||||
# Web UI: http://<server>:8025
|
||||
|
||||
services:
|
||||
mailpit:
|
||||
image: axllent/mailpit:v1.33.1
|
||||
environment:
|
||||
MP_MAX_MESSAGES: 1000
|
||||
MP_SMTP_AUTH_ACCEPT_ANY: 1
|
||||
MP_SMTP_AUTH_ALLOW_INSECURE: 1
|
||||
ports:
|
||||
- "8025:8025"
|
||||
restart: unless-stopped
|
||||
|
||||
worker:
|
||||
environment:
|
||||
SMTP_URL: smtp://mailpit:1025
|
||||
depends_on:
|
||||
mailpit:
|
||||
condition: service_healthy
|
||||
@@ -0,0 +1,112 @@
|
||||
# Production: docker compose -f docker-compose.yml up -d
|
||||
# Development: docker compose up -d (also loads docker-compose.override.yml: Mailpit)
|
||||
|
||||
services:
|
||||
horoscope-api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: services/horoscope-api/Dockerfile
|
||||
image: sorsfonalak/horoscope-api:latest
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
CORS_ALLOWED_ORIGINS: "*"
|
||||
read_only: true
|
||||
restart: unless-stopped
|
||||
|
||||
postgres:
|
||||
image: postgres:18-alpine
|
||||
environment:
|
||||
POSTGRES_USER: sorsfonalak
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-sorsfonalak-dev}
|
||||
POSTGRES_DB: sorsfonalak
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql
|
||||
# Only reachable from this machine (local development and tests).
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U sorsfonalak -d sorsfonalak"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: services/backend/Dockerfile
|
||||
image: sorsfonalak/backend:latest
|
||||
ports:
|
||||
- "8081:8081"
|
||||
environment:
|
||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD:-sorsfonalak-dev}@postgres:5432/sorsfonalak
|
||||
HOROSCOPE_API_URL: http://horoscope-api:8080
|
||||
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001}
|
||||
# Plain HTTP in development; leave the default (true) in production.
|
||||
COOKIE_SECURE: ${COOKIE_SECURE:-false}
|
||||
GOOGLE_CLIENT_IDS: ${GOOGLE_CLIENT_IDS:-}
|
||||
BOOTSTRAP_ADMIN_EMAILS: ${BOOTSTRAP_ADMIN_EMAILS:-}
|
||||
# Paid detailed analyses (empty: anthropic/claude-opus-5.5).
|
||||
ANALYSIS_MODEL: ${ANALYSIS_MODEL:-}
|
||||
# Free short summary of every saved chart (empty: anthropic/claude-sonnet-5.5).
|
||||
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
|
||||
# E-mail + password login; off by default (Google, Apple and Facebook only).
|
||||
PASSWORD_LOGIN: ${PASSWORD_LOGIN:-false}
|
||||
# Stand-in payment (adds an analysis unit at once) until Stripe is connected.
|
||||
MOCK_PAYMENTS: ${MOCK_PAYMENTS:-true}
|
||||
FREE_PERSON_SLOTS: ${FREE_PERSON_SLOTS:-0}
|
||||
UNLIMITED_DAILY_LIMIT: ${UNLIMITED_DAILY_LIMIT:-5}
|
||||
# invite: new accounts need an invitation (admin page "Meghívók"); open: anyone.
|
||||
SIGNUP_MODE: ${SIGNUP_MODE:-invite}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
horoscope-api:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
restart: unless-stopped
|
||||
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: services/worker/Dockerfile
|
||||
image: sorsfonalak/worker:latest
|
||||
environment:
|
||||
DATABASE_URL: postgres://sorsfonalak:${POSTGRES_PASSWORD:-sorsfonalak-dev}@postgres:5432/sorsfonalak
|
||||
# Unset: e-mails stay in the outbox. In development the override file
|
||||
# points it at Mailpit.
|
||||
SMTP_URL: ${SMTP_URL:-}
|
||||
MAIL_FROM: ${MAIL_FROM:-Sorsfonalak <noreply@sorsfonalak.local>}
|
||||
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001}
|
||||
# OPENROUTER_API_KEY (not in git); without it analyses stay pending.
|
||||
env_file:
|
||||
- path: .env.secrets
|
||||
required: false
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: services/frontend
|
||||
image: sorsfonalak/frontend:latest
|
||||
# Host port 3001 (3000 is taken on the dev server).
|
||||
ports:
|
||||
- "3001:3000"
|
||||
environment:
|
||||
BACKEND_URL: http://backend:8081
|
||||
HOROSCOPE_API_URL: http://horoscope-api:8080
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /app/.next/cache
|
||||
- /tmp
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -0,0 +1,39 @@
|
||||
# Csomagok és árazás
|
||||
|
||||
A katalógus a kódban van: `services/backend/src/packages.rs` (`CATALOG`). Ár- vagy tartalomváltozás egy deploy.
|
||||
|
||||
## Költség
|
||||
|
||||
Egy részletes képletelemzés és egy kapcsolati elemzés is kb. **$0,21 (≈ 80 Ft)** Opus 5.5-tel; a rövid összefoglaló kb. $0,01. A fizetési szolgáltató díja kb. 1,5% + 85 Ft tranzakciónként. Az árak bruttók (27% áfa).
|
||||
|
||||
## A lépcső
|
||||
|
||||
| Csomag | Tartalom | Ár | Elemzésenként | Külön megvéve | Megtakarítás |
|
||||
|---|---|---|---|---|---|
|
||||
| Egy elemzés | 1 képletelemzés | 2 990 Ft | 2 990 Ft | – | – |
|
||||
| Páros | 2 képletelemzés, 1 kapcsolati, 1 személy | 6 990 Ft | 2 330 Ft | 9 868 Ft | 29% |
|
||||
| **Család** (Legnépszerűbb) | 6 képletelemzés, 5 kapcsolati, 5 személy | 11 990 Ft | 1 090 Ft | 37 380 Ft | 68% |
|
||||
| Korlátlan | minden korlátlanul, 12 hónapig | 17 990 Ft | – | – | – |
|
||||
| +1 kapcsolati elemzés | kiegészítő | 3 490 Ft | | | |
|
||||
| +5 személy | kiegészítő | 1 990 Ft | | | |
|
||||
|
||||
## Miért így (a nagyobb felé terelés)
|
||||
|
||||
- **Horgony:** az Egy elemzés ára (2 990 Ft) az egységár. Minden más ehhez mérve látszik olcsónak; a kártyákon áthúzva ott a „külön megvéve” ár.
|
||||
- **Kis lépések, nagy ugrások:** minden szint csak egy kicsivel drágább az előzőnél, de sokkal többet ad. Páros: +4 000 Ft-ért háromszor annyi elemzés. Család: +5 000 Ft-ért majdnem négyszer annyi. Korlátlan: +6 000 Ft-ért nincs határ. A kártyán ki is írjuk: „Csak +5 000 Ft a Páros csomaghoz képest”.
|
||||
- **Csali:** a Páros szándékosan „csak jó” ajánlat (−29%), hogy mellette a Család (−68%) kiugorjon. A Család kapja a kiemelést és a „Legnépszerűbb” címkét.
|
||||
- **A Korlátlan mint felső horgony:** a Család ára mellette mérsékeltnek tűnik; aki sokakat venne fel, annak a 6 000 Ft különbség semmiség.
|
||||
- **Drága kiegészítők:** a +1 kapcsolati elemzés 3 490 Ft, többe kerül, mint egy képletelemzés, és a Páros már kettő árán ad egyet kettőtök képletével együtt. Aki darabonként venne, annak jobban megéri csomagot venni.
|
||||
- **A vásárlás pillanatában** (a „Részletes elemzés kérése” után) nem egy darabot kínálunk, hanem három csomagot egymás mellett, kiemelt Családdal.
|
||||
- **Nem jár le:** a megvett elemzések megmaradnak, ezért a nagyobb csomag nem kockázat a vevőnek.
|
||||
|
||||
## Korlátlan csomag
|
||||
|
||||
Egy év; ha még tart, egy újabb a lejárathoz ad hozzá egy évet. Méltányos használat: naponta legfeljebb `UNLIMITED_DAILY_LIMIT` (alapból 5) új részletes elemzés. Legrosszabb esetben is jóval a csomag ára alatt marad a költség, ha valaki nem visszaélésszerűen használja; a napi korlát a gépi tömeges lekérést fogja meg.
|
||||
|
||||
## Későbbre
|
||||
|
||||
- Stripe-bekötés: a `package_orders.source = 'stripe'` már helyet kapott.
|
||||
- Bevezető kedvezmény vagy kupon (pl. az első 100 vásárlónak).
|
||||
- Ajándékba adható csomag (karácsony, Valentin-nap): a Páros és a Család jó ajándék.
|
||||
- Számlázás (NAV Online Számla) a vásárlásokhoz.
|
||||
@@ -0,0 +1,34 @@
|
||||
# sorsfonalak.hu – architektúra és indulási ötletek
|
||||
|
||||
## Tervezett konténerek
|
||||
- **horoszkop-szamito** (Rust) – születési adatok alapján számol. KÉSZ.
|
||||
- **backend** – user, cikk, LLM-kezelés, Facebook-megosztás.
|
||||
- **chat-motor** – websocket.
|
||||
- **worker + Redis** – e-mailek, háttérjobok.
|
||||
- **frontend** (Next.js) – a backendet és a chatmotort használja. Itt készül a radix is, interaktív SVG-komponensként (hover és kattintás a bolygókon, aspektusokon), cserélhető témával. Nincs külön rajzoló szerviz.
|
||||
|
||||
Funkciók fázisokban: 1) személyi horoszkóp + radix, belépés (Facebook, Apple, Google, user/jelszó), LLM-elemzés OpenRouteren (választható modell, a stílus promptban definiálva), Facebook-megosztás → 2) AI által generált cikkmodul képekkel, alattuk chat → jogosultságok: admin, creator, user. Többnyelvű lesz az indulástól.
|
||||
|
||||
## Amit már indulásra érdemes betenni
|
||||
1. **Megosztható kártya (OG-kép)** – a frontend egy szerveroldali Next.js route-ja (pl. /api/og) ugyanabból a radix SVG-komponensből PNG-t renderel (resvg). Ebből lesz az 1200×630-as kép (radix + név + 2-3 mondat), és álló 1080×1920-ast story-hoz. A Facebook 2018 óta nem enged automatikusan posztolni, csak a Share Dialog marad, ezért a megosztás sikere a képen múlik.
|
||||
2. **„Mennyire illünk össze?" meghívó (szinasztria)** – a felhasználó linket küld, a meghívott beírja a születési adatait, regisztrál, és mindketten kompatibilitási elemzést kapnak. Ez hozza a legtöbb új felhasználót.
|
||||
3. **Beszélgetés a saját horoszkóppal** – a chatmotor megkapja a user radixát JSON-ként, és arról lehet kérdezni. Később ez lehet a fizetős funkció.
|
||||
4. **Kreditrendszer az elejétől** – egyszerű kredit-főkönyv minden LLM-hívásra (havi ingyenes keret). Ez tartja kordában a költséget, véd a visszaélés ellen, és később nem kell átírni, ha fizetőssé válik.
|
||||
|
||||
## Technikai dolgok, amik most olcsók, később drágák
|
||||
- **Gyorsítótár az elemzésekre**: a kulcs `hash(radix) + promptverzió + modell`. Így nem fizetünk kétszer, és a promptokat A/B tesztelni is lehet.
|
||||
- **Strukturált LLM-válasz (JSON)**: összefoglaló, erősségek, kihívások, hosszú szöveg külön mezőben. Ebből jön a kártya szövege, az oldal szakaszai és a fordítás.
|
||||
- **Streaming (SSE vagy websocket)**: az elemzés 20-40 másodperc, ezért menet közben kell kiírni.
|
||||
- **Langfuse önhosztolva** az LLM-hívások követésére (prompt, költség, késleltetés); a Sentry mellé.
|
||||
- **Passkey belépés** a social és jelszavas mellé, mert az 50+ célközönségnek ez a kényelmes.
|
||||
- **Ismeretlen születési idő mód**: déli horoszkóp, házak nélkül.
|
||||
- **GDPR**: adatexport, fióktörlés, és az LLM felé név nélkül megy az adat.
|
||||
- A hosszú LLM-hívások (elemzés, cikkírás) is a worker/Redis soron menjenek, ne a backend kérésében.
|
||||
- A radix SVG-komponens legyen tiszta, adatvezérelt (nincs böngésző-függés), hogy ugyanaz a kód rajzolja az interaktív nézetet és a szerveroldali OG-képet.
|
||||
|
||||
## Második kör
|
||||
- Napi személyre szabott horoszkóp a tranzitok alapján (a worker küldi e-mailben vagy push-ban).
|
||||
- PWA + web push a natív app előtt.
|
||||
- Felolvasott elemzés (TTS).
|
||||
- Kozmikus naptár (holdfázisok, retrográd időszakok) és hozzá generált cikkek.
|
||||
- MCP szerver a számító szerviz elé, hogy Claude-ból vagy ChatGPT-ből is lekérhető legyen a horoszkóp.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Levélküldés élesben: Amazon SES
|
||||
|
||||
Élesben most nincs levélküldő beállítva (`SMTP_URL` üres), így minden levél az `email_outbox` táblában vár. Amíg ez így van, a meghívót kézzel is továbbadhatod: az admin „Meghívók” oldala küldés után kiírja a linket („Link másolása”).
|
||||
|
||||
A meghívó a legkényesebb levéltípus, mert a címzett nem kérte. A spammappát elsősorban a feladó hírneve és a domain hitelesítése dönti el, a sablon csak ezután számít. Ezért kellenek a lenti lépések.
|
||||
|
||||
A SES ára 1000 levelenként 0,10 USD; a mi forgalmunknál ez havi néhány cent.
|
||||
|
||||
## 1. Régió és domain (SES konzol)
|
||||
|
||||
1. **Régió:** `eu-central-1` (Frankfurt), hogy az adatok az EU-ban maradjanak. Minden lépést ebben a régióban kell elvégezni, mert a SES-beállítások régiónként külön élnek.
|
||||
2. *Configuration → Identities → Create identity → Domain*: `sorsfonalak.hu`.
|
||||
- **Easy DKIM**, RSA 2048 bit. A SES három CNAME-rekordot ad (lásd 3. pont).
|
||||
- **Custom MAIL FROM domain:** `mail.sorsfonalak.hu`, és *Behavior on MX failure*: *Use default MAIL FROM domain*. Ettől az SPF is a saját domainünkre szól, ami a DMARC-nál számít. Ehhez egy MX- és egy TXT-rekord kell.
|
||||
3. A domain igazolása után bármelyik `@sorsfonalak.hu` cím lehet feladó. Javaslat: `hello@sorsfonalak.hu`. A `noreply` cím a szűrőknél rosszabb, és válaszolni sem lehet rá.
|
||||
|
||||
## 2. Kilépés a homokozóból (sandbox)
|
||||
|
||||
Új SES-fiók homokozóban indul. Ilyenkor:
|
||||
- csak igazolt címekre lehet küldeni (*Identities → Create identity → Email address*; teszteléshez a saját címed elég);
|
||||
- naponta legfeljebb 200 levél megy ki.
|
||||
|
||||
Meghívót idegen címre csak éles hozzáféréssel lehet küldeni: *Account dashboard → Request production access*. Az AWS kézzel bírálja el, általában egy napon belül. A kérésben érdemes leírni:
|
||||
- tranzakciós levelek (megerősítés, értesítés) és meghívók egy zártkörű oldalra;
|
||||
- meghívót csak az admin küld, személyesen ismert embereknek, kis mennyiségben;
|
||||
- minden meghívóban egykattintásos leiratkozás van, a leiratkozott címekre többé nem megy levél;
|
||||
- a visszapattanó és panaszos címeket a SES fiókszintű tiltólistája kezeli (*Suppression list*: bounces és complaints).
|
||||
|
||||
Fontos: ha a visszapattanási arány 5%, vagy a panaszarány 0,1% fölé megy, az AWS felfüggesztheti a küldést. Ezért csak olyan címre küldj meghívót, amelyről tudod, hogy él.
|
||||
|
||||
## 3. DNS a Cloudflare-en
|
||||
|
||||
| Típus | Név | Tartalom |
|
||||
|---|---|---|
|
||||
| CNAME ×3 | `<kód>._domainkey` | `<kód>.dkim.amazonses.com` (a SES konzol kiírja mindhármat) |
|
||||
| MX | `mail` | `feedback-smtp.eu-central-1.amazonses.com`, prioritás 10 |
|
||||
| TXT | `mail` | `v=spf1 include:amazonses.com ~all` |
|
||||
| TXT | `_dmarc` | `v=DMARC1; p=none; rua=mailto:<a te címed>` |
|
||||
|
||||
- Minden rekord **DNS only** (szürke felhő) legyen; a proxyzott CNAME-mel a DKIM nem működik.
|
||||
- DMARC: induláskor `p=none` (csak jelentés). Ha pár hétig minden levél átmegy, szigorítható `p=quarantine`-ra.
|
||||
- Ha a `hello@sorsfonalak.hu` címre érkező válaszokat is olvasni szeretnéd: a Cloudflare *Email Routing* ingyen továbbítja őket a Gmailedre. Ez a fő domainre (`sorsfonalak.hu`) tesz MX- és SPF-rekordot, ami nem ütközik a `mail.` aldomain rekordjaival.
|
||||
|
||||
## 4. Hozzáférés
|
||||
|
||||
Két út van, mindkettő a szerver `.env.secrets` fájljába kerül (kis- vagy nagybetűvel is jó):
|
||||
|
||||
- **SMTP-hozzáférés** (*SMTP settings → Create SMTP credentials*): egy IAM-felhasználó, amely csak levelet küldhet.
|
||||
```
|
||||
SES_SMTP_USERNAME=AKIA...
|
||||
SES_SMTP_PASSWORD=...
|
||||
```
|
||||
- **IAM-kulcspár**, amelynek van `ses:SendRawEmail` joga:
|
||||
```
|
||||
AWS_ACCESS_KEY_ID=AKIA...
|
||||
AWS_SECRET_ACCESS_KEY=...
|
||||
```
|
||||
Más nevek is jók: a kulcsnál `SES_AUTH_KEY`, `SES_ACCESS_KEY`, `SES_KEY`, `AUTH_KEY`, a titoknál `SES_SECRET`, `SES_SECRET_KEY`, `AWS_SECRET`, `AUTH_SECRET` (a teljes lista: `services/worker/src/ses.rs`).
|
||||
A worker ebből az AWS által leírt módon kiszámolja az SMTP-jelszót. Ha az `AWS_SECRET_ACCESS_KEY` helyére az SMTP-jelszót írtad, azt is felismeri, és változatlanul használja.
|
||||
|
||||
A régió alapból `eu-central-1` (Frankfurt); felülírható a `SES_REGION` változóval. A port 2587, ezt a `SES_SMTP_PORT` írja felül. URL-kódolásra itt nincs szükség, mert a worker maga állítja össze a címet.
|
||||
|
||||
## 5. Tűzfal
|
||||
|
||||
A DigitalOcean a dropleteken tiltja a szokásos kimenő SMTP-portokat (25, 465, 587). A SES erre a **2587**-es portot (STARTTLS) is kínálja.
|
||||
|
||||
A droplet saját tűzfala (`sorsfonalak-fw`, DigitalOcean → Networking → Firewalls) a kimenő forgalmat is szűri. Az **Outbound rules** közé fel kell venni a **TCP 2587**-et (cél: All IPv4, All IPv6), különben a worker nem éri el a SES-t.
|
||||
|
||||
## 6. Indítás
|
||||
|
||||
- A `.env` fájlban opcionális: `MAIL_FROM=Sorsfonalak <hello@sorsfonalak.hu>` (ez az alapérték is).
|
||||
- Utána: `docker compose up -d worker`. A naplóban ennek kell megjelennie: `e-mail delivery enabled`, `via=Amazon SES eu-central-1:2587, credentials from …`.
|
||||
- Az eddig várakozó levelek ekkor kimennek. Ha ezt nem szeretnéd, előtte töröld őket: `DELETE FROM email_outbox WHERE sent_at IS NULL;`.
|
||||
- Hibaüzenetek a naplóban:
|
||||
- `535 Authentication Credentials Invalid`: hibás kulcs, vagy az IAM-felhasználónak nincs `ses:SendRawEmail` joga;
|
||||
- `554 Message rejected: Email address is not verified`: a fiók még homokozóban van, és a címzett nincs igazolva;
|
||||
- időtúllépés: a tűzfalon nincs engedélyezve a kimenő 2587-es port.
|
||||
- Ha mégis kész SMTP-címet adnál meg, az `SMTP_URL` mindig elsőbbséget élvez a SES-változókkal szemben.
|
||||
|
||||
## 7. Próba
|
||||
|
||||
1. Admin → Meghívók → **Teszt küldése magamnak**: megérkezik-e, és nem a spamben van-e.
|
||||
2. A Gmailben a levélnél *⋮ → Eredeti megjelenítése*: az SPF, a DKIM és a DMARC mellett is `PASS` álljon.
|
||||
3. A [mail-tester.com](https://www.mail-tester.com) ad egy egyszeri címet. Küldj rá meghívót az admin oldalról (utána vond vissza), és nézd meg a pontszámot; 9/10 fölött jó. Ehhez már éles hozzáférés kell.
|
||||
|
||||
## Amit a kód már elintéz
|
||||
|
||||
- HTML és szöveges változat ugyanazzal a tartalommal. Egyhasábos, képek és követés nélkül, minden link a saját domainre mutat.
|
||||
- `List-Unsubscribe` és `List-Unsubscribe-Post` (RFC 8058): a Gmail és a többi levelező saját „Leiratkozás” gombot mutat. Aki leiratkozik, annak a címére soha többé nem megy meghívó (`email_optouts`, csak a cím hash-e).
|
||||
- A worker saját domaines `Message-ID`-t tesz a levélre. A SES ezt a sajátjára cseréli, ami rendben van.
|
||||
- Meghívót csak admin küldhet. Egy meghívó legfeljebb háromszor megy ki, 24 óránként egyszer. A személyes üzenet legfeljebb 300 karakter, és nem lehet benne link.
|
||||
|
||||
## Később
|
||||
|
||||
A visszapattanásokról és panaszokról a SES utólag, SNS-értesítésben szól; az SMTP-kapcsolat ezt nem jelzi. Ha lesz forgalom, érdemes bekötni egy SNS → backend webhookot. Ez a meghívólistán megjelölné a visszapattant címeket, és a panaszt tevőket a leiratkozottak közé tenné.
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
/.git
|
||||
/.gwt
|
||||
|
||||
/.settings
|
||||
|
||||
/gwt-unitCache
|
||||
|
||||
/www-test
|
||||
|
||||
/test-classes
|
||||
/.project
|
||||
|
||||
/.classpath
|
||||
/.checkstyle
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
Copyright (C) 2013-2017 Lukas Steiger <lsteiger4@gmail.com>
|
||||
|
||||
This program is free software. It comes without any warranty, to
|
||||
the extent permitted by applicable law. You can redistribute it
|
||||
and/or modify it under the terms of the Do What The Fuck You Want
|
||||
To Public License, Version 2, as published by Sam Hocevar.
|
||||
See http://www.wtfpl.net/ for more details.
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
Welcome to Astrology Chart Generator.
|
||||
http://astro-chart.appspot.com
|
||||
|
||||
This application is work in progress and may therefore still display incorrect results.
|
||||
|
||||
The ephemeris used in this application can be found at:
|
||||
http://www.findyourfate.com/astrology/ephemeris/ephemeris.html
|
||||
|
||||
Astrology Chart Generator uses the following IP-location lookup service:
|
||||
http://freegeoip.net
|
||||
|
||||
The location lookup by city-name is powered by:
|
||||
http://code.google.com/apis/maps/index.html
|
||||
|
||||
Sunrise and sunset calculations are done according to the formulas provided at:
|
||||
http://users.electromagnetic.net/bu/astro/sunrise-set.php
|
||||
This application will therefore calculate the same results for sunrise and sunset as calculated here:
|
||||
http://users.electromagnetic.net/bu/astro/iyf-calc.php
|
||||
(Beware: There are many other online calculators that result in different results.)
|
||||
Executable
+19462
File diff suppressed because it is too large
Load Diff
Executable
+19463
File diff suppressed because it is too large
Load Diff
Executable
+19464
File diff suppressed because it is too large
Load Diff
Executable
+19852
File diff suppressed because it is too large
Load Diff
Executable
+2
@@ -0,0 +1,2 @@
|
||||
/gson-2.1.jar
|
||||
/junit-4.10.jar
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.mycompany.myname</groupId>
|
||||
<artifactId>astro</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>astro Maven Webapp</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<dependencies>
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>junit</groupId>-->
|
||||
<!--<artifactId>junit</artifactId>-->
|
||||
<!--<version>3.8.1</version>-->
|
||||
<!--<scope>test</scope>-->
|
||||
<!--</dependency>-->
|
||||
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>javax</groupId>-->
|
||||
<!--<artifactId>javaee-api</artifactId>-->
|
||||
<!--<version>6.0</version>-->
|
||||
<!--<scope>provided</scope>-->
|
||||
<!--</dependency>-->
|
||||
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>astro</finalName>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.tomcat.maven</groupId>
|
||||
<artifactId>tomcat7-maven-plugin</artifactId>
|
||||
<version>2.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>start-tomcat</id>
|
||||
<phase>pre-integration-test</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
|
||||
<execution>
|
||||
<id>stop-tomcat</id>
|
||||
<phase>post-integration-test</phase>
|
||||
<goals>
|
||||
<goal>shutdown</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<port>8888</port>
|
||||
<path>/</path>
|
||||
<fork>true</fork>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.5.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<executable>test.bat</executable>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig">
|
||||
<persistence-manager-factory name="transactions-optional">
|
||||
<property name="javax.jdo.PersistenceManagerFactoryClass"
|
||||
value="org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManagerFactory"/>
|
||||
<property name="javax.jdo.option.ConnectionURL" value="appengine"/>
|
||||
<property name="javax.jdo.option.NontransactionalRead" value="true"/>
|
||||
<property name="javax.jdo.option.NontransactionalWrite" value="true"/>
|
||||
<property name="javax.jdo.option.RetainValues" value="true"/>
|
||||
<property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
|
||||
</persistence-manager-factory>
|
||||
</jdoconfig>
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
|
||||
/appengine-generated
|
||||
|
||||
/classes
|
||||
|
||||
/deploy
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
|
||||
<application>astro-chart</application>
|
||||
<version>1</version>
|
||||
<threadsafe>true</threadsafe>
|
||||
<static-files>
|
||||
<include path="**" />
|
||||
<include path="**.nocache.*" expiration="0s" />
|
||||
<include path="**.cache.*" expiration="365d" />
|
||||
<exclude path="**.gwt.rpc" />
|
||||
</static-files>
|
||||
<system-properties>
|
||||
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
|
||||
</system-properties>
|
||||
</appengine-web-app>
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
/appengine-api-1.0-sdk-1.8.1.1.jar
|
||||
/appengine-api-labs.jar
|
||||
/appengine-endpoints.jar
|
||||
/appengine-jsr107cache-1.8.1.1.jar
|
||||
/datanucleus-appengine-1.0.10.final.jar
|
||||
/datanucleus-core-1.1.5.jar
|
||||
/datanucleus-jpa-1.1.5.jar
|
||||
/geronimo-jpa_3.0_spec-1.1.1.jar
|
||||
/geronimo-jta_1.1_spec-1.1.1.jar
|
||||
/gson-2.1.jar
|
||||
/gwt-servlet.jar
|
||||
/jdo2-api-2.3-eb.jar
|
||||
/jsr107cache-1.1.jar
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
# add to appengine-web.xml:
|
||||
# <system-properties>
|
||||
# <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
|
||||
# </system-properties>
|
||||
.level = WARNING
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
version="2.5"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee">
|
||||
|
||||
<!-- Servlets -->
|
||||
<servlet>
|
||||
<servlet-name>adminService</servlet-name>
|
||||
<servlet-class>astrochart.server.service.AdminServiceImpl</servlet-class>
|
||||
</servlet>
|
||||
<servlet>
|
||||
<servlet-name>epochService</servlet-name>
|
||||
<servlet-class>astrochart.server.service.EpochServiceImpl</servlet-class>
|
||||
</servlet>
|
||||
<servlet>
|
||||
<servlet-name>geocodeService</servlet-name>
|
||||
<servlet-class>astrochart.server.service.GeocodeServiceImpl</servlet-class>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>adminService</servlet-name>
|
||||
<url-pattern>/astrochart/admin</url-pattern>
|
||||
</servlet-mapping>
|
||||
<servlet-mapping>
|
||||
<servlet-name>epochService</servlet-name>
|
||||
<url-pattern>/astrochart/epoch</url-pattern>
|
||||
</servlet-mapping>
|
||||
<servlet-mapping>
|
||||
<servlet-name>geocodeService</servlet-name>
|
||||
<url-pattern>/astrochart/geocode</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<!-- Default page to serve -->
|
||||
<welcome-file-list>
|
||||
<welcome-file>AstroChart.html</welcome-file>
|
||||
</welcome-file-list>
|
||||
|
||||
</web-app>
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module rename-to='astrochart'>
|
||||
<inherits name='com.google.gwt.user.User'/>
|
||||
<inherits name="com.google.gwt.http.HTTP"/>
|
||||
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
|
||||
<entry-point class='astrochart.client.AstroChart'/>
|
||||
<source path='client'/>
|
||||
<source path='shared'/>
|
||||
</module>
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package astrochart.client;
|
||||
|
||||
import java.util.Date;
|
||||
import astrochart.client.event.CancelledEvent;
|
||||
import astrochart.client.event.CancelledEventHandler;
|
||||
import astrochart.client.presenter.AdminPresenter;
|
||||
import astrochart.client.presenter.InfoPresenter;
|
||||
import astrochart.client.presenter.ChartPresenter;
|
||||
import astrochart.client.presenter.Presenter;
|
||||
import astrochart.client.util.DateTimeUtil;
|
||||
import astrochart.client.view.AdminView;
|
||||
import astrochart.client.view.InfoView;
|
||||
import astrochart.client.view.ChartView;
|
||||
import com.google.gwt.event.logical.shared.SelectionEvent;
|
||||
import com.google.gwt.event.logical.shared.SelectionHandler;
|
||||
import com.google.gwt.event.logical.shared.ValueChangeEvent;
|
||||
import com.google.gwt.event.logical.shared.ValueChangeHandler;
|
||||
import com.google.gwt.event.shared.HandlerManager;
|
||||
import com.google.gwt.user.client.History;
|
||||
import com.google.gwt.user.client.ui.HasWidgets;
|
||||
import com.google.gwt.user.client.ui.TabPanel;
|
||||
|
||||
public class AppController implements Presenter, ValueChangeHandler<String> {
|
||||
private final HandlerManager eventBus = new HandlerManager(null);
|
||||
private final DateTimeUtil dateTimeUtil = new DateTimeUtil();
|
||||
private HasWidgets container;
|
||||
|
||||
private final TabPanel tabPanel = new TabPanel();
|
||||
private final ChartView chartView = new ChartView(eventBus, dateTimeUtil);
|
||||
private final InfoView infoView = new InfoView();
|
||||
private final AdminView adminView = new AdminView();
|
||||
|
||||
private ChartPresenter mainPresenter;
|
||||
private Presenter infoPresenter;
|
||||
private Presenter adminPresenter;
|
||||
|
||||
public AppController() {
|
||||
prepareTabs();
|
||||
bind();
|
||||
}
|
||||
|
||||
private void prepareTabs() {
|
||||
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
|
||||
@Override
|
||||
public void onSelection(final SelectionEvent<Integer> event) {
|
||||
final int selection = event.getSelectedItem().intValue();
|
||||
if (selection == 0) {
|
||||
if (!History.getToken().startsWith("chart")) {
|
||||
History.newItem("chart/");
|
||||
}
|
||||
}
|
||||
if (selection == 1) {
|
||||
if (!History.getToken().startsWith("info")) {
|
||||
History.newItem("info/");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
//tabPanel.setAnimationEnabled(true);
|
||||
tabPanel.add(chartView.asWidget(), "Chart");
|
||||
tabPanel.add(infoView.asWidget(), "Info");
|
||||
}
|
||||
|
||||
private void bind() {
|
||||
History.addValueChangeHandler(this);
|
||||
eventBus.addHandler(CancelledEvent.TYPE, new CancelledEventHandler() {
|
||||
@Override
|
||||
public void onCancelled(final CancelledEvent event) {
|
||||
doEditTermCancelled();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void doEditTermCancelled() {
|
||||
History.newItem("chart/");
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void go(final HasWidgets container) {
|
||||
this.container = container;
|
||||
if ("".equals(History.getToken())) {
|
||||
History.newItem("chart/");
|
||||
} else {
|
||||
History.fireCurrentHistoryState();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void onValueChange(final ValueChangeEvent<String> event) {
|
||||
final String token = event.getValue();
|
||||
if (token.startsWith("chart/")) {
|
||||
Date providedUtcDate = null;
|
||||
String dateString = "";
|
||||
if (token.split("/").length > 1) {
|
||||
dateString = token.split("/")[1];
|
||||
try {
|
||||
providedUtcDate = dateTimeUtil.getUtcDateFromUtcString(dateString);
|
||||
} catch (final IllegalArgumentException iae) {
|
||||
assert true; // ignore
|
||||
}
|
||||
}
|
||||
tabPanel.selectTab(0);
|
||||
mainPresenter = new ChartPresenter(eventBus, dateTimeUtil, tabPanel, chartView, providedUtcDate);
|
||||
mainPresenter.go(container);
|
||||
} else if (token.startsWith("info/")) {
|
||||
tabPanel.selectTab(1);
|
||||
infoPresenter = new InfoPresenter(eventBus, tabPanel, infoView);
|
||||
infoPresenter.go(container);
|
||||
} else if (token.startsWith("admin/")) {
|
||||
adminPresenter = new AdminPresenter(adminView);
|
||||
adminPresenter.go(container);
|
||||
} else {
|
||||
assert true; // ignore
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
package astrochart.client;
|
||||
|
||||
import com.google.gwt.core.client.EntryPoint;
|
||||
import com.google.gwt.user.client.ui.Image;
|
||||
import com.google.gwt.user.client.ui.RootPanel;
|
||||
|
||||
/**
|
||||
* Entry point classes define <code>onModuleLoad()</code>.
|
||||
*/
|
||||
public class AstroChart implements EntryPoint {
|
||||
private final AppController appController = new AppController();
|
||||
|
||||
@Override
|
||||
public final void onModuleLoad() {
|
||||
final Image titleImage = new Image("/images/AstroChartTitle.png");
|
||||
RootPanel.get("title").add(titleImage);
|
||||
appController.go(RootPanel.get("content"));
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package astrochart.client.event;
|
||||
|
||||
import com.google.gwt.event.shared.GwtEvent;
|
||||
|
||||
public class CancelledEvent extends GwtEvent<CancelledEventHandler> {
|
||||
public static final Type<CancelledEventHandler> TYPE = new Type<CancelledEventHandler>();
|
||||
|
||||
@Override
|
||||
public final Type<CancelledEventHandler> getAssociatedType() {
|
||||
return TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void dispatch(final CancelledEventHandler handler) {
|
||||
handler.onCancelled(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package astrochart.client.event;
|
||||
|
||||
import com.google.gwt.event.shared.EventHandler;
|
||||
|
||||
public interface CancelledEventHandler extends EventHandler {
|
||||
void onCancelled(final CancelledEvent event);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package astrochart.client.event;
|
||||
|
||||
import java.util.Date;
|
||||
import com.google.gwt.event.shared.GwtEvent;
|
||||
|
||||
public class DateUpdatedEvent extends GwtEvent<DateUpdatedEventHandler> {
|
||||
public static final Type<DateUpdatedEventHandler> TYPE = new Type<DateUpdatedEventHandler>();
|
||||
private final Date localDate;
|
||||
|
||||
public DateUpdatedEvent(final Date localDate) {
|
||||
this.localDate = localDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final Type<DateUpdatedEventHandler> getAssociatedType() {
|
||||
return TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void dispatch(final DateUpdatedEventHandler handler) {
|
||||
handler.onDateUpdated(this);
|
||||
}
|
||||
|
||||
public final Date getLocalDate() {
|
||||
return localDate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package astrochart.client.event;
|
||||
|
||||
import com.google.gwt.event.shared.EventHandler;
|
||||
|
||||
public interface DateUpdatedEventHandler extends EventHandler {
|
||||
void onDateUpdated(final DateUpdatedEvent event);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package astrochart.client.event;
|
||||
|
||||
import com.google.gwt.event.shared.GwtEvent;
|
||||
|
||||
public class ResetAspectsEvent extends GwtEvent<ResetAspectsEventHandler> {
|
||||
public static final Type<ResetAspectsEventHandler> TYPE = new Type<ResetAspectsEventHandler>();
|
||||
|
||||
@Override
|
||||
public final Type<ResetAspectsEventHandler> getAssociatedType() {
|
||||
return TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void dispatch(final ResetAspectsEventHandler handler) {
|
||||
handler.onResetAspects(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package astrochart.client.event;
|
||||
|
||||
import com.google.gwt.event.shared.EventHandler;
|
||||
|
||||
public interface ResetAspectsEventHandler extends EventHandler {
|
||||
void onResetAspects(final ResetAspectsEvent event);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package astrochart.client.event;
|
||||
|
||||
import com.google.gwt.event.shared.GwtEvent;
|
||||
|
||||
public class SetStatusEvent extends GwtEvent<SetStatusEventHandler> {
|
||||
public static final Type<SetStatusEventHandler> TYPE = new Type<SetStatusEventHandler>();
|
||||
private final String statusMessage;
|
||||
|
||||
public SetStatusEvent(final String statusMessage) {
|
||||
this.statusMessage = statusMessage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final Type<SetStatusEventHandler> getAssociatedType() {
|
||||
return TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void dispatch(final SetStatusEventHandler handler) {
|
||||
handler.onSetStatus(this);
|
||||
}
|
||||
|
||||
public final String getStatusMessage() {
|
||||
return statusMessage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package astrochart.client.event;
|
||||
|
||||
import com.google.gwt.event.shared.EventHandler;
|
||||
|
||||
public interface SetStatusEventHandler extends EventHandler {
|
||||
void onSetStatus(final SetStatusEvent event);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package astrochart.client.presenter;
|
||||
|
||||
import com.google.gwt.event.shared.HandlerManager;
|
||||
import com.google.gwt.user.client.ui.TabPanel;
|
||||
import com.google.gwt.user.client.ui.Widget;
|
||||
|
||||
public class AbstractTabPresenter {
|
||||
private final TabPanel tabPanel;
|
||||
private final HandlerManager eventBus;
|
||||
|
||||
public AbstractTabPresenter(final HandlerManager eventBus, final TabPanel tabPanel) {
|
||||
this.tabPanel = tabPanel;
|
||||
this.eventBus = eventBus;
|
||||
}
|
||||
|
||||
public final Widget getTabPanel() {
|
||||
return tabPanel;
|
||||
}
|
||||
|
||||
public final HandlerManager getEventBus() {
|
||||
return eventBus;
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package astrochart.client.presenter;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
import astrochart.client.service.AdminService;
|
||||
import astrochart.client.service.AdminServiceAsync;
|
||||
import astrochart.shared.data.Epoch;
|
||||
import astrochart.shared.enums.Planet;
|
||||
import astrochart.shared.enums.Weekday;
|
||||
import astrochart.shared.enums.time.Month;
|
||||
import com.google.gwt.core.client.GWT;
|
||||
import com.google.gwt.core.client.Scheduler;
|
||||
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
|
||||
import com.google.gwt.event.dom.client.ClickEvent;
|
||||
import com.google.gwt.event.dom.client.ClickHandler;
|
||||
import com.google.gwt.i18n.client.DateTimeFormat;
|
||||
import com.google.gwt.user.client.rpc.AsyncCallback;
|
||||
import com.google.gwt.user.client.ui.Button;
|
||||
import com.google.gwt.user.client.ui.HasWidgets;
|
||||
import com.google.gwt.user.client.ui.Label;
|
||||
import com.google.gwt.user.client.ui.TextArea;
|
||||
import com.google.gwt.user.client.ui.Widget;
|
||||
|
||||
public class AdminPresenter implements Presenter {
|
||||
private static final Logger LOG = Logger.getLogger(AdminPresenter.class.getName());
|
||||
private final AdminServiceAsync adminService = GWT.create(AdminService.class);
|
||||
private final DateTimeFormat format = DateTimeFormat.getFormat("dd MM yyyy HH:mm:ss");
|
||||
private final Display display;
|
||||
|
||||
private Month epochMonth = Month.January;
|
||||
private int epochYear = 0;
|
||||
private String[] lines;
|
||||
private int lineIndex;
|
||||
private int counter;
|
||||
private boolean hasError = false;
|
||||
|
||||
public interface Display {
|
||||
Widget asWidget();
|
||||
Button getSubmitButton();
|
||||
TextArea getInputTextArea();
|
||||
Label getStatusLabel();
|
||||
Label getSecondStatusLabel();
|
||||
}
|
||||
|
||||
public AdminPresenter(final Display view) {
|
||||
this.display = view;
|
||||
}
|
||||
|
||||
public final void bind() {
|
||||
display.getSubmitButton().addClickHandler(new ClickHandler() {
|
||||
@Override
|
||||
public final void onClick(final ClickEvent event) {
|
||||
parseAndSubmitEpochs();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void go(final HasWidgets container) {
|
||||
bind();
|
||||
container.clear();
|
||||
container.add(display.asWidget());
|
||||
display.getStatusLabel().setText("Ready.");
|
||||
display.getInputTextArea().setFocus(true);
|
||||
}
|
||||
|
||||
private void parseAndSubmitEpochs() {
|
||||
display.getSubmitButton().setEnabled(false);
|
||||
counter = 0;
|
||||
lineIndex = 0;
|
||||
lines = display.getInputTextArea().getText().split("\n");
|
||||
hasError = false;
|
||||
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
|
||||
@Override
|
||||
public void execute() {
|
||||
parseLine(lineIndex);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private synchronized void parseLine(final int index) {
|
||||
if (!hasError) {
|
||||
display.getStatusLabel().setText("Processing line: " + index);
|
||||
display.getSecondStatusLabel().setText(epochYear + " " + epochMonth);
|
||||
for (final Month month : Month.values()) {
|
||||
if (lines[index].startsWith(month.name().toUpperCase())) {
|
||||
epochMonth = month;
|
||||
epochYear = Integer.parseInt(lines[index].split(" ")[1]);
|
||||
}
|
||||
}
|
||||
final Month finalEpochMonth = epochMonth;
|
||||
final int finalEpochYear = epochYear;
|
||||
parseEpochLine(finalEpochYear, finalEpochMonth, lines[index]);
|
||||
if (lineIndex >= lines.length) {
|
||||
display.getSubmitButton().setEnabled(true);
|
||||
display.getStatusLabel().setText("Done.");
|
||||
display.getSecondStatusLabel().setText("Number of Epochs submitted: " + counter);
|
||||
} else { // next
|
||||
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
|
||||
@Override
|
||||
public void execute() {
|
||||
parseLine(lineIndex++);
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
display.getSubmitButton().setEnabled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void parseEpochLine(final int epochYear, final Month epochMonth, final String line) {
|
||||
for (final Weekday weekday : Weekday.values()) {
|
||||
if (line.startsWith(weekday.getAbbreviation())) {
|
||||
final String[] split = line.split(" ");
|
||||
//DATE SID.TIME SUN MOON MERCURY VENUS MARS JUPITER SATURN URANUS NEPTUNE PLUTO NODE
|
||||
//0 1 2 3 4 5 6 7 8 9 10 11 12 13
|
||||
//Fr 01 06:42:57 10CP36 07VI24 18CP00 20AQ04 29AR32 21LI12 25LI38 17AR44 17VI18 02TA24 20PI56
|
||||
|
||||
final Epoch epoch = new Epoch();
|
||||
final String monthString = addZeroIfNeeded(String.valueOf(epochMonth.getNumber()));
|
||||
epoch.setSidDate(format.parse(
|
||||
split[1] + " " + monthString + " " + epochYear + " " + split[2]
|
||||
));
|
||||
epoch.setDay(weekday.getAbbreviation());
|
||||
for (final Planet planet : Planet.values()) {
|
||||
if (!planet.equals(Planet.SouthNode)) {
|
||||
epoch.setPosition(planet, split[planet.getToken()]);
|
||||
}
|
||||
}
|
||||
submitEpoch(epoch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String addZeroIfNeeded(final String monthString) {
|
||||
if (monthString.length() == 1) {
|
||||
return "0" + monthString;
|
||||
} else {
|
||||
return monthString;
|
||||
}
|
||||
}
|
||||
|
||||
private void submitEpoch(final Epoch epoch) {
|
||||
adminService.saveEpoch(epoch, new AsyncCallback<Void>() {
|
||||
@Override
|
||||
public void onSuccess(final Void result) {
|
||||
counter++;
|
||||
}
|
||||
@Override
|
||||
public void onFailure(final Throwable caught) {
|
||||
hasError = true;
|
||||
LOG.severe("Fail submitting Epoch: " + caught.getMessage());
|
||||
LOG.severe("Year: " + epochYear + " Month: " + epochMonth + " Epoch: " + epoch);
|
||||
display.getStatusLabel().setText("Fail submitting Epoch: " + caught.getMessage());
|
||||
display.getSecondStatusLabel().setText("Year: " + epochYear + " Month: " + epochMonth + " Epoch: " + epoch);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+449
@@ -0,0 +1,449 @@
|
||||
package astrochart.client.presenter;
|
||||
|
||||
import java.util.Date;
|
||||
import astrochart.client.event.DateUpdatedEvent;
|
||||
import astrochart.client.event.DateUpdatedEventHandler;
|
||||
import astrochart.client.event.ResetAspectsEvent;
|
||||
import astrochart.client.event.ResetAspectsEventHandler;
|
||||
import astrochart.client.event.SetStatusEvent;
|
||||
import astrochart.client.event.SetStatusEventHandler;
|
||||
import astrochart.client.service.EpochService;
|
||||
import astrochart.client.service.EpochServiceAsync;
|
||||
import astrochart.client.service.GeocodeService;
|
||||
import astrochart.client.service.GeocodeServiceAsync;
|
||||
import astrochart.client.util.AstrologyUtil;
|
||||
import astrochart.client.util.DateTimeUtil;
|
||||
import astrochart.client.widgets.Chart;
|
||||
import astrochart.client.widgets.TimeEntry;
|
||||
import astrochart.shared.data.Epoch;
|
||||
import astrochart.shared.data.GeocodeData;
|
||||
import astrochart.shared.enums.AspectType;
|
||||
import astrochart.shared.enums.HouseType;
|
||||
import astrochart.shared.enums.Planet;
|
||||
import astrochart.shared.exceptions.EpochNotFoundException;
|
||||
import astrochart.shared.wrappers.AscendentAndOffset;
|
||||
import astrochart.shared.wrappers.BodyPosition;
|
||||
import astrochart.shared.wrappers.RiseAndSet;
|
||||
import com.google.gwt.core.client.Callback;
|
||||
import com.google.gwt.core.client.GWT;
|
||||
import com.google.gwt.core.client.Scheduler;
|
||||
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
|
||||
import com.google.gwt.event.dom.client.ChangeEvent;
|
||||
import com.google.gwt.event.dom.client.ChangeHandler;
|
||||
import com.google.gwt.event.dom.client.ClickEvent;
|
||||
import com.google.gwt.event.dom.client.ClickHandler;
|
||||
import com.google.gwt.event.dom.client.KeyCodes;
|
||||
import com.google.gwt.event.dom.client.KeyUpEvent;
|
||||
import com.google.gwt.event.dom.client.KeyUpHandler;
|
||||
import com.google.gwt.event.logical.shared.ValueChangeEvent;
|
||||
import com.google.gwt.event.logical.shared.ValueChangeHandler;
|
||||
import com.google.gwt.event.shared.HandlerManager;
|
||||
import com.google.gwt.geolocation.client.Geolocation;
|
||||
import com.google.gwt.geolocation.client.Position;
|
||||
import com.google.gwt.geolocation.client.Position.Coordinates;
|
||||
import com.google.gwt.geolocation.client.PositionError;
|
||||
import com.google.gwt.i18n.client.NumberFormat;
|
||||
import com.google.gwt.user.client.rpc.AsyncCallback;
|
||||
import com.google.gwt.user.client.ui.Button;
|
||||
import com.google.gwt.user.client.ui.CheckBox;
|
||||
import com.google.gwt.user.client.ui.HasWidgets;
|
||||
import com.google.gwt.user.client.ui.Label;
|
||||
import com.google.gwt.user.client.ui.ListBox;
|
||||
import com.google.gwt.user.client.ui.TabPanel;
|
||||
import com.google.gwt.user.client.ui.TextBox;
|
||||
import com.google.gwt.user.client.ui.Widget;
|
||||
|
||||
public class ChartPresenter extends AbstractTabPresenter implements Presenter {
|
||||
private final EpochServiceAsync epochService = GWT.create(EpochService.class);
|
||||
private final GeocodeServiceAsync geocodeService = GWT.create(GeocodeService.class);
|
||||
private final AstrologyUtil astroUtil = new AstrologyUtil();
|
||||
private final DateTimeUtil dateTimeUtil;
|
||||
private final Display display;
|
||||
private Date providedUtcDate;
|
||||
private Epoch epoch;
|
||||
private Date localDate;
|
||||
private Date utcDate;
|
||||
private boolean disableUpdate = false;
|
||||
|
||||
public interface Display {
|
||||
Widget asWidget();
|
||||
Button getUpdatePositionsButton();
|
||||
Button getRegenerateChartButton();
|
||||
Chart getChart();
|
||||
Label getUtcLabel();
|
||||
Label getUtcJdLabel();
|
||||
Label getUtcSidLabel();
|
||||
CheckBox getPlanetCheckBox(Planet planet);
|
||||
Label getPlanetLabel(Planet planet);
|
||||
Button getSelectAllPlanetsButton();
|
||||
Button getUnselectAllPlanetsButton();
|
||||
ListBox getHousesListBox();
|
||||
CheckBox getAspectCheckBox(AspectType type);
|
||||
ListBox getAspectListBox(AspectType type);
|
||||
Label getAspectLabel(AspectType type);
|
||||
void resetAspects();
|
||||
Button resetOrbsButton();
|
||||
void resetOrbs();
|
||||
Button getSelectAllAspectsButton();
|
||||
Button getUnselectAllAspectsButton();
|
||||
TextBox getLocationTextBox();
|
||||
Button getSubmitCityButton();
|
||||
TextBox getLatitudeTextBox();
|
||||
Button getSubmitLatitudeButton();
|
||||
TextBox getLongitudeTextBox();
|
||||
Button getSubmitLongitudeButton();
|
||||
Label getSunriseLabel();
|
||||
Label getSunsetLabel();
|
||||
Label getAscendentLabel();
|
||||
Label getStatusLabel();
|
||||
Label getSunPositionLabel();
|
||||
TimeEntry getTimeEntry();
|
||||
}
|
||||
|
||||
public ChartPresenter(final HandlerManager eventBus, final DateTimeUtil dateTimeUtil, final TabPanel tabPanel, final Display view,
|
||||
final Date providedUtcDate) {
|
||||
super(eventBus, tabPanel);
|
||||
this.dateTimeUtil = dateTimeUtil;
|
||||
this.providedUtcDate = providedUtcDate;
|
||||
this.display = view;
|
||||
}
|
||||
|
||||
public final void bind() {
|
||||
bindBus();
|
||||
this.display.getUpdatePositionsButton().addClickHandler(new ClickHandler() {
|
||||
@Override
|
||||
public void onClick(final ClickEvent event) {
|
||||
updateEpoch();
|
||||
}
|
||||
});
|
||||
this.display.getRegenerateChartButton().addClickHandler(new ClickHandler() {
|
||||
@Override
|
||||
public void onClick(final ClickEvent event) {
|
||||
regenerateChart();
|
||||
}
|
||||
});
|
||||
for (final Planet planet : Planet.values()) {
|
||||
this.display.getPlanetCheckBox(planet).addValueChangeHandler(createDefaultValueChangeHandler());
|
||||
}
|
||||
this.display.getSelectAllPlanetsButton().addClickHandler(createPlanetsChangeHandler(true));
|
||||
this.display.getUnselectAllPlanetsButton().addClickHandler(createPlanetsChangeHandler(false));
|
||||
this.display.getHousesListBox().addChangeHandler(new ChangeHandler() {
|
||||
@Override
|
||||
public void onChange(final ChangeEvent event) {
|
||||
final String houseSystemName = display.getHousesListBox().getItemText(display.getHousesListBox().getSelectedIndex());
|
||||
final HouseType type = HouseType.getTypeForName(houseSystemName);
|
||||
display.getChart().changeHouseSystem(type);
|
||||
}
|
||||
});
|
||||
for (final AspectType type : AspectType.values()) {
|
||||
this.display.getAspectCheckBox(type).addValueChangeHandler(createDefaultValueChangeHandler());
|
||||
this.display.getAspectListBox(type).addChangeHandler(new ChangeHandler() {
|
||||
@Override
|
||||
public void onChange(final ChangeEvent event) {
|
||||
regenerateChart();
|
||||
}
|
||||
});
|
||||
}
|
||||
this.display.resetOrbsButton().addClickHandler(new ClickHandler() {
|
||||
@Override
|
||||
public void onClick(final ClickEvent event) {
|
||||
disableUpdate = true;
|
||||
display.resetOrbs();
|
||||
disableUpdate = false;
|
||||
regenerateChart();
|
||||
|
||||
}
|
||||
});
|
||||
this.display.getSelectAllAspectsButton().addClickHandler(createAspectChangeHandler(true));
|
||||
this.display.getUnselectAllAspectsButton().addClickHandler(createAspectChangeHandler(false));
|
||||
this.display.getLocationTextBox().addKeyUpHandler(new KeyUpHandler() {
|
||||
@Override
|
||||
public void onKeyUp(final KeyUpEvent event) {
|
||||
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
|
||||
updateGeodataByCityName();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.display.getSubmitCityButton().addClickHandler(new ClickHandler() {
|
||||
@Override
|
||||
public void onClick(final ClickEvent event) {
|
||||
updateGeodataByCityName();
|
||||
}
|
||||
});
|
||||
this.display.getSubmitLatitudeButton().addClickHandler(createGeocodeClickHandler());
|
||||
this.display.getSubmitLongitudeButton().addClickHandler(createGeocodeClickHandler());
|
||||
this.display.getLatitudeTextBox().addKeyUpHandler(createGeocodeKeyUpHandler());
|
||||
this.display.getLongitudeTextBox().addKeyUpHandler(createGeocodeKeyUpHandler());
|
||||
}
|
||||
|
||||
public final void bindBus() {
|
||||
getEventBus().addHandler(DateUpdatedEvent.TYPE, new DateUpdatedEventHandler() {
|
||||
@Override
|
||||
public void onDateUpdated(final DateUpdatedEvent event) {
|
||||
updateEpoch(event.getLocalDate());
|
||||
}
|
||||
});
|
||||
getEventBus().addHandler(ResetAspectsEvent.TYPE, new ResetAspectsEventHandler() {
|
||||
@Override
|
||||
public void onResetAspects(final ResetAspectsEvent event) {
|
||||
display.resetAspects();
|
||||
}
|
||||
});
|
||||
getEventBus().addHandler(SetStatusEvent.TYPE, new SetStatusEventHandler() {
|
||||
@Override
|
||||
public void onSetStatus(final SetStatusEvent event) {
|
||||
display.getStatusLabel().setText(event.getStatusMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void go(final HasWidgets container) {
|
||||
bind();
|
||||
container.clear();
|
||||
container.add(super.getTabPanel());
|
||||
if (providedUtcDate != null) {
|
||||
// fill time entry with provided date (calls updateEpoch)
|
||||
display.getTimeEntry().updateDate(providedUtcDate);
|
||||
} else {
|
||||
updateEpoch();
|
||||
}
|
||||
|
||||
// XXX Experimental HTML5 Geolocation
|
||||
// tryToGetGeolocationFromBrowser();
|
||||
|
||||
if (display.getLocationTextBox().getText().equals("unknown")) {
|
||||
updateGeodataByIp();
|
||||
}
|
||||
this.display.getLocationTextBox().setFocus(true);
|
||||
}
|
||||
|
||||
private void updateEpoch() {
|
||||
updateEpoch(null);
|
||||
}
|
||||
|
||||
private void updateEpoch(final Date inputLocalDate) {
|
||||
display.getStatusLabel().setText("Updating positions.");
|
||||
if (inputLocalDate != null) {
|
||||
localDate = inputLocalDate;
|
||||
} else {
|
||||
localDate = display.getTimeEntry().getLocalDate();
|
||||
}
|
||||
utcDate = dateTimeUtil.getUtcDate(localDate);
|
||||
final String timeZone = display.getTimeEntry().getClientTimezone();
|
||||
display.getUtcLabel().setText(dateTimeUtil.formatDateAsUtc(localDate));
|
||||
display.getUtcLabel().setTitle("As Time in your local timezone: \n" + dateTimeUtil.formatLocalDate(utcDate) + timeZone);
|
||||
display.getUtcJdLabel().setText(dateTimeUtil.getFormattedJdTimeDate(utcDate));
|
||||
display.getUtcJdLabel().setTitle("As JD Time in your local timezone: \n" + dateTimeUtil.getFormattedJdTimeDate(localDate) + timeZone);
|
||||
final Date sidDate = dateTimeUtil.getLocalSidTimeDate(localDate); // also known as LST
|
||||
final Date utcSidDate = dateTimeUtil.getLocalSidTimeDate(utcDate); // also known as GMST
|
||||
display.getUtcSidLabel().setTitle("As Sidereal Time in your local timezone: \n" + dateTimeUtil.formatLocalDate(sidDate) + timeZone);
|
||||
display.getUtcSidLabel().setText(dateTimeUtil.formatLocalDate(utcSidDate));
|
||||
epochService.readEpoch(utcSidDate, new AsyncCallback<Epoch>() {
|
||||
@Override
|
||||
public void onSuccess(final Epoch result) {
|
||||
epoch = result;
|
||||
for (final Planet planet : Planet.values()) {
|
||||
final Label label = display.getPlanetLabel(planet);
|
||||
label.setText(result.getPositionDegreeString(planet));
|
||||
label.setTitle(result.getPositionString(planet));
|
||||
}
|
||||
display.getStatusLabel().setText("Positions updated.");
|
||||
processCustomGeocode(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(final Throwable caught) {
|
||||
if (caught instanceof EpochNotFoundException) {
|
||||
display.getStatusLabel().setText("Epoch not found. Please try another date.");
|
||||
} else {
|
||||
display.getStatusLabel().setText("Fail reading epoch: " + caught.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Experimental HTML5 feature
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
private void tryToGetGeolocationFromBrowser() {
|
||||
final Geolocation geolocation = Geolocation.getIfSupported(); // experimental
|
||||
geolocation.getCurrentPosition(new Callback<Position, PositionError>() {
|
||||
@Override
|
||||
public void onSuccess(final Position result) {
|
||||
final Coordinates coords = result.getCoordinates();
|
||||
display.getLatitudeTextBox().setText(String.valueOf(coords.getLatitude()));
|
||||
display.getLatitudeTextBox().setTitle(astroUtil.convertDegrees(coords.getLatitude()));
|
||||
display.getLongitudeTextBox().setText(String.valueOf(coords.getLongitude()));
|
||||
display.getLongitudeTextBox().setTitle(astroUtil.convertDegrees(coords.getLongitude()));
|
||||
processCustomGeocode(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(final PositionError reason) {
|
||||
display.getStatusLabel().setText("Fail: Not able to get geolocation data from browser.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void updateGeodataByIp() {
|
||||
display.getStatusLabel().setText("Updating geodata by IP.");
|
||||
geocodeService.getGeocodeDataForIp(new AsyncCallback<GeocodeData>() {
|
||||
@Override
|
||||
public void onSuccess(final GeocodeData result) {
|
||||
processGeocodeData(result);
|
||||
}
|
||||
@Override
|
||||
public void onFailure(final Throwable caught) {
|
||||
display.getStatusLabel().setText(
|
||||
"Fail: Getting geocode data from IP. Please enter a city name or provide the latitude and longitude manually.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void updateGeodataByCityName() {
|
||||
display.getStatusLabel().setText("Updating geodata by location name.");
|
||||
final String cityName = display.getLocationTextBox().getText().trim();
|
||||
geocodeService.getGeocodeData(cityName, new AsyncCallback<GeocodeData>() {
|
||||
@Override
|
||||
public void onSuccess(final GeocodeData result) {
|
||||
processGeocodeData(result);
|
||||
}
|
||||
@Override
|
||||
public void onFailure(final Throwable caught) {
|
||||
display.getStatusLabel().setText("Fail: Getting geocode data.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void processCustomGeocode(final boolean resetCityName) {
|
||||
display.getStatusLabel().setText("Processing custom geocode data.");
|
||||
final GeocodeData geocode = new GeocodeData();
|
||||
if (resetCityName) {
|
||||
geocode.setCityName("user input");
|
||||
this.display.getLocationTextBox().setText("user input");
|
||||
} else {
|
||||
geocode.setCityName(display.getLocationTextBox().getText());
|
||||
}
|
||||
this.display.getStatusLabel().setText("");
|
||||
try {
|
||||
geocode.setLatitude(Double.valueOf(display.getLatitudeTextBox().getText()));
|
||||
try {
|
||||
geocode.setLongitude(Double.valueOf(display.getLongitudeTextBox().getText()));
|
||||
processGeocodeData(geocode);
|
||||
} catch (final NumberFormatException nfe) {
|
||||
final String message = "Fail: Longitude is not numeric.";
|
||||
this.display.getStatusLabel().setText(message);
|
||||
this.display.getLongitudeTextBox().setFocus(true);
|
||||
}
|
||||
} catch (final NumberFormatException nfe) {
|
||||
final String message = "Fail: Latitide is not numeric.";
|
||||
this.display.getStatusLabel().setText(message);
|
||||
this.display.getLatitudeTextBox().setFocus(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void processGeocodeData(final GeocodeData geocode) {
|
||||
if (geocode == null || (geocode.getCityName().equals("") && geocode.getLatitude() == 0.0D && geocode.getLongitude() == 0.0D)) {
|
||||
assert true; // ignore
|
||||
} else {
|
||||
display.getLocationTextBox().setText(geocode.getCityName());
|
||||
|
||||
final NumberFormat nf = NumberFormat.getFormat("0.0000000");
|
||||
display.getLatitudeTextBox().setTitle(astroUtil.convertDegrees(geocode.getLatitude()));
|
||||
display.getLatitudeTextBox().setText(nf.format(geocode.getLatitude()));
|
||||
display.getLongitudeTextBox().setTitle(astroUtil.convertDegrees(geocode.getLongitude()));
|
||||
display.getLongitudeTextBox().setText(nf.format(geocode.getLongitude()));
|
||||
|
||||
final RiseAndSet ras = astroUtil.calculateSunRiseAndSet(localDate, geocode.getLatitude(), geocode.getLongitude());
|
||||
display.getSunriseLabel().setText(dateTimeUtil.formatLocalDate(ras.getRise()));
|
||||
display.getSunsetLabel().setText(dateTimeUtil.formatLocalDate(ras.getSet()));
|
||||
final BodyPosition position = astroUtil.calculateSunPosition(utcDate, geocode.getLatitude(), geocode.getLongitude());
|
||||
display.getSunPositionLabel().setText(position.toString());
|
||||
|
||||
final AscendentAndOffset ascendent = astroUtil.determineAscendent(utcDate, geocode.getLongitude(), geocode.getLatitude());
|
||||
display.getAscendentLabel().setText(ascendent.toString());
|
||||
|
||||
display.getStatusLabel().setText("Generating chart...");
|
||||
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
|
||||
@Override
|
||||
public void execute() {
|
||||
final String houseSystemName = display.getHousesListBox().getItemText(display.getHousesListBox().getSelectedIndex());
|
||||
final HouseType type = HouseType.getTypeForName(houseSystemName);
|
||||
display.getChart().generateChart(ascendent, epoch, type);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public final void regenerateChart() {
|
||||
if (disableUpdate) {
|
||||
return;
|
||||
}
|
||||
display.getStatusLabel().setText("Generating chart...");
|
||||
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
|
||||
@Override
|
||||
public void execute() {
|
||||
processCustomGeocode(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ClickHandler createAspectChangeHandler(final boolean value) {
|
||||
return new ClickHandler() {
|
||||
@Override
|
||||
public void onClick(final ClickEvent event) {
|
||||
disableUpdate = true;
|
||||
for (final AspectType aspectType : AspectType.values()) {
|
||||
display.getAspectCheckBox(aspectType).setValue(value);
|
||||
}
|
||||
disableUpdate = false;
|
||||
regenerateChart();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private ClickHandler createPlanetsChangeHandler(final boolean value) {
|
||||
return new ClickHandler() {
|
||||
@Override
|
||||
public void onClick(final ClickEvent event) {
|
||||
disableUpdate = true;
|
||||
for (final Planet planet : Planet.values()) {
|
||||
display.getPlanetCheckBox(planet).setValue(value);
|
||||
}
|
||||
disableUpdate = false;
|
||||
regenerateChart();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private ValueChangeHandler<Boolean> createDefaultValueChangeHandler() {
|
||||
return new ValueChangeHandler<Boolean>() {
|
||||
@Override
|
||||
public void onValueChange(final ValueChangeEvent<Boolean> event) {
|
||||
regenerateChart();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private ClickHandler createGeocodeClickHandler() {
|
||||
return new ClickHandler() {
|
||||
@Override
|
||||
public void onClick(final ClickEvent event) {
|
||||
processCustomGeocode(true);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private KeyUpHandler createGeocodeKeyUpHandler() {
|
||||
return new KeyUpHandler() {
|
||||
@Override
|
||||
public void onKeyUp(final KeyUpEvent event) {
|
||||
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
|
||||
processCustomGeocode(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package astrochart.client.presenter;
|
||||
|
||||
import com.google.gwt.event.shared.HandlerManager;
|
||||
import com.google.gwt.user.client.ui.Anchor;
|
||||
import com.google.gwt.user.client.ui.FlexTable;
|
||||
import com.google.gwt.user.client.ui.HTML;
|
||||
import com.google.gwt.user.client.ui.HasWidgets;
|
||||
import com.google.gwt.user.client.ui.TabPanel;
|
||||
import com.google.gwt.user.client.ui.Widget;
|
||||
|
||||
public class InfoPresenter extends AbstractTabPresenter implements Presenter {
|
||||
private final Display display;
|
||||
private int row = 0;
|
||||
|
||||
public interface Display {
|
||||
FlexTable getInfoList();
|
||||
Widget asWidget();
|
||||
}
|
||||
|
||||
public InfoPresenter(final HandlerManager eventBus,
|
||||
final TabPanel tabPanel, final Display view) {
|
||||
super(eventBus, tabPanel);
|
||||
this.display = view;
|
||||
}
|
||||
|
||||
public final void bind() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void go(final HasWidgets container) {
|
||||
bind();
|
||||
prepareTable();
|
||||
container.clear();
|
||||
container.add(super.getTabPanel());
|
||||
}
|
||||
|
||||
private void prepareTable() {
|
||||
display.getInfoList().removeAllRows();
|
||||
display.getInfoList().getColumnFormatter().setWidth(0, "100px");
|
||||
addRowText("Welcome to Astrology Chart Generator.");
|
||||
addRowText("This application is work in progress and may therefore still display incorrect results.");
|
||||
addRowWidget(new HTML(" "));
|
||||
addRowText("The ephemeris used in this application can be found at:");
|
||||
addRowWidget(new Anchor("http://www.findyourfate.com/astrology/ephemeris/ephemeris.html", "http://www.findyourfate.com/astrology/ephemeris/ephemeris.html"));
|
||||
addRowWidget(new HTML(" "));
|
||||
addRowText("Astrology Chart Generator uses the following IP-location lookup service:");
|
||||
addRowWidget(new Anchor("http://freegeoip.net", "http://freegeoip.net"));
|
||||
addRowWidget(new HTML(" "));
|
||||
addRowText("The location lookup by city-name is powered by:");
|
||||
addRowWidget(new Anchor("http://code.google.com/apis/maps/index.html", "http://code.google.com/apis/maps/index.html"));
|
||||
addRowWidget(new HTML(" "));
|
||||
addRowText("Sunrise and sunset calculations are done according to the formulas provided at:");
|
||||
addRowWidget(new Anchor("http://users.electromagnetic.net/bu/astro/sunrise-set.php", "http://users.electromagnetic.net/bu/astro/sunrise-set.php"));
|
||||
addRowText("This application will therefore calculate the same results for sunrise and sunset as calculated here:");
|
||||
addRowWidget(new Anchor("http://users.electromagnetic.net/bu/astro/iyf-calc.php", "http://users.electromagnetic.net/bu/astro/iyf-calc.php"));
|
||||
addRowText("(Beware: There are many other online calculators that result in different results.)");
|
||||
addRowWidget(new HTML(" "));
|
||||
addRowText("The source code and the unit tests of this application can be found at:");
|
||||
addRowWidget(new Anchor("https://github.com/Tok/AstroChart", "https://github.com/Tok/AstroChart"));
|
||||
}
|
||||
|
||||
private void addRowText(final String text) {
|
||||
display.getInfoList().setText(row, 0, text);
|
||||
row++;
|
||||
}
|
||||
|
||||
private void addRowWidget(final Widget widget) {
|
||||
display.getInfoList().setWidget(row, 0, widget);
|
||||
row++;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package astrochart.client.presenter;
|
||||
|
||||
import com.google.gwt.user.client.ui.HasWidgets;
|
||||
|
||||
public abstract interface Presenter {
|
||||
void go(final HasWidgets container);
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package astrochart.client.service;
|
||||
|
||||
import astrochart.shared.data.Epoch;
|
||||
import com.google.gwt.user.client.rpc.RemoteService;
|
||||
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
|
||||
|
||||
@RemoteServiceRelativePath("admin")
|
||||
public interface AdminService extends RemoteService {
|
||||
void saveEpoch(final Epoch epoch);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package astrochart.client.service;
|
||||
|
||||
import astrochart.shared.data.Epoch;
|
||||
import com.google.gwt.user.client.rpc.AsyncCallback;
|
||||
|
||||
public interface AdminServiceAsync {
|
||||
void saveEpoch(final Epoch epoch, final AsyncCallback<Void> callback);;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package astrochart.client.service;
|
||||
|
||||
import java.util.Date;
|
||||
import astrochart.shared.data.Epoch;
|
||||
import astrochart.shared.exceptions.EpochNotFoundException;
|
||||
import com.google.gwt.user.client.rpc.RemoteService;
|
||||
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
|
||||
|
||||
@RemoteServiceRelativePath("epoch")
|
||||
public interface EpochService extends RemoteService {
|
||||
Epoch readEpoch(final Date date) throws EpochNotFoundException;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package astrochart.client.service;
|
||||
|
||||
import java.util.Date;
|
||||
import astrochart.shared.data.Epoch;
|
||||
import com.google.gwt.user.client.rpc.AsyncCallback;
|
||||
|
||||
public interface EpochServiceAsync {
|
||||
void readEpoch(final Date date, final AsyncCallback<Epoch> callback);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user