3 from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
4 from SocketServer import ThreadingMixIn
5 import getopt, threading, sys, urlparse, _winreg, os, subprocess, shutil, tempfile
8 class BuildHTTPServer(ThreadingMixIn, HTTPServer):
9 allow_reuse_address = True
13 print 'Usage: %s [options]'
16 print ' -h, --help Display this help'
17 print ' -i, --install Launch at session startup'
18 print ' -u, --uninstall Do not launch at session startup'
19 print ' -b, --bind <host[:port]> Bind to host:port (default localhost:8142)'
24 opts, args = getopt.getopt(argv, 'hb:iu', ['help', 'bind=', 'install', 'uninstall'])
29 if opt in ['-h', '--help']:
31 elif opt in ['-b', '--bind']:
33 host, port = val.split(':')
38 elif opt in ['-i', '--install']:
39 key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Run', 0, _winreg.KEY_WRITE)
41 _winreg.SetValueEx(key, 'Youtube-dl builder', 0, _winreg.REG_SZ,
42 '"%s" "%s" -b %s:%d' % (sys.executable, os.path.normpath(os.path.abspath(sys.argv[0])),
48 elif opt in ['-u', '--uninstall']:
49 key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Run', 0, _winreg.KEY_WRITE)
51 _winreg.DeleteValue(key, 'Youtube-dl builder')
57 print 'Listening on %s:%d' % (host, port)
58 srv = BuildHTTPServer((host, port), BuildHTTPRequestHandler)
59 thr = threading.Thread(target=srv.serve_forever)
61 raw_input('Hit <ENTER> to stop...\n')
67 for name in os.listdir(path):
68 fname = os.path.join(path, name)
69 if os.path.isdir(fname):
76 #==============================================================================
78 class BuildError(Exception):
79 def __init__(self, output, code=500):
87 class HTTPError(BuildError):
91 class PythonBuilder(object):
92 def __init__(self, **kwargs):
93 pythonVersion = kwargs.pop('python', '2.7')
95 key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Python\PythonCore\%s\InstallPath' % pythonVersion)
97 self.pythonPath, _ = _winreg.QueryValueEx(key, '')
101 raise BuildError('No such Python version: %s' % pythonVersion)
103 super(PythonBuilder, self).__init__(**kwargs)
106 class GITInfoBuilder(object):
107 def __init__(self, **kwargs):
109 self.user, self.repoName = kwargs['path'][:2]
110 self.rev = kwargs.pop('rev')
112 raise BuildError('Invalid path')
113 except KeyError as e:
114 raise BuildError('Missing mandatory parameter "%s"' % e.args[0])
116 path = os.path.join(os.environ['APPDATA'], 'Build archive', self.repoName, self.user)
117 if not os.path.exists(path):
119 self.basePath = tempfile.mkdtemp(dir=path)
120 self.buildPath = os.path.join(self.basePath, 'build')
122 super(GITInfoBuilder, self).__init__(**kwargs)
125 class GITBuilder(GITInfoBuilder):
128 subprocess.check_output(['git', 'clone', 'git://github.com/%s/%s.git' % (self.user, self.repoName), self.buildPath])
129 subprocess.check_output(['git', 'checkout', self.rev], cwd=self.buildPath)
130 except subprocess.CalledProcessError as e:
131 raise BuildError(e.output)
133 super(GITBuilder, self).build()
136 class YoutubeDLBuilder(object):
137 authorizedUsers = ['fraca7', 'phihag', 'rg3', 'FiloSottile']
139 def __init__(self, **kwargs):
140 if self.repoName != 'youtube-dl':
141 raise BuildError('Invalid repository "%s"' % self.repoName)
142 if self.user not in self.authorizedUsers:
143 raise HTTPError('Unauthorized user "%s"' % self.user, 401)
145 super(YoutubeDLBuilder, self).__init__(**kwargs)
149 subprocess.check_output([os.path.join(self.pythonPath, 'python.exe'), 'setup.py', 'py2exe'],
151 except subprocess.CalledProcessError as e:
152 raise BuildError(e.output)
154 super(YoutubeDLBuilder, self).build()
157 class DownloadBuilder(object):
158 def __init__(self, **kwargs):
159 self.handler = kwargs.pop('handler')
160 self.srcPath = os.path.join(self.buildPath, *tuple(kwargs['path'][2:]))
161 self.srcPath = os.path.abspath(os.path.normpath(self.srcPath))
162 if not self.srcPath.startswith(self.buildPath):
163 raise HTTPError(self.srcPath, 401)
165 super(DownloadBuilder, self).__init__(**kwargs)
168 if not os.path.exists(self.srcPath):
169 raise HTTPError('No such file', 404)
170 if os.path.isdir(self.srcPath):
171 raise HTTPError('Is a directory: %s' % self.srcPath, 401)
173 self.handler.send_response(200)
174 self.handler.send_header('Content-Type', 'application/octet-stream')
175 self.handler.send_header('Content-Disposition', 'attachment; filename=%s' % os.path.split(self.srcPath)[-1])
176 self.handler.send_header('Content-Length', str(os.stat(self.srcPath).st_size))
177 self.handler.end_headers()
179 with open(self.srcPath, 'rb') as src:
180 shutil.copyfileobj(src, self.handler.wfile)
182 super(DownloadBuilder, self).build()
185 class CleanupTempDir(object):
188 rmtree(self.basePath)
189 except Exception as e:
190 print 'WARNING deleting "%s": %s' % (self.basePath, e)
192 super(CleanupTempDir, self).build()
196 def __init__(self, **kwargs):
209 class Builder(PythonBuilder, GITBuilder, YoutubeDLBuilder, DownloadBuilder, CleanupTempDir, Null):
213 class BuildHTTPRequestHandler(BaseHTTPRequestHandler):
214 actionDict = { 'build': Builder, 'download': Builder } # They're the same, no more caching.
217 path = urlparse.urlparse(self.path)
218 paramDict = dict([(key, value[0]) for key, value in urlparse.parse_qs(path.query).items()])
219 action, _, path = path.path.strip('/').partition('/')
221 path = path.split('/')
222 if action in self.actionDict:
224 builder = self.actionDict[action](path=path, handler=self, **paramDict)
230 except BuildError as e:
231 self.send_response(e.code)
232 msg = unicode(e).encode('UTF-8')
233 self.send_header('Content-Type', 'text/plain; charset=UTF-8')
234 self.send_header('Content-Length', len(msg))
236 self.wfile.write(msg)
237 except HTTPError as e:
238 self.send_response(e.code, str(e))
240 self.send_response(500, 'Unknown build method "%s"' % action)
242 self.send_response(500, 'Malformed URL')
244 #==============================================================================
246 if __name__ == '__main__':