def writeDeveloperIntoManifest(SDK, usrSDKConfig, decompileDir):
    """"""
    manifestFile = decompileDir + '/AndroidManifest.xml'
    ET.register_namespace('android', androidNS)
    targetTree = ET.parse(manifestFile)
    targetRoot = targetTree.getroot()
    key = '{' + androidNS + '}name'
    value = '{' + androidNS + '}value'
    applicationNode = targetRoot.find('application')
    if applicationNode is None:
        error_operate.error(110)
        return
    metaListNode = applicationNode.findall('meta-data')
    for metaNode in metaListNode:
        name = metaNode.attrib[key]
        for child in usrSDKConfig['param']:
            if child['name'] == name and child['bWriteIntoManifest'] == 1:
                metaListNode.remove(metaNode)

    for child in usrSDKConfig['param']:
        if child['bWriteIntoClient']:
            if child['bWriteIntoManifest'] is not None and child[
                    'bWriteIntoManifest'] == 1:
                metaNode = SubElement(applicationNode, 'meta-data')
                metaNode.set(key, child['name'])
                metaNode.set(value, child['value'])

    targetTree.write(manifestFile, 'UTF-8')
    file_operate.printf(
        'write Developer Infomation into AndroidManifest.xml success')
def copyResToApk(copyFrom, copyTo):
    if not os.path.exists(copyFrom) and not os.path.exists(copyTo):
        file_operate.printf('copy Files from %s to %s Fail:file not found' %
                            (copyFrom, copyTo))
        return
    if os.path.isfile(copyFrom):
        if not appendResXml(copyFrom, copyTo):
            file_operate.copyFile(copyFrom, copyTo)
        return
    for file in os.listdir(copyFrom):
        sourceFile = os.path.join(copyFrom, file)
        targetFile = os.path.join(copyTo, file)
        if os.path.isfile(sourceFile):
            if not os.path.exists(copyTo):
                os.makedirs(copyTo)
            if appendResXml(sourceFile, targetFile):
                continue
            if not os.path.exists(targetFile) or os.path.exists(
                    targetFile
            ) and os.path.getsize(targetFile) != os.path.getsize(sourceFile):
                targetFileHandle = open(targetFile, 'wb')
                sourceFileHandle = open(sourceFile, 'rb')
                targetFileHandle.write(sourceFileHandle.read())
                targetFileHandle.close()
                sourceFileHandle.close()
        if os.path.isdir(sourceFile):
            copyResToApk(sourceFile, targetFile)
def writeChannelInfoIntoDevelopInfo(decompileDir, channel, privateKey):
    """
        the infomation about channel would configure here
    """
    assetsDir = decompileDir + '/assets'
    developerFile = assetsDir + '/developerInfo.xml'
    if not os.path.exists(assetsDir):
        os.makedirs(assetsDir)
    targetTree = None
    targetRoot = None
    if not os.path.exists(developerFile):
        targetTree = ElementTree()
        targetRoot = Element('developer')
        targetTree._setroot(targetRoot)
    else:
        targetTree = ET.parse(developerFile)
        targetRoot = targetTree.getroot()
    infoNode = targetRoot.find('channel')
    if infoNode is None:
        infoNode = SubElement(targetRoot, 'channel')
    if infoNode.get('idChannel') is None:
        infoNode.set('idChannel', str(channel['channelNum']))
        infoNode.set('uApiKey', channel['uapiKey'])
        infoNode.set('uApiSecret', channel['uapiSecret'])
        infoNode.set('oauthLoginServer', channel['oauthLoginServer'])
        if channel['extChannel'] is not None:
            infoNode.set('extChannel', channel['extChannel'])
        infoNode.set('privateKey', privateKey)
    targetTree.write(developerFile, 'UTF-8')
    file_operate.printf(
        "Save channel's information to developerInfo.xml success")
 def assignPackTask(self, task):
     """assign new package task"""
     if self.__status == 1:
         file_operate.printf('A task is running in this thread')
         return
     self.__task = task
     self.__status = 1
def copyMetaDataToAndroidManifest(configFile, manifestFile):

    ET.register_namespace('android', androidNS)
    configTree = ET.parse(configFile)
    configRoot = configTree.getroot()
    metaConfig = configRoot.find("metaconfig")
    if metaConfig is None:
        return
    metaConfigList = metaConfig.findall("meta-data")

    targetTree = ET.parse(manifestFile)
    targetRoot = targetTree.getroot()
    key = '{' + androidNS + '}name'
    value = '{' + androidNS + '}value'
    applicationNode = targetRoot.find('application')
    if applicationNode is None:
        error_operate.error(110)
        return
    metaListNode = applicationNode.findall('meta-data')
    for metaNode in metaListNode:
        name = metaNode.attrib[key]
        for child in metaConfigList:
            if child.attrib[key] == name:
                metaListNode.remove(metaNode)

    for child in metaConfigList:
        metaNode = SubElement(applicationNode, "meta-data")
        metaNode.set(key, child.attrib[key])
        metaNode.set(value, child.attrib[value])

    targetTree.write(manifestFile, 'UTF-8')
    file_operate.printf(
        'write funcellconfig.xml meta-data into AndroidManifest.xml success')
def error(code):
    try:
        idChannel = int(threading.currentThread().getName())
        taskManager.shareInstance().notify(idChannel, 100 + code)
        print '<---error code---> %d' % (code)
        file_operate.printf('%s Failed at code %s!' % (idChannel, -100 - code))
    except:
        print 'error code:%d' % code
Exemple #7
0
    def assignPackTask(self, task, channelIconData):
        """assign new download icon task"""
        if self.__status == 1:
            file_operate.printf('A task is running in this thread')
            return

        self.__task = task
        self.__channelIconData = channelIconData
        self.__status = 1
Exemple #8
0
def checkTaskThread(arrayList = None,dict = None):
    while 1:
        time.sleep(5)
        result = packThreadManager.shareInstance().isRunning()
        if result == 0:
            break
        packThreadManager.shareInstance().startTask(0,arrayList)

    file_operate.printf('Mission download Icon Complete!')
    thread.exit_thread()
Exemple #9
0
def checkTaskThread():
    while 1:
        time.sleep(5)
        result = packThreadManager.shareInstance().isRunning()
        if result == 0:
            break
        packThreadManager.shareInstance().startTask(0)
    taskManager.shareInstance().missionComplete()
    file_operate.printf('Mission Complete!')
    thread.exit_thread()
Exemple #10
0
def checkTaskThread(arrayList=None, dictTemp=None):
    while 1:
        time.sleep(5)
        result = packThreadManager.shareInstance().isRunning()
        if result == 0:
            break
        packThreadManager.shareInstance().startTask(0, arrayList, dictTemp)

    taskManager.shareInstance().missionComplete()
    openfilefolder()
    file_operate.printf('Mission Complete!')
    print "\n---------------------------------all pack complete!---------------------------------"
    thread.exit_thread()
def addFileToApk(srcfile, apkFile):
    if os.path.exists(srcfile) and os.path.exists(apkFile):
        apkFile = file_operate.getFullPath(apkFile)
        aapt = file_operate.getToolPath('aapt')
        rmcmd = '"%s" remove "%s" "%s"' % (aapt, apkFile, 'classes.dex')
        bReturn = file_operate.execFormatCmd(rmcmd)
        if bReturn:
            error_operate.error(70)
            return 1
        f = zipfile.ZipFile(apkFile, 'a')
        f.write(srcfile, 'classes.dex')
        f.close()
        file_operate.printf('add file:' + srcfile)
        return 0
def packResIntoApk(SDKWorkDir, SDK, decompileDir, packageName, usrSDKConfig):
    SDKDir = SDKWorkDir + SDK['SDKName']
    for child in SDK['operateLs']:
        if child['name'] == 'modifyManifest':
            modifyFrom = child['from']
            modifyTo = child['to']
            if modifyFrom == None and modifyTo == None:
                file_operate.printf(
                    'Operate error, Please check your config in funcellconfig.xml'
                )
                error_operate.error(100)
                return 1
            modifyFrom = None.path.join(SDKDir, modifyFrom)
            modifyTo = os.path.join(decompileDir, modifyTo)
            modifyFrom = file_operate.getFullPath(modifyFrom)
            modifyTo = file_operate.getFullPath(modifyTo)
            modifyManifest.modify(modifyTo, modifyFrom, SDK['SDKName'],
                                  usrSDKConfig)
            continue
        if child['name'] == 'copy':
            copyFrom = child['from']
            copyTo = child['to']
            if copyFrom == None and copyTo == None:
                file_operate.printf(
                    'Operate error, Please check your config in funcellconfig.xml'
                )
                error_operate.error(101)
                return 1
            copyFrom = None.path.join(SDKDir, copyFrom)
            copyFrom = file_operate.getFullPath(copyFrom)
            copyTo = os.path.join(decompileDir, copyTo)
            copyTo = file_operate.getFullPath(copyTo)
            copyResToApk(copyFrom, copyTo)
            if child['to'] == 'lib':
                armPath = os.path.join(copyFrom, 'armeabi')
                armv7To = os.path.join(copyTo, 'armeabi-v7a')
                if os.path.exists(armPath) and os.path.exists(armv7To):
                    copyResToApk(armPath, armv7To)

        if child['name'] == 'script':
            scriptPath = SDKDir + '/script.pyc'
            if os.path.exists(scriptPath):
                sys.path.append(SDKDir)
                import script
                script.script(SDK, decompileDir, packageName, usrSDKConfig)
                del sys.modules['script']
                sys.path.remove(SDKDir)

    return 0
def generateDeveloperInfo(channel, SDK, usrSDKConfig, decompileDir,
                          privateKey):
    """the infomation about developer would configure here
       the value of element's attribute cann't be int
    """
    assetsDir = decompileDir + '/assets'
    developerFile = assetsDir + '/developerInfo.xml'
    if not os.path.exists(assetsDir):
        os.makedirs(assetsDir)
    targetTree = None
    targetRoot = None
    if not os.path.exists(developerFile):
        targetTree = ElementTree()
        targetRoot = Element('developer')
        targetTree._setroot(targetRoot)
    else:
        targetTree = ET.parse(developerFile)
        targetRoot = targetTree.getroot()
    infoNode = targetRoot.find('channel')
    if infoNode is None:
        infoNode = SubElement(targetRoot, 'channel')
    if infoNode.get('idChannel') is None:
        infoNode.set('idChannel', str(channel['channelNum']))
        infoNode.set('uApiKey', channel['uapiKey'])
        infoNode.set('uApiSecret', channel['uapiSecret'])
        infoNode.set('oauthLoginServer', channel['oauthLoginServer'])
        if channel['extChannel'] is not None:
            infoNode.set('extChannel', channel['extChannel'])
        infoNode.set('privateKey', privateKey)
    if SDK.get('showVersion') is not None:
        attrName = SDK['SDKName'] + '_Version'
        infoNode.set(attrName, SDK['showVersion'])
    for param in usrSDKConfig['param']:
        if param['bWriteIntoClient'] and not param['bWriteIntoManifest']:
            paramName = param['name']
            pos = paramName.find('##')
            if pos != -1:
                paramName = paramName[pos + 2:]
            if paramName.count('Orientation') > 0:
                infoNode.set(
                    paramName,
                    modifyManifest.getOrientation(
                        decompileDir + '/AndroidManifest.xml', usrSDKConfig))
            else:
                infoNode.set(paramName, param['value'])

    targetTree.write(developerFile, 'UTF-8')
    file_operate.printf('generate developerInfo.xml success')
Exemple #14
0
def renameAppName(appName, androidManiFest = 'AndroidManifest.xml'):
    if not os.path.exists(androidManiFest):
        return False
    ET.register_namespace('android', androidNS)
    targetTree = ET.parse(androidManiFest)
    targetRoot = targetTree.getroot()
    key = '{' + androidNS + '}label'
    file_operate.printf(key)
    applicationNode = targetRoot.find('application')
    if applicationNode is None:
        error_operate.error(121)
        return 1
    ET.dump(applicationNode)
    applicationNode.attrib[key] = appName
    print('rename appname----- :'+appName)
    targetTree.write(androidManiFest, 'UTF-8')
Exemple #15
0
def modify(manifestFile, sourceCfgFile, pluginName, usrSDKConfig):
    manifestFile = file_operate.getFullPath(manifestFile)
    sourceXml = sourceCfgFile
    sourceXml = file_operate.getFullPath(sourceXml)
    if not os.path.exists(sourceXml):
        ForManifestDir = os.path.dirname(sourceXml)
        screenOrientation = getOrientation(manifestFile, usrSDKConfig)
        if screenOrientation == 'landscape' or screenOrientation == 'auto':
            sourceXml = ForManifestDir + '/ForManifestLandscape.xml'
        else:
            sourceXml = ForManifestDir + '/ForManifestPortrait.xml'
    if not os.path.exists(sourceXml):
        return
    ET.register_namespace('android', androidNS)
    targetTree = ET.parse(manifestFile)
    targetRoot = targetTree.getroot()
    haveChanged = doModify(manifestFile, sourceXml, targetRoot)
    if haveChanged:
        file_operate.printf('Modify AndroidManifest.xml for plugin ' +
                            pluginName)
        targetTree.write(manifestFile, 'UTF-8')
Exemple #16
0
def writeChannelInfoIntoDevelopInfo(workDir, channel, game):
    """
    the infomation about channel would configure here
    """
    developerFile = workDir + '/developerInfo.xml'
    targetTree = None
    targetRoot = None

    if os.path.exists(developerFile):
        file_operate.delete_file_folder(developerFile)

    if not os.path.exists(developerFile):
        targetTree = ElementTree()
        targetRoot = Element('developer')
        targetTree._setroot(targetRoot)
    else:
        print 'exists developerInfo!!!----' + developerFile
        targetTree = ET.parse(developerFile)
        targetRoot = targetTree.getroot()
    infoNode = targetRoot.find('channel')
    if infoNode is None:
        infoNode = SubElement(targetRoot, 'channel')
    channelNum = str(channel.get('customChannelNumber'))
    if channelNum == '' or channelNum is None:
        channelNum = str(channel.get('channelNum'))
    if infoNode.get('idChannel') is None:
        infoNode.set('idChannel', channelNum)
        infoNode.set('uApiKey', channel['uapiKey'])
        infoNode.set('uApiSecret', channel['uapiSecret'])
        infoNode.set('oauthLoginServer', channel['oauthLoginServer'])
        if channel['extChannel'] is not None:
            infoNode.set('extChannel', channel['extChannel'])
        if game.get('privateKey') is not None:
            infoNode.set('privateKey', game['privateKey'])
        if game.get('order_url') is not None and game['order_url'] != '':
            infoNode.set('order_url', game['order_url'])
        infoNode.set('standby_domain_name', 'pay.rsdk.com')
    targetTree.write(developerFile, 'UTF-8')
    file_operate.printf(
        "Save channel's information to developerInfo.xml success")
Exemple #17
0
def modify(manifestFile, sourceCfgFile, pluginName):
    manifestFile = file_operate.getFullPath(manifestFile)
    sourceXml = sourceCfgFile
    sourceXml = file_operate.getFullPath(sourceXml)
    file_operate.printf("modify source xml:%s manifestFile:%s" %(sourceXml, manifestFile))
    if not os.path.exists(sourceXml):
        ForManifestDir = os.path.dirname(sourceXml)
        screenOrientation = getStartActivityOrientation(manifestFile)
        file_operate("screenOrientation:%s"%(screenOrientation,))
        if screenOrientation == 'portrait':
            sourceXml = ForManifestDir + '/ForManifestPortrait.xml'
        else:
            sourceXml = ForManifestDir + '/ForManifestLandscape.xml'
    if not os.path.exists(sourceXml):
        return
    ET.register_namespace('android', androidNS)
    targetTree = ET.parse(manifestFile)
    targetRoot = targetTree.getroot()
    haveChanged = doModify(manifestFile, sourceXml, targetRoot)
    if haveChanged:
        file_operate.printf('Modify AndroidManifest.xml for plugin ' + pluginName)
        targetTree.write(manifestFile, 'UTF-8')
Exemple #18
0
def modifyApplicationActivity(key, value, androidManiFest = 'AndroidManifest.xml'):
    if not os.path.exists(androidManiFest):
        return False
    ET.register_namespace('android', androidNS)
    targetTree = ET.parse(androidManiFest)
    targetRoot = targetTree.getroot()
    applicationNode = targetRoot.find('application')
    if applicationNode is None:
        error_operate.error(121)
        return 1
    activityNodes = applicationNode.findall('activity')
    if activityNodes is not None and len(activityNodes) > 0:
        for oneNode in list(activityNodes):
            file_operate.printf("hello world")
            nsKey = '{' + androidNS + '}configChanges'
            file_operate.printf(nsKey)
            ET.dump(oneNode)
            perAttr = oneNode.get(nsKey)
            if perAttr != None and len(perAttr) > 0:
                file_operate.printf("hehehe")
                oneNode.attrib[nsKey] = value
    targetTree.write(androidManiFest, 'UTF-8')
Exemple #19
0
def generateDeveloperInfo(channel, SDK, usrSDKConfig, workDir, game):
    """the infomation about developer would configure here
    the value of element's attribute cann't be int
    """
    developerFile = workDir + '/developerInfo.xml'
    targetTree = None
    targetRoot = None

    if not os.path.exists(developerFile):
        targetTree = ElementTree()
        targetRoot = Element('developer')
        targetTree._setroot(targetRoot)
    else:
        targetTree = ET.parse(developerFile)
        targetRoot = targetTree.getroot()
    infoNode = targetRoot.find('channel')
    if infoNode is None:
        infoNode = SubElement(targetRoot, 'channel')
    channelNum = str(channel.get('customChannelNumber'))
    if channelNum == '' or channelNum is None:
        channelNum = str(channel.get('channelNum'))
    if infoNode.get('idChannel') is None:
        infoNode.set('idChannel', channelNum)
        infoNode.set('uApiKey', channel['uapiKey'])
        infoNode.set('uApiSecret', channel['uapiSecret'])
        infoNode.set('oauthLoginServer', channel['oauthLoginServer'])
        infoNode.set('privateKey', game['privateKey'])
        if channel['extChannel'] is not None:
            infoNode.set('extChannel', channel['extChannel'])
        if game.get('order_url') is not None and game['order_url'] != '':
            infoNode.set('order_url', game['order_url'])
    if usrSDKConfig['type'] & 8:
        for plugin in SDK['pluginLs']:
            type = plugin['typePlugin']
            if type == 2:
                pluginName = plugin['name']
                notifyName = pluginName + '_notify_url'
                notifyValue = ''
                if usrSDKConfig.get('notify_url') is not None:
                    notifyValue = usrSDKConfig['notify_url']
                if notifyValue == '':
                    notifyValue = SDK['orderCallback']
                if notifyValue != '':
                    infoNode.set(notifyName, notifyValue)
                break
    if channel['r_big_app_id'] is not None:
        infoNode.set('r_big_app_id', str(channel['r_big_app_id']))
    if channel['r_sub_app_id'] is not None:
        infoNode.set('r_sub_app_id', str(channel['r_sub_app_id']))
    if SDK.get('showVersion') is not None:
        attrName = SDK['SDKName'] + '_Version'
        infoNode.set(attrName, SDK['showVersion'])
    for param in usrSDKConfig['param']:
        if param['bWriteIntoClient'] and not param['bWriteIntoManifest']:
            paramName = param['name']
            pos = paramName.find('##')
            if pos != -1:
                paramName = paramName[pos + 2:]
            infoNode.set(paramName, param['value'])

    targetTree.write(developerFile, 'UTF-8')
    file_operate.printf('generate developerInfo.xml success')
Exemple #20
0
def error(code):
    file_operate.printf('%s Failed at code %s!' % (idChannel, -100 - code))
Exemple #21
0
def main(channel):
    # 调用函数 8.4
    inspectJDK()
    source = ConfigParse.shareInstance().getSource()
    if os.path.isdir(source):
        error_operate.error(3000)
        return
        # buildGradle(channel)
    else:
        idChannel = channel.get('idChannel')
        channelName = channel.get('name')
        channelNum = channel.get('channelNum')
        ConfigParse.shareInstance().set_channel_num(channelNum)

        extChannel = channel.get('extChannel')
        threading.currentThread().setName(idChannel)
        taskManager.shareInstance().notify(idChannel, 5)
        # source = ConfigParse.shareInstance().getSource()
        basename = os.path.basename(source)
        exttuple = os.path.splitext(basename)
        taskLock = taskManager.shareInstance().getLock()
        basename = exttuple[0]
        extname = exttuple[1]
        game = ConfigParse.shareInstance().getCurrentGame()
        if game is None:
            error_operate.error(3)
            return
        versionName = ConfigParse.shareInstance().getVersionName()
        print '<---Parent apk versionName-->%s' % (versionName)
        keystore = ConfigParse.shareInstance().getKeyStore()
        print '<---Game keystore info-->%s' % (keystore)
        if channelName is None:
            error_operate.error(5)
            return
        taskManager.shareInstance().notify(idChannel, 10)
        # file_operate.execFormatCmd('chmod -R 777 %s' % (file_operate.get_server_dir()+'/workspace/'))
        workDir = file_operate.get_server_dir() + '/workspace/%s/%s' % (
            ConfigParse.shareInstance().getDBName(), idChannel)
        workDir = file_operate.getFullPath(workDir)
        file_operate.delete_file_folder(workDir)
        if not os.path.exists(source):
            error_operate.error(60)
            return
        tmpApkSource = workDir + '/temp.apk'
        file_operate.copyFile(source, tmpApkSource)
        print 'tmpApkSource-->' + tmpApkSource
        decompileDir = workDir + '/decompile'
        ret = apk_operate.decompileApk(tmpApkSource, decompileDir, taskLock)
        print 'step--decompileAPK--RET-->%d' % (ret)
        if ret:
            return
        unknownFile = decompileDir + '/AddForRoot'
        if os.path.exists(decompileDir + '/unknown'):
            os.rename(decompileDir + '/unknown', unknownFile)
        # oldPackageName = apk_operate.getPackageName(decompileDir)
        # isCocosPlay = apk_operate.checkForCocosPlay(decompileDir, channel, oldPackageName)
        # if isCocosPlay:
        #     ret = apk_operate.renameApkForCocosPlay(decompileDir, oldPackageName, channel['packNameSuffix'], game,
        #                                             channel, taskLock)
        #     if ret:
        #         return
        # ConfigParse.shareInstance().setCocosPlayMode(isCocosPlay)

        apk_operate.replace_custom_res(decompileDir)

        taskManager.shareInstance().notify(idChannel, 20)
        SmaliDir = decompileDir + '/smali'
        SDKWorkDir = workDir + '/sdk/'
        for Channel_SDK in channel['sdkLs']:
            idSDK = Channel_SDK['idSDK']
            SDK = ConfigParse.shareInstance().findSDK(idSDK)
            if SDK == None:
                continue
            SDKSrcDir = file_operate.get_server_dir(
            ) + '/config/sdk/' + SDK['SDKName']
            SDKSrcDir = file_operate.getFullPath(SDKSrcDir)
            SDKDestDir = SDKWorkDir + SDK['SDKName']
            file_operate.copyFiles(SDKSrcDir, SDKDestDir)
            if os.path.exists(SDKDestDir + '/ForRes/drawable-xxxhdpi'):
                if file_operate.getTargetSdkVersion(tmpApkSource) < 18:
                    file_operate.delete_file_folder(SDKDestDir +
                                                    '/ForRes/drawable-xxxhdpi')

        taskManager.shareInstance().notify(idChannel, 30)
        for Channel_SDK in channel['sdkLs']:
            idSDK = Channel_SDK['idSDK']
            SDK = ConfigParse.shareInstance().findSDK(idSDK)
            if SDK == None:
                continue
            SDKDir = SDKWorkDir + SDK['SDKName']
            SDKDex = os.path.join(SDKDir, 'classes.dex')
            SDKDex = file_operate.getFullPath(SDKDex)
            ret = apk_operate.dexTrans2Smali(SDKDex, SmaliDir, 4,
                                             'baksmali.jar')
            if ret:
                return

        taskManager.shareInstance().notify(idChannel, 35)
        decompileSmaliDir = decompileDir + '/smali'
        maniFestFile = decompileDir + '/AndroidManifest.xml'
        newPackagename = apk_operate.renameApkPackage(
            decompileSmaliDir, maniFestFile, channel['packNameSuffix'],
            channel['r_bundle_id'])

        #reset apk version
        if channel['r_gameversion_build'] != '' and channel[
                'r_gameversion'] != '':
            apk_operate.resetApkVersion(maniFestFile,
                                        channel['r_gameversion_build'],
                                        channel['r_gameversion'])
            file_operate.printf("Reset ApkVersion success")

        taskManager.shareInstance().notify(idChannel, 45)
        print '<---- decompileDir:%s ---->' % (decompileDir)
        print '<---- channel:%s ---->' % (channel)
        print '<---- game:%s ---->' % (game)
        apk_operate.writeChannelInfoIntoDevelopInfo(decompileDir, channel,
                                                    game)
        apk_operate.writeSupportInfo(decompileDir)
        taskManager.shareInstance().notify(idChannel, 50)
        bExecuteSpecialScipt = False
        for Channel_SDK in channel['sdkLs']:
            idSDK = Channel_SDK['idSDK']
            UsrSDKConfig = ConfigParse.shareInstance().findUserSDKConfigBySDK(
                idSDK, channel['idChannel'])
            SDK = ConfigParse.shareInstance().findSDK(idSDK)
            if SDK == None:
                continue
            ret = apk_operate.packResIntoApk(SDKWorkDir, SDK, decompileDir,
                                             newPackagename, UsrSDKConfig)
            if ret:
                return
            SDKVersionInfo = ConfigParse.shareInstance().findSDKVersion(
                SDK['SDKName'])
            if SDKVersionInfo is not None:
                SDK['showVersion'] = SDKVersionInfo['showVersion']
            print '<---- SDK:%s ---->' % (SDK)
            print '<---- UsrSDKConfig:%s ---->' % (UsrSDKConfig)
            ret = apk_operate.configDeveloperInfo(channel, SDK, UsrSDKConfig,
                                                  decompileDir)
            if ret:
                return
            # apk_operate.downloadUserConfigFile(channel,game,UsrSDKConfig)
            for child in SDK['operateLs']:
                if child['name'] == 'script' or child['name'] == 'Script':
                    bExecuteSpecialScipt = True
                    break

        taskManager.shareInstance().notify(idChannel, 65)
        # bMergeR = False
        ret, bMergeR = apk_operate.addSplashScreen(channel, decompileDir)
        if ret:
            return
        ret = encode_operate.encodeXmlFiles(workDir + '/decompile')
        if ret:
            return

        taskManager.shareInstance().notify(idChannel, 60)
        if bExecuteSpecialScipt:
            ret = special_script.doSpecialOperate(channel, decompileDir,
                                                  newPackagename, SDKWorkDir)
            if ret:
                return

        taskManager.shareInstance().notify(idChannel, 70)

        if extChannel.find("androidsupportv4") != -1:
            print 'handle androidsupportv4 resource'
            androidsupportv4dex = decompileDir + '/../../../../config/channel/android-support-v4.dex'
            if os.path.exists(androidsupportv4dex):
                samilDir = decompileDir + '/smali'
                ret = apk_operate.dexTrans2Smali(androidsupportv4dex, samilDir,
                                                 10)
                if ret:
                    print('copy androidsupportv4 dex to smali fail')
                    return
            else:
                print('androidsupportv4.dex is not exists')
                return

        if (ConfigParse.shareInstance().getChannelIcon(idChannel) != ''):
            iconDir = file_operate.get_server_dir(
            ) + '/workspace/' + ConfigParse.shareInstance().getOutputDir(
            ) + '/icon/'
            if not os.path.exists(iconDir):
                os.makedirs(iconDir)
            urllib.urlretrieve(
                ConfigParse.shareInstance().getChannelIcon(idChannel),
                iconDir + 'icon.png')

            ret = apk_operate.pushIconIntoApk(iconDir, decompileDir)
            if ret:
                return
        # newAppName = ConfigParse.shareInstance().getAppName()
        #modify app display name by game setting
        # apk_operate.modifyAppName(game, decompileDir, newAppName)
        # modify app display name by channel setting
        #if channel display_name is not null,the app displayname will be set by channel
        apk_operate.modifyAppNameByChannel(channel, decompileDir)

        apk_operate.writeDataIntoAndroidManifest(decompileDir, channel)
        taskManager.shareInstance().notify(idChannel, 75)

        ret = apk_operate.produceNewRFile(newPackagename, decompileDir)
        if ret:
            return
        ret = apk_operate.splitDex(workDir, channel)
        if ret:
            return
        taskManager.shareInstance().notify(idChannel, 80)
        tempApkDir = workDir + '/tempApk'
        tempApkDir = file_operate.getFullPath(tempApkDir)
        tempApkName = '%s/game_%s_%s%s' % (tempApkDir, channel['idChannel'],
                                           versionName, extname)
        apk_operate.encryptApkByDeveloper(decompileDir)
        ret = apk_operate.recompileApk(decompileDir, tempApkName)
        if ret:
            return
        print '<---recompileApk success--->'
        taskManager.shareInstance().notify(idChannel, 90)
        for Channel_SDK in channel['sdkLs']:
            idSDK = Channel_SDK['idSDK']
            SDK = ConfigParse.shareInstance().findSDK(idSDK)
            if SDK == None:
                continue
            SDKSrcDir = file_operate.get_server_dir(
            ) + '/config/sdk/' + SDK['SDKName']
            SDKSrcDir = file_operate.getFullPath(SDKSrcDir)
            ForRootDir = SDKSrcDir + '/ForRootDir'
            if os.path.exists(ForRootDir):
                apk_operate.addForRootDir(tempApkName, ForRootDir)

        if os.path.exists(unknownFile):
            apk_operate.addForRootDir(tempApkName, unknownFile)
        ret = apk_operate.signApkAuto(tempApkName, game, channel)
        if ret:
            return
        #outputDir = ConfigParse.shareInstance().getOutputDir()
        #print '<---outputDir--->'+outputDir

#if outputDir == '':
#   outputDir = '../'

#get date for apk file name
        import time

        # dateStr = time.strftime("%Y%m%d%H%M%S")

        #get final apk name
        finalAppName = ''
        print '<---start rename apk--->'
        # if game.get('isModifyAppName') is not None and game['isModifyAppName'] != False:
        #     finalAppName = game.get('gameName').encode('utf-8')
        # display_name = channel['display_name'].encode('utf-8')
        # if display_name is not None and display_name != '':
        #     finalAppName = display_name
        #
        # if finalAppName == '':
        #     finalAppName = game.get('gameName')
        # channel_name = channel['name'].encode('utf-8')
        #outputDir += '/' + game['gameName'] + '/' + versionName + '/' + channel_name
        #outputDir = file_operate.getFullPath(outputDir)
        #apkName = ('%s/%s_%s_%s_%s%s' % (outputDir,
        #                               finalAppName,
        #                              channel_name,
        #                             versionName,
        #                            dateStr,
        #                           extname)).encode('utf-8')
        apkName = ConfigParse.shareInstance().getOutPutApkName()
        print '<---Apk PATH--->' + apkName
        #if platform.system() == 'Windows':
        #   apkName = '%s/game_%s%s' % (outputDir, versionName, extname)
        #  print '<---apk path:'+apkName+'--->'
        strlist = apkName.split('/')
        outputDir = apkName.replace('/' + strlist[len(strlist) - 1], '')
        print '<---outputDir--->' + outputDir
        ret = apk_operate.alignAPK(tempApkName, apkName, outputDir)
        if ret:
            print '{"ret":"fail","msg":"run pack fail"}'
            return
        print '{"ret":"success","msg":"run pack success"}'
        taskManager.shareInstance().notify(idChannel, 100)
def generatePluginInfo(SDK, usrSDKConfig, decompileDir):
    """the infomation about Plugin would configure here"""
    assetsDir = decompileDir + '/assets'
    if not os.path.exists(assetsDir):
        os.makedirs(assetsDir)
    PluginFile = assetsDir + '/supportPlugin.xml'
    targetTree = None
    targetRoot = None
    pluginLsNode = None
    if not os.path.exists(PluginFile):
        targetTree = ElementTree()
        targetRoot = Element('support')
        targetTree._setroot(targetRoot)
    else:
        targetTree = ET.parse(PluginFile)
        targetRoot = targetTree.getroot()
    for plugin in SDK['pluginLs']:
        type = plugin['typePlugin']
        typeTag = '<plugin>'
        if type == 0:
            typeTag = 'user_plugin'
            if not usrSDKConfig['type'] & 32:
                continue
        elif type == 1:
            typeTag = 'ads_plugin'
            if not usrSDKConfig['type'] & 16:
                continue
        elif type == 2:
            typeTag = 'iap_plugin'
            if not usrSDKConfig['type'] & 8:
                continue
        elif type == 3:
            typeTag = 'social_plugin'
            if not usrSDKConfig['type'] & 4:
                continue
        elif type == 4:
            typeTag = 'share_plugin'
            if not usrSDKConfig['type'] & 2:
                continue
        elif type == 5:
            typeTag = 'analytics_plugin'
            if not usrSDKConfig['type'] & 1:
                continue
        elif type == 6:
            typeTag = 'push_plugin'
            if not usrSDKConfig['type'] & 64:
                continue
        pluginName = plugin['name']
        if pluginName is None:
            file_operate.printf('pluginName error')
            error_operate.error(109)
            return 1
        pluginLsNode = targetRoot.find(typeTag)
        if pluginLsNode is not None:
            for plugin in pluginLsNode.getchildren():
                if plugin.text == pluginName:
                    pluginLsNode.remove(plugin)

        if pluginLsNode is None:
            pluginLsNode = SubElement(targetRoot, typeTag)
        paramNode = SubElement(pluginLsNode, 'param')
        paramNode.text = pluginName
        paramNode.set('name', SDK['SDKName'])

    targetTree.write(PluginFile, 'UTF-8')
    file_operate.printf('generate supportPlugin.xml success')
    return 0