Passed
Push — main ( 25f9cf...6bc2f2 )
by Jace
01:32 queued 13s
created

slackoff.browser.detect()   B

Complexity

Conditions 6

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 18
rs 8.6666
c 0
b 0
f 0
cc 6
nop 1
1
import plistlib
2
from pathlib import Path
3
4
import log
5
6
from . import script
7
8
FUNCTIONS = Path(__file__).parent / "browser.applescript"
9
PREFERENCES = (
10
    Path.home()
11
    / "Library"
12
    / "Preferences"
13
    / "com.apple.LaunchServices/com.apple.launchservices.secure.plist"
14
)
15
16
NAMES = {
17
    "com.apple.safari": "Safari",
18
    "com.google.chrome": "Google Chrome",
19
    "org.mozilla.firefox": "Firefox",
20
}
21
DEFAULT = NAMES["com.google.chrome"]
22
23
24
def detect(data: dict | None = None) -> str:
25
    if data is None:
26
        if PREFERENCES.exists():
27
            with PREFERENCES.open("rb") as fp:
28
                data = plistlib.load(fp)
29
        else:
30
            log.debug(f"File not found: {PREFERENCES}")
31
            data = {}
32
33
    for handler in data.get("LSHandlers", []):
34
        if handler.get("LSHandlerURLScheme") == "http":
35
            role = handler["LSHandlerRoleAll"]
36
            name = NAMES[role]
37
            log.info(f"Detected default browser: {name}")
38
            return name
39
40
    log.warn("Unable to determine the default browser")
41
    return DEFAULT
42
43
44
def close(name: str = "") -> bool:
45
    replacements = {DEFAULT: name or detect()}
46
    return script.call(FUNCTIONS, "close()", replacements)
47