# -*- coding: ISO-8859-1 -*-
""" capellaScript
>>> Script Download

    Mit diesem Skript werden Capellaskript Dateien von diversen Homepages heruntergeladen
    und im Capella Skript-Verzeichnis im Ordner Scriptdownload abgelegt.
    Alle Dateien werden mit dem Zeitstempel vom Server versehen.
<<<


  File:     Scriptdownload.py
  Author:   Paul Villiger
  e-mail:   villpaul(a)bluewin.ch
  Created:  20.10.2004
  Modified: 30.12.2021

  Purpose:  Mit diesem Skript werden Capellaskript Dateien von diversen Homepages heruntergeladen
            und im Capella Skript-Verzeichnis in einzelne oder mehrere Ordner abgelegt.
            Alle Dateien werden mit dem Zeitstempel vom Server versehen.

  Remark:   - Anwendung auf eigene Gefahr
            - Bestehende Skripts im Zielverzeichnis werden überschrieben
            - Skript kann auch ohne Capella aufgerufen werden, dann werden alle Plugins geladen

  Config:   - Die URL-Liste kann beliebig erweitert werden.
            - Zu jeder URL muss ein Zielverzeichnis definiert werden.

  History   20.10.04 Erstausgabe
            21.10.04 Dialog
            22.10.04 Proxywerte unter Optionen speichern
            12.11.04 - nur geänderte oder neue Dateien übertragen
                     - Externer Aufruf: Option -p <proxy>
            16.11.04 - Fehler mit win32traceutil
            24.04.05 - Download der Plugins von der capella-software Homepage
            30.06.05 - Neue HP von Stefan Thierfeldt
            21.02.06 - Download von ZIP-Dateien, Link zu Klaus Meglitsch
            01.03.06 - Download von CHM-Dateien
            18.03.06 - Icons werden aus Symbole.zip extrahiert
            19.03.06 - Alle Verzeichnisse werden wieder abgefragt
            01.01.07 - Neue Domain http://freenet-homepage.de/peter.becker/
            25.06.07 - Plugins von Hans H. Lampe
            04.07.07 - neue Domain sins942.ch
            13.10.07 - Behandlung für capella 2008
            13.10.07 - Proxy Behandlung entfernt
            27.10.07 - Korrektur
            11.11.07 - Neue Downloadstruktur
            26.11.07 - Download von plugins*.dat
            10.11.08 - Fehler bei Einzelauswahl
            29.03.09 - capella new website
            02.03.10 - Peter Becker neue Website
            08.04.10 - Plugin Symbols bei notensatz-fischer
            11.09.10 - Für capella7 nur Verzeichnis ScriptDownload
                     - Homepage von Stefan Thierfeld unf HH Lampe entfernt, neu bei capella-software
                     - Für capella7 Behandlung von plugins.dat und plugins-1.bmp
                     - Download Skripthandbuch entfernt
                     - Für capella 7 keine Icon-Behandlung
            12.09.10 - Symbole.zip nur bei capella 2008
            13.09.10 - Externer Aufruf unterdrückt
                     - Korrekturen bei plugins.dat
                     - deutsche Fehlertexte
            14.09.10 - plugins.dat Behandlung optimiert
            22.09.10 - Erste Gruppe ohne Namen --> neuer Name: "Plugin Symbolleiste"
            26.09.10 - Logfile wird erstellt, Endemeldung wird angezeigt
            04.12.10 - Neue Homepage Peter Becker
            18.11.13 - Neue URL capella Plugin
            14.04.16 - Url-Zugriff angepasst: 'User-Agent' : "Magic Browser"
            04.06.16 - Zugriff angepasst: sins942.ch via urllib2 rest via urllib
            27.02.17 - AUf Server plugins.dat -> plugins.dat.txt
            03-09.17 - WW Skript internationalisiert (en-de-nl)
            23.01.18 - Anpassungen an capella 8 und MAC - ohne plugins.dat und alle Plugins
            25.03.18 - Verwendung von urllib.urlretrieve um Dateien herunterzuladen
            14.10.19 - Zugriff angepasst: peter-Becker-cap.de via urllib2
            01.12.21 - Neue Url http://www.notensatz-fischer.de
            14.12.21 - capella 9
            30.12.21 - peter-Becker-cap.de via urllib2
"""
english = {
    'noSuppExtEvoc':'Scriptdownload: Extern evocation will (at the moment) not be supported',
    'Symbollist':'Plugin symbol list',
    'dwnldCap6':'Download for capella 6.',
    'dwnldCap5':'Download for capella 5.',
    'errorReadingCapReg':'ERROR with reading capella registry',
    'allPlugins':'All plugins',
    'pluginsOf':'Plugins of ',
    'copyPluginsdat':'copy plugins.dat',
    'pluginsInDir':'The plugins will be placed in the script directory',
    'placed':' ',
    'sel':'Selection',
    'dir':'Use the directory ',
    'use':' ?',
    'pluginsin':'The plugins will be placed in the',
    'savedAuthor':'script directory "plugins_<author>"',
    'orDir':'or in the directory ',
    'UrlRead':'>>>> URL %s read\r\n',
    'errorURLnotFound':'ERROR: Url "%s" not found, , Error: %s',
    'errorTransl':'ERROR with translating from "%s"',
    'fileReady':'>>>> File %s prepared to transfer\r\n',
    'fileAvail':'>>>> File %s is available\r\n',
    'fileNotAvail':'>>>> File %s is not available\r\n',
    'UrlOpen':'>>>> URL %s is opened\r\n',
    'UrlTimeRead':'>>>> URL %s timestamp read\r\n',
    'errorTimeRn':'ERROR with setting of the time of "%s"\r\n',
    'errorTime':'ERROR with setting of the time of "%s"',
    'fileTransfRn':'File transfered: %s\r\n',
    'fileTransfUncRn':'File transfered unconditionally: %s\r\n',
    'fileIsActual':'File is actual: %s\r\n',
    'fileWillOpen':'>>>> File %s will be opened\r\n',
    'fileIsOpen':'>>>> File %s is opened\r\n',
    'fileClosed':'>>>> File %s is closed\r\n',
    'fileTransfd':'File transfered: ',
    'iconsEx':'Icons will be extracted from %s',
    'iconSaved':'Icon saved: ',
    'iconNotSaved':'Icon not saved: ',
    'errorUnzip':'ERROR with unzip of "%s"\r\n, "%s" ',
    'errorDwnloadRn':'ERROR with downloading of "%s"\r\n',
    'errorDwnload':'ERROR with downoading of "%s"',
    'logFileGen':'%s files were transfered.\r\n\r\nThe Logfile %s was generated.',
    'info':'INFO: %s files were transfered.\r\n\r\nThe Logfile %s was generated.',
    'RnrnFilesTr':'\r\n\r\n%s files were transfered'
}
german = {
    'noSuppExtEvoc':'Scriptdownload: Externer Aufruf wird (momentan) nicht unterstützt',
    'Symbollist':'Plugin Symbolleiste',
    'dwnldCap6':'Herunterladen für capella 6.',
    'dwnldCap5':'Herunterladen für capella 5.',
    'errorReadingCapReg':'FEHLER beim Lesen der capella Registry',
    'allPlugins':'Alle Plugins',
    'pluginsOf':'Plugins von ',
    'copyPluginsdat':'plugins.dat kopieren',
    'pluginsInDir':'Die Plugins werden im Skript-Verzeichnis',
    'placed':' abgelegt',
    'sel':'Auswahl',
    'dir':'Verzeichnis ',
    'use':' verwenden?',
    'pluginsin':'Die Plugins werden im Skript-Verzeichnis',
    'savedAuthor':'unter "Plugins_<Autor>" gespeichert',
    'orDir':'oder im Verzeichnis ',
    'UrlRead':'>>>> URL %s eingelesen\r\n',
    'errorURLnotFound':'FEHLER: Url "%s" nicht gefunden, , Error: %s',
    'errorTransl':'FEHLER beim Uebersetzen von "%s"',
    'fileReady':'>>>> Datei %s bereit zum uebertragen\r\n',
    'fileAvail':'>>>> Datei %s ist vorhanden\r\n',
    'fileNotAvail':'>>>> Datei %s ist nicht vorhanden\r\n',
    'UrlOpen':'>>>> URL %s geoeffnet\r\n',
    'UrlTimeRead':'>>>> URL  %s timestamp gelesen\r\n',
    'errorTimeRn':'FEHLER beim setzen der Zeit von "%s"\r\n',
    'errorTime':'FEHLER beim setzen der Zeit von "%s"',
    'fileTransfRn':'Datei uebertragen: %s\r\n',
    'fileTransfUncRn':'Datei uebertragen unbedingt: %s\r\n',
    'fileIsActual':'Datei ist aktuell: %s\r\n',
    'fileWillOpen':'>>>> Datei %s wird geoeffnet\r\n',
    'fileIsOpen':'>>>> Datei %s ist geoeffnet\r\n',
    'fileClosed':'>>>> Datei %s ist geschlossen\r\n',
    'fileTransfd':'Datei ist übertragen: ',
    'iconsEx':'Icons werden aus %s extrahiert',
    'iconSaved':'Icon gespeichert: ',
    'iconNotSaved':'Icon nicht gespeichert: ',
    'errorUnzip':'FEHLER beim Entkomprimieren von "%s"\r\n, "%s" ',
    'errorDwnloadRn':'FEHLER beim Herunterladen von "%s"\r\n',
    'errorDwnload':'FEHLER beim Herunterladen von "%s"',
    'logFileGen':'Es wurden %s Dateien übertragen.\r\n\r\nDas Logfile %s wurde erstellt.',
    'info':'INFO: Es wurden %s Dateien übertragen.\r\n\r\nDas Logfile %s wurde erstellt.',
    'RnrnFilesTr':'\r\n\r\nEs wurden %s Dateien übertragen'
}
dutch = {
    'noSuppExtEvoc':'Scriptdownload: Extern oproepen wordt (momenteel) niet ondersteund',
    'Symbollist':'Plugin Symbolenlijst',
    'dwnldCap6':'Download voor capella 6.',
    'dwnldCap5':'Download voor capella 5.',
    'errorReadingCapReg':'FOUT bij het lezen van capella registry',
    'allPlugins':'Alle plugins',
    'pluginsOf':'Plugins van ',
    'copyPluginsdat':'plugins.dat kopiëren',
    'pluginsInDir':'De plugins worden in de scriptmap',
    'placed':' ondergebracht',
    'sel':'Selectie',
    'dir':'Map ',
    'use':' gebruiken?',
    'pluginsin':'De Plugins worden in de scriptmap',
    'savedAuthor':'onder "plugins_<auteur>" opgeslagen',
    'orDir':'of in de map ',
    'UrlRead':'>>>> URL %s ingelezen\r\n',
    'errorURLnotFound':'FOUT: Url "%s" niet gevonden, Error: %s',
    'errorTransl':'FOUT bij het vertalen van "%s"',
    'fileReady':'>>>> Bestand %s gereed om op te halen\r\n',
    'fileAvail':'>>>> Bestand %s is beschikbaar\r\n',
    'fileNotAvail':'>>>> Bestand %s is niet beschikbaar\r\n',
    'UrlOpen':'>>>> URL %s geopend\r\n',
    'UrlTimeRead':'>>>> URL %s datering gelezen\r\n',
    'errorTimeRn':'FOUT bij instellen van de tijd van "%s"\r\n',
    'errorTime':'FOUT bij instellen van de tijd van "%s"',
    'fileTransfRn':'Bestand opgehaald: %s\r\n',
    'fileTransfUncRn':'Bestand opgehaald zonder voorwaarde: %s\r\n',
    'fileIsActual':'Bestand is actueel: %s\r\n',
    'fileWillOpen':'>>>> Bestand %s wordt geopend\r\n',
    'fileIsOpen':'>>>> Bestand %s is geopend\r\n',
    'fileClosed':'>>>> Bestand %s is gesloten\r\n',
    'fileTransfd':'Bestand opgehaald: ',
    'iconsEx':'Icons worden uit %s overgenomen',
    'iconSaved':'Icon opgeslagen: ',
    'iconNotSaved':'Icon niet opgeslagen: ',
    'errorUnzip':'FOUT bij het uitpakken van "%s"\r\n, "%s" ',
    'errorDwnloadRn':'FOUT bij het downloaden van "%s"\r\n',
    'errorDwnload':'FOUT bij het downloaden van "%s"',
    'logFileGen':'Er werden %s bestanden opgehaald.\r\n\r\nLogfile %s werd gegenereerd.',
    'info':'INFO: Er werden %s bestanden opgehaald.\r\n\r\nLogfile %s werd gegenereerd.',
    'RnrnFilesTr':'\r\n\r\nEr werden %s bestanden opgehaald.'
}

try:
    setStringTable(
        ("en", english),
        ("de", german),
        ("nl", dutch))
except:
    def tr(s):
        return german[s]

import urllib2, sys, zipfile
import htmllib, formatter, string, time
import urllib, urlparse, os.path, os, shutil
# import _winreg

def latin1(u):
    return u.decode('Latin-1')
def latin1e(u):
    return u.encode('Latin-1')

ok = True # wird bei einem Fehler auf "False" gesetzt

excludeFilter = ['Handbuch.zip', 'Update.zip']
downloadManual = False
copyPluginsDat = False
singleDownloadDir = True
scriptFileList = []
downloadDir = 'ScriptDownload'
symbolFile = 'Symbole.zip'  # Diese Datei enthält die Symbole
symbolDir = 'symbols'       # In dieses Verzeichnis werden die Symbole extrahiert


# Liste der zu untersuchenden URL's. Die Liste kann beliebig erweitert werden.
# Beide Listen müssen identische URLs haben
#            URL                                                            Verzeichnis             Autor
urlList_1 = [('http://www.peter-becker-cap.de/scripts_meine.htm',           downloadDir,            'Peter Becker'),
             ('http://www.peter-becker-cap.de/scripts_salis.htm',           downloadDir,            'Radolf von Salis'),
             ('http://www.peter-becker-cap.de/scripts_lampe.htm',           downloadDir,            'H.H. Lampe'),
             ('http://www.peter-becker-cap.de/scripts_capella.htm',         downloadDir,            'capella'),
             ('https://www.sins942.ch/scripts_pv.html',                        downloadDir,            'Paul Villiger'),
             ('https://www.sins942.ch/scripts_ah.html',                        downloadDir,            'Andreas Herzog'),
             ('https://www.sins942.ch/scripts_lh.html',                        downloadDir,            'Lutz Haas'),
             ('https://www.sins942.ch/scripts_hl.html',                        downloadDir,            'Hartmut Lemmel'),
             ('http://www.capella.de/de/index.cfm/produkte/capella/plugins/',      downloadDir,            'Capella Software'),
             ('http://www.notensatz-fischer.de/capella_Dokumente/html/capella_zubehoer.htm',        downloadDir,          'Plugin Symbols')
             ]

# Liste der zu untersuchenden URL's. Die Liste kann beliebig erweitert werden.
#            URL                                                             Verzeichnis                Autor
urlList_2 = [('http://www.peter-becker-cap.de/scripts_meine.htm',           'Plugins_Becker',            'Peter Becker'),
             ('http://www.peter-becker-cap.de/scripts_salis.htm',           'Plugins_Becker',            'Radolf von Salis'),
             ('http://www.peter-becker-cap.de/scripts_lampe.htm',           'Plugins_Becker',            'H.H. Lampe'),
             ('http://www.peter-becker-cap.de/scripts_capella.htm',         'Plugins_Becker',            'capella'),
           ('http://www.sins942.ch/scripts_pv.html',                        'Plugins_Villiger',         'Paul Villiger'),
           ('http://www.sins942.ch/scripts_ah.html',                        'Plugins_Villiger',         'Andreas Herzog'),
           ('http://www.sins942.ch/scripts_lh.html',                        'Plugins_Villiger',         'Lutz Haas'),
           ('http://www.sins942.ch/scripts_hl.html',                        'Plugins_Villiger',         'Hartmut Lemmel'),
           ('http://www.capella.de/de/index.cfm/produkte/capella/plugins/',      'Plugins_Capella_Software', 'Capella Software'),
           ('http://www.notensatz-fischer.de/capella_Dokumente/html/capella_zubehoer.htm',             'Plugins_Symbols',          'Plugin Symbols')
             ]


def handlePluginsDat(new, orig):

    import xml.dom.minidom

    origChanged = False

    if not os.path.isfile(new):
        return
    if not os.path.isfile(orig):
        return

    fileOrig = open(orig, 'r')
    textOrig = fileOrig.read()
    fileOrig.close()

    fileNew = open(new, 'r')
    textNew = fileNew.read()
    fileNew.close()


    if '<?xml' not in textOrig:
        textOrig = '<?xml version="1.0" encoding="ISO-8859-1"?>\n\r' + textOrig

    if '<?xml' not in textNew:
        textNew = '<?xml version="1.0" encoding="ISO-8859-1"?>\n\r' + textNew
        
    try:
        domOrig = xml.dom.minidom.parseString(textOrig)
        domNew  = xml.dom.minidom.parseString(textNew)
    except:
        return

    groupOrig = None
    for group in domOrig.getElementsByTagName('group'):
        itemCount = len(group.getElementsByTagName('item'))
        if 12 <= itemCount < 30:
            groupOrig = group
            break
        if itemCount < 12:
            break
    
    if groupOrig:
        if not groupOrig.hasAttribute("name"):
            groupOrig.setAttribute("name", tr('Symbollist'))

        # replace items without symbol attributes
        for itemOrig in groupOrig.getElementsByTagName('item'):
            path, itemFile = os.path.split(itemOrig.getAttribute('file'))

            for itemNew in domNew.getElementsByTagName('item'):
                path, fil = os.path.split(itemNew.getAttribute('file'))
                if itemFile == fil:
                    itemOrig.parentNode.replaceChild(itemNew.cloneNode(True), itemOrig)
                    break

        # replace original script group with entries from original file
        for group in domNew.getElementsByTagName('group'):
            itemCount = len(group.getElementsByTagName('item'))
            if 12 <= itemCount < 30:
                group.parentNode.replaceChild(groupOrig, group)
                origChanged = True
                break
            if itemCount < 12:
                break

    if origChanged:
        fileOut = open(new, 'w')
        # fileOut.write( domOrig.toprettyxml(' ','','ISO-8859-1') )
        fileOut.write( domNew.toprettyxml(' ','','ISO-8859-1') )
        fileOut.flush()
        fileOut.close()
    
def errorMsg(text):
    messageBox('',text,img=4)

def writeLogFile(log, init=False):
    if init:
        logFile = open(logFileName, 'w')
    else:
        logFile = open(logFileName, 'a')
    logFile.write(log)
    logFile.flush()
    logFile.close()

homePath = getPersonalDataDir()
scriptPath = os.path.join(homePath, 'scripts')
configPath = os.path.join(homePath, 'config','data')
programDir = getProgramDir()

isMac = '/Applications/capella 8.app/' in programDir
    

(capellaVersion, v2, v3) = capVersion()

global logFileName
logFileName = os.path.join(scriptPath, 'Scriptdownload.log')    

# Wenn Download Verzeichnis besteht, dann Voreinstellung auf Einzelverzeichnis aendern 
if os.path.isdir(os.path.join(scriptPath, downloadDir)):
    singleDownloadDir = True
else:
    singleDownloadDir = True
    

# Benutzerdialog starten
if ok:
    selList = [tr('allPlugins')]
    for (url, pluginDir, author) in urlList_1:
        selList.append(tr('pluginsOf')+author)
    cpPluginsDat = CheckBox('', value = copyPluginsDat)
    dirSelect = CheckBox('', value = singleDownloadDir)

    selPlugin = Radio(selList,value=0)

    if capellaVersion == 7:
        dlg = Dialog('Plugin Download',
                     VBox([selPlugin,
                           Label(' '),
                           HBox([cpPluginsDat, Label(tr('copyPluginsdat'))]),
     #                     HBox([dirSelect, Label('Verzeichnis '+downloadDir +' verwenden?')]),
                           Label(' '),
                           Label(tr('pluginsInDir'), width = 40),
                           Label(downloadDir + tr('placed')),
                           ], text=tr('sel'))
                     )

    elif capellaVersion == 6:   # not Version 7
        dlg = Dialog('Plugin Download',
                     VBox([selPlugin,
                           Label(' '),
     #                     HBox([cpPluginsDat, Label('plugins.dat kopieren')]),
                           HBox([dirSelect, Label(tr('dir')+downloadDir +tr('use'))]),
                           Label(' '),
                           Label(tr('pluginsin'), width = 40),
                           Label(tr('savedAuthor')),
                           Label(tr('orDir')+ downloadDir),
                           ], text=tr('sel'))
                     )
    elif capellaVersion >= 8:
        dlg = Dialog('Plugin Download',
                     VBox([
     #                      selPlugin,
     #                      Label(' '),
     #                     HBox([cpPluginsDat, Label(tr('copyPluginsdat'))]),
     #                     HBox([dirSelect, Label('Verzeichnis '+downloadDir +' verwenden?')]),
     #                     Label(' '),
                           Label(tr('pluginsInDir'), width = 40),
                           Label(os.path.join(scriptPath,downloadDir)),
                           Label(tr('placed')),
                           ])
                     )
    else:
        ok = False

if ok:
    if dlg.run():
        if capellaVersion == 8:
            sel = 0
        else:
            sel = selPlugin.value()

        if sel > 0:
            urlList_1 = [urlList_1[sel-1]]
            urlList_2 = [urlList_2[sel-1]]
        # options.set(opt)

        if capellaVersion == 7:
            copyPluginsDat = cpPluginsDat.value()
            singleDownloadDir = True
        elif capellaVersion == 6:
            singleDownloadDir = dirSelect.value()
            copyPluginsDat = False
        else:
            copyPluginsDat = False
            singleDownloadDir = True

    else:
        ok = False

if singleDownloadDir:
    urlList = urlList_1
else:
    urlList = urlList_2
    

if ok:
    writeLogFile('-- Scriptdownload Logfile --\r\n\r\n', True)
    
    fileCount = 0
    for (url, pluginDir, author) in urlList:
        if os.path.isdir(scriptPath):
            pDir = os.path.join(scriptPath,pluginDir)
            if not os.path.isdir(pDir):
                os.mkdir(pDir)   # Plugin Directory erzeugen wenn noch nicht vorhanden


            # URL lesen
            if 'sins942xx' in url or 'peter-becker-cap' in url:
                try:
                    req = urllib2.Request(url, headers={'User-Agent' : "Capella Browser"})
                    f = urllib2.urlopen(req)
                    lines = f.read()
                    f.close()
                    writeLogFile(tr('UrlRead') % (url))
                except urllib2.URLError, e:
                    writeLogFile(tr('errorURLnotFound') % (url, e))
                    errorMsg(tr('errorURLnotFound') % (url, e))
                    continue     # Goto next URL
                """
                except:
                    writeLogFile(tr('errorURLnotFound') % (url, str(sys.exc_info())))
                    errorMsg(tr('errorURLnotFound') % (url, str(sys.exc_info())))
                    continue     # Goto next URL
                """
                    
            else:
                try:
                    f = urllib.urlopen(url)
                    lines = f.read()
                    f.close()
                    writeLogFile(tr('UrlRead') % (url))
                except:
                    writeLogFile(tr('errorURLnotFound') % (url, 'xxx'))
                    errorMsg(tr('errorURLnotFound') % (url,'xxx'))
                    continue     # Goto next URL
                

            # URL Inhalt nach Links durchsuchen -> anchorlist
            try:
                parser = htmllib.HTMLParser(formatter.NullFormatter(), verbose=1)
                parser.feed(lines)
                parser.close()
            except:
                writeLogFile(tr('errorTransl') % (url))
                errorMsg(tr('errorTransl') % (url))
                continue     # Goto next URL

            for l in parser.anchorlist:

                (addressing_scheme, network_location, path, parameters, query, fragment_identifier) = urlparse.urlparse(l)
                root, tail = os.path.split(path)
                head, ext =os.path.splitext(tail)
                if ext == '.py' and head[-3:] <> '_tr':
                    scriptFileList.append(head)

            for l in parser.anchorlist:
                
                downloadUnconditional = False

                (addressing_scheme, network_location, path, parameters, query, fragment_identifier) = urlparse.urlparse(l)
                root, tail = os.path.split(path)
                head, ext = os.path.splitext(tail)
                
                if ext in ['.py']:
                    pass                            # alle Python Files zulassen
                elif ext in ['.zip']:
                    if capellaVersion in [7,8]:
                        continue
                    else:
                        if 'Symbole' in head:
                            pass
                        else:
                            continue
                elif ext in ['.chm', '.info','.html']:
                    found = False
                    for s in scriptFileList:        # prüfen, ob Datei zu einem Pythonscript gehört
                        if s in head:
                            found = True
                    if not found:
                        continue    # Datei überspringen
                elif ext in ['.dat', '.bmp', '.txt']:
                    if 'plugins' not in head:     # nur bestimmte dat Dateien zulassen
                        continue    # Datei überspringen
                    else:
                        if copyPluginsDat:
                            downloadUnconditional = True
                else:
                    continue    # Datei überspringen

                writeLogFile(tr('fileReady') % (path))                

                if addressing_scheme <> '' :
                    # Absoluter Link
                    u = l
                else:
                    # Relativer Link
                    u = urlparse.urljoin(url, path)

                # Dateinamen aus Link bestimmen
                tail = latin1(tail)
                pluginFile = os.path.join(pDir,tail)
                if os.path.isfile(pluginFile):
                    modTime = os.stat(pluginFile)[8]
                    writeLogFile(tr('fileAvail') % (pluginFile))                
                else:
                    modTime = 0.0
                    writeLogFile(tr('fileNotAvail') % (pluginFile))                

                # Link in Datei speichern
                # if True:
                try:
                    if 'sins942_xx' in u or 'peter-becker-cap' in u:
                        req = urllib2.Request(u, headers={'User-Agent' : "Capella Browser"})
                        f = urllib2.urlopen(req)
                    else:
                        f = urllib.urlopen(u)

                    writeLogFile(tr('UrlOpen') % (u))
                    # Speicherdatum des Links bestimmen und Dateidatum setzen                
                    t = time.time()    # default actual time
                    try:
                        infoLines = str(f.info()).splitlines()
                        for l in infoLines:
                            if 'Last-Modified: ' == l[0:15]:
                                t = time.mktime(time.strptime(l[15:],'%a, %d %b %Y %H:%M:%S GMT'))
                                break
                        writeLogFile(tr('UrlTimeRead') % (u))                

                    except:
                        writeLogFile(tr('errorTimeRn') % (pluginFile))
                        errorMsg(tr('errorTime') % (pluginFile))

                    if modTime < t:
                        log = tr('fileTransfRn') % pluginFile
                    elif downloadUnconditional:
                        log = tr('fileTransfUncRn') % pluginFile
                    else:
                        log = (tr('fileIsActual')) % pluginFile
                    writeLogFile(log)
                    
                    
                    # Datei nur übertragen wenn neuere Datei auf Server vorhanden
                    #  oder sich die Zeit auf dem Server nicht bestimmen lässt
                    if modTime < t or downloadUnconditional:
                        """
                        writeLogFile(tr('fileWillOpen') % (pluginFile))                
                        pf = file(pluginFile,'wb')
                        writeLogFile(tr('fileIsOpen') % (pluginFile))                
                        data = f.read(-1)
                        pf.write(data)
                        pf.flush()
                        pf.close()
                        writeLogFile(tr('fileClosed') % (pluginFile))
                        """

                        writeLogFile(tr('fileWillOpen') % (pluginFile))
                        
                        local_file = file(pluginFile, 'wb')
                        writeLogFile('local_file=')
                        local_file.write( f.read() )
                        writeLogFile('local_file.write()')
                        local_file.close()
                        writeLogFile('local_file.close()')
                        

                        # urllib.urlretrieve(u, pluginFile)
                        writeLogFile(tr('fileClosed') % (pluginFile))
                        
                        os.utime(pluginFile,(t,t))

                        fileCount += 1
                        
                        if capellaVersion == 6:
                            try:
                                # ZIP-Dateien extrahieren
                                if symbolFile in pluginFile and zipfile.is_zipfile(pluginFile):
                                    print tr('iconsEx') % (symbolFile)

                                    symbolDirectory = os.path.join(scriptPath, symbolDir)
                                    if not os.path.isdir(symbolDirectory):
                                        os.mkdir(symbolDirectory)
                                    zip = zipfile.ZipFile(pluginFile,'r')
                                    for zf in zip.infolist():
                                        h, e = os.path.splitext(zf.filename)
                                        if e == '.gif':
                                            try:
                                                outFileName = os.path.join(symbolDirectory, latin1(zf.filename))
                                                outFile = file(outFileName, 'wb')
                                                outFile.write(zip.read(zf.filename))
                                                outFile.close()
                                                print tr('iconSaved') , latin1e(outFileName)
                                            except:
                                                print tr('iconNotSaved') , latin1e(outFileName)

                                    zip.close()
                            except:
                                errorMsg(tr('errorUnzip') % (symbolFile, outFileName))
                                zip.close()
                                
                                
                        # rename plugins.dat.txt to plugins.dat (24.02.2017)
                        if 'plugins' in tail and '.dat.txt' in tail:
                            newTail = tail[:-4]
                            shutil.copy ( pluginFile, os.path.join(pDir, newTail) )
                            tail = newTail

                        if copyPluginsDat and tail == 'plugins.dat':
                            pluginsDatFile = os.path.join(configPath, tail)
                            if not os.path.isdir(configPath):
                                os.mkdir(configPath)
                            """
                            # bestehende plugins.dat sichern
                            if modTime > 0.0:
                                pHead,pExt = os.path.splitext(pluginsDatFile)
                                tString = str(datetime.date.fromtimestamp(modTime))
                                saveFile = os.path.join(pHead + '_' + tString, ext)
                                os.rename(pluginsDatFile, saveFile)
                            """
                            
                            handlePluginsDat(pluginFile, pluginsDatFile)
                            
                            shutil.copyfile(pluginFile, pluginsDatFile)
                        

                        if copyPluginsDat and string.lower(tail) == 'plugins-1.bmp':
                            pluginsDatFile = os.path.join(configPath, 'toolbars', tail)
                            if not os.path.isdir(os.path.join(configPath, 'toolbars')):
                                os.mkdir(os.path.join(configPath, 'toolbars'))
                            """
                            # bestehende Plugins-1.bmp sichern
                            if modTime > 0.0:
                                pHead,pExt = os.path.splitext(pluginsDatFile)
                                tString = str(datetime.date.fromtimestamp(modTime))
                                saveFile = os.path.join(pHead + '_' + tString, ext)
                                os.rename(pluginsDatFile, saveFile)
                            """

                            shutil.copyfile(pluginFile, pluginsDatFile)

                except:
                # else:
                    writeLogFile(tr('errorDwnloadRn') % (u))
                    # errorMsg(tr('errorDwnload') % (u))
                    continue     # Goto next file

    # Zentrales Scriptverzeichnis updaten
    scriptList = os.listdir(scriptPath)
    for (url, pluginDir, author) in urlList:                # Symbole in alle Autorenverzeichnisse verteilen
        for sc in scriptList:
            sf = os.path.join(scriptPath,sc)
            df = os.path.join(scriptPath,pluginDir,sc)
            if os.path.isfile(sf) and os.path.isfile(df):   # wenn Datei in beiden Verzeichnissen vorkommt
                if os.stat(df)[8] > os.stat(sf)[8]:         # und Downloadfile neuer ist,
                    try:
                        shutil.copyfile(df,sf)                         #   dann kopieren
                        t = os.stat(df)[8]
                        os.utime(sf, (t,t))                     # Dateidatum setzen
                    except:
                        pass
        if singleDownloadDir:
            break
                
    if capellaVersion <= 6:
        # Symbol.zip Datei ins symbol-Verzeichnis kopieren
        for (url, pluginDir, author) in urlList:                # Symbole in alle Autorenverzeichnisse verteilen
            pluginPath = os.path.join(scriptPath, pluginDir)
            if symbolFile in os.listdir(pluginPath):
                shutil.copyfile(os.path.join(pluginPath, symbolFile), os.path.join(scriptPath, symbolDir, symbolFile))
                break
    
    if capellaVersion <= 6:
        # Symbole verteilen, nur PNG und nur ab Version 6
        symbolZip = os.path.join(scriptPath, symbolDir, symbolFile)
        if capellaVersion == 6 and os.path.isfile(symbolZip) and zipfile.is_zipfile(symbolZip):
            zip = zipfile.ZipFile(symbolZip,'r')
            symbolFiles = zip.namelist()
            zip.close()

            symbolPath = os.path.join(scriptPath,symbolDir)

            def copySymbols(destDir):                           # destDir ist Unterverzeichnis von scriptPath
                destPath = os.path.join(scriptPath, destDir)
                scriptList = os.listdir(destPath)
                for sc in scriptList:
                    sHead, sExt = os.path.splitext(sc)
                    if sExt == '.py':
                        sy = sHead + '.png'
                        df = os.path.join(destPath, sy)
                        if sy in symbolFiles:
                            zip = zipfile.ZipFile(symbolZip,'r')
                            try:                # wenn capella geöffnet ist kann Datei nicht geschrieben werden
                                outFile = file(df, 'wb')
                                outFile.write(zip.read(sy))
                                outFile.close()
                            except:
                                pass
                            zip.close()
                    
            pluginDirList = []
            for (url, pluginDir, author) in urlList:                # Symbole in alle Autorenverzeichnisse verteilen
                if pluginDir not in pluginDirList:                  
                    copySymbols(pluginDir)
                    pluginDirList.append(pluginDir)                 
            
            copySymbols('')                                         # Symbole ins zentralen Scriptverzeichnis kopieren

    text = tr('logFileGen') % (str(fileCount), latin1e(logFileName))
    messageBox('-- Info --', text)
    
    writeLogFile(tr('RnrnFilesTr') % str(fileCount))
