Guest User

cross-eit for python 3

a guest
Sep 5th, 2021
86
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # Fixed for python3 on 2020-04-10
  4. """
  5. This program fetches schedule information from a mythtv database and exports this data to an XMLTV [1]
  6. formatted XML file.
  7.  
  8. check usage(): for further description
  9. """
  10. import os
  11. import datetime
  12. import time
  13. import sys
  14. import getopt
  15. from MythTV import Guide
  16. from xml.etree.ElementTree import Element, SubElement, tostring
  17.  
  18. def usage():
  19.     print("""This script fetches EPG data for specified channels from a mythtv
  20. database and exports this data to an XMLTV [1] formatted XML file.
  21.    
  22. The purpose of this is to extract EPG from channels with good data,
  23. and use this data to populate other channels where no data is available.
  24.  
  25. Script usage:
  26.    cross-eit.py OPTIONS chanid1,xmlid1 chanid2,xmlid2 chanidN,xmlidN
  27.  
  28. Options:
  29.    -o, --output=file   Write output to XML file.
  30.                        If this argument is not specified output is written to ./output.xml
  31.    -h, --help          Show help text (this text)
  32.  
  33. To check the channel numbers for the channels you want to extract EPG from, run the following command:
  34. mysql -u mythtv -p mythconverg -e \"SELECT chanid,callsign from channel WHERE callsign='channel name'\"
  35.  
  36. If you want to import the EPG data from the xml file using mythfilldatabase,
  37. you must add the appropriate xmltvid for each channel you want to import EPG to in mythweb [2]
  38. as well as uncheck the useonairguide for these channels.
  39.  
  40. Example: (assuming sourceid of 1 for mythtv)
  41.    ./cross-eit.py 1004,tv2.guide 1108,history.guide 1022,natgeo.guide -o /tmp/export.xml
  42.    mythfilldatabase -v xmltv  --file 1 /tmp/export.xml
  43.  
  44. [1] http://wiki.xmltv.org/index.php/XMLTVFormat
  45. [2] http://localhost/mythweb/settings/tv/channels
  46. """)
  47.  
  48. def read_arguments(argv):
  49.     """
  50.    Reads arguments argv, checks for valid options and parses channel information. Returns output file and channels
  51.    """
  52.     output="output.xml"
  53.     try:
  54.         opts, args = getopt.getopt(argv, "ho:", ["help", "output="])
  55.     except getopt.GetoptError:          
  56.         usage()                          
  57.         sys.exit(2)
  58.     for opt, arg in opts:                
  59.         if opt in ("-h", "--help"):      
  60.             usage()                    
  61.             sys.exit(2)                  
  62.         elif opt in ("-o", "--output"):
  63.             output = arg              
  64.     if len(args) == 0:
  65.         print("Error: No channels specified. Aborting...\n" % (args))
  66.         usage()
  67.         sys.exit(2)
  68.     channels={}
  69.     for arg in args:
  70.         try:
  71.             c,x=arg.split(",")
  72.         except:
  73.             print("Error: Not able to parse channel %s. Aborting...\n" % (arg))
  74.             usage()
  75.             sys.exit(2)      
  76.         try:
  77.             testint=int(c)
  78.         except:
  79.             print("Error: Channel number is not an integer - check you syntax. Aborting...\n")
  80.             usage()
  81.             sys.exit(2)
  82.         if len(x) == 0:
  83.             print("Error: please XMLTVID is not specified for channel %s. Aborting...\n" % (c))
  84.             usage()
  85.             sys.exit(2)      
  86.         channels[int(c)]=x
  87.     return channels, output
  88.  
  89.  
  90. def d2s(dateobj):
  91.     """
  92.    Reads dateobject and returns a string in XLMTV format with timezone offset.
  93.    """
  94.     date = dateobj # + datetime.timedelta(seconds=time.altzone)
  95.     ### fms: WAS
  96.     ### date = dateobj + datetime.timedelta(seconds=time.altzone)
  97.     return date.strftime("%Y%m%d%H%M%S")
  98.  
  99. class MyGuide( Guide ):
  100.     @classmethod
  101.     def fromChanID(cls, chanid, db=None):
  102.         return cls._fromQuery("WHERE chanid=%s", (chanid,), db)
  103.  
  104. def schedule(channels):
  105.     """
  106.    Retrives EPG for channels 'channels'. Returns XML ELement 'tv'
  107.    """
  108.     #create xml object "tv"
  109.     tv = Element('tv')
  110.     #Read schedule for each channel and create XML elements
  111.     for chan in channels:
  112.         print("Processing channel number: %s, XMLTV id: %s" % (chan, channels[chan]))
  113.         count = 0
  114.         for prog in MyGuide.fromChanID(chan):
  115.             count += 1
  116.             program         = SubElement(tv, 'programme', channel=channels[chan], start=d2s(prog.starttime), stop=d2s(prog.endtime))
  117.             title           = SubElement(program, 'title')
  118.             title.text      = prog.title
  119.             subtitle        = SubElement(program, 'sub-title')
  120.             subtitle.text   = prog.subtitle
  121.             desc            = SubElement(program, 'desc')
  122.             desc.text       = prog.description
  123.             category        = SubElement(program, 'category')
  124.             category.text   = prog.category
  125.             if int(prog.previouslyshown) == 1:
  126.                 prev        = SubElement(program, 'previously-shown')
  127.         print("Number of processed programs: %d\n" % count)
  128.     return tv
  129.    
  130. def writexmltv(elem, file):
  131.     f = open(file,'w')
  132.     print("Writing XMLTV EPG information to file %s\n" % file)
  133.     f.write('<?xml version="1.0" ?>\n')
  134.     f.write('<!DOCTYPE tv SYSTEM "xmltv.dtd">\n')
  135.     #write tv XML element including all program subelements
  136.     f.write(tostring(elem, encoding="unicode"))
  137.     f.close()
  138.  
  139. def main(args):
  140.     """
  141.    Main script
  142.    """
  143.     version = "v1.2"
  144.     print("cross-eit %s\n" % version)
  145.     channels, outputfile = read_arguments(args)
  146.     xmltags=schedule(channels)
  147.     writexmltv(xmltags, outputfile)
  148.  
  149. if __name__ == "__main__":
  150.     main(sys.argv[1:])
  151.  
RAW Paste Data