Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||||
+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
+2985
File diff suppressed because it is too large
Load Diff
+55
@@ -0,0 +1,55 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "3"
|
||||||
|
members = [
|
||||||
|
"crates/swisseph-sys",
|
||||||
|
"crates/astro-engine",
|
||||||
|
"crates/geo-tz",
|
||||||
|
"crates/service-kit",
|
||||||
|
"crates/db",
|
||||||
|
"crates/horoscope-client",
|
||||||
|
"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" }
|
||||||
|
|
||||||
|
anyhow = "1"
|
||||||
|
argon2 = { version = "0.5", features = ["std"] }
|
||||||
|
axum = "0.8"
|
||||||
|
axum-extra = { version = "0.10", features = ["cookie"] }
|
||||||
|
base64 = "0.22"
|
||||||
|
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,7 @@ 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/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/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, takarítás (később az LLM-elemzések). Részletek: [services/worker/README.md](services/worker/README.md) |
|
||||||
| `crates/db` | PostgreSQL-séma (migrációk) és a szolgáltatások közös adatelérése |
|
| `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/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 |
|
| `crates/service-kit` | közös alapok: naplózás, listen cím, healthcheck, leállítás |
|
||||||
@@ -20,11 +21,17 @@ Asztrológiai rendszer konténeres backendje. A frontenden kívül minden Rustba
|
|||||||
### Docker
|
### Docker
|
||||||
|
|
||||||
```bash
|
```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:8080/healthz
|
||||||
curl -s localhost:8081/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
|
||||||
|
```
|
||||||
|
|
||||||
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.
|
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 …`):
|
Build-argumentumok (`docker compose build --build-arg …`):
|
||||||
|
|||||||
@@ -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,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,126 @@
|
|||||||
|
//! 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");
|
||||||
|
|
||||||
|
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,
|
||||||
|
User,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Role {
|
||||||
|
pub const ALL: [Role; 3] = [Role::Admin, Role::Creator, Role::User];
|
||||||
|
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Role::Admin => "admin",
|
||||||
|
Role::Creator => "creator",
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
|
||||||
|
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,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,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,77 @@
|
|||||||
|
# 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:3000}
|
||||||
|
# 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:-}
|
||||||
|
LLM_MODELS: ${LLM_MODELS:-openrouter/auto}
|
||||||
|
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>}
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
read_only: true
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
@@ -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.
|
||||||
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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package astrochart.client.service;
|
||||||
|
|
||||||
|
import astrochart.shared.data.GeocodeData;
|
||||||
|
import com.google.gwt.user.client.rpc.RemoteService;
|
||||||
|
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
|
||||||
|
|
||||||
|
@RemoteServiceRelativePath("geocode")
|
||||||
|
public interface GeocodeService extends RemoteService {
|
||||||
|
GeocodeData getGeocodeData(final String cityName);
|
||||||
|
GeocodeData getGeocodeDataForIp();
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package astrochart.client.service;
|
||||||
|
|
||||||
|
import astrochart.shared.data.GeocodeData;
|
||||||
|
import com.google.gwt.user.client.rpc.AsyncCallback;
|
||||||
|
|
||||||
|
public interface GeocodeServiceAsync {
|
||||||
|
void getGeocodeData(final String cityName, final AsyncCallback<GeocodeData> callback);
|
||||||
|
void getGeocodeDataForIp(final AsyncCallback<GeocodeData> callback);;
|
||||||
|
}
|
||||||
+546
@@ -0,0 +1,546 @@
|
|||||||
|
package astrochart.client.util;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import com.google.gwt.i18n.client.NumberFormat;
|
||||||
|
import astrochart.shared.EquinocticalShaddowLengths;
|
||||||
|
import astrochart.shared.enums.ZodiacSign;
|
||||||
|
import astrochart.shared.wrappers.AscendentAndOffset;
|
||||||
|
import astrochart.shared.wrappers.BodyPosition;
|
||||||
|
import astrochart.shared.wrappers.RiseAndSet;
|
||||||
|
|
||||||
|
|
||||||
|
public class AstrologyUtil {
|
||||||
|
public static final double EARTH_INCLINATION_J2000 = 23.4392911D; // in degrees
|
||||||
|
public static final double EARTH_INCLINATION_J1950 = 23.4457889D; // in degrees
|
||||||
|
public static final double EARTH_AXIS_TILT = 23.45D; // TODO change to EARTH_AXIS_TILT_PRECISE
|
||||||
|
public static final double EARTH_AXIS_TILT_PRECISE = 23.439D; // TODO use EARTH_INCLINATION_J2000
|
||||||
|
public static final double EARTH_AXIS_TILT_DAILY_CHANGE = 0.0000004D;
|
||||||
|
public static final double PERIHELION_TO_VENERAL_EQUINOX_DEGREES = 102.9372D;
|
||||||
|
public static final double LONG_ABERRATION = 0.9856474D;
|
||||||
|
public static final double ANGLE_TO_SUN_FROM_PERIHELION = 357.528D; // TODO change to ANGLE_TO_SUN_FROM_PERIHELION_PRECISE
|
||||||
|
public static final double ANGLE_TO_SUN_FROM_PERIHELION_PRECISE = 357.5291D;
|
||||||
|
public static final double SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION = 0.9856003D; // TODO change to SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION_PRECISE
|
||||||
|
public static final double SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION_PRECISE = 0.98560028D;
|
||||||
|
public static final double SOLAR_ELEVATION_AT_SUNRISE_AND_SUNSET = -0.83D;
|
||||||
|
public static final double EARTHS_SOLAR_TRANSIT_DATE = 0.0009D;
|
||||||
|
public static final double EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION = 0.0053D;
|
||||||
|
public static final double EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION = 0.0069D;
|
||||||
|
public static final double EARTH_ECCENTRICITY = 0.0167D;
|
||||||
|
public static final double SAEMUNDSON_REFRACTION_CONSTANT_1 = 1.02D;
|
||||||
|
public static final double SAEMUNDSON_REFRACTION_CONSTANT_2 = 10.3D;
|
||||||
|
public static final double SAEMUNDSON_REFRACTION_CONSTANT_3 = 5.11D;
|
||||||
|
public static final double EQUATION_OF_CENTER_CONSTANT_1 = 1.9148D;
|
||||||
|
public static final double EQUATION_OF_CENTER_CONSTANT_2 = 0.0200D;
|
||||||
|
public static final double EQUATION_OF_CENTER_CONSTANT_3 = 0.0003D;
|
||||||
|
|
||||||
|
private final EquinocticalShaddowLengths esl = new EquinocticalShaddowLengths();
|
||||||
|
private final DateTimeUtil dateTimeUtil = new DateTimeUtil();
|
||||||
|
|
||||||
|
private double meanSolarAnomaly = 0D;
|
||||||
|
private double equationOfCenter = 0D;
|
||||||
|
private double solarEclipticalLongitude = 0D;
|
||||||
|
private double solarNoonTransit = 0D;
|
||||||
|
|
||||||
|
public final double getMeanSolarNoonAnomaly() {
|
||||||
|
return meanSolarAnomaly;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getEquationOfCenter() {
|
||||||
|
return equationOfCenter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getSolarEclipticalLongitude() {
|
||||||
|
return solarEclipticalLongitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getSolarNoonTransit() {
|
||||||
|
return solarNoonTransit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asserts the ascendent for the provided local SiderealTime at latitude
|
||||||
|
* @param localSiderealTimeDeg Local siderealTime in degrees
|
||||||
|
* @param latitude of the location
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final ZodiacSign getTropicalAscendent(final double localSiderealTimeDeg, final double localLatitude) {
|
||||||
|
double ascendentDegrees = Math.atan(
|
||||||
|
(Math.cos(localSiderealTimeDeg) * -1)
|
||||||
|
/ (
|
||||||
|
(Math.sin(localSiderealTimeDeg) * Math.cos(EARTH_INCLINATION_J2000))
|
||||||
|
+ (Math.tan(localLatitude) * Math.sin(EARTH_INCLINATION_J2000))
|
||||||
|
));
|
||||||
|
if (ascendentDegrees < 0D || Math.cos(localSiderealTimeDeg) < 0D) {
|
||||||
|
ascendentDegrees = ascendentDegrees + (Constants.DEGREES_IN_CIRCLE / 2);
|
||||||
|
}
|
||||||
|
return ZodiacSign.getSignAtDegree(ascendentDegrees);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final long calculateRashimanaSeconds(final ZodiacSign sign, final double latitude) {
|
||||||
|
final int roundedLat = Double.valueOf(latitude).intValue();
|
||||||
|
final int charakhandas = esl.calculateCharakhandas(sign, roundedLat);
|
||||||
|
final long asus = getAsus(sign, charakhandas);
|
||||||
|
return dateTimeUtil.convertAsusToSiderealSeconds(asus);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long getAsus(final ZodiacSign sign, final int charakhandas) {
|
||||||
|
if (sign.hasLongAscension()) {
|
||||||
|
return sign.getRashimanaGroup().getEquatorialAsus() + charakhandas;
|
||||||
|
} else {
|
||||||
|
return sign.getRashimanaGroup().getEquatorialAsus() - charakhandas;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateEclipticLongitude(final double julianDayNumber) {
|
||||||
|
return Constants.MEAN_LONGITUDE_OF_THE_SUN + (LONG_ABERRATION * julianDayNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateMeanAnomaly(final double julianDayNumber) {
|
||||||
|
return ANGLE_TO_SUN_FROM_PERIHELION + (SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION * julianDayNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateJulianCycle(final double julianDay, final double longitudeWest) {
|
||||||
|
final double cycle = julianDay - DateTimeUtil.J_CONSTANT - (longitudeWest / Constants.DEGREES_IN_CIRCLE);
|
||||||
|
return cycle + Constants.HALF_JULIAN_DAY;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateAccurateJulianCycle(final double julianDay, final double longitude) {
|
||||||
|
return Math.round((julianDay - Constants.JULIAN_DAY_AT_01_01_2000 - EARTHS_SOLAR_TRANSIT_DATE) - (longitude / Constants.DEGREES_IN_CIRCLE));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* calculates the solar meanpoint as ecliptic coordinate
|
||||||
|
* with a numeric eccentricity of ~0.0167
|
||||||
|
* @param eclipticLongitude
|
||||||
|
* @param meanAnormaly
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final double calculateEclipticalLength(final double eclipticLongitude, final double meanAnormaly) {
|
||||||
|
final double el = Math.toRadians(eclipticLongitude % Constants.DEGREES_IN_CIRCLE);
|
||||||
|
final double ma = Math.toRadians(meanAnormaly % Constants.DEGREES_IN_CIRCLE);
|
||||||
|
final double result = el
|
||||||
|
+ ((2 * EARTH_ECCENTRICITY * Math.sin(ma))
|
||||||
|
+ ((5.0D / 4.0D) * Math.pow(EARTH_ECCENTRICITY, 2) * Math.sin(2 * EARTH_ECCENTRICITY))
|
||||||
|
);
|
||||||
|
return Math.toDegrees(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateEclipticInclination(final double julianDayNumber) {
|
||||||
|
return EARTH_AXIS_TILT_PRECISE - (EARTH_AXIS_TILT_DAILY_CHANGE * julianDayNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://de.wikipedia.org/wiki/Sonnenstand#.C3.84quatorialkoordinaten_der_Sonne
|
||||||
|
* @param eclipticInclination
|
||||||
|
* @param eclipticalLength
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final double calculateRightAscension(final double eclipticInclination, final double eclipticalLength) {
|
||||||
|
final double eclipticInclinationRadians = Math.toRadians(eclipticInclination);
|
||||||
|
final double eclipticalLengthRadians = Math.toRadians(eclipticalLength);
|
||||||
|
final double argument = (Math.cos(eclipticInclinationRadians) * Math.sin(eclipticalLengthRadians)) / Math.cos(eclipticalLengthRadians);
|
||||||
|
final double atan = Math.atan(argument);
|
||||||
|
final double result = Math.toDegrees(atan);
|
||||||
|
return clampResult(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double clampResult(final double result) {
|
||||||
|
if (result < 0.0D) {
|
||||||
|
return result + (Constants.DEGREES_IN_CIRCLE / 2);
|
||||||
|
} else {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateDeclination(final double eclipticInclination, final double eclipticalLength) {
|
||||||
|
final double result = Math.asin(Math.sin(Math.toRadians(eclipticInclination)) * Math.sin(Math.toRadians(eclipticalLength)));
|
||||||
|
return Math.toDegrees(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateVeneralEquinoxDegrees(final double starTimeDegrees, final double longitude) {
|
||||||
|
return (starTimeDegrees + longitude) % Constants.DEGREES_IN_CIRCLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateHourAngle(final double localJulianDeg, final double rightAscension) {
|
||||||
|
return localJulianDeg - rightAscension;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateAzimuth(final double hourAngle, final double latitude, final double declination) {
|
||||||
|
final double divisor =
|
||||||
|
(Math.cos(Math.toRadians(hourAngle)) * Math.sin(Math.toRadians(latitude)))
|
||||||
|
- (Math.tan(Math.toRadians(declination)) * Math.cos(Math.toRadians(latitude)));
|
||||||
|
final double azimuthAtan = Math.atan(Math.sin(Math.toRadians(hourAngle)) / divisor);
|
||||||
|
final double azimuth = Math.toDegrees(azimuthAtan);
|
||||||
|
return clampAzimuth(azimuth, divisor);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double clampAzimuth(final double azimuth, final double divisor) {
|
||||||
|
if (divisor < 0D) {
|
||||||
|
return azimuth + (Constants.DEGREES_IN_CIRCLE / 2);
|
||||||
|
} else {
|
||||||
|
return azimuth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateAzimuthNorth(final double hourAngle, final double latitude, final double declination) {
|
||||||
|
return calculateAzimuth(hourAngle, latitude, declination) + (Constants.DEGREES_IN_CIRCLE / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateHeightAngle(final double hourAngle, final double latitude, final double declination) {
|
||||||
|
final double heightAngle =
|
||||||
|
Math.asin((Math.cos(Math.toRadians(declination))
|
||||||
|
* Math.cos(Math.toRadians(hourAngle))
|
||||||
|
* Math.cos(Math.toRadians(latitude)))
|
||||||
|
+ (Math.sin(Math.toRadians(declination))
|
||||||
|
* Math.sin(Math.toRadians(latitude))));
|
||||||
|
return Math.toDegrees(heightAngle);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the mean refraction for an object at the provided angle at 1010 mbar and 10� C.
|
||||||
|
* http://de.wikipedia.org/wiki/Sonnenstand#Korrektur_der_H.C3.B6he_wegen_Refraktion
|
||||||
|
* @param heightAngle
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private double calculateRefraction(final double heightAngle) {
|
||||||
|
final double term = heightAngle + (SAEMUNDSON_REFRACTION_CONSTANT_2 / (heightAngle + SAEMUNDSON_REFRACTION_CONSTANT_3));
|
||||||
|
final double termRadians = Math.toRadians(term);
|
||||||
|
return SAEMUNDSON_REFRACTION_CONSTANT_1 / Math.tan(termRadians);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateRefractionDegrees(final double heightAngle) {
|
||||||
|
return heightAngle + (calculateRefraction(heightAngle) / Constants.MINUTES_PER_DEGREE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://de.wikipedia.org/wiki/Sonnenstand
|
||||||
|
*/
|
||||||
|
public final BodyPosition calculateSunPosition(final Date date, final double latitude, final double longitude) {
|
||||||
|
final double julianDay = dateTimeUtil.getJdTimeDate(date);
|
||||||
|
final double n = dateTimeUtil.calculateJulianDayNumberFromJd(julianDay);
|
||||||
|
final double l = calculateEclipticLongitude(n);
|
||||||
|
final double g = calculateMeanAnomaly(n);
|
||||||
|
final double lambda = calculateEclipticalLength(l, g); //solar ecliptic coordinate
|
||||||
|
|
||||||
|
final double epsilon = calculateEclipticInclination(n); //ecliptic inclination
|
||||||
|
|
||||||
|
final double rightAscension = calculateRightAscension(epsilon, lambda);
|
||||||
|
final double declination = calculateDeclination(epsilon, lambda); //equatorical declination
|
||||||
|
|
||||||
|
final double jdo = dateTimeUtil.getJulianDayNumberTimeDropped(date);
|
||||||
|
final double t = dateTimeUtil.getJulianCenturiesSinceJ2000(jdo); //julian centuries since J2000.0
|
||||||
|
|
||||||
|
final double decimalHours = dateTimeUtil.getDecimalHours(date);
|
||||||
|
final double starTimeHours = dateTimeUtil.calculateStarTimeHours(t, decimalHours);
|
||||||
|
final double starTimeDegrees = dateTimeUtil.convertHoursToDegree(starTimeHours);
|
||||||
|
|
||||||
|
final double localJulianDeg = calculateVeneralEquinoxDegrees(starTimeDegrees, longitude); //veneral equinox degrees
|
||||||
|
|
||||||
|
final double hourAngle = calculateHourAngle(localJulianDeg, rightAscension);
|
||||||
|
|
||||||
|
final double azimuth = calculateAzimuth(hourAngle, latitude, declination);
|
||||||
|
|
||||||
|
final double heightAngle = calculateHeightAngle(hourAngle, latitude, declination);
|
||||||
|
final double refHeight = calculateRefractionDegrees(heightAngle);
|
||||||
|
|
||||||
|
return new BodyPosition(azimuth, refHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateApproxSolarNoon(final double julianCycle, final double longitude) {
|
||||||
|
return Constants.JULIAN_DAY_AT_01_01_2000 + EARTHS_SOLAR_TRANSIT_DATE + (longitude / Constants.DEGREES_IN_CIRCLE) + julianCycle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateAccurateMeanAnomaly(final double solarNoonApprox) {
|
||||||
|
return (ANGLE_TO_SUN_FROM_PERIHELION_PRECISE
|
||||||
|
+ (SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION_PRECISE
|
||||||
|
* (solarNoonApprox - Constants.JULIAN_DAY_AT_01_01_2000)))
|
||||||
|
% Constants.DEGREES_IN_CIRCLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://en.wikipedia.org/wiki/Sunrise_equation#Equation_of_Center
|
||||||
|
* @param meanSolarAnomaly
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final double calculateEquationOfCenter(final double meanSolarAnomaly) {
|
||||||
|
return (EQUATION_OF_CENTER_CONSTANT_1 * Math.sin(Math.toRadians(meanSolarAnomaly)))
|
||||||
|
+ (EQUATION_OF_CENTER_CONSTANT_2 * Math.sin(2D * Math.toRadians(meanSolarAnomaly)))
|
||||||
|
+ (EQUATION_OF_CENTER_CONSTANT_3 * Math.sin(3D * Math.toRadians(meanSolarAnomaly)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateSolarEclipticLongitude(final double meanSolarAnomaly, final double equationOfCenter) {
|
||||||
|
return (meanSolarAnomaly + PERIHELION_TO_VENERAL_EQUINOX_DEGREES + equationOfCenter + (Constants.DEGREES_IN_CIRCLE / 2)) % Constants.DEGREES_IN_CIRCLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateSolarNoonTransit(final double solarNoonApprox, final double meanSolarAnomaly, final double solarEclipticalLongitude) {
|
||||||
|
return solarNoonApprox
|
||||||
|
+ (EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION * Math.sin(Math.toRadians(meanSolarAnomaly)))
|
||||||
|
- (EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION * Math.sin(Math.toRadians(2D * solarEclipticalLongitude)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateSolarDeclination(final double solarEclipticalLongitude) {
|
||||||
|
final double result = Math.asin(
|
||||||
|
Math.sin(Math.toRadians(solarEclipticalLongitude))
|
||||||
|
* Math.sin(Math.toRadians(EARTH_AXIS_TILT))
|
||||||
|
);
|
||||||
|
return Math.toDegrees(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateAccurateMeanAnomalyRecursive(final double solarNoonApprox, final double oldMeanSolarAnomaly, final double solarNoonTransit) {
|
||||||
|
final double meanSolarAnomaly = calculateAccurateMeanAnomaly(solarNoonTransit);
|
||||||
|
if (oldMeanSolarAnomaly != meanSolarAnomaly) {
|
||||||
|
final double equationOfCenter = calculateEquationOfCenter(meanSolarAnomaly);
|
||||||
|
final double solarEclipticalLongitude = calculateSolarEclipticLongitude(meanSolarAnomaly, equationOfCenter);
|
||||||
|
final double newSolarNoonTransit = calculateSolarNoonTransit(solarNoonApprox, meanSolarAnomaly, solarEclipticalLongitude);
|
||||||
|
return calculateAccurateMeanAnomalyRecursive(solarNoonApprox, meanSolarAnomaly, newSolarNoonTransit);
|
||||||
|
} else {
|
||||||
|
this.meanSolarAnomaly = meanSolarAnomaly;
|
||||||
|
this.equationOfCenter = calculateEquationOfCenter(meanSolarAnomaly);
|
||||||
|
this.solarEclipticalLongitude = calculateSolarEclipticLongitude(meanSolarAnomaly, equationOfCenter);
|
||||||
|
this.solarNoonTransit = calculateSolarNoonTransit(solarNoonApprox, meanSolarAnomaly, solarEclipticalLongitude);
|
||||||
|
return meanSolarAnomaly;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateExactHourAngle(final double latitude, final double solarDeclination) {
|
||||||
|
final double result =
|
||||||
|
Math.acos(
|
||||||
|
(Math.sin(Math.toRadians(SOLAR_ELEVATION_AT_SUNRISE_AND_SUNSET))
|
||||||
|
- (Math.sin(Math.toRadians(latitude))
|
||||||
|
* Math.sin(Math.toRadians(solarDeclination))))
|
||||||
|
/ (Math.cos(Math.toRadians(latitude))
|
||||||
|
* Math.cos(Math.toRadians(solarDeclination)))
|
||||||
|
);
|
||||||
|
return Math.toDegrees(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateSolarNoonSecondApprox(final double hourAngle, final double longitude, final double julianCycle) {
|
||||||
|
return Constants.JULIAN_DAY_AT_01_01_2000 + EARTHS_SOLAR_TRANSIT_DATE + ((hourAngle + longitude) / Constants.DEGREES_IN_CIRCLE) + julianCycle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateSunset(final double solarNoonSecondApprox, final double meanSolarAnomaly, final double solarEclipticalLongitude) {
|
||||||
|
return solarNoonSecondApprox
|
||||||
|
+ (EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION * Math.sin(Math.toRadians(meanSolarAnomaly)))
|
||||||
|
- (EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION * Math.sin(Math.toRadians(2D * solarEclipticalLongitude)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateSunrise(final double sunset, final double solarNoonTransit) {
|
||||||
|
return solarNoonTransit - (sunset - solarNoonTransit);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://users.electromagnetic.net/bu/astro/sunrise-set.php
|
||||||
|
* http://www.jgiesen.de/astro/astroJS/sunriseJS/index.htm
|
||||||
|
* @param julianDay
|
||||||
|
* @param latitude
|
||||||
|
* @param longitude
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final RiseAndSet calculateSunRiseAndSet(final Date date, final double latitude, final double longitude) {
|
||||||
|
final double julianDate = dateTimeUtil.calculateJulianDate(date);
|
||||||
|
final double julianCycle = calculateAccurateJulianCycle(julianDate, longitude);
|
||||||
|
final double solarNoonApprox = calculateApproxSolarNoon(julianCycle, longitude);
|
||||||
|
|
||||||
|
final double meanSolarAnomaly = calculateAccurateMeanAnomaly(solarNoonApprox);
|
||||||
|
this.equationOfCenter = calculateEquationOfCenter(meanSolarAnomaly);
|
||||||
|
this.solarEclipticalLongitude = calculateSolarEclipticLongitude(meanSolarAnomaly, equationOfCenter);
|
||||||
|
this.solarNoonTransit = calculateSolarNoonTransit(solarNoonApprox, meanSolarAnomaly, solarEclipticalLongitude);
|
||||||
|
|
||||||
|
final double accurateMeanSolarAnomaly = calculateAccurateMeanAnomalyRecursive(solarNoonApprox, meanSolarAnomaly, solarNoonTransit);
|
||||||
|
|
||||||
|
final double solarDeclination = calculateSolarDeclination(solarEclipticalLongitude);
|
||||||
|
final double hourAngle = calculateExactHourAngle(latitude, solarDeclination);
|
||||||
|
final double solarNoonSecondApprox = calculateSolarNoonSecondApprox(hourAngle, longitude, julianCycle);
|
||||||
|
|
||||||
|
final double sunset = calculateSunset(solarNoonSecondApprox, accurateMeanSolarAnomaly, getSolarEclipticalLongitude());
|
||||||
|
final double sunrise = calculateSunrise(sunset, getSolarNoonTransit());
|
||||||
|
final Date sunriseDate = dateTimeUtil.convertJdToDate(sunrise);
|
||||||
|
final Date sunsetDate = dateTimeUtil.convertJdToDate(sunset);
|
||||||
|
|
||||||
|
final RiseAndSet result = new RiseAndSet(sunriseDate, sunsetDate);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://en.wikipedia.org/wiki/Sunrise_equation
|
||||||
|
* @param julianDay
|
||||||
|
* @param latitude
|
||||||
|
* @param longitude
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final double calculateSunrise(final double julianDay, final double latitude, final double longitude) {
|
||||||
|
//FIXME
|
||||||
|
final double currentJulianCycle = calculateJulianCycle(julianDay, longitude);
|
||||||
|
final double approximateSolarNoon = DateTimeUtil.J_CONSTANT + (longitude / Constants.DEGREES_IN_CIRCLE) + currentJulianCycle;
|
||||||
|
final double solarMeanAnomaly = (ANGLE_TO_SUN_FROM_PERIHELION_PRECISE
|
||||||
|
+ (SOLAR_MEAN_DAILY_ANOMALISTIC_MOTION_PRECISE * (approximateSolarNoon - Constants.JULIAN_DAY_AT_01_01_2000)))
|
||||||
|
% Constants.DEGREES_IN_CIRCLE;
|
||||||
|
final double equationOfCenter =
|
||||||
|
(EQUATION_OF_CENTER_CONSTANT_1 * Math.sin(solarMeanAnomaly))
|
||||||
|
+ (EQUATION_OF_CENTER_CONSTANT_2 * Math.sin(2.0D * solarMeanAnomaly))
|
||||||
|
+ (EQUATION_OF_CENTER_CONSTANT_3 * Math.sin(3.0D * solarMeanAnomaly));
|
||||||
|
final double eclipticLongitude = (solarMeanAnomaly + PERIHELION_TO_VENERAL_EQUINOX_DEGREES + equationOfCenter + (Constants.DEGREES_IN_CIRCLE / 2))
|
||||||
|
% Constants.DEGREES_IN_CIRCLE;
|
||||||
|
final double solarTransit =
|
||||||
|
approximateSolarNoon
|
||||||
|
+ (EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION * Math.sin(solarMeanAnomaly))
|
||||||
|
- (EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION * Math.sin(2.0D * eclipticLongitude)); //hour angle for solar noon
|
||||||
|
final double sunDeclination = Math.asin(Math.sin(eclipticLongitude) * Math.sin(EARTH_AXIS_TILT));
|
||||||
|
final double hourAngle =
|
||||||
|
Math.acos(
|
||||||
|
(Math.sin(SOLAR_ELEVATION_AT_SUNRISE_AND_SUNSET) - (Math.sin(latitude) * Math.sin(sunDeclination)))
|
||||||
|
/ (Math.cos(latitude) * Math.cos(sunDeclination))
|
||||||
|
);
|
||||||
|
final double sunSet = DateTimeUtil.J_CONSTANT + ((hourAngle + longitude) / Constants.DEGREES_IN_CIRCLE) + currentJulianCycle
|
||||||
|
+ (EARTHS_SOLAR_TRANSIT_ECCENTRICAL_VARIATION * Math.sin(solarMeanAnomaly))
|
||||||
|
- (EARTHS_SOLAR_TRANSIT_ECLIPTIC_OBLIQUITY_VARIATION * Math.sin(2D * eclipticLongitude));
|
||||||
|
final double sunRise = solarTransit - (sunSet - solarTransit);
|
||||||
|
return sunRise;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://de.wikipedia.org/wiki/Aszendent_%28Astrologie%29#Berechnung_des_Aszendenten
|
||||||
|
* @param localSiderealDegrees
|
||||||
|
* @param latitude
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final double calculateEclipticLongitudeJ2000Tangens(final double localSiderealDegrees, final double latitude) {
|
||||||
|
final double tanLambda =
|
||||||
|
(Math.cos(Math.toRadians(localSiderealDegrees)) * -1)
|
||||||
|
/ ((Math.sin(Math.toRadians(localSiderealDegrees))
|
||||||
|
* Math.cos(Math.toRadians(EARTH_INCLINATION_J2000)))
|
||||||
|
+ (Math.tan(Math.toRadians(latitude))
|
||||||
|
* Math.sin(Math.toRadians(EARTH_INCLINATION_J2000))));
|
||||||
|
return tanLambda;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final boolean returnDescendent(final double localSiderealDegrees) {
|
||||||
|
return ((Constants.DEGREES_IN_CIRCLE / 4) < localSiderealDegrees && localSiderealDegrees < ((Constants.DEGREES_IN_CIRCLE / 4) * 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getFirstHorizontEclipticSection(final double eclipticLongitudeTan) {
|
||||||
|
final double eclipticLongitude = Math.atan(eclipticLongitudeTan);
|
||||||
|
final double eclipticLongitudeDeg = Math.toDegrees(eclipticLongitude);
|
||||||
|
final double firstS1 = (eclipticLongitudeDeg + (Constants.DEGREES_IN_CIRCLE / 2)) % Constants.DEGREES_IN_CIRCLE;
|
||||||
|
return clampS1(firstS1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double clampS1(final double firstS1) {
|
||||||
|
if (firstS1 >= (Constants.DEGREES_IN_CIRCLE / 2)) {
|
||||||
|
return firstS1 - (Constants.DEGREES_IN_CIRCLE / 2);
|
||||||
|
} else {
|
||||||
|
return firstS1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getSecondHorizontEclipticSection(final double eclipticLongitudeTan) {
|
||||||
|
return getFirstHorizontEclipticSection(eclipticLongitudeTan) + (Constants.DEGREES_IN_CIRCLE / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final ZodiacSign returnSign(final double s1, final double s2, final boolean returnDescendent) {
|
||||||
|
if (returnDescendent) {
|
||||||
|
return ZodiacSign.getSignAtDegree(s2);
|
||||||
|
} else {
|
||||||
|
return ZodiacSign.getSignAtDegree(s1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double returnPosition(final double s1, final double s2, final boolean returnDescendent) {
|
||||||
|
if (returnDescendent) {
|
||||||
|
return s2 - returnSign(s1, s2, returnDescendent).getEclipticLongitude();
|
||||||
|
} else {
|
||||||
|
return s1 - returnSign(s1, s2, returnDescendent).getEclipticLongitude();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final AscendentAndOffset determineAscendent(final Date utcDate, final double longitude, final double latitude) {
|
||||||
|
final double jd = dateTimeUtil.getJdTimeDate(utcDate);
|
||||||
|
final double siderealDegrees = dateTimeUtil.getSiderealDegrees(jd);
|
||||||
|
final double localSiderealDegrees = dateTimeUtil.getLocalSiderealDegrees(siderealDegrees, longitude);
|
||||||
|
final double eclipticLongitudeTan = calculateEclipticLongitudeJ2000Tangens(localSiderealDegrees, latitude);
|
||||||
|
final double s1 = getFirstHorizontEclipticSection(eclipticLongitudeTan);
|
||||||
|
final double s2 = getSecondHorizontEclipticSection(eclipticLongitudeTan);
|
||||||
|
final boolean returnDescendent = returnDescendent(localSiderealDegrees);
|
||||||
|
|
||||||
|
final ZodiacSign sign = returnSign(s1, s2, returnDescendent);
|
||||||
|
final double position = returnPosition(s1, s2, returnDescendent);
|
||||||
|
|
||||||
|
// final double midheaven = calculateMidheaven(localSiderealDegrees);
|
||||||
|
// final double midheaven = calculateMc(localSiderealDegrees);
|
||||||
|
final double midheaven = 0.0D; //FIXME
|
||||||
|
|
||||||
|
final AscendentAndOffset asc = new AscendentAndOffset(sign, position, midheaven);
|
||||||
|
return asc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://www.sismoloc.info/mc_east_and_ac_north.html
|
||||||
|
* ARMC = ascensio recta medii coeli = right ascension of the local meridian
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final double calculateMidheaven(final double armcDegree) {
|
||||||
|
return Math.toDegrees(
|
||||||
|
Math.atan(
|
||||||
|
Math.cos(Math.toRadians(EARTH_INCLINATION_J2000))
|
||||||
|
* (1D / Math.tan(Math.toRadians(armcDegree))) //=cot
|
||||||
|
) * -1D
|
||||||
|
) + ((Constants.DEGREES_IN_CIRCLE / 4) * 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://groups.google.com/group/alt.astrology.moderated/browse_thread/thread/5cf05d6fe8eabb52/17e0c6282d8c7dce?lnk=raot
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final double calculateMc(final double ramc) {
|
||||||
|
return Math.toDegrees(Math.atan(
|
||||||
|
Math.tan(Math.toRadians(ramc))
|
||||||
|
/ Math.cos(Math.toRadians(EARTH_INCLINATION_J2000))
|
||||||
|
)) + ((Constants.DEGREES_IN_CIRCLE / 4) * 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated
|
||||||
|
public final double calculateObliqueAscension(final double ascendentLongitude, final double longitude) {
|
||||||
|
final double rightAscension =
|
||||||
|
Math.toDegrees(Math.atan(
|
||||||
|
Math.cos(Math.toRadians(EARTH_INCLINATION_J2000))
|
||||||
|
* Math.tan(Math.toRadians(ascendentLongitude))
|
||||||
|
));
|
||||||
|
final double d =
|
||||||
|
Math.toDegrees(Math.asin(
|
||||||
|
Math.sin(Math.toRadians(EARTH_INCLINATION_J2000))
|
||||||
|
* Math.sin(Math.toRadians(ascendentLongitude))
|
||||||
|
));
|
||||||
|
System.out.println("rightAscension: " + rightAscension);
|
||||||
|
final double obliqueAscension =
|
||||||
|
rightAscension
|
||||||
|
- Math.toDegrees(Math.asin(
|
||||||
|
Math.tan(Math.toRadians(d))
|
||||||
|
* Math.tan(Math.toRadians(longitude))
|
||||||
|
));
|
||||||
|
return obliqueAscension;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts the provided degrees from decimal to a String with degrees, minutes and seconds.
|
||||||
|
* @param inDegrees decimal
|
||||||
|
* @return converted String
|
||||||
|
*/
|
||||||
|
public final String convertDegrees(final double inDegrees) {
|
||||||
|
final int degrees;
|
||||||
|
if (inDegrees >= 0) {
|
||||||
|
degrees = Double.valueOf(Math.floor(inDegrees)).intValue();
|
||||||
|
} else {
|
||||||
|
degrees = Double.valueOf(Math.ceil(inDegrees)).intValue();
|
||||||
|
}
|
||||||
|
final double decimalPlaces = Math.abs(inDegrees - degrees);
|
||||||
|
final double exactMinutes = decimalPlaces * Constants.MINUTES_PER_DEGREE;
|
||||||
|
final int minutes = Double.valueOf(Math.floor(exactMinutes)).intValue();
|
||||||
|
final double second = Double.valueOf((exactMinutes - Math.floor(exactMinutes)) * Constants.SECONDS_PER_MINUTE);
|
||||||
|
final String secondString = NumberFormat.getFormat("0.0").format(second);
|
||||||
|
return "" + degrees + Constants.DEGREE_SIGN + minutes + Constants.MINUTE_SIGN + secondString + Constants.SECOND_SIGN;
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package astrochart.client.util;
|
||||||
|
|
||||||
|
public final class Constants {
|
||||||
|
public static final double JULIAN_DAY_AT_01_01_2000 = 2451545D;
|
||||||
|
public static final double HALF_JULIAN_DAY = 0.5D;
|
||||||
|
public static final double MEAN_LONGITUDE_OF_THE_SUN = 280.460D; // XXX sometimes given as 280.461
|
||||||
|
public static final double MEAN_LONGITUDE_OF_THE_SUN_PRECISE = 280.46061837D;
|
||||||
|
public static final double DEGREES_IN_CIRCLE = 360.0D;
|
||||||
|
public static final double DEGREES_PER_HOUR = 15D;
|
||||||
|
public static final double MINUTES_PER_DEGREE = 60.0D;
|
||||||
|
public static final double HOURS_PER_DAY = 24D;
|
||||||
|
public static final double MINUTES_PER_HOUR = 60D;
|
||||||
|
public static final double SECONDS_PER_MINUTE = 60D;
|
||||||
|
public static final double SECONDS_PER_HOUR = 3600D;
|
||||||
|
public static final long MILLISECONDS_PER_MINUTE = 60000L;
|
||||||
|
public static final long MILLISECONDS_PER_DAY = 86400000L;
|
||||||
|
public static final char DEGREE_SIGN = '\u00B0';
|
||||||
|
public static final char MINUTE_SIGN = '\u2032';
|
||||||
|
public static final char SECOND_SIGN = '\u2033';
|
||||||
|
|
||||||
|
private Constants() { }
|
||||||
|
}
|
||||||
+392
@@ -0,0 +1,392 @@
|
|||||||
|
package astrochart.client.util;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import com.google.gwt.i18n.client.DateTimeFormat;
|
||||||
|
import com.google.gwt.i18n.client.NumberFormat;
|
||||||
|
import com.google.gwt.i18n.client.TimeZone;
|
||||||
|
|
||||||
|
public class DateTimeUtil {
|
||||||
|
public static final double J_CONSTANT = 2451545.0009D;
|
||||||
|
private static final long MS_2000 = 946684800000L; //2000-01-01 00:00:00 +0000 in milliseconds
|
||||||
|
private static final double JD_2000 = Constants.JULIAN_DAY_AT_01_01_2000 - Constants.HALF_JULIAN_DAY; //2000-01-01 00:00:00 as JD
|
||||||
|
private static final long MS_PER_DAY = 86400000L;
|
||||||
|
private static final double DAYS_PER_YEAR = 365D;
|
||||||
|
private static final long MONTHS_PER_YEAR = 12L;
|
||||||
|
private static final double DAYS_PER_JULIAN_CENTURY = 36525D;
|
||||||
|
private static final double MINUTES_PER_DAY = 1440D;
|
||||||
|
private static final double SECONDS_PER_HOUR = 3600D;
|
||||||
|
private static final double SECONDS_PER_DAY = 86400D;
|
||||||
|
private static final double SIDEREAL_CONSTANT_1 = 13185000.77D;
|
||||||
|
private static final double SIDEREAL_CONSTANT_2 = 2577.765D;
|
||||||
|
private static final double SIDEREAL_CONSTANT_3 = 38710000D;
|
||||||
|
private static final double SIDEREAL_GMST_CONSTANT_0 = 24110.54841D;
|
||||||
|
private static final double SIDEREAL_GMST_CONSTANT_1 = 8640184.812866D;
|
||||||
|
private static final double SIDEREAL_GMST_CONSTANT_2 = 0.093104D;
|
||||||
|
private static final double SIDEREAL_GMST_CONSTANT_3 = 0.0000062D;
|
||||||
|
private static final double SIDEREAL_HOUR_CONSTANT_1 = 18.697374558D;
|
||||||
|
private static final double SIDEREAL_HOUR_CONSTANT_2 = 24.06570982441908D;
|
||||||
|
private static final double GMST_HOUR_CONSTANT_1 = 6.697374558D;
|
||||||
|
private static final double GMST_HOUR_CONSTANT_2 = 0.06570982441908D;
|
||||||
|
private static final double GMST_HOUR_CONSTANT_3 = 1.00273790935D;
|
||||||
|
private static final double GMST_HOUR_CONSTANT_4 = 0.000026D;
|
||||||
|
private static final double STARTIME_CONSTANT_1 = 6.697376D; //change to GMST_HOUR_CONSTANT_1?
|
||||||
|
private static final double STARTIME_CONSTANT_2 = 2400.05134D;
|
||||||
|
private static final double STARTIME_CONSTANT_3 = 1.002738D;
|
||||||
|
private static final long LEAP_YEAR_CONSTANT_4 = 4L;
|
||||||
|
private static final long LEAP_YEAR_CONSTANT_100 = 100L;
|
||||||
|
private static final long LEAP_YEAR_CONSTANT_400 = 400L;
|
||||||
|
private static final long JULIAN_DAY_0_BC = 4800L;
|
||||||
|
private static final long MONTH_FACTOR = 153L;
|
||||||
|
private static final long JDN_OFFSET = 32045L;
|
||||||
|
|
||||||
|
private final DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy.MM.dd HH:mm:ss");
|
||||||
|
private final NumberFormat nf = NumberFormat.getFormat("00"); //number format for hours, minutes or seconds
|
||||||
|
private final NumberFormat jdNf = NumberFormat.getFormat("0.0000"); //number format for JD
|
||||||
|
|
||||||
|
private enum DateTimeRange {
|
||||||
|
Year(0, 4),
|
||||||
|
Month(5, 7),
|
||||||
|
Days(8, 10),
|
||||||
|
Hours(11, 13),
|
||||||
|
Minutes(14, 16),
|
||||||
|
Seconds(17, 19);
|
||||||
|
|
||||||
|
private int from;
|
||||||
|
private int to;
|
||||||
|
|
||||||
|
DateTimeRange(final int from, final int to) {
|
||||||
|
this.from = from;
|
||||||
|
this.to = to;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getFrom() {
|
||||||
|
return from;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getTo() {
|
||||||
|
return to;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String formatDateAsUtc(final Date localDate) {
|
||||||
|
return dateTimeFormat.format(localDate, TimeZone.createTimeZone(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String formatLocalDate(final Date localDate) {
|
||||||
|
return dateTimeFormat.format(localDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String formatLocalDate(final Date localDate, final String timeZone) {
|
||||||
|
final int timeZoneMinutes = getTimeZoneMinutes(timeZone);
|
||||||
|
return dateTimeFormat.format(localDate, TimeZone.createTimeZone(timeZoneMinutes));
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getTimeZoneMinutes(final String timeZone) {
|
||||||
|
if (timeZone.contains("+")) {
|
||||||
|
return Double.valueOf(Double.valueOf(timeZone.split("\\+")[1]) * Constants.MINUTES_PER_HOUR).intValue();
|
||||||
|
} else if (timeZone.contains("-")) {
|
||||||
|
return Double.valueOf(Double.valueOf(timeZone.split("\\-")[1]) * Constants.MINUTES_PER_HOUR).intValue();
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final Date getUtcDate(final Date localDate) {
|
||||||
|
return dateTimeFormat.parse(formatDateAsUtc(localDate));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final Date getUtcDateFromUtcString(final String utcDateString) {
|
||||||
|
return dateTimeFormat.parse(utcDateString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final Date getLocalDateFromUtc(final Date providedUtcDate) {
|
||||||
|
return dateTimeFormat.parse(dateTimeFormat.format(providedUtcDate));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://en.wikipedia.org/wiki/Julian_day#Julian_Date
|
||||||
|
* @param date
|
||||||
|
* @return Julian Date
|
||||||
|
*/
|
||||||
|
public final double getJdTimeDate(final Date date) {
|
||||||
|
final long differenceMs = date.getTime() - new Date(MS_2000).getTime(); //milliseconds since 2000-01-01 00:00:00
|
||||||
|
final double daysSince2000 = differenceMs / Double.valueOf(MS_PER_DAY);
|
||||||
|
final double jd = JD_2000 + daysSince2000; //Julian Date
|
||||||
|
return jd;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final Date convertJdToDate(final double jd) {
|
||||||
|
final double daysSince2000 = jd - JD_2000;
|
||||||
|
final double differenceMs = daysSince2000 * Double.valueOf(MS_PER_DAY);
|
||||||
|
final long dateMs = Double.valueOf(differenceMs).longValue() + new Date(MS_2000).getTime();
|
||||||
|
final Date result = new Date(dateMs);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getFormattedJdTimeDate(final Date date) {
|
||||||
|
return jdNf.format(getJdTimeDate(date));
|
||||||
|
}
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Also known as GMST
|
||||||
|
// * @param localDate
|
||||||
|
// * @return
|
||||||
|
// */
|
||||||
|
// public final Date getGmtSidTimeDate(final Date localDate) {
|
||||||
|
// return getLocalSidTimeDate(getUtcDate(localDate));
|
||||||
|
// }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Also known as LST
|
||||||
|
* http://en.wikipedia.org/wiki/Sidereal_time
|
||||||
|
* @param date
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final Date getLocalSidTimeDate(final Date date) {
|
||||||
|
final double jd = getJdTimeDate(date);
|
||||||
|
final double a = clampA(getSiderealDegrees(jd) / Constants.DEGREES_PER_HOUR);
|
||||||
|
|
||||||
|
final double gmstHours = a % Constants.HOURS_PER_DAY;
|
||||||
|
final double gmstMinutes = ((a % Constants.HOURS_PER_DAY) * Constants.MINUTES_PER_HOUR) % Constants.MINUTES_PER_HOUR;
|
||||||
|
final double gmstSeconds = ((a % Constants.HOURS_PER_DAY) * Constants.MINUTES_PER_HOUR * Constants.SECONDS_PER_MINUTE)
|
||||||
|
% Constants.SECONDS_PER_MINUTE;
|
||||||
|
|
||||||
|
final String dateString = dateTimeFormat.format(date);
|
||||||
|
final int dateYear = Integer.valueOf(dateString.substring(0, 4));
|
||||||
|
final int dateMonth = Integer.valueOf(dateString.substring(5, 7));
|
||||||
|
final int dateDay = Integer.valueOf(dateString.substring(8, 10));
|
||||||
|
|
||||||
|
final String gmstHoursString = nf.format(Math.floor(gmstHours));
|
||||||
|
final String gmstMinutesString = nf.format(Math.floor(gmstMinutes));
|
||||||
|
final String gmstSecondsString = nf.format(Math.floor(gmstSeconds));
|
||||||
|
|
||||||
|
final String gmstDateString =
|
||||||
|
nf.format(dateYear) + "." + nf.format(dateMonth) + "." + nf.format(dateDay) + " "
|
||||||
|
+ gmstHoursString + ":" + gmstMinutesString + ":" + gmstSecondsString;
|
||||||
|
|
||||||
|
return dateTimeFormat.parse(gmstDateString);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double clampA(final double a) {
|
||||||
|
if (a < 0D) {
|
||||||
|
return Constants.DEGREES_IN_CIRCLE - (Math.abs(a) % Constants.DEGREES_IN_CIRCLE);
|
||||||
|
} else {
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://www.cv.nrao.edu/~rfisher/Ephemerides/times.html
|
||||||
|
* @param jd
|
||||||
|
* @return GmstSiderealSeconds
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final double getGmstSeconds(final double jd) {
|
||||||
|
final double julianCenturiesSinceJ2000 = getJulianCenturiesSinceJ2000(jd);
|
||||||
|
final double gmstSiderealSeconds =
|
||||||
|
SIDEREAL_GMST_CONSTANT_0
|
||||||
|
+ (SIDEREAL_GMST_CONSTANT_1 * julianCenturiesSinceJ2000)
|
||||||
|
+ (SIDEREAL_GMST_CONSTANT_2 * Math.pow(julianCenturiesSinceJ2000, 2))
|
||||||
|
- (SIDEREAL_GMST_CONSTANT_3 * Math.pow(julianCenturiesSinceJ2000, 3));
|
||||||
|
return gmstSiderealSeconds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://answers.yahoo.com/question/index?qid=20070830185150AAoNT4i
|
||||||
|
* @param jd
|
||||||
|
* @return gmstSiderealHours
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public final double getGmstHours(final double jd) {
|
||||||
|
final double julianCenturiesSinceJ2000 = getJulianCenturiesSinceJ2000(jd);
|
||||||
|
final double h = 0D;
|
||||||
|
final double gmstSiderealHours =
|
||||||
|
GMST_HOUR_CONSTANT_1
|
||||||
|
+ (GMST_HOUR_CONSTANT_2 * julianCenturiesSinceJ2000)
|
||||||
|
+ (GMST_HOUR_CONSTANT_3 * h)
|
||||||
|
- (GMST_HOUR_CONSTANT_4 * Math.pow(julianCenturiesSinceJ2000, 2));
|
||||||
|
return gmstSiderealHours;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://de.wikipedia.org/wiki/Sternzeit#Berechnung_der_Sternzeit
|
||||||
|
* @param jd
|
||||||
|
* @return sidereal time in degrees.
|
||||||
|
*/
|
||||||
|
public final double getSiderealDegrees(final double jd) {
|
||||||
|
final double julianCenturiesSinceJ2000 = getJulianCenturiesSinceJ2000(jd);
|
||||||
|
final double siderealDegrees =
|
||||||
|
Constants.MEAN_LONGITUDE_OF_THE_SUN_PRECISE
|
||||||
|
+ (SIDEREAL_CONSTANT_1 * julianCenturiesSinceJ2000)
|
||||||
|
+ ((Math.pow(julianCenturiesSinceJ2000, 2)) / SIDEREAL_CONSTANT_2)
|
||||||
|
- ((Math.pow(julianCenturiesSinceJ2000, 3)) / SIDEREAL_CONSTANT_3);
|
||||||
|
return siderealDegrees;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://en.wikipedia.org/wiki/Sidereal_time#Definition
|
||||||
|
* loss of precision of 0.1 second per century
|
||||||
|
* @param decimalDays
|
||||||
|
* @return sidereal time in hours
|
||||||
|
*/
|
||||||
|
public final double getSiderealHours(final double jd) {
|
||||||
|
final double daysSinceJ2000 = jd - Constants.JULIAN_DAY_AT_01_01_2000;
|
||||||
|
final double siderealHours = SIDEREAL_HOUR_CONSTANT_1 + (SIDEREAL_HOUR_CONSTANT_2 * daysSinceJ2000);
|
||||||
|
return siderealHours;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts asus into seconds compare:
|
||||||
|
* http://www.aryabhatt.com/vediclessons/vediclesson5.htm
|
||||||
|
* @param asus
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final long convertAsusToSiderealSeconds(final long asus) {
|
||||||
|
return asus * 4L;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://en.wikipedia.org/wiki/Julian_day#Converting_Gregorian_calendar_date_to_Julian_Day_Number
|
||||||
|
* @param date
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final double getJulianDayNumber(final Date date) {
|
||||||
|
final String dateString = dateTimeFormat.format(date, TimeZone.createTimeZone(0));
|
||||||
|
final int dateYear = Integer.valueOf(dateString.substring(0, 4));
|
||||||
|
final int dateMonth = Integer.valueOf(dateString.substring(5, 7));
|
||||||
|
final int dateDay = Integer.valueOf(dateString.substring(8, 10));
|
||||||
|
final long a = ((MONTHS_PER_YEAR + 2L) - dateMonth) / MONTHS_PER_YEAR;
|
||||||
|
final long y = dateYear + JULIAN_DAY_0_BC - a;
|
||||||
|
final long m = dateMonth + (MONTHS_PER_YEAR * a) - 3;
|
||||||
|
final double jdn = dateDay
|
||||||
|
+ (((MONTH_FACTOR * m) + 2L) / 5L)
|
||||||
|
+ (DAYS_PER_YEAR * y)
|
||||||
|
+ (y / LEAP_YEAR_CONSTANT_4)
|
||||||
|
- (y / LEAP_YEAR_CONSTANT_100)
|
||||||
|
+ (y / LEAP_YEAR_CONSTANT_400)
|
||||||
|
- JDN_OFFSET;
|
||||||
|
return jdn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getJulianDayNumberWithTime(final Date date) {
|
||||||
|
final double jdn = getJulianDayNumber(date);
|
||||||
|
final String dateString = dateTimeFormat.format(date, TimeZone.createTimeZone(0));
|
||||||
|
final double hours = Double.valueOf(dateString.substring(11, 13));
|
||||||
|
final double minutes = Double.valueOf(dateString.substring(14, 16));
|
||||||
|
final double seconds = Double.valueOf(dateString.substring(17, 19));
|
||||||
|
final double result = jdn
|
||||||
|
+ ((hours - MONTHS_PER_YEAR) / Constants.HOURS_PER_DAY)
|
||||||
|
+ minutes / MINUTES_PER_DAY
|
||||||
|
+ seconds / SECONDS_PER_DAY;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getJulianDayNumberTimeDropped(final Date date) {
|
||||||
|
final double jdn = getJulianDayNumber(date);
|
||||||
|
final double hours = 0D;
|
||||||
|
final double minutes = 0D;
|
||||||
|
final double seconds = 0D;
|
||||||
|
final double result = jdn
|
||||||
|
+ ((hours - MONTHS_PER_YEAR) / Constants.HOURS_PER_DAY)
|
||||||
|
+ minutes / MINUTES_PER_DAY
|
||||||
|
+ seconds / SECONDS_PER_DAY;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* calculates julian centuries since J2000.0 for the provided julian day number
|
||||||
|
* @param julianDayNumber
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final double getJulianCenturiesSinceJ2000(final double jd) {
|
||||||
|
return ((jd - Constants.JULIAN_DAY_AT_01_01_2000) / DAYS_PER_JULIAN_CENTURY); //julian centuries since J2000
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateJulianDayNumberFromJd(final double julianDay) {
|
||||||
|
return julianDay - Constants.JULIAN_DAY_AT_01_01_2000; // days since equinox J2000.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* days since Jan 1, 2000 + 2451545
|
||||||
|
* @param date
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public final double calculateJulianDate(final Date date) {
|
||||||
|
final long differenceMs = date.getTime() - new Date(MS_2000).getTime(); //milliseconds since 2000-01-01 00:00:00
|
||||||
|
final double daysSince2000 = differenceMs / Double.valueOf(MS_PER_DAY);
|
||||||
|
return Math.floor(daysSince2000 + Constants.JULIAN_DAY_AT_01_01_2000);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double calculateStarTimeHours(final double julianCenturies, final double decimalHours) {
|
||||||
|
return STARTIME_CONSTANT_1
|
||||||
|
+ (STARTIME_CONSTANT_2 * julianCenturies)
|
||||||
|
+ (STARTIME_CONSTANT_3 * decimalHours);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double convertHoursToDegree(final double starTimeHours) {
|
||||||
|
return starTimeHours * Constants.DEGREES_PER_HOUR;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getDecimalHours(final Date date) {
|
||||||
|
final String dateString = dateTimeFormat.format(date, TimeZone.createTimeZone(0));
|
||||||
|
final double hours = Double.valueOf(dateString.substring(11, 13));
|
||||||
|
final double minutes = Double.valueOf(dateString.substring(14, 16));
|
||||||
|
final double seconds = Double.valueOf(dateString.substring(17, 19));
|
||||||
|
final double decimalHours = hours + (minutes / Constants.SECONDS_PER_MINUTE) + (seconds / SECONDS_PER_HOUR);
|
||||||
|
return decimalHours;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getYear(final Date date) {
|
||||||
|
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Year.getFrom(), DateTimeRange.Year.getTo()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getMonth(final Date date) {
|
||||||
|
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Month.getFrom(), DateTimeRange.Month.getTo()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getDay(final Date date) {
|
||||||
|
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Days.getFrom(), DateTimeRange.Days.getTo()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getHours(final Date date) {
|
||||||
|
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Hours.getFrom(), DateTimeRange.Hours.getTo()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getMinutes(final Date date) {
|
||||||
|
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Minutes.getFrom(), DateTimeRange.Minutes.getTo()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getSeconds(final Date date) {
|
||||||
|
return Integer.valueOf(dateTimeFormat.format(date).substring(DateTimeRange.Seconds.getFrom(), DateTimeRange.Seconds.getTo()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getLocalSiderealDegrees(final double siderealDegrees, final double longitude) {
|
||||||
|
return clampResult((siderealDegrees % Constants.DEGREES_IN_CIRCLE) + longitude);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double clampResult(final double result) {
|
||||||
|
if (result < 0D) {
|
||||||
|
return result + Constants.DEGREES_IN_CIRCLE;
|
||||||
|
} else {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* http://en.wikipedia.org/wiki/Leap_year#Algorithm
|
||||||
|
* @param year
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static final boolean isLeapYear(final int year) {
|
||||||
|
if (year % LEAP_YEAR_CONSTANT_4 == 0) {
|
||||||
|
if (year % LEAP_YEAR_CONSTANT_100 == 0) {
|
||||||
|
return (year % LEAP_YEAR_CONSTANT_400 == 0);
|
||||||
|
} else {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
package astrochart.client.view;
|
||||||
|
|
||||||
|
import astrochart.client.presenter.AdminPresenter;
|
||||||
|
import com.google.gwt.user.client.ui.Button;
|
||||||
|
import com.google.gwt.user.client.ui.Composite;
|
||||||
|
import com.google.gwt.user.client.ui.DecoratorPanel;
|
||||||
|
import com.google.gwt.user.client.ui.FlexTable;
|
||||||
|
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 AdminView extends Composite implements AdminPresenter.Display {
|
||||||
|
private final FlexTable contentTable;
|
||||||
|
private final Button submitButton = new Button("Submit");
|
||||||
|
private final TextArea inputTextArea = new TextArea();
|
||||||
|
private final Label statusLabel = new Label();
|
||||||
|
private final Label secondStatusLabel = new Label();
|
||||||
|
|
||||||
|
public AdminView() {
|
||||||
|
final DecoratorPanel contentTableDecorator = new DecoratorPanel();
|
||||||
|
contentTableDecorator.setWidth("1010px");
|
||||||
|
initWidget(contentTableDecorator);
|
||||||
|
contentTable = new FlexTable();
|
||||||
|
contentTable.setWidget(0, 0, submitButton);
|
||||||
|
inputTextArea.setWidth("997px");
|
||||||
|
inputTextArea.setHeight("500px");
|
||||||
|
contentTable.setWidget(1, 0, inputTextArea);
|
||||||
|
contentTable.setWidget(2, 0, statusLabel);
|
||||||
|
contentTable.setWidget(3, 0, secondStatusLabel);
|
||||||
|
contentTableDecorator.add(contentTable);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Widget asWidget() {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getSubmitButton() {
|
||||||
|
return submitButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final TextArea getInputTextArea() {
|
||||||
|
return inputTextArea;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getStatusLabel() {
|
||||||
|
return statusLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getSecondStatusLabel() {
|
||||||
|
return secondStatusLabel;
|
||||||
|
}
|
||||||
|
}
|
||||||
+409
@@ -0,0 +1,409 @@
|
|||||||
|
package astrochart.client.view;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import astrochart.client.presenter.ChartPresenter;
|
||||||
|
import astrochart.client.util.DateTimeUtil;
|
||||||
|
import astrochart.client.widgets.Chart;
|
||||||
|
import astrochart.client.widgets.TimeEntry;
|
||||||
|
import astrochart.shared.enums.AspectType;
|
||||||
|
import astrochart.shared.enums.HouseType;
|
||||||
|
import astrochart.shared.enums.Planet;
|
||||||
|
import com.google.gwt.event.shared.HandlerManager;
|
||||||
|
import com.google.gwt.user.client.ui.Button;
|
||||||
|
import com.google.gwt.user.client.ui.CheckBox;
|
||||||
|
import com.google.gwt.user.client.ui.Composite;
|
||||||
|
import com.google.gwt.user.client.ui.DecoratorPanel;
|
||||||
|
import com.google.gwt.user.client.ui.FlexTable;
|
||||||
|
import com.google.gwt.user.client.ui.HTML;
|
||||||
|
import com.google.gwt.user.client.ui.HasVerticalAlignment;
|
||||||
|
import com.google.gwt.user.client.ui.HorizontalPanel;
|
||||||
|
import com.google.gwt.user.client.ui.Label;
|
||||||
|
import com.google.gwt.user.client.ui.ListBox;
|
||||||
|
import com.google.gwt.user.client.ui.TextBox;
|
||||||
|
import com.google.gwt.user.client.ui.VerticalPanel;
|
||||||
|
import com.google.gwt.user.client.ui.Widget;
|
||||||
|
|
||||||
|
public class ChartView extends Composite implements ChartPresenter.Display {
|
||||||
|
private final FlexTable contentTable = new FlexTable();
|
||||||
|
private final Button updatePositionsButton = new Button("Update Positions");
|
||||||
|
private final Button regenerateChartButton = new Button("Regenerate Chart");
|
||||||
|
private final TextBox locationTextBox = new TextBox();
|
||||||
|
private final Button submitCityButton = new Button("Get");
|
||||||
|
private final Label latitudeLabel = new Label("Latitude: ");
|
||||||
|
private final TextBox latitudeTextBox = new TextBox();
|
||||||
|
private final Button submitLatitudeButton = new Button("Set");
|
||||||
|
private final Label longitudeLabel = new Label("Longitude: ");
|
||||||
|
private final TextBox longitudeTextBox = new TextBox();
|
||||||
|
private final Button submitLongitudeButton = new Button("Set");
|
||||||
|
private final Label utcLabel = new Label();
|
||||||
|
private final Label utcJdLabel = new Label();
|
||||||
|
private final Label utcSidLabel = new Label();
|
||||||
|
private final ListBox housesListBox = new ListBox();
|
||||||
|
private final Label sunriseLabel = new Label();
|
||||||
|
private final Label sunsetLabel = new Label();
|
||||||
|
private final Label sunPositionLabel = new Label();
|
||||||
|
private final Label ascendentLabel = new Label();
|
||||||
|
private final Label statusLabel = new Label();
|
||||||
|
private final Map<Planet, CheckBox> planetCheckBoxes = new HashMap<Planet, CheckBox>();
|
||||||
|
private final Map<Planet, Label> planetLabels = new HashMap<Planet, Label>();
|
||||||
|
private final Button selectAllPlanetsButton = new Button("Select All");
|
||||||
|
private final Button unselectAllPlanetsButton = new Button("Unselect All");
|
||||||
|
private final Map<AspectType, CheckBox> aspectCheckBoxes = new HashMap<AspectType, CheckBox>();
|
||||||
|
private final Map<AspectType, Label> aspectLabels = new HashMap<AspectType, Label>();
|
||||||
|
private final Map<AspectType, ListBox> aspectListboxes = new HashMap<AspectType, ListBox>();
|
||||||
|
private final Button selectAllAspectsButton = new Button("Select All");
|
||||||
|
private final Button unselectAllAspectsButton = new Button("Unselect All");
|
||||||
|
private final Button resetOrbsButton = new Button("Reset Orbs");
|
||||||
|
|
||||||
|
private final TimeEntry timeEntry;
|
||||||
|
private final Chart chart;
|
||||||
|
private int row;
|
||||||
|
|
||||||
|
public ChartView(final HandlerManager eventBus, final DateTimeUtil dateTimeUtil) {
|
||||||
|
final DecoratorPanel contentTableDecorator = new DecoratorPanel();
|
||||||
|
contentTableDecorator.setWidth("1010px");
|
||||||
|
initWidget(contentTableDecorator);
|
||||||
|
|
||||||
|
row = 0;
|
||||||
|
final HorizontalPanel buttonPanel = new HorizontalPanel();
|
||||||
|
buttonPanel.setSpacing(5);
|
||||||
|
buttonPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
|
||||||
|
|
||||||
|
final HorizontalPanel locPanel = new HorizontalPanel();
|
||||||
|
locPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
|
||||||
|
locationTextBox.setText("unknown");
|
||||||
|
locationTextBox.setWidth("240px");
|
||||||
|
locPanel.add(new Label("Location: "));
|
||||||
|
locPanel.add(locationTextBox);
|
||||||
|
locPanel.add(submitCityButton);
|
||||||
|
buttonPanel.add(locPanel);
|
||||||
|
|
||||||
|
final HorizontalPanel latPanel = new HorizontalPanel();
|
||||||
|
latPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
|
||||||
|
latitudeTextBox.setText("0.0000000");
|
||||||
|
latitudeTextBox.setWidth("80px");
|
||||||
|
latPanel.add(latitudeLabel);
|
||||||
|
latPanel.add(latitudeTextBox);
|
||||||
|
latPanel.add(submitLatitudeButton);
|
||||||
|
buttonPanel.add(latPanel);
|
||||||
|
|
||||||
|
final HorizontalPanel longPanel = new HorizontalPanel();
|
||||||
|
longPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
|
||||||
|
longitudeTextBox.setText("0.0000000");
|
||||||
|
longitudeTextBox.setWidth("80px");
|
||||||
|
longPanel.add(longitudeLabel);
|
||||||
|
longPanel.add(longitudeTextBox);
|
||||||
|
longPanel.add(submitLongitudeButton);
|
||||||
|
buttonPanel.add(longPanel);
|
||||||
|
buttonPanel.add(updatePositionsButton);
|
||||||
|
buttonPanel.add(regenerateChartButton);
|
||||||
|
contentTable.setWidget(row, 0, buttonPanel);
|
||||||
|
contentTable.getFlexCellFormatter().setColSpan(row, 0, 3);
|
||||||
|
row++;
|
||||||
|
|
||||||
|
timeEntry = new TimeEntry(eventBus, dateTimeUtil);
|
||||||
|
final VerticalPanel chartPanel = new VerticalPanel();
|
||||||
|
chartPanel.add(timeEntry);
|
||||||
|
chart = new Chart(eventBus, planetCheckBoxes, aspectListboxes, aspectCheckBoxes, aspectLabels);
|
||||||
|
chartPanel.add(chart);
|
||||||
|
|
||||||
|
contentTable.setWidget(row, 0, chartPanel);
|
||||||
|
contentTable.setText(row, 1, "UTC Time: ");
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_MIDDLE);
|
||||||
|
contentTable.setWidget(row, 2, utcLabel);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_MIDDLE);
|
||||||
|
row++;
|
||||||
|
|
||||||
|
addRow("UTC JD Time: ", utcJdLabel);
|
||||||
|
addRow("UTC Sidereal Time: ", utcSidLabel);
|
||||||
|
contentTable.setWidget(row, 0, new HTML(" "));
|
||||||
|
row++;
|
||||||
|
|
||||||
|
for (final Planet planet : Planet.values()) {
|
||||||
|
final HorizontalPanel pan = new HorizontalPanel();
|
||||||
|
final CheckBox planetCheckBox = new CheckBox();
|
||||||
|
if (planet.isBody() && !planet.isOuter()) {
|
||||||
|
planetCheckBox.setValue(true);
|
||||||
|
}
|
||||||
|
planetCheckBoxes.put(planet, planetCheckBox);
|
||||||
|
final Label planetLabel = new Label();
|
||||||
|
planetLabels.put(planet, planetLabel);
|
||||||
|
pan.add(planetCheckBox);
|
||||||
|
pan.add(new Label(planet.getUnicode() + " " + planet.name() + ": "));
|
||||||
|
addWidgetRow(pan, planetLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
final HorizontalPanel planetButtonPan = new HorizontalPanel();
|
||||||
|
planetButtonPan.add(selectAllPlanetsButton);
|
||||||
|
planetButtonPan.add(unselectAllPlanetsButton);
|
||||||
|
contentTable.setWidget(row, 0, planetButtonPan);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
contentTable.getFlexCellFormatter().setColSpan(row, 0, 2);
|
||||||
|
row++;
|
||||||
|
|
||||||
|
contentTable.setWidget(row, 0, new HTML(" "));
|
||||||
|
row++;
|
||||||
|
|
||||||
|
for (final HouseType houseType : HouseType.values()) {
|
||||||
|
housesListBox.addItem(houseType.getName());
|
||||||
|
}
|
||||||
|
contentTable.setText(row, 0, "Houses System: ");
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_MIDDLE);
|
||||||
|
contentTable.setWidget(row, 1, housesListBox);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_MIDDLE);
|
||||||
|
row++;
|
||||||
|
|
||||||
|
contentTable.setWidget(row, 0, new HTML(" "));
|
||||||
|
row++;
|
||||||
|
|
||||||
|
final FlexTable aspectFlex = new FlexTable();
|
||||||
|
aspectFlex.setText(0, 0, "Aspect");
|
||||||
|
aspectFlex.setText(0, 1, "Counter");
|
||||||
|
aspectFlex.setText(0, 2, "Orb");
|
||||||
|
int aspectRow = 1;
|
||||||
|
for (final AspectType aspectType : AspectType.values()) {
|
||||||
|
final HorizontalPanel pan = new HorizontalPanel();
|
||||||
|
final CheckBox aspectCheckBox = new CheckBox();
|
||||||
|
aspectCheckBox.setValue(true);
|
||||||
|
aspectCheckBoxes.put(aspectType, aspectCheckBox);
|
||||||
|
pan.add(aspectCheckBox);
|
||||||
|
pan.add(new Label(aspectType.getUnicode() + " " + aspectType.name() + "s: "));
|
||||||
|
aspectFlex.setWidget(aspectRow, 0, pan);
|
||||||
|
final Label aspectLabel = new Label();
|
||||||
|
aspectLabel.setText("0");
|
||||||
|
aspectLabels.put(aspectType, aspectLabel);
|
||||||
|
aspectFlex.setWidget(aspectRow, 1, aspectLabel);
|
||||||
|
final ListBox listBox = new ListBox();
|
||||||
|
listBox.setWidth("70px");
|
||||||
|
for (final double orb : aspectType.getOrbs()) {
|
||||||
|
listBox.addItem(String.valueOf(orb));
|
||||||
|
}
|
||||||
|
aspectListboxes.put(aspectType, listBox);
|
||||||
|
aspectFlex.setWidget(aspectRow, 2, listBox);
|
||||||
|
aspectRow++;
|
||||||
|
}
|
||||||
|
resetOrbs();
|
||||||
|
contentTable.setWidget(row, 0, aspectFlex);
|
||||||
|
contentTable.getFlexCellFormatter().setColSpan(row, 0, 2);
|
||||||
|
row++;
|
||||||
|
|
||||||
|
final HorizontalPanel aspectButtonPan = new HorizontalPanel();
|
||||||
|
aspectButtonPan.add(selectAllAspectsButton);
|
||||||
|
aspectButtonPan.add(unselectAllAspectsButton);
|
||||||
|
aspectButtonPan.add(resetOrbsButton);
|
||||||
|
contentTable.setWidget(row, 0, aspectButtonPan);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
contentTable.getFlexCellFormatter().setColSpan(row, 0, 2);
|
||||||
|
row++;
|
||||||
|
|
||||||
|
contentTable.setWidget(row, 0, new HTML(" "));
|
||||||
|
row++;
|
||||||
|
|
||||||
|
addRow("Sunrise Time: ", sunriseLabel);
|
||||||
|
addRow("Sunset Time: ", sunsetLabel);
|
||||||
|
addRow("Sun Position: ", sunPositionLabel);
|
||||||
|
addRow("Tropical Ascendent: ", ascendentLabel);
|
||||||
|
contentTable.setWidget(row, 0, statusLabel);
|
||||||
|
contentTable.getFlexCellFormatter().setColSpan(row, 0, 3);
|
||||||
|
contentTable.getFlexCellFormatter().setRowSpan(1, 0, row - 1); // chart
|
||||||
|
contentTableDecorator.add(contentTable);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addRow(final String label, final Widget widget) {
|
||||||
|
contentTable.setText(row, 0, label);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
contentTable.setWidget(row, 1, widget);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
row++;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addWidgetRow(final Widget first, final Widget second) {
|
||||||
|
contentTable.setWidget(row, 0, first);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
contentTable.setWidget(row, 1, second);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
row++;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private void addRow(final String label, final Widget firstWidget, final Widget secondWidget) {
|
||||||
|
contentTable.setText(row, 0, label);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 0, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
contentTable.setWidget(row, 1, firstWidget);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 1, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
contentTable.setWidget(row, 2, secondWidget);
|
||||||
|
contentTable.getCellFormatter().setVerticalAlignment(row, 2, HasVerticalAlignment.ALIGN_TOP);
|
||||||
|
row++;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Widget asWidget() {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getUpdatePositionsButton() {
|
||||||
|
return updatePositionsButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getRegenerateChartButton() {
|
||||||
|
return regenerateChartButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getUtcLabel() {
|
||||||
|
return utcLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getUtcJdLabel() {
|
||||||
|
return utcJdLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getUtcSidLabel() {
|
||||||
|
return utcSidLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Chart getChart() {
|
||||||
|
return chart;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final CheckBox getPlanetCheckBox(final Planet planet) {
|
||||||
|
return planetCheckBoxes.get(planet);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getPlanetLabel(final Planet planet) {
|
||||||
|
return planetLabels.get(planet);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getSelectAllPlanetsButton() {
|
||||||
|
return selectAllPlanetsButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getUnselectAllPlanetsButton() {
|
||||||
|
return unselectAllPlanetsButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final ListBox getHousesListBox() {
|
||||||
|
return housesListBox;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final CheckBox getAspectCheckBox(final AspectType type) {
|
||||||
|
return aspectCheckBoxes.get(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final ListBox getAspectListBox(final AspectType type) {
|
||||||
|
return aspectListboxes.get(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getAspectLabel(final AspectType type) {
|
||||||
|
return aspectLabels.get(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final void resetAspects() {
|
||||||
|
for (final AspectType aspectType : AspectType.values()) {
|
||||||
|
getAspectLabel(aspectType).setText("0");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button resetOrbsButton() {
|
||||||
|
return resetOrbsButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getUnselectAllAspectsButton() {
|
||||||
|
return unselectAllAspectsButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getSelectAllAspectsButton() {
|
||||||
|
return selectAllAspectsButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final void resetOrbs() {
|
||||||
|
for (final AspectType aspectType : AspectType.values()) {
|
||||||
|
int index = 0;
|
||||||
|
for (final double orb : aspectType.getOrbs()) {
|
||||||
|
if (orb == aspectType.getDefaultOrb()) {
|
||||||
|
getAspectListBox(aspectType).setItemSelected(index, true);
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final TextBox getLocationTextBox() {
|
||||||
|
return locationTextBox;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getSubmitCityButton() {
|
||||||
|
return submitCityButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final TextBox getLatitudeTextBox() {
|
||||||
|
return latitudeTextBox;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getSubmitLatitudeButton() {
|
||||||
|
return submitLatitudeButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final TextBox getLongitudeTextBox() {
|
||||||
|
return longitudeTextBox;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Button getSubmitLongitudeButton() {
|
||||||
|
return submitLongitudeButton;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getSunriseLabel() {
|
||||||
|
return sunriseLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getSunsetLabel() {
|
||||||
|
return sunsetLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getSunPositionLabel() {
|
||||||
|
return sunPositionLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getAscendentLabel() {
|
||||||
|
return ascendentLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Label getStatusLabel() {
|
||||||
|
return statusLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final TimeEntry getTimeEntry() {
|
||||||
|
return timeEntry;
|
||||||
|
}
|
||||||
|
}
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
package astrochart.client.view;
|
||||||
|
|
||||||
|
import astrochart.client.presenter.InfoPresenter;
|
||||||
|
|
||||||
|
import com.google.gwt.user.client.ui.Composite;
|
||||||
|
import com.google.gwt.user.client.ui.DecoratorPanel;
|
||||||
|
import com.google.gwt.user.client.ui.FlexTable;
|
||||||
|
import com.google.gwt.user.client.ui.Widget;
|
||||||
|
|
||||||
|
public class InfoView extends Composite implements InfoPresenter.Display {
|
||||||
|
private final FlexTable contentTable;
|
||||||
|
private final FlexTable infoList = new FlexTable();
|
||||||
|
|
||||||
|
public InfoView() {
|
||||||
|
final DecoratorPanel contentTableDecorator = new DecoratorPanel();
|
||||||
|
contentTableDecorator.setWidth("1010px");
|
||||||
|
initWidget(contentTableDecorator);
|
||||||
|
contentTable = new FlexTable();
|
||||||
|
infoList.setWidth("987px");
|
||||||
|
contentTable.setWidget(0, 0, infoList);
|
||||||
|
contentTableDecorator.add(contentTable);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Widget asWidget() {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final FlexTable getInfoList() {
|
||||||
|
return infoList;
|
||||||
|
}
|
||||||
|
}
|
||||||
+393
@@ -0,0 +1,393 @@
|
|||||||
|
package astrochart.client.widgets;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import astrochart.client.event.ResetAspectsEvent;
|
||||||
|
import astrochart.client.event.SetStatusEvent;
|
||||||
|
import astrochart.shared.data.Epoch;
|
||||||
|
import astrochart.shared.enums.AspectType;
|
||||||
|
import astrochart.shared.enums.ChartColor;
|
||||||
|
import astrochart.shared.enums.ChartProportions;
|
||||||
|
import astrochart.shared.enums.HouseType;
|
||||||
|
import astrochart.shared.enums.Planet;
|
||||||
|
import astrochart.shared.enums.ZodiacSign;
|
||||||
|
import astrochart.shared.wrappers.AscendentAndOffset;
|
||||||
|
import astrochart.shared.wrappers.TextPosition;
|
||||||
|
import com.google.gwt.canvas.client.Canvas;
|
||||||
|
import com.google.gwt.canvas.dom.client.Context2d;
|
||||||
|
import com.google.gwt.canvas.dom.client.CssColor;
|
||||||
|
import com.google.gwt.core.client.Scheduler;
|
||||||
|
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
|
||||||
|
import com.google.gwt.event.shared.HandlerManager;
|
||||||
|
import com.google.gwt.user.client.ui.CheckBox;
|
||||||
|
import com.google.gwt.user.client.ui.Composite;
|
||||||
|
import com.google.gwt.user.client.ui.Label;
|
||||||
|
import com.google.gwt.user.client.ui.ListBox;
|
||||||
|
import com.google.gwt.user.client.ui.VerticalPanel;
|
||||||
|
|
||||||
|
public class Chart extends Composite {
|
||||||
|
private static final int CANVAS_WIDTH = 600;
|
||||||
|
private static final int CANVAS_HEIGHT = 600;
|
||||||
|
private static final int TEXT_SIZE_LARGER = 12;
|
||||||
|
private static final int TEXT_SIZE_LARGE = 8;
|
||||||
|
private static final double LINE_WIDTH_LIGHT = 0.8;
|
||||||
|
private static final double LINE_WIDTH_LIGHTER = 0.75D;
|
||||||
|
private static final double LINE_WIDTH_ALMOSTSUPERLIGHT = 0.40;
|
||||||
|
private static final double LINE_WIDTH_SUPERLIGHT = 0.20;
|
||||||
|
private static final double LINE_WIDTH_HYPERLIGHT = 0.10;
|
||||||
|
private static final int Y_OFFSET = 18;
|
||||||
|
private static final int X_OFFSET = 23;
|
||||||
|
private static final double FULL_CIRCLE = 360D;
|
||||||
|
private static final double RIGHT_ANGLE = 90D;
|
||||||
|
private static final double DEGREES_PER_SIGN = 30D;
|
||||||
|
private static final double DEGREES_PER_HALF_SIGN = DEGREES_PER_SIGN / 2;
|
||||||
|
private final HandlerManager eventBus;
|
||||||
|
private final Map<Planet, CheckBox> planetCheckBoxes;
|
||||||
|
private final Map<AspectType, ListBox> aspectListboxes;
|
||||||
|
private final Map<AspectType, CheckBox> aspectCheckBoxes;
|
||||||
|
private final Map<AspectType, Label> aspectLabels;
|
||||||
|
private final VerticalPanel chartPanel = new VerticalPanel();
|
||||||
|
private final Canvas canvas = Canvas.createIfSupported();
|
||||||
|
private AscendentAndOffset ascendent;
|
||||||
|
private Epoch epoch;
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private HouseType houseType;
|
||||||
|
private final Map<String, TextPosition> aspects = new HashMap<String, TextPosition>();
|
||||||
|
|
||||||
|
public Chart(final HandlerManager eventBus, final Map<Planet, CheckBox> planetCheckBoxes, final Map<AspectType, ListBox> aspectListboxes,
|
||||||
|
final Map<AspectType, CheckBox> aspectCheckBoxes, final Map<AspectType, Label> aspectLabels) {
|
||||||
|
this.eventBus = eventBus;
|
||||||
|
this.planetCheckBoxes = planetCheckBoxes;
|
||||||
|
this.aspectListboxes = aspectListboxes;
|
||||||
|
this.aspectCheckBoxes = aspectCheckBoxes;
|
||||||
|
this.aspectLabels = aspectLabels;
|
||||||
|
if (canvas != null) {
|
||||||
|
canvas.setCoordinateSpaceWidth(CANVAS_WIDTH);
|
||||||
|
canvas.setCoordinateSpaceHeight(CANVAS_HEIGHT);
|
||||||
|
chartPanel.add(canvas);
|
||||||
|
} else {
|
||||||
|
chartPanel.add(new Label("Fail: Your browser doesn't support HTML5 Canvas."));
|
||||||
|
}
|
||||||
|
initWidget(chartPanel);
|
||||||
|
setStyleName("chart");
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private void generateEmptyChart() {
|
||||||
|
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
|
||||||
|
@Override
|
||||||
|
public void execute() {
|
||||||
|
generateChart(new AscendentAndOffset(ZodiacSign.Aries, 0.0D, ((FULL_CIRCLE * 3) / 4)), null, HouseType.Equal);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void generateChart(final AscendentAndOffset ascendent, final Epoch epoch, final HouseType houseType) {
|
||||||
|
this.ascendent = ascendent;
|
||||||
|
this.epoch = epoch;
|
||||||
|
this.houseType = houseType;
|
||||||
|
final Context2d ctx = canvas.getContext2d();
|
||||||
|
ctx.setStrokeStyle(CssColor.make(ChartColor.Black.getHex()));
|
||||||
|
ctx.setFillStyle(CssColor.make(ChartColor.White.getHex()));
|
||||||
|
ctx.setFont("10pt Arial");
|
||||||
|
ctx.fillRect(0, 0, canvas.getOffsetWidth(), canvas.getOffsetHeight()); //clear ctx
|
||||||
|
|
||||||
|
final double offset = ascendent.getOffset() + ascendent.getAscendent().getEclipticLongitude();
|
||||||
|
|
||||||
|
ctx.setLineWidth(1D);
|
||||||
|
markFiveDegrees(ctx, offset);
|
||||||
|
markDegrees(ctx, offset);
|
||||||
|
drawAscendentLine(
|
||||||
|
getXCenter(),
|
||||||
|
getYCenter(),
|
||||||
|
ChartProportions.getRadius(getHcs(), ChartProportions.Inner),
|
||||||
|
ascendent);
|
||||||
|
|
||||||
|
ctx.setLineWidth(2D);
|
||||||
|
drawArc(getXCenter(),
|
||||||
|
getYCenter(),
|
||||||
|
ChartProportions.getRadius(getHcs(), ChartProportions.Inner),
|
||||||
|
0D,
|
||||||
|
FULL_CIRCLE,
|
||||||
|
false);
|
||||||
|
|
||||||
|
//put zodiac
|
||||||
|
ctx.setFont("36pt Arial");
|
||||||
|
for (final ZodiacSign sign : ZodiacSign.values()) {
|
||||||
|
final double angle = keepInRange(sign.getEclipticLongitude() + RIGHT_ANGLE - offset);
|
||||||
|
|
||||||
|
//draw colored section
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.setFillStyle(CssColor.make(sign.getColor().getHex()));
|
||||||
|
final double start = Math.toRadians((sign.getEclipticLongitude() * -1) + (FULL_CIRCLE / 2) - DEGREES_PER_SIGN + offset);
|
||||||
|
final double end = Math.toRadians((sign.getEclipticLongitude() * -1) + (FULL_CIRCLE / 2) + offset);
|
||||||
|
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.OuterEclyptic), start, end, false);
|
||||||
|
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.InnerEclyptic), end, start, true);
|
||||||
|
ctx.fill();
|
||||||
|
ctx.stroke();
|
||||||
|
ctx.closePath();
|
||||||
|
|
||||||
|
//draw Signs
|
||||||
|
final double xSign = getHcs()
|
||||||
|
- (Math.sin(Math.toRadians(angle + DEGREES_PER_HALF_SIGN))
|
||||||
|
* ChartProportions.getRadius(getHcs(), ChartProportions.EclypticCenter)) - X_OFFSET;
|
||||||
|
final double ySign = getHcs()
|
||||||
|
- (Math.cos(Math.toRadians(angle + DEGREES_PER_HALF_SIGN))
|
||||||
|
* ChartProportions.getRadius(getHcs(), ChartProportions.EclypticCenter)) + Y_OFFSET;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.setFillStyle(CssColor.make(ChartColor.White.getHex()));
|
||||||
|
ctx.setStrokeStyle(CssColor.make(ChartColor.Black.getHex()));
|
||||||
|
ctx.fillText(String.valueOf(sign.getUnicode()), xSign, ySign);
|
||||||
|
ctx.strokeText(String.valueOf(sign.getUnicode()), xSign, ySign);
|
||||||
|
ctx.closePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
//draw houses
|
||||||
|
int house = 1;
|
||||||
|
if (houseType.equals(HouseType.Equal) || houseType.equals(HouseType.WholeSigns)) {
|
||||||
|
for (final ZodiacSign sign : ZodiacSign.values()) {
|
||||||
|
double angle = keepInRange(sign.getEclipticLongitude() + RIGHT_ANGLE);
|
||||||
|
if (houseType.equals(HouseType.WholeSigns)) {
|
||||||
|
angle = angle - (offset % DEGREES_PER_SIGN);
|
||||||
|
}
|
||||||
|
ctx.setLineWidth(LINE_WIDTH_HYPERLIGHT);
|
||||||
|
drawExcentricLine(ctx, angle, ChartProportions.Inner, ChartProportions.InnerMark);
|
||||||
|
drawExcentricLine(ctx, angle, ChartProportions.OuterEclyptic, ChartProportions.Outer);
|
||||||
|
ctx.setLineWidth(LINE_WIDTH_LIGHT);
|
||||||
|
writeExcentricInfo(ctx, TEXT_SIZE_LARGE, String.valueOf(house), angle + DEGREES_PER_HALF_SIGN, ChartProportions.HouseNumber);
|
||||||
|
house++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (epoch != null) {
|
||||||
|
//place planet information
|
||||||
|
ctx.setLineWidth(LINE_WIDTH_LIGHTER);
|
||||||
|
for (final Planet planet : Planet.values()) {
|
||||||
|
if (planetCheckBoxes.get(planet).getValue()) {
|
||||||
|
final ZodiacSign sign = ZodiacSign.valueOfAbbrevistion(epoch.getSign(planet));
|
||||||
|
final double degrees = epoch.getPreciseDegrees(planet) + sign.getEclipticLongitude();
|
||||||
|
final double angle = keepInRange(degrees + RIGHT_ANGLE - Double.valueOf(offset).intValue());
|
||||||
|
drawExcentricLine(ctx, angle, ChartProportions.PlanetMark, ChartProportions.InnerMark); //draw outer planet mark
|
||||||
|
writeExcentricInfo(ctx, TEXT_SIZE_LARGER, String.valueOf(planet.getUnicode()), angle, ChartProportions.PlanetSign);
|
||||||
|
writeExcentricInfo(ctx, TEXT_SIZE_LARGE, epoch.getDegrees(planet) + String.valueOf('\u00B0'), angle, ChartProportions.Degree);
|
||||||
|
writeExcentricInfo(ctx, TEXT_SIZE_LARGE, epoch.getMinutes(planet) + String.valueOf('\u2032'), angle, ChartProportions.Minute);
|
||||||
|
drawExcentricLine(ctx, angle, ChartProportions.Inner, ChartProportions.InnerLine); //draw inner planet mark
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
//mark midheaven
|
||||||
|
System.out.println("MC: " + ascendent.getMidheaven());
|
||||||
|
final double angle = keepInRange(ascendent.getMidheaven());
|
||||||
|
drawExcentricLine(ctx, angle, ChartProportions.PlanetMark, ChartProportions.InnerMark); //draw outer mark
|
||||||
|
writeExcentricInfo(ctx, 12, "MC", angle, ChartProportions.PlanetSign);
|
||||||
|
drawExcentricLine(ctx, angle, ChartProportions.Degree, ChartProportions.Inner); //draw inner mark
|
||||||
|
*/
|
||||||
|
|
||||||
|
//draw aspects
|
||||||
|
eventBus.fireEvent(new ResetAspectsEvent());
|
||||||
|
aspects.clear();
|
||||||
|
for (final Planet firstPlanet : Planet.values()) {
|
||||||
|
if (planetCheckBoxes.get(firstPlanet).getValue()) {
|
||||||
|
for (final Planet secondPlanet : Planet.values()) {
|
||||||
|
if (planetCheckBoxes.get(secondPlanet).getValue()) {
|
||||||
|
drawAspectLine(ctx, firstPlanet, secondPlanet, offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//write aspect labels
|
||||||
|
ctx.setFont("12pt Arial");
|
||||||
|
final Iterator<Entry<String, TextPosition>> it = aspects.entrySet().iterator();
|
||||||
|
while (it.hasNext()) {
|
||||||
|
final Entry<String, TextPosition> entry = it.next();
|
||||||
|
if (entry.getValue() != null) {
|
||||||
|
final TextPosition tp = entry.getValue();
|
||||||
|
ctx.setLineWidth(LINE_WIDTH_ALMOSTSUPERLIGHT);
|
||||||
|
ctx.fillRect(tp.getX() - 1D, tp.getY() - DEGREES_PER_HALF_SIGN - 3, DEGREES_PER_HALF_SIGN - 1, DEGREES_PER_HALF_SIGN);
|
||||||
|
ctx.strokeRect(tp.getX() - 1D, tp.getY() - DEGREES_PER_HALF_SIGN - 3, DEGREES_PER_HALF_SIGN - 1, DEGREES_PER_HALF_SIGN);
|
||||||
|
ctx.setLineWidth(1D);
|
||||||
|
ctx.strokeText(tp.getText(), tp.getX(), tp.getY());
|
||||||
|
it.remove(); // avoids a ConcurrentModificationException
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
eventBus.fireEvent(new SetStatusEvent("Ready."));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawAspectLine(final Context2d ctx, final Planet firstPlanet, final Planet secondPlanet, final double offset) {
|
||||||
|
if (firstPlanet.equals(secondPlanet)
|
||||||
|
|| aspects.containsKey(secondPlanet.name() + ":" + firstPlanet.name())) {
|
||||||
|
return; //aspect already placed
|
||||||
|
}
|
||||||
|
|
||||||
|
final ZodiacSign firstSign = ZodiacSign.valueOfAbbrevistion(epoch.getSign(firstPlanet));
|
||||||
|
final double firstDegrees = epoch.getPreciseDegrees(firstPlanet) + firstSign.getEclipticLongitude();
|
||||||
|
final double firstAngle = keepInRange(firstDegrees + RIGHT_ANGLE - Double.valueOf(offset).intValue());
|
||||||
|
final ZodiacSign secondSign = ZodiacSign.valueOfAbbrevistion(epoch.getSign(secondPlanet));
|
||||||
|
final double secondDegrees = epoch.getPreciseDegrees(secondPlanet) + secondSign.getEclipticLongitude();
|
||||||
|
final double secondAngle = keepInRange(secondDegrees + RIGHT_ANGLE - Double.valueOf(offset).intValue());
|
||||||
|
|
||||||
|
final double xFirst = getHcs()
|
||||||
|
- (Math.sin(Math.toRadians(firstAngle)) * ChartProportions.getRadius(getHcs(), ChartProportions.Inner));
|
||||||
|
final double yFirst = getHcs()
|
||||||
|
- (Math.cos(Math.toRadians(firstAngle)) * ChartProportions.getRadius(getHcs(), ChartProportions.Inner));
|
||||||
|
final double xSecond = getHcs()
|
||||||
|
- (Math.sin(Math.toRadians(secondAngle)) * ChartProportions.getRadius(getHcs(), ChartProportions.Inner));
|
||||||
|
final double ySecond = getHcs()
|
||||||
|
- (Math.cos(Math.toRadians(secondAngle)) * ChartProportions.getRadius(getHcs(), ChartProportions.Inner));
|
||||||
|
|
||||||
|
double difference = firstAngle - secondAngle;
|
||||||
|
if (difference < 0D) {
|
||||||
|
difference = difference * -1D;
|
||||||
|
}
|
||||||
|
AspectType isType = null;
|
||||||
|
for (final AspectType type : AspectType.values()) {
|
||||||
|
if (difference <= type.getAngle() + getAspectOrb(type)
|
||||||
|
&& difference >= type.getAngle() - getAspectOrb(type)) {
|
||||||
|
isType = type;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TextPosition tp = null;
|
||||||
|
if (isType != null) {
|
||||||
|
addAspect(isType);
|
||||||
|
if (aspectCheckBoxes.get(isType).getValue()) {
|
||||||
|
ctx.setLineWidth(2.0D); //Labeled aspects with type
|
||||||
|
drawLine(xFirst, yFirst, xSecond, ySecond);
|
||||||
|
final double x = ((xFirst + xSecond) / 2D) - 6D;
|
||||||
|
final double y = ((yFirst + ySecond) / 2D) + 6D;
|
||||||
|
tp = new TextPosition(String.valueOf(isType.getUnicode()), x, y);
|
||||||
|
} else {
|
||||||
|
ctx.setLineWidth(1.0D); //Unlabeled Aspects with type
|
||||||
|
drawLine(xFirst, yFirst, xSecond, ySecond);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ctx.setLineWidth(LINE_WIDTH_SUPERLIGHT); //Apsects without type
|
||||||
|
drawLine(xFirst, yFirst, xSecond, ySecond);
|
||||||
|
}
|
||||||
|
aspects.put(firstPlanet.name() + ":" + secondPlanet.name(), tp);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawExcentricLine(final Context2d ctx, final double angle, final ChartProportions from, final ChartProportions to) {
|
||||||
|
final double xFrom = getHcs() - (Math.sin(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), from));
|
||||||
|
final double yFrom = getHcs() - (Math.cos(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), from));
|
||||||
|
final double xTo = getHcs() - (Math.sin(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), to));
|
||||||
|
final double yTo = getHcs() - (Math.cos(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), to));
|
||||||
|
drawLine(xFrom, yFrom, xTo, yTo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writeExcentricInfo(final Context2d ctx, final int textSize, final String text, final double angle, final ChartProportions prop) {
|
||||||
|
ctx.setFont(textSize + "pt Arial");
|
||||||
|
final double xMinute = getHcs() - (Math.sin(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), prop)) - (textSize / 2);
|
||||||
|
final double yMinute = getHcs() - (Math.cos(Math.toRadians(angle)) * ChartProportions.getRadius(getHcs(), prop)) + (textSize / 2);
|
||||||
|
ctx.strokeText(text, xMinute, yMinute);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void markFiveDegrees(final Context2d ctx, final double offset) {
|
||||||
|
for (int angle = 0; angle < FULL_CIRCLE; angle = angle + 5) {
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.setFillStyle(CssColor.make(ChartColor.White.getHex()));
|
||||||
|
ctx.setStrokeStyle(CssColor.make(ChartColor.Black.getHex()));
|
||||||
|
final double start = Math.toRadians(angle + offset);
|
||||||
|
final double end = Math.toRadians(angle + offset + 5D);
|
||||||
|
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.InnerEclyptic), start, end, false);
|
||||||
|
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.OuterMark), end, start, true);
|
||||||
|
ctx.fill();
|
||||||
|
ctx.stroke();
|
||||||
|
ctx.closePath();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void markDegrees(final Context2d ctx, final double offset) {
|
||||||
|
for (int angle = 0; angle < FULL_CIRCLE; angle++) {
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.setFillStyle(CssColor.make(ChartColor.White.getHex()));
|
||||||
|
ctx.setStrokeStyle(CssColor.make(ChartColor.Black.getHex()));
|
||||||
|
final double start = Math.toRadians(angle + offset);
|
||||||
|
final double end = Math.toRadians(angle + offset + 1D);
|
||||||
|
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.OuterMark), start, end, false);
|
||||||
|
ctx.arc(getXCenter(), getYCenter(), ChartProportions.getRadius(getHcs(), ChartProportions.InnerMark), end, start, true);
|
||||||
|
ctx.fill();
|
||||||
|
ctx.stroke();
|
||||||
|
ctx.closePath();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* returns the half size of the chart
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private int getHcs() {
|
||||||
|
if (getXCenter() >= getYCenter()) {
|
||||||
|
return getXCenter();
|
||||||
|
} else {
|
||||||
|
return getYCenter();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getXCenter() {
|
||||||
|
return canvas.getOffsetWidth() / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getYCenter() {
|
||||||
|
return canvas.getOffsetHeight() / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private double keepInRange(final double angle) {
|
||||||
|
double result = angle;
|
||||||
|
while (result < 0D) {
|
||||||
|
result = result + FULL_CIRCLE;
|
||||||
|
}
|
||||||
|
result = result % FULL_CIRCLE;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawArc(final int x, final int y, final int r,
|
||||||
|
final double startAngle, final double endAngle, final boolean antiClock) {
|
||||||
|
canvas.getContext2d().beginPath();
|
||||||
|
final double start = Math.toRadians(startAngle - RIGHT_ANGLE);
|
||||||
|
final double end = Math.toRadians(endAngle - RIGHT_ANGLE);
|
||||||
|
canvas.getContext2d().arc(x, y, r, start, end, antiClock);
|
||||||
|
canvas.getContext2d().fill();
|
||||||
|
canvas.getContext2d().stroke();
|
||||||
|
canvas.getContext2d().closePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawAscendentLine(final int xCenter, final int yCenter, final int innerRadius,
|
||||||
|
final AscendentAndOffset asc) {
|
||||||
|
drawLine(xCenter - ChartProportions.getRadius(getHcs(), ChartProportions.Inner), yCenter,
|
||||||
|
xCenter - ChartProportions.getRadius(getHcs(), ChartProportions.InnerMark), yCenter);
|
||||||
|
final String text = "ASC " + asc.getAscendent().getUnicode() + " " + asc.getFormattedOffset();
|
||||||
|
canvas.getContext2d().strokeText(text, xCenter - ChartProportions.getRadius(getHcs(), ChartProportions.InnerMark) + 5D, yCenter - 5D);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawLine(final double startX, final double startY, final double endX, final double endY) {
|
||||||
|
canvas.getContext2d().beginPath();
|
||||||
|
canvas.getContext2d().moveTo(startX, startY);
|
||||||
|
canvas.getContext2d().lineTo(endX, endY);
|
||||||
|
canvas.getContext2d().closePath();
|
||||||
|
canvas.getContext2d().stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
private double getAspectOrb(final AspectType type) {
|
||||||
|
final ListBox box = aspectListboxes.get(type);
|
||||||
|
final int selection = box.getSelectedIndex();
|
||||||
|
return Double.valueOf(box.getItemText(selection));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addAspect(final AspectType aspectType) {
|
||||||
|
final Label label = aspectLabels.get(aspectType);
|
||||||
|
int counter = Integer.parseInt(label.getText());
|
||||||
|
counter++;
|
||||||
|
label.setText(String.valueOf(counter));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void changeHouseSystem(final HouseType houseType) {
|
||||||
|
this.houseType = houseType;
|
||||||
|
generateChart(ascendent, epoch, houseType);
|
||||||
|
}
|
||||||
|
}
|
||||||
+259
@@ -0,0 +1,259 @@
|
|||||||
|
package astrochart.client.widgets;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import astrochart.client.event.DateUpdatedEvent;
|
||||||
|
import astrochart.client.util.Constants;
|
||||||
|
import astrochart.client.util.DateTimeUtil;
|
||||||
|
import astrochart.shared.enums.time.Month;
|
||||||
|
import astrochart.shared.enums.time.TimeZone;
|
||||||
|
import com.google.gwt.event.dom.client.ClickEvent;
|
||||||
|
import com.google.gwt.event.dom.client.ClickHandler;
|
||||||
|
import com.google.gwt.event.shared.HandlerManager;
|
||||||
|
import com.google.gwt.i18n.client.DateTimeFormat;
|
||||||
|
import com.google.gwt.user.client.DOM;
|
||||||
|
import com.google.gwt.user.client.ui.Button;
|
||||||
|
import com.google.gwt.user.client.ui.Composite;
|
||||||
|
import com.google.gwt.user.client.ui.FlexTable;
|
||||||
|
import com.google.gwt.user.client.ui.Label;
|
||||||
|
import com.google.gwt.user.client.ui.ListBox;
|
||||||
|
import com.google.gwt.user.client.ui.TextBox;
|
||||||
|
|
||||||
|
public class TimeEntry extends Composite {
|
||||||
|
private static final int HIGHER_BOUNDARY = 2100;
|
||||||
|
private static final int LOWER_BOUNDARY = 1900;
|
||||||
|
private final HandlerManager eventBus;
|
||||||
|
private final DateTimeUtil dateTimeUtil;
|
||||||
|
private final FlexTable flex = new FlexTable();
|
||||||
|
private final TextBox yearTextBox = new TextBox();
|
||||||
|
private final ListBox monthListBox = new ListBox();
|
||||||
|
private final TextBox dayTextBox = new TextBox();
|
||||||
|
private final TextBox hoursTextBox = new TextBox();
|
||||||
|
private final TextBox minutesTextBox = new TextBox();
|
||||||
|
private final TextBox secondsTextBox = new TextBox();
|
||||||
|
private final ListBox timeZoneListBox = new ListBox();
|
||||||
|
private final Button updateButton = new Button("Enter");
|
||||||
|
private final Label statusLabel = new Label(String.valueOf('\u00A0')); // NBSP
|
||||||
|
private final DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy.MM.dd HH:mm:ss");
|
||||||
|
private int clientOffset;
|
||||||
|
private Date localDate; // local date of the client, not the ListBox
|
||||||
|
|
||||||
|
private enum Column {
|
||||||
|
Year(0),
|
||||||
|
Month(1),
|
||||||
|
Day(2),
|
||||||
|
Hours(3),
|
||||||
|
Minutes(4),
|
||||||
|
Seconds(5),
|
||||||
|
Timezone(6),
|
||||||
|
Action(7);
|
||||||
|
|
||||||
|
private int number;
|
||||||
|
|
||||||
|
Column(final int number) {
|
||||||
|
this.number = number;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getNumber() {
|
||||||
|
return number;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public TimeEntry(final HandlerManager eventBus, final DateTimeUtil dateTimeUtil) {
|
||||||
|
this.eventBus = eventBus;
|
||||||
|
this.dateTimeUtil = dateTimeUtil;
|
||||||
|
localDate = new Date();
|
||||||
|
|
||||||
|
for (final Column column : Column.values()) {
|
||||||
|
flex.setText(0, column.getNumber(), column.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
yearTextBox.setWidth("50px");
|
||||||
|
flex.setWidget(1, Column.Year.getNumber(), yearTextBox);
|
||||||
|
for (final Month month : Month.values()) {
|
||||||
|
monthListBox.addItem(month.name());
|
||||||
|
}
|
||||||
|
flex.setWidget(1, Column.Month.getNumber(), monthListBox);
|
||||||
|
dayTextBox.setWidth("50px");
|
||||||
|
flex.setWidget(1, Column.Day.getNumber(), dayTextBox);
|
||||||
|
|
||||||
|
hoursTextBox.setWidth("50px");
|
||||||
|
flex.setWidget(1, Column.Hours.getNumber(), hoursTextBox);
|
||||||
|
minutesTextBox.setWidth("50px");
|
||||||
|
flex.setWidget(1, Column.Minutes.getNumber(), minutesTextBox);
|
||||||
|
secondsTextBox.setWidth("50px");
|
||||||
|
flex.setWidget(1, Column.Seconds.getNumber(), secondsTextBox);
|
||||||
|
for (final TimeZone zone : TimeZone.values()) {
|
||||||
|
timeZoneListBox.addItem(zone.getName());
|
||||||
|
}
|
||||||
|
flex.setWidget(1, Column.Timezone.getNumber(), timeZoneListBox);
|
||||||
|
updateButton.addClickHandler(new ClickHandler() {
|
||||||
|
@Override
|
||||||
|
public void onClick(final ClickEvent event) {
|
||||||
|
updateDate();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
flex.setWidget(1, Column.Action.getNumber(), updateButton);
|
||||||
|
|
||||||
|
flex.setWidget(2, 0, statusLabel);
|
||||||
|
flex.getFlexCellFormatter().setColSpan(2, 0, Column.values().length + 1);
|
||||||
|
|
||||||
|
updateValues();
|
||||||
|
updateDate();
|
||||||
|
|
||||||
|
initWidget(flex);
|
||||||
|
setStyleName("time-entry");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateValues() {
|
||||||
|
yearTextBox.setText(String.valueOf(dateTimeUtil.getYear(localDate)));
|
||||||
|
int monthListIndex = 0;
|
||||||
|
for (final Month month : Month.values()) {
|
||||||
|
if (dateTimeUtil.getMonth(localDate) == month.getNumber()) {
|
||||||
|
monthListBox.setSelectedIndex(monthListIndex);
|
||||||
|
}
|
||||||
|
monthListIndex++;
|
||||||
|
}
|
||||||
|
dayTextBox.setText(String.valueOf(dateTimeUtil.getDay(localDate)));
|
||||||
|
hoursTextBox.setText(String.valueOf(dateTimeUtil.getHours(localDate)));
|
||||||
|
minutesTextBox.setText(String.valueOf(dateTimeUtil.getMinutes(localDate)));
|
||||||
|
secondsTextBox.setText(String.valueOf(dateTimeUtil.getSeconds(localDate)));
|
||||||
|
final double timeZoneOffset = DOM.getElementById("timeZone").getPropertyDouble("value");
|
||||||
|
int zoneListIndex = 0;
|
||||||
|
for (final TimeZone zone : TimeZone.values()) {
|
||||||
|
if (Double.valueOf(timeZoneOffset * Constants.SECONDS_PER_MINUTE).intValue() == zone.getUtcOffsetMinutes()) {
|
||||||
|
clientOffset = Double.valueOf(timeZoneOffset * Constants.SECONDS_PER_MINUTE).intValue();
|
||||||
|
timeZoneListBox.setSelectedIndex(zoneListIndex);
|
||||||
|
}
|
||||||
|
zoneListIndex++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateDate() {
|
||||||
|
// "yyyy.MM.dd HH:mm:ss"
|
||||||
|
statusLabel.setText(String.valueOf('\u00A0'));
|
||||||
|
try {
|
||||||
|
final StringBuilder dateString = new StringBuilder();
|
||||||
|
validateYear();
|
||||||
|
dateString.append(yearTextBox.getText());
|
||||||
|
dateString.append(".");
|
||||||
|
final Month month = Month.valueOf(monthListBox.getValue(monthListBox.getSelectedIndex()));
|
||||||
|
dateString.append(formatToTwoDigits(String.valueOf(month.getNumber())));
|
||||||
|
dateString.append(".");
|
||||||
|
validateDay();
|
||||||
|
dateString.append(formatToTwoDigits(dayTextBox.getText()));
|
||||||
|
dateString.append(" ");
|
||||||
|
validateHours();
|
||||||
|
dateString.append(formatToTwoDigits(hoursTextBox.getText()));
|
||||||
|
dateString.append(":");
|
||||||
|
validateMinutes();
|
||||||
|
dateString.append(formatToTwoDigits(minutesTextBox.getText()));
|
||||||
|
dateString.append(":");
|
||||||
|
validateSeconds();
|
||||||
|
dateString.append(formatToTwoDigits(secondsTextBox.getText()));
|
||||||
|
final Date tempDate = dateTimeFormat.parse(dateString.toString());
|
||||||
|
final TimeZone timeZone = TimeZone.getTimeZoneForName(timeZoneListBox.getValue(timeZoneListBox.getSelectedIndex()));
|
||||||
|
// final com.google.gwt.i18n.client.TimeZone tzUtc =
|
||||||
|
// com.google.gwt.i18n.client.TimeZone.createTimeZone(0);
|
||||||
|
// final com.google.gwt.i18n.client.TimeZone tz =
|
||||||
|
// com.google.gwt.i18n.client.TimeZone.createTimeZone(timeZone.getUtcOffsetMinutes());
|
||||||
|
final Date boxDate = new Date(tempDate.getTime() - (timeZone.getUtcOffsetMinutes() * Constants.MILLISECONDS_PER_MINUTE));
|
||||||
|
localDate = new Date(boxDate.getTime() + (clientOffset * Constants.MILLISECONDS_PER_MINUTE));
|
||||||
|
final StringBuilder status = new StringBuilder();
|
||||||
|
status.append(dateTimeFormat.format(tempDate));
|
||||||
|
status.append(" ");
|
||||||
|
status.append(timeZone.getName());
|
||||||
|
if (timeZone.getUtcOffsetMinutes() != clientOffset) {
|
||||||
|
status.append(" --> ");
|
||||||
|
status.append(dateTimeFormat.format(localDate));
|
||||||
|
status.append(" UTC+");
|
||||||
|
status.append(clientOffset / Constants.SECONDS_PER_MINUTE);
|
||||||
|
}
|
||||||
|
if (timeZone.getUtcOffsetMinutes() != 0) {
|
||||||
|
status.append(" --> ");
|
||||||
|
status.append(dateTimeFormat.format(boxDate));
|
||||||
|
status.append(" UTC ");
|
||||||
|
}
|
||||||
|
statusLabel.setText(status.toString());
|
||||||
|
eventBus.fireEvent(new DateUpdatedEvent(localDate));
|
||||||
|
} catch (final IllegalArgumentException iae) {
|
||||||
|
statusLabel.setText(iae.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateSeconds() {
|
||||||
|
final int minutes = Integer.valueOf(secondsTextBox.getText());
|
||||||
|
if (minutes < 0 || minutes > Constants.MINUTES_PER_HOUR - 1) {
|
||||||
|
secondsTextBox.setFocus(true);
|
||||||
|
throw new IllegalArgumentException("Seconds are out of range.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateMinutes() {
|
||||||
|
final int minutes = Integer.valueOf(minutesTextBox.getText());
|
||||||
|
if (minutes < 0 || minutes > Constants.MINUTES_PER_HOUR - 1) {
|
||||||
|
minutesTextBox.setFocus(true);
|
||||||
|
throw new IllegalArgumentException("Minutes are out of range.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateHours() {
|
||||||
|
final int hours = Integer.valueOf(hoursTextBox.getText());
|
||||||
|
if (hours < 0 || hours > Constants.HOURS_PER_DAY - 1) {
|
||||||
|
hoursTextBox.setFocus(true);
|
||||||
|
throw new IllegalArgumentException("Hour is out of range.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateYear() {
|
||||||
|
final int year = Integer.valueOf(yearTextBox.getText());
|
||||||
|
if (year < LOWER_BOUNDARY || year > HIGHER_BOUNDARY) {
|
||||||
|
yearTextBox.setFocus(true);
|
||||||
|
throw new IllegalArgumentException("Year is out of range.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateDay() {
|
||||||
|
final int day = Integer.valueOf(dayTextBox.getText());
|
||||||
|
final Month month = Month.valueOf(monthListBox.getValue(monthListBox.getSelectedIndex()));
|
||||||
|
if (day < 1 || day > month.getDays()) {
|
||||||
|
final int year = Integer.valueOf(yearTextBox.getText());
|
||||||
|
if (day == month.getDays() + 1 && DateTimeUtil.isLeapYear(year) && month.equals(Month.February)) {
|
||||||
|
dayTextBox.setFocus(true);
|
||||||
|
throw new IllegalArgumentException("Day is out of range. (" + year + " is a leap year).");
|
||||||
|
} else {
|
||||||
|
dayTextBox.setFocus(true);
|
||||||
|
throw new IllegalArgumentException("Day is out of range.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String formatToTwoDigits(final String in) {
|
||||||
|
if (in.length() == 1) {
|
||||||
|
return "0" + in;
|
||||||
|
} else {
|
||||||
|
return in;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final Date getLocalDate() {
|
||||||
|
return localDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getClientTimezone() {
|
||||||
|
return " UTC+" + (clientOffset / Constants.MINUTES_PER_HOUR);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void updateDate(final Date newUtcDate) {
|
||||||
|
localDate = newUtcDate;
|
||||||
|
updateValues();
|
||||||
|
int zoneListIndex = 0;
|
||||||
|
for (final TimeZone zone : TimeZone.values()) {
|
||||||
|
if (zone.getUtcOffsetMinutes() == 0) {
|
||||||
|
timeZoneListBox.setSelectedIndex(zoneListIndex);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
zoneListIndex++;
|
||||||
|
}
|
||||||
|
updateDate();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package astrochart.server.service;
|
||||||
|
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import javax.jdo.JDOHelper;
|
||||||
|
import javax.jdo.PersistenceManager;
|
||||||
|
import javax.jdo.PersistenceManagerFactory;
|
||||||
|
import astrochart.client.service.AdminService;
|
||||||
|
import astrochart.shared.data.Epoch;
|
||||||
|
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
|
||||||
|
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
public class AdminServiceImpl extends RemoteServiceServlet implements AdminService {
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private static final Logger LOG = Logger.getLogger(AdminServiceImpl.class.getName());
|
||||||
|
private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("transactions-optional");
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final void saveEpoch(final Epoch epoch) {
|
||||||
|
System.out.println(epoch);
|
||||||
|
final PersistenceManager pm = PMF.getPersistenceManager();
|
||||||
|
try {
|
||||||
|
pm.makePersistent(epoch);
|
||||||
|
// LOG.log(Level.INFO, "Epoch stored: " + epoch);
|
||||||
|
} finally {
|
||||||
|
pm.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+190
@@ -0,0 +1,190 @@
|
|||||||
|
package astrochart.server.service;
|
||||||
|
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import net.sf.jsr107cache.Cache;
|
||||||
|
import net.sf.jsr107cache.CacheException;
|
||||||
|
import net.sf.jsr107cache.CacheManager;
|
||||||
|
import astrochart.client.service.EpochService;
|
||||||
|
import astrochart.client.util.Constants;
|
||||||
|
import astrochart.shared.data.Epoch;
|
||||||
|
import astrochart.shared.enums.Planet;
|
||||||
|
import astrochart.shared.exceptions.EpochNotFoundException;
|
||||||
|
import com.google.appengine.api.datastore.DatastoreService;
|
||||||
|
import com.google.appengine.api.datastore.DatastoreServiceFactory;
|
||||||
|
import com.google.appengine.api.datastore.Entity;
|
||||||
|
import com.google.appengine.api.datastore.FetchOptions;
|
||||||
|
import com.google.appengine.api.datastore.PreparedQuery;
|
||||||
|
import com.google.appengine.api.datastore.Query;
|
||||||
|
import com.google.appengine.api.datastore.Query.SortDirection;
|
||||||
|
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
|
||||||
|
|
||||||
|
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
public class EpochServiceImpl extends RemoteServiceServlet implements EpochService {
|
||||||
|
private static final int TOLERANCE_FACTOR = 10;
|
||||||
|
private static final int TOLERANCE_DIVISOR = 8;
|
||||||
|
private static final int MINUTES_PER_HOUR = 60;
|
||||||
|
private static final int SECONDS_PER_MINUTE = 60;
|
||||||
|
private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private static final Logger LOG = Logger.getLogger(EpochServiceImpl.class.getName());
|
||||||
|
private final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final Epoch readEpoch(final Date date) throws EpochNotFoundException {
|
||||||
|
final Date low = new Date(date.getTime() - ((Constants.MILLISECONDS_PER_DAY * TOLERANCE_FACTOR) / TOLERANCE_DIVISOR));
|
||||||
|
final Date med = new Date(date.getTime());
|
||||||
|
final Date high = new Date(date.getTime() + ((Constants.MILLISECONDS_PER_DAY * TOLERANCE_FACTOR) / TOLERANCE_DIVISOR));
|
||||||
|
|
||||||
|
Epoch first = null;
|
||||||
|
Epoch second = null;
|
||||||
|
final Epoch result = new Epoch();
|
||||||
|
|
||||||
|
// try to get Epochs from cache
|
||||||
|
Cache cache = null;
|
||||||
|
String firstCacheKey = sdf.format(low);
|
||||||
|
String medCacheKey = sdf.format(med);
|
||||||
|
String secondCacheKey = sdf.format(high);
|
||||||
|
try {
|
||||||
|
cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
|
||||||
|
first = (Epoch) cache.get(firstCacheKey);
|
||||||
|
if (first == null) {
|
||||||
|
first = (Epoch) cache.get(medCacheKey);
|
||||||
|
} else {
|
||||||
|
second = (Epoch) cache.get(medCacheKey);
|
||||||
|
}
|
||||||
|
if (second == null) {
|
||||||
|
second = (Epoch) cache.get(secondCacheKey);
|
||||||
|
}
|
||||||
|
} catch (final CacheException e) {
|
||||||
|
assert true; // ignore
|
||||||
|
}
|
||||||
|
|
||||||
|
if (first == null || second == null) {
|
||||||
|
first = new Epoch();
|
||||||
|
second = new Epoch();
|
||||||
|
final Query q = new Query("Epoch");
|
||||||
|
q.addFilter("sidDate", Query.FilterOperator.GREATER_THAN_OR_EQUAL, low);
|
||||||
|
q.addFilter("sidDate", Query.FilterOperator.LESS_THAN_OR_EQUAL, high);
|
||||||
|
q.addSort("sidDate", SortDirection.ASCENDING);
|
||||||
|
final PreparedQuery pq = datastore.prepare(q);
|
||||||
|
final List<Entity> entities = pq.asList(FetchOptions.Builder.withLimit(2));
|
||||||
|
if (entities.size() < 2) {
|
||||||
|
throw new EpochNotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
final Entity firstEntity = entities.get(0);
|
||||||
|
final Entity secondEntity = entities.get(1);
|
||||||
|
|
||||||
|
first.setSidDate((Date) firstEntity.getProperty("sidDate"));
|
||||||
|
second.setSidDate((Date) secondEntity.getProperty("sidDate"));
|
||||||
|
first.setDay((String) firstEntity.getProperty("day"));
|
||||||
|
second.setDay((String) secondEntity.getProperty("day"));
|
||||||
|
for (final Planet planet : Planet.values()) {
|
||||||
|
first.setPosition(planet, (String) firstEntity.getProperty(planet.name().toLowerCase()));
|
||||||
|
second.setPosition(planet, (String) secondEntity.getProperty(planet.name().toLowerCase()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// write epochs to cache
|
||||||
|
if (cache != null) {
|
||||||
|
cache.put(sdf.format(first.getSidDate()), first);
|
||||||
|
cache.put(sdf.format(second.getSidDate()), second);
|
||||||
|
}
|
||||||
|
|
||||||
|
final long firstTs = first.getSidDate().getTime();
|
||||||
|
final long originalTs = date.getTime();
|
||||||
|
final long secondTs = second.getSidDate().getTime();
|
||||||
|
|
||||||
|
final long totalDifference = secondTs - firstTs; // --> 100%
|
||||||
|
final long firstDifference = originalTs - firstTs;
|
||||||
|
final long secondDifference = secondTs - originalTs;
|
||||||
|
|
||||||
|
result.setSidDate(date);
|
||||||
|
if (firstDifference < secondDifference) {
|
||||||
|
// first result is closer to original date
|
||||||
|
result.setDay(first.getDay());
|
||||||
|
} else {
|
||||||
|
result.setDay(second.getDay());
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final Planet planet : Planet.values()) {
|
||||||
|
if (!planet.equals(Planet.SouthNode)) {
|
||||||
|
// final String firstToken = (String)
|
||||||
|
// firstEntity.getProperty(planet.name().toLowerCase());
|
||||||
|
// final String secondToken = (String)
|
||||||
|
// secondEntity.getProperty(planet.name().toLowerCase());
|
||||||
|
final String firstToken = first.getPosition(planet);
|
||||||
|
final String secondToken = second.getPosition(planet);
|
||||||
|
|
||||||
|
final int firstDegrees = Integer.parseInt(firstToken.substring(0, 2));
|
||||||
|
final int secondDegrees = Integer.parseInt(secondToken.substring(0, 2));
|
||||||
|
final String firstSign = firstToken.substring(2, 4);
|
||||||
|
final String secondSign = secondToken.substring(2, 4);
|
||||||
|
final int firstMinutes = Integer.parseInt(firstToken.substring(4, 6));
|
||||||
|
final int secondMinutes = Integer.parseInt(secondToken.substring(4, 6));
|
||||||
|
|
||||||
|
int averageDegrees = 0;
|
||||||
|
String tokenSign = "";
|
||||||
|
int averageMinutes = 0;
|
||||||
|
long averageTotalMinutes = 0;
|
||||||
|
if (firstSign.equals(secondSign)) {
|
||||||
|
tokenSign = firstSign;
|
||||||
|
//Note: firstDifference and secondDifference are switched in order to weight
|
||||||
|
//the nearer epoch with the smaller difference more than the further
|
||||||
|
averageTotalMinutes = (
|
||||||
|
((firstMinutes + (firstDegrees * MINUTES_PER_HOUR)) * secondDifference)
|
||||||
|
+ ((secondMinutes + (secondDegrees * SECONDS_PER_MINUTE)) * firstDifference)
|
||||||
|
) / totalDifference;
|
||||||
|
} else {
|
||||||
|
if (firstDifference < secondDifference) {
|
||||||
|
//high degrees
|
||||||
|
tokenSign = firstSign;
|
||||||
|
averageTotalMinutes = (
|
||||||
|
((firstMinutes + (firstDegrees * MINUTES_PER_HOUR)) * secondDifference)
|
||||||
|
+ ((secondMinutes + ((secondDegrees + (SECONDS_PER_MINUTE / 2)) * SECONDS_PER_MINUTE)) * firstDifference)
|
||||||
|
) / totalDifference;
|
||||||
|
} else {
|
||||||
|
//low degrees
|
||||||
|
tokenSign = secondSign;
|
||||||
|
averageTotalMinutes = (
|
||||||
|
((firstMinutes + ((firstDegrees + (MINUTES_PER_HOUR / 2)) * MINUTES_PER_HOUR)) * secondDifference)
|
||||||
|
+ ((secondMinutes + (secondDegrees * SECONDS_PER_MINUTE)) * firstDifference)
|
||||||
|
) / totalDifference;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
averageDegrees = (int) averageTotalMinutes / MINUTES_PER_HOUR;
|
||||||
|
if (averageDegrees >= (MINUTES_PER_HOUR / 2)) {
|
||||||
|
averageDegrees = averageDegrees - (MINUTES_PER_HOUR / 2);
|
||||||
|
}
|
||||||
|
averageMinutes = (int) averageTotalMinutes % MINUTES_PER_HOUR;
|
||||||
|
final String tokenDegrees = addZeroIfNeeded(String.valueOf(averageDegrees));
|
||||||
|
final String tokenMinutes = addZeroIfNeeded(String.valueOf(averageMinutes));
|
||||||
|
result.setPosition(planet, tokenDegrees + tokenSign + tokenMinutes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
|
||||||
|
String firstPercent = (firstDifference * 100 / totalDifference) + "%";
|
||||||
|
String secondPercent = (secondDifference * 100 / totalDifference) + "%";
|
||||||
|
System.out.println("First: " + sdf.format(first.getSidDate()) + " " + first.toString() + " " + firstPercent);
|
||||||
|
System.out.println("Result: " + sdf.format(result.getSidDate()) + " " + result.toString() + "<");
|
||||||
|
System.out.println("Second: " + sdf.format(second.getSidDate()) + " " + second.toString() + " " + secondPercent);
|
||||||
|
*/
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String addZeroIfNeeded(final String value) {
|
||||||
|
if (value.length() < 2) {
|
||||||
|
return "0" + value;
|
||||||
|
} else {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package astrochart.server.service;
|
||||||
|
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import astrochart.client.service.GeocodeService;
|
||||||
|
import astrochart.shared.data.GeocodeData;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
|
||||||
|
|
||||||
|
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
public class GeocodeServiceImpl extends RemoteServiceServlet implements GeocodeService {
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private static final Logger LOG = Logger.getLogger(GeocodeServiceImpl.class.getName());
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final GeocodeData getGeocodeData(final String cityName) {
|
||||||
|
final String encodedCityName = encode(cityName);
|
||||||
|
final String geocodeUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" + encodedCityName + "&sensor=false";
|
||||||
|
final GeocodeData result = makeGeocodeRequest(geocodeUrl);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final GeocodeData getGeocodeDataForIp() {
|
||||||
|
final String ipString = getThreadLocalRequest().getRemoteAddr();
|
||||||
|
final String ipGeocodeUrl = "http://freegeoip.net/json/" + ipString;
|
||||||
|
final GeocodeData result = makeIpGeocodeRequest(ipGeocodeUrl);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GeocodeData makeGeocodeRequest(final String geocodeUrl) {
|
||||||
|
try {
|
||||||
|
final URL url = new URL(geocodeUrl);
|
||||||
|
final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
|
||||||
|
final JsonParser parser = new JsonParser();
|
||||||
|
final JsonElement element = parser.parse(reader);
|
||||||
|
reader.close();
|
||||||
|
final JsonObject rootObject = element.getAsJsonObject();
|
||||||
|
return parseJsonGeocodeResult(rootObject);
|
||||||
|
} catch (final MalformedURLException e) {
|
||||||
|
return createErrorGeocode();
|
||||||
|
} catch (final IOException e) {
|
||||||
|
return createErrorGeocode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private GeocodeData createErrorGeocode() {
|
||||||
|
final GeocodeData result = new GeocodeData();
|
||||||
|
result.setCityName("Error finding location.");
|
||||||
|
result.setLatitude(0.0D);
|
||||||
|
result.setLongitude(0.0D);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GeocodeData parseJsonGeocodeResult(final JsonObject rootObject) {
|
||||||
|
final GeocodeData result = new GeocodeData();
|
||||||
|
final JsonArray array = rootObject.getAsJsonArray("results");
|
||||||
|
if (array.size() > 0) {
|
||||||
|
final JsonObject firstResult = array.get(0).getAsJsonObject();
|
||||||
|
|
||||||
|
final JsonElement address = firstResult.get("formatted_address");
|
||||||
|
result.setCityName(address.getAsString());
|
||||||
|
|
||||||
|
final JsonElement geometryElement = firstResult.get("geometry");
|
||||||
|
final JsonElement locationElement = geometryElement.getAsJsonObject().get("location");
|
||||||
|
|
||||||
|
final JsonElement latElement = locationElement.getAsJsonObject().get("lat");
|
||||||
|
result.setLatitude(latElement.getAsDouble());
|
||||||
|
final JsonElement lngElement = locationElement.getAsJsonObject().get("lng");
|
||||||
|
result.setLongitude(lngElement.getAsDouble());
|
||||||
|
} else {
|
||||||
|
result.setCityName("Location not found.");
|
||||||
|
result.setLatitude(0.0D);
|
||||||
|
result.setLongitude(0.0D);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GeocodeData makeIpGeocodeRequest(final String ipGeocodeUrl) {
|
||||||
|
try {
|
||||||
|
final URL url = new URL(ipGeocodeUrl);
|
||||||
|
final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
|
||||||
|
final JsonParser parser = new JsonParser();
|
||||||
|
final JsonElement element = parser.parse(reader);
|
||||||
|
reader.close();
|
||||||
|
final JsonObject rootObject = element.getAsJsonObject();
|
||||||
|
return parseJsonIpGeocodeResult(rootObject);
|
||||||
|
} catch (final MalformedURLException e) {
|
||||||
|
return createErrorGeocode();
|
||||||
|
} catch (final IOException e) {
|
||||||
|
return createErrorGeocode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private GeocodeData parseJsonIpGeocodeResult(final JsonObject rootObject) {
|
||||||
|
final GeocodeData result = new GeocodeData();
|
||||||
|
final JsonElement cityElement = rootObject.getAsJsonObject().get("city");
|
||||||
|
result.setCityName(cityElement.getAsString());
|
||||||
|
final JsonElement latElement = rootObject.getAsJsonObject().get("latitude");
|
||||||
|
result.setLatitude(latElement.getAsDouble());
|
||||||
|
final JsonElement lngElement = rootObject.getAsJsonObject().get("longitude");
|
||||||
|
result.setLongitude(lngElement.getAsDouble());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String encode(final String in) {
|
||||||
|
return in.replaceAll(" ", "%20");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package astrochart.shared;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import astrochart.shared.enums.RashimanaGroup;
|
||||||
|
import astrochart.shared.enums.ZodiacSign;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lengths of the equinoctial shadow of a Shanku of 12 units at different
|
||||||
|
* latitudes Values from: http://www.vedicastro.com/astronomy6.asp
|
||||||
|
*/
|
||||||
|
public class EquinocticalShaddowLengths {
|
||||||
|
private static final double CHARAKHANDA_MULTIPLICATOR_1 = 10D;
|
||||||
|
private static final double CHARAKHANDA_MULTIPLICATOR_2 = 8D;
|
||||||
|
private static final double CHARAKHANDA_MULTIPLICATOR_3 = 3.3333333333D;
|
||||||
|
private static final int LATITUDES = 60;
|
||||||
|
private final Map<Integer, Double> shaddowLengths = new HashMap<Integer, Double>(LATITUDES);
|
||||||
|
|
||||||
|
private enum ShaddowLength {
|
||||||
|
_01(0.21D), _02(0.42D), _03(0.63D), _04(0.84D), _05(1.05D), _06(1.26D), _07(1.47D), _08(1.69D), _09(1.90D), _10(2.11D),
|
||||||
|
_11(2.33D), _12(2.55D), _13(2.70D), _14(2.99D), _15(3.21D), _16(3.44D), _17(3.66D), _18(3.90D), _19(4.13D), _20(4.37D),
|
||||||
|
_21(4.60D), _22(4.85D), _23(5.09D), _24(5.34D), _25(5.59D), _26(5.85D), _27(6.11D), _28(6.38D), _29(6.65D), _30(6.93D),
|
||||||
|
_31(7.21D), _32(7.50D), _33(7.79D), _34(8.09D), _35(8.40D), _36(8.71D), _37(9.04D), _38(9.37D), _39(9.72D), _40(10.06D),
|
||||||
|
_41(10.43D), _42(10.80D), _43(11.19D), _44(11.58D), _45(12.00D), _46(12.42D), _47(12.87D), _48(13.33D), _49(13.80D), _50(14.30D),
|
||||||
|
_51(14.82D), _52(15.35D), _53(15.92D), _54(16.52D), _55(17.13D), _56(17.79D), _57(18.46D), _58(19.20D), _59(19.97D), _60(20.78D);
|
||||||
|
|
||||||
|
private final double length;
|
||||||
|
|
||||||
|
ShaddowLength(final double length) {
|
||||||
|
this.length = length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getLength() {
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public EquinocticalShaddowLengths() {
|
||||||
|
for (final ShaddowLength sl : ShaddowLength.values()) {
|
||||||
|
shaddowLengths.put(Integer.valueOf(sl.name().substring(1, 3)), Double.valueOf(sl.getLength()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getShaddowLength(final int latitude) {
|
||||||
|
return shaddowLengths.get(Integer.valueOf(latitude)).doubleValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int calculateCharakhandas(final ZodiacSign sign, final int latitude) {
|
||||||
|
return calculatePalas(sign, latitude) * 6; // in asus
|
||||||
|
}
|
||||||
|
|
||||||
|
private int calculatePalas(final ZodiacSign sign, final int latitude) {
|
||||||
|
final double shaddowLenght = getShaddowLength(latitude);
|
||||||
|
if (RashimanaGroup.I.equals(sign.getRashimanaGroup())) {
|
||||||
|
return (int) (shaddowLenght * CHARAKHANDA_MULTIPLICATOR_1);
|
||||||
|
} else if (RashimanaGroup.II.equals(sign.getRashimanaGroup())) {
|
||||||
|
return (int) (shaddowLenght * CHARAKHANDA_MULTIPLICATOR_2);
|
||||||
|
} else if (RashimanaGroup.III.equals(sign.getRashimanaGroup())) {
|
||||||
|
return (int) (shaddowLenght * CHARAKHANDA_MULTIPLICATOR_3);
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Sign " + sign + " has illegal rashomana group: " + sign.getRashimanaGroup());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Executable
+201
@@ -0,0 +1,201 @@
|
|||||||
|
package astrochart.shared.data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.Date;
|
||||||
|
import javax.jdo.annotations.IdentityType;
|
||||||
|
import javax.jdo.annotations.PersistenceCapable;
|
||||||
|
import javax.jdo.annotations.Persistent;
|
||||||
|
import javax.jdo.annotations.PrimaryKey;
|
||||||
|
import com.google.gwt.i18n.client.NumberFormat;
|
||||||
|
import astrochart.shared.enums.Planet;
|
||||||
|
import astrochart.shared.enums.ZodiacSign;
|
||||||
|
|
||||||
|
@PersistenceCapable(identityType = IdentityType.APPLICATION)
|
||||||
|
public class Epoch implements Serializable {
|
||||||
|
private static final long serialVersionUID = 546722654874032959L;
|
||||||
|
private static final double MINUTES_PER_DEGREE = 60D;
|
||||||
|
private static final double PRECISION = 100D;
|
||||||
|
|
||||||
|
@PrimaryKey
|
||||||
|
@Persistent
|
||||||
|
private Long key; // Timestamp of sidereal Date
|
||||||
|
|
||||||
|
@Persistent
|
||||||
|
private Date sidDate;
|
||||||
|
@Persistent
|
||||||
|
private String day;
|
||||||
|
|
||||||
|
@Persistent
|
||||||
|
private String sun;
|
||||||
|
@Persistent
|
||||||
|
private String moon;
|
||||||
|
@Persistent
|
||||||
|
private String mercury;
|
||||||
|
@Persistent
|
||||||
|
private String venus;
|
||||||
|
@Persistent
|
||||||
|
private String mars;
|
||||||
|
@Persistent
|
||||||
|
private String jupiter;
|
||||||
|
@Persistent
|
||||||
|
private String saturn;
|
||||||
|
@Persistent
|
||||||
|
private String uranus;
|
||||||
|
@Persistent
|
||||||
|
private String neptune;
|
||||||
|
@Persistent
|
||||||
|
private String pluto;
|
||||||
|
@Persistent
|
||||||
|
private String node;
|
||||||
|
|
||||||
|
public Epoch() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public final Long getKey() {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final Date getSidDate() {
|
||||||
|
return sidDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void setSidDate(final Date sidDate) {
|
||||||
|
this.sidDate = sidDate;
|
||||||
|
this.key = sidDate.getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getDay() {
|
||||||
|
return day;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void setDay(final String day) {
|
||||||
|
this.day = day;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void setPosition(final Planet planet, final String position) {
|
||||||
|
if (planet.equals(Planet.Sun)) {
|
||||||
|
sun = position;
|
||||||
|
} else if (planet.equals(Planet.Moon)) {
|
||||||
|
moon = position;
|
||||||
|
} else if (planet.equals(Planet.Mercury)) {
|
||||||
|
mercury = position;
|
||||||
|
} else if (planet.equals(Planet.Venus)) {
|
||||||
|
venus = position;
|
||||||
|
} else if (planet.equals(Planet.Mars)) {
|
||||||
|
mars = position;
|
||||||
|
} else if (planet.equals(Planet.Jupiter)) {
|
||||||
|
jupiter = position;
|
||||||
|
} else if (planet.equals(Planet.Saturn)) {
|
||||||
|
saturn = position;
|
||||||
|
} else if (planet.equals(Planet.Uranus)) {
|
||||||
|
uranus = position;
|
||||||
|
} else if (planet.equals(Planet.Neptune)) {
|
||||||
|
neptune = position;
|
||||||
|
} else if (planet.equals(Planet.Pluto)) {
|
||||||
|
pluto = position;
|
||||||
|
} else if (planet.equals(Planet.Node)) {
|
||||||
|
node = position;
|
||||||
|
} else if (planet.equals(Planet.SouthNode)) {
|
||||||
|
assert true; // ignore
|
||||||
|
//throw new IllegalArgumentException("Cannot set south node position.");
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Planet unknown.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getPosition(final Planet planet) {
|
||||||
|
if (planet.equals(Planet.Sun)) {
|
||||||
|
return sun;
|
||||||
|
} else if (planet.equals(Planet.Moon)) {
|
||||||
|
return moon;
|
||||||
|
} else if (planet.equals(Planet.Mercury)) {
|
||||||
|
return mercury;
|
||||||
|
} else if (planet.equals(Planet.Venus)) {
|
||||||
|
return venus;
|
||||||
|
} else if (planet.equals(Planet.Mars)) {
|
||||||
|
return mars;
|
||||||
|
} else if (planet.equals(Planet.Jupiter)) {
|
||||||
|
return jupiter;
|
||||||
|
} else if (planet.equals(Planet.Saturn)) {
|
||||||
|
return saturn;
|
||||||
|
} else if (planet.equals(Planet.Uranus)) {
|
||||||
|
return uranus;
|
||||||
|
} else if (planet.equals(Planet.Neptune)) {
|
||||||
|
return neptune;
|
||||||
|
} else if (planet.equals(Planet.Pluto)) {
|
||||||
|
return pluto;
|
||||||
|
} else if (planet.equals(Planet.Node)) {
|
||||||
|
return node;
|
||||||
|
} else if (planet.equals(Planet.SouthNode)) {
|
||||||
|
return determineSouthNodePosition();
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Planet unknown");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getDegrees(final Planet planet) {
|
||||||
|
return Integer.parseInt(getPosition(planet).substring(0, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getSign(final Planet planet) {
|
||||||
|
return getPosition(planet).substring(2, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getMinutes(final Planet planet) {
|
||||||
|
return Integer.parseInt(getPosition(planet).substring(4, 6));
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getPreciseDegrees(final Planet planet) {
|
||||||
|
return getDegrees(planet) + (((getMinutes(planet) * PRECISION) / MINUTES_PER_DEGREE) / PRECISION);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines and returns the position of the south node by evaluating the
|
||||||
|
* north node position.
|
||||||
|
*/
|
||||||
|
private String determineSouthNodePosition() {
|
||||||
|
final String northNode = getPosition(Planet.Node);
|
||||||
|
final String northSign = northNode.substring(2, 4);
|
||||||
|
final String sign = ZodiacSign.valueOfAbbrevistion(northSign).getDescendent();
|
||||||
|
final String southNode = northNode.substring(0, 2) + sign + northNode.substring(4, 6);
|
||||||
|
return southNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getPositionString(final Planet planet) {
|
||||||
|
final StringBuilder builder = new StringBuilder();
|
||||||
|
final ZodiacSign sign = ZodiacSign.valueOfAbbrevistion(getSign(planet));
|
||||||
|
builder.append(sign.getUnicode());
|
||||||
|
builder.append(" ");
|
||||||
|
builder.append(sign);
|
||||||
|
builder.append(" ");
|
||||||
|
final double degree = getPreciseDegrees(planet);
|
||||||
|
builder.append(NumberFormat.getFormat("0.000").format(degree));
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getPositionDegreeString(final Planet planet) {
|
||||||
|
final StringBuilder builder = new StringBuilder();
|
||||||
|
final ZodiacSign sign = ZodiacSign.valueOfAbbrevistion(getSign(planet));
|
||||||
|
builder.append(sign.getUnicode());
|
||||||
|
builder.append(" ");
|
||||||
|
builder.append(sign);
|
||||||
|
builder.append(" ");
|
||||||
|
builder.append(getDegrees(planet));
|
||||||
|
builder.append(String.valueOf('\u00B0'));
|
||||||
|
builder.append(" ");
|
||||||
|
builder.append(getMinutes(planet));
|
||||||
|
builder.append(String.valueOf('\u2032'));
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String toString() {
|
||||||
|
final StringBuilder builder = new StringBuilder();
|
||||||
|
for (final Planet planet : Planet.values()) {
|
||||||
|
builder.append(planet.name());
|
||||||
|
builder.append(":");
|
||||||
|
builder.append(getPosition(planet));
|
||||||
|
builder.append(" ");
|
||||||
|
}
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
package astrochart.shared.data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class GeocodeData implements Serializable {
|
||||||
|
private static final long serialVersionUID = 2353838294439322239L;
|
||||||
|
|
||||||
|
private double latitude;
|
||||||
|
private double longitude;
|
||||||
|
private String cityName;
|
||||||
|
|
||||||
|
public GeocodeData() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getLatitude() {
|
||||||
|
return latitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void setLatitude(final double latitude) {
|
||||||
|
this.latitude = latitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getLongitude() {
|
||||||
|
return longitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void setLongitude(final double longitude) {
|
||||||
|
this.longitude = longitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getCityName() {
|
||||||
|
return cityName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final void setCityName(final String cityName) {
|
||||||
|
this.cityName = cityName;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package astrochart.shared.enums;
|
||||||
|
|
||||||
|
public enum AspectType {
|
||||||
|
Conjunction('\u260C', 0D, 7D, new double[]{1D, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D, 10D}),
|
||||||
|
Sextile('\u26B9', 60D, 5D, new double[]{1D, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D, 10D}), //26B9
|
||||||
|
Quintile('\u0051', 72D, 5D, new double[]{1D, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D, 10D}),
|
||||||
|
Square('\u25A1', 90D, 6D, new double[]{1D, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D, 10D}),
|
||||||
|
Trine('\u25B3', 120D, 5D, new double[]{1D, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D, 10D}),
|
||||||
|
Opposition('\u260D', 180D, 7D, new double[]{1D, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D, 10D});
|
||||||
|
|
||||||
|
// <donh> trines are third-order and sextiles sixth-order. sextiles need to be given half the weight
|
||||||
|
// <donh> and about half the orb, and most certainly less orb than quintiles or squares
|
||||||
|
|
||||||
|
private final char unicode;
|
||||||
|
private final double angle;
|
||||||
|
private final double defaultOrb;
|
||||||
|
private final double[] orbs;
|
||||||
|
|
||||||
|
private AspectType(final char unicode, final double angle, final double defaultOrb, final double[] orbs) {
|
||||||
|
this.unicode = unicode;
|
||||||
|
this.angle = angle;
|
||||||
|
this.defaultOrb = defaultOrb;
|
||||||
|
this.orbs = orbs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final char getUnicode() {
|
||||||
|
return unicode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getAngle() {
|
||||||
|
return angle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double[] getOrbs() {
|
||||||
|
return orbs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getDefaultOrb() {
|
||||||
|
return defaultOrb;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String toString() {
|
||||||
|
return name();
|
||||||
|
}
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
package astrochart.shared.enums;
|
||||||
|
|
||||||
|
public enum ChartColor {
|
||||||
|
Black("#000000"),
|
||||||
|
White("#FFFFFF"),
|
||||||
|
Red("#ED1C24"),
|
||||||
|
Blue("#3F48CC"),
|
||||||
|
Yellow("#FFF200"),
|
||||||
|
Green("#22B14C");
|
||||||
|
|
||||||
|
private final String hex;
|
||||||
|
|
||||||
|
private ChartColor(final String hex) {
|
||||||
|
this.hex = hex;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getHex() {
|
||||||
|
return hex;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String toString() {
|
||||||
|
return name();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package astrochart.shared.enums;
|
||||||
|
|
||||||
|
public enum ChartProportions {
|
||||||
|
Outer(1.00D),
|
||||||
|
HouseNumber(0.98D),
|
||||||
|
OuterEclyptic(0.95D),
|
||||||
|
EclypticCenter(0.85D),
|
||||||
|
InnerEclyptic(0.75D),
|
||||||
|
OuterMark(0.72D),
|
||||||
|
InnerMark(0.70D),
|
||||||
|
PlanetMark(0.66D),
|
||||||
|
PlanetSign(0.62D),
|
||||||
|
Degree(0.55D),
|
||||||
|
Minute(0.48D),
|
||||||
|
InnerLine(0.44D),
|
||||||
|
Inner(0.40D);
|
||||||
|
|
||||||
|
private final double relativeRadius;
|
||||||
|
|
||||||
|
private ChartProportions(final double relativeRadius) {
|
||||||
|
this.relativeRadius = relativeRadius;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final double getRelativeRadius() {
|
||||||
|
return relativeRadius;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final int getRadius(final int halfChartSize, final ChartProportions prop) {
|
||||||
|
return (int) (halfChartSize * prop.getRelativeRadius());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final String toString() {
|
||||||
|
return this.name();
|
||||||
|
}
|
||||||
|
}
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
package astrochart.shared.enums;
|
||||||
|
|
||||||
|
public enum HouseType {
|
||||||
|
Equal("Equal House"),
|
||||||
|
WholeSigns("Whole Sign");
|
||||||
|
// Placidus("Placidus"), //http://groups.google.com/group/alt.astrology.moderated/browse_thread/thread/5cf05d6fe8eabb52/17e0c6282d8c7dce?lnk=raot
|
||||||
|
// Campanus,
|
||||||
|
// Regiomontanus,
|
||||||
|
// KochHousesSystem;
|
||||||
|
|
||||||
|
private final String name;
|
||||||
|
|
||||||
|
private HouseType(final String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String toString() {
|
||||||
|
return name();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static HouseType getTypeForName(final String name) {
|
||||||
|
for (final HouseType type : HouseType.values()) {
|
||||||
|
if (type.getName().equals(name)) {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException();
|
||||||
|
}
|
||||||
|
}
|
||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package astrochart.shared.enums;
|
||||||
|
|
||||||
|
public enum Planet {
|
||||||
|
Sun(3, '\u2609', true, false),
|
||||||
|
Moon(4, '\u263e', true, false),
|
||||||
|
Node(13, '\u260A', false, false), //ascending
|
||||||
|
SouthNode(14, '\u260B', false, false), //descending
|
||||||
|
Mercury(5, '\u263f', true, false),
|
||||||
|
Venus(6, '\u2640', true, false),
|
||||||
|
Mars(7, '\u2642', true, false),
|
||||||
|
Jupiter(8, '\u2643', true, false),
|
||||||
|
Saturn(9, '\u2644', true, false),
|
||||||
|
Uranus(10, '\u2645', true, true),
|
||||||
|
Neptune(11, '\u2646', true, true),
|
||||||
|
Pluto(12, '\u2647', true, true);
|
||||||
|
|
||||||
|
private final int token;
|
||||||
|
private final char unicode;
|
||||||
|
private final boolean isBody;
|
||||||
|
private final boolean isOuter;
|
||||||
|
|
||||||
|
private Planet(final int token, final char unicode, final boolean isBody, final boolean isOuter) {
|
||||||
|
this.token = token;
|
||||||
|
this.unicode = unicode;
|
||||||
|
this.isBody = isBody;
|
||||||
|
this.isOuter = isOuter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getToken() {
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final char getUnicode() {
|
||||||
|
return unicode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final boolean isBody() {
|
||||||
|
return isBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final boolean isOuter() {
|
||||||
|
return isOuter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final String toString() {
|
||||||
|
return this.name();
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package astrochart.shared.enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* compare: http://www.vedicastro.com/astronomy6.asp
|
||||||
|
*/
|
||||||
|
public enum RashimanaGroup {
|
||||||
|
I(1674), II(1795), III(1931);
|
||||||
|
|
||||||
|
private final int equatorialAsus;
|
||||||
|
|
||||||
|
private RashimanaGroup(final int equatorialAsus) {
|
||||||
|
this.equatorialAsus = equatorialAsus;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getEquatorialAsus() {
|
||||||
|
return equatorialAsus;
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package astrochart.shared.enums;
|
||||||
|
|
||||||
|
public enum Weekday {
|
||||||
|
Monday("Mo"), Tuesday("Tu"), Wednesday("We"), Thursday("Th"), Friday("Fr"), Saturday("Sa"), Sunday("Su");
|
||||||
|
|
||||||
|
private final String abbreviation;
|
||||||
|
|
||||||
|
private Weekday(final String abbreviation) {
|
||||||
|
this.abbreviation = abbreviation;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getAbbreviation() {
|
||||||
|
return abbreviation;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final String toString() {
|
||||||
|
return this.name();
|
||||||
|
}
|
||||||
|
}
|
||||||
+88
@@ -0,0 +1,88 @@
|
|||||||
|
package astrochart.shared.enums;
|
||||||
|
|
||||||
|
|
||||||
|
public enum ZodiacSign {
|
||||||
|
Aries(0, ChartColor.Red, '\u2648', "AR", "LI", RashimanaGroup.I, false),
|
||||||
|
Taurus(30, ChartColor.Green, '\u2649', "TA", "SC", RashimanaGroup.II, false),
|
||||||
|
Gemini(60, ChartColor.Yellow, '\u264A', "GE", "SG", RashimanaGroup.III, false),
|
||||||
|
Cancer(90, ChartColor.Blue, '\u264B', "CN", "CP", RashimanaGroup.III, true),
|
||||||
|
Leo(120, ChartColor.Red, '\u264C', "LE", "AQ", RashimanaGroup.II, true),
|
||||||
|
Virgo(150, ChartColor.Green, '\u264D', "VI", "PI", RashimanaGroup.I, true),
|
||||||
|
Libra(180, ChartColor.Yellow, '\u264E', "LI", "AR", RashimanaGroup.I, true),
|
||||||
|
Scorpio(210, ChartColor.Blue, '\u264F', "SC", "TA", RashimanaGroup.II, true),
|
||||||
|
Sagittaurius(240, ChartColor.Red, '\u2650', "SG", "GE", RashimanaGroup.III, true),
|
||||||
|
Capricorn(270, ChartColor.Green, '\u2651', "CP", "CN", RashimanaGroup.III, false),
|
||||||
|
Aquarius(300, ChartColor.Yellow, '\u2652', "AQ", "LE", RashimanaGroup.II, false),
|
||||||
|
Pisces(330, ChartColor.Blue, '\u2653', "PI", "VI", RashimanaGroup.I, false);
|
||||||
|
|
||||||
|
private static final int DEGREES_PER_SIGN = 30;
|
||||||
|
private final int eclipticLongitude;
|
||||||
|
private final ChartColor color;
|
||||||
|
private final char unicode;
|
||||||
|
private final String abbreviation;
|
||||||
|
private final String descendent;
|
||||||
|
private final RashimanaGroup rashimanaGroup;
|
||||||
|
private final boolean hasLongAscension;
|
||||||
|
|
||||||
|
private ZodiacSign(final int eclipticLongitude, final ChartColor color, final char unicode, final String abbreviation, final String descendent,
|
||||||
|
final RashimanaGroup rashimanaGroup, final boolean hasLongAscension) {
|
||||||
|
this.eclipticLongitude = eclipticLongitude;
|
||||||
|
this.color = color;
|
||||||
|
this.unicode = unicode;
|
||||||
|
this.abbreviation = abbreviation;
|
||||||
|
this.descendent = descendent;
|
||||||
|
this.rashimanaGroup = rashimanaGroup;
|
||||||
|
this.hasLongAscension = hasLongAscension;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final ZodiacSign getSignAtDegree(final double degree) {
|
||||||
|
for (final ZodiacSign sign : ZodiacSign.values()) {
|
||||||
|
if (degree >= sign.getEclipticLongitude() && degree < sign.getEclipticLongitude() + DEGREES_PER_SIGN) {
|
||||||
|
return sign;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("Value out of range: " + degree);
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getEclipticLongitude() {
|
||||||
|
return eclipticLongitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final ChartColor getColor() {
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final char getUnicode() {
|
||||||
|
return unicode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getAbbreviation() {
|
||||||
|
return abbreviation;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final String getDescendent() {
|
||||||
|
return descendent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final RashimanaGroup getRashimanaGroup() {
|
||||||
|
return rashimanaGroup;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final boolean hasLongAscension() {
|
||||||
|
return hasLongAscension;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final ZodiacSign valueOfAbbrevistion(final String abbreviation) {
|
||||||
|
for (final ZodiacSign sign : ZodiacSign.values()) {
|
||||||
|
if (sign.getAbbreviation().equals(abbreviation)) {
|
||||||
|
return sign;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("Fail: Abbreviation unknown: " + abbreviation);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final String toString() {
|
||||||
|
return this.name();
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package astrochart.shared.enums.time;
|
||||||
|
|
||||||
|
public enum Month {
|
||||||
|
January(1, 31),
|
||||||
|
February(2, 28), // 29 days in leap years
|
||||||
|
March(3, 31),
|
||||||
|
April(4, 30),
|
||||||
|
May(5, 31),
|
||||||
|
June(6, 30),
|
||||||
|
July(7, 31),
|
||||||
|
August(8, 31),
|
||||||
|
September(9, 30),
|
||||||
|
October(10, 31),
|
||||||
|
November(11, 30),
|
||||||
|
December(12, 31);
|
||||||
|
|
||||||
|
private final int number;
|
||||||
|
private final int days;
|
||||||
|
|
||||||
|
private Month(final int number, final int days) {
|
||||||
|
this.number = number;
|
||||||
|
this.days = days;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getNumber() {
|
||||||
|
return number;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int getDays() {
|
||||||
|
return days;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final String toString() {
|
||||||
|
return this.name();
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user