Add bounded author-triggered geographical resolution and map positioning
This commit is contained in:
parent
47d400cbb7
commit
9eb1f553ef
92
Docs/Geography/GeographicalPositioning.md
Normal file
92
Docs/Geography/GeographicalPositioning.md
Normal file
@ -0,0 +1,92 @@
|
||||
# Geographical resolution and map positioning
|
||||
|
||||
Implementation and qualification record, 13 November 2026. This feature extends existing Locations and Maps. Word Companion, manuscript persistence, Context and Intent are untouched.
|
||||
|
||||
## Author workflow and triggers
|
||||
|
||||
Creating a location **never submits a geographical request**, including creation with a parent. Existing-name and type edits invalidate affected coordinates but do not request new lookup. Moving an existing location beneath a recognised geographical root requests resolution for that branch. Editing an existing location's parent follows the same path. For an already arranged hierarchy, Location Details offers **Resolve this arranged hierarchy (up to 20 places)** as a deliberate request. There is no database-wide enrichment or periodic refresh. The 30-second worker only drains these finite persisted requests.
|
||||
|
||||
Admission is deliberately conservative: up to 20 locations per branch, one batch per author per hour and six batches per application per hour. Retry and explicit replacement use the same admission limit. Larger branches must be arranged/requested in smaller portions; multiple quick hierarchy edits may hit the hourly limit. Hierarchy edits still save when lookup admission is declined; the Locations tree explains the outcome. Confirmation does not spend a provider request or batch allowance.
|
||||
|
||||
Location Details shows status, candidate name/administrative context/country/coordinates and source attribution. Selecting a candidate sends its index and the observed generation, never client-supplied coordinates. Confirmed matches persist until identifying context changes or the author explicitly chooses replacement/exclusion. Authors can exclude lookup and later re-enable it; re-enabling waits for a deliberate hierarchy request.
|
||||
|
||||
## Eligibility and root reference
|
||||
|
||||
Existing database types are Country, Region, Town, Village, Street, Building, Floor, Room, Outdoor Area, Vehicle Interior, Landmark and Other. Only Country, Region, Town and Village currently qualify. The generic rule also supports State, County and City if those types already exist in another installation; it does not insert or rename types. Premises, streets and arbitrary non-geographical intermediate parents are excluded.
|
||||
|
||||
Country and administrative-root recognition uses the bundled Debian `iso-codes` ISO 3166-1/3166-2 datasets, not a UK-only coordinate gazetteer. Attribution/licensing accompany the files in `PlotLine/Data/Reference/Geography/COPYRIGHT.txt`. Update these reference snapshots from the upstream iso-codes project, review their differences and run the focused geography tests. Country names, official/common names and alpha-3 identifiers are accepted. Explicit subdivision codes and country-qualified subdivision names (for example `US-CA` or `California, US`) avoid unsafe bare-region assumptions. UK/United Kingdom and US/USA/United States aliases are supported, as are England, Scotland, Wales and Northern Ireland. Bare Georgia is deliberately excluded; use GEO for the country or US-GA for the state. Fictional roots fail closed. Incomplete/archived ancestor chains also fail closed.
|
||||
|
||||
Depth is flexible: there is no requirement to insert missing administrative levels. All available geographical ancestors are sent, with a country restriction and explicit subdivision checking when available. Production rules contain no manuscript-specific place names.
|
||||
|
||||
## Provider decision and policy
|
||||
|
||||
The initial configurable provider is **public Nominatim**, following the developer's explicit decision for a small user base and finite author-triggered hierarchy requests. No local UK gazetteer, OS Names API, map tiles or additional coordinate infrastructure is shipped.
|
||||
|
||||
The [OSMF usage policy](https://operations.osmfoundation.org/policies/nominatim/) was checked on 13 November 2026. It permits modest user-triggered searches, limits the application as a whole to at most one request per second, requires an identifying User-Agent and attribution, discourages recurring/bulk work, and restricts permissible small bulk jobs to one thread on one machine. Regular or day-long scripts have a stricter four-request-per-minute ceiling. Repeated queries must be cached. Service availability and permission can change. These limits are not a blanket approval for scaling the workload; review the provider before increasing caps or user numbers.
|
||||
|
||||
This implementation always uses the stricter 15-second interval, one designated host, one database-fenced external request at a time and a 200-request daily application cap. Retries also consume this budget. Public usage requires no API key or subscription; service capacity is donated and carries no application SLA. Data attribution is `© OpenStreetMap contributors`, with the [ODbL/copyright link](https://www.openstreetmap.org/copyright), retained with candidates and displayed in Location Details and geographical preview. The ODbL terms apply to reuse of the geographical cache; do not publish a substantial extracted database without reviewing its obligations.
|
||||
|
||||
The [Search API](https://nominatim.org/release-docs/latest/api/Search/) returns ranked matches, not a proof of uniqueness. The Nominatim adapter automatically resolves only one non-truncated candidate with an exact place-name match, matching country/subdivision, all available additional administrative ancestors represented in the response, and identifying context beyond a country-only root (an explicit subdivision root or additional matching ancestor). Multiple candidates, missing context, aliases without exact provider-name evidence and country-only queries require confirmation. A single ranking alone is insufficient. This deliberately means that the broad `United Kingdom → town` case may require confirmation; `England → town` or matching county context can resolve automatically. Other adapters must establish equivalent reliable matching rules before setting `UniqueWithinContext`. The deterministic tests cover automatic resolution and conservative ambiguity. OSM identities use `osm_type:osm_id`; Nominatim's transient numeric `place_id` is not treated as a stable identity ([output documentation](https://nominatim.org/release-docs/latest/api/Output/)).
|
||||
|
||||
Earlier OS Open Names investigation found Great Britain coverage only, OGL commercial reuse, quarterly full replacements and an API alternative with the same underlying geographical coverage. Northern Ireland must not be inferred from Great Britain coverage. This direction was superseded by the explicit Nominatim decision; no OS data/importer/provider is part of this feature.
|
||||
|
||||
## Configuration and safe disable/switch
|
||||
|
||||
Defaults keep external processing disabled. Put the following section in the deployment's watched `appsettings.Production.json` (or the applicable watched environment JSON), preserving its other settings:
|
||||
|
||||
```json
|
||||
"Geography": {
|
||||
"Enabled": false,
|
||||
"Provider": "Nominatim",
|
||||
"Endpoint": "https://nominatim.openstreetmap.org/search",
|
||||
"UserAgent": "PlotDirector/1.0 (+https://dev.plotdirector.com/)",
|
||||
"WorkerHost": "atlas",
|
||||
"MinimumIntervalSeconds": 15
|
||||
}
|
||||
```
|
||||
|
||||
Use the actual designated machine name and an identifying application/contact URL. `Enabled=true` requires a valid PlotDirector User-Agent and matching host. `Enabled=false` or a provider value other than Nominatim disables external lookup. An alternative Nominatim-compatible endpoint can be selected through the same configuration. `IOptionsMonitor` reloads watched JSON without redeployment. Environment-variable changes require a process restart, so use watched JSON when immediate disable/switch is required. HTTP redirects are disabled, and the server never exposes this configuration to browser clients. HttpClient request logging is removed for this client to prevent query URLs leaking into routine logs.
|
||||
|
||||
No external requests run during the automated tests. Public service testing must be an explicitly approved, small manual author-triggered acceptance check, not a dependency of the regression gate.
|
||||
|
||||
## Queue, cache, concurrency and privacy
|
||||
|
||||
The Locations trigger invalidates changed locations and descendants on name/type/parent/archive changes. Ordinary descriptions do not invalidate confirmed geography. Invalidation increments a generation and revokes leases; it does not submit new work. The application admits author hierarchy events after its existing project-access checks. SQL rechecks project access and generation and admits the finite subtree under a transaction and central quota lock.
|
||||
|
||||
Jobs persist across restarts. A single per-location row deduplicates work. A two-minute processing lease supports crash recovery; a 25-second HTTP timeout keeps normal calls within that lease. Provider reservations serialize all external requests across application processes, with a persistent next-request timestamp, daily budget and cross-author request-key lease. The designated-host check prevents external processing on a second machine. Persistent request-key caching prevents repeats, including empty results; no TTL refresh is scheduled. Provider/endpoint plus country/subdivision and the complete available ancestor context form the request hash. Different Newtown contexts cannot reuse coordinates based on name alone.
|
||||
|
||||
Shared cache entries contain provider-returned public geographical candidates: provider/OSM identity, canonical display name, coordinates, country, administrative context, attribution and resolution time. They contain no project, account, private description, manuscript text or original hierarchy. Per-author confirmation remains on that author's Location record; an ambiguous choice by one author is not silently promoted into another author's confirmed match. Identical candidate sets may be reused, with confirmation still required.
|
||||
|
||||
Provider failures have four bounded attempts and 60/120/240/480-second backoff. Rate reservation failures defer work without consuming a provider failure. HTTP 403/429 also apply an application-wide cooldown, respecting Retry-After subject to safe bounds. No provider error body/query/credential is logged. Only bounded error-type operational events are logged. Stale completion checks both generation and lease; a confirmed coordinate cannot be overwritten by a worker.
|
||||
|
||||
## Maps
|
||||
|
||||
**Position geographically** projects resolved, unlocked location markers onto the currently visible canvas area. It uses a spherical azimuthal equidistant local projection, north up at its centre; circular longitude centring handles the antimeridian. One scale preserves aspect ratio with padding. Single/coincident points remain finite and centred; coincident places deliberately overlap. Shapes, paths, unlinked markers and locked pieces retain their serialized contents. Connected routes retain their existing behaviour of following their linked markers.
|
||||
|
||||
This is a local projection, not a claim that every pairwise spherical distance is exactly preserved. Extents beyond 15 degrees from the centre (roughly 1,650 km) are refused to avoid a misleading global arrangement. Labels and markers may overlap in dense clusters; authors can adjust them afterwards.
|
||||
|
||||
The existing canvas renders a preview while the working document remains unchanged. The dialog identifies moves, skipped statuses/locks and attribution. Cancel/Escape preserve the complete document. Apply adds one existing Undo/Redo checkpoint; Save uses the established map revision/permission/persistence path. No objects are deleted/recreated. Manual canvas dragging cannot alter geographical coordinates. Repositioning is always explicit.
|
||||
|
||||
## Database rollout
|
||||
|
||||
New tables/procedures are in 253, 254, 255 and 256. Apply **253, 255, 254, 256**, not a blind numeric replay. During Development qualification, 254 exposed that a new job-state label exceeded the original 24-character column; 255 is the forward-only width repair, preserving the applied scripts. 254 then completed successfully. 256 indexes the durable queue and batch-time lookup.
|
||||
|
||||
Development was verified as `PlotDirector_Development` before applying changes. A copy-only compressed CHECKSUM backup was successfully created and its nonempty container file verified at `/var/opt/mssql/backup/PlotDirector_Development_geography_20261113_142234.bak`. An additional RESTORE VERIFYONLY attempt was unavailable to the application principal (CREATE DATABASE permission); no restore was attempted. The backup is not a tested restore. Existing unrelated manuscript/Word work is preserved.
|
||||
|
||||
New per-location geography rows cascade on physical Location deletion. Shared public cache and provider-budget rows contain no private project hierarchy. The feature does not modify the existing map X/Y schema. Project backups currently do not export/import geocoding decisions; restored locations will need an explicit hierarchy request and confirmation again. Existing map canvas coordinates continue through the established map backup path.
|
||||
|
||||
## Verification commands
|
||||
|
||||
Run build and regression serially:
|
||||
|
||||
```sh
|
||||
dotnet build PlotLine.slnx
|
||||
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj
|
||||
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --geography
|
||||
```
|
||||
|
||||
The normal harness includes the deterministic geography group. Development-only SQL regressions `253_LocationGeographyRegression.sql` and `254_GeographyHierarchyBatchesRegression.sql` use rollback fixtures. `--geography-database` separately verifies 16 concurrent database provider reservations, persistent cooldown and fresh-connection recovery using random synthetic provider/request identifiers, then removes only its own rows. It makes no external requests.
|
||||
|
||||
Browser tests: `maps-geography-engine.cjs`, `maps-geography.cjs`, `location-geography.cjs`, existing `maps-engine.cjs`, `maps-workspace.cjs`, `location-reparent.cjs`, and `application-pwa.cjs`. The workspace tests use the isolated Razor host (`--toolbar-browser-host`) and deterministic mocked resolutions/saves, including browser/PWA and light/dark themes. The existing Maps test screenshots were redirected to the task evidence directory because the shared `/tmp` write quota rejected screenshot output; assertions were unchanged.
|
||||
|
||||
Final execution results, deployed commit and any remaining Development acceptance work are recorded in the delivery report accompanying this document.
|
||||
20
PlotLine.Tests/Browser/location-geography.cjs
Normal file
20
PlotLine.Tests/Browser/location-geography.cjs
Normal file
@ -0,0 +1,20 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
(async()=>{const browser=await chromium.launch();try{
|
||||
const page=await browser.newPage();let chosen=null;
|
||||
const candidate={Provider:'Fake',PlaceID:'node:1',Name:'Newtown <script>unsafe()</script>',Latitude:52.5,Longitude:-3.3,CountryCode:'GB',AdministrativeNames:['Powys','Wales'],Attribution:'Synthetic fixture'};
|
||||
let state={locationID:11,generation:4,status:'Needs confirmation',candidatesJson:JSON.stringify([candidate]),isExcluded:false};
|
||||
await page.route('https://plotdirector.test/**',r=>{
|
||||
if(r.request().url().includes('/Geography/State'))return r.fulfill({json:[state]});
|
||||
if(r.request().url().endsWith('/Geography/Confirm')){chosen=Object.fromEntries(new URLSearchParams(r.request().postData()));state={...state,status:'Resolved',matchJson:JSON.stringify(candidate),confirmed:true};return r.fulfill({json:{ok:true}});}
|
||||
return r.fulfill({contentType:'text/html',body:'<div data-geography-location="11" data-project-id="7"><span data-geography-status></span><div data-geography-body></div></div><input name="__RequestVerificationToken" value="test-token">'});
|
||||
});
|
||||
await page.goto('https://plotdirector.test/Locations/Details/11');
|
||||
await page.addScriptTag({content:fs.readFileSync(require('node:path').resolve(__dirname,'../../PlotLine/wwwroot/js/location-geography.js'),'utf8')});
|
||||
await page.getByRole('button',{name:/Newtown/}).click();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-geography-status]').textContent==='Resolved');
|
||||
assert.deepEqual(chosen,{projectId:'7',locationId:'11',generation:'4',candidateIndex:'0'});
|
||||
assert(await page.getByText('Newtown <script>unsafe()</script> · Powys, Wales · GB',{exact:true}).isVisible(),'metadata is rendered as text');
|
||||
assert.equal(await page.locator('script').count(),1,'no candidate HTML injection');
|
||||
assert(await page.getByRole('button',{name:'Change geographical match'}).isVisible());
|
||||
console.log('PASS Location candidate context, index-only confirmation, generation protection and safe text rendering; no external calls.');
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});
|
||||
23
PlotLine.Tests/Browser/maps-geography-engine.cjs
Normal file
23
PlotLine.Tests/Browser/maps-geography-engine.cjs
Normal file
@ -0,0 +1,23 @@
|
||||
const assert=require('node:assert/strict');
|
||||
const {position}=require('../../PlotLine/wwwroot/js/maps-geography-engine.js');
|
||||
const box={x:0,y:0,w:1200,h:800};
|
||||
const marker=(id,more={})=>({featureID:String(id),name:'Place '+id,locationID:id,geometryClass:'Marker',x:10,y:10,isLocked:false,...more});
|
||||
const state=(id,lat,lon)=>({locationID:id,status:'Resolved',matchJson:JSON.stringify({Latitude:lat,Longitude:lon,Attribution:'Synthetic'})});
|
||||
const fs=[marker(1),marker(2),marker(3),marker(4,{isLocked:true}),marker(5,{geometryClass:'Path'}),{featureID:'unrelated',geometryClass:'Area',x:99,y:98}];
|
||||
const before=JSON.stringify(fs),r=position(fs,[state(1,52,0),state(2,52.01,0),state(3,52,.01),state(4,52,0),state(5,52,0)],box);
|
||||
assert.equal(JSON.stringify(fs),before,'projection leaves source untouched (preview cancel)');
|
||||
assert(r.features[1].y<r.features[0].y,'north is up');assert(r.features[2].x>r.features[0].x,'east is right');
|
||||
const north=r.features[0].y-r.features[1].y,east=r.features[2].x-r.features[0].x;
|
||||
assert(Math.abs(east/north-Math.cos(52*Math.PI/180))<.002,'geographical distance ratio and a single aspect scale');
|
||||
for(const p of r.features.slice(0,3)){assert(p.x>=80&&p.x<=1120);assert(p.y>=80&&p.y<=720);}
|
||||
assert.deepEqual(r.features.slice(3),fs.slice(3),'locks, paths and unrelated drawings remain byte-equivalent');
|
||||
assert.equal(r.skipped.length,2);
|
||||
for(const coords of [[[52,0]],[[52,0],[52,0]],[[52,0],[52,1]],[[0,179.9],[0,-179.9]],[[89,0],[89,1]]]){
|
||||
const result=position(coords.map((_,i)=>marker(i+1)),coords.map((p,i)=>state(i+1,...p)),box);
|
||||
assert(result.features.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y)),'single/two/coincident/antimeridian/polar points finite');
|
||||
if(coords.length===1)assert.deepEqual([result.features[0].x,result.features[0].y],[600,400]);
|
||||
}
|
||||
assert.throws(()=>position([marker(1),marker(2)],[state(1,0,0),state(2,0,160)],box),/too large|too much/);
|
||||
assert.equal(position([marker(1)],[{locationID:1,status:'Needs confirmation'}],box).positioned.length,0);
|
||||
assert.equal(position([marker(1)],[state(1,NaN,0)],box).positioned.length,0);
|
||||
console.log('PASS geographical projection direction, proportional distances, aspect ratio, padding, antimeridian, polar/single/coincident cases, extent refusal, locks and preservation.');
|
||||
59
PlotLine.Tests/Browser/maps-geography.cjs
Normal file
59
PlotLine.Tests/Browser/maps-geography.cjs
Normal file
@ -0,0 +1,59 @@
|
||||
const {chromium}=require('playwright');
|
||||
const assert=require('node:assert/strict');
|
||||
const base=process.env.PD_MAPS_TEST_URL||'http://127.0.0.1:5238';
|
||||
(async()=>{
|
||||
const browser=await chromium.launch();
|
||||
try{
|
||||
for(const pwa of [false,true])for(const theme of ['modern-light','modern-dark']){
|
||||
const context=await browser.newContext({viewport:{width:1700,height:1100}});
|
||||
if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
let saves=0;
|
||||
await page.route('**/Maps/Save',r=>{saves++;const d=r.request().postDataJSON();d.map.revision++;return r.fulfill({json:d});});
|
||||
const states=[[11,52.486,-1.89],[12,52.391,-2.016]].map(([id,lat,lon])=>({locationID:id,status:'Resolved',matchJson:JSON.stringify({Latitude:lat,Longitude:lon,Attribution:'Synthetic fixture; no provider calls'})}));
|
||||
states.push({locationID:13,status:'Needs confirmation'});
|
||||
await page.route('**/Geography/State?*',r=>r.fulfill({json:states}));
|
||||
await page.goto(base+'/fixture?page=maps&theme='+theme);await page.waitForFunction(()=>!!window.PlotDirectorMapWorkspace);
|
||||
await page.evaluate(()=>{
|
||||
const W=window.PlotDirectorMapWorkspace;
|
||||
W.edit(()=>{
|
||||
for(const [id,name,lock]of [[11,'Birmingham',false],[12,'Rubery',false],[13,'Newtown',false],[14,'Locked place',true]])W.document.features.push({featureID:crypto.randomUUID(),name,type:'Town',geometryClass:'Marker',layer:'Places',x:id*5,y:id*7,width:48,height:48,rotation:0,zOrder:1,isPlaced:true,isProvisional:false,isLocked:lock,showLabel:true,labelX:0,labelY:0,locationID:id,geometryJson:'{}'});
|
||||
W.document.features.push({featureID:crypto.randomUUID(),name:'Drawing',type:'Island',geometryClass:'Area',layer:'Land',x:500,y:500,width:200,height:100,rotation:0,zOrder:0,isPlaced:true,isLocked:false,geometryJson:'{}'});
|
||||
});
|
||||
});
|
||||
const read=()=>page.evaluate(()=>JSON.stringify(window.PlotDirectorMapWorkspace.document.features));
|
||||
const before=await read();
|
||||
async function command(id){
|
||||
if(pwa&&id==='mapsGeographic'){
|
||||
const proxy=page.locator('[data-pwa-context-controls] [data-command-identity="handler:mapsGeographic"]');
|
||||
assert.equal(await proxy.count(),1,'geographical action is available in the PWA ribbon');
|
||||
const menu=proxy.locator('xpath=ancestor::details[1]');
|
||||
if(await menu.count()&&await menu.getAttribute('data-compact')==='true'&&await menu.getAttribute('open')===null)await menu.locator(':scope > summary').click();
|
||||
await proxy.click();
|
||||
}else await page.evaluate(id=>document.getElementById(id).click(),id);
|
||||
}
|
||||
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});
|
||||
assert.equal(await read(),before,'preview never mutates saved/working document');
|
||||
assert.match(await page.locator('#mapsGeographicSummary').innerText(),/Newtown — Needs confirmation/);
|
||||
assert.match(await page.locator('#mapsGeographicSummary').innerText(),/Locked place — Locked/);
|
||||
await command('mapsGeographicCancel');assert.equal(await read(),before);assert.equal(saves,0);
|
||||
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});await page.keyboard.press('Escape');
|
||||
assert.equal(await page.locator('#mapsGeographicDialog').isVisible(),false,'Escape cancels');assert.equal(await read(),before);
|
||||
await command('mapsGeographic');await page.locator('#mapsGeographicDialog').waitFor({state:'visible'});await command('mapsGeographicApply');
|
||||
const applied=await read();assert.notEqual(applied,before);
|
||||
const features=JSON.parse(applied),prior=JSON.parse(before);
|
||||
assert(features[1].x<features[0].x&&features[1].y>features[0].y,'Rubery is southwest of Birmingham');
|
||||
assert.deepEqual(features.slice(2),prior.slice(2),'ambiguous/locked/drawings preserved');
|
||||
await command('mapsUndo');assert.equal(await read(),before,'one undo restores operation');
|
||||
await command('mapsRedo');assert.equal(await read(),applied,'redo reproduces operation');
|
||||
await command('mapsSave');await page.waitForFunction(()=>!window.PlotDirectorMapWorkspace.busy);assert.equal(saves,1);
|
||||
const id=features[0].featureID;await page.evaluate(id=>window.PlotDirectorMapWorkspace.select(id),id);
|
||||
await page.locator(`[data-feature-id="${id}"]`).focus();await page.keyboard.press('ArrowRight');
|
||||
assert.equal(JSON.parse(await read())[0].x,features[0].x+5,'manual movement remains available');
|
||||
assert.equal(states[0].matchJson,JSON.stringify({Latitude:52.486,Longitude:-1.89,Attribution:'Synthetic fixture; no provider calls'}),'canvas movement cannot change geographic coordinates');
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS geographic preview/cancel/Escape/apply/undo/redo/save/manual movement/preservation',pwa?'PWA':'browser',theme);
|
||||
await context.close();
|
||||
}
|
||||
}finally{await browser.close();}
|
||||
})().catch(e=>{console.error(e);process.exit(1);});
|
||||
41
PlotLine.Tests/GeographyDatabaseTests.cs
Normal file
41
PlotLine.Tests/GeographyDatabaseTests.cs
Normal file
@ -0,0 +1,41 @@
|
||||
using System.Diagnostics;
|
||||
using System.Data;
|
||||
using System.Security.Cryptography;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using PlotLine.Data;
|
||||
internal static class GeographyDatabaseTests
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
|
||||
foreach(var arg in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(arg);
|
||||
using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();
|
||||
if(process.ExitCode!=0)throw new InvalidOperationException("Development configuration unavailable.");
|
||||
var connectionString=env.Split('\n').Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');
|
||||
if(new SqlConnectionStringBuilder(connectionString).InitialCatalog!="PlotDirector_Development")throw new InvalidOperationException("Development only.");
|
||||
using var db=new SqlConnection(connectionString);await db.OpenAsync();
|
||||
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new InvalidOperationException("Wrong effective database.");
|
||||
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connectionString}}).Build();
|
||||
var factory=new SqlConnectionFactory(config);var provider="FakeConcurrency-"+Guid.NewGuid().ToString("N");
|
||||
var keys=Enumerable.Range(0,16).Select(_=>Convert.ToHexString(RandomNumberGenerator.GetBytes(32))).ToArray();
|
||||
var leases=Enumerable.Range(0,16).Select(_=>Guid.NewGuid()).ToArray();
|
||||
try
|
||||
{
|
||||
var results=await Task.WhenAll(Enumerable.Range(0,16).Select(i=>new GeographyRepository(factory).ReserveAsync(provider,TimeSpan.FromSeconds(15),keys[i],leases[i])));
|
||||
if(results.Count(x=>x)!=1)throw new InvalidOperationException("Concurrent workers acquired more than one provider slot.");
|
||||
var winner=Array.IndexOf(results,true);
|
||||
// A fresh repository (process-equivalent connection) must still see the persisted occupied slot.
|
||||
if(await new GeographyRepository(factory).ReserveAsync(provider,TimeSpan.FromSeconds(15),keys[0],Guid.NewGuid()))throw new InvalidOperationException("Restart bypassed gate.");
|
||||
await new GeographyRepository(factory).ReleaseAsync(leases[winner],3600);
|
||||
if(await new GeographyRepository(factory).ReserveAsync(provider,TimeSpan.FromSeconds(15),keys[0],Guid.NewGuid()))throw new InvalidOperationException("Provider cooldown bypassed.");
|
||||
Console.WriteLine("PASS 16 concurrent SQL provider reservations: exactly one winner, fresh-connection recovery and persistent provider cooldown; zero external calls.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Only this test's random synthetic provider and exact random request keys are removed.
|
||||
await db.ExecuteAsync("DELETE dbo.GeographicLookupLease WHERE RequestKey IN @keys; DELETE dbo.GeographicProviderGate WHERE Provider=@provider",new{keys,provider});
|
||||
}
|
||||
}
|
||||
}
|
||||
113
PlotLine.Tests/GeographyTests.cs
Normal file
113
PlotLine.Tests/GeographyTests.cs
Normal file
@ -0,0 +1,113 @@
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Data;
|
||||
using System.Text.Json;
|
||||
using System.Net;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Controllers;
|
||||
|
||||
internal static class GeographyTests
|
||||
{
|
||||
private static void Check(bool value,string message){if(!value)throw new InvalidOperationException(message);}
|
||||
public static async Task Run()
|
||||
{
|
||||
var rules=new GeographicRules(Path.GetFullPath("PlotLine/Data/Reference/Geography"));
|
||||
foreach(var name in new[]{"United Kingdom","UK","England","Scotland","Wales","USA","United States","Japan","Brazil","South Africa","Australia","IND","GB-ENG","California, US"})
|
||||
Check(rules.Root(name)!=null,"Recognised root: "+name);
|
||||
foreach(var name in new[]{"Middle-earth","The Shire","California","Georgia","West Midlands"})Check(rules.Root(name)==null,"Unsafe root: "+name);
|
||||
Check(rules.Root("Northern Ireland")?.SubdivisionCode=="GB-NIR","Northern Ireland is a distinct root.");
|
||||
LocationItem Place(string name,string type,int? parent=null)=>new(){LocationName=name,LocationTypeName=type,ParentLocationID=parent};
|
||||
var chain=new[]{Place("Rubery","Village",2),Place("England","Country")};
|
||||
var query=rules.Query(chain)!;Check(query!=null && query.SubdivisionCode=="GB-ENG","Direct hierarchy.");
|
||||
Check(rules.Query([Place("Rubery","Village",2),Place("Rednal","Town",3),Place("Birmingham","Town",4),Place("West Midlands","Region",5),Place("England","Country",6),Place("UK","Country")])?.Ancestors.Length==5,"Deep hierarchy.");
|
||||
Check(rules.Query([Place("Hobbiton","Village",2),Place("Middle-earth","Country")])==null,"Fictional root.");
|
||||
Check(rules.Query([Place("Pub","Building",2),Place("England","Country")])==null,"Premises excluded.");
|
||||
Check(rules.Query([Place("England","Country",99)])==null,"Missing ancestor fails closed.");
|
||||
var other=query! with {Ancestors=["Scotland"]};Check(GeographicRules.CacheKey(query!)!=GeographicRules.CacheKey(other),"Names in different regions cannot share a request.");
|
||||
Check(GeographicRules.CacheKey(query!,"edition1")!=GeographicRules.CacheKey(query!,"edition2"),"Provider/edition isolate caches.");
|
||||
var candidate=new GeographicCandidate("Fake","os-1","Rubery",52.4,-2,"GB",["England","GB-ENG"],"Synthetic test fixture");
|
||||
Check(GeographicRules.Candidates(query!,[candidate,candidate,candidate with{CountryCode="US"},candidate with{Latitude=double.NaN}]).Count==1,"Filter invalid candidates and deduplicate provider identities.");
|
||||
var queue=new QueueFake(chain);var provider=new ProviderFake([candidate]);
|
||||
await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);
|
||||
Check(queue.Status=="Needs confirmation"&&provider.Calls==1,"Single provider ranking alone is ambiguous.");
|
||||
queue.Requeue();await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);
|
||||
Check(provider.Calls==1,"Cached candidate identity avoids another provider request.");
|
||||
queue.Requeue();queue.Cached=null;provider.Results=[candidate with{UniqueWithinContext=true}];
|
||||
await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);Check(queue.Status=="Resolved"&&queue.Match!=null,"Deterministic provider uniqueness resolves.");
|
||||
queue.Requeue();queue.Cached=null;provider.Fail=true;
|
||||
for(var attempt=0;attempt<4;attempt++){queue.Job.Attempts=attempt;await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);}
|
||||
Check(queue.Status=="Unresolved"&&queue.State=="Done"&&queue.Delay==480,"Retries bounded with exponential backoff.");
|
||||
provider.Fail=false;queue.Requeue();queue.AllowReservation=false;var calls=provider.Calls;
|
||||
Check(!await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default)&&provider.Calls==calls,"Database rate reservation must precede provider calls.");
|
||||
queue.AllowReservation=true;queue.Requeue();provider.IsEnabled=false;
|
||||
await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);Check(queue.State=="Waiting configuration"&&provider.Calls==calls,"Unconfigured provider never called.");
|
||||
queue.Requeue();queue.Chain=[Place("Hobbiton","Town",2),Place("Middle-earth","Country")];provider.IsEnabled=true;
|
||||
await new GeographicProcessor(queue,rules,provider).ProcessOneAsync(default);Check(queue.Status=="Not eligible"&&provider.Calls==calls,"Fictional hierarchy never reaches provider.");
|
||||
using(var response=JsonDocument.Parse("""
|
||||
[{"osm_type":"node","osm_id":123,"name":"Newtown","lat":"52.5","lon":"-3.3","display_name":"Newtown, Powys, Wales, United Kingdom","addresstype":"town","address":{"town":"Newtown","county":"Powys","state":"Wales","ISO3166-2-lvl4":"GB-WLS","country_code":"gb"}}]
|
||||
"""))
|
||||
{
|
||||
var result=NominatimGeocodingProvider.Parse(query! with{Name="Newtown",SubdivisionCode=null,Ancestors=["UK"]},response.RootElement);
|
||||
Check(result.Count==1&&result[0].PlaceID=="node:123"&&!result[0].UniqueWithinContext,"Nominatim OSM identity, metadata and conservative ambiguity.");
|
||||
Check(NominatimGeocodingProvider.Parse(query! with{Name="Newtown",SubdivisionCode="GB-WLS",Ancestors=["Wales","Powys"]},response.RootElement).Single().UniqueWithinContext,"Exact place plus matching county/constituent context resolves deterministically.");
|
||||
Check(NominatimGeocodingProvider.Parse(query!,response.RootElement).Count==0,"Reject results outside explicit subdivision.");
|
||||
}
|
||||
var denied=new GeographyController(null!,new DeniedAccess(),null!,null!,null!);
|
||||
Check(await denied.State(7,null) is NotFoundResult,"Cross-account state rejected before repository.");
|
||||
Check(await denied.Confirm(7,1,1,0) is NotFoundResult,"Cross-account coordinate confirmation rejected.");
|
||||
Check(await denied.Retry(7,1,1) is NotFoundResult,"Cross-account retries rejected.");
|
||||
Check(await denied.Exclude(7,1,1,true) is NotFoundResult,"Cross-account exclusion rejected.");
|
||||
Check(await denied.Hierarchy(7,1,null!) is NotFoundResult,"Cross-account hierarchy admission rejected.");
|
||||
Check(typeof(GeographyController).GetMethods().Where(m=>m.IsDefined(typeof(HttpPostAttribute),true))
|
||||
.All(m=>m.IsDefined(typeof(ValidateAntiForgeryTokenAttribute),true)),"Every geography mutation requires antiforgery.");
|
||||
var settings=new MonitorFake();var transport=new HttpFake();var nominatim=new NominatimGeocodingProvider(settings,transport);
|
||||
Check(!nominatim.Enabled,"No external provider is enabled by default.");
|
||||
settings.Value=new(){Enabled=true,Provider="Nominatim",WorkerHost=Environment.MachineName,UserAgent="PlotDirector/1.0 (+https://plotdirector.test/)"};
|
||||
Check(nominatim.Enabled && nominatim.MinimumInterval.TotalSeconds>=15,"Designated worker and stricter public rate.");
|
||||
await nominatim.SearchAsync(query!,default);
|
||||
Check(transport.Calls==1&&transport.LastUri!.Contains("countrycodes=gb")&&transport.LastUri.Contains("Rubery")&&transport.UserAgent!.StartsWith("PlotDirector/"),"Central proxy sends only bounded place/context query and identifying User-Agent.");
|
||||
settings.Value.Enabled=false;Check(!nominatim.Enabled,"Configuration disables requests without redeployment.");
|
||||
settings.Value.Enabled=true;settings.Value.WorkerHost="another-host";Check(!nominatim.Enabled,"Other machines cannot send public requests.");
|
||||
settings.Value.WorkerHost=Environment.MachineName;settings.Value.Provider="Disabled";Check(!nominatim.Enabled,"Provider configuration can switch off Nominatim.");
|
||||
Console.WriteLine("PASS geography roots, hierarchy, provider-independent fake, cache identities, ambiguity, failures/backoff and rate reservation.");
|
||||
}
|
||||
sealed class DeniedAccess:IProjectAccessService
|
||||
{
|
||||
public Task<bool> CanAccessProjectAsync(int id)=>Task.FromResult(false);
|
||||
public Task<bool> CanOwnProjectAsync(int id)=>Task.FromResult(false);
|
||||
public Task<bool> CanAccessEntityAsync(string type,int id)=>Task.FromResult(false);
|
||||
}
|
||||
sealed class MonitorFake:IOptionsMonitor<GeocodingOptions>
|
||||
{
|
||||
public GeocodingOptions Value=new();public GeocodingOptions CurrentValue=>Value;
|
||||
public GeocodingOptions Get(string? name)=>Value;
|
||||
public IDisposable? OnChange(Action<GeocodingOptions,string?> listener)=>null;
|
||||
}
|
||||
sealed class HttpFake:HttpMessageHandler,IHttpClientFactory
|
||||
{
|
||||
public int Calls;public string? LastUri,UserAgent;
|
||||
public HttpClient CreateClient(string name)=>new(this,false);
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken ct)
|
||||
{Calls++;LastUri=request.RequestUri!.ToString();UserAgent=request.Headers.UserAgent.ToString();return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent("[]")});}
|
||||
}
|
||||
sealed class ProviderFake(IReadOnlyList<GeographicCandidate> results):IGeocodingProvider
|
||||
{
|
||||
public string Name=>"Fake"; public bool IsEnabled=true;public bool Enabled=>IsEnabled;public TimeSpan MinimumInterval=>TimeSpan.FromSeconds(1);
|
||||
public IReadOnlyList<GeographicCandidate> Results=results;public int Calls;public bool Fail;
|
||||
public Task<IReadOnlyList<GeographicCandidate>> SearchAsync(GeographicQuery q,CancellationToken ct){Calls++;if(Fail)throw new IOException("Synthetic failure");return Task.FromResult(Results);}
|
||||
}
|
||||
sealed class QueueFake(IReadOnlyList<LocationItem> chain):IGeographicQueue
|
||||
{
|
||||
public GeographicJob Job=new(){LocationID=1,Generation=1,Lease=Guid.NewGuid()};public IReadOnlyList<LocationItem> Chain=chain;
|
||||
public string? Status,State,Cached,Match;public int Delay;public bool AllowReservation=true;bool ready=true;
|
||||
public void Requeue(){ready=true;Job.Lease=Guid.NewGuid();}
|
||||
public Task<GeographicJob?> ClaimAsync(bool enabled){if(!ready)return Task.FromResult<GeographicJob?>(null);ready=false;return Task.FromResult<GeographicJob?>(Job);}
|
||||
public Task<IReadOnlyList<LocationItem>> ChainAsync(int id)=>Task.FromResult(Chain);
|
||||
public Task<string?> CacheAsync(string key)=>Task.FromResult(Cached);
|
||||
public Task<bool> ReserveAsync(string provider,TimeSpan interval,string key,Guid lease)=>Task.FromResult(AllowReservation);
|
||||
public Task ReleaseAsync(Guid lease,int cooldownSeconds=0)=>Task.CompletedTask;
|
||||
public Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0)
|
||||
{Status=status;State=jobState;Match=match;Delay=delay;if(candidates!=null)Cached=candidates;ready=jobState=="Queued";return Task.CompletedTask;}
|
||||
}
|
||||
}
|
||||
@ -15,6 +15,8 @@ using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.ViewModels;
|
||||
|
||||
if(args.Contains("--geography-database")){await GeographyDatabaseTests.Run();return;}
|
||||
if(args.Contains("--geography")){await GeographyTests.Run();return;}
|
||||
if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev")||args.Contains("--chapter-incremental-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync-dev")){await ChapterSyncDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;}
|
||||
@ -151,6 +153,7 @@ if(args.Contains("--native-companion")){await NativeCompanionTests.Run();Console
|
||||
|
||||
var tests = new (string Name, Action Test)[]
|
||||
{
|
||||
("Geographical roots, providers, queue outcomes and access", () => GeographyTests.Run().GetAwaiter().GetResult()),
|
||||
("Intent evidence preserves provenance and author control", () => IntentAssessmentTests.Run().GetAwaiter().GetResult()),
|
||||
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
|
||||
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
|
||||
|
||||
96
PlotLine.Tests/Sql/253_LocationGeographyRegression.sql
Normal file
96
PlotLine.Tests/Sql/253_LocationGeographyRegression.sql
Normal file
@ -0,0 +1,96 @@
|
||||
-- Development only. All fixtures, cache and queue effects roll back.
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
IF DB_NAME()<>'PlotDirector_Development' THROW 51000,'Development only.',1;
|
||||
BEGIN TRANSACTION;
|
||||
BEGIN TRY
|
||||
DECLARE @User int=(SELECT TOP(1) UserID FROM dbo.AppUser ORDER BY UserID),@Name nvarchar(200)=CONCAT('Geography rollback fixture ',NEWID());
|
||||
EXEC dbo.Project_Save @ProjectName=@Name,@UserID=@User;
|
||||
DECLARE @Project int=(SELECT ProjectID FROM dbo.Projects WHERE ProjectName=@Name);
|
||||
DECLARE @Country int=(SELECT LocationTypeID FROM dbo.LocationTypes WHERE TypeName='Country'),@Town int=(SELECT LocationTypeID FROM dbo.LocationTypes WHERE TypeName='Town');
|
||||
INSERT dbo.Locations(ProjectID,LocationName,LocationTypeID)VALUES(@Project,'England',@Country);
|
||||
DECLARE @Root int=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,ParentLocationID,LocationName,LocationTypeID)VALUES(@Project,@Root,'Rubery',@Town);
|
||||
DECLARE @Child int=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,LocationName,LocationTypeID)VALUES(@Project,'Scotland',@Country);
|
||||
DECLARE @Sibling int=SCOPE_IDENTITY();
|
||||
IF EXISTS(SELECT 1 FROM dbo.LocationGeography WHERE LocationID=@Child AND JobState='Queued') THROW 51000,'Creation triggered geocoding',1;
|
||||
IF (SELECT COUNT(*) FROM dbo.LocationGeography WHERE LocationID=@Child)<>1 THROW 51000,'Durable deduplication failed',1;
|
||||
DECLARE @Generation bigint=(SELECT Generation FROM dbo.LocationGeography WHERE LocationID=@Child);
|
||||
UPDATE dbo.Locations SET Description='Private story text never sent to gazetteer' WHERE LocationID=@Root;
|
||||
IF (SELECT Generation FROM dbo.LocationGeography WHERE LocationID=@Child)<>@Generation THROW 51000,'Unrelated change invalidated geography',1;
|
||||
UPDATE dbo.Locations SET LocationName='Wales' WHERE LocationID=@Root;
|
||||
IF (SELECT Generation FROM dbo.LocationGeography WHERE LocationID=@Child)<>@Generation+1 THROW 51000,'Ancestor rename did not invalidate descendant',1;
|
||||
IF (SELECT Generation FROM dbo.LocationGeography WHERE LocationID=@Sibling)<>1 THROW 51000,'Sibling invalidated unnecessarily',1;
|
||||
UPDATE dbo.Locations SET ParentLocationID=@Sibling WHERE LocationID=@Child;
|
||||
IF (SELECT Generation FROM dbo.LocationGeography WHERE LocationID=@Child)<>@Generation+2 THROW 51000,'Reparent did not invalidate',1;
|
||||
UPDATE dbo.LocationGeography SET JobState='Done'; -- Rollback-only isolation from pre-existing jobs.
|
||||
UPDATE dbo.LocationGeography SET JobState='Queued' WHERE LocationID=@Child;
|
||||
DECLARE @Jobs table(LocationID int,Generation bigint,Attempts int,Lease uniqueidentifier);
|
||||
INSERT @Jobs EXEC dbo.Geography_Claim @Enabled=1;
|
||||
IF (SELECT COUNT(*) FROM @Jobs)<>1 THROW 51000,'Claim failed',1;
|
||||
DECLARE @Lease uniqueidentifier=(SELECT Lease FROM @Jobs),@Current bigint=(SELECT Generation FROM @Jobs);
|
||||
DELETE @Jobs;
|
||||
INSERT @Jobs EXEC dbo.Geography_Claim @Enabled=1;
|
||||
IF EXISTS(SELECT 1 FROM @Jobs) THROW 51000,'Duplicate job claimed',1;
|
||||
UPDATE dbo.LocationGeography SET LeaseUntil=DATEADD(minute,-1,SYSUTCDATETIME()) WHERE LocationID=@Child;
|
||||
INSERT @Jobs EXEC dbo.Geography_Claim @Enabled=1;
|
||||
IF (SELECT Lease FROM @Jobs)=@Lease THROW 51000,'Restart recovery did not replace lease',1;
|
||||
DECLARE @Candidates nvarchar(max)=N'[{"Provider":"Fake","PlaceID":"fake-1","Name":"Rubery","Latitude":52.39,"Longitude":-2.01,"CountryCode":"GB","AdministrativeNames":["England"],"Attribution":"Synthetic regression fixture","UniqueWithinContext":false}]';
|
||||
EXEC dbo.Geography_Complete @LocationID=@Child,@Generation=@Current,@Lease=@Lease,@Status='Resolved',@JobState='Done',@MatchJson=@Candidates;
|
||||
IF (SELECT Status FROM dbo.LocationGeography WHERE LocationID=@Child)<>'Pending' THROW 51000,'Expired lease overwrote state',1;
|
||||
SET @Lease=(SELECT Lease FROM @Jobs);
|
||||
DECLARE @Key char(64)=REPLICATE('f',64);
|
||||
EXEC dbo.Geography_Complete @LocationID=@Child,@Generation=@Current,@Lease=@Lease,@Status='Needs confirmation',@JobState='Done',@CandidatesJson=@Candidates,@RequestKey=@Key;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.GeographicCache WHERE RequestKey=@Key AND CandidatesJson=@Candidates) THROW 51000,'Cache did not persist public provider identities',1;
|
||||
DECLARE @Denied bit=0;
|
||||
BEGIN TRY
|
||||
EXEC dbo.Geography_Choose @ProjectID=@Project,@UserID=-2147483647,@LocationID=@Child,@Generation=@Current,@CandidateIndex=0;
|
||||
END TRY BEGIN CATCH
|
||||
IF ERROR_NUMBER()=51000 SET @Denied=1; ELSE THROW;
|
||||
END CATCH;
|
||||
-- Permission errors can doom an XACT_ABORT transaction; test successful workflow in a fresh rollback below.
|
||||
IF @Denied=0 THROW 51000,'Cross-account confirmation accepted',1;
|
||||
IF XACT_STATE()=-1 BEGIN ROLLBACK; SELECT 'PASS trigger invalidation, durable claim/deduplication, restart leases, stale rejection, public cache and cross-account confirmation rejection'; RETURN; END;
|
||||
ROLLBACK;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF XACT_STATE()<>0 ROLLBACK;
|
||||
THROW;
|
||||
END CATCH;
|
||||
GO
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
BEGIN TRANSACTION;
|
||||
BEGIN TRY
|
||||
DECLARE @User int=(SELECT TOP(1) UserID FROM dbo.AppUser ORDER BY UserID),@Name nvarchar(200)=CONCAT('Geography confirmation fixture ',NEWID());
|
||||
EXEC dbo.Project_Save @ProjectName=@Name,@UserID=@User;
|
||||
DECLARE @Project int=(SELECT ProjectID FROM dbo.Projects WHERE ProjectName=@Name);
|
||||
INSERT dbo.Locations(ProjectID,LocationName)VALUES(@Project,'Fixture');
|
||||
DECLARE @Location int=SCOPE_IDENTITY(),@Candidates nvarchar(max)=N'[{"Provider":"Fake","PlaceID":"fake-1","Name":"Rubery","Latitude":52.39,"Longitude":-2.01,"CountryCode":"GB","AdministrativeNames":["England"],"Attribution":"Synthetic regression fixture"}]';
|
||||
UPDATE dbo.LocationGeography SET Status='Needs confirmation',JobState='Done',CandidatesJson=@Candidates WHERE LocationID=@Location;
|
||||
EXEC dbo.Geography_Choose @ProjectID=@Project,@UserID=@User,@LocationID=@Location,@Generation=1,@CandidateIndex=0;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.LocationGeography WHERE LocationID=@Location AND Confirmed=1 AND Status='Resolved' AND JSON_VALUE(MatchJson,'$.PlaceID')='fake-1') THROW 51000,'Confirmation failed',1;
|
||||
UPDATE dbo.Locations SET Description='Preserve author choice' WHERE LocationID=@Location;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.LocationGeography WHERE LocationID=@Location AND Confirmed=1) THROW 51000,'Confirmation lost on unrelated edit',1;
|
||||
EXEC dbo.Geography_Exclude @ProjectID=@Project,@UserID=@User,@LocationID=@Location,@Generation=1,@IsExcluded=1;
|
||||
UPDATE dbo.Locations SET LocationName='Renamed excluded fixture' WHERE LocationID=@Location;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.LocationGeography WHERE LocationID=@Location AND IsExcluded=1 AND JobState='Done' AND Status='Not eligible') THROW 51000,'Excluded location requeued',1;
|
||||
DECLARE @Generation bigint=(SELECT Generation FROM dbo.LocationGeography WHERE LocationID=@Location);
|
||||
EXEC dbo.Geography_Exclude @ProjectID=@Project,@UserID=@User,@LocationID=@Location,@Generation=@Generation,@IsExcluded=0;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.LocationGeography WHERE LocationID=@Location AND JobState='Awaiting hierarchy request' AND Confirmed=0 AND MatchJson IS NULL) THROW 51000,'Reinclusion failed',1;
|
||||
DECLARE @Gate table(Allowed bit);
|
||||
DECLARE @Lease uniqueidentifier=NEWID(),@Key char(64)=REPLICATE('e',64);
|
||||
INSERT @Gate EXEC dbo.Geography_Reserve @Provider='FakeRegression',@IntervalMs=1000,@RequestKey=@Key,@Lease=@Lease;
|
||||
IF (SELECT Allowed FROM @Gate)<>1 THROW 51000,'First rate reservation failed',1;
|
||||
DELETE @Gate;
|
||||
INSERT @Gate EXEC dbo.Geography_Reserve @Provider='FakeRegression',@IntervalMs=1000,@RequestKey=@Key,@Lease=@Lease;
|
||||
IF (SELECT Allowed FROM @Gate)<>0 THROW 51000,'Repeated rate reservation accepted',1;
|
||||
ROLLBACK;
|
||||
SELECT 'PASS author confirmation/preservation, exclusion/reinclusion, provider reservation and duplicate lookup lease';
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF XACT_STATE()<>0 ROLLBACK;
|
||||
THROW;
|
||||
END CATCH;
|
||||
GO
|
||||
SELECT DB_NAME() VerifiedDatabase;
|
||||
SELECT COUNT(*) GeographyProcedureCount FROM sys.procedures WHERE name LIKE 'Geography[_]%';
|
||||
@ -0,0 +1,31 @@
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
IF DB_NAME()<>'PlotDirector_Development' THROW 51000,'Development only.',1;
|
||||
BEGIN TRANSACTION;
|
||||
BEGIN TRY
|
||||
DECLARE @User int=(SELECT TOP(1) UserID FROM dbo.AppUser ORDER BY UserID),@Name nvarchar(200)=CONCAT('Hierarchy event fixture ',NEWID());
|
||||
EXEC dbo.Project_Save @ProjectName=@Name,@UserID=@User;
|
||||
DECLARE @Project int=(SELECT ProjectID FROM dbo.Projects WHERE ProjectName=@Name);
|
||||
INSERT dbo.Locations(ProjectID,LocationName)VALUES(@Project,'United Kingdom');
|
||||
DECLARE @Root int=SCOPE_IDENTITY();
|
||||
INSERT dbo.Locations(ProjectID,ParentLocationID,LocationName)VALUES(@Project,@Root,'Birmingham');
|
||||
DECLARE @Child int=SCOPE_IDENTITY();
|
||||
IF EXISTS(SELECT 1 FROM dbo.LocationGeography WHERE LocationID IN(@Root,@Child) AND JobState<>'Awaiting hierarchy request') THROW 51000,'Creation enqueued lookup',1;
|
||||
UPDATE dbo.Locations SET LocationName='England' WHERE LocationID=@Root;
|
||||
IF EXISTS(SELECT 1 FROM dbo.LocationGeography WHERE LocationID=@Child AND JobState<>'Awaiting hierarchy request') THROW 51000,'Rename enqueued lookup',1;
|
||||
DECLARE @Generation bigint=(SELECT Generation FROM dbo.LocationGeography WHERE LocationID=@Root);
|
||||
EXEC dbo.Geography_SubmitHierarchy @ProjectID=@Project,@UserID=@User,@LocationID=@Root,@Generation=@Generation;
|
||||
IF (SELECT COUNT(*) FROM dbo.LocationGeography WHERE LocationID IN(@Root,@Child) AND JobState='Queued')<>2 THROW 51000,'Explicit hierarchy request did not queue finite scope',1;
|
||||
IF (SELECT COUNT(*) FROM dbo.GeographicAuthorBatch WHERE UserID=@User)<>1 THROW 51000,'Batch admission missing',1;
|
||||
DECLARE @Denied bit=0;
|
||||
BEGIN TRY
|
||||
EXEC dbo.Geography_SubmitHierarchy @ProjectID=@Project,@UserID=@User,@LocationID=@Root,@Generation=@Generation;
|
||||
END TRY BEGIN CATCH
|
||||
IF ERROR_NUMBER()=51000 SET @Denied=1; ELSE THROW;
|
||||
END CATCH;
|
||||
IF @Denied=0 THROW 51000,'Author batch quota bypassed',1;
|
||||
IF XACT_STATE()<>0 ROLLBACK;
|
||||
SELECT 'PASS creation and rename do not geocode; explicit hierarchy event queues finite branch; repeat author batches rejected';
|
||||
END TRY BEGIN CATCH
|
||||
IF XACT_STATE()<>0 ROLLBACK;
|
||||
THROW;
|
||||
END CATCH;
|
||||
@ -543,7 +543,7 @@ internal static class ToolbarBrowserHost
|
||||
Project = model.Project!, Maps = [map], Document = new MapDocument { Map = map },
|
||||
Locations = [new LocationItem { LocationID = 11, ProjectID = 7, LocationName = "Harbour town" }, new LocationItem { LocationID = 12, ProjectID = 7, LocationName = "Hill village" }]
|
||||
});
|
||||
surface += "<script src='/js/application-dialogs.js'></script><script src='/js/workspace-surface.js'></script><script src='/js/maps-symbols.js'></script><script src='/js/workspace-bridge.js'></script><script src='/js/maps-engine.js'></script><script src='/js/maps-appearance-engine.js'></script><script src='/js/maps-workspace.js'></script><script src='/js/maps-appearance.js'></script><script src='/js/maps-story-engine.js'></script><script src='/js/maps-story.js'></script>";
|
||||
surface += "<script src='/js/application-dialogs.js'></script><script src='/js/workspace-surface.js'></script><script src='/js/maps-symbols.js'></script><script src='/js/workspace-bridge.js'></script><script src='/js/maps-engine.js'></script><script src='/js/maps-appearance-engine.js'></script><script src='/js/maps-geography-engine.js'></script><script src='/js/maps-workspace.js'></script><script src='/js/maps-appearance.js'></script><script src='/js/maps-story-engine.js'></script><script src='/js/maps-story.js'></script>";
|
||||
}
|
||||
if (context.Request.Query["page"] == "floorplans")
|
||||
{
|
||||
|
||||
70
PlotLine/Controllers/GeographyController.cs
Normal file
70
PlotLine/Controllers/GeographyController.cs
Normal file
@ -0,0 +1,70 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services;
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize]
|
||||
public sealed class GeographyController(GeographyRepository repository,IProjectAccessService access,ICurrentUserService currentUser,GeographicRules rules,ILocationRepository locations) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> State(int projectId,int? locationId)
|
||||
{
|
||||
if(!await access.CanAccessProjectAsync(projectId)) return NotFound();
|
||||
Response.Headers.CacheControl="private, no-store";
|
||||
var states=await repository.GetAsync(projectId,currentUser.UserId!.Value,locationId);
|
||||
if(states.Any(s=>s.Status=="Pending"))
|
||||
{
|
||||
var projectLocations=(await locations.ListByProjectAsync(projectId)).ToDictionary(l=>l.LocationID);
|
||||
foreach(var state in states.Where(s=>s.Status=="Pending"))
|
||||
{
|
||||
var chain=new List<PlotLine.Models.LocationItem>();
|
||||
var visited=new HashSet<int>();var id=state.LocationID;
|
||||
while(projectLocations.TryGetValue(id,out var place)&&visited.Add(id)&&chain.Count<=100)
|
||||
{
|
||||
chain.Add(place);
|
||||
if(place.ParentLocationID is not int parent)break;
|
||||
id=parent;
|
||||
}
|
||||
if(rules.Query(chain) is null)
|
||||
{
|
||||
state.Status="Not eligible";
|
||||
state.Message="Use geographical types beneath a recognised country or qualified region.";
|
||||
}
|
||||
}
|
||||
}
|
||||
return Json(states);
|
||||
}
|
||||
[HttpPost,ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Confirm(int projectId,int locationId,long generation,int candidateIndex)
|
||||
{
|
||||
if(!await access.CanAccessProjectAsync(projectId)) return NotFound();
|
||||
if(!ModelState.IsValid || candidateIndex is <0 or >9) return BadRequest();
|
||||
try { await repository.ChooseAsync(projectId,currentUser.UserId!.Value,locationId,generation,candidateIndex); return Json(new {ok=true}); }
|
||||
catch(SqlException ex) when(ex.Number==51000) { return Conflict(new {message=ex.Message}); }
|
||||
}
|
||||
[HttpPost,ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Retry(int projectId,int locationId,long generation,bool replaceConfirmed=false)
|
||||
{
|
||||
if(!await access.CanAccessProjectAsync(projectId)) return NotFound();
|
||||
if(!ModelState.IsValid) return BadRequest();
|
||||
try { await repository.RetryAsync(projectId,currentUser.UserId!.Value,locationId,generation,replaceConfirmed); return Json(new {ok=true}); }
|
||||
catch(SqlException ex) when(ex.Number==51000) { return Conflict(new {message=ex.Message}); }
|
||||
}
|
||||
[HttpPost,ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Exclude(int projectId,int locationId,long generation,bool isExcluded)
|
||||
{
|
||||
if(!await access.CanAccessProjectAsync(projectId)) return NotFound();
|
||||
if(!ModelState.IsValid) return BadRequest();
|
||||
try { await repository.ExcludeAsync(projectId,currentUser.UserId!.Value,locationId,generation,isExcluded); return Json(new {ok=true}); }
|
||||
catch(SqlException ex) when(ex.Number==51000) { return Conflict(new {message=ex.Message}); }
|
||||
}
|
||||
[HttpPost,ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Hierarchy(int projectId,int locationId,[FromServices] GeographicHierarchyService hierarchy)
|
||||
{
|
||||
if(!await access.CanAccessProjectAsync(projectId)) return NotFound();
|
||||
if(!ModelState.IsValid) return BadRequest();
|
||||
return Json(new {message=await hierarchy.SubmitAsync(projectId,locationId)});
|
||||
}
|
||||
}
|
||||
@ -6,7 +6,7 @@ using PlotLine.ViewModels;
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize]
|
||||
public sealed class LocationsController(ILocationService locations) : Controller
|
||||
public sealed class LocationsController(ILocationService locations, GeographicHierarchyService geography) : Controller
|
||||
{
|
||||
public async Task<IActionResult> Index(int projectId)
|
||||
{
|
||||
@ -75,6 +75,7 @@ public sealed class LocationsController(ILocationService locations) : Controller
|
||||
try
|
||||
{
|
||||
await locations.ReparentAsync(projectId, locationId, parentLocationId, expectedParentLocationId);
|
||||
TempData["GeographyMessage"] = await geography.SubmitAsync(projectId, locationId);
|
||||
if (IsAjaxRequest())
|
||||
{
|
||||
var model = await locations.GetLocationsAsync(projectId);
|
||||
@ -115,7 +116,10 @@ public sealed class LocationsController(ILocationService locations) : Controller
|
||||
return View("Edit", editModel);
|
||||
}
|
||||
|
||||
var before = model.LocationID > 0 ? await locations.GetEditAsync(model.LocationID) : null;
|
||||
var locationId = await locations.SaveAsync(model);
|
||||
if (before is not null && before.ParentLocationID != model.ParentLocationID)
|
||||
TempData["LocationMessage"] = await geography.SubmitAsync(model.ProjectID, locationId);
|
||||
return RedirectToAction(nameof(Details), new { id = locationId });
|
||||
}
|
||||
|
||||
|
||||
73
PlotLine/Data/GeographyRepository.cs
Normal file
73
PlotLine/Data/GeographyRepository.cs
Normal file
@ -0,0 +1,73 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Data;
|
||||
|
||||
public interface IGeographicQueue
|
||||
{
|
||||
Task<GeographicJob?> ClaimAsync(bool enabled);
|
||||
Task<IReadOnlyList<LocationItem>> ChainAsync(int locationId);
|
||||
Task<string?> CacheAsync(string requestKey);
|
||||
Task<bool> ReserveAsync(string provider,TimeSpan interval,string requestKey,Guid lease);
|
||||
Task ReleaseAsync(Guid lease,int cooldownSeconds=0);
|
||||
Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0);
|
||||
}
|
||||
|
||||
public sealed class GeographyRepository(ISqlConnectionFactory connections) : IGeographicQueue
|
||||
{
|
||||
public async Task<IReadOnlyList<LocationGeography>> GetAsync(int projectId, int userId, int? locationId = null)
|
||||
{
|
||||
using var db = connections.CreateConnection();
|
||||
return (await db.QueryAsync<LocationGeography>("dbo.Geography_Get", new { ProjectID=projectId, UserID=userId, LocationID=locationId }, commandType:CommandType.StoredProcedure)).ToList();
|
||||
}
|
||||
public async Task<GeographicJob?> ClaimAsync(bool enabled)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
return await db.QuerySingleOrDefaultAsync<GeographicJob>("dbo.Geography_Claim",new { Enabled=enabled },commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task<IReadOnlyList<LocationItem>> ChainAsync(int locationId)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
return (await db.QueryAsync<LocationItem>("dbo.Geography_Chain",new {LocationID=locationId},commandType:CommandType.StoredProcedure)).ToList();
|
||||
}
|
||||
public async Task<string?> CacheAsync(string requestKey)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
return await db.QuerySingleOrDefaultAsync<string>("dbo.Geography_Cache",new {RequestKey=requestKey},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task<bool> ReserveAsync(string provider,TimeSpan interval,string requestKey,Guid lease)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
return await db.QuerySingleAsync<bool>("dbo.Geography_Reserve",new {Provider=provider,RequestKey=requestKey,Lease=lease,IntervalMs=(int)Math.Clamp(interval.TotalMilliseconds,0,86400000)},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task CompleteAsync(GeographicJob job,string status,string jobState,string? key=null,string? candidates=null,string? match=null,string? message=null,bool failure=false,int delay=0)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
await db.ExecuteAsync("dbo.Geography_Complete",new {job.LocationID,job.Generation,job.Lease,Status=status,JobState=jobState,RequestKey=key,CandidatesJson=candidates,MatchJson=match,Message=message,Failure=failure,DelaySeconds=delay},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task ChooseAsync(int projectId,int userId,int locationId,long generation,int candidateIndex)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
await db.ExecuteAsync("dbo.Geography_Choose",new {ProjectID=projectId,UserID=userId,LocationID=locationId,Generation=generation,CandidateIndex=candidateIndex},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task RetryAsync(int projectId,int userId,int locationId,long generation,bool replaceConfirmed=false)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
await db.ExecuteAsync("dbo.Geography_Retry",new {ProjectID=projectId,UserID=userId,LocationID=locationId,Generation=generation,ReplaceConfirmed=replaceConfirmed},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task ExcludeAsync(int projectId,int userId,int locationId,long generation,bool isExcluded)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
await db.ExecuteAsync("dbo.Geography_Exclude",new {ProjectID=projectId,UserID=userId,LocationID=locationId,Generation=generation,IsExcluded=isExcluded},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task SubmitAsync(int projectId,int userId,int locationId,long generation)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
await db.ExecuteAsync("dbo.Geography_SubmitHierarchy",new {ProjectID=projectId,UserID=userId,LocationID=locationId,Generation=generation},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
public async Task ReleaseAsync(Guid lease,int cooldownSeconds=0)
|
||||
{
|
||||
using var db=connections.CreateConnection();
|
||||
await db.ExecuteAsync("dbo.Geography_ProviderRelease",new {Lease=lease,CooldownSeconds=cooldownSeconds},commandType:CommandType.StoredProcedure);
|
||||
}
|
||||
}
|
||||
34
PlotLine/Data/Reference/Geography/COPYRIGHT.txt
Normal file
34
PlotLine/Data/Reference/Geography/COPYRIGHT.txt
Normal file
@ -0,0 +1,34 @@
|
||||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Upstream-Name: iso-codes
|
||||
Upstream-Contact: Dr. Tobias Quathamer <toddy@debian.org>
|
||||
Source: https://salsa.debian.org/iso-codes-team/iso-codes
|
||||
|
||||
Files: *
|
||||
Copyright: © 2001-2008 Alastair McKinstry
|
||||
© 2004-2016 Christian Perrier
|
||||
© 2005-2026 Dr. Tobias Quathamer
|
||||
License: LGPL-2.1+
|
||||
This package is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
.
|
||||
This package is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
.
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, see <https://www.gnu.org/licenses/>.
|
||||
.
|
||||
On Debian systems, the full text of the GNU Lesser General
|
||||
Public License version 2.1 can be found in the file
|
||||
`/usr/share/common-licenses/LGPL-2.1'.
|
||||
|
||||
Files: scripts/remove-potcdate.sin
|
||||
Copyright: © 2002 Free Software Foundation, Inc.
|
||||
License: FSFAP
|
||||
Copying and distribution of this file, with or without modification,
|
||||
are permitted in any medium without royalty provided the copyright
|
||||
notice and this notice are preserved. This file is offered as-is,
|
||||
without any warranty.
|
||||
501
PlotLine/Data/Reference/Geography/LICENSE.txt
Normal file
501
PlotLine/Data/Reference/Geography/LICENSE.txt
Normal file
@ -0,0 +1,501 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
<https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||
|
||||
<signature of Moe Ghoul>, 1 April 1990
|
||||
Moe Ghoul, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
7
PlotLine/Data/Reference/Geography/README.md
Normal file
7
PlotLine/Data/Reference/Geography/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# ISO geographical roots
|
||||
|
||||
These are eligibility reference names/codes only, not a coordinate gazetteer.
|
||||
Snapshots copied from Debian's `/usr/share/iso-codes/json/iso_3166-1.json` and `iso_3166-2.json` on 13 November 2026.
|
||||
Upstream: https://salsa.debian.org/iso-codes-team/iso-codes
|
||||
See COPYRIGHT.txt for authorship and licensing. Preserve it on redistribution.
|
||||
To update, replace the two reference JSON files from a reviewed upstream release and run `--geography` and the ordinary regression harness.
|
||||
1931
PlotLine/Data/Reference/Geography/countries.json
Normal file
1931
PlotLine/Data/Reference/Geography/countries.json
Normal file
File diff suppressed because it is too large
Load Diff
26690
PlotLine/Data/Reference/Geography/subdivisions.json
Normal file
26690
PlotLine/Data/Reference/Geography/subdivisions.json
Normal file
File diff suppressed because it is too large
Load Diff
24
PlotLine/Models/GeographyModels.cs
Normal file
24
PlotLine/Models/GeographyModels.cs
Normal file
@ -0,0 +1,24 @@
|
||||
namespace PlotLine.Models;
|
||||
|
||||
public sealed record GeographicRoot(string CountryCode, string? SubdivisionCode = null);
|
||||
public sealed record GeographicQuery(string Name, string CountryCode, string? SubdivisionCode, string[] Ancestors);
|
||||
public sealed record GeographicCandidate(string Provider, string PlaceID, string Name, double Latitude, double Longitude,
|
||||
string CountryCode, string[] AdministrativeNames, string Attribution, bool UniqueWithinContext = false);
|
||||
public sealed class LocationGeography
|
||||
{
|
||||
public int LocationID { get; set; }
|
||||
public long Generation { get; set; }
|
||||
public string Status { get; set; } = "Pending";
|
||||
public string? CandidatesJson { get; set; }
|
||||
public string? MatchJson { get; set; }
|
||||
public bool Confirmed { get; set; }
|
||||
public bool IsExcluded { get; set; }
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
public sealed class GeographicJob
|
||||
{
|
||||
public int LocationID { get; set; }
|
||||
public Guid Lease { get; set; }
|
||||
public long Generation { get; set; }
|
||||
public int Attempts { get; set; }
|
||||
}
|
||||
@ -23,6 +23,14 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Update="Data/Reference/Geography/*.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</Content>
|
||||
<Content Include="Data/Reference/Geography/*.txt">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</Content>
|
||||
<Content Include="Docs\AI\**\*">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
|
||||
@ -169,6 +169,17 @@ public class Program
|
||||
builder.Services.AddScoped<ILocationRepository, LocationRepository>();
|
||||
builder.Services.AddScoped<IFloorPlanRepository, FloorPlanRepository>();
|
||||
builder.Services.AddScoped<MapRepository>();
|
||||
builder.Services.AddScoped<GeographyRepository>();
|
||||
builder.Services.AddScoped<IGeographicQueue>(sp=>sp.GetRequiredService<GeographyRepository>());
|
||||
builder.Services.AddSingleton(new GeographicRules(Path.Combine(builder.Environment.ContentRootPath, "Data", "Reference", "Geography")));
|
||||
builder.Services.Configure<GeocodingOptions>(builder.Configuration.GetSection("Geography"));
|
||||
builder.Services.AddHttpClient("Geocoding", client=>client.Timeout=TimeSpan.FromSeconds(25))
|
||||
.RemoveAllLoggers()
|
||||
.ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler { AllowAutoRedirect=false });
|
||||
builder.Services.AddSingleton<IGeocodingProvider, NominatimGeocodingProvider>();
|
||||
builder.Services.AddScoped<GeographicHierarchyService>();
|
||||
builder.Services.AddScoped<GeographicProcessor>();
|
||||
builder.Services.AddHostedService<GeographicWorker>();
|
||||
builder.Services.AddScoped<MapReferenceImageService>();
|
||||
builder.Services.AddScoped<IMapStoryRepository, MapStoryRepository>();
|
||||
builder.Services.AddScoped<IMapStoryService, MapStoryService>();
|
||||
|
||||
18
PlotLine/Services/GeographicHierarchyService.cs
Normal file
18
PlotLine/Services/GeographicHierarchyService.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Data;
|
||||
namespace PlotLine.Services;
|
||||
|
||||
public sealed class GeographicHierarchyService(GeographyRepository repository,GeographicRules rules,IProjectAccessService access,ICurrentUserService currentUser)
|
||||
{
|
||||
public async Task<string> SubmitAsync(int projectId,int locationId)
|
||||
{
|
||||
if(!await access.CanAccessProjectAsync(projectId))return "Project access is required.";
|
||||
var chain=await repository.ChainAsync(locationId);
|
||||
if(chain.Count==0 || chain[0].ProjectID!=projectId)return "Location is unavailable.";
|
||||
if(rules.Query(chain) is null)return "This hierarchy is not eligible for geographical lookup. Use geographical types beneath a recognised root.";
|
||||
var state=(await repository.GetAsync(projectId,currentUser.UserId!.Value,locationId)).SingleOrDefault();
|
||||
if(state is null)return "Geographical state is unavailable.";
|
||||
try {await repository.SubmitAsync(projectId,currentUser.UserId!.Value,locationId,state.Generation);return "Geographical hierarchy lookup requested (at most 20 places). External processing requires the configured provider to be enabled.";}
|
||||
catch(SqlException ex) when(ex.Number==51000){return ex.Message;}
|
||||
}
|
||||
}
|
||||
72
PlotLine/Services/GeographicResolution.cs
Normal file
72
PlotLine/Services/GeographicResolution.cs
Normal file
@ -0,0 +1,72 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using PlotLine.Models;
|
||||
|
||||
namespace PlotLine.Services;
|
||||
|
||||
// Only public geographical names enter this interface. Never pass descriptions, aliases or manuscript text.
|
||||
public interface IGeocodingProvider
|
||||
{
|
||||
string Name { get; }
|
||||
bool Enabled { get; }
|
||||
TimeSpan MinimumInterval { get; }
|
||||
Task<IReadOnlyList<GeographicCandidate>> SearchAsync(GeographicQuery query, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed class GeographicRules
|
||||
{
|
||||
private readonly Dictionary<string, GeographicRoot> roots = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static readonly HashSet<string> Types = new(StringComparer.OrdinalIgnoreCase)
|
||||
{ "Country", "Region", "State", "County", "City", "Town", "Village" };
|
||||
public GeographicRules(string referenceDirectory)
|
||||
{
|
||||
using var countries = JsonDocument.Parse(File.ReadAllText(Path.Combine(referenceDirectory, "countries.json")));
|
||||
foreach (var country in countries.RootElement.GetProperty("3166-1").EnumerateArray())
|
||||
{
|
||||
var root = new GeographicRoot(country.GetProperty("alpha_2").GetString()!);
|
||||
foreach (var key in new[] { "name", "official_name", "common_name", "alpha_3" })
|
||||
if (country.TryGetProperty(key, out var name)) roots[name.GetString()!] = root;
|
||||
}
|
||||
using var subdivisions = JsonDocument.Parse(File.ReadAllText(Path.Combine(referenceDirectory, "subdivisions.json")));
|
||||
foreach (var region in subdivisions.RootElement.GetProperty("3166-2").EnumerateArray())
|
||||
{
|
||||
var code = region.GetProperty("code").GetString()!;
|
||||
var root = new GeographicRoot(code[..2], code);
|
||||
// Explicit ISO codes and country-qualified names avoid ambiguous bare region names (e.g. Georgia).
|
||||
roots[code] = root;
|
||||
roots[$"{region.GetProperty("name").GetString()}, {code[..2]}"] = root;
|
||||
}
|
||||
roots["UK"] = roots["United Kingdom"] = new("GB");
|
||||
roots["USA"] = roots["US"] = roots["United States"] = new("US");
|
||||
roots["England"] = new("GB", "GB-ENG");
|
||||
roots["Scotland"] = new("GB", "GB-SCT");
|
||||
roots["Wales"] = new("GB", "GB-WLS");
|
||||
roots["Northern Ireland"] = new("GB", "GB-NIR");
|
||||
// Georgia alone may mean either the country or US state; require an explicit country identifier.
|
||||
roots.Remove("Georgia");
|
||||
}
|
||||
public GeographicRoot? Root(string name) => roots.GetValueOrDefault(name.Trim());
|
||||
public GeographicQuery? Query(IReadOnlyList<LocationItem> chain)
|
||||
{
|
||||
if (chain.Count == 0 || chain.Count > 100 || !Types.Contains(chain[0].LocationTypeName ?? "")) return null;
|
||||
if (chain[^1].ParentLocationID is not null) return null;
|
||||
var root = Root(chain[^1].LocationName);
|
||||
if (root is null) return null;
|
||||
// Premises and arbitrary fictional intermediate parents must never be sent to a provider.
|
||||
if (chain.Any(l => !Types.Contains(l.LocationTypeName ?? ""))) return null;
|
||||
return new(chain[0].LocationName, root.CountryCode, root.SubdivisionCode,
|
||||
chain.Skip(1).Reverse().Select(l => l.LocationName).ToArray());
|
||||
}
|
||||
public static string CacheKey(GeographicQuery query, string source = "") => Convert.ToHexString(SHA256.HashData(
|
||||
Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Source = source, Name = query.Name.Trim().ToUpperInvariant(), query.CountryCode,
|
||||
query.SubdivisionCode, Ancestors = query.Ancestors.Select(x => x.Trim().ToUpperInvariant()).ToArray() }))));
|
||||
public static IReadOnlyList<GeographicCandidate> Candidates(GeographicQuery query, IEnumerable<GeographicCandidate> candidates)
|
||||
=> candidates.Where(c => c.CountryCode.Equals(query.CountryCode, StringComparison.OrdinalIgnoreCase)
|
||||
&& !string.IsNullOrWhiteSpace(c.Provider) && !string.IsNullOrWhiteSpace(c.PlaceID)
|
||||
&& !string.IsNullOrWhiteSpace(c.Attribution) && double.IsFinite(c.Latitude) && double.IsFinite(c.Longitude)
|
||||
&& c.Latitude is >= -90 and <= 90 && c.Longitude is >= -180 and <= 180)
|
||||
.DistinctBy(c => (c.Provider, c.PlaceID)).Take(10).ToList();
|
||||
// A provider ranking or a single returned result alone does not establish uniqueness.
|
||||
// Conservative initial adapter contract: all matches require author confirmation.
|
||||
}
|
||||
95
PlotLine/Services/GeographicWorker.cs
Normal file
95
PlotLine/Services/GeographicWorker.cs
Normal file
@ -0,0 +1,95 @@
|
||||
using System.Text.Json;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services;
|
||||
|
||||
public sealed class GeographicWorker(IServiceScopeFactory scopes, ILogger<GeographicWorker> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer=new PeriodicTimer(TimeSpan.FromSeconds(30));
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope=scopes.CreateScope();
|
||||
var processor=scope.ServiceProvider.GetRequiredService<GeographicProcessor>();
|
||||
// Bounded batches also classify ineligible roots without sending any external requests.
|
||||
for(var i=0;i<20 && !stoppingToken.IsCancellationRequested;i++)
|
||||
if(!await processor.ProcessOneAsync(stoppingToken)) break;
|
||||
}
|
||||
catch(OperationCanceledException) when(stoppingToken.IsCancellationRequested) { return; }
|
||||
catch(Exception ex)
|
||||
{
|
||||
// Log codes only: provider exceptions may include private queries or credentials.
|
||||
logger.LogWarning("Geographic queue cycle failed ({ErrorType}); retrying next cycle.",ex.GetType().Name);
|
||||
}
|
||||
} while(await timer.WaitForNextTickAsync(stoppingToken));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class GeographicProcessor(IGeographicQueue repository,GeographicRules rules,IGeocodingProvider provider)
|
||||
{
|
||||
public async Task<bool> ProcessOneAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var job=await repository.ClaimAsync(provider.Enabled);
|
||||
if(job is null) return false;
|
||||
var cooldown=0;
|
||||
try
|
||||
{
|
||||
var chain=await repository.ChainAsync(job.LocationID);
|
||||
var query=rules.Query(chain);
|
||||
if(query is null)
|
||||
{
|
||||
await repository.CompleteAsync(job,"Not eligible","Done",message:"Use geographical types beneath a recognised country or qualified region.");
|
||||
return true;
|
||||
}
|
||||
var key=GeographicRules.CacheKey(query,provider.Name);
|
||||
var cached=await repository.CacheAsync(key);
|
||||
IReadOnlyList<GeographicCandidate> candidates;
|
||||
if(cached is not null) candidates=JsonSerializer.Deserialize<List<GeographicCandidate>>(cached) ?? [];
|
||||
else
|
||||
{
|
||||
if(!provider.Enabled)
|
||||
{
|
||||
await repository.CompleteAsync(job,"Pending","Waiting configuration",message:"External geographical lookup is disabled until a provider is configured.");
|
||||
return true;
|
||||
}
|
||||
if(!await repository.ReserveAsync("Geocoding.External",provider.MinimumInterval,key,job.Lease))
|
||||
{
|
||||
await repository.CompleteAsync(job,"Pending","Queued",delay:Math.Max(1,(int)Math.Ceiling(provider.MinimumInterval.TotalSeconds)));
|
||||
return false;
|
||||
}
|
||||
using var timeout=CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(30));
|
||||
candidates=await provider.SearchAsync(query,timeout.Token);
|
||||
}
|
||||
candidates=GeographicRules.Candidates(query,candidates);
|
||||
var json=JsonSerializer.Serialize(candidates);
|
||||
// Provider adapters must establish uniqueness independently of their result limit/ranking.
|
||||
var resolved=candidates.Count==1 && candidates[0].UniqueWithinContext;
|
||||
await repository.CompleteAsync(job,candidates.Count==0?"Unresolved":resolved?"Resolved":"Needs confirmation","Done",key,json,
|
||||
resolved?JsonSerializer.Serialize(candidates[0]):null,
|
||||
candidates.Count==0?"No reliable geographical match.":resolved?"Unique geographical match":"Choose a geographical match.");
|
||||
}
|
||||
catch(OperationCanceledException) when(cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// The lease expires durably; a subsequent worker recovers it.
|
||||
throw;
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
if(ex is GeocodingHttpException http)
|
||||
cooldown=http.StatusCode is 403 or 429 ? Math.Clamp((int)(http.RetryAfter?.TotalSeconds ?? 3600),900,86400) : 60;
|
||||
var exhausted=job.Attempts>=3;
|
||||
await repository.CompleteAsync(job,exhausted?"Unresolved":"Pending",exhausted?"Done":"Queued",
|
||||
message:exhausted?"Provider lookup failed after four attempts. You can retry later.":"Provider temporarily unavailable.",
|
||||
failure:true,delay:(int)Math.Pow(2,job.Attempts)*60);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await repository.ReleaseAsync(job.Lease,cooldown);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
93
PlotLine/Services/NominatimGeocodingProvider.cs
Normal file
93
PlotLine/Services/NominatimGeocodingProvider.cs
Normal file
@ -0,0 +1,93 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services;
|
||||
|
||||
public sealed class GeocodingOptions
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
public string Provider { get; set; } = "Nominatim";
|
||||
public string Endpoint { get; set; } = "https://nominatim.openstreetmap.org/search";
|
||||
public string UserAgent { get; set; } = "";
|
||||
public string WorkerHost { get; set; } = "";
|
||||
public int MinimumIntervalSeconds { get; set; } = 15;
|
||||
}
|
||||
|
||||
// Configuration comes from IOptionsMonitor: the JSON settings provider supports changes without redeployment.
|
||||
public sealed class NominatimGeocodingProvider(IOptionsMonitor<GeocodingOptions> options,IHttpClientFactory clients) : IGeocodingProvider
|
||||
{
|
||||
public string Name => "Nominatim:"+options.CurrentValue.Endpoint;
|
||||
public bool Enabled => options.CurrentValue is {Enabled:true,Provider:"Nominatim"} config
|
||||
&& string.Equals(config.WorkerHost,Environment.MachineName,StringComparison.OrdinalIgnoreCase)
|
||||
&& Valid(config);
|
||||
// All author-triggered multi-place batches use the stricter 4/minute ceiling, even when small.
|
||||
public TimeSpan MinimumInterval => TimeSpan.FromSeconds(Math.Clamp(options.CurrentValue.MinimumIntervalSeconds,15,86400));
|
||||
private static bool Valid(GeocodingOptions config) => Uri.TryCreate(config.Endpoint,UriKind.Absolute,out var uri)
|
||||
&& uri.Scheme=="https" && string.IsNullOrEmpty(uri.UserInfo) && string.IsNullOrEmpty(uri.Query)
|
||||
&& config.UserAgent.StartsWith("PlotDirector/",StringComparison.Ordinal) && config.UserAgent.Length>=25
|
||||
&& (config.UserAgent.Contains("https://",StringComparison.Ordinal)||config.UserAgent.Contains('@'));
|
||||
public async Task<IReadOnlyList<GeographicCandidate>> SearchAsync(GeographicQuery query,CancellationToken cancellationToken)
|
||||
{
|
||||
var config=options.CurrentValue;
|
||||
if(!Enabled)throw new InvalidOperationException("Geocoding is disabled or this host is not the designated worker.");
|
||||
// Only public place names and geographical ancestors, never descriptions or story content.
|
||||
var text=string.Join(", ",new[]{query.Name}.Concat(query.Ancestors.Reverse()));
|
||||
var uri=config.Endpoint+"?format=jsonv2&addressdetails=1&namedetails=1&limit=10&dedupe=1&countrycodes="
|
||||
+Uri.EscapeDataString(query.CountryCode.ToLowerInvariant())+"&accept-language=en&q="+Uri.EscapeDataString(text);
|
||||
using var request=new HttpRequestMessage(HttpMethod.Get,uri);
|
||||
request.Headers.UserAgent.ParseAdd(config.UserAgent);
|
||||
using var response=await clients.CreateClient("Geocoding").SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellationToken);
|
||||
if(!response.IsSuccessStatusCode)
|
||||
throw new GeocodingHttpException((int)response.StatusCode,
|
||||
response.Headers.RetryAfter?.Delta ?? (response.Headers.RetryAfter?.Date-DateTimeOffset.UtcNow));
|
||||
if(response.Content.Headers.ContentLength is >1_000_000)throw new InvalidDataException("Oversized provider response.");
|
||||
await using var stream=await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||
using var buffer=new MemoryStream();
|
||||
var chunk=new byte[8192];int read;
|
||||
while((read=await stream.ReadAsync(chunk,cancellationToken))>0){if(buffer.Length+read>1_000_000)throw new InvalidDataException("Oversized provider response.");buffer.Write(chunk,0,read);}
|
||||
using var json=JsonDocument.Parse(buffer.ToArray());
|
||||
return Parse(query,json.RootElement);
|
||||
}
|
||||
public static IReadOnlyList<GeographicCandidate> Parse(GeographicQuery query,JsonElement response)
|
||||
{
|
||||
if(response.ValueKind!=JsonValueKind.Array)throw new InvalidDataException("Invalid provider response.");
|
||||
var candidates=new List<GeographicCandidate>();
|
||||
var reliable=new HashSet<string>(StringComparer.Ordinal);
|
||||
static string Normalize(string value)=>string.Join(' ',value.Trim().ToUpperInvariant().Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries));
|
||||
foreach(var row in response.EnumerateArray().Take(10))
|
||||
{
|
||||
string Text(string field)=>row.TryGetProperty(field,out var value)?value.ToString():"";
|
||||
var type=Text("addresstype");
|
||||
if(type is not ("country" or "state" or "region" or "county" or "city" or "town" or "village" or "hamlet" or "suburb" or "quarter" or "neighbourhood" or "administrative"))continue;
|
||||
if(!row.TryGetProperty("address",out var address))continue;
|
||||
var country=address.TryGetProperty("country_code",out var cc)?cc.GetString()?.ToUpperInvariant():null;
|
||||
if(country!=query.CountryCode)continue;
|
||||
var admin=address.EnumerateObject().Where(p=>p.Name is not ("postcode" or "country_code" or "house_number" or "road"))
|
||||
.Select(p=>p.Value.ToString()).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
if(query.SubdivisionCode is not null && !admin.Contains(query.SubdivisionCode,StringComparer.OrdinalIgnoreCase))continue;
|
||||
if(!double.TryParse(Text("lat"),NumberStyles.Float,CultureInfo.InvariantCulture,out var lat)
|
||||
||!double.TryParse(Text("lon"),NumberStyles.Float,CultureInfo.InvariantCulture,out var lon))continue;
|
||||
var identity=Text("osm_type")+":"+Text("osm_id");
|
||||
if(identity is ":"||string.IsNullOrEmpty(Text("osm_id")))continue;
|
||||
var context=query.Ancestors.Skip(1).Select(Normalize).ToArray();
|
||||
var exactName=Normalize(Text("name"))==Normalize(query.Name);
|
||||
var contextMatches=context.All(name=>admin.Any(a=>Normalize(a)==name));
|
||||
// Require exact place name plus more identifying context than a country-only query.
|
||||
// A constituent/admin root or an additional matching ancestor supplies that context.
|
||||
if(exactName && contextMatches && (query.SubdivisionCode is not null || context.Length>0))reliable.Add(identity);
|
||||
candidates.Add(new("Nominatim",identity,Text("display_name"),lat,lon,country,admin,
|
||||
"© OpenStreetMap contributors · ODbL 1.0 · https://www.openstreetmap.org/copyright",false));
|
||||
}
|
||||
var valid=GeographicRules.Candidates(query,candidates);
|
||||
// Ranked results alone are insufficient. Never auto-select a saturated result set or multiple candidates.
|
||||
if(valid.Count==1 && response.GetArrayLength()<10 && reliable.Contains(valid[0].PlaceID))
|
||||
return new[]{valid[0] with {UniqueWithinContext=true}};
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
public sealed class GeocodingHttpException(int statusCode,TimeSpan? retryAfter) : Exception
|
||||
{
|
||||
public int StatusCode { get; } = statusCode;
|
||||
public TimeSpan? RetryAfter { get; } = retryAfter;
|
||||
}
|
||||
175
PlotLine/Sql/253_LocationGeography.sql
Normal file
175
PlotLine/Sql/253_LocationGeography.sql
Normal file
@ -0,0 +1,175 @@
|
||||
-- Forward-only geography infrastructure. No provider is enabled by this migration.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF OBJECT_ID('dbo.GeographicCache','U') IS NULL
|
||||
CREATE TABLE dbo.GeographicCache(
|
||||
RequestKey char(64) NOT NULL PRIMARY KEY,
|
||||
CandidatesJson nvarchar(max) NOT NULL CHECK(ISJSON(CandidatesJson)=1),
|
||||
ResolvedAt datetime2 NOT NULL DEFAULT SYSUTCDATETIME()
|
||||
);
|
||||
IF OBJECT_ID('dbo.LocationGeography','U') IS NULL
|
||||
CREATE TABLE dbo.LocationGeography(
|
||||
LocationID int NOT NULL PRIMARY KEY REFERENCES dbo.Locations(LocationID) ON DELETE CASCADE,
|
||||
Generation bigint NOT NULL DEFAULT 1,
|
||||
Status varchar(24) NOT NULL DEFAULT 'Pending',
|
||||
Confirmed bit NOT NULL DEFAULT 0,
|
||||
IsExcluded bit NOT NULL DEFAULT 0,
|
||||
CandidatesJson nvarchar(max) NULL,
|
||||
MatchJson nvarchar(max) NULL,
|
||||
RequestKey char(64) NULL,
|
||||
Message nvarchar(200) NULL,
|
||||
JobState varchar(24) NOT NULL DEFAULT 'Queued',
|
||||
Attempts int NOT NULL DEFAULT 0,
|
||||
NextAttempt datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),
|
||||
Lease uniqueidentifier NULL,
|
||||
LeaseUntil datetime2 NULL,
|
||||
LastRetry datetime2 NULL,
|
||||
CHECK(Status IN('Pending','Resolved','Needs confirmation','Unresolved','Not eligible'))
|
||||
);
|
||||
IF OBJECT_ID('dbo.GeographicLookupLease','U') IS NULL
|
||||
CREATE TABLE dbo.GeographicLookupLease(RequestKey char(64) NOT NULL PRIMARY KEY, Lease uniqueidentifier NOT NULL, LeaseUntil datetime2 NOT NULL);
|
||||
IF OBJECT_ID('dbo.GeographicProviderGate','U') IS NULL
|
||||
CREATE TABLE dbo.GeographicProviderGate(Provider nvarchar(100) NOT NULL PRIMARY KEY, NextRequest datetime2 NOT NULL);
|
||||
GO
|
||||
CREATE OR ALTER TRIGGER dbo.Location_GeographyChanged ON dbo.Locations AFTER INSERT, UPDATE AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF NOT (UPDATE(LocationName) OR UPDATE(ParentLocationID) OR UPDATE(LocationTypeID) OR UPDATE(IsArchived)) RETURN;
|
||||
;WITH Changed AS (
|
||||
SELECT i.LocationID FROM inserted i LEFT JOIN deleted d ON d.LocationID=i.LocationID
|
||||
WHERE d.LocationID IS NULL OR i.LocationName<>d.LocationName OR ISNULL(i.ParentLocationID,0)<>ISNULL(d.ParentLocationID,0)
|
||||
OR ISNULL(i.LocationTypeID,0)<>ISNULL(d.LocationTypeID,0) OR i.IsArchived<>d.IsArchived
|
||||
), Descendants AS (
|
||||
SELECT LocationID FROM Changed UNION ALL
|
||||
SELECT l.LocationID FROM dbo.Locations l JOIN Descendants p ON l.ParentLocationID=p.LocationID
|
||||
)
|
||||
SELECT DISTINCT LocationID INTO #Affected FROM Descendants OPTION(MAXRECURSION 100);
|
||||
UPDATE g SET Generation=Generation+1,Status=CASE WHEN IsExcluded=1 THEN 'Not eligible' ELSE 'Pending' END,Confirmed=0,CandidatesJson=NULL,MatchJson=NULL,RequestKey=NULL,
|
||||
Message=NULL,JobState=CASE WHEN IsExcluded=1 THEN 'Done' ELSE 'Queued' END,Attempts=0,NextAttempt=SYSUTCDATETIME(),Lease=NULL,LeaseUntil=NULL
|
||||
FROM dbo.LocationGeography g JOIN #Affected a ON a.LocationID=g.LocationID;
|
||||
INSERT dbo.LocationGeography(LocationID)
|
||||
SELECT a.LocationID FROM #Affected a WHERE NOT EXISTS(SELECT 1 FROM dbo.LocationGeography g WHERE g.LocationID=a.LocationID);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Get @ProjectID int,@UserID int,@LocationID int=NULL AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
|
||||
SELECT g.LocationID,g.Generation,g.Status,g.Confirmed,g.IsExcluded,g.CandidatesJson,g.MatchJson,g.Message
|
||||
FROM dbo.LocationGeography g JOIN dbo.Locations l ON l.LocationID=g.LocationID
|
||||
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND (@LocationID IS NULL OR l.LocationID=@LocationID);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Claim @Enabled bit AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
DECLARE @Now datetime2=SYSUTCDATETIME(),@Lease uniqueidentifier=NEWID();
|
||||
;WITH job AS (SELECT TOP(1) * FROM dbo.LocationGeography WITH(UPDLOCK,READPAST,ROWLOCK)
|
||||
WHERE (JobState='Queued' OR (JobState='Waiting configuration' AND @Enabled=1) OR (JobState='Processing' AND LeaseUntil<@Now))
|
||||
AND NextAttempt<=@Now ORDER BY NextAttempt,LocationID)
|
||||
UPDATE job SET JobState='Processing',Lease=@Lease,LeaseUntil=DATEADD(minute,2,@Now)
|
||||
OUTPUT inserted.LocationID,inserted.Generation,inserted.Attempts,inserted.Lease;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Chain @LocationID int AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
;WITH chain AS (
|
||||
SELECT LocationID,ParentLocationID,ProjectID,LocationName,LocationTypeID,0 Depth FROM dbo.Locations WHERE LocationID=@LocationID AND IsArchived=0
|
||||
UNION ALL SELECT p.LocationID,p.ParentLocationID,p.ProjectID,p.LocationName,p.LocationTypeID,c.Depth+1
|
||||
FROM dbo.Locations p JOIN chain c ON c.ParentLocationID=p.LocationID AND c.ProjectID=p.ProjectID WHERE p.IsArchived=0
|
||||
) SELECT c.*,t.TypeName LocationTypeName FROM chain c LEFT JOIN dbo.LocationTypes t ON t.LocationTypeID=c.LocationTypeID
|
||||
ORDER BY Depth OPTION(MAXRECURSION 100);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Cache @RequestKey char(64) AS
|
||||
SELECT CandidatesJson FROM dbo.GeographicCache WHERE RequestKey=@RequestKey;
|
||||
GO
|
||||
-- One database-wide gate per provider. Reservation persists across workers, processes and restarts.
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Reserve @Provider nvarchar(100),@IntervalMs int,@RequestKey char(64),@Lease uniqueidentifier AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
IF @IntervalMs<0 OR @IntervalMs>86400000 THROW 51000,'Invalid provider interval.',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @Lock int;
|
||||
EXEC @Lock=sys.sp_getapplock @Resource='PlotDirector.Geography.ProviderGate',@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=1000;
|
||||
IF @Lock<0 BEGIN ROLLBACK; SELECT CAST(0 AS bit); RETURN; END;
|
||||
DECLARE @Now datetime2=SYSUTCDATETIME();
|
||||
DELETE dbo.GeographicLookupLease WHERE LeaseUntil<@Now;
|
||||
IF EXISTS(SELECT 1 FROM dbo.GeographicLookupLease WHERE RequestKey=@RequestKey)
|
||||
BEGIN COMMIT; SELECT CAST(0 AS bit); RETURN; END;
|
||||
IF EXISTS(SELECT 1 FROM dbo.GeographicProviderGate WHERE Provider=@Provider AND NextRequest>@Now)
|
||||
BEGIN COMMIT; SELECT CAST(0 AS bit); RETURN; END;
|
||||
UPDATE dbo.GeographicProviderGate SET NextRequest=DATEADD(millisecond,@IntervalMs,@Now) WHERE Provider=@Provider;
|
||||
IF @@ROWCOUNT=0 INSERT dbo.GeographicProviderGate VALUES(@Provider,DATEADD(millisecond,@IntervalMs,@Now));
|
||||
INSERT dbo.GeographicLookupLease VALUES(@RequestKey,@Lease,DATEADD(minute,2,@Now));
|
||||
COMMIT; SELECT CAST(1 AS bit);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Complete
|
||||
@LocationID int,@Generation bigint,@Lease uniqueidentifier,@Status varchar(24),@JobState varchar(24),
|
||||
@RequestKey char(64)=NULL,@CandidatesJson nvarchar(max)=NULL,@MatchJson nvarchar(max)=NULL,
|
||||
@Message nvarchar(200)=NULL,@Failure bit=0,@DelaySeconds int=0
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
BEGIN TRANSACTION;
|
||||
DELETE dbo.GeographicLookupLease WHERE Lease=@Lease;
|
||||
UPDATE dbo.LocationGeography SET Status=@Status,JobState=@JobState,RequestKey=@RequestKey,CandidatesJson=@CandidatesJson,
|
||||
MatchJson=@MatchJson,Message=@Message,Attempts=Attempts+CONVERT(int,@Failure),
|
||||
NextAttempt=DATEADD(second,@DelaySeconds,SYSUTCDATETIME()),Lease=NULL,LeaseUntil=NULL
|
||||
WHERE LocationID=@LocationID AND Generation=@Generation AND Lease=@Lease AND Confirmed=0;
|
||||
IF @@ROWCOUNT=1 AND @RequestKey IS NOT NULL AND @CandidatesJson IS NOT NULL
|
||||
BEGIN
|
||||
UPDATE dbo.GeographicCache WITH(UPDLOCK,SERIALIZABLE) SET CandidatesJson=@CandidatesJson,ResolvedAt=SYSUTCDATETIME() WHERE RequestKey=@RequestKey;
|
||||
IF @@ROWCOUNT=0 INSERT dbo.GeographicCache(RequestKey,CandidatesJson) VALUES(@RequestKey,@CandidatesJson);
|
||||
END;
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Choose
|
||||
@ProjectID int,@UserID int,@LocationID int,@Generation bigint,@CandidateIndex int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
|
||||
IF @CandidateIndex<0 OR @CandidateIndex>9 THROW 51000,'Invalid candidate.',1;
|
||||
UPDATE g SET MatchJson=JSON_QUERY(g.CandidatesJson,CONCAT('$[',@CandidateIndex,']')),Status='Resolved',Confirmed=1,
|
||||
JobState='Done',Lease=NULL,LeaseUntil=NULL,Message='Author confirmed'
|
||||
FROM dbo.LocationGeography g JOIN dbo.Locations l ON l.LocationID=g.LocationID
|
||||
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND g.LocationID=@LocationID AND g.Generation=@Generation
|
||||
AND g.Status='Needs confirmation' AND JSON_QUERY(g.CandidatesJson,CONCAT('$[',@CandidateIndex,']')) IS NOT NULL;
|
||||
IF @@ROWCOUNT<>1 THROW 51000,'Location changed. Refresh before choosing a match.',1;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Retry @ProjectID int,@UserID int,@LocationID int,@Generation bigint,@ReplaceConfirmed bit=0 AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
|
||||
UPDATE g SET Status='Pending',JobState='Queued',Attempts=0,NextAttempt=SYSUTCDATETIME(),Lease=NULL,LeaseUntil=NULL,
|
||||
Generation=Generation+1,Confirmed=0,CandidatesJson=NULL,MatchJson=NULL,Message=NULL,LastRetry=SYSUTCDATETIME()
|
||||
FROM dbo.LocationGeography g JOIN dbo.Locations l ON l.LocationID=g.LocationID
|
||||
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND g.LocationID=@LocationID AND g.Generation=@Generation
|
||||
AND g.IsExcluded=0 AND (g.Confirmed=0 OR @ReplaceConfirmed=1) AND g.Status IN('Unresolved','Needs confirmation','Resolved')
|
||||
AND (g.LastRetry IS NULL OR g.LastRetry<DATEADD(hour,-1,SYSUTCDATETIME()));
|
||||
IF @@ROWCOUNT<>1 THROW 51000,'Retry is unavailable. Confirmed matches are preserved; other lookups can be retried once per hour.',1;
|
||||
END;
|
||||
GO
|
||||
INSERT dbo.LocationGeography(LocationID)
|
||||
SELECT l.LocationID FROM dbo.Locations l WHERE l.IsArchived=0 AND NOT EXISTS(SELECT 1 FROM dbo.LocationGeography g WHERE g.LocationID=l.LocationID);
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Exclude @ProjectID int,@UserID int,@LocationID int,@Generation bigint,@IsExcluded bit AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
|
||||
UPDATE g SET IsExcluded=@IsExcluded,Generation=Generation+1,Confirmed=0,MatchJson=NULL,CandidatesJson=NULL,
|
||||
Status=CASE WHEN @IsExcluded=1 THEN 'Not eligible' ELSE 'Pending' END,
|
||||
JobState=CASE WHEN @IsExcluded=1 THEN 'Done' ELSE 'Queued' END,
|
||||
Message=CASE WHEN @IsExcluded=1 THEN 'Excluded by author' ELSE NULL END,Attempts=0,NextAttempt=SYSUTCDATETIME(),Lease=NULL,LeaseUntil=NULL
|
||||
FROM dbo.LocationGeography g JOIN dbo.Locations l ON l.LocationID=g.LocationID
|
||||
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND g.LocationID=@LocationID AND g.Generation=@Generation;
|
||||
IF @@ROWCOUNT<>1 THROW 51000,'Location changed. Refresh before changing geographical lookup.',1;
|
||||
END;
|
||||
GO
|
||||
138
PlotLine/Sql/254_GeographyAuthorHierarchyBatches.sql
Normal file
138
PlotLine/Sql/254_GeographyAuthorHierarchyBatches.sql
Normal file
@ -0,0 +1,138 @@
|
||||
-- Replaces automatic creation/backfill with bounded, explicit hierarchy requests.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF OBJECT_ID('dbo.GeographicAuthorBatch','U') IS NULL
|
||||
CREATE TABLE dbo.GeographicAuthorBatch(
|
||||
BatchID bigint IDENTITY PRIMARY KEY, UserID int NOT NULL, RequestedAt datetime2 NOT NULL DEFAULT SYSUTCDATETIME(), LocationCount int NOT NULL
|
||||
);
|
||||
IF COL_LENGTH('dbo.GeographicProviderGate','Lease') IS NULL
|
||||
ALTER TABLE dbo.GeographicProviderGate ADD Lease uniqueidentifier NULL,LeaseUntil datetime2 NULL,RequestDay date NULL,DailyRequests int NOT NULL DEFAULT 0;
|
||||
GO
|
||||
-- Cancel only legacy automatic jobs introduced by 253; they have never been author submitted.
|
||||
UPDATE dbo.LocationGeography SET JobState='Awaiting hierarchy request',Status='Pending',Lease=NULL,LeaseUntil=NULL,
|
||||
Message='Arrange or explicitly request resolution of this hierarchy to look up geographical places.'
|
||||
WHERE JobState IN('Queued','Waiting configuration','Processing') AND Confirmed=0;
|
||||
GO
|
||||
CREATE OR ALTER TRIGGER dbo.Location_GeographyChanged ON dbo.Locations AFTER INSERT, UPDATE AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF NOT (UPDATE(LocationName) OR UPDATE(ParentLocationID) OR UPDATE(LocationTypeID) OR UPDATE(IsArchived)) RETURN;
|
||||
;WITH Changed AS (
|
||||
SELECT i.LocationID FROM inserted i LEFT JOIN deleted d ON d.LocationID=i.LocationID
|
||||
WHERE d.LocationID IS NULL OR i.LocationName<>d.LocationName OR ISNULL(i.ParentLocationID,0)<>ISNULL(d.ParentLocationID,0)
|
||||
OR ISNULL(i.LocationTypeID,0)<>ISNULL(d.LocationTypeID,0) OR i.IsArchived<>d.IsArchived
|
||||
), Descendants AS (
|
||||
SELECT LocationID FROM Changed UNION ALL
|
||||
SELECT l.LocationID FROM dbo.Locations l JOIN Descendants p ON l.ParentLocationID=p.LocationID
|
||||
)
|
||||
SELECT DISTINCT LocationID INTO #Affected FROM Descendants OPTION(MAXRECURSION 100);
|
||||
UPDATE g SET Generation=Generation+1,Status=CASE WHEN IsExcluded=1 THEN 'Not eligible' ELSE 'Pending' END,Confirmed=0,
|
||||
CandidatesJson=NULL,MatchJson=NULL,RequestKey=NULL,Attempts=0,Lease=NULL,LeaseUntil=NULL,
|
||||
JobState=CASE WHEN IsExcluded=1 THEN 'Done' ELSE 'Awaiting hierarchy request' END,
|
||||
Message='Identifying context changed. Arrange or request resolution of this hierarchy.'
|
||||
FROM dbo.LocationGeography g JOIN #Affected a ON a.LocationID=g.LocationID;
|
||||
-- A new location does not trigger geocoding, even when it has a parent.
|
||||
INSERT dbo.LocationGeography(LocationID,JobState,Message)
|
||||
SELECT a.LocationID,'Awaiting hierarchy request','Arrange or request resolution of this hierarchy.' FROM #Affected a
|
||||
WHERE NOT EXISTS(SELECT 1 FROM dbo.LocationGeography g WHERE g.LocationID=a.LocationID);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_BatchPermit @UserID int,@LocationCount int AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF @@TRANCOUNT=0 THROW 51000,'Batch admission requires a transaction.',1;
|
||||
DECLARE @Lock int;
|
||||
EXEC @Lock=sys.sp_getapplock @Resource='PlotDirector.Geography.AuthorBatches',@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=1000;
|
||||
IF @Lock<0 THROW 51000,'Geographical lookup is busy. Try later.',1;
|
||||
IF @LocationCount NOT BETWEEN 1 AND 20 THROW 51000,'Choose a hierarchy branch of at most 20 locations.',1;
|
||||
IF EXISTS(SELECT 1 FROM dbo.GeographicAuthorBatch WHERE UserID=@UserID AND RequestedAt>DATEADD(hour,-1,SYSUTCDATETIME()))
|
||||
OR (SELECT COUNT(*) FROM dbo.GeographicAuthorBatch WHERE RequestedAt>DATEADD(hour,-1,SYSUTCDATETIME()))>=6
|
||||
THROW 51000,'Geographical lookup batch limit reached. Try again in an hour.',1;
|
||||
DELETE dbo.GeographicAuthorBatch WHERE RequestedAt<DATEADD(day,-90,SYSUTCDATETIME());
|
||||
INSERT dbo.GeographicAuthorBatch(UserID,LocationCount) VALUES(@UserID,@LocationCount);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_SubmitHierarchy @ProjectID int,@UserID int,@LocationID int,@Generation bigint AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
|
||||
BEGIN TRANSACTION;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.LocationGeography g WITH(UPDLOCK,HOLDLOCK) JOIN dbo.Locations l ON l.LocationID=g.LocationID
|
||||
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND l.LocationID=@LocationID AND g.Generation=@Generation)
|
||||
THROW 51000,'Hierarchy changed. Refresh before requesting geographical lookup.',1;
|
||||
;WITH tree AS(
|
||||
SELECT LocationID FROM dbo.Locations WHERE LocationID=@LocationID AND ProjectID=@ProjectID AND IsArchived=0
|
||||
UNION ALL SELECT l.LocationID FROM dbo.Locations l JOIN tree p ON l.ParentLocationID=p.LocationID WHERE l.ProjectID=@ProjectID AND l.IsArchived=0
|
||||
) SELECT LocationID INTO #Scope FROM tree OPTION(MAXRECURSION 100);
|
||||
DECLARE @Count int=(SELECT COUNT(*) FROM #Scope);
|
||||
EXEC dbo.Geography_BatchPermit @UserID,@Count;
|
||||
UPDATE g SET JobState='Queued',Status='Pending',NextAttempt=SYSUTCDATETIME(),Message='Author hierarchy lookup queued.'
|
||||
FROM dbo.LocationGeography g JOIN #Scope s ON s.LocationID=g.LocationID
|
||||
WHERE g.IsExcluded=0 AND g.Confirmed=0 AND g.Status<>'Resolved' AND g.JobState<>'Processing';
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
-- A single external request at a time across processes, on the designated configured host only.
|
||||
-- 15 seconds between starts; 200/day application ceiling. Provider errors can extend cooldown.
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Reserve @Provider nvarchar(100),@IntervalMs int,@RequestKey char(64),@Lease uniqueidentifier AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
SET @IntervalMs=CASE WHEN @IntervalMs<15000 THEN 15000 ELSE @IntervalMs END;
|
||||
IF @IntervalMs>86400000 THROW 51000,'Invalid provider interval.',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @Lock int;
|
||||
EXEC @Lock=sys.sp_getapplock @Resource='PlotDirector.Geography.ProviderGate',@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=1000;
|
||||
IF @Lock<0 BEGIN ROLLBACK; SELECT CAST(0 AS bit); RETURN; END;
|
||||
DECLARE @Now datetime2=SYSUTCDATETIME();
|
||||
DELETE dbo.GeographicLookupLease WHERE LeaseUntil<@Now;
|
||||
IF EXISTS(SELECT 1 FROM dbo.GeographicLookupLease WHERE RequestKey=@RequestKey)
|
||||
OR EXISTS(SELECT 1 FROM dbo.GeographicProviderGate WHERE Provider=@Provider AND
|
||||
(NextRequest>@Now OR LeaseUntil>@Now OR (RequestDay=CONVERT(date,@Now) AND DailyRequests>=200)))
|
||||
BEGIN COMMIT; SELECT CAST(0 AS bit); RETURN; END;
|
||||
UPDATE dbo.GeographicProviderGate SET NextRequest=DATEADD(millisecond,@IntervalMs,@Now),Lease=@Lease,LeaseUntil=DATEADD(minute,2,@Now),
|
||||
DailyRequests=CASE WHEN RequestDay=CONVERT(date,@Now) THEN DailyRequests+1 ELSE 1 END,RequestDay=CONVERT(date,@Now) WHERE Provider=@Provider;
|
||||
IF @@ROWCOUNT=0 INSERT dbo.GeographicProviderGate(Provider,NextRequest,Lease,LeaseUntil,RequestDay,DailyRequests)
|
||||
VALUES(@Provider,DATEADD(millisecond,@IntervalMs,@Now),@Lease,DATEADD(minute,2,@Now),CONVERT(date,@Now),1);
|
||||
INSERT dbo.GeographicLookupLease VALUES(@RequestKey,@Lease,DATEADD(minute,2,@Now));
|
||||
COMMIT; SELECT CAST(1 AS bit);
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_ProviderRelease @Lease uniqueidentifier,@CooldownSeconds int=0 AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
UPDATE dbo.GeographicProviderGate SET Lease=NULL,LeaseUntil=NULL,
|
||||
NextRequest=CASE WHEN DATEADD(second,@CooldownSeconds,SYSUTCDATETIME())>NextRequest THEN DATEADD(second,@CooldownSeconds,SYSUTCDATETIME()) ELSE NextRequest END
|
||||
WHERE Lease=@Lease;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Retry @ProjectID int,@UserID int,@LocationID int,@Generation bigint,@ReplaceConfirmed bit=0 AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON; SET XACT_ABORT ON;
|
||||
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
|
||||
BEGIN TRANSACTION;
|
||||
EXEC dbo.Geography_BatchPermit @UserID,1;
|
||||
UPDATE g SET Status='Pending',JobState='Queued',Attempts=0,NextAttempt=SYSUTCDATETIME(),Lease=NULL,LeaseUntil=NULL,
|
||||
Generation=Generation+1,Confirmed=0,CandidatesJson=NULL,MatchJson=NULL,Message=NULL,LastRetry=SYSUTCDATETIME()
|
||||
FROM dbo.LocationGeography g JOIN dbo.Locations l ON l.LocationID=g.LocationID
|
||||
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND g.LocationID=@LocationID AND g.Generation=@Generation AND g.IsExcluded=0
|
||||
AND (g.Confirmed=0 OR @ReplaceConfirmed=1) AND g.Status IN('Unresolved','Needs confirmation','Resolved');
|
||||
IF @@ROWCOUNT<>1 THROW 51000,'Retry is unavailable. Refresh the geographical status.',1;
|
||||
COMMIT;
|
||||
END;
|
||||
GO
|
||||
-- Re-enabling an excluded place waits for the next deliberate hierarchy request.
|
||||
CREATE OR ALTER PROCEDURE dbo.Geography_Exclude @ProjectID int,@UserID int,@LocationID int,@Generation bigint,@IsExcluded bit AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
EXEC dbo.StoryMap_Authorize @ProjectID,@UserID;
|
||||
UPDATE g SET IsExcluded=@IsExcluded,Generation=Generation+1,Confirmed=0,MatchJson=NULL,CandidatesJson=NULL,
|
||||
Status=CASE WHEN @IsExcluded=1 THEN 'Not eligible' ELSE 'Pending' END,
|
||||
JobState=CASE WHEN @IsExcluded=1 THEN 'Done' ELSE 'Awaiting hierarchy request' END,
|
||||
Message=CASE WHEN @IsExcluded=1 THEN 'Excluded by author' ELSE 'Arrange or request resolution of this hierarchy.' END,
|
||||
Attempts=0,Lease=NULL,LeaseUntil=NULL
|
||||
FROM dbo.LocationGeography g JOIN dbo.Locations l ON l.LocationID=g.LocationID
|
||||
WHERE l.ProjectID=@ProjectID AND l.IsArchived=0 AND g.LocationID=@LocationID AND g.Generation=@Generation;
|
||||
IF @@ROWCOUNT<>1 THROW 51000,'Location changed. Refresh before changing geographical lookup.',1;
|
||||
END;
|
||||
GO
|
||||
7
PlotLine/Sql/255_GeographyHierarchyStateWidth.sql
Normal file
7
PlotLine/Sql/255_GeographyHierarchyStateWidth.sql
Normal file
@ -0,0 +1,7 @@
|
||||
-- Repairs the state width discovered during Development qualification of 254.
|
||||
-- Fresh installations: apply 253, this repair, then 254. Development: apply this repair and resume 254.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
ALTER TABLE dbo.LocationGeography ALTER COLUMN JobState varchar(40) NOT NULL;
|
||||
GO
|
||||
8
PlotLine/Sql/256_GeographyQueueIndex.sql
Normal file
8
PlotLine/Sql/256_GeographyQueueIndex.sql
Normal file
@ -0,0 +1,8 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('dbo.LocationGeography') AND name='IX_LocationGeography_Queue')
|
||||
CREATE INDEX IX_LocationGeography_Queue ON dbo.LocationGeography(JobState,NextAttempt) INCLUDE(LeaseUntil);
|
||||
IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE object_id=OBJECT_ID('dbo.GeographicAuthorBatch') AND name='IX_GeographicAuthorBatch_Time')
|
||||
CREATE INDEX IX_GeographicAuthorBatch_Time ON dbo.GeographicAuthorBatch(RequestedAt) INCLUDE(UserID);
|
||||
GO
|
||||
@ -23,6 +23,12 @@
|
||||
|
||||
<partial name="_ProjectSectionNav" model="Model.Project" />
|
||||
|
||||
<section class="edit-panel" data-geography-location="@Model.Location.LocationID" data-project-id="@Model.Project.ProjectID">
|
||||
<details><summary>Geographical position: <span data-geography-status>Loading…</span></summary><div data-geography-body></div></details>
|
||||
</section>
|
||||
@Html.AntiForgeryToken()
|
||||
<script src="~/js/location-geography.js" asp-append-version="true" defer></script>
|
||||
|
||||
<div class="location-page">
|
||||
<div data-pd-context="location" data-pd-context-id="@Model.Location.LocationID" data-pd-context-label="@Model.Location.LocationName" data-pwa-help class="page-heading compact">
|
||||
<div>
|
||||
|
||||
@ -1,5 +1,9 @@
|
||||
@model LocationListViewModel
|
||||
<section class="edit-panel location-tree" data-location-tree>
|
||||
@if (TempData["GeographyMessage"] is string geographyMessage)
|
||||
{
|
||||
<p class="muted" role="status">@geographyMessage</p>
|
||||
}
|
||||
@foreach (var location in Model.Locations)
|
||||
{
|
||||
<div data-pd-context="location" data-pd-context-id="@location.LocationID" data-pd-context-label="@location.LocationName" class="location-tree-row" data-drag-type="location" data-drag-id="@location.LocationID" data-drag-label="@location.LocationName" data-parent-location-id="@location.ParentLocationID" data-parent-location-name="@location.ParentLocationName" style="--location-depth:@location.Depth">
|
||||
|
||||
@ -19,6 +19,7 @@
|
||||
<button type="button" id="mapsSave" data-pwa-context="Map" data-ribbon-icon="save">Save</button>
|
||||
<details data-pwa-context="Map actions" data-pwa-menu-icon="layout" data-pwa-compact="true"><summary>Map actions</summary><div class="maps-menu"><button type="button" id="mapsRename" data-ribbon-icon="writer">Rename map</button><button type="button" id="mapsDuplicate" data-ribbon-icon="copy">Duplicate map</button><button type="button" id="mapsDelete" data-ribbon-icon="remove">Delete map…</button></div></details>
|
||||
<div data-pwa-context="Editing" class="maps-edit-tools"><button type="button" id="mapsUndo" data-ribbon-icon="undo">Undo</button><button type="button" id="mapsRedo" data-ribbon-icon="redo">Redo</button></div>
|
||||
<button type="button" id="mapsGeographic" data-pwa-context="Arrange" data-ribbon-icon="auto-arrange">Position geographically</button>
|
||||
<button type="button" id="mapsArrange" data-pwa-context="Arrange" data-ribbon-icon="auto-arrange">Arrange from relationships</button>
|
||||
<button type="button" id="mapsAppearance" data-pwa-context="Map appearance" data-ribbon-icon="settings">Map appearance</button>
|
||||
<button type="button" id="mapsDetach" data-pwa-context="Workspace" data-ribbon-icon="separate-window">Open in separate window</button>
|
||||
@ -65,6 +66,7 @@
|
||||
</div>
|
||||
<dialog id="mapsNewDialog"><form id="mapsNewForm"><h2>New map</h2><label>Name <input name="Name" maxlength="200" required autofocus /></label><label>What are you mapping? <select name="Kind">@foreach(var kind in PlotLine.Services.MapValidation.Kinds){<option>@kind</option>}</select></label><label>How would you like to begin? <select name="Starter"><option value="blank">Blank map</option><option value="land">Single land mass</option><option value="island">Large island</option><option value="islands">Island group</option><option value="two">Two land masses</option><option value="inland">Inland region</option><option value="local">City / local area</option></select></label><label>Parent map <select name="ParentMapID"><option value="">None</option>@foreach(var map in Model.Maps){<option value="@map.MapID">@map.Name</option>}</select></label><p>Starter layouts contain editable shapes only. You name and define your world.</p><div><button type="button" id="mapsNewCancel">Cancel</button><button type="submit">Create map</button></div></form></dialog>
|
||||
<dialog id="mapsArrangeDialog"><h2>Arrange from relationships</h2><p>Preview an arrangement using directions and relative distances. Known distances never control spacing.</p><label><input type="checkbox" id="mapsOnlyNew" /> Arrange unplaced / new items only</label><p id="mapsArrangeWarnings"></p><button type="button" id="mapsArrangeCancel">Cancel</button><button type="button" id="mapsArrangeApply">Apply arrangement</button></dialog>
|
||||
<dialog id="mapsGeographicDialog"><h2>Position geographically</h2><p>Preview shown on the map. Listed location markers will move; all other map objects retain their positions. North is up. Relative distances use one scale in both directions. Coincident places overlap.</p><div id="mapsGeographicSummary"></div><p>Apply adds one Undo step. Use Save to persist the map. You can drag markers afterwards.</p><button type="button" id="mapsGeographicCancel">Cancel</button><button type="button" id="mapsGeographicApply">Apply positions</button></dialog>
|
||||
</section>
|
||||
@Html.AntiForgeryToken()
|
||||
<script id="mapsBootstrap" type="application/json">@Html.Raw(JsonSerializer.Serialize(new { projectId = Model.Project.ProjectID, maps = Model.Maps, locations = Model.Locations, floorPlans = Model.FloorPlans, referenceImages = Model.ReferenceImages, document = Model.Document }, new JsonSerializerOptions(JsonSerializerDefaults.Web)))</script>
|
||||
@ -73,6 +75,7 @@
|
||||
<script src="~/js/maps-symbols.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-engine.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-appearance-engine.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-geography-engine.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-workspace.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-appearance.js" asp-append-version="true"></script>
|
||||
<script src="~/js/maps-story-engine.js" asp-append-version="true"></script>
|
||||
|
||||
35
PlotLine/wwwroot/js/location-geography.js
Normal file
35
PlotLine/wwwroot/js/location-geography.js
Normal file
@ -0,0 +1,35 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const host=document.querySelector('[data-geography-location]');
|
||||
if(!host)return;
|
||||
const projectId=host.dataset.projectId,locationId=host.dataset.geographyLocation;
|
||||
const status=host.querySelector('[data-geography-status]'),body=host.querySelector('[data-geography-body]');
|
||||
const token=document.querySelector('input[name="__RequestVerificationToken"]')?.value;
|
||||
async function change(action,data){
|
||||
const response=await fetch('/Geography/'+action,{method:'POST',headers:{RequestVerificationToken:token},body:new URLSearchParams({projectId,locationId,...data})});
|
||||
const result=await response.json().catch(()=>null);
|
||||
if(!response.ok||response.redirected)throw Error(result?.message||'Could not update geographical match.');
|
||||
await load();
|
||||
if(result?.message)status.textContent=result.message;
|
||||
}
|
||||
function button(label,action){const b=document.createElement('button');b.type='button';b.className='btn btn-outline-secondary btn-sm';b.textContent=label;b.onclick=async()=>{b.disabled=true;try{await action();}catch(e){status.textContent=e.message;b.disabled=false;}};body.append(b);}
|
||||
function line(text){const p=document.createElement('p');p.textContent=text;body.append(p);}
|
||||
async function load(){
|
||||
const response=await fetch('/Geography/State?'+new URLSearchParams({projectId,locationId}),{cache:'no-store'});
|
||||
if(!response.ok||response.redirected)throw Error('Geographical status unavailable.');
|
||||
const rows=await response.json(),state=rows[0];
|
||||
status.textContent=state?.status||'Pending';body.replaceChildren();
|
||||
if(!state){line('Awaiting geographical classification.');return;}
|
||||
if(state.message)line(state.message);
|
||||
if(!state.isExcluded)button('Resolve this arranged hierarchy (up to 20 places)',()=>change('Hierarchy',{}));
|
||||
button(state.isExcluded?'Enable automatic geographical lookup':'Exclude automatic geographical lookup',()=>change('Exclude',{generation:state.generation,isExcluded:!state.isExcluded}));
|
||||
if(state.matchJson){const m=JSON.parse(state.matchJson);line(`${m.Name} · ${m.AdministrativeNames.join(', ')} · ${m.CountryCode}`);line(`${m.Latitude}, ${m.Longitude}`);line(m.Attribution);}
|
||||
if(state.status==='Needs confirmation'){
|
||||
const candidates=JSON.parse(state.candidatesJson||'[]');
|
||||
candidates.forEach((m,index)=>button(`${m.Name} · ${m.AdministrativeNames.join(', ')} · ${m.CountryCode} (${m.Latitude}, ${m.Longitude}) — ${m.Attribution}`,()=>change('Confirm',{generation:state.generation,candidateIndex:index})));
|
||||
}
|
||||
if(state.status==='Resolved')button('Change geographical match',()=>change('Retry',{generation:state.generation,replaceConfirmed:true}));
|
||||
if(['Unresolved','Needs confirmation'].includes(state.status))button('Retry geographical lookup',()=>change('Retry',{generation:state.generation}));
|
||||
}
|
||||
load().catch(e=>status.textContent=e.message);
|
||||
})();
|
||||
37
PlotLine/wwwroot/js/maps-geography-engine.js
Normal file
37
PlotLine/wwwroot/js/maps-geography-engine.js
Normal file
@ -0,0 +1,37 @@
|
||||
/* Spherical azimuthal equidistant projection, north up at the centre.
|
||||
Refuse large extents: no flat projection preserves all worldwide distances/directions. */
|
||||
(function(root){
|
||||
'use strict';
|
||||
function position(features,states,bounds){
|
||||
const rad=Math.PI/180,R=6371008.8,wrap=a=>Math.atan2(Math.sin(a),Math.cos(a));
|
||||
if(![bounds.x,bounds.y,bounds.w,bounds.h].every(Number.isFinite)||bounds.w<=0||bounds.h<=0)throw Error('Map area is unavailable.');
|
||||
const skipped=[],points=[],output=JSON.parse(JSON.stringify(features));
|
||||
for(const f of output){
|
||||
if(!f.locationID)continue;
|
||||
const state=states.find(s=>s.locationID===f.locationID);
|
||||
let match=null;try{match=JSON.parse(state?.matchJson||'null');}catch{}
|
||||
const reason=f.isLocked?'Locked':f.geometryClass!=='Marker'?'Only location markers can be positioned':state?.status!=='Resolved'?(state?.status||'Pending'):!match?'Unresolved':null;
|
||||
if(reason){skipped.push({name:f.name,reason});continue;}
|
||||
if(!Number.isFinite(match.Latitude)||!Number.isFinite(match.Longitude)||Math.abs(match.Latitude)>90||Math.abs(match.Longitude)>180){skipped.push({name:f.name,reason:'Invalid geographical coordinates'});continue;}
|
||||
points.push({feature:f,lat:match.Latitude*rad,lon:match.Longitude*rad,attribution:match.Attribution});
|
||||
}
|
||||
if(!points.length)return {features:output,positioned:[],skipped};
|
||||
const sin=points.reduce((s,p)=>s+Math.sin(p.lon),0),cos=points.reduce((s,p)=>s+Math.cos(p.lon),0);
|
||||
if(Math.hypot(sin,cos)<1e-9)throw Error('These locations span too much of the world. Use separate regional maps.');
|
||||
const lon0=Math.atan2(sin,cos),lat0=points.reduce((s,p)=>s+p.lat,0)/points.length;
|
||||
for(const p of points){
|
||||
const dl=wrap(p.lon-lon0),cosc=Math.max(-1,Math.min(1,Math.sin(lat0)*Math.sin(p.lat)+Math.cos(lat0)*Math.cos(p.lat)*Math.cos(dl))),c=Math.acos(cosc);
|
||||
if(c>15*rad)throw Error('These locations cover too large an area for reliable local positioning. Use separate regional maps (within about 1,650 km of their centre).');
|
||||
const k=c<1e-10?1:c/Math.sin(c);
|
||||
p.x=R*k*Math.cos(p.lat)*Math.sin(dl);
|
||||
p.y=-R*k*(Math.cos(lat0)*Math.sin(p.lat)-Math.sin(lat0)*Math.cos(p.lat)*Math.cos(dl));
|
||||
}
|
||||
const xs=points.map(p=>p.x),ys=points.map(p=>p.y),left=Math.min(...xs),right=Math.max(...xs),top=Math.min(...ys),bottom=Math.max(...ys);
|
||||
const pad=Math.min(80,bounds.w*.12,bounds.h*.12),w=bounds.w-2*pad,h=bounds.h-2*pad;
|
||||
const scale=Math.min(right-left>1e-6?w/(right-left):Infinity,bottom-top>1e-6?h/(bottom-top):Infinity);
|
||||
for(const p of points){p.feature.x=bounds.x+bounds.w/2+(p.x-(left+right)/2)*(Number.isFinite(scale)?scale:0);p.feature.y=bounds.y+bounds.h/2+(p.y-(top+bottom)/2)*(Number.isFinite(scale)?scale:0);p.feature.isPlaced=true;}
|
||||
return {features:output,positioned:points.map(p=>({name:p.feature.name,attribution:p.attribution})),skipped};
|
||||
}
|
||||
root.PlotDirectorGeography={position};
|
||||
if(typeof module!=='undefined')module.exports={position};
|
||||
})(typeof window!=='undefined'?window:globalThis);
|
||||
@ -215,7 +215,7 @@
|
||||
function previewArrange(){if(!doc||mode!=='create')return;preview=E.arrange(doc.features,doc.relationships,$('mapsOnlyNew').checked);$('mapsArrangeWarnings').textContent=preview.warnings.length?'Some intentions cannot all be represented exactly: '+preview.warnings.slice(0,5).join('; ')+'. You can still apply and adjust manually.':'Preview ready. Locked pieces and established anchors stay in place.';render();updateButtons();}
|
||||
// Delegated interaction continues to work after the PWA shell moves controls into its ribbon.
|
||||
document.addEventListener('click',e=>{
|
||||
const modeButton=e.target.closest('button[data-mode]');if(modeButton){if(preview)return;window.PlotDirectorMapAppearance?.completeAdjustment();if(modeButton.dataset.mode==='story'&&dirty){requestLeave(()=>modeButton.click());return;}mode=modeButton.dataset.mode;app.dataset.mode=mode;for(const id of ['mapsSave','mapsUndo','mapsRedo','mapsArrange'])$(id).hidden=mode!=='create';document.querySelectorAll('button[data-mode]').forEach(b=>b.setAttribute('aria-pressed',String(b===modeButton)));$('mapsStory').hidden=mode!=='story';pending=null;svg.classList.remove('placing');render();details();updateButtons();window.dispatchEvent(new CustomEvent('pd-map-mode',{detail:mode}));return;}
|
||||
const modeButton=e.target.closest('button[data-mode]');if(modeButton){if(preview)return;window.PlotDirectorMapAppearance?.completeAdjustment();if(modeButton.dataset.mode==='story'&&dirty){requestLeave(()=>modeButton.click());return;}mode=modeButton.dataset.mode;app.dataset.mode=mode;for(const id of ['mapsSave','mapsUndo','mapsRedo','mapsArrange','mapsGeographic'])$(id).hidden=mode!=='create';document.querySelectorAll('button[data-mode]').forEach(b=>b.setAttribute('aria-pressed',String(b===modeButton)));$('mapsStory').hidden=mode!=='story';pending=null;svg.classList.remove('placing');render();details();updateButtons();window.dispatchEvent(new CustomEvent('pd-map-mode',{detail:mode}));return;}
|
||||
const asset=e.target.closest('[data-asset]'),loc=e.target.closest('[data-location]');if(asset||loc){pending={type:asset?.dataset.asset||'Settlement',locationID:loc?Number(loc.dataset.location):null};svg.classList.add('placing');status('Click the map to place '+(asset?.dataset.asset||'this Location')+'. Escape cancels.');return;}
|
||||
const actionButton=e.target.closest('[data-action]');if(actionButton)action(actionButton.dataset.action);
|
||||
const rel=e.target.closest('[data-edit-rel]');if(rel)relationEditor(rel.dataset.editRel);
|
||||
@ -281,6 +281,7 @@
|
||||
window.addEventListener('pd-workspace-message',e=>{if(e.detail.type==='map-saved'&&e.detail.payload.mapID===doc?.map.mapID&&e.detail.payload.revision>doc.map.revision)status('This map was saved in another window. Reload before editing further. Your current changes remain here.',true);});
|
||||
document.addEventListener('keydown',e=>{
|
||||
if(e.defaultPrevented||document.querySelector('.modal.show'))return;
|
||||
if(e.key==='Escape'&&$('mapsGeographicDialog').open){e.preventDefault();cancelGeographic();return;}
|
||||
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'&&!e.target.closest('dialog')){e.preventDefault();if(e.target.matches('[data-field]'))e.target.dispatchEvent(new Event('change',{bubbles:true}));save();return;}
|
||||
if(e.target.matches('input,textarea,select')||e.target.isContentEditable)return;
|
||||
if(e.key==='Escape'){if(!drag&&!pending&&app.classList.contains('maps-maximised'))return;e.preventDefault();svg.classList.remove('manipulating');if(drag&&drag.kind!=='pan'){doc=JSON.parse(history.pop());future=drag.redo;drag=null;}pending=null;selected.clear();shapeEdit=false;svg.classList.remove('placing');render();details();return;}
|
||||
@ -307,6 +308,34 @@
|
||||
$('mapsRename').onclick=async()=>{if(!doc)return;const answer=await window.PlotDirectorDialogs.choose({title:'Rename map',message:'Choose a name for this map.',input:{label:'Map name',value:doc.map.name},actions:[{label:'Rename',value:'rename',className:'btn-primary'},{label:'Cancel',value:'cancel'}]});if(answer?.value==='rename'&&answer.input.trim())safeEdit(()=>{doc.map.name=answer.input.trim().slice(0,200);crumbs();});};
|
||||
$('mapsDuplicate').onclick=async()=>{if(!doc||busy||preview)return;if(dirty){requestLeave(()=>$('mapsDuplicate').click());return;}try{const result=await request('Create',{ProjectID:boot.projectId,Name:doc.map.name+' copy',Kind:doc.map.kind,...(doc.map.parentMapID?{ParentMapID:doc.map.parentMapID}:{})});const d=clone(doc);d.map.mapID=result.id;d.map.name+=' copy';d.map.revision=0;d.features.forEach(f=>f.createLocation=false);await request('Save',d,true);dirty=false;location.href=url(result.id);}catch(error){status(error.message,true);}};
|
||||
$('mapsDelete').onclick=async()=>{if(!doc||busy||preview)return;const answer=await window.PlotDirectorDialogs.choose({title:'Delete map?',message:`Delete “${doc.map.name}”? Detailed child maps will become top-level maps. Story Locations, Floor Plans and project reference images are kept.`,actions:[{label:'Delete map',value:'delete',className:'btn-danger'},{label:'Cancel',value:'cancel'}]});if(answer?.value!=='delete')return;try{await request('Delete',{projectId:boot.projectId,id:doc.map.mapID,revision:doc.map.revision});dirty=false;location.href=url();}catch(error){status(error.message,true);}};
|
||||
$('mapsGeographic').onclick=async()=>{
|
||||
if(!doc||busy||preview||drag||mode!=='create'||window.PlotDirectorMapAppearance?.adjusting)return;
|
||||
busy=true;updateButtons();const before=snapshot();
|
||||
try{
|
||||
const response=await fetch('/Geography/State?projectId='+boot.projectId,{cache:'no-store'});
|
||||
if(!response.ok||response.redirected)throw Error('Could not load geographical resolutions. Your map is unchanged.');
|
||||
const states=await response.json();
|
||||
if(snapshot()!==before)throw Error('The map changed while loading. Try positioning again.');
|
||||
const result=window.PlotDirectorGeography.position(doc.features,states,view);
|
||||
const summary=$('mapsGeographicSummary');summary.replaceChildren();
|
||||
const add=text=>{const p=document.createElement('p');p.textContent=text;summary.append(p);};
|
||||
add(result.positioned.length+' location markers will move.');
|
||||
for(const item of result.positioned)add('Move: '+item.name);
|
||||
for(const item of result.skipped)add('Keep: '+item.name+' — '+item.reason);
|
||||
for(const attribution of new Set(result.positioned.map(p=>p.attribution).filter(Boolean)))add(attribution);
|
||||
preview=result;render();$('mapsGeographicApply').disabled=!result.positioned.length;
|
||||
$('mapsGeographicDialog').showModal();
|
||||
}catch(error){status(error.message,true);}finally{busy=false;updateButtons();}
|
||||
};
|
||||
function cancelGeographic(){preview=null;$('mapsGeographicDialog').close();render();updateButtons();}
|
||||
$('mapsGeographicCancel').onclick=cancelGeographic;
|
||||
$('mapsGeographicDialog').oncancel=e=>{e.preventDefault();cancelGeographic();};
|
||||
$('mapsGeographicApply').onclick=()=>{
|
||||
if(!preview?.positioned?.length||busy||mode!=='create')return;
|
||||
const result=preview;preview=null;checkpoint();doc.features=result.features;
|
||||
changed('Geographical positions applied. Save to persist; Undo restores previous positions.');
|
||||
$('mapsGeographicDialog').close();render();details();updateButtons();
|
||||
};
|
||||
$('mapsArrange').onclick=()=>{if(!doc||busy||mode!=='create')return;previewArrange();$('mapsArrangeDialog').showModal();};$('mapsOnlyNew').onchange=previewArrange;
|
||||
function cancelArrange(){preview=null;$('mapsArrangeDialog').close();render();updateButtons();}
|
||||
$('mapsArrangeCancel').onclick=cancelArrange;$('mapsArrangeDialog').oncancel=e=>{e.preventDefault();cancelArrange();};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user