salah_cli 0.1.0

CLI to calculate Islamic prayer times.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use anyhow::{Context, Result};
use chrono::NaiveDate;
use chrono_tz::Tz;
use clap::{ArgAction, Parser, Subcommand};
use colored::*;
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
use serde::Deserialize;
use std::io::Write;

use crate::api;
use crate::datetime;
use crate::times::types;

pub const ALLOWED_TIMES: [&'static str; 8] = [
    "fajr", "sunrise", "dhuhr", "asr", "maghrib", "isha", "midnight", "fardh",
];

pub const TIMES_DESC: [&'static str; 8] = [
    "The dawn prayer time.",
    "Sunrise time. Fajr ends at sunrise",
    "The mid-day prayer time.",
    "The evening prayer time.",
    "The sunset prayer time.",
    "The night prayer time.",
    "Islamic midnight time. Isha ends at midnight",
    "Gets only the 5 obligatory (fardh) prayer times. Ignores any others",
];

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Options {
    #[command(subcommand)]
    commands: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Use location (city/country) to get prayer times. WARNING: Uses external API call, network connection required.
    Location {
        #[command(flatten)]
        common: CommonConfig,

        /// City to calculate the times for
        #[arg(long)]
        city: String,

        /// Country to calculate the times for
        #[arg(long)]
        country: String,
    },
    /// Use coordinates (latitude/longitude) to get prayer times.
    Coord {
        #[command(flatten)]
        common: CommonConfig,

        /// Latitude to calculate the times for
        #[arg(long)]
        lat: f64,

        /// Longitude to calculate the time for
        #[arg(long)]
        lng: f64,
    },
    /// Lists all the available timings.
    Timings,
    /// Lists all the calculation authorities
    Authority,
    /// Lists all the available timezones with search functionality
    Timezones {
        /// Search query to find specific available timezones
        #[arg(default_value_t=String::new())]
        query: String,
    },
}

#[derive(Parser, Debug)]
pub struct CommonConfig {
    /// Names of the timings to calculate for (see `salah timings` for available values) (ignored by --all)
    #[arg(action=ArgAction::Append)]
    timings: Vec<String>,

    /// Date to calculate the timings for (YYYY-MM-DD). Use `today` for today's date.
    #[arg(short, long, default_value_t=String::from("today"))]
    date: String,

    /// Timezone to output the timings for.
    #[arg(short, long, default_value_t=String::from("America/Toronto"))]
    timezone: String,

    /// Calculates all the available prayer timings.
    #[arg(short, long, action=ArgAction::SetTrue)]
    all: bool,

    /// If set, uses Hanafi madhab for Asr calculation [default: false]
    #[arg(long, action=ArgAction::SetTrue)]
    hanafi: bool,

    /// Calculation authority to use (see `salah authority` for available values)
    #[arg(long, default_value_t=String::from("ISNA"))]
    auth: String,

    /// Format string for timings output. See `man strftime` for configuration.
    #[arg(long, default_value_t=String::from("%H:%M:%S"))]
    format: String,
}

impl CommonConfig {
    fn parsed_date(&self) -> Result<NaiveDate> {
        let tz: Tz = self
            .parsed_timezone()
            .with_context(|| format!("Unable to parse timezone"))?;

        return datetime::str2date(&self.date, tz);
    }

    fn parsed_timezone(&self) -> Result<Tz> {
        match self.timezone.parse::<Tz>() {
            Ok(t) => Ok(t),
            Err(e) => return Err(anyhow::anyhow!(e)),
        }
    }

    fn parsed_timings(&self) -> Result<Vec<types::Timing>> {
        let mut timings: Vec<types::Timing> = vec![];
        let all_timings: Vec<types::Timing> = types::Timing::list().into_iter().collect();
        if self.all {
            timings = all_timings;
        } else {
            for timing in &self.timings {
                let m = match types::Timing::from_str(timing) {
                    Some(t) => t,
                    None => return Err(anyhow::anyhow!("timing = `{}` is not valid!", timing)),
                };
                timings.push(m);
            }
        }

        return Ok(timings);
    }

    fn parsed_auth(&self) -> Result<types::Authority> {
        match types::Authority::from_str(&self.auth) {
            Some(a) => Ok(a),
            None => Err(anyhow::anyhow!("authority = `{}` is not valid!", self.auth)),
        }
    }
}

#[derive(Debug)]
pub enum ParsedOptions {
    Calculation {
        date: NaiveDate,
        timezone: Tz,
        lat: f64,
        lng: f64,
        timings: Vec<types::Timing>,
        auth: types::Authority,
        school: types::School,
        format: String,
    },
    Timings,
    Authority,
    Timezones {
        query: String,
    },
}

/// Validates the command-line arguments
pub async fn parse() -> Result<ParsedOptions> {
    let opts = Options::parse();

    match &opts.commands {
        Commands::Location {
            common,
            city,
            country,
        } => {
            let date = common
                .parsed_date()
                .with_context(|| format!("Failed to create date with `{}`", common.date))?;
            let timezone = common
                .parsed_timezone()
                .with_context(|| format!("Failed to create timezone with `{}`", common.timezone))?;
            let timings = common
                .parsed_timings()
                .with_context(|| format!("Failed to parse timings with {:?}", common.timings))?;
            let auth = common
                .parsed_auth()
                .with_context(|| format!("Failed to parse authority with `{}`", common.auth))?;
            let school = if common.hanafi {
                types::School::Hanafi
            } else {
                types::School::Shafi
            };
            let format = common.format.to_owned();

            // API call to get lat,lng from city, country
            #[derive(Deserialize)]
            struct APICoord {
                lat: String,
                lon: String,
            }
            let url = format!(
                "https://nominatim.openstreetmap.org/search?city={}&country={}&format=jsonv2",
                city, country
            );
            let mut headers = HeaderMap::new();
            headers.insert(USER_AGENT, HeaderValue::from_static("salah-cli"));
            let coords: Vec<APICoord> = api::fetch::<Vec<APICoord>>(url.as_str(), headers)
                .await
                .with_context(|| {
                    format!(
                        "Could not get coordinates with city = `{}` and country = `{}`",
                        city, country
                    )
                })?;

            if coords.len() < 1 {
                return Err(anyhow::anyhow!("Could not find lat, lng from city = `{}` and country = `{}`. Please check spelling!", city, country));
            }

            let lat = coords[0]
                .lat
                .parse::<f64>()
                .with_context(|| format!("Could not convert `lat` = `{}` to f64", coords[0].lat))?;
            let lng = coords[0]
                .lon
                .parse::<f64>()
                .with_context(|| format!("Could not convert `lng` = `{}` to f64", coords[0].lon))?;

            return Ok(ParsedOptions::Calculation {
                date,
                timezone,
                lat,
                lng,
                timings,
                auth,
                school,
                format,
            });
        }
        Commands::Coord { common, lat, lng } => {
            let date = common
                .parsed_date()
                .with_context(|| format!("Failed to create date with `{}`", common.date))?;
            let timezone = common
                .parsed_timezone()
                .with_context(|| format!("Failed to create timezone with `{}`", common.timezone))?;
            let timings = common
                .parsed_timings()
                .with_context(|| format!("Failed to parse timings with {:?}", common.timings))?;
            let auth = common
                .parsed_auth()
                .with_context(|| format!("Failed to parse authority with `{}`", common.auth))?;
            let school = if common.hanafi {
                types::School::Hanafi
            } else {
                types::School::Shafi
            };
            let format = common.format.to_owned();
            return Ok(ParsedOptions::Calculation {
                date,
                timezone,
                lat: *lat,
                lng: *lng,
                timings,
                auth,
                school,
                format,
            });
        }
        Commands::Timings => {
            return Ok(ParsedOptions::Timings);
        }
        Commands::Authority => {
            return Ok(ParsedOptions::Authority);
        }
        Commands::Timezones { query } => {
            return Ok(ParsedOptions::Timezones {
                query: query.to_owned(),
            });
        }
    }
}

pub fn stdout_writer() -> std::io::BufWriter<std::io::StdoutLock<'static>> {
    let stdout = std::io::stdout();
    let writer = std::io::BufWriter::new(stdout.lock());
    return writer;
}

pub fn display_timings() {
    let mut writer = stdout_writer();

    writer
        .write(
            format!(
                "{}: {}",
                "Usage".underline(),
                "salah <location | coords> [OPTIONS] [TIMINGS]..."
            )
            .as_bytes(),
        )
        .unwrap();
    writer.write(b"\n").unwrap();
    writer
        .write(b"\nThe below can be passed to [TIMINGS]...")
        .unwrap();
    writer.write(b"\n").unwrap();
    writer
        .write(format!("\n{}:", "Timings".underline()).as_bytes())
        .unwrap();

    for time in types::Timing::list() {
        writer
            .write(
                format!(
                    "\n  {:<width$}{:<width$}",
                    time.to_str(),
                    time.desc(),
                    width = 10
                )
                .as_bytes(),
            )
            .unwrap();
    }

    writer.write(b"\n").unwrap();
    writer.flush().unwrap();
}

pub fn display_authority() {
    let mut writer = stdout_writer();

    writer
        .write(format!("{}: {}", "Usage".underline(), "--auth <AUTH>").as_bytes())
        .unwrap();
    writer.write(b"\n").unwrap();
    writer
        .write(format!("\n{}:", "Explanation".underline()).as_bytes())
        .unwrap();

    writer
        .write(b"\nCalculation authorities are used for the calculation of Fajr and Isha.")
        .unwrap();
    writer.write(b"\nThe time for Fajr is described as dawn; when there is fine white line at the horizon.").unwrap();
    writer.write(b"\nIsha time is described as when the night sky has lost all the light from the sunset.").unwrap();
    writer
        .write(
            b"\nAs this is quite ambiguous, the scholars have differed upon the angle that the sun",
        )
        .unwrap();
    writer
        .write(
            b"\nmakes when these two times occur. Each authority has slightly different angles for",
        )
        .unwrap();
    writer
        .write(b"\nFajr and Isha. Makkah uses a time difference from Maghrib (sunset).")
        .unwrap();
    writer
        .write(
            b"\n\nThe below can be used with the --auth <AUTH> option when calculating timings.\n",
        )
        .unwrap();
    writer
        .write(format!("\n{}:", "Authorities".underline()).as_bytes())
        .unwrap();

    for auth in types::Authority::list() {
        writer
            .write(
                format!(
                    "\n  {:<width$}{:<width$}",
                    auth.to_str(),
                    format!("{} - {}", auth.desc(), auth.name()),
                    width = 10
                )
                .as_bytes(),
            )
            .unwrap();
    }
    writer.write(b"\n").unwrap();

    writer.flush().unwrap();
}

pub fn display_timezones(query: &String) {
    let timezones = include_str!("../data/tz.txt");
    let mut writer = stdout_writer();
    writer
        .write(format!("{}: {}", "Usage".underline(), "-t, --timezone <TIMEZONE>").as_bytes())
        .unwrap();
    writer.write(b"\n").unwrap();
    writer
        .write(b"\nThe below values can be used with the -t, --timezone <TIMEZONE> option.")
        .unwrap();
    if query == &String::new() {
        writer
            .write(b"\nOptionally, use salah timezones [QUERY] to search for specific timezones.")
            .unwrap();
        writer.write(b"\n").unwrap();
        writer
            .write(format!("\n{}:", "Timezones".underline()).as_bytes())
            .unwrap();
        for line in timezones.lines() {
            if line != "\n" {
                writer.write(format!("\n  {}", line).as_bytes()).unwrap();
            }
        }
    } else {
        writer.write(b"\n").unwrap();
        writer
            .write(format!("\n{}: `{}`", "Query".underline(), query).as_bytes())
            .unwrap();
        writer.write(b"\n").unwrap();
        writer
            .write(format!("\n{}:", "Results".underline()).as_bytes())
            .unwrap();

        let space_separated: Vec<&str> = query.split(" ").collect();
        let parsed_query = space_separated.join("_").to_lowercase();
        let mut num_found = 0;

        for line in timezones.lines() {
            if line.to_lowercase().contains(parsed_query.as_str()) {
                writer.write(format!("\n  {}", line).as_bytes()).unwrap();
                num_found += 1;
            }
        }
        writer
            .write(format!("\nFound {} result(s)", num_found).as_bytes())
            .unwrap();
    }
    writer.write(b"\n").unwrap();
    writer.flush().unwrap();
}