#!/usr/bin/env python
#
# Copyright (c) 2005-2011 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
# 
# License is granted to copy, to use, and to make and use derivative works
# for non-commercial purposes, provided that this copyright notice and
# contact information is left intact in all such works and any altered
# versions of the source are clearly marked as such.
# 
# This software is provided "AS IS", without warranty of any kind, express
# or implied. In no event shall the author be held liable for any damages
# in connection with this software or the use or other dealings in this
# software.
#
# ************************************************************************
#
# Download Data Direct XML TV Listings data and import it into a MySQL
# database using the xtvd Python module. The username and password needed
# to download the data must be stored in a .xtvd config file in the user's
# home directory.
#
# Each time this program is run, all previous database information is
# cleared and replaced with the information downloaded.

import os, sys, urllib2, xtvd, zlib
from ConfigParser import *
from mx import DateTime

missing_config = """
Please create a .xtvd file in your home directory of the form:

    [auth]
    username: sd_login
    password: sd_password

whee sd_login and sdpassword are the username and password you selected when
you signed up at http://www.schedulesdirect.org/. If you don't yet have a
username and password, please refer to the installation instructions in
README.html.
"""

class GzipStream:
    def __init__(self, fileobj):
        self._fileobj = fileobj
        self._dc = zlib.decompressobj(16+zlib.MAX_WBITS)
        self._buf = ""

    def read(self, size=-1):
        if len(self._buf) == 0:
            self._buf = self._fileobj.read(1024)

        if len(self._buf) > 0:
            result = self._dc.decompress(self._buf, size)
            self._buf = self._dc.unconsumed_tail
        else:
            result = self._dc.flush()

        return result

cfg = ConfigParser()
cfg.read(os.environ['HOME'] + '/.xtvd')

try:
    username = cfg.get('auth', 'username')
    password = cfg.get('auth', 'password')
except (NoOptionError, NoSectionError):
    print missing_config
    sys.exit()

url = 'http://webservices.schedulesdirect.tmsdatadirect.com/schedulesdirect/tvlistings/xtvdService'
realm = 'TMSWebServiceRealm'

start = DateTime.utc()
end = start + 14 * DateTime.oneDay

data = """<?xml version='1.0' encoding='utf-8'?>
          <SOAP-ENV:Envelope
              xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'
              xmlns:xsd='http://www.w3.org/2001/XMLSchema'
              xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
              xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/'>
          <SOAP-ENV:Body>
            <tms:download xmlns:tms='urn:TMSWebServices'>
              <startTime xsi:type='tms:dateTime'>%s</startTime>
              <endTime xsi:type='tms:dateTime'>%s</endTime>
            </tms:download>
          </SOAP-ENV:Body>
          </SOAP-ENV:Envelope>""" % (start.strftime('%Y-%m-%dT00:00:00Z'),
                                     end.strftime('%Y-%m-%dT00:00:00Z'))

authinfo = urllib2.HTTPDigestAuthHandler()
authinfo.add_password(realm, url, username, password)

request = urllib2.Request(url, data,
                          {'Accept-Encoding': 'gzip',
                           'User-Agent': 'xtvd-tools/%s' % xtvd.__version__})

response = urllib2.build_opener(authinfo).open(request)

if response.headers['Content-Encoding'] == 'gzip':
    response = GzipStream(response)

xtvd.load(response)
