[buildserver] Rely on repository license
[youtube-dl] / devscripts / buildserver.py
1 #!/usr/bin/python
2
3 from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
4 from SocketServer import ThreadingMixIn
5 import getopt, threading, sys, urlparse, _winreg, os, subprocess, shutil, tempfile
6
7
8 class BuildHTTPServer(ThreadingMixIn, HTTPServer):
9     allow_reuse_address = True
10
11
12 def usage():
13     print 'Usage: %s [options]'
14     print 'Options:'
15     print
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)'
20     sys.exit(0)
21
22
23 def main(argv):
24     opts, args = getopt.getopt(argv, 'hb:iu', ['help', 'bind=', 'install', 'uninstall'])
25     host = 'localhost'
26     port = 8142
27
28     for opt, val in opts:
29         if opt in ['-h', '--help']:
30             usage()
31         elif opt in ['-b', '--bind']:
32             try:
33                 host, port = val.split(':')
34             except ValueError:
35                 host = val
36             else:
37                 port = int(port)
38         elif opt in ['-i', '--install']:
39             key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Run', 0, _winreg.KEY_WRITE)
40             try:
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])),
43                                                            host, port))
44             finally:
45                 _winreg.CloseKey(key)
46             print 'Installed.'
47             sys.exit(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)
50             try:
51                 _winreg.DeleteValue(key, 'Youtube-dl builder')
52             finally:
53                 _winreg.CloseKey(key)
54             print 'Uninstalled.'
55             sys.exit(0)
56
57     print 'Listening on %s:%d' % (host, port)
58     srv = BuildHTTPServer((host, port), BuildHTTPRequestHandler)
59     thr = threading.Thread(target=srv.serve_forever)
60     thr.start()
61     raw_input('Hit <ENTER> to stop...\n')
62     srv.shutdown()
63     thr.join()
64
65
66 def rmtree(path):
67     for name in os.listdir(path):
68         fname = os.path.join(path, name)
69         if os.path.isdir(fname):
70             rmtree(fname)
71         else:
72             os.chmod(fname, 0666)
73             os.remove(fname)
74     os.rmdir(path)
75
76 #==============================================================================
77
78 class BuildError(Exception):
79     def __init__(self, output, code=500):
80         self.output = output
81         self.code = code
82
83     def __str__(self):
84         return self.output
85
86
87 class HTTPError(BuildError):
88     pass
89
90
91 class PythonBuilder(object):
92     def __init__(self, **kwargs):
93         pythonVersion = kwargs.pop('python', '2.7')
94         try:
95             key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Python\PythonCore\%s\InstallPath' % pythonVersion)
96             try:
97                 self.pythonPath, _ = _winreg.QueryValueEx(key, '')
98             finally:
99                 _winreg.CloseKey(key)
100         except Exception:
101             raise BuildError('No such Python version: %s' % pythonVersion)
102
103         super(PythonBuilder, self).__init__(**kwargs)
104
105
106 class GITInfoBuilder(object):
107     def __init__(self, **kwargs):
108         try:
109             self.user, self.repoName = kwargs['path'][:2]
110             self.rev = kwargs.pop('rev')
111         except ValueError:
112             raise BuildError('Invalid path')
113         except KeyError as e:
114             raise BuildError('Missing mandatory parameter "%s"' % e.args[0])
115
116         path = os.path.join(os.environ['APPDATA'], 'Build archive', self.repoName, self.user)
117         if not os.path.exists(path):
118             os.makedirs(path)
119         self.basePath = tempfile.mkdtemp(dir=path)
120         self.buildPath = os.path.join(self.basePath, 'build')
121
122         super(GITInfoBuilder, self).__init__(**kwargs)
123
124
125 class GITBuilder(GITInfoBuilder):
126     def build(self):
127         try:
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)
132
133         super(GITBuilder, self).build()
134
135
136 class YoutubeDLBuilder(object):
137     authorizedUsers = ['fraca7', 'phihag', 'rg3', 'FiloSottile']
138
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)
144
145         super(YoutubeDLBuilder, self).__init__(**kwargs)
146
147     def build(self):
148         try:
149             subprocess.check_output([os.path.join(self.pythonPath, 'python.exe'), 'setup.py', 'py2exe'],
150                                     cwd=self.buildPath)
151         except subprocess.CalledProcessError as e:
152             raise BuildError(e.output)
153
154         super(YoutubeDLBuilder, self).build()
155
156
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)
164
165         super(DownloadBuilder, self).__init__(**kwargs)
166
167     def build(self):
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)
172
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()
178
179         with open(self.srcPath, 'rb') as src:
180             shutil.copyfileobj(src, self.handler.wfile)
181
182         super(DownloadBuilder, self).build()
183
184
185 class CleanupTempDir(object):
186     def build(self):
187         try:
188             rmtree(self.basePath)
189         except Exception as e:
190             print 'WARNING deleting "%s": %s' % (self.basePath, e)
191
192         super(CleanupTempDir, self).build()
193
194
195 class Null(object):
196     def __init__(self, **kwargs):
197         pass
198
199     def start(self):
200         pass
201
202     def close(self):
203         pass
204
205     def build(self):
206         pass
207
208
209 class Builder(PythonBuilder, GITBuilder, YoutubeDLBuilder, DownloadBuilder, CleanupTempDir, Null):
210     pass
211
212
213 class BuildHTTPRequestHandler(BaseHTTPRequestHandler):
214     actionDict = { 'build': Builder, 'download': Builder } # They're the same, no more caching.
215
216     def do_GET(self):
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('/')
220         if path:
221             path = path.split('/')
222             if action in self.actionDict:
223                 try:
224                     builder = self.actionDict[action](path=path, handler=self, **paramDict)
225                     builder.start()
226                     try:
227                         builder.build()
228                     finally:
229                         builder.close()
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))
235                     self.end_headers()
236                     self.wfile.write(msg)
237                 except HTTPError as e:
238                     self.send_response(e.code, str(e))
239             else:
240                 self.send_response(500, 'Unknown build method "%s"' % action)
241         else:
242             self.send_response(500, 'Malformed URL')
243
244 #==============================================================================
245
246 if __name__ == '__main__':
247     main(sys.argv[1:])