MythTV  master
revision3XSL_api.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 # ----------------------
4 # Name: revision3XSL_api - XPath and XSLT functions for the Revision3 RSS/HTML items
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__ ="revision3XSL_api - XPath and XSLT functions for the www.revision3L.com 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.1"
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 = ['revision3LinkGeneration', 'revision3Episode', 'revision3checkIfDBItem', ]
95  self.episodeRegex = [
96  re.compile(u'''^.+?\\-\\-(?P<episodeno>[0-9]+)\\-\\-.*$''', re.UNICODE),
97  ]
98  self.namespaces = {
99  'atom': "http://www.w3.org/2005/Atom",
100  'media': "http://search.yahoo.com/mrss/",
101  'itunes':"http://www.itunes.com/dtds/podcast-1.0.dtd",
102  'xhtml': "http://www.w3.org/1999/xhtml",
103  'mythtv': "http://www.mythtv.org/wiki/MythNetvision_Grabber_Script_Format",
104  'cnettv': "http://cnettv.com/mrss/",
105  'creativeCommons': "http://backend.userland.com/creativeCommonsRssModule",
106  'amp': "http://www.adobe.com/amp/1.0",
107  'content': "http://purl.org/rss/1.0/modules/content/",
108  }
109  self.mediaIdFilters = [
110  [etree.XPath('//object/@id', namespaces=self.namespaces ), None],
111  ]
112  self.FullScreen = u'http://revision3.com/show/popupPlayer?video_id=%s&quality=high&offset=0'
113  self.FullScreenParser = common.parsers['html'].copy()
114  # end __init__()
115 
116 
121 
122  def revision3LinkGeneration(self, context, *arg):
123  '''Generate a link for the video.
124  Call example: 'mnvXpath:revision3LinkGeneration(string(link))'
125  return the url link
126  '''
127  webURL = arg[0]
128  try:
129  tmpHTML = etree.parse(webURL, self.FullScreenParser)
130  except Exception, errmsg:
131  sys.stderr.write(u"Error reading url(%s) error(%s)\n" % (webURL, errmsg))
132  return webURL
133 
134  for index in range(len(self.mediaIdFilters)):
135  mediaId = self.mediaIdFilters[index][0](tmpHTML)
136  if not len(mediaId):
137  continue
138  if self.mediaIdFilters[index][1]:
139  match = self.mediaIdFilters[index][1].match(mediaId[0])
140  if match:
141  videocode = match.groups()
142  return self.FullScreen % (videocode[0])
143  else:
144  return self.FullScreen % (mediaId[0].strip().replace(u'player-', u''))
145  else:
146  return webURL
147  # end revision3LinkGeneration()
148 
149  def revision3Episode(self, context, *arg):
150  '''Parse the download link and extract an episode number
151  Call example: 'mnvXpath:revision3Episode(.)'
152  return the a massaged title element and an episode element in an array
153  '''
154  title = arg[0][0].find('title').text
155  link = arg[0][0].find('enclosure').attrib['url']
156 
157  episodeNumber = u''
158  for index in range(len(self.episodeRegex)):
159  match = self.episodeRegex[index].match(link)
160  if match:
161  episodeNumber = int(match.groups()[0])
162  break
163  titleElement = etree.XML(u"<xml></xml>")
164  etree.SubElement(titleElement, "title").text = u'Ep%03d: %s' % (episodeNumber, title)
165  if episodeNumber:
166  etree.SubElement(titleElement, "episode").text = u'%s' % episodeNumber
167  return [titleElement]
168  # end revision3Episode()
169 
170  def revision3checkIfDBItem(self, context, arg):
171  '''Use a unique key value pairing to find out if the 'internetcontentarticles' table already
172  has a matching item. This is done to save accessing the Internet when not required.
173  Call example: 'mnvXpath:revision3checkIfDBItem(.)'
174  return True if a match was found
175  return False if a match was not found
176  '''
177  return common.checkIfDBItem('dummy', {'title': self.revision3Episode(context, arg)[0].find('title').text, })
178  # end revision3checkIfDBItem()
179 
180 
185 
186 
191 
192 
static pid_list_t::iterator find(const PIDInfoMap &map, pid_list_t &list, pid_list_t::iterator begin, pid_list_t::iterator end, bool find_open)
def revision3LinkGeneration(self, context, *arg)
Start of XPath extension functions.
long long copy(QFile &dst, QFile &src, uint block_size)
Copies src file to dst file.