Beispiel #1
0
def History_List(params):
    # try to open history
    try:
        htree = ElementTree()
        htree.parse(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'history.xml'))
        xml_h = htree.getroot()
    except:
        xbmc.log("*** HISTORY NOT FOUND ")
        return False

    # build list of history
    for rec_h in xml_h:
        try:
            #get channel details
            name     = rec_h.find('Channel').text.encode('utf-8')
            img      = rec_h.find('Image').text
            url      = rec_h.find('URL').text

            i = xbmcgui.ListItem(rec_h.find('Date').text+' [COLOR FF00FF00]   '+name+'[/COLOR]', path = urllib.unquote(url), thumbnailImage=img) # iconImage=mi.img
            u = sys.argv[0] + '?mode=PLAY'
            u += '&url=%s'%urllib.quote_plus(url)
            u += '&name=%s'%urllib.quote_plus(name)
            u += '&img=%s'%urllib.quote_plus(img)
            i.setProperty('fanart_image', img)
            #i.setProperty('IsPlayable', 'true')
            xbmcplugin.addDirectoryItem(h, u, i, False)
        except:
            pass

    xbmcplugin.endOfDirectory(h)
Beispiel #2
0
def tidy(file, new_inline_tags=None):

    command = ["tidy", "-qn", "-asxml"]

    if new_inline_tags:
        command.append("--new-inline-tags")
        command.append(string.join(new_inline_tags, ","))

    # FIXME: support more tidy options!

    # convert
    os.system(
        "%s %s >%s.out 2>%s.err" % (string.join(command), file, file, file)
        )
    # check that the result is valid XML
    try:
        tree = ElementTree()
        tree.parse(file + ".out")
    except:
        print "*** %s:%s" % sys.exc_info()[:2]
        print ("*** %s is not valid XML "
               "(check %s.err for info)" % (file, file))
        tree = None
    else:
        if os.path.isfile(file + ".out"):
            os.remove(file + ".out")
        if os.path.isfile(file + ".err"):
            os.remove(file + ".err")

    return tree
Beispiel #3
0
def tidy(file, new_inline_tags=None):

    command = ["tidy", "-qn", "-asxml"]

    if new_inline_tags:
        command.append("--new-inline-tags")
        command.append(string.join(new_inline_tags, ","))

    # FIXME: support more tidy options!

    # convert
    os.system(
        "%s %s >%s.out 2>%s.err" % (string.join(command), file, file, file)
        )
    # check that the result is valid XML
    try:
        tree = ElementTree()
        tree.parse(file + ".out")
    except:
        print "*** %s:%s" % sys.exc_info()[:2]
        print ("*** %s is not valid XML "
               "(check %s.err for info)" % (file, file))
        tree = None
    else:
        if os.path.isfile(file + ".out"):
            os.remove(file + ".out")
        if os.path.isfile(file + ".err"):
            os.remove(file + ".err")

    return tree
Beispiel #4
0
def Save_Last_Serial_Info(tag, serial, serial_url, img, part):
    # get max history lenght
    try:
        max_history = (1, 5, 10, 20, 30, 50)[int(Addon.getSetting('history_len'))]
        if max_history > 99:
            max_history = 99
    except:
        max_history = 10

    sdate = today = date.today().isoformat()

    # load or create history file
    try:
        tree = ElementTree()
        tree.parse(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'history.xml'))
        xml1 = tree.getroot()
    except:
        # create XML structure
        xml1 = Element("SERIALU_NET_HISTORY")

    # shrink history to limit
    if len(xml1) > max_history:
        idx = 1
        for rec in xml1:
            if idx >= max_history:
                xml1.remove(rec)
            idx = idx + 1

    # format name
    if part.find('[/COLOR]') > -1:
        part = re.compile('[COLOR FF00FF00](.+?)[/COLOR]', re.MULTILINE|re.DOTALL).find(part)

    xml_hist = None
    # update sequince number for history records
    for rec in xml1:
        if rec.tag == tag:
            rec.find("ID").text = str(0).zfill(2)
            xml_hist = rec
        else:
            rec.find("ID").text = str(int(rec.find("ID").text)+1).zfill(2)

    if xml_hist == None:
        xml_hist = SubElement(xml1, tag)
        SubElement(xml_hist, "ID").text     = str(0).zfill(2)
        SubElement(xml_hist, "Serial").text = unescape(serial)
        SubElement(xml_hist, "URL").text    = serial_url
        SubElement(xml_hist, "Date").text   = sdate
        SubElement(xml_hist, "Part").text   = unescape(part)
        SubElement(xml_hist, "Image").text  = img
    else:
        xml_hist.find("Part").text   = unescape(part)
        xml_hist.find("Date").text   = sdate

    # sort history by IDs
    xml1[:] = sorted(xml1, key=getkey)

    ElementTree(xml1).write(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'history.xml'), encoding='utf-8')
Beispiel #5
0
    def __init__(self, mode):
        #--
        Addon = xbmcaddon.Addon(id='plugin.video.igru.net.ua')
        self.path = os.path.join(Addon.getAddonInfo('path'), r'resources',
                                 r'data')

        today = date.today()
        #--
        if mode == 'UPDATE':
            #load current serial list
            try:
                self.tree = ElementTree()
                self.tree.parse(os.path.join(self.path, 'movies.xml'))
                self.xml = self.tree.getroot()
                self.xml.find("LAST_UPDATE").text = today.isoformat()
                self.movies = self.xml.find('MOVIES')
                self.types = self.xml.find('TYPES')
                self.years = self.xml.find('YEARS')
                self.info = "Update FEPCOM.NET Info"
                self.isUpdate = 1
                self.pinfo = self.xml.find("LOADED_PAGES")
            except:
                # create XML structure
                self.xml = Element("IGRU_NET_UA")
                SubElement(self.xml, "LAST_UPDATE").text = today.isoformat()
                self.movies = SubElement(self.xml, "MOVIES")
                self.types = SubElement(self.xml, "TYPES")
                self.years = SubElement(self.xml, "YEARS")
                self.info = "Reload FEPCOM.NET Info"
                self.isUpdate = 0
                self.pinfo = SubElement(self.xml, "LOADED_PAGES")
        elif mode == 'READ':
            self.tree = ElementTree()
            self.tree.parse(os.path.join(self.path, 'movies.xml'))
            self.xml = self.tree.getroot()
            self.last_update = self.xml.find("LAST_UPDATE").text
            self.movies = self.xml.find('MOVIES')
            self.types = self.xml.find('TYPES')
            self.years = self.xml.find('YEARS')
            self.info = "Update FEPCOM.NET Info"
            self.isUpdate = -1
            self.pinfo = self.xml.find("LOADED_PAGES")
            self.pinfo.text = ''
        else:
            # create XML structure
            self.xml = Element("IGRU_NET_UA")
            SubElement(self.xml, "LAST_UPDATE").text = today.isoformat()
            self.movies = SubElement(self.xml, "MOVIES")
            self.types = SubElement(self.xml, "TYPES")
            self.years = SubElement(self.xml, "YEARS")
            self.info = "Reload FEPCOM.NET Info"
            self.isUpdate = 0
            self.pinfo = SubElement(self.xml, "LOADED_PAGES")
Beispiel #6
0
    def __init__(self, mode):
        #--
        Addon = xbmcaddon.Addon(id='plugin.video.igru.net.ua')
        self.path = os.path.join(Addon.getAddonInfo('path'), r'resources', r'data')

        today = date.today()
        #--
        if mode == 'UPDATE':
            #load current serial list
            try:
                self.tree = ElementTree()
                self.tree.parse(os.path.join(self.path, 'movies.xml'))
                self.xml = self.tree.getroot()
                self.xml.find("LAST_UPDATE").text = today.isoformat()
                self.movies  = self.xml.find('MOVIES')
                self.types   = self.xml.find('TYPES')
                self.years   = self.xml.find('YEARS')
                self.info = "Update FEPCOM.NET Info"
                self.isUpdate= 1
                self.pinfo   = self.xml.find("LOADED_PAGES")
            except:
                # create XML structure
                self.xml = Element("IGRU_NET_UA")
                SubElement(self.xml, "LAST_UPDATE").text = today.isoformat()
                self.movies  = SubElement(self.xml, "MOVIES")
                self.types   = SubElement(self.xml, "TYPES")
                self.years   = SubElement(self.xml, "YEARS")
                self.info = "Reload FEPCOM.NET Info"
                self.isUpdate= 0
                self.pinfo   = SubElement(self.xml, "LOADED_PAGES")
        elif mode == 'READ':
             self.tree = ElementTree()
             self.tree.parse(os.path.join(self.path, 'movies.xml'))
             self.xml = self.tree.getroot()
             self.last_update = self.xml.find("LAST_UPDATE").text
             self.movies  = self.xml.find('MOVIES')
             self.types   = self.xml.find('TYPES')
             self.years   = self.xml.find('YEARS')
             self.info = "Update FEPCOM.NET Info"
             self.isUpdate= -1
             self.pinfo   = self.xml.find("LOADED_PAGES")
             self.pinfo.text = ''
        else:
            # create XML structure
            self.xml = Element("IGRU_NET_UA")
            SubElement(self.xml, "LAST_UPDATE").text = today.isoformat()
            self.movies  = SubElement(self.xml, "MOVIES")
            self.types   = SubElement(self.xml, "TYPES")
            self.years   = SubElement(self.xml, "YEARS")
            self.info = "Reload FEPCOM.NET Info"
            self.isUpdate= 0
            self.pinfo   = SubElement(self.xml, "LOADED_PAGES")
Beispiel #7
0
def Get_Serial_Genre():
    # load serials types
    tree = ElementTree()
    tree.parse(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'serials.xml'))

    for rec in tree.getroot().find('GENRES'):
            name = rec.find('name').text.encode('utf-8')
            tag  = rec.tag.encode('utf-8')
            i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
            u = sys.argv[0] + '?mode=SERIAL'
            u += '&name=%s'%urllib.quote_plus('[ЖАНРЫ]')
            u += '&tag=%s'%urllib.quote_plus(tag)
            xbmcplugin.addDirectoryItem(h, u, i, True)

    xbmcplugin.endOfDirectory(h)
Beispiel #8
0
    def extract(self, stpData):

        if not stpData or not 'name' in stpData:
            return ''

        stpName = stpData['name']

        for directory in self.localizations[stpData['site']]:
            configFileLocations = [
                "{0}{1}/{2}/rcm/{2}.xml".format(self.stpCfgLocation, directory, stpName),
                "{0}{1}/{2}/rcm/{3}.xml".format(self.stpCfgLocation, directory, stpName, stpName.replace('tstp', 'trbs')),
                "{0}{1}/{2}/{2}.xml".format(self.stpCfgLocation, directory, stpName),
                "{0}{1}/{2}/beans/{2}.xml".format(self.stpCfgLocation, directory, stpName),
                "{0}{1}/{2}/beans/{3}.xml".format(self.stpCfgLocation, directory, stpName, stpName.lower()),
            ]

            for configFileLoc in configFileLocations:
                if os.path.exists(configFileLoc):
                    root = ET.parse(configFileLoc).getroot()
                    for xpath in self.paths:
                        for tag in root.findall(xpath):
                            if 'value' in tag.attrib:
                                return str(tag.attrib['value'])
                            return str(tag.text)

        return ''
Beispiel #9
0
def refs_from_protein_xml(xml):
    import ElementTree.ElementTree as ET
    tree = ET.parse(xml)
    root = tree.getroot()
    for seq in root.findall('GBSeq'):
        seq_acc = seq.find('GBSeq_primary-accession').text
        for other_id in seq.findall('GBSeq_other-seqids/GBSeqid'):
            s = other_id.text.split('|')
            if 'gi' == s[0]:
                seq_id = s[1]
                break
        else:
            continue
        refs = set()
        for feature in seq.findall('GBSeq_feature-table/GBFeature'):
            key = feature.find('GBFeature_key')
            if None != key and 'CDS' == key.text:
                for qualifier in feature.findall(
                        'GBFeature_quals/GBQualifier'):
                    name = qualifier.find('GBQualifier_name')
                    if None != name and 'db_xref' == name.text:
                        ref = parse_ref(
                            qualifier.find('GBQualifier_value').text)
                        if ref:
                            refs.add(ref)
        yield seq_acc, T.DbRef.parse_as(seq_id, T.db.entrez_protein), refs
Beispiel #10
0
def Get_Serial_Genre():
    # load serials types
    tree = ElementTree()
    tree.parse(
        os.path.join(Addon.getAddonInfo('path'), r'resources', r'data',
                     r'serials.xml'))

    for rec in tree.getroot().find('GENRES'):
        name = rec.find('name').text.encode('utf-8')
        tag = rec.tag.encode('utf-8')
        i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
        u = sys.argv[0] + '?mode=SERIAL'
        u += '&name=%s' % urllib.quote_plus('[ЖАНРЫ]')
        u += '&tag=%s' % urllib.quote_plus(tag)
        xbmcplugin.addDirectoryItem(h, u, i, True)

    xbmcplugin.endOfDirectory(h)
Beispiel #11
0
 def Save_to_XML(self):
     #-- sort serials/categories/years
     self.movies[:] = sorted(self.movies, key=self.getkey)
     self.types[:] = sorted(self.types, key=self.getkey_name)
     self.years[:] = sorted(self.years, key=self.getkey_name, reverse=True)
     #-- save to XML file
     ElementTree(self.xml).write(os.path.join(self.path, 'movies.xml'),
                                 encoding='utf-8')
Beispiel #12
0
def Check_History(tag):
    # try to open history
    try:
        htree = ElementTree()
        htree.parse(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'history.xml'))
        xml_h = htree.getroot()
    except:
        xbmc.log("*** HISTORY NOT FOUND ")
        return ''

    # build list of history
    try:
        part = xml_h.find(tag).find('Part').text
    except:
        part = ''

    return part.encode('utf-8')
Beispiel #13
0
def Check_History(tag):
    # try to open history
    try:
        htree = ElementTree()
        htree.parse(
            os.path.join(Addon.getAddonInfo('path'), r'resources', r'data',
                         r'history.xml'))
        xml_h = htree.getroot()
    except:
        xbmc.log("*** HISTORY NOT FOUND ")
        return ''

    # build list of history
    try:
        part = xml_h.find(tag).find('Part').text
    except:
        part = ''

    return part.encode('utf-8')
Beispiel #14
0
def Get_Serial_Type():
    # add search to the list
    name = '[COLOR FF00FFF0]' + '[ПОИСК]' + '[/COLOR]'
    i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
    u = sys.argv[0] + '?mode=SERIAL'
    u += '&name=%s' % urllib.quote_plus(name)
    u += '&tag=%s' % urllib.quote_plus(' ')
    xbmcplugin.addDirectoryItem(h, u, i, True)

    # add last viewed serial
    name = '[COLOR FF00FF00]' + '[ИСТОРИЯ]' + '[/COLOR]'
    i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
    u = sys.argv[0] + '?mode=SERIAL'
    u += '&name=%s' % urllib.quote_plus(name)
    u += '&tag=%s' % urllib.quote_plus(' ')
    xbmcplugin.addDirectoryItem(h, u, i, True)

    # add serial genres
    name = '[COLOR FFFFF000]' + '[ЖАНРЫ]' + '[/COLOR]'
    i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
    u = sys.argv[0] + '?mode=GENRE'
    u += '&name=%s' % urllib.quote_plus(name)
    xbmcplugin.addDirectoryItem(h, u, i, True)

    # load serials types
    tree = ElementTree()
    tree.parse(
        os.path.join(Addon.getAddonInfo('path'), r'resources', r'data',
                     r'serials.xml'))

    for rec in tree.getroot().find('TYPES'):
        name = rec.find('name').text.encode('utf-8')
        tag = rec.tag.encode('utf-8')
        i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
        u = sys.argv[0] + '?mode=SERIAL'
        u += '&name=%s' % urllib.quote_plus(name)
        u += '&tag=%s' % urllib.quote_plus(tag)
        xbmcplugin.addDirectoryItem(h, u, i, True)

    xbmcplugin.endOfDirectory(h)
Beispiel #15
0
def Get_Serial_Type():
    # add search to the list
    name = '[COLOR FF00FFF0]' + '[ПОИСК]' + '[/COLOR]'
    i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
    u = sys.argv[0] + '?mode=SERIAL'
    u += '&name=%s'%urllib.quote_plus(name)
    u += '&tag=%s'%urllib.quote_plus(' ')
    xbmcplugin.addDirectoryItem(h, u, i, True)

    # add last viewed serial
    name = '[COLOR FF00FF00]'+ '[ИСТОРИЯ]' + '[/COLOR]'
    i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
    u = sys.argv[0] + '?mode=SERIAL'
    u += '&name=%s'%urllib.quote_plus(name)
    u += '&tag=%s'%urllib.quote_plus(' ')
    xbmcplugin.addDirectoryItem(h, u, i, True)

    # add serial genres
    name = '[COLOR FFFFF000]'+ '[ЖАНРЫ]' + '[/COLOR]'
    i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
    u = sys.argv[0] + '?mode=GENRE'
    u += '&name=%s'%urllib.quote_plus(name)
    xbmcplugin.addDirectoryItem(h, u, i, True)

    # load serials types
    tree = ElementTree()
    tree.parse(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'serials.xml'))

    for rec in tree.getroot().find('TYPES'):
            name = rec.find('name').text.encode('utf-8')
            tag  = rec.tag.encode('utf-8')
            i = xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
            u = sys.argv[0] + '?mode=SERIAL'
            u += '&name=%s'%urllib.quote_plus(name)
            u += '&tag=%s'%urllib.quote_plus(tag)
            xbmcplugin.addDirectoryItem(h, u, i, True)

    xbmcplugin.endOfDirectory(h)
Beispiel #16
0
def Save_History(name, url, img):
    tag = 'ch_'+f_md5(url).hexdigest()

    # get max history lenght
    try:
        max_history = (1, 5, 10, 20, 30, 50)[int(Addon.getSetting('history_len'))]
        if max_history > 99:
            max_history = 99
    except:
        max_history = 10

    sdate = today = date.today().isoformat()

    # load or create history file
    try:
        tree = ElementTree()
        tree.parse(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'history.xml'))
        xml1 = tree.getroot()
    except:
        # create XML structure
        xml1 = Element("ULTIMATV_HISTORY")

    # shrink history to limit
    if len(xml1) > max_history:
        idx = 1
        for rec in xml1:
            if idx >= max_history:
                xml1.remove(rec)
            idx = idx + 1

    xml_hist = None
    # update sequince number for history records
    for rec in xml1:
        if rec.tag == tag:
            rec.find("ID").text = str(0).zfill(2)
            xml_hist = rec
        else:
            rec.find("ID").text = str(int(rec.find("ID").text)+1).zfill(2)

    if xml_hist == None:
        xml_hist = SubElement(xml1, tag)
        SubElement(xml_hist, "ID").text     = str(0).zfill(2)
        SubElement(xml_hist, "Channel").text = unescape(name)
        SubElement(xml_hist, "URL").text    = url
        SubElement(xml_hist, "Image").text  = img
        SubElement(xml_hist, "Date").text   = sdate
    else:
        xml_hist.find("Date").text   = sdate

    # sort history by IDs
    xml1[:] = sorted(xml1, key=getkey)

    ElementTree(xml1).write(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'history.xml'), encoding='utf-8')
Beispiel #17
0
def validateFile(filename):
    """
  Checks if a given file follows SNSC3 pseudo-XML.
  Errors from small files, such as those containing only
  <location> blocks, are suppressed as these cause
  major issues for the parser.
  
  :param filename: name of the file to read from
  :raises ParseError: bubbled up from ElementTree
  """
    with open(filename, 'rb') as xml_file:
        bytes = readXml(xml_file)
        try:
            print('Validating ' + filename + '...')
            tree = ElementTree().parseBytes(bytes)
            if not verify(tree):
                warnings.warn(filename + ' is invalid!')
        finally:
            xml_file.close()
Beispiel #18
0
def refs_from_protein_xml(xml):
    import ElementTree.ElementTree as ET
    tree = ET.parse(xml)
    root = tree.getroot()
    for seq in root.findall('GBSeq'):
        seq_acc = seq.find('GBSeq_primary-accession').text
        for other_id in seq.findall('GBSeq_other-seqids/GBSeqid'):
            s = other_id.text.split('|')
            if 'gi' == s[0]:
                seq_id = s[1]
                break
        else:
            continue
        refs = set()
        for feature in seq.findall('GBSeq_feature-table/GBFeature'):
            key = feature.find('GBFeature_key')
            if None != key and 'CDS' == key.text:
                for qualifier in feature.findall('GBFeature_quals/GBQualifier'):
                    name = qualifier.find('GBQualifier_name')
                    if None != name and 'db_xref' == name.text:
                        ref = parse_ref(qualifier.find('GBQualifier_value').text)
                        if ref:
                            refs.add(ref)
        yield seq_acc, T.DbRef.parse_as(seq_id, T.db.entrez_protein), refs
Beispiel #19
0
import urllib2, urllib, re, cookielib, sys, time

# load XML library
sys.path.append(r'g:\XBMC\resources\lib')
from ElementTree  import Element, SubElement, ElementTree

tree = ElementTree()
tree.parse(r'g:\xbmc\resources\data\test.xml')

for i in tree.getroot():             # Iterates through all found links
    print i.text
    print i.tag

for k in tree.find('text').find('buttonbox2'):
    print k.text
#tree.write("output.xhtml")
Beispiel #20
0
def Save_Last_Serial_Info(tag, serial, serial_url, img, part):
    # get max history lenght
    try:
        max_history = (1, 5, 10, 20, 30,
                       50)[int(Addon.getSetting('history_len'))]
        if max_history > 99:
            max_history = 99
    except:
        max_history = 10

    sdate = today = date.today().isoformat()

    # load or create history file
    try:
        tree = ElementTree()
        tree.parse(
            os.path.join(Addon.getAddonInfo('path'), r'resources', r'data',
                         r'history.xml'))
        xml1 = tree.getroot()
    except:
        # create XML structure
        xml1 = Element("SERIALU_NET_HISTORY")

    # shrink history to limit
    if len(xml1) > max_history:
        idx = 1
        for rec in xml1:
            if idx >= max_history:
                xml1.remove(rec)
            idx = idx + 1

    # format name
    if part.find('[/COLOR]') > -1:
        part = re.compile('[COLOR FF00FF00](.+?)[/COLOR]',
                          re.MULTILINE | re.DOTALL).find(part)

    xml_hist = None
    # update sequince number for history records
    for rec in xml1:
        if rec.tag == tag:
            rec.find("ID").text = str(0).zfill(2)
            xml_hist = rec
        else:
            rec.find("ID").text = str(int(rec.find("ID").text) + 1).zfill(2)

    if xml_hist == None:
        xml_hist = SubElement(xml1, tag)
        SubElement(xml_hist, "ID").text = str(0).zfill(2)
        SubElement(xml_hist, "Serial").text = unescape(serial)
        SubElement(xml_hist, "URL").text = serial_url
        SubElement(xml_hist, "Date").text = sdate
        SubElement(xml_hist, "Part").text = unescape(part)
        SubElement(xml_hist, "Image").text = img
    else:
        xml_hist.find("Part").text = unescape(part)
        xml_hist.find("Date").text = sdate

    # sort history by IDs
    xml1[:] = sorted(xml1, key=getkey)

    ElementTree(xml1).write(os.path.join(Addon.getAddonInfo('path'),
                                         r'resources', r'data',
                                         r'history.xml'),
                            encoding='utf-8')
Beispiel #21
0
def Update_Serial_XML(mode):
    #show Dialog
    dp = xbmcgui.DialogProgress()

    isUpdate = 0

    if mode == 'UPDATE':
        #load current serial list
        try:
            tree = ElementTree()
            tree.parse(os.path.join(path, r'serials.xml'))
            xml1 = tree.getroot()
            xml1.find("LAST_UPDATE").text = today.isoformat()
            xml_serials = xml1.find('SERIALS')
            xml_types = xml1.find('TYPES')
            xml_genres = xml1.find('GENRES')
            dp.create("Update SERIALU.NET Info")
            isUpdate = 1
        except:
            # create XML structure
            xml1 = Element("SERIALU_NET")
            SubElement(xml1, "LAST_UPDATE").text = today.isoformat()
            xml_serials = SubElement(xml1, "SERIALS")
            xml_types = SubElement(xml1, "TYPES")
            xml_genres = SubElement(xml1, "GENRES")
            dp.create("Reload SERIALU.NET Info")
    else:
        # create XML structure
        xml1 = Element("SERIALU_NET")
        SubElement(xml1, "LAST_UPDATE").text = today.isoformat()
        xml_serials = SubElement(xml1, "SERIALS")
        xml_types = SubElement(xml1, "TYPES")
        xml_genres = SubElement(xml1, "GENRES")
        dp.create("Reload SERIALU.NET Info")

    # grab serial's info from site
    url = 'http://serialu.net/'
    #start_time = datetime.now()
    serial_found = 0

    # get max page number for update
    print Addon.getSetting('update_len')
    try:
        max_page = (10, 20, 50, 100, 1000)[int(Addon.getSetting('update_len'))]
    except:
        max_page = 10

    # get number of webpages to grab information
    page_num = Get_Page_Number(url)

    if isUpdate == 1:
        page_num = min(page_num, max_page)

    # get all serials
    for count in range(1, page_num + 1):
        xbmc.log(' ***  page ' + str(count))
        serial_found = Get_Film_Info(url + '/page/' + str(count) + '/',
                                     xml_serials, xml_types, xml_genres,
                                     serial_found, dp)
        percent = min(count * 100 / page_num, 100)
        dp.update(percent, '',
                  'Loaded: ' + str(count) + ' of ' + str(page_num) + ' pages',
                  'Кол-во сериалов: ' + str(serial_found))

    # order sort serials/categories/genres by names
    xml_serials[:] = sorted(xml_serials, key=getkey)
    xml_types[:] = sorted(xml_types, key=getkey)
    xml_genres[:] = sorted(xml_genres, key=getkey)

    dp.close()
    ElementTree(xml1).write(os.path.join(path, r'serials.xml'),
                            encoding='utf-8')
 def parse():
     tree = ElementTree.fromstring(self.url)
Beispiel #23
0
def Get_Serial_List(params):
    s_type = urllib.unquote_plus(params['name'])
    s_tag  = urllib.unquote_plus(params['tag'])
    if s_type == None: return False

    # show search dialog
    if s_type == '[COLOR FF00FFF0]' + '[ПОИСК]' + '[/COLOR]':
        skbd = xbmc.Keyboard()
        skbd.setHeading('Поиск сериалов. Формат: name[:yyyy]')
        skbd.doModal()
        if skbd.isConfirmed():
            SearchStr = skbd.getText().split(':')
            s_name = SearchStr[0]
            if len(SearchStr) > 1:
                s_year = SearchStr[1]
            else:
                s_year = ''
        else:
            return False
        #--
        if not unicode(s_year).isnumeric() and (s_name == '' or s_year <> ''):
            xbmcgui.Dialog().ok('Ошибка поиска',
            'Неверно задан формат поиска сериала.',
            'Используйте формат: ',
            '    <поиск по имени>[:<поиск по году YYYY>]')
            return False

    # load serials types
    tree = ElementTree()
    tree.parse(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'serials.xml'))

    if s_type == '[COLOR FF00FF00]'+ '[ИСТОРИЯ]' + '[/COLOR]':
        # try to open history
        try:
            htree = ElementTree()
            htree.parse(os.path.join(Addon.getAddonInfo('path'), r'resources', r'data', r'history.xml'))
            xml_h = htree.getroot()
        except:
            xbmc.log("*** HISTORY NOT FOUND ")
            return False

        # build list of history
        for rec_h in xml_h:
            rec = tree.getroot().find('SERIALS').find(rec_h.tag.encode('utf-8'))
            try:
                #get serial details
                i_name      = rec_h.find('Date').text+' '+rec.find('name').text.encode('utf-8')
                try:
                    i_year = int(rec.find('year').text)
                except:
                    try:
                        i_year = int(rec.find('year').text.split('-')[0])
                    except:
                        i_year = 1900

                #get serial details
                i_image     = rec.find('img').text.encode('utf-8')
                i_url       = rec.find('url').text.encode('utf-8')
                i_director  = rec.find('director').text
                i_text      = rec.find('text').text
                i_genre     = rec.find('genre').text
                # set serial to XBMC
                i = xbmcgui.ListItem(i_name, iconImage=i_image, thumbnailImage=i_image)
                u = sys.argv[0] + '?mode=LIST'
                u += '&name=%s'%urllib.quote_plus(i_name)
                u += '&url=%s'%urllib.quote_plus(i_url)
                u += '&img=%s'%urllib.quote_plus(i_image)
                u += '&tag=%s'%urllib.quote_plus(rec.tag)
                u += '&part=%s'%urllib.quote_plus(rec_h.find('Part').text.encode('utf-8'))
                i.setInfo(type='video', infoLabels={ 'title':       i_name,
            						'year':        i_year,
            						'director':    i_director,
            						'plot':        i_text,
            						'genre':       i_genre})
                i.setProperty('fanart_image', i_image)
                xbmcplugin.addDirectoryItem(h, u, i, True)
            except:
                pass
    else:
        for rec in tree.getroot().find('SERIALS'):
            try:
                #get serial details
                i_name      = rec.text.encode('utf-8')
                try:
                    i_year = int(rec.find('year').text)
                except:
                    try:
                        i_year = int(rec.find('year').text.split('-')[0])
                    except:
                        i_year = 1900

                if s_type == '[ЖАНРЫ]':
                    if rec.find('genres').find(s_tag) is None:
                        continue

                elif s_type == '[COLOR FF00FFF0]' + '[ПОИСК]' + '[/COLOR]':
                    # checkout by category or name/year
                    if s_name.strip() <> '':
                        s1 = s_name.lower().strip()
                        s2 = rec.text.lower().strip().encode('utf-8')
                        if s1 not in s2:
                            continue
                    if s_year <> '':
                        if int(s_year) <> i_year:
                            continue
                else:
                    if rec.find('categories').find(s_tag) is None:
                        continue

                #get serial details
                i_image     = rec.find('img').text.encode('utf-8')
                i_url       = rec.find('url').text.encode('utf-8')
                i_director  = rec.find('director').text
                i_text      = rec.find('text').text
                i_genre     = rec.find('genre').text
                # set serial to XBMC
                i = xbmcgui.ListItem(i_name, iconImage=i_image, thumbnailImage=i_image)
                u = sys.argv[0] + '?mode=LIST'
                u += '&name=%s'%urllib.quote_plus(i_name)
                u += '&url=%s'%urllib.quote_plus(i_url)
                u += '&img=%s'%urllib.quote_plus(i_image)
                u += '&tag=%s'%urllib.quote_plus(rec.tag)
                u += '&part=%s'%urllib.quote_plus('-')
                i.setInfo(type='video', infoLabels={ 'title':       i_name,
            						'year':        i_year,
            						'director':    i_director,
            						'plot':        i_text,
            						'genre':       i_genre})
                i.setProperty('fanart_image', i_image)
                xbmcplugin.addDirectoryItem(h, u, i, True)
            except:
                xbmc.log('***   ERROR ')

    xbmcplugin.endOfDirectory(h)
Beispiel #24
0
if len(sys.argv) > 1:
    mode = sys.argv[1]
else:
    mode = 'UPDATE'

ret = 'NO'

if mode != 'UPDATE' and mode != 'INFO':
    dialog = xbmcgui.Dialog()
    if dialog.yesno('Внимание!', 'Пересоздание списка сериалов требует',
                    'значительного времени (15-20 минут).',
                    'Пересоздать список?'):
        ret = 'YES'
    else:
        ret = 'NO'

if mode == 'UPDATE' or ret == 'YES':
    Update_Serial_XML(mode)
else:
    if mode == 'INFO':
        dialog = xbmcgui.Dialog()
        tree = ElementTree()
        tree.parse(os.path.join(path, r'serials.xml'))

        update_date = 'Список сериалов создан: ' + tree.getroot().find(
            'LAST_UPDATE').text
        serial_count = 'Количество сериалов   : ' + str(
            len(tree.getroot().find('SERIALS')))

        dialog.ok('Информация', '', update_date, serial_count)
Beispiel #25
0
    def Make_GMP_File(self, save_gmp_path):
        GRMProject = Element("GRMProject")
        GRMProject.set("xmlns", "http://tempuri.org/GRMProject.xsd")
        ProjectSettings = SubElement(GRMProject, "ProjectSettings")
        SubElement(ProjectSettings, 'ProjectFile').text = save_gmp_path
        SubElement(ProjectSettings, 'GRMSimulationType').text = 'SingleEvent'
        SubElement(ProjectSettings, 'WatershedFile')
        SubElement(ProjectSettings, 'SlopeFile')
        SubElement(ProjectSettings, 'FlowDirectionFile')
        SubElement(ProjectSettings, 'FlowAccumFile')
        SubElement(ProjectSettings, 'StreamFile')
        SubElement(ProjectSettings, 'ChannelWidthFile')
        SubElement(ProjectSettings, 'InitialSoilSaturationRatioFile')
        SubElement(ProjectSettings, 'LandCoverDataType').text = 'File'
        SubElement(ProjectSettings, 'LandCoverFile')
        SubElement(ProjectSettings, 'LandCoverVATFile')
        SubElement(ProjectSettings, 'ConstantRoughnessCoeff')
        SubElement(ProjectSettings, 'ConstantImperviousRatio')
        SubElement(ProjectSettings, 'SoilTextureDataType').text = 'File'
        SubElement(ProjectSettings, 'SoilTextureFile')
        SubElement(ProjectSettings, 'SoilTextureVATFile')
        SubElement(ProjectSettings, 'ConstantSoilPorosity')
        SubElement(ProjectSettings, 'ConstantSoilEffPorosity')
        SubElement(ProjectSettings, 'ConstantSoilWettingFrontSuctionHead')
        SubElement(ProjectSettings, 'ConstantSoilHydraulicConductivity')
        SubElement(ProjectSettings, 'SoilDepthDataType').text = 'File'
        SubElement(ProjectSettings, 'SoilDepthFile')
        SubElement(ProjectSettings, 'SoilDepthVATFile')
        SubElement(ProjectSettings, 'ConstantSoilDepth')
        SubElement(ProjectSettings, 'InitialChannelFlowFile')
        SubElement(ProjectSettings,
                   'RainfallDataType').text = 'TextFileASCgrid'
        SubElement(ProjectSettings, 'RainfallInterval')
        SubElement(ProjectSettings, 'RainfallDataFile')
        SubElement(ProjectSettings,
                   'FlowDirectionType').text = 'StartsFromE_TauDEM'
        SubElement(ProjectSettings, 'GridCellSize')
        SubElement(ProjectSettings, 'IsParallel').text = 'true'
        SubElement(ProjectSettings, 'MaxDegreeOfParallelism').text = '-1'
        SubElement(ProjectSettings, 'SimulStartingTime').text = '0'
        SubElement(ProjectSettings, 'ComputationalTimeStep')
        SubElement(ProjectSettings, 'IsFixedTimeStep').text = 'false'
        SubElement(ProjectSettings, 'SimulationDuration')
        SubElement(ProjectSettings, 'OutputTimeStep')
        SubElement(ProjectSettings, 'SimulateInfiltration').text = 'true'
        SubElement(ProjectSettings, 'SimulateSubsurfaceFlow').text = 'true'
        SubElement(ProjectSettings, 'SimulateBaseFlow').text = 'true'
        SubElement(ProjectSettings, 'SimulateFlowControl').text = 'false'
        SubElement(ProjectSettings, 'CrossSectionType').text = 'CSSingle'
        SubElement(ProjectSettings,
                   'SingleCSChannelWidthType').text = 'CWGemeration'
        SubElement(ProjectSettings, 'ChannelWidthEQc').text = '1.698'
        SubElement(ProjectSettings, 'ChannelWidthEQd').text = '0.318'
        SubElement(ProjectSettings, 'ChannelWidthEQe').text = '0.5'
        SubElement(ProjectSettings, 'ChannelWidthMostDownStream')
        SubElement(ProjectSettings, 'LowerRegionHeight')
        SubElement(ProjectSettings, 'LowerRegionBaseWidth')
        SubElement(ProjectSettings, 'UpperRegionBaseWidth')
        SubElement(ProjectSettings, 'CompoundCSIniFlowDepth')
        SubElement(ProjectSettings, 'CompoundCSChannelWidthLimit')
        SubElement(ProjectSettings, 'BankSideSlopeRight').text = '1.5'
        SubElement(ProjectSettings, 'BankSideSlopeLeft').text = '1.5'
        SubElement(ProjectSettings, 'MakeIMGFile').text = 'false'
        SubElement(ProjectSettings, 'MakeASCFile').text = 'false'
        SubElement(ProjectSettings, 'MakeSoilSaturationDistFile').text = 'true'
        SubElement(ProjectSettings, 'MakeRfDistFile').text = 'true'
        SubElement(ProjectSettings, 'MakeRFaccDistFile').text = 'true'
        SubElement(ProjectSettings, 'MakeFlowDistFile').text = 'true'
        SubElement(ProjectSettings, 'PrintOption').text = 'All'
        SubElement(ProjectSettings, 'WriteLog').text = 'false'
        SubElement(ProjectSettings, 'AboutThisProject')
        SubElement(ProjectSettings, 'AboutWatershed')
        SubElement(ProjectSettings, 'AboutLandCoverMap')
        SubElement(ProjectSettings, 'AboutSoilMap')
        SubElement(ProjectSettings, 'AboutSoilDepthMap')
        SubElement(ProjectSettings, 'AboutRainfall')
        SubElement(ProjectSettings, 'ProjectSavedTime')

        # PC 이름 가져오기
        pc_name = os.getenv("COMPUTERNAME")

        # USER (로그인 된 계정) 이름 가져오기
        user_name = os.getenv("USERNAME")

        Path = os.path.dirname(os.path.realpath(__file__)) + "\DLL\GRMCore.dll"
        clsGRM = cGRM(Path)

        SubElement(ProjectSettings, 'ComputerName').text = pc_name
        SubElement(ProjectSettings, 'ComputerUserName').text = user_name
        SubElement(ProjectSettings,
                   'GRMVersion').text = str(clsGRM.BuildInfo.FileVersion)
        ElementTree(GRMProject).write(save_gmp_path,
                                      encoding="utf-8",
                                      xml_declaration=True)
Beispiel #26
0
import urllib2, urllib, re, cookielib, sys, time

# load XML library
sys.path.append(r'g:\XBMC\resources\lib')
from ElementTree import Element, SubElement, ElementTree

window = Element("window")

title = SubElement(window, "title", font="large")
title.text = ("Проверка АБВГД..").decode('utf-8')

text = SubElement(window, "text", wrap="word")

box = SubElement(text, "buttonbox1")
SubElement(box, "button").text = ("OK").decode('utf-8')
SubElement(box, "button").text = ("Проба записи").decode('utf-8')

box = SubElement(text, "buttonbox2")
SubElement(box, "button").text = ("Error").decode('utf-8')
SubElement(box, "button").text = ("Але! Гараж").decode('utf-8')

ElementTree(window).write(r'g:\xbmc\resources\data\test.xml', encoding='utf-8')
Beispiel #27
0
class MovieDB:
    #-- init
    def __init__(self, mode):
        #--
        Addon = xbmcaddon.Addon(id='plugin.video.igru.net.ua')
        self.path = os.path.join(Addon.getAddonInfo('path'), r'resources', r'data')

        today = date.today()
        #--
        if mode == 'UPDATE':
            #load current serial list
            try:
                self.tree = ElementTree()
                self.tree.parse(os.path.join(self.path, 'movies.xml'))
                self.xml = self.tree.getroot()
                self.xml.find("LAST_UPDATE").text = today.isoformat()
                self.movies  = self.xml.find('MOVIES')
                self.types   = self.xml.find('TYPES')
                self.years   = self.xml.find('YEARS')
                self.info = "Update FEPCOM.NET Info"
                self.isUpdate= 1
                self.pinfo   = self.xml.find("LOADED_PAGES")
            except:
                # create XML structure
                self.xml = Element("IGRU_NET_UA")
                SubElement(self.xml, "LAST_UPDATE").text = today.isoformat()
                self.movies  = SubElement(self.xml, "MOVIES")
                self.types   = SubElement(self.xml, "TYPES")
                self.years   = SubElement(self.xml, "YEARS")
                self.info = "Reload FEPCOM.NET Info"
                self.isUpdate= 0
                self.pinfo   = SubElement(self.xml, "LOADED_PAGES")
        elif mode == 'READ':
             self.tree = ElementTree()
             self.tree.parse(os.path.join(self.path, 'movies.xml'))
             self.xml = self.tree.getroot()
             self.last_update = self.xml.find("LAST_UPDATE").text
             self.movies  = self.xml.find('MOVIES')
             self.types   = self.xml.find('TYPES')
             self.years   = self.xml.find('YEARS')
             self.info = "Update FEPCOM.NET Info"
             self.isUpdate= -1
             self.pinfo   = self.xml.find("LOADED_PAGES")
             self.pinfo.text = ''
        else:
            # create XML structure
            self.xml = Element("IGRU_NET_UA")
            SubElement(self.xml, "LAST_UPDATE").text = today.isoformat()
            self.movies  = SubElement(self.xml, "MOVIES")
            self.types   = SubElement(self.xml, "TYPES")
            self.years   = SubElement(self.xml, "YEARS")
            self.info = "Reload FEPCOM.NET Info"
            self.isUpdate= 0
            self.pinfo   = SubElement(self.xml, "LOADED_PAGES")


    #-- system functions -------------------------------------------------------
    def getkey(self, elem):
        return elem.text

    def getkey_name(self, elem):
        return elem.findtext("name")

    def f_md5(self, str):
        rez = md5(str.encode('utf8'))
        return rez.hexdigest()

    def movie_sort_compare(self, a, b):
        return cmp(a['name'], b['name'])

    #-- check if movie exists --------------------------------------------------
    def Is_Movie_Exists(self, url):
        is_found = 0

        for rec in self.movies:
            if rec.find('url').text == url:
                is_found = 1
                break

        return is_found

    #-- get number of loaded pages ---------------------------------------------
    def Get_Loaded_Pages(self, id):
        try:
            pages = int(self.pinfo.find('r'+str(id)).text)
        except:
            pages = 0

        return pages

    #-- set number of loaded pages ---------------------------------------------
    def Set_Loaded_Pages(self, id, pages):
        try:
            self.pinfo.find('r'+str(id)).text = str(pages)
        except:
            SubElement(self.pinfo, 'r'+str(id)).text = str(pages)

    #-- save to file -----------------------------------------------------------
    def Save_to_XML(self):
        #-- sort serials/categories/years
        self.movies[:]  = sorted(self.movies, key=self.getkey)
        self.types[:]   = sorted(self.types,  key=self.getkey_name)
        self.years[:]   = sorted(self.years,  key=self.getkey_name, reverse=True)
        #-- save to XML file
        ElementTree(self.xml).write(os.path.join(self.path, 'movies.xml'), encoding='utf-8')

    #-- add movie --------------------------------------------------------------
    def Add_Movie(self, movie):
        # add info to XML
        xml_movie_hash = 'mov_' + self.f_md5(movie['origin'] + movie['year'])
        #check if movie info exists
        xml_movie = self.movies.find(xml_movie_hash)
        if xml_movie is None:   #-- create new record
            # create serial record in XML
            xml_movie = SubElement(self.movies, xml_movie_hash)
            xml_movie.text = movie['name']
            SubElement(xml_movie, "origin").text   = movie['origin']
            SubElement(xml_movie, "url").text      = movie['url']
            SubElement(xml_movie, "genre").text    = movie['genre']
            SubElement(xml_movie, "director").text = movie['director']
            SubElement(xml_movie, "actors").text   = movie['actor']
            SubElement(xml_movie, "text").text     = movie['descr']
            SubElement(xml_movie, "img").text      = movie['image']
            # add year info
            SubElement(xml_movie, "year").text     = movie['year']
            year_hash = self.Get_Movie_Year(movie['year'])
            # add movie category info
            SubElement(xml_movie, "categories")
            cat = xml_movie.find("categories")
            for cat_rec in movie['category']:
                cat_hash = self.Get_Movie_Type(cat_rec)
                if cat.find(cat_hash) is None:
                    SubElement(cat, cat_hash)

    #-- get type ---------------------------------------------------------------
    def Get_Movie_Type(self, type_name):
        #-- store movie's category in XML
        xml_type_hash = 'st_'+self.f_md5(type_name)
        # check if type exists
        type = self.types.find(xml_type_hash)
        if type is None:
            type = SubElement(self.types, xml_type_hash)
            SubElement(type, "name").text = type_name
        #--
        return xml_type_hash

    #-- get year ---------------------------------------------------------------
    def Get_Movie_Year(self, year_name):
        #-- store movie's year in XML
        xml_type_hash = 'yr_'+self.f_md5(year_name)
        # check if year exists
        year = self.years.find(xml_type_hash)
        if year is None:
            year = SubElement(self.years, xml_type_hash)
            SubElement(year, "name").text = year_name
        #--
        return xml_type_hash

    #-- get type list ----------------------------------------------------------
    def Get_List_Type(self):
        return self.types

     #-- get year list ---------------------------------------------------------
    def Get_List_Year(self):
        return self.years

     #-- get movie list ----------------------------------------------------------
    def Get_List_Movie(self, par_tag, par_year, par_type_hash):
        movie_list = []

        for rec in self.movies:
            #-- get movie info
            i = self.Get_Movie_Info(rec)

            if unicode(i['year']).isnumeric():
                i_year      = int(i['year'])
            else:
                i_year      = 0
            # checkout by category or name/year
            if par_tag <> '*' and par_tag <> '':
                if par_tag not in i['name']:
                        continue
            if par_year <> '':
                if int(par_year) <> i_year:
                    continue
            if par_type_hash <> '':
                if rec.find('categories').find(par_type_hash) is None:
                    continue

            movie_list.append(i)
        #-- sort list
        movie_list.sort(self.movie_sort_compare)

        return movie_list, len(movie_list)

    #---------- get movie info -----------------------------------------------------
    def Get_Movie_Info(self, rec):
        mi = []
        mi = {}
        #-- name
        mi['name']     = rec.text.encode('utf8')
        #-- origin name
        try:    mi['origin']      = rec.find('origin').text.encode('utf8')
        except: mi['origin']      = ''
        #-- image
        try:    mi['img']          = rec.find('img').text.encode('utf8')
        except: mi['img']          = ''
        #-- url
        try:    mi['url']          = rec.find('url').text.encode('utf8')
        except: mi['url']          = ''
        #-- year
        try:    mi['year']         = rec.find('year').text.encode('utf8')
        except: mi['year']         = ''
        if unicode(mi['year'].decode('utf8')).strip().isnumeric(): pass
        else:
            try:
                mi['year'] = re.compile('([0-9][0-9][0-9][0-9])', re.MULTILINE|re.DOTALL).findall(mi['year'])[0]
            except:
                mi['year']= '0000'
        #-- genre
        try:    mi['genre']        = rec.find('genre').text.encode('utf8')
        except: mi['genre']        = ''
        #-- director
        try:    mi['director']     = rec.find('director').text.encode('utf8')
        except: mi['director']     = ''
        #-- actors
        try:    mi['actors']       = rec.find('actors').text.encode('utf8')
        except: mi['actors']       = ''
        #-- description
        try:    mi['text']         = rec.find('text').text.encode('utf8')
        except: mi['text']         = ''
        #-----
        return mi
    #---------------------------------------------------------------------------
Beispiel #28
0
def Get_Serial_List(params):
    s_type = urllib.unquote_plus(params['name'])
    s_tag = urllib.unquote_plus(params['tag'])
    if s_type == None: return False

    # show search dialog
    if s_type == '[COLOR FF00FFF0]' + '[ПОИСК]' + '[/COLOR]':
        skbd = xbmc.Keyboard()
        skbd.setHeading('Поиск сериалов. Формат: name[:yyyy]')
        skbd.doModal()
        if skbd.isConfirmed():
            SearchStr = skbd.getText().split(':')
            s_name = SearchStr[0]
            if len(SearchStr) > 1:
                s_year = SearchStr[1]
            else:
                s_year = ''
        else:
            return False
        #--
        if not unicode(s_year).isnumeric() and (s_name == '' or s_year <> ''):
            xbmcgui.Dialog().ok('Ошибка поиска',
                                'Неверно задан формат поиска сериала.',
                                'Используйте формат: ',
                                '    <поиск по имени>[:<поиск по году YYYY>]')
            return False

    # load serials types
    tree = ElementTree()
    tree.parse(
        os.path.join(Addon.getAddonInfo('path'), r'resources', r'data',
                     r'serials.xml'))

    if s_type == '[COLOR FF00FF00]' + '[ИСТОРИЯ]' + '[/COLOR]':
        # try to open history
        try:
            htree = ElementTree()
            htree.parse(
                os.path.join(Addon.getAddonInfo('path'), r'resources', r'data',
                             r'history.xml'))
            xml_h = htree.getroot()
        except:
            xbmc.log("*** HISTORY NOT FOUND ")
            return False

        # build list of history
        for rec_h in xml_h:
            rec = tree.getroot().find('SERIALS').find(
                rec_h.tag.encode('utf-8'))
            try:
                #get serial details
                i_name = rec_h.find('Date').text + ' ' + rec.find(
                    'name').text.encode('utf-8')
                try:
                    i_year = int(rec.find('year').text)
                except:
                    try:
                        i_year = int(rec.find('year').text.split('-')[0])
                    except:
                        i_year = 1900

                #get serial details
                i_image = rec.find('img').text.encode('utf-8')
                i_url = rec.find('url').text.encode('utf-8')
                i_director = rec.find('director').text
                i_text = rec.find('text').text
                i_genre = rec.find('genre').text
                # set serial to XBMC
                i = xbmcgui.ListItem(i_name,
                                     iconImage=i_image,
                                     thumbnailImage=i_image)
                u = sys.argv[0] + '?mode=LIST'
                u += '&name=%s' % urllib.quote_plus(i_name)
                u += '&url=%s' % urllib.quote_plus(i_url)
                u += '&img=%s' % urllib.quote_plus(i_image)
                u += '&tag=%s' % urllib.quote_plus(rec.tag)
                u += '&part=%s' % urllib.quote_plus(
                    rec_h.find('Part').text.encode('utf-8'))
                i.setInfo(type='video',
                          infoLabels={
                              'title': i_name,
                              'year': i_year,
                              'director': i_director,
                              'plot': i_text,
                              'genre': i_genre
                          })
                i.setProperty('fanart_image', i_image)
                xbmcplugin.addDirectoryItem(h, u, i, True)
            except:
                pass
    else:
        for rec in tree.getroot().find('SERIALS'):
            try:
                #get serial details
                i_name = rec.text.encode('utf-8')
                try:
                    i_year = int(rec.find('year').text)
                except:
                    try:
                        i_year = int(rec.find('year').text.split('-')[0])
                    except:
                        i_year = 1900

                if s_type == '[ЖАНРЫ]':
                    if rec.find('genres').find(s_tag) is None:
                        continue

                elif s_type == '[COLOR FF00FFF0]' + '[ПОИСК]' + '[/COLOR]':
                    # checkout by category or name/year
                    if s_name.strip() <> '':
                        s1 = s_name.lower().strip()
                        s2 = rec.text.lower().strip().encode('utf-8')
                        if s1 not in s2:
                            continue
                    if s_year <> '':
                        if int(s_year) <> i_year:
                            continue
                else:
                    if rec.find('categories').find(s_tag) is None:
                        continue

                #get serial details
                i_image = rec.find('img').text.encode('utf-8')
                i_url = rec.find('url').text.encode('utf-8')
                i_director = rec.find('director').text
                i_text = rec.find('text').text
                i_genre = rec.find('genre').text
                # set serial to XBMC
                i = xbmcgui.ListItem(i_name,
                                     iconImage=i_image,
                                     thumbnailImage=i_image)
                u = sys.argv[0] + '?mode=LIST'
                u += '&name=%s' % urllib.quote_plus(i_name)
                u += '&url=%s' % urllib.quote_plus(i_url)
                u += '&img=%s' % urllib.quote_plus(i_image)
                u += '&tag=%s' % urllib.quote_plus(rec.tag)
                u += '&part=%s' % urllib.quote_plus('-')
                i.setInfo(type='video',
                          infoLabels={
                              'title': i_name,
                              'year': i_year,
                              'director': i_director,
                              'plot': i_text,
                              'genre': i_genre
                          })
                i.setProperty('fanart_image', i_image)
                xbmcplugin.addDirectoryItem(h, u, i, True)
            except:
                xbmc.log('***   ERROR ')

    xbmcplugin.endOfDirectory(h)
Beispiel #29
0
class MovieDB:
    #-- init
    def __init__(self, mode):
        #--
        Addon = xbmcaddon.Addon(id='plugin.video.igru.net.ua')
        self.path = os.path.join(Addon.getAddonInfo('path'), r'resources',
                                 r'data')

        today = date.today()
        #--
        if mode == 'UPDATE':
            #load current serial list
            try:
                self.tree = ElementTree()
                self.tree.parse(os.path.join(self.path, 'movies.xml'))
                self.xml = self.tree.getroot()
                self.xml.find("LAST_UPDATE").text = today.isoformat()
                self.movies = self.xml.find('MOVIES')
                self.types = self.xml.find('TYPES')
                self.years = self.xml.find('YEARS')
                self.info = "Update FEPCOM.NET Info"
                self.isUpdate = 1
                self.pinfo = self.xml.find("LOADED_PAGES")
            except:
                # create XML structure
                self.xml = Element("IGRU_NET_UA")
                SubElement(self.xml, "LAST_UPDATE").text = today.isoformat()
                self.movies = SubElement(self.xml, "MOVIES")
                self.types = SubElement(self.xml, "TYPES")
                self.years = SubElement(self.xml, "YEARS")
                self.info = "Reload FEPCOM.NET Info"
                self.isUpdate = 0
                self.pinfo = SubElement(self.xml, "LOADED_PAGES")
        elif mode == 'READ':
            self.tree = ElementTree()
            self.tree.parse(os.path.join(self.path, 'movies.xml'))
            self.xml = self.tree.getroot()
            self.last_update = self.xml.find("LAST_UPDATE").text
            self.movies = self.xml.find('MOVIES')
            self.types = self.xml.find('TYPES')
            self.years = self.xml.find('YEARS')
            self.info = "Update FEPCOM.NET Info"
            self.isUpdate = -1
            self.pinfo = self.xml.find("LOADED_PAGES")
            self.pinfo.text = ''
        else:
            # create XML structure
            self.xml = Element("IGRU_NET_UA")
            SubElement(self.xml, "LAST_UPDATE").text = today.isoformat()
            self.movies = SubElement(self.xml, "MOVIES")
            self.types = SubElement(self.xml, "TYPES")
            self.years = SubElement(self.xml, "YEARS")
            self.info = "Reload FEPCOM.NET Info"
            self.isUpdate = 0
            self.pinfo = SubElement(self.xml, "LOADED_PAGES")

    #-- system functions -------------------------------------------------------
    def getkey(self, elem):
        return elem.text

    def getkey_name(self, elem):
        return elem.findtext("name")

    def f_md5(self, str):
        rez = md5(str.encode('utf8'))
        return rez.hexdigest()

    def movie_sort_compare(self, a, b):
        return cmp(a['name'], b['name'])

    #-- check if movie exists --------------------------------------------------
    def Is_Movie_Exists(self, url):
        is_found = 0

        for rec in self.movies:
            if rec.find('url').text == url:
                is_found = 1
                break

        return is_found

    #-- get number of loaded pages ---------------------------------------------
    def Get_Loaded_Pages(self, id):
        try:
            pages = int(self.pinfo.find('r' + str(id)).text)
        except:
            pages = 0

        return pages

    #-- set number of loaded pages ---------------------------------------------
    def Set_Loaded_Pages(self, id, pages):
        try:
            self.pinfo.find('r' + str(id)).text = str(pages)
        except:
            SubElement(self.pinfo, 'r' + str(id)).text = str(pages)

    #-- save to file -----------------------------------------------------------
    def Save_to_XML(self):
        #-- sort serials/categories/years
        self.movies[:] = sorted(self.movies, key=self.getkey)
        self.types[:] = sorted(self.types, key=self.getkey_name)
        self.years[:] = sorted(self.years, key=self.getkey_name, reverse=True)
        #-- save to XML file
        ElementTree(self.xml).write(os.path.join(self.path, 'movies.xml'),
                                    encoding='utf-8')

    #-- add movie --------------------------------------------------------------
    def Add_Movie(self, movie):
        # add info to XML
        xml_movie_hash = 'mov_' + self.f_md5(movie['origin'] + movie['year'])
        #check if movie info exists
        xml_movie = self.movies.find(xml_movie_hash)
        if xml_movie is None:  #-- create new record
            # create serial record in XML
            xml_movie = SubElement(self.movies, xml_movie_hash)
            xml_movie.text = movie['name']
            SubElement(xml_movie, "origin").text = movie['origin']
            SubElement(xml_movie, "url").text = movie['url']
            SubElement(xml_movie, "genre").text = movie['genre']
            SubElement(xml_movie, "director").text = movie['director']
            SubElement(xml_movie, "actors").text = movie['actor']
            SubElement(xml_movie, "text").text = movie['descr']
            SubElement(xml_movie, "img").text = movie['image']
            # add year info
            SubElement(xml_movie, "year").text = movie['year']
            year_hash = self.Get_Movie_Year(movie['year'])
            # add movie category info
            SubElement(xml_movie, "categories")
            cat = xml_movie.find("categories")
            for cat_rec in movie['category']:
                cat_hash = self.Get_Movie_Type(cat_rec)
                if cat.find(cat_hash) is None:
                    SubElement(cat, cat_hash)

    #-- get type ---------------------------------------------------------------
    def Get_Movie_Type(self, type_name):
        #-- store movie's category in XML
        xml_type_hash = 'st_' + self.f_md5(type_name)
        # check if type exists
        type = self.types.find(xml_type_hash)
        if type is None:
            type = SubElement(self.types, xml_type_hash)
            SubElement(type, "name").text = type_name
        #--
        return xml_type_hash

    #-- get year ---------------------------------------------------------------
    def Get_Movie_Year(self, year_name):
        #-- store movie's year in XML
        xml_type_hash = 'yr_' + self.f_md5(year_name)
        # check if year exists
        year = self.years.find(xml_type_hash)
        if year is None:
            year = SubElement(self.years, xml_type_hash)
            SubElement(year, "name").text = year_name
        #--
        return xml_type_hash

    #-- get type list ----------------------------------------------------------
    def Get_List_Type(self):
        return self.types

    #-- get year list ---------------------------------------------------------
    def Get_List_Year(self):
        return self.years

    #-- get movie list ----------------------------------------------------------
    def Get_List_Movie(self, par_tag, par_year, par_type_hash):
        movie_list = []

        for rec in self.movies:
            #-- get movie info
            i = self.Get_Movie_Info(rec)

            if unicode(i['year']).isnumeric():
                i_year = int(i['year'])
            else:
                i_year = 0
            # checkout by category or name/year
            if par_tag <> '*' and par_tag <> '':
                if par_tag not in i['name']:
                    continue
            if par_year <> '':
                if int(par_year) <> i_year:
                    continue
            if par_type_hash <> '':
                if rec.find('categories').find(par_type_hash) is None:
                    continue

            movie_list.append(i)
        #-- sort list
        movie_list.sort(self.movie_sort_compare)

        return movie_list, len(movie_list)

    #---------- get movie info -----------------------------------------------------
    def Get_Movie_Info(self, rec):
        mi = []
        mi = {}
        #-- name
        mi['name'] = rec.text.encode('utf8')
        #-- origin name
        try:
            mi['origin'] = rec.find('origin').text.encode('utf8')
        except:
            mi['origin'] = ''
        #-- image
        try:
            mi['img'] = rec.find('img').text.encode('utf8')
        except:
            mi['img'] = ''
        #-- url
        try:
            mi['url'] = rec.find('url').text.encode('utf8')
        except:
            mi['url'] = ''
        #-- year
        try:
            mi['year'] = rec.find('year').text.encode('utf8')
        except:
            mi['year'] = ''
        if unicode(mi['year'].decode('utf8')).strip().isnumeric(): pass
        else:
            try:
                mi['year'] = re.compile('([0-9][0-9][0-9][0-9])', re.MULTILINE
                                        | re.DOTALL).findall(mi['year'])[0]
            except:
                mi['year'] = '0000'
        #-- genre
        try:
            mi['genre'] = rec.find('genre').text.encode('utf8')
        except:
            mi['genre'] = ''
        #-- director
        try:
            mi['director'] = rec.find('director').text.encode('utf8')
        except:
            mi['director'] = ''
        #-- actors
        try:
            mi['actors'] = rec.find('actors').text.encode('utf8')
        except:
            mi['actors'] = ''
        #-- description
        try:
            mi['text'] = rec.find('text').text.encode('utf8')
        except:
            mi['text'] = ''
        #-----
        return mi