import http.server, urllib.request, json, time, threading
from pathlib import Path
root=Path(__file__).parent
class Proxy(http.server.BaseHTTPRequestHandler):
 def log_message(self,*args): pass
 def do_GET(self):
  url='https://registry.npmjs.org'+self.path
  try:
   with urllib.request.urlopen(url, timeout=90) as upstream:
    data=upstream.read();typ=upstream.headers.get('Content-Type','application/octet-stream')
   if '.tgz' in self.path:
    with open(root/'proxy-events.log','a') as log:log.write('Tarball requested; holding download for 25 seconds\n')
    time.sleep(25)
    with open(root/'proxy-events.log','a') as log:log.write('Tarball released\n')
   elif 'json' in typ:
    data=data.replace(b'https://registry.npmjs.org/',b'http://127.0.0.1:18761/')
   self.send_response(200);self.send_header('Content-Type',typ);self.send_header('Content-Length',len(data));self.end_headers();self.wfile.write(data)
  except (BrokenPipeError,ConnectionResetError):
   with open(root/'proxy-events.log','a') as log:log.write('Installer disconnected before tarball delivery\n')
  except Exception as e:
   self.send_error(502,str(e))
http.server.ThreadingHTTPServer(('127.0.0.1',18761),Proxy).serve_forever()
