-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxbel-add.py
executable file
·102 lines (79 loc) · 2.58 KB
/
xbel-add.py
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
#!/usr/bin/env python3
# SPDX-License-Identifier: WTFPL
# /// script
# dependencies = ["lxml"]
# ///
import argparse
import datetime
import locale
import mimetypes
import os
from pathlib import Path
import sys
import lxml.etree
def xdg_share():
return Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share"))
DEFAULT_PATH = xdg_share() / "recently-used.xbel"
def add_bookmark(url, xbel):
when_add = datetime.datetime.now(datetime.timezone.utc)
bookmark = lxml.etree.SubElement(xbel, "bookmark")
bookmark.attrib["href"] = url
bookmark.attrib["added"] = (
when_add.isoformat("T").replace("+00:00", "Z")
)
bookmark.attrib["modified"] = bookmark.attrib["added"]
bookmark.attrib["visited"] = bookmark.attrib["added"]
info = lxml.etree.SubElement(bookmark, "info")
metadata = lxml.etree.SubElement(info, "metadata")
metadata.attrib["owner"] = "http://freedesktop.org"
mime = lxml.etree.SubElement(
metadata,
"{http://www.freedesktop.org/standards/shared-mime-info}mime-type",
)
try:
mime.attrib["type"] = mimetypes.guess_type(url)[0]
except (TypeError, IndexError):
mime.attrib["type"] = "application/octet-stream"
# not sure if all of this is required, but it seems apps tend to discard
# the whole XBEL if some of it is missing...
apps = lxml.etree.SubElement(
metadata,
"{http://www.freedesktop.org/standards/desktop-bookmarks}applications",
)
app = lxml.etree.SubElement(
apps,
"{http://www.freedesktop.org/standards/desktop-bookmarks}application",
)
app.attrib["name"] = "xbel-add"
app.attrib["exec"] = "false"
app.attrib["modified"] = bookmark.attrib["added"]
app.attrib["count"] = "1"
def main():
locale.setlocale(locale.LC_ALL, "")
parser = argparse.ArgumentParser()
parser.add_argument(
"path", type=Path,
help="Path to add as recently used in XBEL file",
)
parser.add_argument(
"--xbel", default=DEFAULT_PATH,
help=f"Path of XBEL file (default: {DEFAULT_PATH})",
)
args = parser.parse_args()
args.path = args.path.resolve()
if args.xbel == "-":
fp = sys.stdin
else:
fp = open(args.xbel)
with fp:
tree = lxml.etree.parse(fp)
root = tree.getroot()
if root.tag != "xbel":
sys.exit(f"error: expect 'xbel' root tag, got {xbel.tag!r}")
add_bookmark(args.path.as_uri(), root)
if args.xbel == "-":
tree.write(sys.stdout.buffer)
else:
tree.write(args.xbel)
if __name__ == "__main__":
main()