/* eslint-disable no-console */ import Inject from "@entity-access/entity-access/dist/di/di.js"; import Workflow, { UniqueActivity } from "@entity-access/entity-access/dist/workflows/Workflow.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import TempFileService from "../../storage/TempFileService.js"; import TempFolder from "@entity-access/server-pages/dist/core/TempFolder.js"; import { spawnPromise } from "../../../common/spawnPromise.js"; import WorkflowContext from "@entity-access/entity-access/dist/workflows/WorkflowContext.js"; import GeoEntity, { geoType } from "../../model/entities/GeoEntity.js"; import { globalEnv } from "../../../common/globalEnv.js"; import QueryBuilder from "../../../common/QueryBuilder.js"; import SecureFetchBuilder from "../../../common/fetch/SecureFetchBuilder.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import { fileURLToPath } from "node:url"; import { readFile } from "node:fs/promises"; /** * For same phyical server, we should only download it once */ export default class DownloadGeoEntitiesWorkflow extends Workflow { static taskGroup = "batch"; static queue(context: WorkflowContext) { return context.queue(DownloadGeoEntitiesWorkflow, null, { id: "download-geo-entities" }); } cache = new Map>(); async run() { if (globalEnv.isRootHost) { await this.downloadFromGeoNames(); return; } if (globalEnv.otpIn.host) { // download from parent... await this.downloadFromHost("country"); await this.downloadFromHost("state"); await this.downloadFromHost("city"); return; } await this.downloadFromGeoNames(); } @UniqueActivity async downloadFromHost( type: geoType, @Inject db?: SocialMailContext ) { // get past from last saved geotype const last = await db.geoEntities.where({ type }, (x, p) => x.type === p.type) .orderByDescending((x) => x.dateUpdated) .first(); const past = last?.dateUpdated; const client = SecureFetchBuilder .url(`https://${globalEnv.otpIn.host}/`) .logWhenFailed(console.error) .header("authorization", `basic ${Buffer.from(`${globalEnv.otpIn.key}:${globalEnv.otpIn.secret}`).toString("base64")}`); let start = 0; for(;;) { let q = new QueryBuilder>(client, GeoEntity.name); q = q.where({ start, type, past }, (p) => (x) => x.type === p.type && x.geoEntityID > p.start ); if (past) { q = q.where({ past }, (p) => (x) => x.dateUpdated > p.past); } const { items, more } = await q.orderBy(void 0, (p) => (x) => x.geoEntityID) .range(0, 1000) .toPage(); console.log(`Downloaded ${items.length} items for ${type}`); for(const item of items) { start = item.geoEntityID; await this.save(db, type, item.externalID, item); } if(!more) { break; } } } @UniqueActivity async downloadFromGeoNames( @Inject db?: SocialMailContext, @Inject tfs?: TempFileService ) { if (await this.exists(db)) { return; } await this.downloadCountries(tfs, db); await this.downloadStates(tfs, db); await this.downloadCities(tfs, db); } async downloadCountries(tfs: TempFileService, db: SocialMailContext) { const file = await tfs.download("http://download.geonames.org/export/dump/countryInfo.txt"); let last: string; let schema = void 0; let isoField; let geoNameIDField; let fipsField; let countryField; let currencyCodeField; let currencyNameField; let phoneField; let total = 0; const isdJson = JSON.parse(await readFile(fileURLToPath(import.meta.resolve("../../../../content/json/isd.json")), "utf-8")); const isdCountries = isdJson.countries as { iso_code, mask, dial_code }[]; for await(const line of file.lines()) { if(line.startsWith("#")) { last = line; continue; } if(!schema) { schema = {}; let i = 0; for (const t of last.substring(1).split("\t")) { const fieldID = i++; switch(t.trim()) { case "ISO": isoField = fieldID; break; case "geonameid": geoNameIDField = fieldID; break; case "fips": fipsField = fieldID; break; case "Phone": phoneField = fieldID; break; case "Country": countryField = fieldID; break; case "CurrencyCode": currencyCodeField = fieldID; break; case "CurrencyName": currencyNameField = fieldID; break; } } } const tokens = line.split("\t"); if (!tokens.length) { continue; } total++; const code = tokens[isoField]; const fips = tokens[fipsField]; const name = tokens[countryField]; const externalID = tokens[geoNameIDField]; const currencyCode = tokens[currencyCodeField]; const currencyName = tokens[currencyNameField]; const isdItem = isdCountries.find((x) => x.iso_code === code); const phoneFormat = isdItem?.mask; const isdCode = isdItem?.dial_code ?? tokens[phoneField]; const fields = { fips, name, code, currencyCode, currencyName, isdCode, phoneFormat }; await this.save(db, "country", externalID, fields); } console.log(`Saved ${total} countries correctly.`); } async save(db: SocialMailContext, type: geoType, externalID, fields: Partial) { const keys = { externalID, type }; fields.externalID = externalID; fields.type = type; fields.displayName = fields.name; fields.fullName = fields.name; fields.name = fields.name.toLowerCase(); fields.dateUpdated = this.currentTime; await db.geoEntities.withKeys(keys).updateOrInsert(fields); } async downloadStates(tfs: TempFileService, db: SocialMailContext) { const file = await tfs.download("http://download.geonames.org/export/dump/admin1CodesASCII.txt"); let total = 0; let done = 0; for await(const line of file.lines()) { if(line.startsWith("#")) { continue; } const tokens = line.split("\t"); if (!tokens.length) { continue; } const [ code, name, _localDisplayName, externalID ] = tokens; const [countryCode, stateCode] = code.split("."); const parent = await this.getCached(countryCode, () => db.geoEntities.where({ countryCode }, (x, p) => x.type === "country" && x.code === p.countryCode ).first()); total++; if (!parent) { continue; } done++; const fields = { name, code: stateCode, countryCode, parentID: parent?.geoEntityID, }; await this.save(db, "state", externalID, fields); } // update local name... await db.geoEntities.where((x) => x.type === "state") .update((x) => ({ fullName: `${x.displayName}, ${x.parent.fullName}` })); console.log(`Saved ${done} out of ${total} states correctly.`); } async downloadCities(tfs: TempFileService, db: SocialMailContext) { const zipFile = await tfs.download("http://download.geonames.org/export/dump/cities15000.zip"); using tempFolder = new TempFolder(); await spawnPromise("7z", ["x", zipFile.path, `-o${tempFolder.folder}`]); const file = tempFolder.get("cities15000.txt"); let total = 0; let done = 0; for await(const line of file.lines()) { if(line.startsWith("#")) { continue; } const tokens = line.split("\t"); if (!tokens.length) { continue; } const [ externalID, name, _asciiName, _alternateNames, latitude, longitude, _featureClass, _featureCode, countryCode, _cc2, admin1Code /** State */, _admin2Code, _admin3Code, _admin4Code, population, _elevation, _dem, timezone, ] = tokens; const parent = await this.getCached( countryCode + "." + admin1Code, () => db.geoEntities.where({ countryCode, admin1Code }, (x, p) => x.type === "state" && x.code === p.admin1Code && x.parent.code === p.countryCode ).first()); total++; if(!parent) { // console.warn(`No parent found for ${countryCode} ${admin1Code}`); continue; } done++; const fields = { name, code: externalID, countryCode, latitude: latitude as any, longitude: longitude as any, population: population as any, timezone, parentID: parent.geoEntityID }; await this.save(db, "city", externalID, fields); } // update local name... await db.geoEntities.where((x) => x.type === "city") .update((x) => ({ location: Sql.spatial.point(x.longitude, x.latitude, 4326), fullName: `${x.displayName}, ${x.parent.fullName}` })); console.log(`Saved ${done} out of ${total} cities correctly.`); } getCached(key, fx: () => Promise) { let entity = this.cache.get(key); if(!entity) { entity = fx(); this.cache.set(key, entity); } return entity; } async exists(db: SocialMailContext) { // download only once a month const past = DateTime.now.addDays(-30); const exists = await db.geoEntities.where({ past }, (x, p) => x.dateUpdated > p.past) .some(); return exists; } }