~tsileo/entries

ref: 3e1f6bc0fb750588f86c0ed24a9786ea7f37dc0e entries/cli.py -rw-r--r-- 7.8 KiB
3e1f6bc0Thomas Sileo Tweak the setup.py 10 months ago
                                                                                
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
import binascii
import os
import pkg_resources
import urllib
import tempfile
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer

import click
import mf2py
import requests
import yaml

VERSION = pkg_resources.get_distribution("entries").version

CLIENT_ID = "https://hexa.ninja/5ce9a178def3b70a/entries-cli"
REDIRECT_URI = "http://localhost:7881/"


class IndieAuthCallbackHandler(BaseHTTPRequestHandler):
    """HTTPServer handler for intercepting the IndieAuth callback."""

    def __init__(self, request, address, server, me, token_endpoint):
        self.me = me
        self.token_endpoint = token_endpoint
        super().__init__(request, address, server)

    def log_message(self, format, *args):
        return

    def do_GET(self):
        data = urllib.parse.parse_qs(self.path[2:])
        # data contains
        # - code
        # - state
        # - me
        tok = requests.post(
            self.token_endpoint,
            data={
                "grant_type": "authorization_code",
                "code": data["code"][0],
                "client_id": CLIENT_ID,
                "redirect_uri": REDIRECT_URI,
                "me": self.me,
            },
            headers={"Accept": "application/json"},
        )
        tok.raise_for_status()

        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(
            b'<body style="background:#111;color:#ddd"><h1>Done, you can close this tab now.</h1></body>'
        )

        self.server.access_token = tok.json()["access_token"]


def _wait_for_access_token(me, tok_endpoint):
    """Spawn a HTTPServer and wait for the IndieAuth callback to get executed."""
    server = HTTPServer(
        ("localhost", 7881),
        lambda request, address, server: IndieAuthCallbackHandler(
            request, address, server, me, tok_endpoint
        ),
    )
    server.handle_request()
    return server.access_token


def get_access_token(u, scopes):
    """Initiate an IndieAuth Authorization flow to get an acess token (for talking to the Miropub endpoint)."""
    # Guess the identity from the URL
    me = urllib.parse.urlparse(u)._replace(path="/").geturl()

    # Fetch the 3 endpoints needed:
    # TODO(tsileo): clean error if missing
    dat = mf2py.parse(url=u)
    auth_endpoint = dat["rels"]["authorization_endpoint"][0]
    tok_endpoint = dat["rels"]["token_endpoint"][0]
    micropub_endpoint = dat["rels"]["micropub"][0]

    # Generate a random state
    state = binascii.hexlify(os.urandom(6)).decode()

    # Actually initiate the Authorization flow
    auth_url = (
        auth_endpoint
        + "?"
        + urllib.parse.urlencode(
            {
                "me": me,
                "response_type": "code",
                "state": state,
                "redirect_uri": REDIRECT_URI,
                "scope": " ".join(scopes),
                "client_id": CLIENT_ID,
            }
        )
    )

    # Open the URL in a tab
    webbrowser.open_new_tab(auth_url)

    click.echo("waiting for the IndieAuth callback...")
    tok = _wait_for_access_token(me, tok_endpoint)
    click.echo("success")

    # And wait for the callback via the redirect_uri
    return (me, micropub_endpoint, tok)


def micropub_create(micropub_endpoint, access_token, content, meta):
    props = {"content": [content]}
    if meta["name"]:
        props["name"] = [meta["name"]]
    if meta["category"]:
        props["category"] = meta["category"]
    for k in ["mp-slug", "mp-extra-head", "mp-extra-body"]:
        if k in meta:
            props[k] = [meta[k]]

    resp = requests.post(
        micropub_endpoint,
        headers={"Authorization": f"Bearer {access_token}"},
        json={"type": ["h-entry"], "properties": props},
    )
    resp.raise_for_status()
    webbrowser.open_new_tab(resp.headers.get("Location"))


def micropub_update(micropub_endpoint, access_token, url, content, meta):
    replace = {"content": [content]}
    if meta["name"]:
        replace["name"] = [meta["name"]]
    if meta["category"]:
        replace["category"] = meta["category"]
    # XXX no mp-slug update
    for k in ["mp-extra-head", "mp-extra-body"]:
        if meta[k]:
            replace[k] = [meta[k]]
    resp = requests.post(
        micropub_endpoint,
        headers={"Authorization": f"Bearer {access_token}"},
        json={"action": "update", "url": url, "replace": replace},
    )
    resp.raise_for_status()
    webbrowser.open_new_tab(resp.headers.get("Location"))


def micropub_delete(micropub_endpoint, access_token, url):
    resp = requests.post(
        micropub_endpoint,
        headers={"Authorization": f"Bearer {access_token}"},
        json={"action": "delete", "url": url},
    )
    resp.raise_for_status()
    webbrowser.open_new_tab(url)


def micropub_source(micropub_endpoint, access_token, url):
    resp = requests.get(
        micropub_endpoint,
        {"q": "source", "url": url},
        headers={"Authorization": f"Bearer {access_token}"},
    )
    resp.raise_for_status()
    return resp.json()


@click.group()
@click.version_option(VERSION)
def cli():
    pass


@click.command()
@click.argument("url", required=True)
def get_token(url):
    _, _, tok = get_access_token(url, ["create", "update", "delete"])
    click.echo(tok)


header = """name: title
mp-slug: slug
category: []
---
"""


def edit(header):
    """`click.edit` wrapper that keeps a copy of the edited content in a file."""
    dat = click.edit(header)
    if dat is None:
        raise ValueError("cancelled, no data saved")
    raw_meta, message = dat.split("---", 1)

    # Keep the data in case the server fails
    # TODO(tsileo): clean it
    with tempfile.NamedTemporaryFile("w", delete=False) as cache:
        cache.write(dat)

    click.echo(f"data will be available at {cache.name} in case of crash")
    return message, yaml.safe_load(raw_meta), cache.name


def done(t):
    os.remove(t)
    click.echo("success 🐢")


@click.command()
@click.argument("url", required=True)
def create(url):
    _, micropub_endpoint, tok = get_access_token(url, ["create"])

    message, meta, t = edit(header)

    micropub_create(micropub_endpoint, tok, message, meta)
    done(t)


def _get(source, k, default):
    if k in source["properties"] and len(source["properties"][k]):
        vs = source["properties"][k]
        if k in ["category"]:
            return vs
        else:
            return vs[0]

    return default


def build_header(source):
    name = _get(source, "name", "null")
    slug = _get(source, "mp-slug", "null")
    extra_head = "\n  ".join(_get(source, "mp-extra-head", "").split("\n"))
    extra_body = "\n  ".join(_get(source, "mp-extra-body", "").split("\n"))
    cat = _get(source, "category", [])
    return f"""name: {name}
mp-slug: {slug}
category: {cat!s}
mp-extra-head: |
  {extra_head}
mp-extra-body: |
  {extra_body}
---"""


@click.command()
@click.argument("url", required=True)
def update(url):
    _, micropub_endpoint, tok = get_access_token(url, ["update"])

    # Fetch the source
    source = micropub_source(micropub_endpoint, tok, url)
    existing_content = source["properties"]["content"][0]

    # Edit
    new_content, meta, t = edit(build_header(source) + existing_content)
    micropub_update(micropub_endpoint, tok, url, new_content, meta)
    done(t)


@click.command()
@click.argument("url", required=True)
def source(url):
    _, micropub_endpoint, tok = get_access_token(url, ["update"])

    # Fetch the source
    source = micropub_source(micropub_endpoint, tok, url)
    click.echo(source)


@click.command()
@click.argument("url", required=True)
def delete(url):
    _, micropub_endpoint, tok = get_access_token(url, ["delete"])
    micropub_delete(micropub_endpoint, tok, url)


cli.add_command(get_token)
cli.add_command(create)
cli.add_command(update)
cli.add_command(source)
cli.add_command(delete)


if __name__ == "__main__":
    cli()