MythTV  master
pbsXSL_api.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 # ----------------------
4 # Name: pbsXSL_api - XPath and XSLT functions for the PBS RSS/HTML itmes
5 # Python Script
6 # Author: R.D. Vaughan
7 # Purpose: This python script is intended to perform a variety of utility functions
8 # for the conversion of data to the MNV standard RSS output format.
9 # See this link for the specifications:
10 # http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format
11 #
12 # License:Creative Commons GNU GPL v2
13 # (http://creativecommons.org/licenses/GPL/2.0/)
14 #-------------------------------------
15 __title__ ="pbsXSL_api - XPath and XSLT functions for the PBS RSS/HTML"
16 __author__="R.D. Vaughan"
17 __purpose__='''
18 This python script is intended to perform a variety of utility functions
19 for the conversion of data to the MNV standard RSS output format.
20 See this link for the specifications:
21 http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format
22 '''
23 
24 __version__="v0.1.0"
25 # 0.1.0 Initial development
26 
27 
28 # Specify the class names that have XPath extention functions
29 __xpathClassList__ = ['xpathFunctions', ]
30 
31 # Specify the XSLT extention class names. Each class is a stand lone extention function
32 #__xsltExtentionList__ = ['xsltExtExample', ]
33 __xsltExtentionList__ = []
34 
35 import os, sys, re, time, datetime, shutil, urllib, string
36 from copy import deepcopy
37 
38 
39 class OutStreamEncoder(object):
40  """Wraps a stream with an encoder"""
41  def __init__(self, outstream, encoding=None):
42  self.out = outstream
43  if not encoding:
44  self.encoding = sys.getfilesystemencoding()
45  else:
46  self.encoding = encoding
47 
48  def write(self, obj):
49  """Wraps the output stream, encoding Unicode strings with the specified encoding"""
50  if isinstance(obj, unicode):
51  try:
52  self.out.write(obj.encode(self.encoding))
53  except IOError:
54  pass
55  else:
56  try:
57  self.out.write(obj)
58  except IOError:
59  pass
60 
61  def __getattr__(self, attr):
62  """Delegate everything but write to the stream"""
63  return getattr(self.out, attr)
64 sys.stdout = OutStreamEncoder(sys.stdout, 'utf8')
65 sys.stderr = OutStreamEncoder(sys.stderr, 'utf8')
66 
67 try:
68  from StringIO import StringIO
69  from lxml import etree
70 except Exception, e:
71  sys.stderr.write(u'\n! Error - Importing the "lxml" and "StringIO" python libraries failed on error(%s)\n' % e)
72  sys.exit(1)
73 
74 # Check that the lxml library is current enough
75 # From the lxml documents it states: (http://codespeak.net/lxml/installation.html)
76 # "If you want to use XPath, do not use libxml2 2.6.27. We recommend libxml2 2.7.2 or later"
77 # Testing was performed with the Ubuntu 9.10 "python-lxml" version "2.1.5-1ubuntu2" repository package
78 version = ''
79 for digit in etree.LIBXML_VERSION:
80  version+=str(digit)+'.'
81 version = version[:-1]
82 if version < '2.7.2':
83  sys.stderr.write(u'''
84 ! Error - The installed version of the "lxml" python library "libxml" version is too old.
85  At least "libxml" version 2.7.2 must be installed. Your version is (%s).
86 ''' % version)
87  sys.exit(1)
88 
89 
90 class xpathFunctions(object):
91  """Functions specific extending XPath
92  """
93  def __init__(self):
94  self.functList = ['pbsTitleSeriesEpisodeLink', 'pbsDuration', 'pbsDownloadlink']
96  # Season 8: Episode 1
97  re.compile(u'''^.+?Season\\ (?P<seasno>[0-9]+)\\:\\ Episode\\ (?P<epno>[0-9]+).*$''', re.UNICODE),
98  # Season 8, Episode 1
99  re.compile(u'''^.+?Season\\ (?P<seasno>[0-9]+)\\,\\ Episode\\ (?P<epno>[0-9]+).*$''', re.UNICODE),
100  # Episode 1:
101  re.compile(u'''^.+?Episode\\ (?P<epno>[0-9]+).*$''', re.UNICODE),
102  ]
103  self.namespaces = {
104  'media': u"http://search.yahoo.com/mrss/",
105  'xhtml': u"http://www.w3.org/1999/xhtml",
106  'mythtv': "http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format",
107  'mediaad': "http://PBS/dtd/mediaad/1.0",
108  }
109  self.persistence = {}
110  # end __init__()
111 
112 
117 
118  def pbsTitleSeriesEpisodeLink(self, context, *arg):
119  '''Generate a link for the PBS site.
120  Call example: 'mnvXpath:pbsTitleSeriesEpisodeLink(normalize-space(./title),normalize-space(./link))/*'
121  return the title, link and season and episode number elements if any were in the title
122  '''
123  tmpTitle = arg[0]
124  tmpLink = arg[1]
125 
126  # Set the custom HTML PBS link
127  tmpVideoCode = tmpLink.replace(u'http://video.pbs.org/video/', u'')[:-1]
128  self.persistence[tmpLink] = common.linkWebPage('dummy', 'pbs')
129 
130  # Parse out any Season
131  seasonNumber = None
132  episodeNumber = None
133  for index in range(len(self.seriesEpisodeRegex)):
134  match = self.seriesEpisodeRegex[index].match(tmpTitle)
135  if match:
136  if index < 2:
137  (seasonNumber, episodeNumber) = match.groups()
138  break
139  else:
140  episodeNumber = match.groups()[0]
141  break
142 
143  # Massage video title
144  index = tmpTitle.rfind('|')
145  if index != -1:
146  tmpTitle = tmpTitle[index+1:].strip()
147  if seasonNumber and episodeNumber:
148  tmpTitle = u'S%02dE%02d: %s' % (int(seasonNumber), int(episodeNumber), tmpTitle)
149  elif episodeNumber:
150  index = tmpTitle.find(':')
151  if index != -1:
152  tmpTitle = tmpTitle[index+1:].strip()
153  tmpTitle = u'Ep%02d: %s' % (int(episodeNumber), tmpTitle)
154  self.persistence[tmpLink] = common.linkWebPage('dummy', 'pbs').replace(u'TITLE', urllib.quote(tmpTitle)).replace(u'VIDEOCODE', tmpVideoCode)
155 
156  # Make the elements to include in the item
157  elementTmp = etree.XML('<xml></xml>')
158  etree.SubElement(elementTmp, "title").text = tmpTitle
159  if seasonNumber:
160  etree.SubElement(elementTmp, "season").text = u"%s" % int(seasonNumber)
161  if episodeNumber:
162  etree.SubElement(elementTmp, "episode").text = u"%s" % int(episodeNumber)
163  etree.SubElement(elementTmp, "link").text = self.persistence[tmpLink]
164  return elementTmp
165  # end pbsTitleSeriesEpisodeLink()
166 
167  def pbsDuration(self, context, *arg):
168  '''Return the video duration in seconds
169  Call example: 'mnvXpath:pbsDuration(normalize-string(./dd/p[@class="info"]/span[@class="time"]))'
170  return the video duration
171  '''
172  if not arg[0]:
173  return u''
174  return arg[0][:-3]
175  # end pbsDuration()
176 
177  def pbsDownloadlink(self, context, *arg):
178  '''Return a previously created download link
179  Call example: 'mnvXpath:pbsDownloadlink(normalize-space(./link))'
180  return the url link
181  '''
182  downloadLink = self.persistence[arg[0]]
183  del self.persistence[arg[0]]
184  return downloadLink
185  # end pbsDownloadlink()
186 
187 
192 
193 
198 
199 
def pbsTitleSeriesEpisodeLink(self, context, *arg)
Start of XPath extension functions.
Definition: pbsXSL_api.py:118
def __init__(self, outstream, encoding=None)
Definition: pbsXSL_api.py:41