예제 #1
0
    def iterFileMapAndCopyFile(self):
        cfgResRootDir = self.sdksRootDir
        luaversion = ConfigParse.shareInstance().getLuaVersion()
        fileMap = ConfigParse.shareInstance().getFileMap()

        rules = fileMap.get(luaversion, None)
        if not rules:
            print("no coresponding luaversion")
            exit(1)

        for k, v in rules.items():
            source = os.path.join(cfgResRootDir, luaversion, k)
            target = os.path.join(self.decompileDir, v['targetDir'])
            # 如果source是文件
            if os.path.isfile(source):
                # 直接复制到目标文件夹, 忽略模式
                target = os.path.join(target, k)
                file_utils.copyFiles(source, target)
            # 是文件夹
            else:
                mode = v['copyMode']
                if mode == '*':
                    file_utils.copyFiles(source, target)
                elif mode == '-':
                    sourceDirFiles = os.listdir(source)
                    targetDirFiles = os.listdir(target)
                    for f in [
                            s for s in sourceDirFiles if s in targetDirFiles
                    ]:
                        source = os.path.join(source, f)
                        target = os.path.join(target, f)
                        file_utils.copyFiles(source, target)
    def startTask(self, platform):
        packageLs = ConfigParse.shareInstance().getPackageLs()
        # print '<---TASK INFO--->%s' %(packageLs)
        for package in packageLs:
            idChannel = package['idChannel']
            if idChannel in self.__finishChannel:
                #print '<---...CONTINUE WORKING...--->'
                continue
            pkThread = self.getIdleThread()
            if pkThread is None:
                return
            pkThread.setPlatform(platform)
            channel = ConfigParse.shareInstance().findChannel(idChannel)
            if channel is None:
                continue
            pkThread.assignPackTask(channel)
            print '<---packThreadStart--->'
            if not pkThread.isAlive():
                pkThread.start()
            self.__finishChannel.append(idChannel)

        bOver = True
        for thread in self.__taskThreads:
            if thread.getStatus() != 0:
                bOver = False
                break

        if bOver == True:
            for thread in self.__taskThreads:
                thread.stop()
                self.__taskThreads.remove(thread)
예제 #3
0
def startIos():
    reload(sys)
    sys.setdefaultencoding('utf8')
    ConfigParse.shareInstance().readUserConfig(1)
    taskManager.shareInstance().clearRecord()
    packThreadManager.shareInstance().clearRecord()
    packThreadManager.shareInstance().setCurWorkDir(os.getcwd())
    source = ConfigParse.shareInstance().getSource()
    game = ConfigParse.shareInstance().getCurrentGame()
    versionName = ConfigParse.shareInstance().getVersionName()
    packThreadManager.shareInstance().startTask(1)
    thread.start_new_thread(checkTaskThreadForIos, ())
예제 #4
0
def reportCmdError(cmd, stdoutput, erroutput):
    """
    """
    errorLog = stdoutput + '\r\n' + erroutput
    if ConfigParse.shareInstance().get_log_dir() is None:
        reportError(errorLog, int(threading.currentThread().getName()))
    else:
        error = '==================>>>> ERROR <<<<==================\r\n'
        error += '[Time]: ' + time.strftime(
            '%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '\r\n'
        error += '[Error]:\r\n'
        error += errorLog + '\r\n'
        error += '==================================================\r\n'
        log(error, ConfigParse.shareInstance().get_log_dir())
예제 #5
0
def modify_file(workDir, strForReplace, funName):
    #AppController.mm的路径(appctrl_path帝国争霸,超级舰队的。appctrl_path2是战舰传奇的)
    appctrlPath = workDir + '/AppController.mm'
    appctrlPath2 = workDir + '/ios/AppController.mm'

    #如果没有AppController.mm就去找AppDelegate.m的路径
    xcodeProjPath = workDir + '/' + ConfigParse.shareInstance().getProjXcode()
    AppDelegatePath = xcodeProjPath[:-10] + '/AppDelegate.m'

    replaceFlag = '#pragma mark rsdk_' + funName + '_end'  #根据传入的funName拼接 代码标记
    replaceStr = strForReplace + '\n' + replaceFlag  #要添加的代码 + 代码标记
    print 'replaceStr===>' + replaceStr

    #判断AppController.mm或者AppDelegate.m文件路径
    if os.path.exists(appctrlPath):
        content = replace_file(appctrlPath, replaceFlag, replaceStr)
        write_str_to_file(appctrlPath, content)
    elif os.path.exists(appctrlPath2):
        content = replace_file(appctrlPath2, replaceFlag, replaceStr)
        write_str_to_file(appctrlPath2, content)
    elif os.path.exists(AppDelegatePath):
        content = replace_file(AppDelegatePath, replaceFlag, replaceStr)
        write_str_to_file(AppDelegatePath, content)
    else:
        print 'not exist appcontroller.mm or appdelegate.m'
    return
예제 #6
0
def start():
    reload(sys)
    sys.setdefaultencoding('utf8')
    ConfigParse.shareInstance().readUserConfig(0)
    taskManager.shareInstance().clearRecord()
    packThreadManager.shareInstance().clearRecord()
    packThreadManager.shareInstance().setCurWorkDir(os.getcwd())
    # source = ConfigParse.shareInstance().getSource()
    #print '<---source-->'+source
    # game = ConfigParse.shareInstance().getCurrentGame()
    # if os.path.isfile(source):
    # versionName = ConfigParse.shareInstance().getVersionName()
    # print '<---Config VersionName-->'+versionName
    # file_operate.backupApk(source, game, versionName)
    packThreadManager.shareInstance().startTask(0)
    thread.start_new_thread(checkTaskThread, ())
예제 #7
0
    def doPackWithOneChannelSymbol(self, channelId, tempRecompileApk,
                                   tempSignedApkName, outputDir, outputName,
                                   symbol, taskWorkDir):
        '''
        @param channelId 渠道id,用于获取keystore
        @param tempRecompileApk 重打包后的未签名apk path
        @param tempSignedApkName  签名对齐后的包名称
        @param outputDir  输出路径(非完整path)
        @param outputName  输出名称(非完整path)
        @param symbol  自定义渠道标记
        @param taskWorkDir  工作目录
        '''
        log_utils.getLogger().info('doPackWithOneChannelSymbol ... ')
        #添加渠道标识
        log_utils.getLogger().info('adding channel symbol to /assets/ ... ')
        channelSymbolFileName = ConfigParse.shareInstance(
        ).getChannelSymbolFileName()
        zip_utils.addChannelSymbolFile(tempRecompileApk, symbol,
                                       channelSymbolFileName, taskWorkDir)

        #apk签名
        log_utils.getLogger().info('signing apk')
        keystoreInfo = ConfigParse.shareInstance().getKeystoreInfoByChannelId(
            channelId)
        ret = cmd_tools.signApk(tempRecompileApk, keystoreInfo['file'],
                                keystoreInfo['storePassword'],
                                keystoreInfo['keyAlias'],
                                keystoreInfo['aliasPassword'])
        if ret:
            raise PackException(pack_exception.SIGN_APK_FAILED,
                                'sign apk failed')

        #apk优化
        apkName = '%s/%s' % (outputDir, outputName)
        outputDir = os.path.dirname(apkName)

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

        log_utils.getLogger().debug(outputDir)
        log_utils.getLogger().info('zipaligning and renaming apk apkName == ' +
                                   apkName)
        ret = cmd_tools.alignAPK(tempRecompileApk, tempSignedApkName)
        if ret:
            raise PackException(pack_exception.ALIGN_APK_FAILED,
                                'align apk failed')
        os.rename(tempSignedApkName, apkName)
예제 #8
0
def log(str):
    outputDir = ConfigParse.shareInstance().getOutputDir()
    logDir = outputDir + 'Log/'
    if not os.path.exists(logDir):
        os.makedirs(logDir)
    logFile = codecs.open(logDir + 'error.log', 'a+', 'utf-8')
    content = str + '\r\n'
    logFile.write(unicode(content, 'gbk'))
    logFile.close()
예제 #9
0
def execFormatCmd(cmd):
    cmd = cmd.replace('\\', '/')
    cmd = re.sub('/+', '/', cmd)
    if platform.system() == 'Windows':
        st = subprocess.STARTUPINFO
        st.dwFlags = subprocess.STARTF_USESHOWWINDOW
        st.wShowWindow = subprocess.SW_HIDE
    else:
        cmd = cmd.encode('utf-8').decode('iso-8859-1')

    # findret = cmd.find('jarsigner')
    # if findret > -1:
    #     import shlex
    #     cmds = shlex.split(cmd)
    #     log_utils.getLogger().debug('the execformatCmd cmds:'+str(cmds))
    #     s = subprocess.Popen(cmds)
    # else:
    #     s = subprocess.Popen(cmd, shell=True)

    #===========================================================================
    # import shlex
    # cmds = shlex.split(cmd)
    # #log_utils.getLogger().debug("eeeeeeeeeeeeeeeeeee" + cmd)
    # s = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    #===========================================================================

    import locale
    cmd = cmd.encode(locale.getdefaultlocale()[1])
    p = subprocess.Popen(cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=True)

    ConfigParse.shareInstance().setCurrentSubProcess(p)

    while p.poll() == None:
        line = p.stdout.readline()
        if not line:
            break
        # print line
        log_utils.getLogger().info(line)
    p.wait()
    return p.returncode
예제 #10
0
 def kill_subprocess(self):
     p = ConfigParse.shareInstance().getCurrentSubProcess()
     #=======================================================================
     # process = psutil.Process(p.pid)
     # for proc in process.get_children(recursive=True):
     #     proc.kill()
     # process.kill()
     #=======================================================================
     #os.system("taskkill /PID %s /F" % p.pid)
     os.kill(p.pid, signal.CTRL_C_EVENT)
예제 #11
0
    def __init__(self):
        self.sdksRootDir = os.path.join(env.SUPPORT_DIR, self._projectShorName)

        self.outputDir = ConfigParse.shareInstance().getOutputDir()
        if self.outputDir is None:
            raise PackException(pack_exception.PHP_PARAMS_ERROR,
                                'outputDir is None')
        self.outputName = ConfigParse.shareInstance().getOutputName()
        self.apkFile = ConfigParse.shareInstance().getApkPath()

        timestamp_str = str(time.time())
        self.taskWorkDir = os.path.join(my_utils.getWorkDir(),
                                        self._projectShorName, timestamp_str,
                                        "temp")

        if not os.path.exists(self.taskWorkDir):
            os.makedirs(self.taskWorkDir)
        log_utils.getLogger().info('taskWorkDir == ' + self.taskWorkDir)
        self.decompileDir = self.taskWorkDir + '/decompile'
        self.tmpApkToolPath = os.path.join(self.taskWorkDir, 'apktooltmp')
예제 #12
0
def log(str):
    outputDir = ConfigParse.shareInstance().getOutputDir()
    logDir = outputDir + '/log/'
    if not os.path.exists(logDir):
        os.makedirs(logDir)
    logFile = codecs.open(logDir + 'error.txt', 'a+', 'utf-8')
    content = str + '\r\n'
    if platform.system() == 'Windows':
        logFile.write(unicode(content, 'gbk'))
    else:
        logFile.write(unicode(content, 'gbk'))
    logFile.close()
예제 #13
0
def doSpecialOperate(channel, decompileDir, packageName, SDKWorkDir):
    """There are special operate in some SDK"""
    for Channel_SDK in channel['sdkLs']:
        idSDK = Channel_SDK['idSDK']
        SDK = ConfigParse.shareInstance().findSDK(idSDK)
        if SDK is None:
            continue
        usrSDKConfig = ConfigParse.shareInstance().findUserSDKConfigBySDK(
            idSDK, channel['idChannel'])
        SDKDir = SDKWorkDir + SDK['SDKName']
        scriptPath = SDKDir + '/' + 'script.pyc'
        if os.path.exists(scriptPath):
            sys.path.append(SDKDir)
            import script
            ret = script.script(SDK, decompileDir, packageName, usrSDKConfig)
            del sys.modules['script']
            sys.path.remove(SDKDir)
            if ret != None and ret == 1:
                return 1

    return 0
예제 #14
0
def log(str, outputDir=None):
    if outputDir is None:
        outputDir = ConfigParse.shareInstance().getOutputLogDir()
    logDir = get_server_dir() + '/Log/' + outputDir + '/'
    print 'log_dir:' + logDir
    if not os.path.exists(logDir):
        os.makedirs(logDir)
    logFile = codecs.open(logDir + 'error.txt', 'a+', 'utf-8')
    print '<---logFile--->' + logDir + 'error.txt'
    content = str + '\r\n'
    if platform.system() == 'Windows':
        logFile.write(unicode(content, 'gbk'))
    else:
        logFile.write(unicode(content, 'gbk'))
    logFile.close()
예제 #15
0
    def doPackWithoutChannelSymbol(self, tempRecompileApk, tempSignedApkName,
                                   outputDir, outputName):
        '''
        @param channelId 渠道id,用于获取keystore
        @param tempRecompileApk 重打包后的未签名apk path
        @param tempSignedApkName  签名对齐后的包名称
        @param outputDir  输出路径(非完整path)
        @param outputName  输出名称(非完整path)
        '''
        log_utils.getLogger().info('doPackWithoutChannelSymbol ... ')
        #apk签名
        log_utils.getLogger().info('signing apk')
        keystoreInfo = ConfigParse.shareInstance().getKeystoreInfo()

        # 签名,没细看
        ret = cmd_tools.signApk(tempRecompileApk, keystoreInfo['file'],
                                keystoreInfo['storePassword'],
                                keystoreInfo['keyAlias'],
                                keystoreInfo['aliasPassword'])
        if ret:
            raise PackException(pack_exception.SIGN_APK_FAILED,
                                'sign apk failed')

        #apk优化
        apkName = '%s/%s' % (outputDir, outputName)
        outputDir = os.path.dirname(apkName)

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

        log_utils.getLogger().debug(outputDir)
        log_utils.getLogger().info('zipaligning and renaming apk apkName == ' +
                                   apkName)

        # 调用工具里的 zipalign.exe 对temRecompileApk 进行优化,生成tempSignedApkName
        ret = cmd_tools.alignAPK(tempRecompileApk, tempSignedApkName)

        if ret:
            raise PackException(pack_exception.ALIGN_APK_FAILED,
                                'align apk failed')
        import shutil
        shutil.move(tempSignedApkName, apkName)
예제 #16
0
def reportError(errorOuput, idChannel):
    """
    """
    packageName = ''
    channel = ConfigParse.shareInstance().findChannel(idChannel)
    if channel != None and channel.get('packNameSuffix') != None:
        packageName = str(channel['packNameSuffix'])
        channelName = str(channel['name'])
        if platform.system() == 'Windows':
            channelName = str(channel['name']).encode('gbk')
        else:
            channelName = channel['name'].decode('utf8').encode('gbk')
    error = '==================>>>> ERROR <<<<==================\r\n'
    error += '[rsdk_Channel]: ' + threading.currentThread().getName() + '\r\n'
    error += '[rsdk_ChannelName]: ' + channelName + '\r\n'
    error += '[rsdk_Package]: ' + packageName + '\r\n'
    error += '[rsdk_Time]: ' + time.strftime(
        '%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '\r\n'
    error += '[rsdk_Error]:\r\n'
    error += errorOuput + '\r\n'
    error += '===================================================\r\n'
    log(error)
예제 #17
0
def split_apk(db_name, game_id, id_channel, parent_apk_path, sub_apk_path,
              sub_channel_id):
    reload(sys)
    sys.setdefaultencoding('utf8')
    log_dir = '%s/%s/%s' % (db_name, game_id, id_channel)
    ConfigParse.shareInstance().set_log_dir(log_dir)
    if not os.path.exists(parent_apk_path):
        logError('parent apk not exist', log_dir)
        print '{"ret":"fail","msg":"parent apk not exist"}'
        return
    middle_dir = '%s/%s' % (db_name, sub_channel_id)
    split_work_dir = file_operate.get_server_dir(
    ) + '/split_workspace/%s' % middle_dir
    print 'split_work_dir:' + split_work_dir
    if os.path.exists(split_work_dir):
        file_operate.delete_file_folder(split_work_dir)

    os.makedirs(split_work_dir)
    split_decompile_dir = split_work_dir + '/decompile'
    os.mkdir(split_decompile_dir)

    channel_temp_apk_dir = split_work_dir + '/temp'
    os.mkdir(channel_temp_apk_dir)

    channel_temp_apk = channel_temp_apk_dir + '/temp.apk'
    file_operate.copyFile(parent_apk_path, channel_temp_apk)

    ret = apk_operate.decompileApk(channel_temp_apk, split_decompile_dir, None)
    if ret:
        logError('decompileApk parent apk fail', log_dir)
        print '{"ret":"fail","msg":"decompileApk parent apk fail"}'
        return
    ConfigParse.shareInstance().readUserConfig(0)
    sub_channel_config = ConfigParse.shareInstance().get_sub_channel_config()

    sub_channel_icon_url = None
    display_name = None
    sub_app_id = ''
    sub_num = ''

    if len(sub_channel_config) > 0:
        for r in sub_channel_config:
            if int(id_channel) != int(r['p_channel_id']):
                logError('param channel id is not right', log_dir)
                print '{"ret":"fail","msg":"param channel id is not right"}'
                return

            if int(game_id) != int(r['game_id']):
                logError('param game id is not right', log_dir)
                print '{"ret":"fail","msg":"param game id is not right"}'
                return

            if r['r_channel_game_icon'] is None:
                sub_channel_icon_url = ''
            else:
                sub_channel_icon_url = r['r_channel_game_icon']

            if r['display_name'] is None:
                display_name = ''
            else:
                display_name = r['display_name'].encode('utf-8')

            sub_app_id = str(r['sub_app_id'])
            print 'sub_app_id: %s' % sub_app_id
            sub_num = str(r['sub_num'])

    else:
        logError('sub channel config is empty', log_dir)
        print '{"ret":"fail","msg":"sub channel config is empty"}'
        return

    if sub_app_id == 0 or sub_num == 0:
        log_info = 'ret:fail,msg:sub_app_id and sub_num == 0'
        logError(log_info, log_dir)
        return

    if display_name != '' and display_name is not None:
        apk_operate.doModifyAppName(split_decompile_dir, display_name)

    if sub_channel_icon_url != '' and sub_channel_icon_url is not None:
        channel_icon_dir = split_work_dir + '/icon/'
        os.mkdir(channel_icon_dir)
        urllib.urlretrieve(sub_channel_icon_url, channel_icon_dir + 'icon.png')
        ret = apk_operate.pushIconIntoApk(channel_icon_dir,
                                          split_decompile_dir)
        if ret:
            logError('pushIconIntoApk error', log_dir)
            return
    ret = encode_operate.decodeXmlFiles(split_decompile_dir)
    if ret:
        logError('decodeXmlFiles error', log_dir)
        return

    channel = ConfigParse.shareInstance().findChannel(int(id_channel))
    sdk_dir = split_work_dir + '/sdk/'
    for channel_sdk in channel['sdkLs']:
        id_sdk = channel_sdk['idSDK']
        SDK = ConfigParse.shareInstance().findSDK(id_sdk)
        if SDK is None:
            continue
        split_script_src_dir = file_operate.get_server_dir(
        ) + '/config/sdk/' + SDK['SDKName'] + '/specialsplit_script.pyc'
        split_script_src_dir = file_operate.getFullPath(split_script_src_dir)
        if not os.path.exists(split_script_src_dir):
            continue

        split_script_dest_dir = sdk_dir + SDK[
            'SDKName'] + '/specialsplit_script.pyc'

        file_operate.copyFiles(split_script_src_dir, split_script_dest_dir)
        SDKDir = sdk_dir + SDK['SDKName']
        sys.path.append(SDKDir)
        import specialsplit_script
        print 'sub_app_id:' + sub_app_id
        ret = specialsplit_script.script(split_decompile_dir, sub_app_id,
                                         sub_num)
        del sys.modules['specialsplit_script']
        sys.path.remove(SDKDir)
        if ret:
            logError("error do Special Operate", log_dir)
            print "error do Special Operate"
            return

    ret = change_develop_id(split_decompile_dir, sub_app_id, sub_num)
    print 'change_develop_id ret:%s' % ret
    if ret:
        logError('change develop id error', log_dir)
        return

    encode_operate.encodeXmlFiles(split_decompile_dir)

    channel_unsign_apk = channel_temp_apk_dir + '/channel_temp_apk.apk'
    ret = apk_operate.recompileApk(split_decompile_dir, channel_unsign_apk)
    if ret:
        logError("recompileApk fail", log_dir)
        print "recompileApk fail"
        return
    game = ConfigParse.shareInstance().getCurrentGame()
    if game is None:
        print 'game is none'
        logError('game is none', log_dir)
        return
    ret = apk_operate.signApkAuto(channel_unsign_apk, game, channel,
                                  middle_dir)

    if ret:
        print 'signApkAuto fail'
        logError('signApkAuto fail', log_dir)
        return

    out_put_dir = os.path.dirname(sub_apk_path)
    ret = apk_operate.alignAPK(channel_unsign_apk, sub_apk_path, out_put_dir)
    if ret:
        print 'alignAPK fail'
        logError('alignAPK fail', log_dir)
        return
    print '{"ret":"success","msg":"run pack success"}'
    file_operate.delete_file_folder(split_work_dir)
예제 #18
0
    def doBatchPackWithChannelSymols(self, channelId, unsignedApk,
                                     tempSignedApkName, outputDir, outputName,
                                     symbolList, taskWorkDir):
        '''
        @param channelId 渠道id,用于获取keystore
        @param unsignedApk 重打包后的未签名apk path
        @param tempSignedApkName  签名对齐后的包名称
        @param outputDir  输出路径(非完整path)
        @param outputName  输出名称(非完整path)
        @param symbolList  自定义渠道标记列表
        @param taskWorkDir  工作目录
        '''
        log_utils.getLogger().info('doBatchPackWithChannelSymols ... ')
        batchPackDir = os.path.join(taskWorkDir, 'batch')
        if not os.path.exists(batchPackDir):
            os.makedirs(batchPackDir)

        copiedUnsignedApk = os.path.join(os.path.dirname(unsignedApk),
                                         'batchTmpApk.apk')

        log_utils.getLogger().info('start batch packing ... ')
        for symbol in symbolList:
            if not file_utils.copyFile(unsignedApk, copiedUnsignedApk):
                raise PackException(
                    pack_exception.COPY_FILE_EXCEPTION,
                    'cannot copy apk during doBatchPackWithChannelSymols')

            #添加渠道标识
            log_utils.getLogger().info(
                'adding channel symbol to /assets/ ... ')
            channelSymbolFileName = ConfigParse.shareInstance(
            ).getChannelSymbolFileName()
            zip_utils.addChannelSymbolFile(copiedUnsignedApk, symbol,
                                           channelSymbolFileName, taskWorkDir)

            #apk签名
            log_utils.getLogger().info('signing apk')
            keystoreInfo = ConfigParse.shareInstance(
            ).getKeystoreInfoByChannelId(channelId)
            ret = cmd_tools.signApk(copiedUnsignedApk, keystoreInfo['file'],
                                    keystoreInfo['storePassword'],
                                    keystoreInfo['keyAlias'],
                                    keystoreInfo['aliasPassword'])
            if ret:
                raise PackException(pack_exception.SIGN_APK_FAILED,
                                    'sign apk failed')

            #apk优化
            apkName = '%s/%s' % (batchPackDir, outputName)
            basename = os.path.splitext(os.path.basename(apkName))[0]
            apkOutputDir = os.path.dirname(apkName)
            if not os.path.exists(apkOutputDir):
                os.makedirs(apkOutputDir)

            apkName = os.path.join(apkOutputDir,
                                   basename + '(' + symbol + ').apk')

            log_utils.getLogger().debug(apkOutputDir)
            log_utils.getLogger().info(
                'zipaligning and renaming apk apkName == ' + apkName)
            ret = cmd_tools.alignAPK(copiedUnsignedApk, tempSignedApkName)
            if ret:
                raise PackException(pack_exception.ALIGN_APK_FAILED,
                                    'align apk failed')
            os.rename(tempSignedApkName, apkName)

        log_utils.getLogger().info('batch packing success... ')
        log_utils.getLogger().info('zip apk files ... ')
        zip_utils.zipApks(batchPackDir, '%s/%s' % (outputDir, outputName))
예제 #19
0
def main(channel, dict):
    threading.currentThread().setName(channel)
    
    writeConfigToSdkConfigFile(channel, dict)
    
    dictTemp = ConfigParse.shareInstance().ConfigRead(channel)
    platformId = dictTemp.get('platformId')
    appVersion = dictTemp.get('appVersion')
    resVersion = dictTemp.get('resVersion')
    platformType = dictTemp.get('platformType')
    packageName = dictTemp.get('packageName')
    checkBox_isChecked = dict.get('checkBox_isChecked')
    checkBox_2_isChecked = dict.get('checkBox_2_isChecked')
    checkBox_4_isChecked = dict.get('checkBox_4_isChecked')
    checkBox_5_isChecked = dict.get('checkBox_5_isChecked')
    checkBox_voice_isChecked=dict.get('checkBox_voice_isChecked')
    
    comboBox_currentText = dict.get('comboBox_currentText')
    comboBox_3_currentText = dict.get('comboBox_3_currentText')
    comboBox_4_currentText = dict.get('comboBox_4_currentText')
    comboBox_6_currentText = dict.get('comboBox_6_currentText')
    comboBox_voice_currentText= dict.get('comboBox_voice_currentText')
    taskManager.shareInstance().notify(channel, 5)
    
    taskLock = taskManager.shareInstance().getLock()
    
    ret = execGameCommonInitializeScript(channel, platformId, appVersion, resVersion, platformType)
    if ret:
        return
    CreateTmpFolder(channel)
    source = ConfigParse.shareInstance().getApkPath()
#     source = dict.get('ApkPath')
    backupApk(source, channel)
    sourceDir = file_operate.getFullPath(constant.sdkRelatePath + channel)
    targetDir = file_operate.getFullPath(constant.tmpPath + '/' + channel)
    file_operate.copyFiles(sourceDir, targetDir)

    apkFile = targetDir + "/common.apk"
    deDir = targetDir + "/oldApkDir"
    operate.decompileApk_android(apkFile, deDir, taskLock)
    
    processStatistics(channel, checkBox_isChecked, comboBox_4_currentText)
    
    processAdvertising(channel, checkBox_2_isChecked, comboBox_6_currentText)
    
    processCrash(channel, checkBox_4_isChecked, comboBox_currentText) 

    processPush(channel, checkBox_5_isChecked, comboBox_3_currentText) 
    
    processMedia(channel,checkBox_voice_isChecked,comboBox_voice_currentText)

    oldApkDir = targetDir + "/oldApkDir"
    SmaliDir = oldApkDir + "/smali"
    dexFile1 = targetDir + "/classes.dex"
    ret = operate.dexTrans2Smali(dexFile1, SmaliDir, 3)
    
    dexFile2 = targetDir + "/classes2.dex"
    if os.path.exists(dexFile2):
        global splitDexFlag
        splitDexFlag = True
        ret = operate.dexTrans2Smali(dexFile2, SmaliDir, 3)
    if ret:
        return
#     dexFileApk = oldApkDir + "/classes.dex"
#     ret = operate.dexTrans2Smali(dexFileApk, SmaliDir, 3)
#     if ret:
#         return
    # copy res
    if os.path.exists(targetDir + "/ForRes"):
        operate.copyResToApk(targetDir + "/ForRes", oldApkDir + "/res")
    # copy funcellconfig.xml
    file_operate.copyFile(file_operate.getchannelFuncellConfigXmlPath(channel), oldApkDir + "/assets/funcellconfig.xml")
    # copy Assets
    armPath = targetDir + "/ForAssets/so/armeabi"
    armv7Path = targetDir + "/ForAssets/so/armeabi-v7a"
    if os.path.exists(armPath) and os.path.exists(armv7Path):
        operate.copyResToApk(armPath, armv7Path)
        
    if os.path.exists(targetDir + "/ForAssets"):
        operate.copyResToApk(targetDir + "/ForAssets", oldApkDir + "/assets")
    # copy extra
    
    if os.path.exists(targetDir + "/extra"):
        #-----------------六扇门配置-----------------------
        if os.path.exists(targetDir + "/extra/Assets/GameAssets/Resources/Config"):
            execOtherScript(targetDir)
        #----------------------------------------
#         operate.copyResToApk(targetDir+"/extra", oldApkDir+"/assets")
        file_operate.copyFiles(targetDir + "/extra", oldApkDir + "/assets")
    
    # copy libs
    if os.path.exists(targetDir + "/ForLibs"):
        if os.path.exists(oldApkDir + "/lib/armeabi") and os.path.exists(targetDir + "/ForLibs/armeabi"):
            operate.copyResToApk(targetDir + "/ForLibs/armeabi", oldApkDir + "/lib/armeabi")
        if os.path.exists(oldApkDir + "/lib/armeabi-v7a") and os.path.exists(targetDir + "/ForLibs/armeabi-v7a"):
            operate.copyResToApk(targetDir + "/ForLibs/armeabi-v7a", oldApkDir + "/lib/armeabi-v7a")
        if os.path.exists(oldApkDir + "/lib/x86") and os.path.exists(targetDir + "/ForLibs/x86"):
            operate.copyResToApk(targetDir + "/ForLibs/x86", oldApkDir + "/lib/x86")
        if os.path.exists(oldApkDir + "/lib/mips") and os.path.exists(targetDir + "/ForLibs/mips"):
            operate.copyResToApk(targetDir + "/ForLibs/mips", oldApkDir + "/lib/mips")
    
    # �ϲ�AndroidManifest.xml
    manifestFile = oldApkDir + "/AndroidManifest.xml"
    ET.register_namespace('android', constant.androidNS)
    targetTree = ET.parse(manifestFile)
    targetRoot = targetTree.getroot()
    
    haveChanged = modifyManifest.doModify(manifestFile, targetDir + "/ForManifest.xml", targetRoot)
    if haveChanged:
        targetTree.write(manifestFile, 'UTF-8')
    
    
    newPackagename = operate.renameApkPackage(SmaliDir, manifestFile, packageName)
    
    print channel , oldApkDir
    operate.addSplashScreen(channel, targetDir);
    
    ret = execGameCommongameSdkScript(channel, oldApkDir)
    if ret:
        return
    
    # statisticsScript
    statisticsScriptPath = targetDir + "/statisticsScript.pyc"
    if os.path.exists(statisticsScriptPath):
        sys.path.append(targetDir)
        import statisticsScript
        statisticsScript.Script(oldApkDir, newPackagename)
        del sys.modules['statisticsScript']
        sys.path.remove(targetDir)
    
    # advertisingScript
    advertisingScriptPath = targetDir + "/advertisingScript.pyc"
    if os.path.exists(advertisingScriptPath):
        sys.path.append(targetDir)
        import advertisingScript
        advertisingScript.Script(oldApkDir, newPackagename)
        del sys.modules['advertisingScript']
        sys.path.remove(targetDir)
    
    # pushScript
    pushScriptPath = targetDir + "/pushScript.pyc"
    if os.path.exists(pushScriptPath):
        sys.path.append(targetDir)
        import pushScript
        ret = pushScript.script(oldApkDir, newPackagename)
        del sys.modules['pushScript']
        lsPath = []
        for item in sys.path:
            if str(item) == str(targetDir):
                continue
            lsPath.append(item)
        sys.path = lsPath
    
    # sdk����ű�
    scriptPath = targetDir + "/script.pyc"
    if os.path.exists(scriptPath):
        sys.path.append(targetDir)
        import script
        ret = script.script(oldApkDir, newPackagename)
        del sys.modules['script']
        lsPath = []
        for item in sys.path:
            if str(item) == str(targetDir):
                continue
            lsPath.append(item)
        sys.path = lsPath
    
    ret = operate.pushIconIntoApk('', oldApkDir, channel)
    
    operate.modifyGameName(channel, oldApkDir)
    
    ret = operate.produceNewRFile(channel, newPackagename, oldApkDir)
    if ret:
        return
    
    # smali to dex
#     classesDexFile = oldApkDir + "/classes.dex"
#     ret = operate.smaliTrans2dex(SmaliDir, classesDexFile)
#     if ret:
#         return 
    #         if os.path.exists(SmaliDir):
    #             file_operate.delete_file_folder(SmaliDir)
    
    if splitDexFlag == True:
        print '+++++++++++++++++++++++++++++++++++++'
#         operate.splitDex(targetDir, oldApkDir)
        operate.splitDex_old(targetDir, oldApkDir)
        print '+++++++++++++++++++++++++++++++++++++'
        

    operate.rewriteYml(oldApkDir)    
    tempApkName = file_operate.getFullPath(constant.outDir) + "/apk_"+channel+"_unsigned.apk"
    ret = operate.recompileApk(oldApkDir, tempApkName)
    if ret:
        return
    keystoreFile = ConfigParse.shareInstance().getKeystoreFile()
    storepassword = ConfigParse.shareInstance().getKeystorePassword()
    alias = ConfigParse.shareInstance().getKeystoreAlias()
    aliasPasswd = ConfigParse.shareInstance().getKeystoreAliasPassword()
    # def signApk(apkFile, keyStore, storepassword, keyalias, aliaspassword):
    ret = operate.signApk(tempApkName, keystoreFile, storepassword, alias, aliasPasswd)
    print "sign"
    print ret
    if ret:
        return
    
    apkName = file_operate.getFullPath(constant.outDir) + "/apk_" + channel + ".apk" 
    ret = operate.alignAPK(tempApkName, apkName, file_operate.getFullPath(constant.outDir))
    
    ret = execGameCommonFinalizeScript(channel, platformId, appVersion, resVersion, checkBox_isChecked, checkBox_4_isChecked, checkBox_5_isChecked)
    if ret:
        print 'execGameCommonFinalizeScript error:'
        return
    taskManager.shareInstance().notify(channel, 100)
    print "----------------------------%s pack complete!------------------------" % channel
예제 #20
0
def openfilefolder():
        QDesktopServices.openUrl(QUrl(file_operate.getFullPath(ConfigParse.shareInstance().getOutApkDir()), QUrl.TolerantMode))
예제 #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)
예제 #22
0
def getGameSdkScriptPath():
    return getFullPath(constant.sdkRelatePath +
                       ConfigParse.shareInstance().getChannelName() +
                       "/gameSdkScript")
예제 #23
0
def getForManifestXmlPath():
    return getFullPath(constant.sdkRelatePath +
                       ConfigParse.shareInstance().getChannelName() +
                       "/ForManifest.xml")
예제 #24
0
def deleteWorkspace(channel):
    idChannel = channel['idChannel']
    workDir = file_operate.get_server_dir() + '/workspace/%s/%s' % (
        ConfigParse.shareInstance().getDBName(), idChannel)
    workDir = file_operate.getFullPath(workDir)
    file_operate.delete_file_folder(workDir)
    rlImg = Image.open(gameIconPath)

    if useMark:
        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 = file_operate.getFullPath(
            constant.sdkRelatePath + ConfigParse.shareInstance(
            ).getChannelName()) + '/icon_marks/' + markName + '.png'
        if not os.path.exists(markPath):
            return 1
        else:
            markIcon = Image.open(markPath)
            rlImg = appendIconMark(rlImg, markIcon, (0, 0))


#             rlImg.show()

    ldpiSize = (36, 36)
    mdpiSize = (48, 48)
    hdpiSize = (72, 72)
    xhdpiSize = (96, 96)
    xxhdpiSize = (144, 144)
    xxxhdpiSize = (512, 512)
예제 #26
0
파일: entry.py 프로젝트: YiFeng0755/Repack
def php_entry(arg):
    # 单例
    ConfigParse.shareInstance().initData(arg)

    from pack_managers.newengine_pack_manager import NewEnginePackManager
    NewEnginePackManager().run()
예제 #27
0
def getUIConfigXmlPath():
    return getFullPath(constant.sdkRelatePath +
                       ConfigParse.shareInstance().getChannelName() +
                       "/uiconfig.xml")
예제 #28
0
    def pack(self):
        try:
            log_utils.getLogger().info('generating new r file ... ')
            #重新生成R文件

            ret = cmd_tools.produceNewRFile(self._packageName,
                                            self.decompileDir)
            if ret:
                raise PackException(pack_exception.PRODUCE_NEW_R_FILE_FAILED,
                                    'produce new r file failed')

            #重新编译成apk
            tempRecompileApkDir = self.taskWorkDir + '/tempRecompileApk'
            tempRecompileApk = '%s/nosig.apk' % (tempRecompileApkDir)
            tempSignedApkName = '%s/_sig.apk' % (tempRecompileApkDir)

            log_utils.getLogger().info(
                'recompiling apk ... tempRecompileApk = ' + tempRecompileApk)
            ret = cmd_tools.recompileApk(self.decompileDir, tempRecompileApk,
                                         self.tmpApkToolPath)
            if ret:
                raise PackException(pack_exception.RECOMPILE_APK_FAILED,
                                    'recompile apk failed')

            # self.outputName是 autotest_xxx.apk
            self.doPackWithoutChannelSymbol(tempRecompileApk,
                                            tempSignedApkName, self.outputDir,
                                            self.outputName)

            #测试桩重打包
            import env
            testbundle_apkFile = os.path.join(
                env.SUPPORT_DIR, self._projectShorName,
                ConfigParse.shareInstance().getLuaVersion(), 'testbundle',
                'TestBundle.apk')
            #testbundle_apkFile = os.path.join(env.GOD_TOOL_DIR, 'TestBundle_base.apk')
            if not os.path.exists(testbundle_apkFile):
                raise PackException(
                    pack_exception.SOURCE_APK_NOT_EXIST,
                    'testbundle_base apk file %s does not exist' %
                    testbundle_apkFile)

            # 拷贝TestBundle.apk 到  工作目录下/testbundle_temp.apk
            tmpTestBundleApk = self.taskWorkDir + '/testbundle_temp.apk'
            my_utils.copyFile(testbundle_apkFile, tmpTestBundleApk)

            testbundle_decompileDir = self.taskWorkDir + '/testbundle_decompile'
            testbundle_tmpApkToolPath = os.path.join(self.taskWorkDir,
                                                     'testbundle_apktooltmp')

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

            log_utils.getLogger().info('decompiling testbundle apk ... ')

            #测试桩反编译 到   工作目录下/testbundle_decompile
            ret = cmd_tools.decompileApk(tmpTestBundleApk,
                                         testbundle_decompileDir,
                                         testbundle_tmpApkToolPath)
            if ret:
                raise PackException(
                    pack_exception.DECOMPLE_APK_FAILED,
                    'decompile testbundle apk %s failed' % tmpTestBundleApk)

            testbundle_packageName = "com.boyaa.application.testbundle"
            # 修改manifest.xml
            self.repackTestBundleForMatch(self.sdksRootDir,
                                          testbundle_decompileDir,
                                          self._packageName)

            log_utils.getLogger().info(
                'generating new r file for testbundle... ')
            #重新生成测试桩的R文件
            ret = cmd_tools.produceNewRFile(testbundle_packageName,
                                            testbundle_decompileDir)
            if ret:
                raise PackException(
                    pack_exception.PRODUCE_NEW_R_FILE_FAILED,
                    'produce new r file for testbundle failed')

            #重新编译测试桩apk
            testbundle_tempRecompileApkDir = self.taskWorkDir + '/testbundle_tempRecompileApk'
            testbundle_tempRecompileApk = '%s/testbundle_nosig.apk' % (
                testbundle_tempRecompileApkDir)
            testbundle_tempSignedApkName = '%s/testbundle_sig.apk' % (
                testbundle_tempRecompileApkDir)

            log_utils.getLogger().info(
                'recompiling apk ... tempRecompileApk = ' +
                testbundle_tempRecompileApk)
            ret = cmd_tools.recompileApk(testbundle_decompileDir,
                                         testbundle_tempRecompileApk,
                                         testbundle_tmpApkToolPath)
            if ret:
                raise PackException(pack_exception.RECOMPILE_APK_FAILED,
                                    'recompile test bundle apk failed')

            self.doPackWithoutChannelSymbol(
                testbundle_tempRecompileApk, testbundle_tempSignedApkName,
                os.path.join(self.outputDir, 'testbundle'), "testbundle.apk")

            #log_utils.getLogger().info('doPack: =============================================success=============================================' + StreamHandler.terminator)

        except PackException as pe:
            log_utils.getLogger().error(pe)
            #log_utils.getLogger().info('doPack: =============================================Failed=============================================' + StreamHandler.terminator)
            return
예제 #29
0
def getVersionName():
    return ConfigParse.shareInstance().getVersionName()
예제 #30
0
def main(channel):
    idChannel = channel.get('idChannel')
    channelName = channel.get('name')
    channelNum = channel.get('channelNum')
    threading.currentThread().setName(idChannel)
    taskManager.shareInstance().notify(idChannel, 20)
    source = ConfigParse.shareInstance().getSource()
    basename = os.path.basename(source)
    exttuple = os.path.splitext(basename)
    basename = exttuple[0]
    extname = exttuple[1]
    originDir = ConfigParse.shareInstance().getProjFolder()
    useSDK = ConfigParse.shareInstance().getProjSDKVersion()
    systemSDKPath = ConfigParse.shareInstance().getProjSDKPath()
    ipaPackage = ConfigParse.shareInstance().getProjIpaPackage()
    game = ConfigParse.shareInstance().getCurrentGame()
    if channelName is None:
        error_operate.error(5)
        return
    versionName = ConfigParse.shareInstance().getVersionName()
    outputDir = ConfigParse.shareInstance().getOutputDir()
    if outputDir == '':
        outputDir = '../'
    #cocos2dx need cocos2dx framework,so we must put release pdroject to cocos2dx dictionary
    #outputDir += '/' + game['gameName'] + '/' + versionName + '/' + channel['name']
    outputDir += '/' + channel['name'] + '_' + versionName

    outputDir = file_operate.getFullPath(outputDir)
    outputDir = os.path.realpath(outputDir)
    file_operate.delete_file_folder(outputDir)
    #workDir = outputDir + '/Project_iOS'
    workDir = outputDir
    workDir = file_operate.getFullPath(workDir)
    workDir = os.path.realpath(workDir)
    file_operate.delete_file_folder(workDir)
    iconDir = '../workspace/icon/' + channelNum
    iconDir = file_operate.getFullPath(iconDir)
    iconDir = os.path.realpath(iconDir)
    if not os.path.exists(outputDir):
        os.makedirs(outputDir)
    if not os.path.exists(workDir):
        os.makedirs(workDir)
    file_operate.copyFiles(originDir, workDir)
    pbxFile = workDir + '/' + ConfigParse.shareInstance().getProjXcode(
    ) + '/project.pbxproj'
    target_name = None
    project = XcodeProject.Load(pbxFile)
    #从congfig.py里的getTargetName取到要编译打包的target,没有的话用默认的最后一个target
    if ConfigParse.shareInstance().getTargetName():
        target_name = project_name = ConfigParse.shareInstance().getTargetName(
        )
        print '----config ---- target name ----' + target_name
#        print 'ERROR_>'+target_name+'<_ERROR'
#        print 'WARNING_>'+target_name+'<_WARNING'
    else:
        target_name = project_name = project.get_target_name()

    project_config = project.get_configurations()
    #use release archieve ipa
    project_config = 'Release'
    project.add_other_ldflags('-ObjC')
    project.showSearchPathInfo()
    """add other flag param"""
    #project.add_other_ldflags('-lz')

    if project.modified:
        project.save()
    taskManager.shareInstance().notify(idChannel, 40)
    parentDir = ''
    for parent, dirnames, filenames in os.walk(workDir):
        for filename in filenames:
            if filename == 'Contents.json':
                if parent.find('Images.xcassets/AppIcon.appiconset') != -1:
                    parentDir = parent

    if parentDir != '':
        for parent, dirnames, filenames in os.walk(parentDir):
            for filename in filenames:
                if filename != 'Contents.json':
                    os.remove(parentDir + '/' + filename)

        jsonFile = open(parentDir + '/Contents.json')
        jsonContent = json.load(jsonFile)
        for child in jsonContent['images']:
            imgSize = int(child['size'][0:child['size'].find('x')]) * int(
                child['scale'][0:child['scale'].find('x')])
            imgName = 'Icon-' + str(imgSize) + '.png'
            if os.path.exists(iconDir + '/' +
                              imgName) and not os.path.exists(parentDir + '/' +
                                                              imgName):
                file_operate.copyFile(iconDir + '/' + imgName,
                                      parentDir + '/' + imgName)
            child['filename'] = imgName

        jsonContent = json.dumps(jsonContent)
        jsonFile.close()
        jsonFile = open(parentDir + '/Contents.json', 'w')
        try:
            jsonFile.write(jsonContent)
        finally:
            jsonFile.close()

    project_infoplist = workDir + '/' + ConfigParse.shareInstance(
    ).getProjXcode() + '/../' + project.get_infoplistfile()
    newAppName = ''
    if game.get(
            'isModifyiOSName') is not None and game['isModifyiOSName'] == True:
        newAppName = ConfigParse.shareInstance().getIosName()
        if newAppName is None or newAppName == '':
            newAppName = game.get('gameName')
    #set display name by channel
    if channel['display_name'] != '':
        newAppName = channel['display_name']

    customBundleId = channel['r_bundle_id']
    if os.path.exists(project_infoplist) and (
            newAppName != '' or channel['packNameSuffix'] != ''
            or channel['r_gameversion'] != ''
            or channel['r_gameversion_build'] != '' or customBundleId != ''):
        plistModify = False
        try:
            plist = readPlist(project_infoplist)
            for key in plist:
                if key == 'CFBundleName' and newAppName != '':
                    plist['CFBundleName'] = newAppName
                    plistModify = True
                elif key == 'CFBundleIdentifier':
                    if customBundleId == '':
                        plist['CFBundleIdentifier'] = plist[
                            'CFBundleIdentifier'] + channel['packNameSuffix']
                    else:
                        plist['CFBundleIdentifier'] = customBundleId
                    plistModify = True
                elif key == 'CFBundleShortVersionString' and channel[
                        'r_gameversion'] != '':
                    plist['CFBundleShortVersionString'] = channel[
                        'r_gameversion']
                    plistModify = True
                elif key == 'CFBundleVersion' and channel[
                        'r_gameversion_build'] != '':
                    plist['CFBundleVersion'] = channel['r_gameversion_build']
                    plistModify = True

            if plistModify == True:
                try:
                    writePlist(plist, project_infoplist)
                    project.modify_bundle_identifier(
                        plist['CFBundleIdentifier'])
                    project.save()
                except Exception as e:
                    print 'modify bundle Id/bundle Name Error:' + e

        except:
            print 'No Plist found'

    writeChannelInfoIntoDevelopInfo(workDir, channel, game)
    writeSupportInfo(workDir)
    SDKWorkDir = workDir + '/sdk/'
    list = [0, 2, 1, 3, 4, 5, 6]
    for count in range(len(list)):
        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
            for plugin in SDK['pluginLs']:
                type = plugin['typePlugin']
                if type == list[count]:
                    SDKSrcDir = '../config/sdk/' + SDK['SDKName']
                    SDKSrcDir = file_operate.getFullPath(SDKSrcDir)
                    SDKDestDir = SDKWorkDir + SDK['SDKName']
                    SDKDestDir = os.path.realpath(SDKDestDir)
                    if os.path.exists(SDKDestDir):
                        continue
                    file_operate.copyFiles(SDKSrcDir, SDKDestDir)
                    lib_path = 'sdk/' + SDK['SDKName'] + '/'
                    project = XcodeProject.Load(pbxFile)
                    scriptPath = SDKDestDir + '/script.pyc'
                    if os.path.exists(scriptPath):
                        sys.path.append(SDKDestDir)
                        import script
                        script.script(SDK, workDir, target_name, usrSDKConfig,
                                      SDKDestDir, project)
                        del sys.modules['script']
                        sys.path.remove(SDKDestDir)
                    if os.path.exists(SDKDestDir + '/Frameworks'):
                        addFrameworkGroupPath(SDKDestDir + '/Frameworks',
                                              target_name, project)

                    if os.path.exists(SDKDestDir + '/Resources'):
                        for res in os.listdir(SDKDestDir + '/Resources'):
                            project.add_file(SDKDestDir + '/Resources/' + res,
                                             None, 'SOURCE_ROOT', True, False,
                                             False, target_name)

                    if os.path.exists(SDKDestDir + '/Codes'):
                        for codes in os.listdir(SDKDestDir + '/Codes'):
                            project.add_file(SDKDestDir + '/Codes/' + codes,
                                             None, 'SOURCE_ROOT', True, False,
                                             False, target_name)

                    if project.modified:
                        project.save()
                    xmlFile = SDKDestDir + '/config.xml'
                    doc = minidom.parse(xmlFile)
                    rootNode = doc.documentElement
                    sysFrameworksList = rootNode.getElementsByTagName(
                        'sysFrameworks')
                    for sysFrameworksNode in sysFrameworksList:
                        path = ''
                        required = False
                        if sysFrameworksNode.getAttribute('required') == '0':
                            required = True
                        if sysFrameworksNode.getAttribute(
                                'path') == 'xcodeFrameworks':
                            path = systemSDKPath + '/System/Library/Frameworks/' + sysFrameworksNode.getAttribute(
                                'name')
                        elif sysFrameworksNode.getAttribute(
                                'path') == 'xcodeUsrlib':
                            path = systemSDKPath + '/usr/lib/'
                            frameworkName = sysFrameworksNode.getAttribute(
                                'name')
                            #if ios 9 and above,replace .dylib to .tbd
                            if isIOS9(systemSDKPath):
                                print 'use ios 9 sdk for' + sysFrameworksNode.getAttribute(
                                    'name')
                                path = path + frameworkName.replace(
                                    '.dylib', '.tbd')
                            else:
                                path = path + frameworkName
                                print 'donot use ios 9 sdk'
                        else:
                            path = sysFrameworksNode.getAttribute(
                                'path') + sysFrameworksNode.getAttribute(
                                    'name')
                        ret = project.add_file_if_doesnt_exist(
                            path, None, 'SOURCE_ROOT', True, required, False,
                            target_name)

                        if project.modified:
                            project.save()

                    for child in SDK['operateLs']:
                        if child['name'] == 'RemoveValidArchs_arm64':
                            project.modify_validarchs()
                            if project.modified:
                                project.save()

                    generateDeveloperInfo(channel, SDK, usrSDKConfig, workDir,
                                          game)
                    generatePluginInfo(SDK, usrSDKConfig, workDir)

    if os.path.exists(workDir + '/supportPlugin.xml'):
        encode_operate.xmlEncode(workDir + '/supportPlugin.xml')
        project.add_file(workDir + '/supportPlugin.xml', None, 'SOURCE_ROOT',
                         True, False, False, target_name)
        if project.modified:
            project.save()
    if os.path.exists(workDir + '/developerInfo.xml'):
        encode_operate.xmlEncode(workDir + '/developerInfo.xml')
        project.add_file(workDir + '/developerInfo.xml', None, 'SOURCE_ROOT',
                         True, False, False, target_name)
        if project.modified:
            project.save()
        taskManager.shareInstance().notify(idChannel, 70)
    if ipaPackage != 'True':
        taskManager.shareInstance().notify(idChannel, 100)
        return
    xcodeDir = workDir + '/' + ConfigParse.shareInstance().getProjXcode(
    ) + '/../'
    xcodeDir = os.path.realpath(xcodeDir)
    print 'XcodeDir ' + xcodeDir
    #change dictionary first,then run build command
    os.chdir(xcodeDir)
    mode = 0
    if useSDK.find('simulator') == -1:
        mode = 1
    cmd = None
    projectFileName = ConfigParse.shareInstance().getProjXcode().replace(
        '/', '')
    if mode == 0:
        cmd = 'xcodebuild ' + useSDK + ' -target ' + target_name + ' -arch i386 >xcodebuild.txt'
    else:
        #clean project and target
        cmd = 'xcodebuild clean ' + useSDK + ' -project ' + projectFileName + ' -target ' + target_name
        ret = file_operate.execFormatCmd(cmd)
        #don't build. use archieve
        cmd = 'xcodebuild ' + useSDK + ' -target ' + target_name + '>xcodebuild.txt'
        #cmd = 'xcodebuild archive -scheme ' + target_name + '  -target ' + target_name + ' -archivePath ' + target_name + '.xcarchive >xcodearchive.txt'

    ret = file_operate.execFormatCmd(cmd)
    buildFile = workDir + '/xcodebuild.txt'
    if not os.path.exists(buildFile):
        print 'file not exists'
    else:
        file_object = open(buildFile)
        try:
            buildText = file_object.read()
            print buildText.find('BUILD SUCCEEDED')
            if buildText.find('BUILD SUCCEEDED') < 0:
                print 'BUILD FAILED!'
                error_operate.error(200)
                return
        finally:
            file_object.close()

    # ret = file_operate.execFormatCmd(cmd)
    # buildFile = workDir + '/xcodearchive.txt'
    # if not os.path.exists(buildFile):
    #     print 'file not exists'
    # else:
    #     file_object = open(buildFile)
    #     try:
    #         buildText = file_object.read()
    #         print buildText.find('** ARCHIVE SUCCEEDED **')
    #         if buildText.find('** ARCHIVE SUCCEEDED **') < 0:
    #             print 'ARCHIVE FAILED!'
    #             error_operate.error(200)
    #             return
    #     finally:
    #         file_object.close()

    appDir = None
    if mode == 0:
        appDir = project_config + '-iphonesimulator/'
    else:
        appDir = project_config + '-iphoneos/'
    ipaName = target_name + '_' + channelName + '_' + versionName + '.ipa'
    #use xcodebuild exportArchieve export ipa.this code don't contain Symbols.
    cmd = 'xcrun -sdk iphoneos PackageApplication -v ' + '"' + xcodeDir + '/build/' + appDir + project_name + '.app" -o "' + outputDir + '/' + ipaName + '"'
    #cmd = 'xcodebuild -exportArchive -archivePath ' + target_name + '.xcarchive -exportPath "' + xcodeDir + '" -exportFormat ipa >exportarchieve.txt'
    ret = file_operate.execFormatCmd(cmd)
    taskManager.shareInstance().notify(idChannel, 100)