]>
Commit | Line | Data |
---|---|---|
940227cb MT |
1 | #!/usr/bin/python |
2 | ||
3 | import random | |
940227cb MT |
4 | import tornado.web |
5 | ||
6 | from handlers_base import * | |
7 | ||
940227cb | 8 | class DownloadFileHandler(BaseHandler): |
9068dba1 | 9 | def prepare(self): |
54af860e | 10 | self.set_header("Pragma", "no-cache") |
54af860e | 11 | |
9068dba1 MT |
12 | def head(self, filename): |
13 | self.redirect_to_mirror(filename) | |
14 | ||
15 | def get(self, filename): | |
16 | self.redirect_to_mirror(filename, log_download=True) | |
17 | ||
18 | def find_mirror(self, filename): | |
5488a9f4 MT |
19 | exists = self.mirrors.file_exists(filename) |
20 | if not exists: | |
54af860e | 21 | raise tornado.web.HTTPError(404, "File not found: %s" % filename) |
940227cb | 22 | |
0673d1b0 | 23 | # Find mirrors located near to the user. |
5488a9f4 | 24 | # If we have not found any, we use a random one. |
9068dba1 | 25 | remote_location = self.get_remote_location() |
0673d1b0 | 26 | |
9068dba1 | 27 | if remote_location: |
5488a9f4 | 28 | mirrors = self.mirrors.get_for_location(remote_location, filename=filename) |
940227cb | 29 | |
5488a9f4 MT |
30 | if mirrors: |
31 | return random.choice(mirrors) | |
54af860e | 32 | |
5488a9f4 | 33 | return self.mirrors.get_random(filename=filename) |
9068dba1 MT |
34 | |
35 | def redirect_to_mirror(self, filename, log_download=False): | |
36 | # Find a random mirror. | |
37 | mirror = self.find_mirror(filename) | |
38 | ||
39 | # Construct the redirection URL. | |
40 | download_url = mirror.build_url(filename) | |
41 | ||
42 | # Redirect the request. | |
43 | self.redirect(download_url) | |
122c9026 | 44 | |
9068dba1 MT |
45 | if not log_download: |
46 | return | |
47 | ||
48 | remote_location = self.get_remote_location() | |
49 | if remote_location: | |
50 | country_code = remote_location.country | |
51 | else: | |
52 | country_code = None | |
53 | ||
54 | self.db.execute("INSERT INTO log_download(filename, mirror, country_code) \ | |
55 | VALUES(%s, %s, %s)", filename, mirror.id, country_code) | |
edd297c4 MT |
56 | |
57 | ||
58 | class DownloadCompatHandler(BaseHandler): | |
59 | def get(self, path, url): | |
edd297c4 | 60 | for filename in self.mirrors.get_all_files(): |
5488a9f4 MT |
61 | if not filename.endswith("/%s" % url): |
62 | continue | |
edd297c4 | 63 | |
5488a9f4 MT |
64 | self.redirect("/%s" % filename) |
65 | return | |
edd297c4 | 66 | |
5488a9f4 | 67 | raise tornado.web.HTTPError(404) |