]> git.0d.be Git - pige-extractor.git/blob - download.cgi
always use absolute paths, do not meddle with working directory
[pige-extractor.git] / download.cgi
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 import time
5 import cgi
6 import os
7 import sys
8 import datetime
9 import syslog
10
11 try:
12     from config import BASE_DIR, PATH_LAYOUT, FILENAME_LAYOUT
13 except ImportError:
14     BASE_DIR = '/home/alsa-record/'
15     PATH_LAYOUT = '%Y/%m-%b/%d-%a/'
16     FILENAME_LAYOUT = '%Hh%M'
17
18 if isinstance(BASE_DIR, basestring):
19     BASE_DIR = [BASE_DIR]
20
21 for i, dirname in enumerate(BASE_DIR):
22     if not dirname.endswith('/'):
23         BASE_DIR[i] = dirname + '/'
24
25 syslog.openlog('pigebox')
26
27 d = cgi.parse()
28
29 if os.environ.get('PATH_INFO'):
30     # filename has to be of the following form: %Y%m%d-%Hh%M-%Hh%M.%ext
31     filename = os.path.basename(os.environ.get('PATH_INFO'))
32     date = filename[:8]
33     start = '%s:%s' % (filename[9:11], filename[12:14])
34     seconds = 0
35     if filename[14] == 'm': # support for seconds
36         seconds += 3
37         start += ':' + filename[15:17]
38     else:
39         start += ':00'
40     end = '%s:%s' % (filename[15+seconds:17+seconds], filename[18+seconds:20+seconds])
41     if seconds:
42         end += ':' + filename[24:26]
43     else:
44         end += ':00'
45     ext = filename.rsplit('.')[-1]
46
47     start = datetime.datetime.strptime('%s %s' % (date, start),
48            '%Y%m%d %H:%M:%S')
49     end = datetime.datetime.strptime('%s %s' % (date, end),
50            '%Y%m%d %H:%M:%S')
51 elif d:
52     end = '%s:%s' % (d.get('end_hour')[0], d.get('end_min')[0])
53
54     start = datetime.datetime.strptime('%s %s:%s' % (
55            d.get('date')[0], d.get('start_hour')[0], d.get('start_min')[0]),
56            '%d/%m/%Y %H:%M')
57     end = datetime.datetime.strptime('%s %s:%s' % (
58            d.get('date')[0], d.get('end_hour')[0], d.get('end_min')[0]),
59            '%d/%m/%Y %H:%M')
60     if d.get('wav'):
61         ext = 'wav'
62     else:
63         ext = 'ogg'
64     filename = '%s-%s.ext' % (
65             start.strftime('%Y-%m-%d-%Hh%M'), end.strftime('%Hh%M'), ext)
66 else:
67     print 'Location: .'
68     print ''
69     print 'Hop'
70     sys.exit(0)
71
72 if end < start:
73     end = end + datetime.timedelta(1)
74
75 floor_start = start
76 if floor_start.second:
77     floor_start = floor_start.replace(second=0)
78 floor_start = floor_start.replace(minute=floor_start.minute/15*15)
79
80 ceil_end = end
81 if ceil_end.second:
82     ceil_end = ceil_end.replace(minute=ceil_end.minute+1, second=0)
83 if ceil_end.minute%15:
84     if ceil_end.minute / 15 == 3:
85         ceil_end = ceil_end.replace(minute=0)
86         ceil_end += datetime.timedelta(seconds=3600)
87     else:
88         ceil_end = ceil_end.replace(minute=(1+(ceil_end.minute/15))*15)
89
90 def get_filenames(base_dir):
91     path = os.path.join(base_dir, start.strftime(PATH_LAYOUT))
92     if not path:
93         filenames = [x for x in os.listdir('.')]
94     else:
95         filenames = [os.path.join(path, x) for x in os.listdir(path)]
96         if end.hour < start.hour:
97             path = os.path.join(base_dir, end.strftime(PATH_LAYOUT))
98             if os.path.exists(path):
99                 filenames.extend([os.path.join(path, x) for x in os.listdir(path)])
100
101     filenames = [x for x in filenames if
102             x[len(base_dir):] >= floor_start.strftime(PATH_LAYOUT + FILENAME_LAYOUT) and
103             x[len(base_dir):] < ceil_end.strftime(PATH_LAYOUT + FILENAME_LAYOUT)]
104     return filenames
105
106 while True:
107     filenames = []
108     for base_dir in BASE_DIR:
109         filenames.extend(get_filenames(base_dir))
110     filenames.sort()
111
112     without_extension = [os.path.splitext(x)[0] for x in filenames]
113     for f in without_extension:
114         if without_extension.count(f) > 1:
115             # currently encoding, wait a moment and try again
116             print 'X-Currently-Encoding: please wait'
117             time.sleep(5)
118             break
119     else:
120         break
121
122 syslog.syslog(syslog.LOG_INFO, 'extraction (%s to %s)' % (
123                         start.strftime('%Y-%m-%d %Hh%M'),
124                         end.strftime('%Hh%M')))
125
126 if ext == 'wav':
127     print 'Content-Type: audio/x-wav'
128 else:
129     print 'Content-Type: audio/ogg'
130
131 print 'Content-Disposition: attachment; filename=%s\n' % filename
132
133 sys.stdout.flush()
134
135 if ext == 'ogg':
136     command = ['sox'] + filenames + ['-t', 'ogg', '-C', '6', '-']
137 elif ext == 'flac':
138     command = ['sox'] + filenames + ['-t', 'flac', '-']
139 else:
140     command = ['sox'] + filenames + ['-t', 'wav', '-']
141
142 # trim
143 command.append('trim')
144 command.append('=%s' % (start - floor_start).seconds)
145 command.append('=%s' % (end - floor_start).seconds)
146
147 if '--test' in sys.argv:
148     print ' '.join(command)
149 else:
150     os.system(' '.join(command))