You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

247 lines
8.3 KiB

  1. #!/usr/bin/python
  2. from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
  3. from SocketServer import ThreadingMixIn
  4. import getopt, threading, sys, urlparse, _winreg, os, subprocess, shutil, tempfile
  5. class BuildHTTPServer(ThreadingMixIn, HTTPServer):
  6. allow_reuse_address = True
  7. def usage():
  8. print 'Usage: %s [options]'
  9. print 'Options:'
  10. print
  11. print ' -h, --help Display this help'
  12. print ' -i, --install Launch at session startup'
  13. print ' -u, --uninstall Do not launch at session startup'
  14. print ' -b, --bind <host[:port]> Bind to host:port (default localhost:8142)'
  15. sys.exit(0)
  16. def main(argv):
  17. opts, args = getopt.getopt(argv, 'hb:iu', ['help', 'bind=', 'install', 'uninstall'])
  18. host = 'localhost'
  19. port = 8142
  20. for opt, val in opts:
  21. if opt in ['-h', '--help']:
  22. usage()
  23. elif opt in ['-b', '--bind']:
  24. try:
  25. host, port = val.split(':')
  26. except ValueError:
  27. host = val
  28. else:
  29. port = int(port)
  30. elif opt in ['-i', '--install']:
  31. key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Run', 0, _winreg.KEY_WRITE)
  32. try:
  33. _winreg.SetValueEx(key, 'Youtube-dl builder', 0, _winreg.REG_SZ,
  34. '"%s" "%s" -b %s:%d' % (sys.executable, os.path.normpath(os.path.abspath(sys.argv[0])),
  35. host, port))
  36. finally:
  37. _winreg.CloseKey(key)
  38. print 'Installed.'
  39. sys.exit(0)
  40. elif opt in ['-u', '--uninstall']:
  41. key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Run', 0, _winreg.KEY_WRITE)
  42. try:
  43. _winreg.DeleteValue(key, 'Youtube-dl builder')
  44. finally:
  45. _winreg.CloseKey(key)
  46. print 'Uninstalled.'
  47. sys.exit(0)
  48. print 'Listening on %s:%d' % (host, port)
  49. srv = BuildHTTPServer((host, port), BuildHTTPRequestHandler)
  50. thr = threading.Thread(target=srv.serve_forever)
  51. thr.start()
  52. raw_input('Hit <ENTER> to stop...\n')
  53. srv.shutdown()
  54. thr.join()
  55. def rmtree(path):
  56. for name in os.listdir(path):
  57. fname = os.path.join(path, name)
  58. if os.path.isdir(fname):
  59. rmtree(fname)
  60. else:
  61. os.chmod(fname, 0666)
  62. os.remove(fname)
  63. os.rmdir(path)
  64. #==============================================================================
  65. class BuildError(Exception):
  66. def __init__(self, output, code=500):
  67. self.output = output
  68. self.code = code
  69. def __str__(self):
  70. return self.output
  71. class HTTPError(BuildError):
  72. pass
  73. class PythonBuilder(object):
  74. def __init__(self, **kwargs):
  75. pythonVersion = kwargs.pop('python', '2.7')
  76. try:
  77. key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Python\PythonCore\%s\InstallPath' % pythonVersion)
  78. try:
  79. self.pythonPath, _ = _winreg.QueryValueEx(key, '')
  80. finally:
  81. _winreg.CloseKey(key)
  82. except Exception:
  83. raise BuildError('No such Python version: %s' % pythonVersion)
  84. super(PythonBuilder, self).__init__(**kwargs)
  85. class GITInfoBuilder(object):
  86. def __init__(self, **kwargs):
  87. try:
  88. self.user, self.repoName = kwargs['path'][:2]
  89. self.rev = kwargs.pop('rev')
  90. except ValueError:
  91. raise BuildError('Invalid path')
  92. except KeyError as e:
  93. raise BuildError('Missing mandatory parameter "%s"' % e.args[0])
  94. path = os.path.join(os.environ['APPDATA'], 'Build archive', self.repoName, self.user)
  95. if not os.path.exists(path):
  96. os.makedirs(path)
  97. self.basePath = tempfile.mkdtemp(dir=path)
  98. self.buildPath = os.path.join(self.basePath, 'build')
  99. super(GITInfoBuilder, self).__init__(**kwargs)
  100. class GITBuilder(GITInfoBuilder):
  101. def build(self):
  102. try:
  103. subprocess.check_output(['git', 'clone', 'git://github.com/%s/%s.git' % (self.user, self.repoName), self.buildPath])
  104. subprocess.check_output(['git', 'checkout', self.rev], cwd=self.buildPath)
  105. except subprocess.CalledProcessError as e:
  106. raise BuildError(e.output)
  107. super(GITBuilder, self).build()
  108. class YoutubeDLBuilder(object):
  109. authorizedUsers = ['fraca7', 'phihag', 'rg3', 'FiloSottile']
  110. def __init__(self, **kwargs):
  111. if self.repoName != 'youtube-dl':
  112. raise BuildError('Invalid repository "%s"' % self.repoName)
  113. if self.user not in self.authorizedUsers:
  114. raise HTTPError('Unauthorized user "%s"' % self.user, 401)
  115. super(YoutubeDLBuilder, self).__init__(**kwargs)
  116. def build(self):
  117. try:
  118. subprocess.check_output([os.path.join(self.pythonPath, 'python.exe'), 'setup.py', 'py2exe'],
  119. cwd=self.buildPath)
  120. except subprocess.CalledProcessError as e:
  121. raise BuildError(e.output)
  122. super(YoutubeDLBuilder, self).build()
  123. class DownloadBuilder(object):
  124. def __init__(self, **kwargs):
  125. self.handler = kwargs.pop('handler')
  126. self.srcPath = os.path.join(self.buildPath, *tuple(kwargs['path'][2:]))
  127. self.srcPath = os.path.abspath(os.path.normpath(self.srcPath))
  128. if not self.srcPath.startswith(self.buildPath):
  129. raise HTTPError(self.srcPath, 401)
  130. super(DownloadBuilder, self).__init__(**kwargs)
  131. def build(self):
  132. if not os.path.exists(self.srcPath):
  133. raise HTTPError('No such file', 404)
  134. if os.path.isdir(self.srcPath):
  135. raise HTTPError('Is a directory: %s' % self.srcPath, 401)
  136. self.handler.send_response(200)
  137. self.handler.send_header('Content-Type', 'application/octet-stream')
  138. self.handler.send_header('Content-Disposition', 'attachment; filename=%s' % os.path.split(self.srcPath)[-1])
  139. self.handler.send_header('Content-Length', str(os.stat(self.srcPath).st_size))
  140. self.handler.end_headers()
  141. with open(self.srcPath, 'rb') as src:
  142. shutil.copyfileobj(src, self.handler.wfile)
  143. super(DownloadBuilder, self).build()
  144. class CleanupTempDir(object):
  145. def build(self):
  146. try:
  147. rmtree(self.basePath)
  148. except Exception as e:
  149. print 'WARNING deleting "%s": %s' % (self.basePath, e)
  150. super(CleanupTempDir, self).build()
  151. class Null(object):
  152. def __init__(self, **kwargs):
  153. pass
  154. def start(self):
  155. pass
  156. def close(self):
  157. pass
  158. def build(self):
  159. pass
  160. class Builder(PythonBuilder, GITBuilder, YoutubeDLBuilder, DownloadBuilder, CleanupTempDir, Null):
  161. pass
  162. class BuildHTTPRequestHandler(BaseHTTPRequestHandler):
  163. actionDict = { 'build': Builder, 'download': Builder } # They're the same, no more caching.
  164. def do_GET(self):
  165. path = urlparse.urlparse(self.path)
  166. paramDict = dict([(key, value[0]) for key, value in urlparse.parse_qs(path.query).items()])
  167. action, _, path = path.path.strip('/').partition('/')
  168. if path:
  169. path = path.split('/')
  170. if action in self.actionDict:
  171. try:
  172. builder = self.actionDict[action](path=path, handler=self, **paramDict)
  173. builder.start()
  174. try:
  175. builder.build()
  176. finally:
  177. builder.close()
  178. except BuildError as e:
  179. self.send_response(e.code)
  180. msg = unicode(e).encode('UTF-8')
  181. self.send_header('Content-Type', 'text/plain; charset=UTF-8')
  182. self.send_header('Content-Length', len(msg))
  183. self.end_headers()
  184. self.wfile.write(msg)
  185. except HTTPError as e:
  186. self.send_response(e.code, str(e))
  187. else:
  188. self.send_response(500, 'Unknown build method "%s"' % action)
  189. else:
  190. self.send_response(500, 'Malformed URL')
  191. #==============================================================================
  192. if __name__ == '__main__':
  193. main(sys.argv[1:])