Beispiel #1
0
    def load_blocks_in_file(self, filePath, fileName):

        log_utils.debug("begin load blocks in file:" + filePath)

        if fileName == "public.xml":
            block = ResourceBlock.create_single_block_with_type(
                ResourceBlock.RES_VAL_PUBLIC, filePath, self.librayName)
            self.entries[block.fullname()] = block
            return

        tree = ET.parse(filePath)
        root = tree.getroot()
        for node in list(root):
            resType = node.tag
            resName = node.attrib.get('name')
            typeAlias = node.attrib.get('type')
            format = node.attrib.get('format')
            if typeAlias != None:
                resType = typeAlias

            if resName == None or len(resName) == 0:
                # maybe eat-comment
                continue

            block = ResourceBlock.create_value_block_with_format(
                resType, filePath, resName, self.librayName, format)

            fullName = block.fullname()

            if fullName in self.entries:
                log_utils.warning(
                    "value resource %s duplicated in same sub folder. in %s and %s",
                    resName, filePath, self.entries[fullName].path())
                # raise RuntimeError("value resource duplicated in same res sub folder")  #aapt can ignore this if there are with same values. so just ignore here.
                # wait to delete
                self.deleteableBlocks.append(block)
            else:
                self.entries[fullName] = block

                # load all children of styleable
                if block.is_styleable():
                    children = node.findall('attr')
                    if children != None and len(children) > 0:
                        for attrNode in children:
                            attrName = attrNode.attrib.get('name')
                            attrFormat = attrNode.attrib.get('format')
                            if attrFormat == None or len(attrFormat) == 0:
                                # enum or flag
                                attrChildren = list(attrNode)

                                if attrChildren != None and len(
                                        attrChildren) > 0:
                                    for attrCNode in attrChildren:
                                        attrFormat = attrCNode.tag
                                        break

                            attrBlock = ResourceBlock.create_value_block_with_format(
                                ResourceBlock.RES_VAL_ATTR, filePath, attrName,
                                self.librayName, attrFormat)
                            block.add_child(attrBlock)
Beispiel #2
0
def merge(manifestFiles):

    if manifestFiles == None or len(manifestFiles) == 0:
        return True

    manifests = list()
    for manifest in manifestFiles:
        if os.path.exists(manifest):
            m = ManifestFile.create(manifest)
            manifests.append(m)
        else:
            log_utils.warning("manifest file not exists. just igore. " +
                              manifest)

    if len(manifests) <= 1:
        log_utils.debug("manifest file no need to merge")
        return True

    baseManifest = manifests.pop(len(manifests) - 1)

    for manifest in manifests:

        if not manifest.can_merge_to(baseManifest):
            log_utils.error("manifest merge failed. %s and %s  has same node.",
                            manifest.path(), baseManifest.path())
            return False

        ret = baseManifest.merge_with(manifest)

        if not ret:

            return False

    return True
Beispiel #3
0
def get_all_use_permissions(manifestFile):
    if not os.path.exists(manifestFile):
        log_utils.debug("the manifest file not exists:" + manifestFile)
        return None

    ET.register_namespace('android', androidNS)
    key = '{' + androidNS + '}name'

    tree = ET.parse(manifestFile)
    root = tree.getroot()

    key = '{' + androidNS + '}name'
    nodes = root.findall('uses-permission')

    if nodes == None or len(nodes) == 0:
        log_utils.warning("there is no uses-permission in " + manifestFile)
        return None

    permissions = []
    for node in nodes:

        name = node.get(key)

        if name not in permissions:
            permissions.append(name)
        else:
            log_utils.warning("ignore permission. node " + name +
                              " duplicated in " + manifestFile)

    return permissions
Beispiel #4
0
def copy_files(src,
               dest,
               ignoredExt=None,
               ignoredFiles=None,
               overrideable=True):
    if not os.path.exists(src):
        log_utils.warning("the path is not exists.path:%s", src)
        return

    filename = os.path.basename(src)
    if ignoredFiles != None and filename in ignoredFiles:
        return

    if os.path.isfile(src):
        copy_file(src, dest, ignoredExt, ignoredFiles, overrideable)
        return

    for f in os.listdir(src):
        sourcefile = os.path.join(src, f)
        targetfile = os.path.join(dest, f)
        if os.path.isfile(sourcefile):
            copy_file(sourcefile, targetfile, ignoredExt, ignoredFiles,
                      overrideable)
        else:
            copy_files(sourcefile, targetfile, ignoredExt, ignoredFiles,
                       overrideable)
Beispiel #5
0
def copy_file(src,
              dest,
              ignoredExt=None,
              ignoredFiles=None,
              overrideable=True):
    sourcefile = getFullPath(src)
    destfile = getFullPath(dest)
    if not os.path.exists(sourcefile):
        return

    if (not overrideable) and os.path.exists(destfile):
        log_utils.warning("file copy failed. target file already exists. " +
                          destfile)
        return

    fileName = os.path.basename(src)

    if ignoredFiles != None and fileName in ignoredFiles:
        return

    (baseName, ext) = os.path.splitext(fileName)

    if ext != None and ignoredExt != None and ext in ignoredExt:
        return

    destdir = os.path.dirname(destfile)
    if not os.path.exists(destdir):
        os.makedirs(destdir)

    shutil.copy(src, dest)
Beispiel #6
0
def jar2dex(srcDir, dstDir, dextool="dx.jar"):
    """
        compile jar files to dex.
    """

    dexToolPath = file_utils.getFullToolPath("/lib/dx.jar")
    heapSize = config_utils.get_jvm_heap_size()
    cmd = file_utils.getJavaCMD() + ' -jar -Xms%sm -Xmx%sm "%s" --dex --multi-dex --output="%s" ' % (
        heapSize, heapSize, dexToolPath, dstDir)

    num = 0

    for f in os.listdir(srcDir):
        if f.endswith(".jar"):
            num = num + 1
            cmd = cmd + " " + os.path.join(srcDir, f)

    libsPath = os.path.join(srcDir, "libs")
    if os.path.exists(libsPath):

        for f in os.listdir(libsPath):
            if (not f.startswith(".")) and f.endswith(".jar"):
                num = num + 1
                cmd = cmd + " " + os.path.join(srcDir, "libs", f)

    if num == 0:
        # no jar
        log_utils.warning("no need to do jar2dex. there is no jars in " + srcDir)
        return True

    return file_utils.exec_cmd(cmd)
Beispiel #7
0
    def merge_jni(self, targetLibs):

        if not os.path.exists(self.aarDir):
            log_utils.warning("the aar is not unarchived:" + self.aarFile)
            return False

        jniPath = os.path.join(self.aarDir, "jni")

        if not os.path.exists(jniPath):
            log_utils.debug(
                "aar jni merge completed. there is no jni folder in " +
                self.aarFile)
            return True

        for f in os.listdir(jniPath):

            cpuPath = os.path.join(jniPath, f)

            for c in os.listdir(cpuPath):
                cpuTargetPath = os.path.join(targetLibs, f, c)
                if os.path.exists(cpuTargetPath):
                    log_utils.error("jni in aar " + self.aarFile +
                                    " merge failed. " + c +
                                    " already exists in " + targetLibs)
                    return False

                file_utils.copy_file(os.path.join(cpuPath, c), cpuTargetPath)
                log_utils.debug(f + "/" + c + " in aar " + self.aarFile +
                                " copied to " + targetLibs)

        return True
Beispiel #8
0
def parse_version_info(ymlPath):
    """
        parse versionCode and versionName in apktool.yml
    """

    if not os.path.exists(ymlPath):
        log_utils.warning("the apktool.yml is not exists " + ymlPath)
        return ("0", "1.0.0")

    ymlFile = open(ymlPath, 'r')
    lines = ymlFile.readlines()
    ymlFile.close()

    versionCode = "0"
    versionName = "1.0.0"

    for line in lines:
        if 'versionCode' in line:
            versionCode = line.replace('versionCode:',
                                       '').strip().replace("'", "")

        elif 'versionName' in line:
            versionName = line.replace('versionName:',
                                       '').strip().replace("'", "")

    return (versionCode, versionName)
Beispiel #9
0
    def merge_res(self, targetRes):

        if not os.path.exists(self.aarDir):
            log_utils.warning("the aar is not unarchived:" + self.aarFile)
            return False

        resPath = os.path.join(self.aarDir, "res")

        if not os.path.exists(resPath):
            self.needR = False
            log_utils.debug(
                "aar res merge completed. there is no res folder in " +
                self.aarFile)
            return True

        resFiles = file_utils.list_files(resPath, [], [])
        if len(resFiles) == 0:
            self.needR = False
            log_utils.debug(
                "aar res merge completed. there is no res file in " +
                self.aarFile)
            return True

        resPaths = [resPath, targetRes]

        ResourceMerger2.merge(resPaths)
        log_utils.debug("res in aar " + self.aarFile + " merged into " +
                        targetRes)

        return True
Beispiel #10
0
    def parse_leaf_nodes(self, nodes, strictMode):

        key = '{' + androidNS + '}name'

        if nodes != None and len(nodes) > 0:

            for node in nodes:

                name = node.get(key)

                if name == None or len(name) == 0:
                    log_utils.warning("manifest merge ignored " + str(node))
                    continue

                typeName = node.tag

                component = ManifestComponent(typeName, name, node, strictMode)
                fullName = component.full_name()

                if file_provider_full_name == fullName:
                    self.cache_file_provider(component)

                if fullName not in self.components:

                    self.components[fullName] = component

                else:

                    log_utils.warning("node " + name + " duplicated in " +
                                      self.manifestFile)
Beispiel #11
0
    def add_child(self, block):

        if block.fullname() in self.children:
            log_utils.warning("attr in declare-styleable duplicated:%s; %s",
                              block.path(), block.name)
            return

        self.children[block.fullname()] = block
Beispiel #12
0
def copyChannelResources(game, channel, decompileDir):

    """
        Copy channel resources to decompile folder. for example icon resources, assets and so on.
    """
    resPath = "games/" + game['appName'] + "/channels/" + channel['id']
    resPath = file_utils.getFullPath(resPath)
    if not os.path.exists(resPath):
        log_utils.warning("the channel %s special res path is not exists. %s", channel['id'], resPath)
        return 0

    targetResPath = file_utils.getFullPath(decompileDir)
    copyResToApk(resPath, targetResPath)

    log_utils.info("copy channel %s special res to apk success.", channel['name'])
    return 0
def copy_files(src, dest):
    if not os.path.exists(src):
        log_utils.warning("the src is not exists.path:%s", src)
        return

    if os.path.isfile(src):
        copy_file(src, dest)
        return

    for f in os.listdir(src):
        sourcefile = os.path.join(src, f)
        targetfile = os.path.join(dest, f)
        if os.path.isfile(sourcefile):
            copy_file(sourcefile, targetfile)
        else:
            copy_files(sourcefile, targetfile)
Beispiel #14
0
def copy_files(src, dest):
    if not os.path.exists(src):
        log_utils.warning("the src is not exists.path:%s", src)
        return

    if os.path.isfile(src):
        copy_file(src, dest)
        return

    for f in os.listdir(src):
        sourcefile = os.path.join(src, f)
        targetfile = os.path.join(dest, f)
        if os.path.isfile(sourcefile):
            copy_file(sourcefile, targetfile)
        else:
            copy_files(sourcefile, targetfile)
Beispiel #15
0
    def merge(cls, resPaths):
        """merge multiple res folders.  merge res one by one from the first one to the last one. then in the last one is the final merged resources"""
        merger = ResourceMerger2()

        if resPaths == None or len(resPaths) <= 1:
            log_utils.warning("resPaths not specified or only one res path.")
            return

        for resPath in resPaths:

            if os.path.exists(resPath):
                resSet = ResourceSet.create(merger.parse_name(resPath),
                                            resPath)
                merger.resSets.append(resSet)

        merger.do_merge()
Beispiel #16
0
    def merge_manifest(self, targetManifest):

        if not os.path.exists(self.aarDir):
            log_utils.warning("the aar is not unarchived:" + self.aarFile)
            return False

        manifestPath = os.path.join(self.aarDir, "AndroidManifest.xml")

        if not os.path.exists(manifestPath):
            self.needR = False
            log_utils.debug("there is no AndroidManifest.xml in " +
                            manifestPath)
            return True

        self.packageName = manifest_utils.get_package_name(manifestPath)

        return manifest_merger.merge2(manifestPath, targetManifest)
Beispiel #17
0
    def merge_assets(self, targetAssets):

        if not os.path.exists(self.aarDir):
            log_utils.warning("the aar is not unarchived:" + self.aarFile)
            return False

        assetPath = os.path.join(self.aarDir, "assets")

        if not os.path.exists(assetPath):
            log_utils.debug(
                "aar assets merge completed. there is no assets folder in " +
                self.aarFile)
            return True

        assets_merger.merge(assetPath, targetAssets)

        return True
Beispiel #18
0
def processingIcons(appicon_path="", platform="ios", sizeArray=[]):
    """APPIcon的处理流程"""
    # 获取icon原图
    origin_image = Image.open(appicon_path).convert("RGBA")

    for x in range(0, len(sizeArray)):
        width = sizeArray[x][1]
        # 调整图像大小
        outImage = origin_image.resize((width, width), Image.BILINEAR)

        if platform == "ios":
            imgName = sizeArray[x][0] + ".png"
            file_manager.joinFilePath(
                file_manager.getFullPath(Index.temp_icon),
                platform + "/AppIcon.appiconset")
            temp_ios_path = file_manager.createFilePath(
                file_manager.getFullPath(Index.temp_icon) + platform +
                "/AppIcon.appiconset")
            print(temp_ios_path)
            outImage.save(temp_ios_path + "/" + imgName, "png")
            print(temp_ios_path + "/" + imgName)
            if x == 0:
                file_manager.joinFilePath(
                    file_manager.getFullPath(Index.temp_icon), platform)
                temp_ios_path = file_manager.createFilePath(
                    file_manager.getFullPath(Index.temp_icon) + platform +
                    "/AppIcon.appiconset")
                content_path = file_manager.getFullPath("upload/icon/jsonfile")
                log_utils.info(temp_ios_path + "\n" + content_path)
                file_manager.copyFiles(content_path, temp_ios_path)

        elif platform == "android":
            typeFileName = sizeArray[x][0]
            imgName = "ic_launcher.png"
            file_manager.joinFilePath(
                file_manager.getFullPath(Index.temp_icon),
                platform + "/" + typeFileName)
            temp_android_path = file_manager.createFilePath(
                file_manager.getFullPath(Index.temp_icon) + platform + "/" +
                typeFileName)
            print(temp_android_path)
            outImage.save(temp_android_path + "/" + imgName, "png")
            print(temp_android_path + "/" + imgName)
        else:
            log_utils.warning("平台选择错误")
Beispiel #19
0
def modify_doNotCompress(ymlPath, uncompressRegx):
    """
        modify uncompress types into doNotCompress
    """

    if uncompressRegx == None or len(uncompressRegx) == 0:
        return

    if not os.path.exists(ymlPath):
        log_utils.warning("the apktool.yml is not exists " + uncompressRegx)
        return

    ymlFile = open(ymlPath, 'r')
    lines = ymlFile.readlines()
    ymlFile.close()

    if 'arsc' not in uncompressRegx:
        uncompressRegx.insert(0, 'arsc')

    newLines = list()
    inDoNotCompress = False
    for line in lines:

        if 'doNotCompress:' in line:
            newLines.append(line)
            inDoNotCompress = True

            for aitem in uncompressRegx:
                newLines.append("- " + aitem + "\n")

        elif line.strip().startswith('-') and inDoNotCompress:
            continue

        else:
            inDoNotCompress = False
            newLines.append(line)

    content = ''
    for line in newLines:
        content = content + line

    ymlFile = open(ymlPath, 'w')
    ymlFile.write(content)
    ymlFile.close()
Beispiel #20
0
    def merge_jars(self, targetLibs):

        if not os.path.exists(self.aarDir):
            log_utils.warning("the aar is not unarchived:" + self.aarFile)
            return False

        classesPath = os.path.join(self.aarDir, "classes.jar")
        if os.path.exists(classesPath):
            targetPath = os.path.join(targetLibs, self.aarName + ".jar")
            file_utils.copy_file(classesPath, targetPath)
            log_utils.debug("classes.jar in aar " + self.aarFile +
                            " copied to " + targetPath)

        libsPath = os.path.join(self.aarDir, "libs")

        if not os.path.exists(libsPath):
            log_utils.debug(
                "aar libs merge completed. there is no libs folder in " +
                self.aarFile)
            return True

        for f in os.listdir(libsPath):

            if f.endswith(".jar"):

                targetName = self.aarName + "." + f
                targetName = targetName.replace(" ",
                                                "")  # //remove spaces in name

                targetPath = os.path.join(
                    targetLibs, targetName
                )  # rename jar in aar libs folder with aar name prefix.

                if os.path.exists(targetPath):
                    log_utils.error("libs in aar " + self.aarFile +
                                    " merge failed. " + f +
                                    " already exists in " + targetLibs)
                    return False

                file_utils.copy_file(os.path.join(libsPath, f), targetPath)
                log_utils.debug(f + " in aar " + self.aarFile + " copied to " +
                                targetLibs)

        return True
Beispiel #21
0
def add_compress_regx(ymlPath, compressRegx):
    """
        remove matched compress types from doNotCompress tag
    """

    if compressRegx == None or len(compressRegx) == 0:
        return

    if not os.path.exists(ymlPath):
        log_utils.warning("the apktool.yml is not exists " + ymlPath)
        return

    ymlFile = open(ymlPath, 'r')
    lines = ymlFile.readlines()
    ymlFile.close()

    handlingCompress = False

    newLines = []
    for line in lines:

        if 'doNotCompress:' in line:
            handlingCompress = True
            newLines.append(line)
        elif handlingCompress and line.startswith('-'):
            currLine = line[1:].strip()
            matchs = [c for c in compressRegx if c == currLine]
            if len(matchs) <= 0:
                newLines.append(line)

        else:
            handlingCompress = False
            newLines.append(line)

    content = ''
    for line in newLines:
        content = content + line

    ymlFile = open(ymlPath, 'w')
    ymlFile.write(content)
    ymlFile.close()
Beispiel #22
0
def modifyFileContent(sourcefile, oldContent, newContent):
    if os.path.isdir(sourcefile):
        log_utils.warning("the source %s must be a file not a dir", sourcefile)
        return

    if not os.path.exists(sourcefile):
        log_utils.warning("the source is not exists.path:%s", sourcefile)
        return

    f = open(sourcefile, 'r+')
    data = str(f.read())
    f.close()
    bRet = False
    idx = data.find(oldContent)
    while idx != -1:
        data = data[:idx] + newContent + data[idx + len(oldContent):]
        idx = data.find(oldContent, idx + len(oldContent))
        bRet = True

    if bRet:
        fw = open(sourcefile, 'w')
        fw.write(data)
        fw.close()
        log_utils.info("modify file success.path:%s", sourcefile)
    else:
        log_utils.warning(
            "there is no content matched in file:%s with content:%s",
            sourcefile, oldContent)
def modifyFileContent(sourcefile, oldContent, newContent):
    if os.path.isdir(sourcefile):
        log_utils.warning("the source %s must be a file not a dir", sourcefile)
        return

    if not os.path.exists(sourcefile):
        log_utils.warning("the source is not exists.path:%s", sourcefile)
        return 

    f = open(sourcefile, 'r+')
    data = str(f.read())
    f.close()
    bRet = False
    idx = data.find(oldContent)
    while idx != -1:
        data = data[:idx] + newContent + data[idx + len(oldContent):]
        idx = data.find(oldContent, idx + len(oldContent))
        bRet = True

    if bRet:
        fw = open(sourcefile, 'w')
        fw.write(data)
        fw.close()
        log_utils.info("modify file success.path:%s", sourcefile)
    else:
        log_utils.warning("there is no content matched in file:%s with content:%s", sourcefile, oldContent)
Beispiel #24
0
def mergeResXml(copyFrom, copyTo):

    """
        Merge all android res xml
    """



    if not os.path.exists(copyTo):
        return False

    aryXml = ['strings.xml','styles.xml','colors.xml','dimens.xml','ids.xml','attrs.xml','integers.xml','arrays.xml','bools.xml','drawables.xml']
    basename = os.path.basename(copyFrom)

    if basename in aryXml:
        if config_utils.is_py_env_2():
            f = open(copyTo)
        else:
            f = open(copyTo, 'r', encoding='utf-8')
        targetContent = f.read()
        f.close()

        fromTree = ET.parse(copyFrom)
        fromRoot = fromTree.getroot()
        toTree = ET.parse(copyTo)
        toRoot = toTree.getroot()
        for node in list(fromRoot):
            val = node.get('name')
            if val != None and len(val) > 0:
                valMatched = '"'+val+'"'
                attrIndex = targetContent.find(valMatched)
                if -1 == attrIndex:
                    toRoot.append(node)
                else:
                    log_utils.warning("The node %s is already exists in %s", val, basename)

        toTree.write(copyTo, 'UTF-8')
        return True
    return False
Beispiel #25
0
    def merge_val_files(cls, filePath, targetFilePath):

        # log_utils.debug("merge val files:" + filePath + " and " + targetFilePath)

        if not os.path.exists(targetFilePath):
            log_utils.warning("merge_val_files. but target file not exists:" +
                              targetFilePath + ". just copy " + filePath)
            file_utils.copy_file(filePath, targetFilePath)
            return

        oldTree = ET.parse(filePath)
        oldRoot = oldTree.getroot()

        tree = ET.parse(targetFilePath)
        root = tree.getroot()

        for node in list(oldRoot):
            log_utils.debug("merge res node %s from %s to %s",
                            node.attrib.get('name'), filePath, targetFilePath)
            root.append(node)

        tree.write(targetFilePath, "UTF-8")
Beispiel #26
0
def merge_files(src, dest):

    if not os.path.exists(src):
        log_utils.warning("the path is not exists.path:%s", src)
        return

    if os.path.exists(dest) and os.path.isfile(dest):

        log_utils.warning("assets merge igored file:" + src +
                          " already exists in " + dest)
        return

    if os.path.isfile(src):
        file_utils.copy_file(src, dest)
        return

    for f in os.listdir(src):
        sourcefile = os.path.join(src, f)
        targetfile = os.path.join(dest, f)
        if os.path.isfile(sourcefile):
            file_utils.copy_file(sourcefile, targetfile)
        else:
            merge_files(sourcefile, targetfile)
Beispiel #27
0
def copyAppResources(game, decompileDir):
    """
        Copy game res files to apk.
    """
    resPath = "games/" + game['appName'] + "/res"
    resPath = file_utils.getFullPath(resPath)
    if not os.path.exists(resPath):
        log_utils.warning("the game %s has no extra res folder", game['appName'])
        return

    assetsPath = os.path.join(resPath, 'assets')
    libsPath = os.path.join(resPath, 'libs')
    resourcePath = os.path.join(resPath, 'res')

    targetAssetsPath = os.path.join(decompileDir, 'assets')
    targetLibsPath = os.path.join(decompileDir, 'lib')
    targetResourcePath = os.path.join(decompileDir, 'res')

    decompileDir = file_utils.getFullPath(decompileDir)

    copyResToApk(assetsPath, targetAssetsPath)
    copyResToApk(libsPath, targetLibsPath)
    copyResToApk(resourcePath, targetResourcePath)
Beispiel #28
0
def handleThirdPlugins(workDir, decompileDir, game, channel, packageName):

    pluginsFolder = file_utils.getFullPath('config/plugin')
    gamePluginFolder = file_utils.getFullPath('games/'+game['appName']+'/plugin')
    plugins = channel.get('third-plugins')

    if plugins == None or len(plugins) <= 0:
        log_utils.info("the channel %s has no supported plugins.", channel['name'])
        return 0

    #copy all resources to temp folder.
    for plugin in plugins:
        pluginName = plugin['name']
        pluginSourceFolder = os.path.join(pluginsFolder, pluginName)
        if not os.path.exists(pluginSourceFolder):
            log_utils.warning("the plugin %s config folder is not exists", pluginName)
            continue

        pluginTargetFolder = workDir + "/plugins/" + pluginName
        file_utils.copy_files(pluginSourceFolder, pluginTargetFolder)

        gamePluginSourceFolder = os.path.join(gamePluginFolder, pluginName)
        if not os.path.exists(gamePluginSourceFolder):
            log_utils.warning("the plugin %s is not configed in the game %s", pluginName, game['appName'])
            continue

        file_utils.copy_files(gamePluginSourceFolder, pluginTargetFolder)

        if not os.path.exists(pluginSourceFolder + "/classes.dex"):
            jar2dex(pluginSourceFolder, pluginTargetFolder)


    #handle plugins
    smaliDir = os.path.join(decompileDir, "smali")
    pluginNum = 0
    for plugin in plugins:
        pluginName = plugin['name']
        pluginFolder = workDir + "/plugins/" + pluginName

        if not os.path.exists(pluginFolder):
            log_utils.warning("the plugin %s temp folder is not exists", pluginName)
            continue

        pluginDexFile = os.path.join(pluginFolder, "classes.dex")
        ret = dex2smali(pluginDexFile, smaliDir, "baksmali.jar")
        if ret:
            return 1

        ret = copyResource(game, channel, packageName, pluginFolder, decompileDir, plugin['operations'], pluginName, plugin)
        if ret:
            return 1

        pluginNum += 1

    log_utils.info("Total plugin num:%s;success handle num:%s", str(len(plugins)), str(pluginNum))
Beispiel #29
0
import codecs
import numpy as np

if not os.path.exists(args.out_dir):
    os.makedirs(args.out_dir)
L.set_logger(os.path.abspath(args.out_dir), 'train_log.txt')
L.print_args(args)

output_nbest_path = args.out_dir + '/augmented.nbest'
shutil.copy(args.input_nbest, output_nbest_path)

with open(args.weights, 'r') as input_weights:
    lines = input_weights.readlines()
    if len(lines) > 1:
        L.warning(
            "Weights file has more than one line. I'll read the 1st and ignore the rest."
        )
    weights = np.asarray(lines[0].strip().split(" "), dtype=float)

prefix = os.path.basename(args.input_nbest)
input_aug_nbest = NBestList(output_nbest_path, mode='r')
output_nbest = NBestList(args.out_dir + '/' + prefix + '.reranked.nbest',
                         mode='w')
output_1best = codecs.open(args.out_dir + '/' + prefix + '.reranked.1best',
                           mode='w',
                           encoding='UTF-8')


def is_number(s):
    try:
        float(s)
Beispiel #30
0
def writeManifestMetaInfo(channel, decompileDir):
    manifestFile = decompileDir + "/AndroidManifest.xml"
    manifestFile = file_utils.getFullPath(manifestFile)
    ET.register_namespace('android', androidNS)
    tree = ET.parse(manifestFile)
    root = tree.getroot()

    key = '{'+androidNS+'}name'
    val = '{'+androidNS+'}value'

    appNode = root.find('application')
    if appNode is None:
        return

    metaDataList = appNode.findall('meta-data')

    if metaDataList != None:
        for metaDataNode in metaDataList:
            keyName = metaDataNode.attrib[key]
            for child in channel['params']:
                if keyName == child['name'] and child['bWriteInManifest'] == '1':
                    log_utils.warning("the meta-data node %s repeated. remove it .", keyName)
                    appNode.remove(metaDataNode)

            if 'third-plugins' in channel and channel['third-plugins'] != None and len(channel['third-plugins']) > 0:

                for cPlugin in channel['third-plugins']:
                    if 'params' in cPlugin and cPlugin['params'] != None and len(cPlugin['params']) > 0:
                        for child in cPlugin['params']:
                            if keyName == child['name'] and child['bWriteInManifest'] == '1':
                                log_utils.warning("the meta-data node %s repeated. remove it .", keyName)
                                appNode.remove(metaDataNode)


    for child in channel['params']:
        if child['bWriteInManifest'] != None and child['bWriteInManifest'] == '1':
            metaNode = SubElement(appNode, 'meta-data')
            metaNode.set(key, child['name'])
            metaNode.set(val, child['value'])

    if 'third-plugins' in channel and channel['third-plugins'] != None and len(channel['third-plugins']) > 0:

        for cPlugin in channel['third-plugins']:
            if 'params' in cPlugin and cPlugin['params'] != None and len(cPlugin['params']) > 0:
                for child in cPlugin['params']:
                    if child['bWriteInManifest'] != None and child['bWriteInManifest'] == '1':
                        metaNode = SubElement(appNode, 'meta-data')
                        metaNode.set(key, child['name'])
                        metaNode.set(val, child['value'])

    if 'U8_APPLICATION_PROXY_NAME' in channel:
        metaNode = SubElement(appNode, 'meta-data')
        metaNode.set(key, "U8_APPLICATION_PROXY_NAME")
        metaNode.set(val, channel['U8_APPLICATION_PROXY_NAME'])        


    #log_utils.info(ET.tostring(root,encoding="us-ascii", method="text"))

    tree.write(manifestFile, 'UTF-8')

    log_utils.info("The manifestFile meta-data write successfully")
Beispiel #31
0
def appendChannelIconMark(game, channel, decompileDir):

    """
        自动给游戏图标加上渠道SDK的角标
        没有角标,生成没有角标的ICON
    """

    gameIconPath = 'games/' + game['appName'] + '/icon/icon.png'
    gameIconPath = file_utils.getFullPath(gameIconPath)
    if not os.path.exists(gameIconPath):
        log_utils.error("the game %s icon is not exists:%s",game['appName'], gameIconPath)
        return 1

    useMark = True

    if 'icon' not in channel:
        log_utils.warning("the channel %s of game %s do not config icon in config.xml,no icon mark.", channel['name'], game['appName'])
        useMark = False


    rlImg = Image.open(gameIconPath)

    if useMark:
        #如果有角标,则添加角标
        markType = channel['icon']
        markName = 'right-bottom'
        if markType == 'rb':
            markName = 'right-bottom'
        elif markType == 'rt':
            markName = 'right-top'
        elif markType == 'lt':
            markName = 'left-top'
        elif markType == 'lb':
            markName = 'left-bottom'

        markPath = 'config/sdk/' + channel['name'] + '/icon_marks/' + markName + '.png'

        if not os.path.exists(markPath):
            log_utils.warning("the icon mark %s is not exists of sdk %s.no icon mark.", markPath, channel['name'])
        else:
            markIcon = Image.open(markPath)
            rlImg = image_utils.appendIconMark(rlImg, markIcon, (0, 0))

    ldpiSize = (36, 36)
    mdpiSize = (48, 48)
    hdpiSize = (72, 72)
    xhdpiSize = (96, 96)
    xxhdpiSize = (144,144)
    xxxhdpiSize = (192, 192)

    ldpiIcon = rlImg.resize(ldpiSize, Image.ANTIALIAS)
    mdpiIcon = rlImg.resize(mdpiSize, Image.ANTIALIAS)
    hdpiIcon = rlImg.resize(hdpiSize, Image.ANTIALIAS)
    xhdpiIcon = rlImg.resize(xhdpiSize, Image.ANTIALIAS)
    xxhdpiIcon = rlImg.resize(xxhdpiSize, Image.ANTIALIAS)
    xxxhdpiIcon = rlImg.resize(xxxhdpiSize, Image.ANTIALIAS)

    ldpiPath = file_utils.getFullPath(decompileDir + '/res/drawable-ldpi')
    mdpiPath = file_utils.getFullPath(decompileDir + '/res/drawable-mdpi')
    hdpiPath = file_utils.getFullPath(decompileDir + '/res/drawable-hdpi')
    xhdpiPath = file_utils.getFullPath(decompileDir + '/res/drawable-xhdpi')
    xxhdpiPath = file_utils.getFullPath(decompileDir + '/res/drawable-xxhdpi')
    xxxhdpiPath = file_utils.getFullPath(decompileDir + '/res/drawable-xxxhdpi')

    if not os.path.exists(ldpiPath):
        os.makedirs(ldpiPath)

    if not os.path.exists(mdpiPath):
        os.makedirs(mdpiPath)

    if not os.path.exists(hdpiPath):
        os.makedirs(hdpiPath)

    if not os.path.exists(xhdpiPath):
        os.makedirs(xhdpiPath)

    if not os.path.exists(xxhdpiPath):
        os.makedirs(xxhdpiPath)

    if not os.path.exists(xxxhdpiPath):
        os.makedirs(xxxhdpiPath)

    gameIconName = getAppIconName(decompileDir) + '.png'

    ldpiIcon.save(os.path.join(ldpiPath, gameIconName), 'PNG')
    mdpiIcon.save(os.path.join(mdpiPath, gameIconName), 'PNG')
    hdpiIcon.save(os.path.join(hdpiPath, gameIconName), 'PNG')
    xhdpiIcon.save(os.path.join(xhdpiPath, gameIconName), 'PNG')
    xxhdpiIcon.save(os.path.join(xxhdpiPath, gameIconName), 'PNG')
    xxxhdpiIcon.save(os.path.join(xxxhdpiPath, gameIconName), 'PNG')

    return 0
Beispiel #32
0
def checkValueResources(decompileDir):
    valXmls = ['strings.xml', 'styles.xml', 'colors.xml','dimens.xml', 'ids.xml','attrs.xml','integers.xml','arrays.xml','bools.xml','drawables.xml','public.xml']

    resDir = decompileDir + '/res/values'
    existsStrs = {}
    stringsXml = resDir + '/strings.xml'
    if os.path.exists(stringsXml):
        stringTree = ET.parse(stringsXml)
        root = stringTree.getroot()
        for node in list(root):
            stringItem = {}
            name = node.attrib.get('name')
            val = node.text
            stringItem['file'] = stringsXml
            stringItem['name'] = name
            stringItem['value'] = val
            existsStrs[name] = stringItem

    existsColors = {}
    colorsXml = resDir + 'colors.xml'
    if os.path.exists(colorsXml):
        colorTree = ET.parse(colorsXml)
        root = colorTree.getroot()
        for node in list(root):
            colorItem = {}
            name = node.attrib.get('name')
            val = node.text.lower()
            colorItem['file'] = colorsXml
            colorItem['name'] = name
            colorItem['value'] = val
            existsColors[name] = colorItem


    valueFiles = {}
    for filename in os.listdir(resDir):
        if filename in valXmls:
            continue

        srcFile = os.path.join(resDir,filename)
        if os.path.splitext(srcFile)[1] != '.xml':
            continue
        tree = ET.parse(srcFile)
        root = tree.getroot()
        if root.tag != 'resources':
            continue

        for node in list(root):
            dictRes = None
            if node.tag == 'string':
                dictRes = existsStrs
            elif node.tag == 'color':
                dictRes = existsColors
            else:
                continue

            name = node.attrib.get('name')
            val = node.text

            if name is None:
                continue

            resItem = dictRes.get(name)
            if resItem is not None:
                resVal = resItem.get('value')
                log_utils.warning("node %s duplicated!!! the val is %s;the newVal is %s", name, val, resVal)
                if val.lower() == resVal.lower():
                    root.remove(node)
                else:
                    #file_utils.printF("The node Name :"+name+" are compicated. and script handle failed.")
                    #return 1
                    root.remove(node)

            else:
                valItem = {}
                valItem['file'] = srcFile
                valItem['name'] = name
                valItem['value'] = val
                dictRes[name] = valItem

        valueFiles[srcFile] = tree

    for valFile in valueFiles.keys():
        valueFiles[valFile].write(valFile, 'UTF-8')

    return 0