Example #1
0
def list_timezones():
    """Return a list of all time zones known to the system."""
    l = []
    for i in xrange(parentsize):
        l.append(_winreg.EnumKey(tzparent, i))
    return l
Example #2
0
def enumerate_recorded_ports_by_vid_pid(vid, pid):
    """Given a port name, checks the dynamically
    linked registries to find the VID/PID values
    associated with this port.

    @param int vid: The Vendor ID
    @param int pid: The Product ID
    @return iterator: An iterator of information for each port with these VID/PID values
    """
    base = "SYSTEM\\CurrentControlSet\\Enum\\USB\\"
    #Convert pid/hex to upper case hex numbers
    #path = get_path(convert_to_16_bit_hex(vid), convert_to_16_bit_hex(pid))

    if vid is not None and pid is not None:
        vidpidkeys = [{
            'key':
            get_path(convert_to_16_bit_hex(vid), convert_to_16_bit_hex(pid)),
            'VID':
            convert_to_16_bit_hex(vid),
            'PID':
            convert_to_16_bit_hex(pid)
        }]
    else:
        vidpidkeys = filter_usb_dev_keys(base, vid, pid)

    for vidpidkey_details in vidpidkeys:
        vidpidkey = vidpidkey_details['key']

        try:
            #The key is the VID PID address for all possible Rep connections
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, vidpidkey)
        except WindowsError as e:
            #Windows registry seems to sometimes enumerates keys that don't exist
            continue
        #For each subkey of key
        for i in itertools.count():
            try:
                #we grab the keys name
                child_name = winreg.EnumKey(
                    key, i)  #EnumKey gets the NAME of a subkey
                #Open a new key which is pointing at the node with the info we need
                new_path = "%s\\%s\\Device Parameters" % (vidpidkey,
                                                          child_name)
                try:
                    child_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                               new_path)
                except WindowsError as e:
                    continue  #not all com ports are fully filled out

                #child_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path+'\\'+child_name+'\\Device Parameters')
                comport_info = {
                    'iSerial': child_name,
                    'VID': vidpidkey_details['VID'],
                    'PID': vidpidkey_details['PID']
                }

                #For each bit of information in this new key
                for j in itertools.count():
                    try:
                        #Grab the values for a certain index
                        child_values = winreg.EnumValue(child_key, j)
                        comport_info[child_values[0]] = child_values[1]
                    #We've reached the end of the tree
                    except EnvironmentError:
                        yield comport_info
                        break
            #We've reached the end of the tree
            except EnvironmentError:
                break
Example #3
0
    def win32Runtime(self):
        try:
            vs = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                 r"SOFTWARE\Microsoft\VisualStudio")

            msbuild = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                r"SOFTWARE\Microsoft\MSBuild\ToolsVersions")

        except WindowsError:
            print("Visual Studio wasn't installed")
            return False

        vsPath = None
        i = 0
        try:
            while True:
                version = _winreg.EnumKey(vs, i)
                try:
                    if float(version) >= 11.0:
                        key = _winreg.OpenKey(vs, r"SxS\VS7")
                        vsPath, type = _winreg.QueryValueEx(key, version)
                except:
                    pass
                i += 1
        except WindowsError:
            pass

        if vsPath is None:
            print("Can't find the Visual Studio's path in the regedit")
            return False

        msbuildPath = None
        i = 0
        try:
            while True:
                version = _winreg.EnumKey(msbuild, i)
                try:
                    if float(version) >= 4.0:
                        key = _winreg.OpenKey(msbuild, version)
                        msbuildPath, type = _winreg.QueryValueEx(
                            key, "MSBuildToolsPath")
                except:
                    pass
                i += 1
        except WindowsError:
            pass

        if msbuildPath is None:
            print("Can't find the MSBuildTools' path in the regedit")
            return False

        res = self.checkFileByExtention(".sln")
        if not res:
            print("Can't find the \".sln\" file")
            return False

        msbuildPath = os.path.join(msbuildPath, "MSBuild.exe")
        projectPath = os.path.join(self.projectPath, self.projectName)
        commands = [
            msbuildPath, projectPath, "/maxcpucount:4", "/t:build",
            "/p:configuration=Debug"
        ]

        child = subprocess.Popen(commands, stdout=subprocess.PIPE)
        for line in child.stdout:
            print(line)

        child.wait()

        return True
 def enum_types(mimedb):
     for i in count():
         try:
             yield _winreg.EnumKey(mimedb, i)
         except EnvironmentError:
             break
Example #5
0
def find_python_from_registry(location, reg=None):
    if platform.system() != 'Windows' or winreg is None:
        return None

    if reg is None:
        path = find_python_from_registry(location,
                                         reg=winreg.HKEY_CURRENT_USER)
        if path is None:
            path = find_python_from_registry(location,
                                             reg=winreg.HKEY_LOCAL_MACHINE)
        return path

    val = None
    sub_key = 'InstallPath'
    compiled = re.compile(r'^\d+\.\d+$')

    try:
        with winreg.OpenKey(reg, location) as handle:
            versions = []
            try:
                for index in range(1024):
                    version = winreg.EnumKey(handle, index)
                    try:
                        if compiled.search(version):
                            versions.append(version)
                    except re.error:
                        pass
            except EnvironmentError:
                pass
            versions.sort(reverse=True)
            for version in versions:
                try:
                    path = winreg.QueryValue(handle, version + '\\' + sub_key)
                    if path is not None:
                        path = find_python_in_folder(path)
                        if path is not None:
                            log(
                                DEBUG,
                                'Found python from {reg}\\{key}\\{version}\\{sub_key}.'
                                .format(
                                    reg=reg,
                                    key=location,
                                    version=version,
                                    sub_key=sub_key,
                                ))
                            return path
                except WindowsError:
                    log(
                        DEBUG,
                        'Could not read registry value "{reg}\\{key}\\{version}\\{sub_key}".'
                        .format(
                            reg=reg,
                            key=location,
                            version=version,
                            sub_key=sub_key,
                        ))
    except WindowsError:
        log(
            DEBUG, 'Could not read registry value "{reg}\\{key}".'.format(
                reg=reg,
                key=location,
            ))
    except:
        log(
            ERROR,
            'Could not read registry value "{reg}\\{key}":\n{exc}'.format(
                reg=reg,
                key=location,
                exc=traceback.format_exc(),
            ))

    return val
Example #6
0
                        usbPorts[portName] = True
                except WindowsError:
                    continue

    # KGS USB for BM46
    try:
        rootKey = _winreg.OpenKey(
            _winreg.HKEY_LOCAL_MACHINE,
            r"SYSTEM\CurrentControlSet\Enum\USB\VID_1148&PID_0001")
    except WindowsError as e:
        pass
    else:
        with rootKey:
            for index in itertools.count():
                try:
                    keyName = _winreg.EnumKey(rootKey, index)
                except WindowsError:
                    break
                try:
                    with _winreg.OpenKey(
                            rootKey,
                            os.path.join(keyName,
                                         "Device Parameters")) as paramsKey:
                        portName = _winreg.QueryValueEx(paramsKey,
                                                        "PortName")[0]
                        ports.append({
                            'friendlyName':
                            u'USB: KGS USB To Serial Com Port (%s)' % portName,
                            'hardwareID':
                            ur'USB\VID_1148&PID_0001',
                            'port':
Example #7
0
 def __iter__(self):
     'Iterate over the key names.'
     return iter(
         tuple(
             _winreg.EnumKey(self.__key, index)
             for index in xrange(_winreg.QueryInfoKey(self.__key)[0])))
Example #8
0
def _find_natspeak():
    '''
    Finds engine 'natspeak.exe' path and verifies supported DNS versions via Windows Registry.
    '''

    try:
        if six.PY2:
            import _winreg as winreg
        else:
            import winreg
    except ImportError:
        printer.out("Could not import winreg")
        return ""

    printer.out("Searching Windows Registry For DNS...")
    proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
    try:
        proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
    except KeyError:
        proc_arch64 = False

    if proc_arch == 'x86' and not proc_arch64:
        arch_keys = {0}
    elif proc_arch == 'x86' or proc_arch == 'amd64':
        arch_keys = {winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY}
    else:
        raise Exception("Unhandled arch: %s" % proc_arch)

    for arch_key in arch_keys:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                             "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
                             0, winreg.KEY_READ | arch_key)
        for i in xrange(0, winreg.QueryInfoKey(key)[0]):
            skey_name = winreg.EnumKey(key, i)
            skey = winreg.OpenKey(key, skey_name)
            DisplayName, Publisher, DisplayVersion, InstallLocation = 'null'
            try:
                DisplayName = winreg.QueryValueEx(skey, 'DisplayName')[0]
                Publisher = winreg.QueryValueEx(skey, 'Publisher')[0]
                DisplayVersion = winreg.QueryValueEx(skey, 'DisplayVersion')[0]
                InstallLocation = winreg.QueryValueEx(skey, 'InstallLocation')[0]
            except OSError as error:
                if error.errno == 2:  # Suppresses '[Error 2] The system cannot find the file specified'
                    pass
                else:
                    printer.out(error)
            finally:
                skey.Close()
                if Publisher == "Nuance Communications Inc." and "Dragon" in DisplayName:
                    DnsVersion = int(str(DisplayVersion)[:2])
                    if DnsVersion >= 13:
                        engine_path = str(Path(InstallLocation).joinpath("Program/natspeak.exe"))
                        if os.path.isfile(engine_path):
                            printer.out("Search Complete.")
                            return engine_path
                    else:
                        printer.out(
                            "Dragon Naturally Speaking {} is not supported by Caster. Only versions 13 and above are supported. Purchase Dragon Naturally Speaking 13 or above"
                            .format(DnsVersion))
    printer.out("Cannot find dragon engine path")
    return ""
Example #9
0
def _get_windows_timezone():  # type: () -> Timezone

    # Windows is special. It has unique time zone names (in several
    # meanings of the word) available, but unfortunately, they can be
    # translated to the language of the operating system, so we need to
    # do a backwards lookup, by going through all time zones and see which
    # one matches.
    handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)

    tz_local_key_name = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
    localtz = winreg.OpenKey(handle, tz_local_key_name)

    timezone_info = {}
    size = winreg.QueryInfoKey(localtz)[1]
    for i in range(size):
        data = winreg.EnumValue(localtz, i)
        timezone_info[data[0]] = data[1]

    localtz.Close()

    if "TimeZoneKeyName" in timezone_info:
        # Windows 7 (and Vista?)

        # For some reason this returns a string with loads of NUL bytes at
        # least on some systems. I don't know if this is a bug somewhere, I
        # just work around it.
        tzkeyname = timezone_info["TimeZoneKeyName"].split("\x00", 1)[0]
    else:
        # Windows 2000 or XP

        # This is the localized name:
        tzwin = timezone_info["StandardName"]

        # Open the list of timezones to look up the real name:
        tz_key_name = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
        tzkey = winreg.OpenKey(handle, tz_key_name)

        # Now, match this value to Time Zone information
        tzkeyname = None
        for i in range(winreg.QueryInfoKey(tzkey)[0]):
            subkey = winreg.EnumKey(tzkey, i)
            sub = winreg.OpenKey(tzkey, subkey)

            info = {}
            size = winreg.QueryInfoKey(sub)[1]
            for i in range(size):
                data = winreg.EnumValue(sub, i)
                info[data[0]] = data[1]

            sub.Close()
            try:
                if info["Std"] == tzwin:
                    tzkeyname = subkey
                    break
            except KeyError:
                # This timezone didn't have proper configuration.
                # Ignore it.
                pass

        tzkey.Close()
        handle.Close()

    if tzkeyname is None:
        raise LookupError("Can not find Windows timezone configuration")

    timezone = windows_timezones.get(tzkeyname)
    if timezone is None:
        # Nope, that didn't work. Try adding "Standard Time",
        # it seems to work a lot of times:
        timezone = windows_timezones.get(tzkeyname + " Standard Time")

    # Return what we have.
    if timezone is None:
        raise LookupError("Unable to find timezone " + tzkeyname)

    return Timezone(timezone)
Example #10
0
 def iter_keys(self, key):
     """! Iterate over subkeys of a key
     """
     for i in range(winreg.QueryInfoKey(key)[0]):
         yield winreg.OpenKey(key, winreg.EnumKey(key, i))
Example #11
0
def xmlUpdate(xmlString, lastInformation):

    xmlFile = xml.dom.minidom.parseString(xmlString)

    # Check Serial number between Ocs and WMI
    ssn = xmlFile.getElementsByTagName("SSN")[0].childNodes[0].nodeValue
    if (len(lastInformation['serialNumber']) > 0
            and ssn != lastInformation['serialNumber']):
        ssn = lastInformation['serialNumber']

    # Operating system installation date
    newnode = xmlFile.createElement("INSTALLDATE")
    newtext = xmlFile.createTextNode(lastInformation['installDate'])
    refnode = xmlFile.getElementsByTagName("OSVERSION")[0]

    newnode.appendChild(newtext)
    refnode.parentNode.insertBefore(newnode, refnode.nextSibling)
    #Optionnal : help to the final xml File can be easy read
    newnode.parentNode.insertBefore(xmlFile.createTextNode("\n"), newnode)

    # Company Register
    newnode = xmlFile.createElement("WINCOMPANY")
    newtext = xmlFile.createTextNode(lastInformation['companyRegister'])
    refnode = xmlFile.getElementsByTagName("WINOWNER")[0]

    newnode.appendChild(newtext)
    refnode.parentNode.insertBefore(newnode, refnode.nextSibling)
    newnode.parentNode.insertBefore(xmlFile.createTextNode("\n"), newnode)

    # OS Architecture
    newnode = xmlFile.createElement("OSARCHITECTURE")
    newtext = xmlFile.createTextNode(lastInformation['osArchitecture'])
    refnode = xmlFile.getElementsByTagName("OSNAME")[0]

    newnode.appendChild(newtext)
    refnode.parentNode.insertBefore(newnode, refnode.nextSibling)
    newnode.parentNode.insertBefore(xmlFile.createTextNode("\n"), newnode)

    # Last login Date
    newnode = xmlFile.createElement("DATELASTLOGGEDUSER")
    newtext = xmlFile.createTextNode(lastInformation['lastLogin'][1])
    refnode = xmlFile.getElementsByTagName("LASTLOGGEDUSER")[0]

    newnode.appendChild(newtext)
    refnode.parentNode.insertBefore(newnode, refnode.nextSibling)
    newnode.parentNode.insertBefore(xmlFile.createTextNode("\n"), newnode)

    # Default Gateway
    newnode = xmlFile.createElement("DEFAULTGATEWAY")
    newtext = xmlFile.createTextNode(lastInformation['defaultGateway'])
    refnode = xmlFile.getElementsByTagName("HARDWARE")[0]

    newnode.appendChild(newtext)
    refnode.appendChild(newnode)
    refnode.appendChild(xmlFile.createTextNode("\n"))

    # First boot date
    newnode = xmlFile.createElement("DATEFIRSTRUN")
    newtext = xmlFile.createTextNode(lastInformation['dateFirst'])
    refnode = xmlFile.getElementsByTagName("BIOS")[0]

    newnode.appendChild(newtext)
    refnode.appendChild(newnode)
    refnode.appendChild(xmlFile.createTextNode("\n"))

    # Last boot date
    newnode = xmlFile.createElement("DATELASTRUN")
    newtext = xmlFile.createTextNode(lastInformation['dateLastBoot'])
    refnode = xmlFile.getElementsByTagName("BIOS")[0]

    newnode.appendChild(newtext)
    refnode.appendChild(newnode)
    refnode.appendChild(xmlFile.createTextNode("\n"))

    # Who is Burner ?
    key = _winreg.OpenKey(
        _winreg.HKEY_CURRENT_USER,
        "Software\Microsoft\Windows\CurrentVersion\Explorer\CD Burning\Drives")
    deviceKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                "System\MountedDevices\\")
    #Search the tag of all burner
    burner = []
    try:
        i = 0
        while True:
            keyname = _winreg.EnumKey(key, i)
            subkey = _winreg.OpenKey(
                _winreg.HKEY_CURRENT_USER,
                "Software\Microsoft\Windows\CurrentVersion\Explorer\CD Burning\Drives\\"
                + keyname)
            if not (_winreg.QueryValueEx(subkey, "Drive Type")[0] == 3):
                burner.append(
                    _winreg.QueryValueEx(deviceKey, "\\??\\" + keyname)[0])

            _winreg.CloseKey(subkey)
            i = i + 1
    except WindowsError:  # pyflakes.ignore
        pass
    _winreg.CloseKey(key)

    #Add if the drive is burner
    for device in xmlFile.getElementsByTagName("DRIVES"):
        if device.getElementsByTagName(
                "TYPE")[0].firstChild.nodeValue == "CD-Rom Drive":
            isBurner = False
            newnode = xmlFile.createElement("BURNER")
            i = 0
            while i < len(burner) and not isBurner:
                #Compare the tag with the tag of DosDevices to found the letter device of the burner
                isBurner = (_winreg.QueryValueEx(
                    deviceKey,
                    "\\DosDevices\\" + device.getElementsByTagName("LETTER")
                    [0].firstChild.nodeValue[0] + ":")[0] == burner[i])
                if isBurner:
                    del burner[i]
                i += 1

            if isBurner:
                newtext = xmlFile.createTextNode("Burner")
            else:
                newtext = xmlFile.createTextNode("Only Reader")

            newnode.appendChild(newtext)
            device.appendChild(newnode)
            device.appendChild(xmlFile.createTextNode("\n"))

    _winreg.CloseKey(deviceKey)

    # Initializing Variable
    listSoftXML = xmlFile.getElementsByTagName("SOFTWARES")
    listSoftXMLDefault = xmlFile.getElementsByTagName("SOFTWARES")
    OSNAME = xmlFile.getElementsByTagName("OSNAME")[0].firstChild.nodeValue
    defaultNode = listSoftXMLDefault[0].cloneNode(1)
    key = _winreg.OpenKey(
        _winreg.HKEY_LOCAL_MACHINE,
        "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")
    updateDetection = Pulse2InventoryProxyConfig().updatedetection

    try:
        i = 0
        while True:  #For every software in Uninstall Registry
            keyname = _winreg.EnumKey(key, i)
            subkey = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\\" +
                keyname)

            try:
                displayName = _winreg.QueryValueEx(subkey, "DisplayName")[0]
                nodeId = foundNodeInList(listSoftXML, "NAME", displayName)

                if nodeId != -1:
                    selectnode = listSoftXML[nodeId]
                    #del(listSoftXML[nodeId])       # Warning : Both key Registry can be exist for the same software.
                    # Drop used software can acelerat the improving
                    # but it can lost some information in two places.
                    #Type Package
                    newnode = xmlFile.createElement("FROM")
                    newtext = xmlFile.createTextNode('win')

                    newnode.appendChild(newtext)
                    selectnode.appendChild(newnode)
                    selectnode.appendChild(xmlFile.createTextNode("\n"))

                    #Software installation Date
                    try:
                        installDate = _winreg.QueryValueEx(
                            subkey, "InstallDate")[0]
                        installDate = windowsDateConversion(installDate, False)
                    except WindowsError:  # pyflakes.ignore
                        installDate = "N/A"

                    newnode = xmlFile.createElement("INSTALLDATE")
                    newtext = xmlFile.createTextNode(installDate)

                    newnode.appendChild(newtext)
                    selectnode.appendChild(newnode)
                    selectnode.appendChild(xmlFile.createTextNode("\n"))

                    # Version Check
                    try:
                        refnode = selectnode.getElementsByTagName(
                            "VERSION")[0].firstChild
                        if refnode.nodeValue == "N/A":
                            displayversion = _winreg.QueryValueEx(
                                subkey, "DisplayVersion")[0]
                            refnode.nodeValue = displayversion
                    except WindowsError:  # pyflakes.ignore
                        pass

                    # Software size calculated on hardDisk
                    try:
                        folder = _winreg.QueryValueEx(subkey,
                                                      "InstallLocation")[0]
                        if len(folder) > 0:
                            foldersize = sizeFolder(folder)
                            if not (foldersize > 0):
                                foldersize = "N/A"

                        else:
                            foldersize = "N/A"
                            newnode = xmlFile.createElement("FOLDER")
                            newtext = xmlFile.createTextNode("N/A")
                            refnode = selectnode.getElementsByTagName(
                                "VERSION")[0]

                            newnode.appendChild(newtext)
                            refnode.parentNode.insertBefore(
                                newnode, refnode.nextSibling)
                            newnode.parentNode.insertBefore(
                                xmlFile.createTextNode("\n"), newnode)

                    except WindowsError:  # pyflakes.ignore
                        foldersize = "N/A"
                        folder = "N/A"

                    newnode = xmlFile.createElement("FOLDERSIZE")
                    newtext = xmlFile.createTextNode(str(foldersize))
                    refnode = selectnode.getElementsByTagName("FOLDER")[0]

                    newnode.appendChild(newtext)
                    refnode.parentNode.insertBefore(newnode,
                                                    refnode.nextSibling)
                    newnode.parentNode.insertBefore(
                        xmlFile.createTextNode("\n"), newnode)

                    # Software Size estimated by Operating System
                    try:
                        estimatedSize = _winreg.QueryValueEx(
                            subkey, "EstimatedSize")[0]
                        if not (estimatedSize > 0):
                            estimatedSize = "N/A"
                    except WindowsError:  # pyflakes.ignore
                        estimatedSize = "N/A"

                    selectnode.getElementsByTagName(
                        "FILESIZE")[0].firstChild.nodeValue = estimatedSize

                    #Uninstall command
                    try:
                        uninstallCommand = _winreg.QueryValueEx(
                            subkey, "UninstallString")[0]
                    except WindowsError:  # pyflakes.ignore
                        uninstallCommand = "N/A"

                    if len(uninstallCommand) == 0:
                        uninstallCommand = "N/A"

                    newnode = xmlFile.createElement("UNINSTALL")
                    newtext = xmlFile.createTextNode(uninstallCommand)

                    newnode.appendChild(newtext)
                    selectnode.appendChild(newnode)
                    selectnode.appendChild(xmlFile.createTextNode("\n"))

                    # update detections
                    isUpdate = False
                    if updateDetection:
                        try:
                            parentKey = _winreg.QueryValueEx(
                                subkey, "ParentKeyName")[0]
                            isUpdate = True
                            nodeParentId = -1
                            if len(parentKey) > 0:
                                if parentKey == 'OperatingSystem':  #Update de l'OS
                                    nodeParentId = foundNodeInList(
                                        listSoftXMLDefault, "NAME", OSNAME)
                                    parentName = OSNAME
                                else:
                                    try:
                                        parentRegisterKey = _winreg.OpenKey(
                                            _winreg.HKEY_LOCAL_MACHINE,
                                            "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\\"
                                            + parentKey)
                                        parentName = _winreg.QueryValueEx(
                                            parentRegisterKey,
                                            "DisplayName")[0]
                                        _winreg.CloseKey(parentRegisterKey)
                                        nodeParentId = foundNodeInList(
                                            listSoftXMLDefault, "NAME",
                                            parentName)
                                    except WindowsError:  # if parent doesn't exist # pyflakes.ignore
                                        parentName = _winreg.QueryValueEx(
                                            subkey, "ParentDisplayName")[0]
                                        if len(
                                                parentName
                                        ) > 0:  # search parent with his name
                                            nodeParentId = foundNodeInList(
                                                listSoftXMLDefault, "NAME",
                                                parentName)
                                            if nodeParentId == -1:  # create the simulated parent
                                                newnode = defaultNode.cloneNode(
                                                    1)
                                                nodeslist = newnode.childNodes
                                                for j in range(
                                                        0, len(nodeslist)):
                                                    if j % 2 == 1:
                                                        nodeslist[
                                                            j].firstChild.nodeValue = "N/A"

                                                newnode.getElementsByTagName(
                                                    "NAME"
                                                )[0].firstChild.nodeValue = parentName
                                                xmlFile.getElementsByTagName(
                                                    "CONTENT")[0].insertBefore(
                                                        newnode,
                                                        listSoftXMLDefault[len(
                                                            listSoftXMLDefault)
                                                                           -
                                                                           1])
                                                nodeParentId = foundNodeInList(
                                                    listSoftXMLDefault, "NAME",
                                                    parentName)

                                            listSoftXMLDefault = xmlFile.getElementsByTagName(
                                                "SOFTWARES")
                                            nodeParentId = foundNodeInList(
                                                listSoftXMLDefault, "NAME",
                                                parentName)

                                if nodeParentId > -1:
                                    '''
                                    selectnode.tagName = "UPDATE"                       #to transformed the select node (update)
                                    del(listSoftXML[nodeId])                            #on child of his parent node (software updated)
                                    selectnode.parentNode.removeChild(selectnode.previousSibling)
                                    listSoftXMLDefault[nodeParentId].appendChild(selectnode)
                                    listSoftXMLDefault[nodeParentId].appendChild(xmlFile.createTextNode("\n"))
                                    '''

                                    selectnode.setAttribute(
                                        "parent", parentName
                                    )  #only notified the dependance by attribute
                                    del (listSoftXML[nodeId])

                        except WindowsError:  # pyflakes.ignore
                            isUpdate = False

                    # if not update, we calculate this Rate Of Use and get icon
                    #log-on frequency    Only for WinXP et 2K (On Vista, it's doesn't exist)
                    if not updateDetection or (updateDetection
                                               and not isUpdate):
                        try:
                            arpKey = _winreg.OpenKey(
                                _winreg.HKEY_LOCAL_MACHINE,
                                "SOFTWARE\Microsoft\Windows\CurrentVersion\App Management\ARPCache\\"
                                + keyname)
                            try:
                                rateOfUse = _winreg.QueryValueEx(
                                    arpKey, "SlowInfoCache")[0]
                                valueRateOfUse = ord(rateOfUse[24])
                                if valueRateOfUse == 255:
                                    valueRateOfUse = "N/A"

                            except WindowsError:  # pyflakes.ignore
                                valueRateOfUse = "N/A"

                            _winreg.CloseKey(arpKey)
                        except WindowsError:  # pyflakes.ignore
                            valueRateOfUse = "N/A"

                        refnode = selectnode.getElementsByTagName("RATEOFUSE")
                        if len(refnode) == 0:
                            newnode = xmlFile.createElement("RATEOFUSE")
                            newtext = xmlFile.createTextNode(
                                str(valueRateOfUse))

                            newnode.appendChild(newtext)
                            selectnode.appendChild(newnode)
                            selectnode.appendChild(
                                xmlFile.createTextNode("\n"))
                        else:
                            if valueRateOfUse != "N/A":
                                if refnode[0].firstChild.valueNode != "N/A":
                                    refnode[0].firstChild.valueNode = refnode[
                                        0].firstChild.valueNode + valueRateOfUse
                                else:
                                    refnode[
                                        0].firstChild.valueNode = valueRateOfUse

                        if Pulse2InventoryProxyConfig().addicon:
                            try:
                                iconpath = _winreg.QueryValueEx(
                                    subkey, "DisplayIcon")[0]
                                if iconpath[0] == '"':
                                    iconpath = iconpath[1:len(iconpath) - 1]

                                k = len(iconpath) - 1
                                while (k > (len(iconpath) - 4)
                                       and iconpath[k] != ','):
                                    k -= 1

                                nIcon = 0
                                if iconpath[k] == ',':
                                    try:
                                        if (k < len(iconpath)):
                                            nIcon = int(iconpath[k + 1])
                                    except ValueError:
                                        pass
                                    iconpath = iconpath[0:k]
                                length = len(iconpath)

                                if iconpath[length - 3:] == 'ico':
                                    stringBit = windowsIconGetter(
                                        iconpath, nIcon, False)
                                else:
                                    stringBit = windowsIconGetter(
                                        iconpath, nIcon, True)

                                if stringBit != None:
                                    newnode = xmlFile.createElement("ICON")
                                    newtext = xmlFile.createTextNode(stringBit)

                                    newnode.appendChild(newtext)
                                    selectnode.appendChild(newnode)
                                    selectnode.appendChild(
                                        xmlFile.createTextNode("\n"))

                            except WindowsError:  # pyflakes.ignore
                                pass

            except WindowsError:  # pyflakes.ignore
                pass

            _winreg.CloseKey(subkey)
            i += 1

    except WindowsError:  # pyflakes.ignore
        pass

    if Pulse2InventoryProxyConfig().addicon:
        # Do NOT FORGET !
        os.remove(dirTmpFile)

    _winreg.CloseKey(key)
    xmlString = xmlFile.toxml("utf-8")
    return xmlString
Example #12
0
 def iter_keys_as_str(self, key):
     """! Iterate over subkeys of a key returning subkey as string
     """
     for i in range(winreg.QueryInfoKey(key)[0]):
         yield winreg.EnumKey(key, i)
Example #13
0
def fetchSDKVars(targetArch='x86', wantedVersion=None):
    archSwitch = scriptSwitchByTargetArch.get(targetArch)
    if not archSwitch:
        common.debug(
            "windowsSdk.py, fetchSDKVars: Unsupported target arch: %s" %
            targetArch)
    try:
        versionsKey = _winreg.OpenKey(
            _winreg.HKEY_LOCAL_MACHINE,
            r'SOFTWARE\Microsoft\Microsoft SDKs\Windows')
    except Exception as e:
        common.debug(
            "windowsSdk.py, fetchSDKVars: Windows SDK tool: no SDKs installed: root registry key not found, %s"
            % e)
        return None
    versionsKeyLen = _winreg.QueryInfoKey(versionsKey)[0]
    if versionsKeyLen < 1:
        common.debug(
            "windowsSdk.py, fetchSDKVars: No SDK versions found: root registry key empty"
        )
        return None
    if wantedVersion:
        versionStrings = [wantedVersion]
    else:
        versionStrings = [
            x for x in (_winreg.EnumKey(versionsKey, index)
                        for index in xrange(versionsKeyLen))
            if x.startswith('v')
        ]
    for v in reversed(versionStrings):
        try:
            versionKey = _winreg.OpenKey(versionsKey, v)
        except Exception as e:
            common.debug(
                "windowsSdk.py, fetchSDKVars: failed to open registry key for version %s: %s"
                % (v, e))
            continue
        try:
            installDir = _winreg.QueryValueEx(versionKey,
                                              "InstallationFolder")[0]
        except Exception as e:
            common.debug(
                "windowsSdk.py, fetchSDKVars: no InstallationFolder value in registry key: %s: %s"
                % (v, e))
            continue
        scriptPath = os.path.join(installDir,
                                  os.path.join('bin', 'setenv.cmd'))
        if not os.path.isfile(scriptPath):
            common.debug(
                "windowsSdk.py, fetchSDKVars: Script %s does not exist" %
                scriptPath)
            continue
        p = subprocess.Popen(
            ['cmd', '/V', '/c', scriptPath, archSwitch, '&&', 'set'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        try:
            return common.parse_output(stdout)
        except Exception as e:
            common.debug(
                "windowsSdk.py, fetchSDKVars: Error parsing script output: %s"
                % e)
            continue
    common.debug("windowsSdk.py, fetchSDKVars: No suitable SDK could be used")
    return None
Example #14
0
    def build_win32(self):
        if not self._platforms.is_win32_active():
            return

        if not cocos.os_is_win32():
            raise cocos.CCPluginError("Please build on winodws")

        project_dir = self._project.get_project_dir()
        win32_projectdir = self._platforms.project_path()
        build_mode = self._mode
        if self._project._is_script_project():
            if build_mode == 'debug':
                output_dir = os.path.join(
                    project_dir, CCPluginCompile.OUTPUT_DIR_SCRIPT_DEBUG,
                    'win32')
            else:
                output_dir = os.path.join(
                    project_dir, CCPluginCompile.OUTPUT_DIR_SCRIPT_RELEASE,
                    'win32')
        else:
            output_dir = os.path.join(project_dir,
                                      CCPluginCompile.OUTPUT_DIR_NATIVE,
                                      build_mode, 'win32')

        cocos.Logging.info("building")
        try:
            vs = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                 r"SOFTWARE\Microsoft\VisualStudio")

            msbuild = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                r"SOFTWARE\Microsoft\MSBuild\ToolsVersions")

        except WindowsError:
            message = "Visual Studio wasn't installed"
            raise cocos.CCPluginError(message)

        vsPath = None
        i = 0
        try:
            while True:
                version = _winreg.EnumKey(vs, i)
                try:
                    if float(version) >= 11.0:
                        key = _winreg.OpenKey(vs, r"SxS\VS7")
                        vsPath, type = _winreg.QueryValueEx(key, version)
                except:
                    pass
                i += 1
        except WindowsError:
            pass

        if vsPath is None:
            message = "Can't find the Visual Studio's path in the regedit"
            raise cocos.CCPluginError(message)

        msbuildPath = None
        i = 0
        try:
            while True:
                version = _winreg.EnumKey(msbuild, i)
                try:
                    if float(version) >= 4.0:
                        key = _winreg.OpenKey(msbuild, version)
                        msbuildPath, type = _winreg.QueryValueEx(
                            key, "MSBuildToolsPath")
                except:
                    pass
                i += 1
        except WindowsError:
            pass

        if msbuildPath is None:
            message = "Can't find the MSBuildTools' path in the regedit"
            raise cocos.CCPluginError(message)

        cfg_obj = self._platforms.get_current_config()
        if cfg_obj.sln_file is not None:
            sln_name = cfg_obj.sln_file
            if cfg_obj.project_name is None:
                import cocos_project
                raise cocos.CCPluginError("Must specified \"%s\" when \"%s\" is specified in file \"%s\"") % \
                      (cocos_project.Win32Config.KEY_PROJECT_NAME, cocos_project.Win32Config.KEY_SLN_FILE, cocos_project.Project.CONFIG)
            else:
                name = cfg_obj.project_name
        else:
            name, sln_name = self.checkFileByExtention(".sln",
                                                       win32_projectdir)
            if not sln_name:
                message = "Can't find the \".sln\" file"
                raise cocos.CCPluginError(message)

        self.project_name = name
        msbuildPath = os.path.join(msbuildPath, "MSBuild.exe")
        projectPath = os.path.join(win32_projectdir, sln_name)
        build_mode = 'Debug' if self._is_debug_mode() else 'Release'

        commands = ' '.join([
            msbuildPath, projectPath, "/maxcpucount:4",
            "/t:%s" % self.project_name,
            "/p:configuration=%s" % build_mode
        ])

        self._run_cmd(commands)

        cocos.Logging.info("build succeeded.")

        # copy files
        build_folder_name = "%s.win32" % build_mode
        build_folder_path = os.path.join(win32_projectdir, build_folder_name)
        if not os.path.isdir(build_folder_path):
            message = "Can not find the %s" % build_folder_path
            raise cocos.CCPluginError(message)

        # remove the files in output dir (keep the exe files)
        if os.path.exists(output_dir):
            output_files = os.listdir(output_dir)
            for element in output_files:
                ele_full_path = os.path.join(output_dir, element)
                if os.path.isfile(ele_full_path):
                    base_name, file_ext = os.path.splitext(element)
                    if not file_ext == ".exe":
                        os.remove(ele_full_path)
                elif os.path.isdir(ele_full_path):
                    shutil.rmtree(ele_full_path)

        # create output dir if it not existed
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        # copy dll & exe
        files = os.listdir(build_folder_path)
        for filename in files:
            name, ext = os.path.splitext(filename)
            proj_exe_name = "%s.exe" % self.project_name
            if ext == '.dll' or filename == proj_exe_name:
                file_path = os.path.join(build_folder_path, filename)
                cocos.Logging.info("Copying %s" % filename)
                shutil.copy(file_path, output_dir)

        # copy lua files & res
        build_cfg_path = self._build_cfg_path()
        build_cfg = os.path.join(build_cfg_path,
                                 CCPluginCompile.BUILD_CONFIG_FILE)
        if not os.path.exists(build_cfg):
            message = "%s not found" % build_cfg
            raise cocos.CCPluginError(message)
        f = open(build_cfg)
        data = json.load(f)

        if data.has_key(CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES):
            if self._no_res:
                fileList = data[CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES]
            else:
                fileList = data[CCPluginCompile.CFG_KEY_COPY_RESOURCES] + data[
                    CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES]
        else:
            fileList = data[CCPluginCompile.CFG_KEY_COPY_RESOURCES]

        for cfg in fileList:
            copy_files_with_config(cfg, build_cfg_path, output_dir)

        self.run_root = output_dir
Example #15
0
def get_localzone_name():
    # Windows is special. It has unique time zone names (in several
    # meanings of the word) available, but unfortunately, they can be
    # translated to the language of the operating system, so we need to
    # do a backwards lookup, by going through all time zones and see which
    # one matches.
    handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)

    TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
    localtz = winreg.OpenKey(handle, TZLOCALKEYNAME)
    keyvalues = valuestodict(localtz)
    localtz.Close()

    if 'TimeZoneKeyName' in keyvalues:
        # Windows 7 (and Vista?)

        # For some reason this returns a string with loads of NUL bytes at
        # least on some systems. I don't know if this is a bug somewhere, I
        # just work around it.
        tzkeyname = keyvalues['TimeZoneKeyName'].split('\x00', 1)[0]
    else:
        # Windows 2000 or XP

        # This is the localized name:
        tzwin = keyvalues['StandardName']

        # Open the list of timezones to look up the real name:
        TZKEYNAME = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
        tzkey = winreg.OpenKey(handle, TZKEYNAME)

        # Now, match this value to Time Zone information
        tzkeyname = None
        for i in range(winreg.QueryInfoKey(tzkey)[0]):
            subkey = winreg.EnumKey(tzkey, i)
            sub = winreg.OpenKey(tzkey, subkey)
            data = valuestodict(sub)
            sub.Close()
            try:
                if data['Std'] == tzwin:
                    tzkeyname = subkey
                    break
            except KeyError:
                # This timezone didn't have proper configuration.
                # Ignore it.
                pass

        tzkey.Close()
        handle.Close()

    if tzkeyname is None:
        raise LookupError('Can not find Windows timezone configuration')

    timezone = win_tz.get(tzkeyname)
    if timezone is None:
        # Nope, that didn't work. Try adding "Standard Time",
        # it seems to work a lot of times:
        timezone = win_tz.get(tzkeyname + " Standard Time")

    # Return what we have.
    if timezone is None:
        raise pytz.UnknownTimeZoneError('Can not find timezone ' + tzkeyname)

    return timezone
Example #16
0
def configure_sopcast(latest_version):
    #Configuration for LINUX
    if xbmc.getCondVisibility(
            'system.platform.linux'
    ) and not xbmc.getCondVisibility('system.platform.Android'):
        print("Detected OS: Linux")
        #Linux Armv
        if "arm" in os.uname()[4]:
            print("Sopcast Configuration - LINUX ARM")
            if settings.getSetting('rpi2') == "true":
                print("Raspberry PI 2")
                SPSC_KIT = os.path.join(addonpath,
                                        sopcast_raspberry.split("/")[-1])
                download_tools().Downloader(sopcast_raspberry, SPSC_KIT,
                                            translate(30076), translate(30000))
                if tarfile.is_tarfile(SPSC_KIT):
                    path_libraries = os.path.join(pastaperfil, "sopcast")
                    download_tools().extract(SPSC_KIT, path_libraries)
                    xbmc.sleep(500)
                    download_tools().remove(SPSC_KIT)
                if latest_version:
                    settings.setSetting('sopcast_version',
                                        value=latest_version)
                return

        elif os.uname()[4] == "x86_64":
            generic = False
            if settings.getSetting('openelecx86_64') == "true":
                print("Detected OpenELEC x86_64")
                SPSC_KIT = os.path.join(addonpath,
                                        openelecx86_64_sopcast.split("/")[-1])
                download_tools().Downloader(openelecx86_64_sopcast, SPSC_KIT,
                                            translate(30076), translate(30000))
                if tarfile.is_tarfile(SPSC_KIT):
                    download_tools().extract(SPSC_KIT, pastaperfil)
                    xbmc.sleep(500)
                    download_tools().remove(SPSC_KIT)
                if latest_version:
                    settings.setSetting('sopcast_version',
                                        value=latest_version)
                return
            else:
                generic = True
        elif os.uname()[4] == "i386" or os.uname()[4] == "i686":
            generic = False
            if settings.getSetting('openeleci386') == "true":
                SPSC_KIT = os.path.join(addonpath,
                                        openelecxi386_sopcast.split("/")[-1])
                download_tools().Downloader(openelecxi386_sopcast, SPSC_KIT,
                                            translate(30076), translate(30000))
                if tarfile.is_tarfile(SPSC_KIT):
                    download_tools().extract(SPSC_KIT, pastaperfil)
                    xbmc.sleep(500)
                    download_tools().remove(SPSC_KIT)
                if latest_version:
                    settings.setSetting('sopcast_version',
                                        value=latest_version)
                return
            else:
                generic = True
        if generic == True:
            print "++++++++++++++++ generic sopcast install"
            SPSC_KIT = os.path.join(addonpath,
                                    sopcast_linux_generic.split("/")[-1])
            xbmc.log("download  crap path: " + SPSC_KIT)
            download_tools().Downloader(sopcast_linux_generic, SPSC_KIT,
                                        translate(30076), translate(30000))
            if tarfile.is_tarfile(SPSC_KIT):
                path_libraries = os.path.join(pastaperfil, "sopcast")
                download_tools().extract(SPSC_KIT, path_libraries)
                print "++++++++++++++ downloading"
                xbmc.sleep(500)
                download_tools().remove(SPSC_KIT)
            else:
                print "++++++++++++++ it isn't a tarfile fuuuuuck"
            #set every single file from the bundle as executable
            path_libraries = os.path.join(pastaperfil, "sopcast")
            dirs, files = xbmcvfs.listdir(path_libraries)
            for ficheiro in files:
                binary_path = os.path.join(path_libraries, ficheiro)
                st = os.stat(binary_path)
                import stat
                os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
            path_libraries = os.path.join(path_libraries, "lib")
            dirs, files = xbmcvfs.listdir(path_libraries)
            for ficheiro in files:
                binary_path = os.path.join(path_libraries, ficheiro)
                st = os.stat(binary_path)
                import stat
                os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
            if latest_version:
                settings.setSetting('sopcast_version', value=latest_version)
            return

    elif xbmc.getCondVisibility('system.platform.windows'):
        print("Detected OS: Windows")
        if not xbmcvfs.exists(pastaperfil): xbmcvfs.mkdir(pastaperfil)
        #Sop
        import ctypes
        is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
        if is_admin == False:
            mensagemok(translate(30000), translate(30077), translate(30078))
        else:
            cmd = ['sc', 'delete', 'sopcastp2p']
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
            for line in proc.stdout:
                print("cmd out: " + line.rstrip())
            xbmc.sleep(1000)
            ret = mensagemprogresso.create(translate(30000), translate(30000))
            mensagemprogresso.update(0, translate(30117), "  ")
            xbmc.sleep(1000)
            import _winreg
            aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
            try:
                aKey = _winreg.OpenKey(aReg,
                                       r'SOFTWARE\SopCast\Player\InstallPath',
                                       0, _winreg.KEY_READ)
                name, value, type = _winreg.EnumValue(aKey, 0)
                sopcast_executable = value
                print("Installation executable of sopcast was found: " +
                      sopcast_executable)
                _winreg.CloseKey(aKey)
                mensagemprogresso.update(10, translate(30079),
                                         translate(30080))
            except:
                sopcast_executable = ""
                mensagemok(translate(30000), translate(30081),
                           translate(30082))
            if not sopcast_executable: pass
            else:
                xbmc.sleep(1000)
                mensagemprogresso.update(20, translate(30083), "  ")
                xbmc.sleep(1000)
                print("Getting windows users IDS")
                aReg = _winreg.ConnectRegistry(None,
                                               _winreg.HKEY_LOCAL_MACHINE)
                aKey = _winreg.OpenKey(
                    aReg,
                    r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
                )
                users = []
                for i in range(1024):
                    try:
                        asubkey = _winreg.EnumKey(aKey, i)
                        print(asubkey)
                        aKeydois = _winreg.OpenKey(
                            aReg,
                            os.path.join(
                                'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList',
                                asubkey))
                        val = _winreg.QueryValueEx(aKeydois,
                                                   "ProfileImagePath")
                        try:
                            print(val[0])
                        except:
                            print(
                                "Notice: User with strange characters, print cmd ignored."
                            )
                        if "Windows" in val[0] or "%systemroot%" in val[0]:
                            pass
                        else:
                            users.append(asubkey)
                    except:
                        pass
                if not users:
                    mensagemok(translate(30000), translate(30084))
                else:
                    mensagemprogresso.update(30, translate(30085),
                                             translate(30080))
                    xbmc.sleep(200)
                    mensagemprogresso.update(30, translate(30086), "   ")
                    xbmc.sleep(1000)
                    print("System Users", users)
                    srvany_final_location = os.path.join(
                        sopcast_executable.replace("SopCast.exe", ""),
                        "srvany.exe")
                    srvany_download_location = os.path.join(
                        addonpath, "srvany.exe")
                    srvanytgz_download_location = os.path.join(
                        addonpath, "srvany.tar.gz")
                    download_tools().Downloader(srvany_executable,
                                                srvanytgz_download_location,
                                                translate(30087),
                                                translate(30000))
                    xbmc.sleep(1000)
                    if tarfile.is_tarfile(srvanytgz_download_location):
                        path_libraries = addonpath
                        download_tools().extract(srvanytgz_download_location,
                                                 path_libraries)
                        xbmcvfs.copy(srvany_download_location,
                                     srvany_final_location)
                        download_tools().remove(srvanytgz_download_location)
                        download_tools().remove(srvany_download_location)
                    xbmc.sleep(1000)
                    ret = mensagemprogresso.create(translate(30000),
                                                   translate(30000))
                    xbmc.sleep(200)
                    mensagemprogresso.update(35, translate(30088), "  ")
                    xbmc.sleep(1000)
                    cmd = [
                        'sc', 'create', 'sopcastp2p', 'binpath=',
                        os.path.join(
                            os.path.join(
                                sopcast_executable.replace("SopCast.exe", "")),
                            'srvany.exe')
                    ]
                    proc = subprocess.Popen(cmd,
                                            stdout=subprocess.PIPE,
                                            shell=True)
                    servicecreator = False
                    for line in proc.stdout:
                        print("cmd out: " + line.rstrip())
                        servicecreator = True
                    if servicecreator == False:
                        mensagemok(translate(30000), translate(30089))
                    else:
                        mensagemprogresso.update(40, translate(30088),
                                                 translate(30080))
                        xbmc.sleep(1000)
                        mensagemprogresso.update(45, translate(30090), "  ")
                        xbmc.sleep(1000)
                        print("Trying to modify regedit....")
                        try:
                            aReg = _winreg.ConnectRegistry(
                                None, _winreg.HKEY_LOCAL_MACHINE)
                            key = _winreg.CreateKey(
                                aReg,
                                r'SYSTEM\CurrentControlSet\Services\sopcastp2p\Parameters'
                            )
                            _winreg.SetValueEx(
                                key, 'AppDirectory', 0, _winreg.REG_SZ,
                                os.path.join(
                                    sopcast_executable.replace(
                                        "SopCast.exe", "")))
                            _winreg.SetValueEx(
                                key, 'Application', 0, _winreg.REG_SZ,
                                os.path.join(
                                    os.path.join(
                                        sopcast_executable.replace(
                                            "SopCast.exe", "")),
                                    "SopCast.exe"))
                            _winreg.SetValueEx(key, 'AppParameters', 0,
                                               _winreg.REG_SZ, "sop://")
                            mensagemprogresso.update(50, translate(30090),
                                                     translate(30080))
                            regedit = True
                        except:
                            mensagemok(translate(30000), translate(30091))
                            regedit = False
                        if regedit == False: pass
                        else:
                            xbmc.sleep(1000)
                            mensagemprogresso.update(50, translate(30092),
                                                     "   ")
                            cmd = ['sc', 'sdshow', 'sopcastp2p']
                            proc = subprocess.Popen(cmd,
                                                    stdout=subprocess.PIPE,
                                                    shell=True)
                            lines = []
                            for line in proc.stdout:
                                if line.rstrip() != "" and "(" in line.rstrip(
                                ):
                                    lines.append(line.rstrip())
                                else:
                                    pass
                            if len(lines) != 1:
                                mensagemok(translate(30000), translate(30093))
                            else:
                                linha_arr = []
                                for user in users:
                                    linha_arr.append('(A;;RPWPCR;;;' + user +
                                                     ')')
                                linha_add = ''
                                for linha in linha_arr:
                                    linha_add += linha
                                print("line piece to add: " + linha_add)
                                linha_final = lines[0].replace(
                                    "S:(", linha_add + "S:(")
                                print("Final line: " + linha_final)
                                permissions = False
                                xbmc.sleep(500)
                                mensagemprogresso.update(
                                    60, translate(30092), translate(30080))
                                xbmc.sleep(500)
                                mensagemprogresso.update(
                                    60, translate(30094), "   ")
                                cmd = [
                                    'sc', 'sdset', 'sopcastp2p', linha_final
                                ]
                                proc = subprocess.Popen(cmd,
                                                        stdout=subprocess.PIPE,
                                                        shell=True)
                                for line in proc.stdout:
                                    print(line.rstrip())
                                    permissions = True
                                if permissions == False:
                                    mensagemok(translate(30000),
                                               translate(30095))
                                else:
                                    mensagemprogresso.update(
                                        70, translate(30094), translate(30080))
                                    xbmc.sleep(1000)
                                    mensagemprogresso.update(
                                        70, translate(30096), "   ")
                                    print(
                                        "Trying to set sopcastp2p service regedit permissions..."
                                    )
                                    download_tools().Downloader(
                                        srvany_permissions,
                                        os.path.join(
                                            pastaperfil,
                                            "sopcastp2p-permissions.txt"),
                                        translate(30097), translate(30000))
                                    xbmc.sleep(500)
                                    ret = mensagemprogresso.create(
                                        translate(30000), translate(30000))
                                    xbmc.sleep(500)
                                    mensagemprogresso.update(
                                        80, translate(30098), "   ")
                                    xbmc.sleep(1000)
                                    cmd = [
                                        'regini',
                                        os.path.join(
                                            pastaperfil,
                                            "sopcastp2p-permissions.txt")
                                    ]
                                    proc = subprocess.Popen(
                                        cmd,
                                        stdout=subprocess.PIPE,
                                        shell=True)
                                    for line in proc.stdout:
                                        print(line.rstrip())
                                    mensagemprogresso.update(
                                        90, translate(30098), translate(30098))
                                    mensagemprogresso.update(
                                        100, translate(30099), "   ")
                                    xbmc.sleep(2000)
                                    mensagemprogresso.close()
                                    if latest_version:
                                        settings.setSetting(
                                            'sopcast_version',
                                            value=latest_version)
                                    return

    elif xbmc.getCondVisibility('System.Platform.OSX'):
        print("Detected OS: Mac OSX")
        available = False
        if os.uname()[-1] == "x86_64":
            mac_package = osx_x64_sopcast
            available = True
        elif os.uname()[-1] == "i386":
            mac_package = osx_i386_sopcast
            available = True
        else:
            available = False
        if available == True:
            if not os.path.exists(pastaperfil):
                xbmcvfs.mkdir(pastaperfil)
            MAC_KIT = os.path.join(addonpath, mac_package.split("/")[-1])
            download_tools().Downloader(mac_package, MAC_KIT, translate(30076),
                                        translate(30000))
            if tarfile.is_tarfile(MAC_KIT):
                path_libraries = os.path.join(pastaperfil)
                download_tools().extract(MAC_KIT, pastaperfil)
                download_tools().remove(MAC_KIT)
                sp_sc_auth = os.path.join(pastaperfil, "sopcast", "sp-sc-auth")
                st = os.stat(sp_sc_auth)
                import stat
                os.chmod(sp_sc_auth, st.st_mode | stat.S_IEXEC)
            if latest_version:
                settings.setSetting('sopcast_version', value=latest_version)
            return
        else:
            mensagemok(translate(30000), translate(30100))
            return

    elif xbmc.getCondVisibility('System.Platform.Android'):

        print("Detected OS: Android")
        #Sopcast configuration
        print("Starting SopCast Configuration")

        #Moving sopclient to ext4 hack - tks steeve from xbmctorrent

        sopclient_builtin_location = os.path.join(addonpath, "resources",
                                                  "binaries", "sopclient")

        #Hack to get current xbmc app id
        xbmcfolder = xbmc.translatePath(addonpath).split("/")

        found = False
        if settings.getSetting('auto_appid') == 'true':
            i = 0
            sopcast_installed = False
            for folder in xbmcfolder:
                if folder.count('.') >= 2 and folder != addon_id:
                    found = True
                    break
                else:
                    i += 1
            if found == True:
                uid = os.getuid()
                app_id = xbmcfolder[i]
        else:
            if settings.getSetting('custom_appid') != '':
                uid = os.getuid()
                app_id = settings.getSetting('custom_appid')
                found = True

        if found == True:
            xbmc_data_path = os.path.join("/data", "data", app_id)

            if os.path.exists(xbmc_data_path) and uid == os.stat(
                    xbmc_data_path).st_uid:
                android_binary_dir = os.path.join(xbmc_data_path, "files",
                                                  "program.plexus")
                if not os.path.exists(android_binary_dir):
                    os.makedirs(android_binary_dir)
                android_binary_path = os.path.join(android_binary_dir,
                                                   "sopclient")
                if not os.path.exists(android_binary_path) or os.path.getsize(
                        android_binary_path) != os.path.getsize(
                            sopclient_builtin_location):
                    shutil.copy2(sopclient_builtin_location,
                                 android_binary_path)
                binary_path = android_binary_path
                st = os.stat(binary_path)
                import stat
                os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
                settings.setSetting('android_sopclient', value=binary_path)
                opcao = xbmcgui.Dialog().yesno(translate(30000),
                                               translate(30101),
                                               translate(30103))
                if not opcao:
                    settings.setSetting('external-sopcast', value='1')
                    sopcast_installed = True
                    mensagemok(translate(30000), translate(30099))
                else:
                    mensagemok(translate(30000), translate(30104))
                    if os.path.exists(os.path.join("sdcard", "Download")):
                        pasta = os.path.join("sdcard", "Download")
                        sopfile = os.path.join("sdcard", "Download",
                                               sopcast_apk.split("/")[-1])
                    else:
                        dialog = xbmcgui.Dialog()
                        pasta = dialog.browse(int(0), translate(30105),
                                              'videos')
                        sopfile = os.path.join(pasta,
                                               sopcast_apk.split("/")[-1])
                    download_tools().Downloader(sopcast_apk, sopfile,
                                                translate(30106),
                                                translate(30000))
                    if tarfile.is_tarfile(sopfile):
                        download_tools().extract(sopfile, pasta)
                        download_tools().remove(sopfile)
                    mensagemok(translate(30000), translate(30107), pasta,
                               translate(30108))
                    sopcast_installed = True
                    settings.setSetting('external-sopcast', value='0')
                    mensagemok(translate(30000), translate(30099))
                if latest_version:
                    settings.setSetting('sopcast_version',
                                        value=latest_version)
                return

        else:
            mensagemok(translate(30000), translate(30109))
            return
Example #17
0
def gather_msvc_versions(conf, versions):
    try:
        ce_sdk = _winreg.OpenKey(
            _winreg.HKEY_LOCAL_MACHINE,
            'SOFTWARE\\Wow6432node\\Microsoft\\Windows CE Tools\\SDKs')
    except WindowsError:
        try:
            ce_sdk = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                'SOFTWARE\\Microsoft\\Windows CE Tools\\SDKs')
        except WindowsError:
            ce_sdk = ''
    if ce_sdk:
        supported_wince_platforms = []
        ce_index = 0
        while 1:
            try:
                sdk_device = _winreg.EnumKey(ce_sdk, ce_index)
            except WindowsError:
                break
            ce_index = ce_index + 1
            sdk = _winreg.OpenKey(ce_sdk, sdk_device)
            path, type = _winreg.QueryValueEx(sdk, 'SDKRootDir')
            path = str(path)
            path, device = os.path.split(path)
            if not device:
                path, device = os.path.split(path)
            for arch, compiler in all_wince_platforms:
                platforms = []
                if os.path.isdir(os.path.join(path, device, 'Lib', arch)):
                    platforms.append((arch, compiler,
                                      os.path.join(path, device, 'Include',
                                                   arch),
                                      os.path.join(path, device, 'Lib', arch)))
                if platforms:
                    supported_wince_platforms.append((device, platforms))
    version_pattern = re.compile('^..?\...?')
    for vcver, vcvar in [('VCExpress', 'exp'), ('VisualStudio', '')]:
        try:
            all_versions = _winreg.OpenKey(
                _winreg.HKEY_LOCAL_MACHINE,
                'SOFTWARE\\Wow6432node\\Microsoft\\' + vcver)
        except WindowsError:
            try:
                all_versions = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                               'SOFTWARE\\Microsoft\\' + vcver)
            except WindowsError:
                continue
        index = 0
        while 1:
            try:
                version = _winreg.EnumKey(all_versions, index)
            except WindowsError:
                break
            index = index + 1
            if not version_pattern.match(version):
                continue
            try:
                msvc_version = _winreg.OpenKey(all_versions,
                                               version + "\\Setup\\VS")
                path, type = _winreg.QueryValueEx(msvc_version, 'ProductDir')
                path = str(path)
                targets = []
                if ce_sdk:
                    for device, platforms in supported_wince_platforms:
                        cetargets = []
                        for platform, compiler, include, lib in platforms:
                            winCEpath = os.path.join(path, 'VC', 'ce')
                            if os.path.isdir(winCEpath):
                                common_bindirs, _1, _2 = conf.get_msvc_version(
                                    'msvc', version, 'x86',
                                    os.path.join(path, 'Common7', 'Tools',
                                                 'vsvars32.bat'))
                                if os.path.isdir(
                                        os.path.join(winCEpath, 'lib',
                                                     platform)):
                                    bindirs = [
                                        os.path.join(winCEpath, 'bin',
                                                     compiler),
                                        os.path.join(winCEpath, 'bin',
                                                     'x86_' + compiler)
                                    ] + common_bindirs
                                    incdirs = [
                                        include,
                                        os.path.join(winCEpath, 'include'),
                                        os.path.join(winCEpath, 'atlmfc',
                                                     'include')
                                    ]
                                    libdirs = [
                                        lib,
                                        os.path.join(winCEpath, 'lib',
                                                     platform),
                                        os.path.join(winCEpath, 'atlmfc',
                                                     'lib', platform)
                                    ]
                                    cetargets.append(
                                        (platform, (platform,
                                                    (bindirs, incdirs,
                                                     libdirs))))
                        versions.append((device + ' ' + version, cetargets))
                if os.path.isfile(os.path.join(path, 'VC', 'vcvarsall.bat')):
                    for target, realtarget in all_msvc_platforms[::-1]:
                        try:
                            targets.append(
                                (target,
                                 (realtarget,
                                  conf.get_msvc_version(
                                      'msvc', version, target,
                                      os.path.join(path, 'VC',
                                                   'vcvarsall.bat')))))
                        except:
                            pass
                elif os.path.isfile(
                        os.path.join(path, 'Common7', 'Tools',
                                     'vsvars32.bat')):
                    try:
                        targets.append(
                            ('x86', ('x86',
                                     conf.get_msvc_version(
                                         'msvc', version, 'x86',
                                         os.path.join(path, 'Common7', 'Tools',
                                                      'vsvars32.bat')))))
                    except Configure.ConfigurationError:
                        pass
                versions.append(('msvc ' + version, targets))
            except WindowsError:
                continue
Example #18
0
        else:
            return True

    def get_credentials(self):
        try:
            key = OpenKey(HKEY_CURRENT_USER,
                          'Software\Martin Prikryl\WinSCP 2\Sessions')
        except Exception, e:
            print_debug('DEBUG', str(e))
            return False

        pwdFound = []
        num_profiles = _winreg.QueryInfoKey(key)[0]
        for n in range(num_profiles):
            name_skey = _winreg.EnumKey(
                key, n
            )  # with win32api.RegEnumKey => color is present / with _winreg.EnumKey not wtf ????

            skey = OpenKey(key, name_skey)
            num = _winreg.QueryInfoKey(skey)[1]

            port = ''
            values = {}

            for nn in range(num):
                k = _winreg.EnumValue(skey, nn)

                if k[0] == 'HostName':
                    self.hostname = k[1]

                if k[0] == 'UserName':
Example #19
0
#This program will read the USB logs from Windows and Linux System
import os
import _winreg

#Detecting System type first

if (os.name=='nt'):
    print "===Dumping Information of USB connected to this Devices==="
    #Getting details of USB from registry
    query = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Enum\USBSTOR', 0)
    i = 0
    try:
        while True:
            print _winreg.EnumKey(query, i)
            i += 1

    except WindowsError:
        print("\n\n")
        pass

elif(os.name=='posix'):
    usb_logs = open("/var/log/messages", "r")
    for line in usb_logs.readlines():
        if ("usb" or "USB") in line:
            print line,
    usb_logs.close()
Example #20
0
def RegistryResolve():
    nameservers = []
    x = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
    try:
        y = _winreg.OpenKey(
            x, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters")
    except EnvironmentError:  # so it isn't NT/2000/XP
        # windows ME, perhaps?
        try:  # for Windows ME
            y = _winreg.OpenKey(
                x, r"SYSTEM\CurrentControlSet\Services\VxD\MSTCP")
            nameserver, dummytype = _winreg.QueryValueEx(y, 'NameServer')
            if nameserver and not (nameserver in nameservers):
                nameservers.extend(stringdisplay(nameserver))
        except EnvironmentError:
            pass
        return nameservers  # no idea
    try:
        nameserver = _winreg.QueryValueEx(y, "DhcpNameServer")[0].split()
    except:
        nameserver = _winreg.QueryValueEx(y, "NameServer")[0].split()
    if nameserver:
        nameservers = nameserver
    nameserver = _winreg.QueryValueEx(y, "NameServer")[0]
    _winreg.CloseKey(y)
    try:  # for win2000
        y = _winreg.OpenKey(
            x,
            r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DNSRegisteredAdapters"
        )
        for i in range(1000):
            try:
                n = _winreg.EnumKey(y, i)
                z = _winreg.OpenKey(y, n)
                dnscount, dnscounttype = _winreg.QueryValueEx(
                    z, 'DNSServerAddressCount')
                dnsvalues, dnsvaluestype = _winreg.QueryValueEx(
                    z, 'DNSServerAddresses')
                nameservers.extend(binipdisplay(dnsvalues))
                _winreg.CloseKey(z)
            except EnvironmentError:
                break
        _winreg.CloseKey(y)
    except EnvironmentError:
        pass
#
    try:  # for whistler
        y = _winreg.OpenKey(
            x,
            r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces")
        for i in range(1000):
            try:
                n = _winreg.EnumKey(y, i)
                z = _winreg.OpenKey(y, n)
                try:
                    nameserver, dummytype = _winreg.QueryValueEx(
                        z, 'NameServer')
                    if nameserver and not (nameserver in nameservers):
                        nameservers.extend(stringdisplay(nameserver))
                except EnvironmentError:
                    pass
                _winreg.CloseKey(z)
            except EnvironmentError:
                break
        _winreg.CloseKey(y)
    except EnvironmentError:
        #print "Key Interfaces not found, just do nothing"
        pass


#
    _winreg.CloseKey(x)
    return nameservers
Example #21
0
def GuessVisualStudioPath():
    defaultPath = r"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7" \
                  r"\IDE"
    defaultExecutable = "devenv.com"

    if not IsWindows():
        return defaultPath, defaultExecutable

    keyNamesAndExecutables = [
        # Pair for non-Express editions.
        (GetWindowsRegistryKeyName(r'Microsoft\VisualStudio'), 'devenv.com'),
        # Pair for 2012 Express edition.
        (GetWindowsRegistryKeyName(r'Microsoft\VSWinExpress'),
         'VSWinExpress.exe'),
        # Pair for pre-2012 Express editions.
        (GetWindowsRegistryKeyName(r'Microsoft\VCExpress'), 'VCExpress.exe')
    ]

    bestGuess = (0.0, (defaultPath, defaultExecutable))

    import _winreg
    for (keyName, executable) in keyNamesAndExecutables:
        try:
            key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyName)
        except WindowsError:
            # Can't find this key - moving on the next one.
            continue

        try:
            subkeyCounter = 0
            while True:
                try:
                    subkeyName = _winreg.EnumKey(key, subkeyCounter)
                    subkeyCounter += 1
                except WindowsError:
                    # Reached end of enumeration. Moving on the next key.
                    break

                match = re.match(r'^\d+\.\d+$', subkeyName)
                if match:
                    with _winreg.OpenKey(key, subkeyName) as subkey:
                        try:
                            (installDir, registrytype) = _winreg.QueryValueEx(
                                subkey, 'InstallDir')
                        except WindowsError:
                            # Can't find value under the key - continue to the next key.
                            continue
                        isExpress = executable != 'devenv.com'
                        if not isExpress and subkeyName == '14.0':
                            # Stop search since if we found non-Express VS2015 version
                            # installed, which is preferred version.
                            return installDir, executable
                        else:
                            version = float(subkeyName)
                            # We prefer higher version of Visual Studio and given equal
                            # version numbers we prefer non-Express edition.
                            if version > bestGuess[0]:
                                bestGuess = (version, (installDir, executable))
        finally:
            _winreg.CloseKey(key)
    return bestGuess[1]
Example #22
0
def enumerate_ftdi_ports_by_vid_pid(vid, pid):
    """Lists all the FTDI ports in the FTDIBUS
    registry entry with a given VID/PID pair.

    @param int vid: The Vendor ID
    @param int pid: The Product ID
    @return iterator: An iterator of information for each port with these VID/PID values
    """
    base = "SYSTEM\\CurrentControlSet\\Enum\\FTDIBUS\\"

    try:
        ftdibus = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, base)
    except WindowsError as e:
        logging.getLogger('list_ports_windows').debug('WindowsError: ' +
                                                      e.strerror)
        # If a WindowsError occurs there has never been an FTDI plugged in.
        # There's nothing to iterate, so we raise a StopIteration exception.
        raise StopIteration

    try:
        for index in itertools.count():
            ftdi_port = winreg.EnumKey(ftdibus, index)

            ftdi_data = ftdi_vid_pid_regex.match(ftdi_port)
            if None != ftdi_data:

                current_vid = ftdi_data.group(1)
                current_pid = ftdi_data.group(2)
                not_iSerial = ftdi_data.group(3)

                if (vid == None or vid == current_vid) and (pid == None or pid
                                                            == current_pid):
                    try:
                        device_params = winreg.OpenKey(
                            winreg.HKEY_LOCAL_MACHINE,
                            base + ftdi_port + '\\0000\\Device Parameters')
                        for param in itertools.count():
                            name, value, type = winreg.EnumValue(
                                device_params, param)
                            if 'PortName' == name:
                                port_name = value
                                break
                    except WindowsError as e:
                        logging.getLogger('list_ports_windows').error(
                            'WindowsError: ' + e.strerror)
                        # didn't find a portname? not sure if this is a
                        # problem, or if this will even ever happen.
                        continue

                    yield {
                        'VID': current_vid,
                        'PID': current_pid,
                        'iSerial': not_iSerial,
                        'PortName': port_name
                    }
            else:
                logging.getLogger('list_ports_windows').debug(
                    'FTDI does not match pattern.')

            index += 1
    except WindowsError as e:
        # the end of the FTDI list
        raise StopIteration
Example #23
0
    hkey = None
    try:
        hkey = _winreg.OpenKey(hive, parent_sub_key)
    except WindowsError, e:
        if e.winerror == 2:
            # 2 = 'file not found' happens when key does not exist
            return False
    if not really_delete:
        return True
    if not hkey:
        # key not found
        return False
    keys_size = _winreg.QueryInfoKey(hkey)[0]
    child_keys = []
    for i in range(keys_size):
        child_keys.append(parent_key + '\\' + _winreg.EnumKey(hkey, i))
    for child_key in child_keys:
        delete_registry_key(child_key, True)
    _winreg.DeleteKey(hive, parent_sub_key)
    return True


def delete_updates():
    """Returns commands for deleting Windows Updates files"""
    windir = os.path.expandvars('$windir')
    dirs = glob.glob(os.path.join(windir, '$NtUninstallKB*'))
    dirs += [os.path.expandvars('$windir\\SoftwareDistribution\\Download')]
    dirs += [os.path.expandvars('$windir\\ie7updates')]
    dirs += [os.path.expandvars('$windir\\ie8updates')]
    if not dirs:
        # if nothing to delete, then also do not restart service
Example #24
0
def autoconf():
	#Configuration for LINUX 
	if xbmc.getCondVisibility('system.platform.linux') and not xbmc.getCondVisibility('system.platform.Android') and not settings.getSetting('force_android') == "true":
		print("Detected OS: Linux")
		#Linux Armv6
		if os.uname()[4] == "armv6l":
			try:
				if re.search(os.uname()[1],"openelec",re.IGNORECASE): acestream_rpi = acestream_openelec_raspberry
				elif re.search(os.uname()[1],"raspbmc",re.IGNORECASE): acestream_rpi = acestream_generic_raspberry
				elif os.path.isfile("/etc/xbian_version"): acestream_rpi = acestream_generic_raspberry
				elif "ARCH" in os.uname()[2]:
					acestream_rpi = acestream_generic_raspberry
					settings.setSetting('python_cmd',value='python2')
				else:
					mensagemok(translate(40000),translate(400007),translate(400008))
					OS_list = ["OpenELEC","Raspbmc","Xbian","Pipplware","Arch Linux Arm"]
					url_packagerpi_list = [acestream_openelec_raspberry, acestream_generic_raspberry, acestream_generic_raspberry,acestream_generic_raspberry, acestream_generic_raspberry]
					OS_Rpi_choose = xbmcgui.Dialog().select
					choose=OS_Rpi_choose('Select your OS',OS_list)
					if choose > -1:
						acestream_rpi= url_packagerpi_list[choose]
						if OS_list[choose] == "Arch Linux Arm": settings.setSetting('python_cmd',value='python2')
			except: acestream_rpi = ""
			print("Detected linux armv6 - possible Raspberry PI")
			#Sop

			SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
			download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000))
			import tarfile            
			if tarfile.is_tarfile(SPSC_KIT):
				path_libraries = os.path.join(pastaperfil,"sopcast")
				download_tools().extract(SPSC_KIT,path_libraries)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)

            		#Ace
			SPSC_KIT = os.path.join(addonpath,acestream_rpi.split("/")[-1])
			download_tools().Downloader(acestream_rpi,SPSC_KIT,translate(40026),translate(40000))
        
			if tarfile.is_tarfile(SPSC_KIT):
				path_libraries = os.path.join(pastaperfil,"acestream")
				download_tools().extract(SPSC_KIT,path_libraries)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)

			settings.setSetting('autoconfig',value='false')


                elif os.uname()[4] == "armv7l":
			if re.search(os.uname()[1],"openelec",re.IGNORECASE):
				OS_Choose = "OpenELEC"
			elif os.path.isfile("/etc/xbian_version"):
				OS_Choose = "Xbian"
			else:
                		mensagemok(translate(40000),translate(40109),translate(40110))
                		OS_list = ["MXLinux","OpenELEC","Xbian"]
                		choose=xbmcgui.Dialog().select('Select your OS',OS_list)
                		if choose > -1:
                			OS_Choose= OS_list[choose]

			#Linux armv7 configuration according to platform

			#MXLINUX
                	if OS_Choose == "MXLinux":
				acestream_installed = False
				sopcast_installed = False
               			print("Detected MXLinux armv7")
               			SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
               			download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000))
               			import tarfile
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					sopcast_installed = True

				SPSC_KIT = os.path.join(addonpath,acestream_mxlinux.split("/")[-1])
				download_tools().Downloader(acestream_mxlinux,SPSC_KIT,translate(40026),translate(40000))
        			if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"acestream")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					acestream_installed = True
				if acestream_installed and sopcast_installed:
					settings.setSetting('autoconfig',value='false')	

			#OPENELEC

                	if OS_Choose == "OpenELEC":
                		import tarfile
				acestream_installed = False
				sopcast_installed = False
                		print("Openelec armv7 platform detected")
                		SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
                		download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000))
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					sopcast_installed = True
				SPSC_KIT = os.path.join(addonpath,acestream_armv7_openelec.split("/")[-1])
				download_tools().Downloader(acestream_armv7_openelec,SPSC_KIT,translate(40026),translate(40000))
        			if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"acestream")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					acestream_installed = True
				if acestream_installed and sopcast_installed:
					settings.setSetting('autoconfig',value='false')	

			#XBIAN
               		if OS_Choose == "Xbian":
               			import tarfile
				acestream_installed = False
				sopcast_installed = False
               			print("Xbian armv7 platform detected")
               			SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
               			download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(40025),translate(40000))
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					sopcast_installed = True
				SPSC_KIT = os.path.join(addonpath,acestream_armv7_xbian.split("/")[-1])
				download_tools().Downloader(acestream_armv7_xbian,SPSC_KIT,translate(40026),translate(40000))
       				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"acestream")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
					acestream_installed = True
				if acestream_installed and sopcast_installed:
					settings.setSetting('autoconfig',value='false')	


			
		elif (os.uname()[4] == "x86_64" and re.search(os.uname()[1],"openelec",re.IGNORECASE)) or settings.getSetting('openelecx86_64') == "true":
			settings.setSetting('openelecx86_64',value='true')
			print("Detected OpenELEC x86_64")
			SPSC_KIT = os.path.join(addonpath,openelecx86_64_package.split("/")[-1])
			download_tools().Downloader(openelecx86_64_package,SPSC_KIT,translate(40112),translate(40000))
			import tarfile
			if tarfile.is_tarfile(SPSC_KIT):
				download_tools().extract(SPSC_KIT,pastaperfil)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)
			settings.setSetting('autoconfig',value='false')

		elif (os.uname()[4] == "i386" and re.search(os.uname()[1],"openelec",re.IGNORECASE)) or (os.uname()[4] == "i686" and re.search(os.uname()[1],"openelec",re.IGNORECASE)) or settings.getSetting('openeleci386') == "true":
			settings.setSetting('openeleci386',value='true')
			print("Detected OpenELEC i386")
			SPSC_KIT = os.path.join(addonpath,openeleci386_package.split("/")[-1])
			download_tools().Downloader(openeleci386_package,SPSC_KIT,translate(40112),translate(40000))
			import tarfile
			if tarfile.is_tarfile(SPSC_KIT):
				download_tools().extract(SPSC_KIT,pastaperfil)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)
			settings.setSetting('autoconfig',value='false')		
	
		else:
			if os.uname()[4] == "x86_64":
				opcao= xbmcgui.Dialog().yesno(translate(40000), translate(40113))
				if opcao: 
					settings.setSetting('openelecx86_64',value='true')
					autoconf()
			elif os.uname()[4] == "i386" or os.uname()[4] == "i686":
				opcao= xbmcgui.Dialog().yesno(translate(40000), translate(600023))
				if opcao: 
					settings.setSetting('openeleci386',value='true')
					autoconf()

			else: mensagemok(translate(40000),translate(40056))
			

			#Linux but not openelec i386 nor openelec x86_64 - General Linux platforms configuration
			
			if settings.getSetting('openeleci386') == "false" and settings.getSetting('openelecx86_64') == "false":

				print("Detected Other Linux i386 Plataform")

            		#Sop
            		#Download and extract sopcast-bundle
				SPSC_KIT = os.path.join(addonpath,sopcast_linux_generico.split("/")[-1])
				download_tools().Downloader(sopcast_linux_generico,SPSC_KIT,translate(40025),translate(40000))
				import tarfile
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
				#set every single file from the bundle as executable
				path_libraries = os.path.join(pastaperfil,"sopcast")
				dirs, files = xbmcvfs.listdir(path_libraries)
				for ficheiro in files:
					binary_path = os.path.join(path_libraries,ficheiro)
					st = os.stat(binary_path)
					import stat
					os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
				path_libraries = os.path.join(path_libraries,"lib")
				dirs, files = xbmcvfs.listdir(path_libraries)
				for ficheiro in files:
					binary_path = os.path.join(path_libraries,ficheiro)
					st = os.stat(binary_path)
					import stat
					os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
	   		 
	   		 #Ace
	   		 
				if os.uname()[4] == "x86_64":
					ACE_KIT = os.path.join(addonpath,acestream_linux_x64_generic.split("/")[-1])
					download_tools().Downloader(acestream_linux_x64_generic,ACE_KIT,translate(40026),translate(40000))
					import tarfile
					if tarfile.is_tarfile(ACE_KIT):
						download_tools().extract(ACE_KIT,pastaperfil)
						xbmc.sleep(500)
						download_tools().remove(ACE_KIT)
				
					settings.setSetting('autoconfig',value='false')
					
				elif os.uname()[4] == "i386" or os.uname()[4] == "i686":
					ACE_KIT = os.path.join(addonpath,acestream_linux_i386_generic.split("/")[-1])
					download_tools().Downloader(acestream_linux_i386_generic,ACE_KIT,translate(40026),translate(40000))
					import tarfile
					if tarfile.is_tarfile(ACE_KIT):
						download_tools().extract(ACE_KIT,pastaperfil)
						xbmc.sleep(500)
						download_tools().remove(ACE_KIT)
				
					settings.setSetting('autoconfig',value='false')


	elif xbmc.getCondVisibility('system.platform.windows'):
		print("Detected OS: Windows")
		if not xbmcvfs.exists(pastaperfil): xbmcvfs.mkdir(pastaperfil)
        	#Sop
		import ctypes
                is_admin=ctypes.windll.shell32.IsUserAnAdmin() != 0
                if is_admin == False:
                    mensagemok(translate(40000),translate(40158),translate(40159))
                else:
		    import subprocess
                    cmd = ['sc','delete','sopcastp2p']
                    proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                    for line in proc.stdout:
                        print("cmd out: " + line.rstrip())
                    xbmc.sleep(1000)
                    ret = mensagemprogresso.create(translate(40000),translate(40000))
                    mensagemprogresso.update(0,translate(40160),"  ")
                    xbmc.sleep(1000)
                    import _winreg
                    aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                    try:
                        aKey = _winreg.OpenKey(aReg, r'SOFTWARE\SopCast\Player\InstallPath',0, _winreg.KEY_READ)
                        name, value, type = _winreg.EnumValue(aKey, 0)
                        sopcast_executable = value
                        print("Installation executable of sopcast was found: " + sopcast_executable)
                        _winreg.CloseKey(aKey)
                        mensagemprogresso.update(10,translate(40160),translate(40161))
                    except:
                        sopcast_executable = ""
                        mensagemok(translate(40000),translate(40162),translate(40163))
                    if not sopcast_executable: pass
                    else:
                        xbmc.sleep(1000)
                        mensagemprogresso.update(20,translate(40164),"  ")
                        xbmc.sleep(1000)
                        print ("Getting windows users IDS")
                        aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                        aKey = _winreg.OpenKey(aReg, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList')
                        users = []
                        for i in range(1024):
                            try:
                                asubkey=_winreg.EnumKey(aKey,i)
                                print(asubkey)
                                aKeydois = _winreg.OpenKey(aReg, os.path.join('SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList',asubkey))
                                val=_winreg.QueryValueEx(aKeydois, "ProfileImagePath")
                                try:
                                    print(val[0])
                                except:
                                    print("Notice: User with strange characters, print cmd ignored.")
                                if "Windows" in val[0] or "%systemroot%" in val[0]:
                                    pass
                                else:
                                    users.append(asubkey)
                            except:
                                pass
                        if not users:
                            mensagemok(translate(40000),translate(40165))
                        else:
                            mensagemprogresso.update(30,translate(40164),translate(40161))
                            xbmc.sleep(200)
                            mensagemprogresso.update(30,translate(40166),"   ")
                            xbmc.sleep(1000)
                            print("System Users", users)
                            srvany_final_location = os.path.join(sopcast_executable.replace("SopCast.exe",""),"srvany.exe")
                            srvany_download_location = os.path.join(addonpath,"srvany.exe")
                            srvanytgz_download_location = os.path.join(addonpath,"srvany.tar.gz")                            
                            download_tools().Downloader(srvany_executable,srvanytgz_download_location,translate(40167),translate(40000)) 
                            xbmc.sleep(1000)
                            import tarfile
                            if tarfile.is_tarfile(srvanytgz_download_location):
                                path_libraries = addonpath
                                download_tools().extract(srvanytgz_download_location,path_libraries)
                                xbmcvfs.copy(srvany_download_location,srvany_final_location)
                                download_tools().remove(srvanytgz_download_location)
                                download_tools().remove(srvany_download_location)
                            xbmc.sleep(1000)
                            ret = mensagemprogresso.create(translate(40000),translate(40000))
                            xbmc.sleep(200)
                            mensagemprogresso.update(35,translate(40168),"  ")
                            xbmc.sleep(1000)
                            import subprocess
                            cmd = ['sc','create','sopcastp2p','binpath=',os.path.join(os.path.join(sopcast_executable.replace("SopCast.exe","")),'srvany.exe')]
                            proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                            servicecreator = False
                            for line in proc.stdout:
                                print ("cmd out: " + line.rstrip())
                                servicecreator = True
                            if servicecreator == False:
                                mensagemok(translate(40000),translate(40169))
                            else:
                                mensagemprogresso.update(40,translate(40168),translate(40161))
                                xbmc.sleep(1000)
                                mensagemprogresso.update(45,translate(40170),"  ")
                                xbmc.sleep(1000)
                                print("Trying to modify regedit....")
                                try:
                                    aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                                    key = _winreg.CreateKey(aReg, r'SYSTEM\CurrentControlSet\Services\sopcastp2p\Parameters')
                                    _winreg.SetValueEx(key, 'AppDirectory', 0, _winreg.REG_SZ, os.path.join(sopcast_executable.replace("SopCast.exe","")))
                                    _winreg.SetValueEx(key, 'Application', 0, _winreg.REG_SZ, os.path.join(os.path.join(sopcast_executable.replace("SopCast.exe","")),"SopCast.exe"))
                                    _winreg.SetValueEx(key, 'AppParameters', 0, _winreg.REG_SZ, "sop://")
                                    mensagemprogresso.update(50,translate(40170), translate(40161))
                                    regedit = True
                                except:
                                    mensagemok(translate(40000),translate(40171))
                                    regedit = False
                                if regedit == False: pass
                                else:
                                    xbmc.sleep(1000)
                                    mensagemprogresso.update(50,translate(40172), "   ")
                                    cmd = ['sc','sdshow','sopcastp2p']
                                    proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                    lines = []
                                    for line in proc.stdout:
					print(line.rstrip())
                                        if line.rstrip() != "" and "(" in line.rstrip(): lines.append(line.rstrip())
                                        else: pass
                                    if len(lines) != 1: mensagemok(translate(40000),translate(40173))
                                    else:
                                        linha_arr = []
                                        for user in users:
                                            linha_arr.append('(A;;RPWPCR;;;' + user + ')')
                                        linha_add = ''
                                        for linha in linha_arr:
                                            linha_add += linha
                                        print("line peace to add: " + linha_add)
                                        linha_final = lines[0].replace("S:(",linha_add + "S:(")
                                        print("Final line: " + linha_final)
                                        permissions = False
                                        xbmc.sleep(500)
                                        mensagemprogresso.update(60,translate(40172), translate(40161))
                                        xbmc.sleep(500)
                                        mensagemprogresso.update(60,translate(40174), "   ")
                                        cmd = ['sc','sdset','sopcastp2p',linha_final]
                                        proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                        for line in proc.stdout:
                                            print(line.rstrip())
                                            permissions = True
                                        if permissions == False: mensagemok(translate(40000),translate(40175))
                                        else:
                                            mensagemprogresso.update(70,translate(40174), translate(40161))
                                            xbmc.sleep(1000)
                                            mensagemprogresso.update(70,translate(40176), "   ")
                                            print("Trying to set sopcastp2p service regedit permissions...")
                                            download_tools().Downloader(srvany_permissions,os.path.join(pastaperfil,"sopcastp2p-permissions.txt"),translate(40177),translate(40000))
                                            xbmc.sleep(500)
                                            ret = mensagemprogresso.create(translate(40000),translate(40000))
                                            xbmc.sleep(500)
                                            mensagemprogresso.update(80,translate(40178), "   ")
                                            xbmc.sleep(1000)
                                            cmd = ['regini',os.path.join(pastaperfil,"sopcastp2p-permissions.txt")]
                                            proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                            for line in proc.stdout:
                                                print(line.rstrip())
                                            mensagemprogresso.update(90,translate(40178), translate(40178))
                                            mensagemprogresso.update(100,translate(40179), "   ")
                                            xbmc.sleep(2000)
                                            mensagemprogresso.close()
        #Ace
		SPSC_KIT = os.path.join(addonpath,acestream_windows.split("/")[-1])
		download_tools().Downloader(acestream_windows,SPSC_KIT,translate(40026),translate(40000))
		import shutil
		if xbmcvfs.exists(os.path.join(pastaperfil,"acestream")):
			shutil.rmtree(os.path.join(pastaperfil,"acestream"))
		if xbmcvfs.exists(os.path.join(pastaperfil,"player")):
			shutil.rmtree(os.path.join(pastaperfil,"player"))
		import tarfile
		if tarfile.is_tarfile(SPSC_KIT):
			path_libraries = os.path.join(pastaperfil)
			download_tools().extract(SPSC_KIT,path_libraries)
			download_tools().remove(SPSC_KIT)
		settings.setSetting('autoconfig',value='false')
    
	elif xbmc.getCondVisibility('System.Platform.OSX'):
		print("Detected OS: Mac OSX")
		available = False
		if os.uname()[-1] == "x86_64":
			mac_package = osx_x86_64
			available = True
		elif os.uname()[-1] == "i386":
			mac_package = osx_i386
			available = True
		else:
			available = False
		if available == True:		
			if not xbmcvfs.exists(pastaperfil):
				xbmcvfs.mkdir(pastaperfil)		
			MAC_KIT = os.path.join(addonpath,mac_package.split("/")[-1])
			download_tools().Downloader(mac_package,MAC_KIT,translate(40112),translate(40000))
			import tarfile
			if tarfile.is_tarfile(MAC_KIT):
				path_libraries = os.path.join(pastaperfil)
				download_tools().extract(MAC_KIT,pastaperfil)
				download_tools().remove(MAC_KIT)
				sp_sc_auth = os.path.join(pastaperfil,"sopcast","sp-sc-auth")
				st = os.stat(sp_sc_auth)
				import stat
				os.chmod(sp_sc_auth, st.st_mode | stat.S_IEXEC)
				settings.setSetting('autoconfig',value='false')
		else:
			mensagemok(translate(40000),translate(600014))
			sys.exit(0)
				
	elif xbmc.getCondVisibility('System.Platform.Android') or settings.getSetting('force_android') == "true":

		print("Detected OS: Android")
		#Sopcast configuration
		print("Starting SopCast Configuration")

		#Moving sopclient to ext4 hack - tks steeve from xbmctorrent

		sopclient_builtin_location = os.path.join(addonpath,"resources","binaries","sopclient")

		#Hack to get current xbmc app id
		xbmcfolder=xbmc.translatePath(addonpath).split("/")

		i = 0
		found = False
		sopcast_installed = False
		
		for folder in xbmcfolder:
			if folder.count('.') >= 2 and folder != addon_id :
				found = True
				break
			else:
				i+=1

		if found == True:
			uid = os.getuid()
			app_id = xbmcfolder[i]
			xbmc_data_path = os.path.join("/data", "data", app_id)
			if os.path.exists(xbmc_data_path) and uid == os.stat(xbmc_data_path).st_uid:
				android_binary_dir = os.path.join(xbmc_data_path, "files", "plugin.video.p2p-streams")
				if not os.path.exists(android_binary_dir):
            				os.makedirs(android_binary_dir)
				android_binary_path = os.path.join(android_binary_dir, "sopclient")
		        	if not os.path.exists(android_binary_path) or os.path.getsize(android_binary_path) != os.path.getsize(sopclient_builtin_location):
					import shutil
					shutil.copy2(sopclient_builtin_location, android_binary_path)
				binary_path = android_binary_path
				st = os.stat(binary_path)
				import stat
				os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
				settings.setSetting('android_sopclient',value=binary_path)
				opcao= xbmcgui.Dialog().yesno(translate(40000), translate(50011),translate(50012))
				if not opcao:
					settings.setSetting('external_sopcast',value='1')
					settings.setSetting('force_android',value='true')
					sopcast_installed = True
					mensagemok(translate(40000),translate(50014))
				else:
					mensagemok(translate(40000),translate(50013))
					if xbmcvfs.exists(os.path.join("sdcard","Download")):
						pasta = os.path.join("sdcard","Download")
						sopfile = os.path.join("sdcard","Download",sopcast_apk.split("/")[-1])
					else:
						dialog = xbmcgui.Dialog()
						pasta = dialog.browse(int(0), translate(40190), 'myprograms')
						sopfile = os.path.join(pasta,sopcast_apk.split("/")[-1])
					download_tools().Downloader(sopcast_apk,sopfile,translate(40073),translate(40000))
					import tarfile
					if tarfile.is_tarfile(sopfile):
						download_tools().extract(sopfile,pasta)
						download_tools().remove(sopfile)
					mensagemok(translate(40000),translate(50015),pasta,translate(50016))
					sopcast_installed = True
					settings.setSetting('external_sopcast',value='0')
					mensagemok(translate(40000),translate(50014))

		else:
			mensagemok(translate(40000),translate(50017))

		#acestream config for android

		if sopcast_installed == True:
			mensagemok(translate(40000),translate(50018),translate(50019),translate(50020))
			if xbmcvfs.exists(os.path.join("sdcard","Download")):
				pasta = os.path.join("sdcard","Download")
				acefile = os.path.join("sdcard","Download",acestreamengine_apk.split("/")[-1])
			else:
				dialog = xbmcgui.Dialog()
				pasta = dialog.browse(int(0), translate(40190), 'myprograms')
				acefile = os.path.join(pasta,acestreamengine_apk.split("/")[-1])
			download_tools().Downloader(acestreamengine_apk,acefile,translate(40072),translate(40000))
			import tarfile
			if tarfile.is_tarfile(acefile):
				download_tools().extract(acefile,pasta)
				download_tools().remove(acefile)
			xbmc.sleep(2000)
			mensagemok(translate(40000),translate(50021),pasta,translate(50016))
			mensagemok(translate(40000),translate(50022))
			mensagemok(translate(40000),translate(50023),translate(50024),translate(50025))
			settings.setSetting('autoconfig',value='false')