use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde_json::{Map, Value, json};
use crate::cli::{LgdAction, LgdArgs};
use crate::exit::Exit;
use crate::layout::{days_of_date, hex, sha256_file};
pub const STATES_URL: &str = "https://lgdirectory.gov.in/globalviewstateforcitizen.do";
pub const DOWNLOAD_URL: &str = "https://lgdirectory.gov.in/downloadDirectory.do";
pub const TERMS_URL: &str = "https://lgdirectory.gov.in/copyRightPolicy.do";
pub const TERMS: &str = "Material featured on this site may be reproduced free of charge in any format or media without requiring specific permission. This is subject to the material being reproduced accurately and not being used in a derogatory manner or in a misleading context. Where the material is being published or issued to others, the source must be prominently acknowledged.";
pub const ACKNOWLEDGEMENT: &str = "Source: Local Government Directory, Government of India";
pub const DISTRICTS_FILE: &str = "districts.csv";
pub const ORIGINAL_FILE: &str = "districts-source.xlsx";
pub const REPORT: &str = "All Districts of India";
pub const REPORT_FORMAT: &str = "Xls Report";
pub const DATA_GOV_URL: &str =
"https://www.data.gov.in/resource/local-government-directory-lgd-districts";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LgdState {
pub code: String,
pub name: String,
pub kind: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LgdDistrict {
pub state_code: String,
pub code: String,
pub name: String,
}
#[must_use]
pub fn manual_step(lgd_dir: &Path) -> String {
let path = lgd_dir.join(DISTRICTS_FILE);
format!(
"open {DOWNLOAD_URL}, choose the report \"{REPORT}\" and the format \"{REPORT_FORMAT}\", \
type the captcha and press Download; open the file in LibreOffice or Excel and save it as \
\"CSV UTF-8\" at {}; then run: geolith dataset lgd districts. Other official route: the \
data.gov.in resource \"Local Government Directory (LGD) - Districts\" ({DATA_GOV_URL}), \
Download, CSV (a form with a captcha), saved at the same path",
path.display()
)
}
fn cell_text(html: &str) -> String {
let mut out = String::with_capacity(html.len());
let mut in_tag = false;
for ch in html.chars() {
match ch {
'<' => in_tag = true,
'>' => {
in_tag = false;
out.push(' ');
}
_ if !in_tag => out.push(ch),
_ => {}
}
}
out.replace(" ", " ")
.replace("&", "&")
.replace("'", "'")
.replace(""", "\"")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
fn table_rows(html: &str) -> Vec<Vec<String>> {
let lower = html.to_ascii_lowercase();
let mut rows = Vec::new();
let mut at = 0;
while let Some(start) = lower[at..].find("<tr") {
let start = at + start;
let Some(end) = lower[start..].find("</tr>") else {
break;
};
let end = start + end;
let row = &html[start..end];
let row_lower = row.to_ascii_lowercase();
let mut cells = Vec::new();
let mut cursor = 0;
while let Some(cell) = row_lower[cursor..]
.find("<td")
.or_else(|| row_lower[cursor..].find("<th"))
{
let cell = cursor + cell;
let Some(open) = row[cell..].find('>') else {
break;
};
let content_at = cell + open + 1;
let Some(close) = row_lower[content_at..]
.find("</td>")
.or_else(|| row_lower[content_at..].find("</th>"))
else {
break;
};
let close = content_at + close;
cells.push(cell_text(&row[content_at..close]));
cursor = close;
}
rows.push(cells);
at = end;
}
rows
}
pub fn parse_states_page(html: &str) -> Result<Vec<LgdState>> {
let rows = table_rows(html);
let header = rows
.iter()
.position(|row| {
row.iter()
.any(|cell| cell.eq_ignore_ascii_case("state lgd code"))
})
.with_context(|| "no \"State LGD Code\" header on the page")?;
let mut states: Vec<LgdState> = Vec::new();
for row in &rows[header + 1..] {
let code = row.get(1).map_or("", String::as_str);
let name = row.get(2).map_or("", String::as_str);
let kind = row.get(4).map_or("", String::as_str);
if !code.bytes().all(|byte| byte.is_ascii_digit()) || code.is_empty() || name.is_empty() {
continue;
}
if states.iter().any(|state| state.code == code) {
bail!("state code {code} repeats");
}
states.push(LgdState {
code: code.to_owned(),
name: name.to_owned(),
kind: kind.to_owned(),
});
}
if states.is_empty() {
bail!("no state rows on the page");
}
Ok(states)
}
fn header_key(header: &str) -> String {
header
.trim_start_matches('\u{feff}')
.to_lowercase()
.split(|ch: char| !ch.is_ascii_alphanumeric())
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
fn is_state_code(key: &str) -> bool {
key == "state code" || key == "state lgd code"
}
fn is_district_code(key: &str) -> bool {
key == "district code" || key == "district lgd code"
}
fn is_district_name(key: &str) -> bool {
matches!(
key,
"district name" | "district name in english" | "district name english"
)
}
pub fn parse_districts_csv(text: &str) -> Result<Vec<LgdDistrict>> {
let rows = parse_csv_rows(text)?;
let at = rows
.iter()
.position(|row| {
let keys: Vec<String> = row.iter().map(|header| header_key(header)).collect();
keys.iter().any(|key| is_state_code(key))
&& keys.iter().any(|key| is_district_code(key))
})
.with_context(|| {
format!(
"no header with a state code and a district code column (first row: {:?})",
rows.first()
)
})?;
let keys: Vec<String> = rows[at].iter().map(|header| header_key(header)).collect();
let state = keys.iter().position(|key| is_state_code(key)).unwrap_or(0);
let code = keys
.iter()
.position(|key| is_district_code(key))
.unwrap_or(0);
let name = keys
.iter()
.position(|key| is_district_name(key))
.with_context(|| format!("no district name column in {:?}", rows[at]))?;
let mut districts: Vec<LgdDistrict> = Vec::new();
for (index, row) in rows[at + 1..].iter().enumerate() {
if row.iter().all(|cell| cell.trim().is_empty()) {
continue;
}
let district = LgdDistrict {
state_code: row.get(state).map_or("", String::as_str).trim().to_owned(),
code: row.get(code).map_or("", String::as_str).trim().to_owned(),
name: row.get(name).map_or("", String::as_str).trim().to_owned(),
};
let numeric =
|value: &str| !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit());
if !numeric(&district.state_code) || !numeric(&district.code) || district.name.is_empty() {
bail!("row {}: bad district row {:?}", at + index + 2, row);
}
if districts.iter().any(|known| known.code == district.code) {
bail!("district code {} repeats", district.code);
}
districts.push(district);
}
Ok(districts)
}
fn parse_csv_rows(text: &str) -> Result<Vec<Vec<String>>> {
crate::normals::parse_csv(text)
}
#[must_use]
pub fn states_csv(states: &[LgdState]) -> String {
let quote = |field: &str| {
if field.contains([',', '"', '\n']) {
format!("\"{}\"", field.replace('"', "\"\""))
} else {
field.to_owned()
}
};
let mut out = String::from("state_code,state_name,state_or_ut\n");
for state in states {
out.push_str(&format!(
"{},{},{}\n",
state.code,
quote(&state.name),
quote(&state.kind)
));
}
out
}
pub fn read_states_csv(text: &str) -> Result<Vec<LgdState>> {
let mut rows = parse_csv_rows(text)?;
let header = rows.first().cloned().unwrap_or_default();
if header.join(",") != "state_code,state_name,state_or_ut" {
bail!("states.csv header is {header:?}");
}
rows.remove(0);
Ok(rows
.into_iter()
.filter(|row| row.iter().any(|cell| !cell.is_empty()))
.map(|row| LgdState {
code: row.first().cloned().unwrap_or_default(),
name: row.get(1).cloned().unwrap_or_default(),
kind: row.get(2).cloned().unwrap_or_default(),
})
.collect())
}
#[must_use]
pub fn is_iso_time(text: &str) -> bool {
let bytes = text.as_bytes();
if bytes.len() < 17
|| bytes[4] != b'-'
|| bytes[7] != b'-'
|| bytes[10] != b'T'
|| bytes[13] != b':'
{
return false;
}
let num = |range: std::ops::Range<usize>| -> Option<i64> {
std::str::from_utf8(bytes.get(range)?).ok()?.parse().ok()
};
let (Some(year), Some(month), Some(day), Some(hour), Some(minute)) =
(num(0..4), num(5..7), num(8..10), num(11..13), num(14..16))
else {
return false;
};
if !(1..=12).contains(&month) || !(1..=31).contains(&day) || days_of_date(&text[..10]).is_none()
{
return false;
}
if hour >= 24 || minute >= 60 {
return false;
}
let rest = &text[16..];
let rest = match rest.strip_prefix(':') {
Some(rest) => rest,
None => rest,
};
if rest.starts_with(':') {
let Some(second) = rest.get(1..3).and_then(|value| value.parse::<u32>().ok()) else {
return false;
};
if second >= 60 {
return false;
}
}
let _ = year;
true
}
fn fetch_text(url: &str) -> Result<String> {
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(60)))
.build()
.into();
let mut attempt = 1;
loop {
match agent.get(url).call() {
Ok(mut response) if response.status().is_success() => {
return response
.body_mut()
.with_config()
.limit(16 * 1024 * 1024)
.read_to_string()
.with_context(|| format!("reading {url}"));
}
Ok(response) => {
if attempt >= 5 {
bail!("fetching {url}: HTTP {}", response.status());
}
}
Err(error) => {
if attempt >= 5 {
return Err(error).with_context(|| format!("fetching {url}"));
}
}
}
std::thread::sleep(Duration::from_secs(2 * attempt));
attempt += 1;
}
}
fn write_atomic(path: &Path, text: &str) -> Result<()> {
let tmp = path.with_extension("tmp");
fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
fs::rename(&tmp, path).with_context(|| format!("renaming to {}", path.display()))
}
fn read_source(lgd_dir: &Path) -> Map<String, Value> {
fs::read_to_string(lgd_dir.join("source.json"))
.ok()
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
.and_then(|value| value.as_object().cloned())
.unwrap_or_default()
}
fn update_source(
lgd_dir: &Path,
mut source: Map<String, Value>,
key: &str,
value: Value,
) -> Result<()> {
source.insert(key.to_owned(), value);
source.insert(
"acknowledgement".to_owned(),
Value::String(ACKNOWLEDGEMENT.to_owned()),
);
let mut text =
serde_json::to_string_pretty(&Value::Object(source)).context("serializing source.json")?;
text.push('\n');
write_atomic(&lgd_dir.join("source.json"), &text)
}
fn utc_now() -> String {
crate::layout::utc_now()
}
pub fn states(force: bool, html: Option<&Path>, lgd_dir: &Path) -> Result<()> {
fs::create_dir_all(lgd_dir).with_context(|| format!("creating {}", lgd_dir.display()))?;
let out = lgd_dir.join("states.csv");
if out.is_file() && !force {
let text =
fs::read_to_string(&out).with_context(|| format!("reading {}", out.display()))?;
println!(
"states: {} (kept {})",
read_states_csv(&text)?.len(),
out.display()
);
return Ok(());
}
let page = match html {
Some(path) => {
fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?
}
None => fetch_text(STATES_URL)?,
};
let states = parse_states_page(&page)?;
write_atomic(&out, &states_csv(&states))?;
update_source(
lgd_dir,
read_source(lgd_dir),
"states",
json!({
"url": STATES_URL,
"fetched_at": utc_now(),
"count": states.len(),
"terms_url": TERMS_URL,
"terms": TERMS,
}),
)?;
println!("states: {} (wrote {})", states.len(), out.display());
Ok(())
}
pub fn districts(lgd_dir: &Path, downloaded_at: Option<&str>) -> Result<usize> {
fs::create_dir_all(lgd_dir).with_context(|| format!("creating {}", lgd_dir.display()))?;
let path = lgd_dir.join(DISTRICTS_FILE);
if !path.is_file() {
bail!(
"{} is missing. Manual step: {}",
path.display(),
manual_step(lgd_dir)
);
}
let text = fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
let districts = parse_districts_csv(&text)?;
let mut source = read_source(lgd_dir);
let earlier = source.get("districts").cloned().unwrap_or(Value::Null);
let sha256 = hex(&sha256_file(&path)?);
let original = lgd_dir.join(ORIGINAL_FILE);
let original_sha = if original.is_file() {
Some(hex(&sha256_file(&original)?))
} else {
None
};
let earlier_sha = earlier.get("sha256").and_then(Value::as_str);
let earlier_original = earlier
.get("original")
.and_then(|value| value.get("sha256"))
.and_then(Value::as_str);
let same_files =
earlier_sha == Some(sha256.as_str()) && earlier_original == original_sha.as_deref();
if downloaded_at.is_none() && earlier.get("downloaded_at").is_some() && !same_files {
eprintln!("lgd: the district files changed; downloaded_at dropped (pass --downloaded-at)");
}
let downloaded = downloaded_at.map(str::to_owned).or_else(|| {
same_files
.then(|| {
earlier
.get("downloaded_at")
.and_then(Value::as_str)
.map(str::to_owned)
})
.flatten()
});
let saved_at = crate::layout::format_utc(
i64::try_from(crate::layout::modified_millis(&path)? / 1000).unwrap_or_default(),
);
let mut entry = serde_json::Map::new();
entry.insert("file".into(), Value::String(DISTRICTS_FILE.into()));
entry.insert("from".into(), Value::String(DOWNLOAD_URL.into()));
entry.insert("report".into(), Value::String(REPORT.into()));
entry.insert("format".into(), Value::String(REPORT_FORMAT.into()));
if let Some(downloaded) = downloaded {
entry.insert("downloaded_at".into(), Value::String(downloaded));
}
if let Some(sha) = original_sha {
entry.insert(
"original".into(),
json!({ "file": ORIGINAL_FILE, "sha256": sha }),
);
}
entry.insert("saved_at".into(), Value::String(saved_at));
entry.insert("sha256".into(), Value::String(sha256));
entry.insert("count".into(), json!(districts.len()));
entry.insert("terms_url".into(), Value::String(TERMS_URL.into()));
entry.insert("terms".into(), Value::String(TERMS.into()));
update_source(lgd_dir, source.clone(), "districts", Value::Object(entry))?;
let _ = &mut source;
println!("districts: {} ({})", districts.len(), path.display());
Ok(districts.len())
}
pub fn run(args: &LgdArgs) -> Result<()> {
match &args.action {
LgdAction::States(states_args) => {
states(
states_args.force,
states_args.html.as_deref(),
&ldg_dir(args)?,
)?;
}
LgdAction::Districts(districts_args) => {
if let Some(at) = districts_args.downloaded_at.as_deref()
&& !is_iso_time(at)
{
eprintln!("--downloaded-at needs an ISO 8601 time with an offset, got {at:?}");
return Err(Exit(2).into());
}
districts(&ldg_dir(args)?, districts_args.downloaded_at.as_deref())?;
}
}
Ok(())
}
fn ldg_dir(args: &LgdArgs) -> Result<std::path::PathBuf> {
if let Some(dir) = args.dir.clone() {
return Ok(dir);
}
if let Some(dir) = crate::settings::current().run.lgd_dir.clone() {
return Ok(dir);
}
Ok(crate::layout::data_root()?.join("datasets").join("lgd"))
}
#[must_use]
pub fn source_entries(lgd_dir: &Path) -> BTreeMap<String, Value> {
read_source(lgd_dir).into_iter().collect()
}