ubuntuusers.de

ubuntuusers.deAblagetv_grab
Titel:
tv_grab
Datum:
7. Oktober 2009 07:55
Aktionen:
Code:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/python
 
# By hads <epg@nice.net.nz>
# Released under the MIT license
# Last updated 2009-05-10
 
# xmltv.info
# 2007-08-19 - Trivial changes to adapt script to xmltv.info
# 2009-05-10 - Added feature to correct start time of each program by adding a fixed hour-offset
 
import os, sys
import httplib
import logging
import time
import datetime
import re
 
from datetime import datetime, timedelta
from optparse import OptionParser
from cStringIO import StringIO
from gzip import GzipFile
from urlparse import urlparse
 
NAME = 'tv_grab_de-py'
VERSION = '0.1'
DESCRIPTION = 'Germany (xmltv.info)'
HOUR_OFFSET = -2
 
SOURCES = (
       'http://www.tvprog.org/tv.xml',
)

# setup logging
log = logging.getLogger(NAME)
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(logging.Formatter('%(levelname)s - %(message)s'))
log.addHandler(ch)
 
try:
        try:
                from xml.etree import cElementTree as ElementTree
        except ImportError:
                from elementtree import ElementTree
except ImportError:
        log.critical('ElementTree is required and is not found')
        sys.exit(2)
 
def doDownload(source):
        """
        Download a gzipped file and return a string
        """
        host = urlparse(source)[1]
        url = urlparse(source)[2]
        log.info('Downloading data from %s...' % host)
 
        h = httplib.HTTPConnection(host)
        headers = {
                'User-Agent': '%s %s' % (NAME, VERSION),
                'Accept-encoding': 'gzip',
        }
 
        h.request('GET', url, headers=headers)
        res = h.getresponse()
 
        if res.status != 200:
                return False
 
        log.info('Done')

	return res.read()

def getListings(cache=None):
        """
        Loop through listing sources and download them
        """
        if cache:
                try:
                        data = open(cache).read()
                except IOError:
                        pass
                else:
                        return data
        for source in SOURCES:
                res = doDownload(source)
                if res and len(res) > 0:
                        return res
                else:
                        log.error('Invalid data')
 
class XMLTVConfig(object):
        """
        Parses and writes configuration files in the XMLTV format
        """
 
        channels = []
        enabled_channels = []
 
        def __init__(self, conf_file):
                self.conf_file = conf_file
                try:
                        f = open(conf_file)
                except IOError:
                        self.exists = False
                else:
                        self.exists = True
                        i = 1
                        for line in f:
                                line = line.strip()
                                if line and line[0] != '#':
                                        if line.startswith('channel'):
                                                if '=' in line:
                                                        key, value = line.split('=', 1)
                                                        self.channels.append(value)
                                                        self.enabled_channels.append(value)
                                                elif '!' in line:
                                                        key, value = line.split('!', 1)
                                                        self.channels.append(value)
                                        else:
                                                log.info('Ignoring bad line in config file [%s:%s]', conf_file, i)
                                i += 1
                        f.close()
 
        def write(self):
                try:
                        f = open(self.conf_file, 'w')
                except IOError:
                        log.error("Couldn't write config file")
                else:
                        for channel in self.channels:
                                if channel in self.enabled_channels:
                                        f.write('channel=%s\n' % channel)
                                else:
                                        f.write('channel!%s\n' % channel)
                        f.close()
 
# Setup command line options
parser = OptionParser(version='%prog ' + str(VERSION))
parser.set_defaults(quiet=False, capabilities=False, debug=False)
parser.add_option('--quiet', action='store_true',
        help='be quiet, don\'t output status information.')
parser.add_option('--debug', action='store_true', dest='debug',
        help='output debugging information.')
parser.add_option('--capabilities', action='store_true',
        help='show this grabbers capabilities.')
parser.add_option('--configure', action='store_true',
        help='manually configure this grabber.')
parser.add_option('--config-file',
        help='Use configuration file CONFIG_FILE.')
parser.add_option('--description', action='store_true',
        help='show desciption of this grabber.')
parser.add_option('--preferredmethod', action='store_true',
        help='show the preferred download method of this grabber.')
parser.add_option('--days', type='int',
        help='supply data for DAYS days.')
parser.add_option('--offset', type='int',
        help='output data for day today plus OFFSET days.')
parser.add_option('--output',
        help='send output to file OUTPUT, the default is STDOUT.')
parser.add_option('--cache',
        help='cache XML data to file CACHE')
(options, args) = parser.parse_args()
 
if options.debug and options.quiet:
        parser.error('options --debug and --quiet are mutually exclusive')
 
if options.capabilities:
        print 'baseline'
        print 'manualconfig'
        print 'preferredmethod'
        print 'cache'
        sys.exit()
 
if options.description:
        print DESCRIPTION
        sys.exit()
 
if options.preferredmethod:
        print 'allatonce'
        sys.exit()
 
if options.config_file:
        config_file = options.config_file
else:
        config_dir = os.path.expanduser('~/.xmltv/')
        # Create config directory if it doesn't exist
        if not os.path.isdir(config_dir):
                try:
                        os.mkdir(config_dir)
                except:
                        log.critical('Failed to create config directory: %s' % config_dir)
                        sys.exit(2)
        config_file = os.path.join(config_dir, '%s.conf' % NAME)
 
# setup configuration
conf = XMLTVConfig(config_file)
 
if options.debug:
        ch.setLevel(logging.DEBUG)
 
if options.quiet:
        ch.setLevel(logging.CRITICAL)
 
if options.configure:
        available_channels = []
        new_channels = []
        new_enabled_channels = []
 
        text = getListings()
        log.info('Parsing channel data...')
        doc = ElementTree.parse(StringIO(text)).getroot()
 
        for element in doc:
                if element.tag == 'channel':
                        new_channels.append(element.get('id'))
                        available_channels.append((element.get('id'), element[0].text))
 
        log.info('Done (%s channels)' % len(available_channels))
        print
        print 'Please select the channels you wish to use for'
        print 'this source by pressing y or n when prompted:'
        print
        if conf.exists:
                log.warning('Config file already exists, abort (CTRL-C) if you wish to keep the current config')
        print
        for channel in available_channels:
                use = raw_input('Use channel %s (%s)? [y/N]' % (channel[1].encode( "utf-8" ), channel[0].encode( "utf-8" )))
                if use.lower() == 'y':
                        new_enabled_channels.append(channel[0])
        conf.channels = new_channels
        conf.enabled_channels = new_enabled_channels
        conf.write()
        sys.exit()
 
if not conf.exists:
        log.critical('Not configured! Perhaps you meant to run with --config-file or --configure?')
        sys.exit(2)
 
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
 
if options.offset:
        offset = timedelta(days=options.offset)
        start_listings = today + offset
        log.debug('Showing listings from %s' % start_listings)
else:
        start_listings = today
 
if options.days:
        days = timedelta(days=options.days)
        end_listings = start_listings + days
        log.debug('Showing listings until %s' % end_listings)
else:
        end_listings = None
 
text = getListings(cache=options.cache)
 
if not text:
        log.critical('No listings data found!')
        sys.exit(2)
 
log.info('Parsing listings...')
doc = ElementTree.parse(StringIO(text)).getroot()
 
newdoc = ElementTree.Element('tv', doc.attrib)
 
for element in doc:
        if element.tag == 'channel' and element.get('id') in conf.enabled_channels:
                newdoc.append(element)
        if element.tag == 'programme' and element.get('channel') in conf.enabled_channels:
                # build datetime from start attribute of programme
                ### CHANGE 2007-08-19, hcvst@xmltv.info
                # The xmltv file as provided by xmltv.info does currently not contain any
                # timezone information, such as +0200. It should be added in the future.
                # The last six characters can only be removed (as is done in the original version
                # of this script) if the timezone info is present.   
                start_time = element.get('start')
                start_time_tz = ''
                if " " in start_time:
                    p = re.compile(' .*')
                    start_time_tz = p.search(start_time)
                    start_time = p.sub('', start_time)
                programme_start = datetime.fromtimestamp(
                        time.mktime(
                                time.strptime(start_time, '%Y%m%d%H%M%S')
                        )
                )
 
                # Fix the Start time of a showing as it may be false
                programme_start = programme_start + timedelta(hours=HOUR_OFFSET)
                element.set('start', programme_start.strftime('%Y%m%d%H%M%S'))
 
                # Fix the End time of a showing
                end_time = element.get('stop')
                end_time_tz = ''
                if " " in end_time:
                    p = re.compile(' .*')
                    end_time_tz = p.search(end_time)
                    end_time = p.sub('', end_time)
                programme_end = datetime.fromtimestamp(
                    time.mktime(
                        time.strptime(end_time, '%Y%m%d%H%M%S')
                    )
                )
                programme_end = programme_end + timedelta(hours=HOUR_OFFSET)
                element.set('stop', programme_end.strftime('%Y%m%d%H%M%S'))
 
 
                if programme_start > start_listings:
                        if end_listings:
                                if programme_start < end_listings:
                                        newdoc.append(element)
                        else:
                                newdoc.append(element)
 
output = ElementTree.tostring(newdoc)
 
log.info('Done')
 
if options.cache:
        open(options.cache, 'w').write(output)
 
if options.output:
        open(options.output, 'w').write(output)
else:
        print output