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