]> git.0d.be Git - pige-extractor.git/blob - download.cgi
Fixed getting archive passing the midnight mark
[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 syslog.openlog('pigebox')
12
13 d = cgi.parse()
14
15 if not d:
16     print 'Location: .'
17     print ''
18     print 'Hop'
19     sys.exit(0)
20
21 end = '%s:%s' % (d.get('end_hour')[0], d.get('end_min')[0])
22
23 start = datetime.datetime.strptime('%s %s:%s' % (
24         d.get('date')[0], d.get('start_hour')[0], d.get('start_min')[0]),
25         '%d/%m/%Y %H:%M')
26 end = datetime.datetime.strptime('%s %s:%s' % (
27         d.get('date')[0], d.get('end_hour')[0], d.get('end_min')[0]),
28         '%d/%m/%Y %H:%M')
29 if end < start:
30     end = end + datetime.timedelta(1)
31
32 os.chdir('/home/alsa-record/')
33
34 def get_filenames():
35     path = start.strftime('%Y/%m-%b/%d-%a/')
36     filenames = [os.path.join(path, x) for x in os.listdir(path)]
37     if end.hour < start.hour:
38         path = end.strftime('%Y/%m-%b/%d-%a/')
39         if os.path.exists(path):
40             filenames.extend([os.path.join(path, x) for x in os.listdir(path)])
41     filenames.sort()
42
43     filenames = [x for x in filenames if
44                 x >= start.strftime('%Y/%m-%b/%d-%a/%Hh%M') and 
45                 x < end.strftime('%Y/%m-%b/%d-%a/%Hh%M')]
46     return filenames
47
48 while True:
49     filenames = get_filenames()
50     without_extension = [os.path.splitext(x)[0] for x in filenames]
51     for f in without_extension:
52         if without_extension.count(f) > 1:
53             # currently encoding, wait a moment and try again
54             print 'X-Currently-Encoding: please wait'
55             time.sleep(5)
56             break
57     else:
58         break
59
60 syslog.syslog(syslog.LOG_INFO, 'extraction (%s to %s)' % (
61                         start.strftime('%Y-%m-%d %Hh%M'),
62                         end.strftime('%Hh%M')))
63
64 if d.get('wav'):
65     ext = 'wav'
66     print 'Content-Type: audio/x-wav'
67 else:
68     ext = 'ogg'
69     print 'Content-Type: audio/ogg'
70
71 print 'Content-Disposition: attachment; filename=%s.%s\n' % \
72                 (start.strftime('%Y-%m-%d-%Hh%M') + end.strftime('-%Hh%M'), ext)
73
74 sys.stdout.flush()
75
76 if ext == 'ogg':
77     command = ['sox'] + filenames + ['-t', 'ogg', '-C', '6', '-']
78 else:
79     command = ['sox'] + filenames + ['-t', 'wav', '-']
80 os.system(' '.join(command))
81