summaryrefslogtreecommitdiff
path: root/main.py
blob: c7bdd4389c009910c56ee5c71706fd1822c43906 (plain)
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
import argparse
from configparser import ConfigParser, NoOptionError
from datetime import datetime, timezone
import sys

from suntime import Sun, SunTimeException
from xdg import xdg_config_home


def get_location(args):
    if args.latitude is not None and args.longitude is not None:
        return args.latitude, args.longitude

    config = ConfigParser()
    config_location = xdg_config_home().joinpath("auto-dark-mode", "config")
    try:
        with open(config_location) as stream:
            config.read_string("[auto-dark-mode]\n" + stream.read())
        config.read(config_location)

        latitude = config.getfloat("auto-dark-mode", "latitude")
        longitude = config.getfloat("auto-dark-mode", "longitude")
    except (FileNotFoundError, NoOptionError):
        sys.exit(
            f"Please supply latitude and longitude with the --latitude and --longitude flags, or set them in {config_location}"
        )

    return latitude, longitude


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Check if we're in day (after sunrise but before sunset) or night (after sunset but before sunrise) time"
    )
    parser.add_argument(
        "--day",
        action="store_true",
        default=False,
        help="return successfully if it's day",
    )
    parser.add_argument(
        "--night",
        action="store_true",
        default=True,
        help="return successfully if it's night (default)",
    )
    parser.add_argument("--latitude", type=float, help="specify your latitude")
    parser.add_argument("--longitude", type=float, help="specify your longitude")

    args = parser.parse_args()

    latitude, longitude = get_location(args)

    try:
        sun = Sun(latitude, longitude)
    except SunTimeException:
        sys.exit("Could not determine sunrise/sunset times")

    utc_now = datetime.now(timezone.utc)

    if utc_now > sun.get_sunrise_time() and utc_now < sun.get_sunset_time():
        if not args.day:
            sys.exit(1)

    else:
        if args.day:
            sys.exit(1)