__init__.py 13.1 KB
Newer Older
Michael Murtaugh's avatar
Michael Murtaugh committed
1
2
3
4
5
6
7
8
from aiohttp import web
import sys, os, asyncio, json
from asyncio import create_subprocess_exec
from urllib.parse import urlparse, unquote as urlunquote, quote as urlquote
import argparse
from asyncio.subprocess import DEVNULL, STDOUT, PIPE
import aiohttp
import base64
9

Michael Murtaugh's avatar
Michael Murtaugh committed
10
11
12
"""
Todo: use proper http error responses for errors, see aiohttp/http_exceptions.py
"""
13

Michael Murtaugh's avatar
Michael Murtaugh committed
14
15
16
17
18
19
20
21
MAKE = {
    'UP_TO_DATE': 0,
    'NEEDS_REMAKING': 1,
    'NOT_MAKEABLE': 2
}

MAKE_BY_CODE = {code: value for value, code in MAKE.items()}

Michael Murtaugh's avatar
Michael Murtaugh committed
22

Michael Murtaugh's avatar
Michael Murtaugh committed
23
async def is_makeable (path, cwd=".", makefile="makefile", make="make", verbose=False):
Michael Murtaugh's avatar
Michael Murtaugh committed
24
25
26
27
28
29
30
    """
    returns:
      0=file is up to date,
      1=file needs remaking,
      2=file is not makeable
    """
    rpath = os.path.relpath(path, cwd)
31
    p = await create_subprocess_exec(make, "--question", "-f", makefile, rpath, cwd = cwd, stdout=DEVNULL, stderr=DEVNULL)
Michael Murtaugh's avatar
Michael Murtaugh committed
32
33
    # retcode 0=file is up to date, 1=file needs remaking, 2=file is not makeable
    ret = await p.wait()
Michael Murtaugh's avatar
Michael Murtaugh committed
34
35
    if verbose:
        print (f"{make} --question -f {makefile} {path} returned: {MAKE_BY_CODE[ret]}", file=sys.stderr)
Michael Murtaugh's avatar
Michael Murtaugh committed
36
    await log(f"is_makeable {0}: {MAKE_BY_CODE[ret]}".format(path, ret))
Michael Murtaugh's avatar
Michael Murtaugh committed
37
38
    return ret

Michael Murtaugh's avatar
Michael Murtaugh committed
39
async def make (path, cwd=".", makefile="makefile", make="make", force=False, verbose=False):
Michael Murtaugh's avatar
Michael Murtaugh committed
40
    rpath = os.path.relpath(path, cwd)
41
    makeargs = [make, "-f", makefile, rpath]
Michael Murtaugh's avatar
Michael Murtaugh committed
42
43
44
45
46
47
48
49
50
51
52
53
    if force:
        makeargs.append("-B")
    p = await create_subprocess_exec(*makeargs, stdout = PIPE, stderr = STDOUT, cwd = cwd)
    resp = ""
    while True:
        line = await p.stdout.readline()
        if not line:
            break
        resp+=line.decode("utf-8")
        # log(line)
        # print (line)
    ret = await p.wait() == 0
Michael Murtaugh's avatar
Michael Murtaugh committed
54
55
    if verbose:
        print ("make {0}: {1}".format(path, ret), file=sys.stderr)
Michael Murtaugh's avatar
Michael Murtaugh committed
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
    await log("make {0}: {1}".format(path, ret))
    return (ret, resp)

textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))

def is_binary_file (p):
    """ returns none on ioerror """
    try:
        return not os.path.isdir(p) and is_binary_string(open(p, 'rb').read(1024))
    except IOError:
        return None

def editable (path):
    _, ext = os.path.splitext(path)
    ext = ext.lower()[1:]
    # print (f"editable? ext {ext}", file=sys.stderr)
    return ((ext not in ("html", "htm")) and not os.path.isdir(path) and not is_binary_file(path))

# From aiohttp/web_urldispatcher.py
# remove editor_url (no longer being used ?!)
def directory_as_html(filepath, directory, prefix, editor_url=None):
    # returns directory's index as html

    # sanity check
    assert os.path.isdir(filepath)

    # relative_path_to_dir = filepath.relative_to(self._directory)
    relative_path_to_dir = os.path.relpath(filepath, directory)
    
    index_of = "Index of /{}".format(relative_path_to_dir)
    h1 = "<h1>{}</h1>".format(index_of)

    index_list = []
    dir_index = os.listdir(filepath)
    for _file in sorted(dir_index):
        # show file url as relative to static path
        # rel_path = _file.relative_to(self._directory).as_posix()
        # rel_path = os.path.relpath(_file, directory)
        # file_url = prefix + '/' + rel_path
        fp = os.path.join(filepath, _file)
        file_url = '/' + urlquote(fp)
        target = None
        if editable(fp) and editor_url:
            file_url = "{0}#{1}".format(editor_url, file_url)
            target = "editor"
        # if file is a directory, add '/' to the end of the name
        if os.path.isdir(_file):
            file_name = "{}/".format(_file)
        else:
            file_name = _file
        if target:
            link_src = '<li><a href="{url}" target="{target}">{name}</a></li>'.format(
                url=file_url,
                target="editor",
                name=file_name)
        else:
            link_src = '<li><a href="{url}">{name}</a></li>'.format(
                url=file_url,
                name=file_name)
        index_list.append(link_src)
    ul = "<ul>\n{}\n</ul>".format('\n'.join(index_list))
    body = "<body>\n{}\n{}\n</body>".format(h1, ul)

Michael Murtaugh's avatar
Michael Murtaugh committed
120
    head_str = "<head>\n<title>{}</title>\n</head>".format(index_of)
Michael Murtaugh's avatar
Michael Murtaugh committed
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
    html = "<html>\n{}\n{}\n</html>".format(head_str, body)

    return html

# Based on aiohttp/web_urldispatcher.py
def directory_as_json(filepath, directory, prefix, editor_url=None):
    # returns directory's index as html

    # sanity check
    assert os.path.isdir(filepath)

    # relative_path_to_dir = filepath.relative_to(self._directory)
    relative_path_to_dir = os.path.relpath(filepath, directory)
    # index_of = "Index of /{}".format(relative_path_to_dir)
    # h1 = "<h1>{}</h1>".format(index_of)

    index_list = []
    dir_index = os.listdir(filepath)
    for _file in sorted(dir_index):
        # show file url as relative to static path
        # rel_path = _file.relative_to(self._directory).as_posix()
        # rel_path = os.path.relpath(_file, directory)
        # file_url = prefix + '/' + rel_path
        if filepath == ".":
            fp = _file
        else:
            fp = os.path.join(filepath, _file)
        file_url = '/' + urlquote(fp)
        target = None
        if editable(fp) and editor_url:
            file_url = "{0}#{1}".format(editor_url, file_url)
            target = "editor"

        # if file is a directory, add '/' to the end of the name
        is_dir = os.path.isdir(fp)
        if is_dir:
            file_name = "{}/".format(_file)
        else:
            file_name = _file
        stat = os.stat(fp)
        index_list.append({
            'url': file_url,
            'name': file_name,
            'editable': editable(fp),
            'size': stat.st_size,
            'mtime': stat.st_mtime,
            'atime': stat.st_atime,
            'dir': is_dir
        })
    ret = {}
    ret['filepath'] = filepath
    ret['rpath'] = relative_path_to_dir
    ret['children'] = index_list

    return json.dumps(ret)

async def route_get (request):
    # return FileResponse(filepath, chunk_size=self._chunk_size)
    # print ("rOUTE_get", request.rel_url, request.rel_url.query)
    path = urlunquote(urlparse(request.rel_url.raw_path.lstrip("/")).path)
Michael Murtaugh's avatar
Michael Murtaugh committed
181
    # print ("GET", path, file=sys.stderr)
Michael Murtaugh's avatar
Michael Murtaugh committed
182
183
    if path == '':
        path = '.'
Michael Murtaugh's avatar
Michael Murtaugh committed
184
    pathisdir = os.path.isdir(path)
185
186
    makefile = request.app['makefile']
    makecmd = request.app['make']
Michael Murtaugh's avatar
Michael Murtaugh committed
187
188
189
190
191
192
193
    verbose = request.app['verbose']
    if not pathisdir:
        # only use is_makeable with paths
        # scons treats directory names as all targets in a folder
        im = await is_makeable(path, makefile=makefile, make=makecmd, verbose=verbose)
    else:
        im = MAKE['UP_TO_DATE']
Michael Murtaugh's avatar
Michael Murtaugh committed
194
    remake = 'remake' in request.rel_url.query
Michael Murtaugh's avatar
Michael Murtaugh committed
195
196
    if path and (im == MAKE['NEEDS_REMAKING'] or \
            (im == MAKE['UP_TO_DATE'] and remake)):
Michael Murtaugh's avatar
Michael Murtaugh committed
197
        code, resp = await make(path, makefile=makefile, make=makecmd, force=remake, verbose=verbose)
Michael Murtaugh's avatar
Michael Murtaugh committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        if not code:
            resppage = """<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>An error occuring making the file {0}. Here's the output:</p>
<p><pre>{1}</pre></p>
</body>
</html>""".format(path, resp)
            return web.Response(text=resppage, content_type="text/html")
    if os.path.exists(path):
        if os.path.isdir(path):
            if 'application/json' in request.headers.get("Accept") or 'json' in request.rel_url.query:
                return web.Response(text=directory_as_json(path, '', '', editor_url=request.app['editor']), content_type="application/json")                
            else:
                return web.Response(text=directory_as_html(path, '', '', editor_url=request.app['editor']), content_type="text/html")
        else:
            return web.FileResponse(path, chunk_size=256*1024)
217
    else:
Michael Murtaugh's avatar
Michael Murtaugh committed
218
219
220
        raise web.HTTPNotFound()
        # return web.Response(text="404 on path {0}".format(path))

Michael Murtaugh's avatar
Michael Murtaugh committed
221
async def route_post (request, verbose=False):
Michael Murtaugh's avatar
Michael Murtaugh committed
222
223
    """ write posted text value to file """
    path = urlunquote(urlparse(request.rel_url.raw_path.lstrip("/")).path)
Michael Murtaugh's avatar
Michael Murtaugh committed
224
225
    if verbose:
        print ("POST", path, file=sys.stderr)
Michael Murtaugh's avatar
Michael Murtaugh committed
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
    # if os.path.exists(path) and os.path.isfile(path):
    # POST CAN CLOBBER ANY FILES THAT ARE WRITABLE BY THE USER !
    # this is maybe a way too dangerous default ...
    # 
    data = await request.post()
    resp = {}
    # SAVE
    if 'text' in data:
        text = data['text']
        # doing file io inline here is not strictly speaking very async ;)
        with open(path, "w") as f:
            f.write(text)
        resp['text'] = 'ok'
    if 'base64' in data:
        data = data['base64']
        # print ("base64", data)
        # strip optional data header: data:image/png;base64,FFFFFFFF
        if data.startswith("data:"):
            data = data.split(",", 1)[1]
        with open(path, "wb") as f:
            f.write(base64.b64decode(data))
    # RENAME
    if 'name' in data:
        newpath = os.path.join(os.path.split(path)[0], data['name'])
        if path != newpath:
            os.rename(path, newpath)
            resp['name'] = 'ok'
    # DELETE
    if 'delete' in data:
        os.remove(path)
        resp['delete'] = 'ok'
    return web.Response(text=json.dumps(resp), content_type="application/json")
    # else:
    #     raise web.HTTPMethodNotAllowed()
        # return web.Response(text="post not allowed on {0}".format(path))

active_sockets = []

async def log (msg):
    for ws in active_sockets:
        await ws.send_str(msg)


async def websocket_handler(request):
Michael Murtaugh's avatar
Michael Murtaugh committed
270
    # print('Websocket connection starting')
Michael Murtaugh's avatar
Michael Murtaugh committed
271
272
    ws = web.WebSocketResponse()
    await ws.prepare(request)
Michael Murtaugh's avatar
Michael Murtaugh committed
273
    # print('Websocket connection ready')
Michael Murtaugh's avatar
Michael Murtaugh committed
274
275
276
    active_sockets.append(ws)

    async for msg in ws:
Michael Murtaugh's avatar
Michael Murtaugh committed
277
        # print(msg)
Michael Murtaugh's avatar
Michael Murtaugh committed
278
        if msg.type == aiohttp.WSMsgType.TEXT:
Michael Murtaugh's avatar
Michael Murtaugh committed
279
            # print(msg.data)
Michael Murtaugh's avatar
Michael Murtaugh committed
280
281
282
283
284
285
286
            if msg.data == 'close':
                await ws.close()
            else:
                await ws.send_str(msg.data + '/answer')

    active_sockets.remove(ws)

Michael Murtaugh's avatar
Michael Murtaugh committed
287
    # print('Websocket connection closed')
Michael Murtaugh's avatar
Michael Murtaugh committed
288
289
    return ws

290
291
292
293
294

async def lab_index_handler (request):
    htdocs = request.app['htdocs']
    return web.FileResponse(os.path.join(htdocs, "index.html"))

Michael Murtaugh's avatar
Michael Murtaugh committed
295
296
297
298
299
300
async def terminal_index_handler (request):
    htdocs = request.app['htdocs']
    return web.FileResponse(os.path.join(htdocs, "terminal", "index.html"))

# from .terminal import terminal_websocket_handler

Michael Murtaugh's avatar
Michael Murtaugh committed
301
302
303
def main ():
    ap = argparse.ArgumentParser("make & serve")
    ap.add_argument("--makefile", "-f", default="Makefile")
304
    ap.add_argument("--scons", action="store_true", default=False)
Michael Murtaugh's avatar
Michael Murtaugh committed
305
306
307
308
    ap.add_argument("--host", default="localhost")
    ap.add_argument("--port", type=int, default=8000)
    ap.add_argument("--editor", default=None)
    ap.add_argument("--static", nargs=2, default=None, action="append")
Michael Murtaugh's avatar
Michael Murtaugh committed
309
    ap.add_argument("--verbose", action="store_true", default=False)
310
    ap.add_argument("--version", action="store_true", default=False)
Michael Murtaugh's avatar
Michael Murtaugh committed
311
312
    args = ap.parse_args()

313
314
315
316
    version = '3.1.0-dev-2021-02-14'
    print (f"Makeserver {version}")
    if args.version:
        sys.exit(0)
Michael Murtaugh's avatar
Michael Murtaugh committed
317

Michael Murtaugh's avatar
Michael Murtaugh committed
318
319
320
321
322
323
324
325
    if sys.platform == 'win32':
        # Folowing: https://docs.python.org/3/library/asyncio-subprocess.html
        # On Windows, the default event loop is SelectorEventLoop which does not support subprocesses.
        # ProactorEventLoop should be used instead.
        loop = asyncio.ProactorEventLoop()
        asyncio.set_event_loop(loop)
    app = web.Application()
    app['makefile'] = args.makefile
Michael Murtaugh's avatar
Michael Murtaugh committed
326
    app['verbose'] = args.verbose
327
328
329
330
    if args.scons or (args.makefile.lower() == "sconstruct.py"):
        app['make'] = "scons"
    else:
        app['make'] = "make"
Michael Murtaugh's avatar
Michael Murtaugh committed
331
    app['editor'] = args.editor
Michael Murtaugh's avatar
Michael Murtaugh committed
332
    # app.router.add_route('GET', '/ws', websocket_handler)
Michael Murtaugh's avatar
Michael Murtaugh committed
333
334
335

    data = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data")
    htdocs = os.path.join(data, "htdocs")
336
    app['htdocs'] = htdocs
337
338
    laburl = "__lab__"
    print (f"Adding static route {laburl}/ -> {htdocs}")
339
340
    # add /__lab__/ => index.html
    app.router.add_route("GET", f"/{laburl}/", lab_index_handler)
Michael Murtaugh's avatar
Michael Murtaugh committed
341
342
343
#    app.router.add_route("GET", f"/{laburl}/terminal/", terminal_index_handler)
#    app.router.add_route("GET", f"/{laburl}/terminal/ws", terminal_websocket_handler)
    app.router.add_static(f"/{laburl}", htdocs, show_index=args.verbose)
Michael Murtaugh's avatar
Michael Murtaugh committed
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

    if args.static:
        for name, path in args.static:
            print ("Adding static route {0} -> {1}".format(name, path))
            app.router.add_static(name, path)
    app.add_routes([web.get('/{make:.*}', route_get)])
    app.add_routes([web.post('/{make:.*}', route_post)])

    port = args.port
    tries = 0
    max_tries = 10

    # DYNAMIC PORT SELECTION
    import socket, errno
    while tries<max_tries:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind((args.host, port))
            sock.close()
            break
        except socket.error as e:
            if e.errno == errno.EADDRINUSE:
                print (f"port {port} in use", file=sys.stderr)
                port = port + 1
                tries += 1
            else:
                raise(e)
371
    print (f"listening on http://{args.host}:{port}/{laburl}/")
Michael Murtaugh's avatar
Michael Murtaugh committed
372
373
374
375
    web.run_app(app, host=args.host, port=port)

if __name__ == "__main__":
    main()