__init__.py 11.9 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

23
async def is_makeable (path, cwd=".", makefile="makefile", make="make"):
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()
34
    print (f"{make} --question -f {makefile} {path} returned: {MAKE_BY_CODE[ret]}", file=sys.stderr)
Michael Murtaugh's avatar
Michael Murtaugh committed
35
    await log(f"is_makeable {0}: {MAKE_BY_CODE[ret]}".format(path, ret))
Michael Murtaugh's avatar
Michael Murtaugh committed
36
37
    return ret

38
async def make (path, cwd=".", makefile="makefile", make="make", force=False):
Michael Murtaugh's avatar
Michael Murtaugh committed
39
    rpath = os.path.relpath(path, cwd)
40
    makeargs = [make, "-f", makefile, rpath]
Michael Murtaugh's avatar
Michael Murtaugh committed
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
    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
    print ("make {0}: {1}".format(path, ret), file=sys.stderr)
    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)

    head_str = "<head>\n<title>{}</title>\n<link rel=\"stylesheet\" href=\"/include/index.css\"></script>\n<script src=\"/include/index.js\"></script>\n</head>".format(index_of)
    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)
    print ("GET", path, file=sys.stderr)
    if path == '':
        path = '.'
182
183
184
    makefile = request.app['makefile']
    makecmd = request.app['make']
    im = await is_makeable(path, makefile=makefile, make=makecmd)
Michael Murtaugh's avatar
Michael Murtaugh committed
185
    remake = 'remake' in request.rel_url.query
Michael Murtaugh's avatar
Michael Murtaugh committed
186
187
    if path and (im == MAKE['NEEDS_REMAKING'] or \
            (im == MAKE['UP_TO_DATE'] and remake)):
188
        code, resp = await make(path, makefile=makefile, make=makecmd, force=remake)
Michael Murtaugh's avatar
Michael Murtaugh committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
        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)
208
    else:
Michael Murtaugh's avatar
Michael Murtaugh committed
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
        raise web.HTTPNotFound()
        # return web.Response(text="404 on path {0}".format(path))

async def route_post (request):
    """ write posted text value to file """
    path = urlunquote(urlparse(request.rel_url.raw_path.lstrip("/")).path)
    print ("POST", path, file=sys.stderr)
    # 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):
    print('Websocket connection starting')
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    print('Websocket connection ready')
    active_sockets.append(ws)

    async for msg in ws:
        print(msg)
        if msg.type == aiohttp.WSMsgType.TEXT:
            print(msg.data)
            if msg.data == 'close':
                await ws.close()
            else:
                await ws.send_str(msg.data + '/answer')

    active_sockets.remove(ws)

    print('Websocket connection closed')
    return ws

def main ():
    ap = argparse.ArgumentParser("make & serve")
    ap.add_argument("--makefile", "-f", default="Makefile")
283
    ap.add_argument("--scons", action="store_true", default=False)
Michael Murtaugh's avatar
Michael Murtaugh committed
284
285
286
287
288
289
    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")
    args = ap.parse_args()

Michael Murtaugh's avatar
Michael Murtaugh committed
290
291
    print ("Makeserver Version 3.1.0")

Michael Murtaugh's avatar
Michael Murtaugh committed
292
293
294
295
296
297
298
299
    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
300
301
302
303
    if args.scons or (args.makefile.lower() == "sconstruct.py"):
        app['make'] = "scons"
    else:
        app['make'] = "make"
Michael Murtaugh's avatar
Michael Murtaugh committed
304
305
306
307
308
    app['editor'] = args.editor
    app.router.add_route('GET', '/ws', websocket_handler)

    data = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data")
    htdocs = os.path.join(data, "htdocs")
309
310
311
    laburl = "__lab__"
    print (f"Adding static route {laburl}/ -> {htdocs}")
    app.router.add_static(f"/{laburl}", htdocs, show_index=True)
Michael Murtaugh's avatar
Michael Murtaugh committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338

    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)
339
    print (f"listening on http://{args.host}:{port}/{laburl}/")
Michael Murtaugh's avatar
Michael Murtaugh committed
340
341
342
343
    web.run_app(app, host=args.host, port=port)

if __name__ == "__main__":
    main()