File: datauri.py 1 #!/usr/bin/python3 2 3 # The MIT License (MIT) 4 # 5 # Copyright © 2024 pacman64 6 # 7 # Permission is hereby granted, free of charge, to any person obtaining a copy 8 # of this software and associated documentation files (the “Software”), to deal 9 # in the Software without restriction, including without limitation the rights 10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 # copies of the Software, and to permit persons to whom the Software is 12 # furnished to do so, subject to the following conditions: 13 # 14 # The above copyright notice and this permission notice shall be included in 15 # all copies or substantial portions of the Software. 16 # 17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 # SOFTWARE. 24 25 26 from base64 import b64encode 27 from mimetypes import guess_type 28 from sys import argv, exit, stderr, stdout 29 30 31 info = ''' 32 datauri [options...] [filepaths/URIs...] 33 34 Turn each named input (file/URI) given into a data-URI line. 35 36 Data-URIs are base64-encoded text representations of arbitrary data, which 37 include their payload's MIME-type, and which are directly useable/shareable 38 in web-browsers as links, despite not looking like normal links/URIs. 39 ''' 40 41 # no args or a leading help-option arg means show the help message and quit 42 if len(argv) == 1 or argv[1] in ('-h', '--h', '-help', '--help'): 43 print(info.strip(), file=stderr) 44 exit(0) 45 46 47 def seems_url(s: str) -> bool: 48 protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') 49 return any(s.startswith(p) for p in protocols) 50 51 52 def handle_input(w, src, path: str) -> None: 53 mime = '' 54 55 # get MIME-type from response headers, if input is an HTTP response 56 if hasattr(inp, 'getheader'): 57 mime = inp.getheader('content-type') 58 59 # failing that, guess the MIME-type from the input's name/URI 60 if not mime: 61 (mime, _) = guess_type(path) 62 63 if not mime: 64 raise Exception(f'{path}: can\'t guess MIME-type') 65 66 w.write(b'data:') 67 w.write(bytes(mime, encoding='utf-8')) 68 w.write(b';base64,') 69 w.write(b64encode(src.read())) 70 w.write(b'\n') 71 72 73 try: 74 if '-' in argv: 75 raise Exception('can\'t use standard input, only named sources') 76 77 if any(seems_url(e) for e in argv): 78 from urllib.request import urlopen 79 80 for path in argv[1:]: 81 if seems_url(path): 82 with urlopen(path) as inp: 83 handle_input(stdout.buffer, inp, path) 84 continue 85 86 with open(path, mode='rb') as inp: 87 handle_input(stdout.buffer, inp, path) 88 except BrokenPipeError: 89 # quit quietly, instead of showing a confusing error message 90 stderr.close() 91 except KeyboardInterrupt: 92 exit(2) 93 except Exception as e: 94 print(f'\x1b[31m{e}\x1b[0m', file=stderr) 95 exit(1)