package_utils.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. # 安卓游戏打包脚本
  2. # 1.用apktool解包
  3. # 2.复制res资源、assets资源、jniLib资源
  4. # 3.修改包名、app名、渠道文件
  5. # 4.添加app icon、合并AndroidManifest文件
  6. # 5.添加app启动图,修改AndroidManifest文件
  7. # 6.生成新的R文件
  8. # 7.将新的R文件编译,生成dex,再用baksmali生成smali,替换旧的R文件
  9. # 8.将jar资源打包成dex,再用baksmali生成smali,拷贝到smali目录下
  10. # 9.统计方法量,并分割dex(将smali文件拷贝到目录smali_classes2)
  11. # 10.用apktool回包
  12. # 11.重新签名
  13. import file_utils
  14. import xml_utils
  15. import smali_utils
  16. import config_utils
  17. import game_utils
  18. import os
  19. import os.path
  20. import json
  21. import sys
  22. import importlib
  23. import uuid
  24. import zipfile
  25. ignoreLauncher = ['jm_ysdk', 'jm_yijie', 'jm_quick', 'jm_beiyu', 'jm_xq_jrtt']
  26. def pack(game, sdk, config):
  27. config['cache'] = uuid.uuid1()
  28. subChannel = config['subChannel']
  29. # 解包
  30. ret = decomplie(game, sdk, subChannel, config)
  31. if ret:
  32. return ret
  33. # 删除旧代码
  34. ret = removeOldCode(game, sdk, subChannel, config)
  35. if ret:
  36. return ret
  37. # 删除一些不支持的属性
  38. ret = removeNoSupportAttr(game, sdk, subChannel, config)
  39. if ret:
  40. return ret
  41. # 删除一些不支持的配置
  42. ret = fixUnSupportConfig(game, sdk, subChannel, config)
  43. if ret:
  44. return ret
  45. # 合并Drawable-v4目录
  46. ret = mergeDrawableRes(game, sdk, subChannel, config)
  47. if ret:
  48. return ret
  49. # 移除相同的资源
  50. ret = removeSameRes(game, sdk, subChannel, config)
  51. if ret:
  52. return ret
  53. # 复制res资源
  54. ret = copyRes(game, sdk, subChannel, config)
  55. if ret:
  56. return ret
  57. # 合并主文件
  58. ret = mergeManifestRes(game, sdk, subChannel, config)
  59. if ret:
  60. return ret
  61. # 替换占位符
  62. ret = changePlaceholders(game, sdk, subChannel, config)
  63. if ret:
  64. return ret
  65. # 添加meta-data
  66. ret = addMetaData(game, sdk, subChannel, config)
  67. if ret:
  68. return ret
  69. # 增加配置文件
  70. ret = addConfig(game, sdk, subChannel, config)
  71. if ret:
  72. return ret
  73. # 复制app res资源
  74. ret = copyAppRes(game, sdk, subChannel, config)
  75. if ret:
  76. return ret
  77. # 更改包名
  78. if 'packageName' in config and config['packageName'] != '':
  79. ret = changePackageName(game, sdk, subChannel, config)
  80. if ret:
  81. return ret
  82. # 更改app名
  83. if 'name' in config and config['name'] != '':
  84. ret = changeAppName(game, sdk, subChannel, config)
  85. if ret:
  86. return ret
  87. # 更改app icon
  88. if config['changeIcon']:
  89. ret = changeAppIcon(game, sdk, subChannel, config)
  90. if ret:
  91. return ret
  92. # 添加启动图操作
  93. if config['addLauncher']:
  94. ret = addLauncher(game, sdk, subChannel, config)
  95. if ret:
  96. return ret
  97. # 添加多图标
  98. #ret = addMoreIcon(game, sdk, subChannel, config)
  99. #if ret:
  100. # return ret
  101. # 打包lib依赖
  102. ret = packJar(game, sdk, subChannel, config)
  103. if ret:
  104. return ret
  105. # sdk脚本处理
  106. ret = doSDKPostScript(game, sdk, config)
  107. if ret:
  108. return ret
  109. # 乐变sdk的特殊处理
  110. ret = game_utils.sdkLebianChange(game, sdk, config)
  111. if ret:
  112. return ret
  113. # 游戏脚本处理
  114. ret = doGamePostScript(game, sdk, config)
  115. if ret:
  116. return ret
  117. # log sdk
  118. if 'logSdk' in config:
  119. for log in config['logSdk']:
  120. ret = addLogSdk(game, sdk, subChannel, config, log)
  121. if ret:
  122. return ret
  123. # 生成R文件
  124. '''ret = generateNewRFile(game, sdk, subChannel, config)
  125. if ret:
  126. return ret'''
  127. # 添加MultiDex支持
  128. if config['splitDex']:
  129. ret = splitDex(game, sdk, subChannel, config)
  130. if ret:
  131. return ret
  132. # 更改版本号
  133. ret = changeVersion(game, sdk, subChannel, config)
  134. if ret:
  135. return ret
  136. # 回编译
  137. ret = recomplie(game, sdk, subChannel, config)
  138. if ret:
  139. return ret
  140. # 对齐apk
  141. ret = alignApk(game, sdk, subChannel, config)
  142. if ret:
  143. return ret
  144. # 签名
  145. ret = apksignerApk(game, sdk, subChannel, config)
  146. if ret:
  147. return ret
  148. # 添加渠道信息
  149. ret = addChannel(game, sdk, subChannel, config)
  150. if ret:
  151. return ret
  152. # 清理产生的中间文件
  153. if config['clearCache']:
  154. clearTemp(game, sdk, subChannel, config)
  155. return 0
  156. def decomplie(game, sdk, subChannel, config):
  157. '''
  158. 解包
  159. '''
  160. apktoolPath = file_utils.getApkToolPath()
  161. gamePath = file_utils.getFullGameApk(game)
  162. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  163. if os.path.exists(decompliePath):
  164. print('delete decomplie folder...')
  165. file_utils.deleteFolder(decompliePath)
  166. print('decomplie apk...')
  167. return file_utils.execJarCmd(apktoolPath, 'd -f "%s" -o "%s"' % (gamePath, decompliePath))
  168. def removeOldCode(game, sdk, subChannel, config):
  169. '''
  170. 删除旧代码
  171. '''
  172. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  173. codePath = os.path.join(decompliePath, 'smali', 'com', 'jmhy', 'sdk')
  174. #file_utils.deleteFolder(codePath)
  175. allFiles = []
  176. allFiles = file_utils.list_files(codePath, allFiles)
  177. for f in allFiles:
  178. fpath, fname = os.path.split(f) #分离文件名和路径
  179. if fname == 'R.smali' or fname.startswith('R$'):
  180. continue
  181. os.remove(f)
  182. print('remove %s' % f)
  183. return 0
  184. def copyRes(game, sdk, subChannel, config):
  185. '''
  186. 复制res资源
  187. '''
  188. # 拷贝sdk资源
  189. print('copy res...')
  190. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  191. sdkPath = file_utils.getFullSDKPath(sdk)
  192. resPath = os.path.join(sdkPath, 'res')
  193. decomplieResPath = file_utils.getFullPath(decompliePath, 'res')
  194. for d in os.listdir(resPath):
  195. copyResWithType(resPath, decomplieResPath, d)
  196. # 拷贝assets
  197. print('copy assets...')
  198. assetsPath = file_utils.getFullPath(sdkPath, 'assets')
  199. decomplieAssetsPath = file_utils.getFullPath(decompliePath, 'assets')
  200. if os.path.exists(assetsPath):
  201. ret = file_utils.copyFileAllDir(assetsPath, decomplieAssetsPath)
  202. if ret:
  203. return ret
  204. # 拷贝jniLib
  205. print('copy jniLibs...')
  206. jniPath = file_utils.getFullPath(sdkPath, 'jniLibs')
  207. decomplieJniPath = file_utils.getFullPath(decompliePath, 'lib')
  208. abiFilters = []
  209. if os.path.exists(decomplieJniPath):
  210. for abi in os.listdir(decomplieJniPath):
  211. if abi == 'armeabi-v7a' or abi == 'armeabi':
  212. abiFilters.append(abi)
  213. else:
  214. abiFilters = ['armeabi-v7a']
  215. if os.path.exists(jniPath):
  216. ret = file_utils.copyFileAllDir(jniPath, decomplieJniPath, False, abiFilters)
  217. if ret:
  218. return ret
  219. return 0
  220. def mergeDrawableRes(game, sdk, subChannel, config):
  221. '''
  222. 合并Drawable-v4目录
  223. '''
  224. print('merge drawable path...')
  225. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  226. resPath = os.path.join(decompliePath, 'res')
  227. for path in os.listdir(resPath):
  228. print('res path %s' % path)
  229. if (path.startswith('drawable') or path.startswith('mipmap')) and path.endswith('-v4'):
  230. print('merge path %s' % path)
  231. v4DrawablePath = os.path.join(resPath, path)
  232. drawablePath = os.path.join(resPath, path[:-3])
  233. if os.path.exists(drawablePath):
  234. ret = file_utils.copyFileAllDir(v4DrawablePath, drawablePath, True)
  235. if ret:
  236. return ret
  237. else:
  238. os.rename(v4DrawablePath, drawablePath)
  239. return 0
  240. def removeSameRes(game, sdk, subChannel, config):
  241. '''
  242. 移除相同的资源
  243. '''
  244. # 读取sdk的资源
  245. print('remove same res...')
  246. sdkPath = file_utils.getFullSDKPath(sdk)
  247. sdkResPath = os.path.join(sdkPath, 'res')
  248. resList = []
  249. for path in os.listdir(sdkResPath):
  250. if not path.startswith('values'):
  251. continue
  252. absPath = os.path.join(sdkResPath, path)
  253. for resFile in os.listdir(absPath):
  254. '''if not resFile.startswith('jm_'):
  255. continue'''
  256. resList = xml_utils.readAllRes(os.path.join(absPath, resFile), resList)
  257. if len(resList) == 0:
  258. print('no same res found')
  259. return 0
  260. # 移除相同的资源
  261. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  262. resPath = os.path.join(decompliePath, 'res')
  263. for path in os.listdir(resPath):
  264. if not path.startswith('values'):
  265. continue
  266. absPath = os.path.join(resPath, path)
  267. for resFile in os.listdir(absPath):
  268. xml_utils.removeSameRes(os.path.join(absPath, resFile), resList)
  269. return 0
  270. def mergeManifestRes(game, sdk, subChannel, config):
  271. '''
  272. 合并主文件
  273. '''
  274. print('merge AndroidManifest...')
  275. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  276. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  277. sdkPath = file_utils.getFullSDKPath(sdk)
  278. libManifest = file_utils.getFullPath(sdkPath, 'manifest.xml')
  279. return xml_utils.mergeManifestRes(manifest, libManifest)
  280. def copyAppRes(game, sdk, subChannel, config):
  281. '''
  282. 拷贝app的资源,比如app icon、启动图等
  283. '''
  284. channelPath = file_utils.getSubChannelPath(game, sdk, subChannel)
  285. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  286. # assets
  287. print('copy assets...')
  288. assetsPath = file_utils.getFullPath(channelPath, 'assets')
  289. decomplieAssetsPath = file_utils.getFullPath(decompliePath, 'assets')
  290. if os.path.exists(assetsPath):
  291. ret = file_utils.copyFileAllDir(assetsPath, decomplieAssetsPath)
  292. if ret:
  293. return ret
  294. # icon
  295. print('copy icon...')
  296. ret = copyAppResWithType(decompliePath, channelPath, 'icon')
  297. if ret:
  298. return ret
  299. # 启动图
  300. print('copy splash...')
  301. ret = copyAppResWithType(decompliePath, channelPath, 'splash')
  302. if ret:
  303. return ret
  304. # 其他图片
  305. print('copy image...')
  306. ret = copyAppResWithType(decompliePath, channelPath, 'image')
  307. if ret:
  308. return ret
  309. return 0
  310. def copyAppResWithType(decompliePath, channelPath, typeName):
  311. decomplieResPath = os.path.join(decompliePath, 'res')
  312. iconPath = os.path.join(channelPath, typeName)
  313. if not os.path.exists(iconPath):
  314. print('dir "%s" not exists' % iconPath)
  315. return 0
  316. for d in os.listdir(iconPath):
  317. ret = copyResWithType(iconPath, decomplieResPath, d)
  318. if ret:
  319. return ret
  320. return 0
  321. def copyResWithType(resPath, decomplieResPath, typeName):
  322. # appt的打包目录会带-v4后缀
  323. resDir = os.path.join(resPath, typeName)
  324. target = os.path.join(decomplieResPath, typeName)
  325. targetV4 = os.path.join(decomplieResPath, typeName + '-v4')
  326. if not os.path.exists(target) and not os.path.exists(targetV4):
  327. os.makedirs(target)
  328. return file_utils.copyFileAllDir(resDir, target, False)
  329. elif not os.path.exists(target):
  330. return file_utils.copyFileAllDir(resDir, targetV4, False)
  331. else:
  332. return file_utils.copyFileAllDir(resDir, target, False)
  333. def removeNoSupportAttr(game, sdk, subChannel, config):
  334. '''
  335. 删除一些不支持的属性
  336. '''
  337. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  338. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  339. xml_utils.removeRootAttr(manifest, 'compileSdkVersion')
  340. xml_utils.removeRootAttr(manifest, 'compileSdkVersionCodename')
  341. return 0
  342. def fixUnSupportConfig(game, sdk, subChannel, config):
  343. '''
  344. 删除一些不支持的配置
  345. '''
  346. # 检查minSdkVersion
  347. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  348. yml = os.path.join(decompliePath, 'apktool.yml')
  349. minSdkVersion = 15
  350. file_utils.changeMinSdkVersion(yml, minSdkVersion)
  351. resPath = os.path.join(decompliePath, 'res')
  352. tag = '-v'
  353. for res in os.listdir(resPath):
  354. print('res = ' + res)
  355. if res.startswith('values') and tag in res:
  356. start = res.index(tag)
  357. version = res[start+len(tag):]
  358. if not version.isdigit():
  359. continue
  360. version = int(version)
  361. print('version = %d' % version)
  362. if version < minSdkVersion:
  363. unSopportPath = os.path.join(resPath, res)
  364. print('unSopportPath = ' + unSopportPath)
  365. file_utils.deleteFolder(unSopportPath)
  366. print('deleteFolder = ' + unSopportPath)
  367. return 0
  368. def changePackageName(game, sdk, subChannel, config):
  369. '''
  370. 更改包名
  371. '''
  372. # 全局替换AndroidManifest里面的包名
  373. newPackageName = config['packageName']
  374. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  375. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  376. packageName = xml_utils.getPackageName(manifest)
  377. xml_utils.changePackageName(manifest, newPackageName)
  378. print('change package name %s --> %s' % (packageName, newPackageName))
  379. return 0
  380. def changeAppName(game, sdk, subChannel, config):
  381. '''
  382. 更改app名
  383. '''
  384. # 生成string.xml文件
  385. name = config['name']
  386. resName = 'common_sdk_name'
  387. if 'outName' in config:
  388. resName = resName + '_' + config['outName']
  389. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  390. stringFile = os.path.join(decompliePath, 'res', 'values', 'sdk_strings_temp.xml')
  391. content = '<?xml version="1.0" encoding="utf-8"?><resources><string name="%s">%s</string></resources>' % (resName, name)
  392. file_utils.createFile(stringFile, content)
  393. # 修改主文件的app名的值
  394. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  395. xml_utils.changeAppName(manifest, '@string/%s' % resName)
  396. print('change app name %s' % name)
  397. return 0
  398. def changeAppIcon(game, sdk, subChannel, config):
  399. '''
  400. 更改app icon
  401. '''
  402. print('change app icon...')
  403. resName = 'common_sdk_icon'
  404. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  405. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  406. xml_utils.changeAppIcon(manifest, '@mipmap/%s' % resName)
  407. return 0
  408. def addMetaData(game, sdk, subChannel, config):
  409. '''
  410. 添加meta-data
  411. '''
  412. if 'metaData' not in config:
  413. return 0
  414. print('add meta-data...')
  415. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  416. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  417. xml_utils.addMetaData(manifest, config['metaData'])
  418. return 0
  419. def addConfig(game, sdk, subChannel, config):
  420. '''
  421. 添加config.json
  422. '''
  423. if 'configData' not in config:
  424. return 0
  425. print('add config.json...')
  426. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  427. configJson = os.path.join(decompliePath, 'assets', 'jmhy_config.json')
  428. jsonText = json.dumps(config['configData'], ensure_ascii=False)
  429. file_utils.createFile(configJson, jsonText)
  430. return 0
  431. def changePlaceholders(game, sdk, subChannel, config):
  432. '''
  433. 处理掉占位符
  434. '''
  435. if 'placeholders' not in config:
  436. return 0
  437. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  438. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  439. placeholders = config['placeholders']
  440. for placeholder in placeholders:
  441. oldText = '${%s}' % placeholder
  442. newText = placeholders[placeholder]
  443. print('change placeholder %s -> %s' % (oldText, newText))
  444. file_utils.replaceContent(manifest, oldText, newText)
  445. return 0
  446. def addLauncher(game, sdk, subChannel, config):
  447. '''
  448. 添加启动图
  449. '''
  450. # ysdk的特殊处理
  451. if sdk in ignoreLauncher:
  452. return 0
  453. channelPath = file_utils.getSubChannelPath(game, sdk, subChannel)
  454. splashPath = os.path.join(channelPath, 'splash')
  455. if len(os.listdir(splashPath)) == 0:
  456. print('dir splash is empty')
  457. return 0
  458. print('add launcher...')
  459. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  460. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  461. activity = xml_utils.getLauncherActivityName(manifest)
  462. if activity == 'com.jmhy.sdk.template.LauncherActivity':
  463. print('add launcher already exist...')
  464. return 1
  465. # 添加关联资源
  466. internalPath = file_utils.getFullInternalPath()
  467. ret = copyAppResWithType(decompliePath, internalPath, 'launcher_res')
  468. if ret:
  469. return ret
  470. # 拷贝代码
  471. print('copy launcher code...')
  472. codePath = os.path.join(internalPath, 'launcher_code', 'smali')
  473. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  474. ret = file_utils.copyFileAllDir(codePath, smaliPath)
  475. if ret:
  476. return ret
  477. # 修改主文件信息
  478. print('change launcher config...')
  479. orientation = xml_utils.getScreenOrientation(manifest)
  480. activity = xml_utils.removeLauncherActivity(manifest)
  481. xml_utils.addLauncherActivity(manifest, orientation, 'com.jmhy.sdk.template.LauncherActivity')
  482. # 修改跳转的
  483. launcherActivity = os.path.join(decompliePath, 'smali', 'com', 'jmhy', 'sdk', 'template', 'LauncherActivity.smali')
  484. file_utils.replaceContent(launcherActivity, '{class}', activity)
  485. print('change launcher %s to %s' % (activity, 'com.jmhy.sdk.template.LauncherActivity'))
  486. # config['oldLauncher'] = activity
  487. if 'launcherTime' in config:
  488. timeHex = formatHex(config['launcherTime'])
  489. file_utils.replaceContent(launcherActivity, '0x0BB8', timeHex)
  490. return 0
  491. def addMoreIcon(game, sdk, subChannel, config):
  492. '''
  493. 添加多个图标
  494. '''
  495. print('add more icon support...')
  496. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  497. icon = '@mipmap/common_sdk_icon'
  498. if not config['changeIcon']:
  499. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  500. icon = xml_utils.getApplicationAttr(manifest, 'icon')
  501. switchIcon = icon
  502. if config['switchIcon']:
  503. switchIcon = '@mipmap/common_sdk_icon2'
  504. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  505. return xml_utils.addMoreIcon(manifest, icon, switchIcon)
  506. def formatHex(millisecond):
  507. '''
  508. 将毫秒转为16进制,4位格式
  509. '''
  510. timeHex = str(hex(millisecond)).upper()
  511. timeHex = timeHex[2:]
  512. formatHex = ''
  513. if len(timeHex) == 3:
  514. formatHex = '0x0' + timeHex
  515. elif len(timeHex) == 4:
  516. formatHex = '0x' + timeHex
  517. else:
  518. formatHex = '0x0BB8'
  519. return formatHex
  520. def doSDKPostScript(game, sdk, config):
  521. '''
  522. 执行sdk相关特殊处理脚本
  523. '''
  524. sdkPath = file_utils.getFullSDKPath(sdk)
  525. scriptPath = os.path.join(sdkPath, 'script')
  526. targetScript = os.path.join(scriptPath, 'sdk_script.py')
  527. if not os.path.exists(targetScript):
  528. print('sdk_script no exists')
  529. return 0
  530. print('doSDKPostScript...')
  531. sys.path.append(scriptPath)
  532. module = importlib.import_module('sdk_script')
  533. ret = module.execute(game, sdk, config)
  534. sys.path.remove(scriptPath)
  535. return ret
  536. def doGamePostScript(game, sdk, config):
  537. '''
  538. 执行游戏相关特殊处理脚本
  539. '''
  540. channelPath = file_utils.getFullGamePath(game)
  541. scriptPath = os.path.join(channelPath, 'script')
  542. targetScript = os.path.join(scriptPath, 'game_script.py')
  543. if not os.path.exists(targetScript):
  544. print('game_script no exists')
  545. return 0
  546. print('doGamePostScript...')
  547. sys.path.append(scriptPath)
  548. module = importlib.import_module('game_script')
  549. ret = module.execute(game, sdk, config)
  550. sys.path.remove(scriptPath)
  551. return ret
  552. def addLogSdk(game, sdk, subChannel, config, logSdk):
  553. # 拷贝jniLibs
  554. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  555. sdkPath = file_utils.getFullLogSDKPath(logSdk)
  556. print('copy log jniLibs...')
  557. jniPath = file_utils.getFullPath(sdkPath, 'jniLibs')
  558. decomplieJniPath = file_utils.getFullPath(decompliePath, 'lib')
  559. abiFilters = []
  560. if os.path.exists(decomplieJniPath):
  561. for abi in os.listdir(decomplieJniPath):
  562. if abi == 'armeabi-v7a' or abi == 'armeabi':
  563. abiFilters.append(abi)
  564. else:
  565. abiFilters = ['armeabi-v7a']
  566. if os.path.exists(jniPath):
  567. ret = file_utils.copyFileAllDir(jniPath, decomplieJniPath, False, abiFilters)
  568. if ret:
  569. return ret
  570. print('merge log AndroidManifest...')
  571. libManifest = file_utils.getFullPath(sdkPath, 'manifest.xml')
  572. if os.path.exists(libManifest):
  573. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  574. ret = xml_utils.mergeManifestRes(manifest, libManifest)
  575. if ret:
  576. return ret
  577. return packLogJar(game, sdk, subChannel, config, logSdk)
  578. def generateNewRFile(game, sdk, subChannel, config):
  579. '''
  580. 生成新的R文件
  581. '''
  582. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  583. androidPlatforms = file_utils.getAndroidCompileToolPath()
  584. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  585. decomplieResPath = file_utils.getFullPath(decompliePath, 'res')
  586. compliePath = file_utils.getFullPath(decompliePath, 'gen')
  587. if not os.path.exists(compliePath):
  588. os.makedirs(compliePath)
  589. # 生成R文件
  590. print('create R.java ...')
  591. if config['aapt2disable']:
  592. aapt = file_utils.getAAPTPath()
  593. ret = file_utils.getExecPermission(aapt)
  594. if ret:
  595. return ret
  596. createRCmd = '"%s" p -f -m -J "%s" -S "%s" -I "%s" -M "%s"' % (aapt, compliePath, decomplieResPath, androidPlatforms, manifest)
  597. ret = file_utils.execFormatCmd(createRCmd)
  598. if ret:
  599. return ret
  600. else:
  601. # compile
  602. aapt = file_utils.getAAPT2Path()
  603. ret = file_utils.getExecPermission(aapt)
  604. if ret:
  605. return ret
  606. print('compiled res ...')
  607. complieResPath = os.path.join(compliePath, 'compiled')
  608. complieResCmd = '"%s" compile --dir "%s" -o "%s"' % (aapt, decomplieResPath, complieResPath)
  609. file_utils.execFormatCmd(complieResCmd)
  610. # unzip
  611. print('unzip compiled res ...')
  612. unzipResPath = os.path.join(compliePath, 'aapt2_res')
  613. with zipfile.ZipFile(complieResPath) as zf:
  614. zf.extractall(unzipResPath)
  615. print('create unzip %s' % unzipResPath)
  616. # link
  617. print('link res ...')
  618. outApk = os.path.join(compliePath, 'res.apk')
  619. linkResCmd = '"%s" link -o "%s" -I "%s" --manifest "%s" --java "%s" --auto-add-overlay' % (aapt, outApk, androidPlatforms, manifest, compliePath)
  620. for filename in os.listdir(unzipResPath):
  621. linkResCmd += ' %s' % filename
  622. print('link cmd len is %s' % len(linkResCmd))
  623. ret = file_utils.execFormatCmd(linkResCmd, unzipResPath)
  624. if ret:
  625. return ret
  626. # 编译R文件
  627. print('complie R.java ...')
  628. packageName = xml_utils.getPackageName(manifest)
  629. packagePath = file_utils.getPackagePath(compliePath, packageName)
  630. RSourceFile = os.path.join(packagePath, 'R.java')
  631. complieRCmd = 'javac -source 1.8 -target 1.8 -encoding UTF-8 "%s"' % RSourceFile
  632. ret = file_utils.execFormatCmd(complieRCmd)
  633. if ret:
  634. return ret
  635. # 生成dex
  636. print('dex R.class ...')
  637. outDex = os.path.join(compliePath, 'classes.dex')
  638. if config['aapt2disable']:
  639. dx = file_utils.getDxPath()
  640. dexCmd = '--dex --no-warning --output="%s" "%s"' % (outDex, compliePath)
  641. else:
  642. dx = file_utils.getD8Path()
  643. clazz = os.path.join(packagePath, '*.class')
  644. dexCmd = '--lib "%s" --output "%s" %s' % (androidPlatforms, compliePath, clazz)
  645. ret = file_utils.execJarCmd(dx, dexCmd)
  646. if ret:
  647. return ret
  648. # 反向dex生成smali
  649. # 存放在out目录
  650. print('baksmali classes.dex ...')
  651. baksmaliPath = file_utils.getBaksmaliPath()
  652. outPath = file_utils.getFullPath(decompliePath, 'out')
  653. ret = file_utils.execJarCmd(baksmaliPath, 'd "%s" -o "%s"' % (outDex, outPath))
  654. if ret:
  655. return ret
  656. # 将生成的文件拷贝到目标目录
  657. print('copy R.smali ...')
  658. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  659. file_utils.copyFileAllDir(outPath, smaliPath)
  660. return 0
  661. def packJar(game, sdk, subChannel, config):
  662. '''
  663. 打包所有的jar
  664. '''
  665. splitDex = config['splitDex']
  666. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  667. outPath = file_utils.getFullPath(decompliePath, 'gen')
  668. if not os.path.exists(outPath):
  669. os.makedirs(outPath)
  670. if config['aapt2disable']:
  671. dx = file_utils.getDxPath()
  672. dexCmd = '--dex --multi-dex --no-warning --output="%s"' % outPath
  673. else:
  674. dx = file_utils.getD8Path()
  675. androidPlatforms = file_utils.getAndroidCompileToolPath()
  676. dexCmd = '--lib "%s" --output "%s"' % (androidPlatforms, outPath)
  677. # 找到所有lib依赖
  678. sdkPath = file_utils.getFullSDKPath(sdk)
  679. libs = os.path.join(sdkPath, 'libs')
  680. libConfig = os.path.join(libs, 'config.json')
  681. # 存在配置文件
  682. if os.path.exists(libConfig):
  683. jsonText = file_utils.readFile(libConfig)
  684. libConf = json.loads(jsonText)
  685. if 'libConfig' in config and config['libConfig'] in libConf:
  686. conf = config['libConfig']
  687. libList = libConf[conf]
  688. for jar in libList:
  689. dexCmd += ' ' + os.path.join(libs, jar)
  690. elif 'default' in libConf:
  691. libList = libConf['default']
  692. for jar in libList:
  693. dexCmd += ' ' + os.path.join(libs, jar)
  694. else:
  695. for jar in os.listdir(libs):
  696. if not jar.endswith('.jar'):
  697. continue
  698. dexCmd += ' ' + os.path.join(libs, jar)
  699. else:
  700. for jar in os.listdir(libs):
  701. if not jar.endswith('.jar'):
  702. continue
  703. dexCmd += ' ' + os.path.join(libs, jar)
  704. # multidex.jar
  705. if splitDex:
  706. dexCmd += ' ' + file_utils.getMultiDexPath()
  707. # sdk实现类
  708. print('packageing all jar ...')
  709. dexCmd += ' ' + os.path.join(sdkPath, '%s.jar' % sdk)
  710. ret = file_utils.execJarCmd(dx, dexCmd)
  711. if ret:
  712. return ret
  713. # 反向dex生成smali
  714. # 存放在out目录
  715. print('baksmali classes.dex ...')
  716. outDex = os.path.join(outPath, 'classes.dex')
  717. baksmaliPath = file_utils.getBaksmaliPath()
  718. outPath = file_utils.getFullPath(decompliePath, 'out')
  719. ret = file_utils.execJarCmd(baksmaliPath, 'd "%s" -o "%s"' % (outDex, outPath))
  720. if ret:
  721. return ret
  722. # 将生成的文件拷贝到目标目录
  723. print('copy all smali ...')
  724. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  725. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  726. if ret:
  727. return ret
  728. return 0
  729. def packLogJar(game, sdk, subChannel, config, logSdk):
  730. '''
  731. 打包所有的jar
  732. '''
  733. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  734. outPath = file_utils.getFullPath(decompliePath, 'gen')
  735. if not os.path.exists(outPath):
  736. os.makedirs(outPath)
  737. if config['aapt2disable']:
  738. dx = file_utils.getDxPath()
  739. dexCmd = '--dex --multi-dex --no-warning --output="%s"' % outPath
  740. else:
  741. dx = file_utils.getD8Path()
  742. androidPlatforms = file_utils.getAndroidCompileToolPath()
  743. dexCmd = '--lib "%s" --output "%s"' % (androidPlatforms, outPath)
  744. # 找到所有lib依赖
  745. sdkPath = file_utils.getFullLogSDKPath(logSdk)
  746. libs = os.path.join(sdkPath, 'libs')
  747. for jar in os.listdir(libs):
  748. if not jar.endswith('.jar'):
  749. continue
  750. dexCmd += ' ' + os.path.join(libs, jar)
  751. # sdk实现类
  752. print('packageing all log jar ...')
  753. dexCmd += ' ' + os.path.join(sdkPath, '%s.jar' % logSdk)
  754. ret = file_utils.execJarCmd(dx, dexCmd)
  755. if ret:
  756. return ret
  757. # 反向dex生成smali
  758. # 存放在out目录
  759. print('baksmali classes.dex ...')
  760. outDex = os.path.join(outPath, 'classes.dex')
  761. baksmaliPath = file_utils.getBaksmaliPath()
  762. outPath = file_utils.getFullPath(decompliePath, 'out')
  763. ret = file_utils.execJarCmd(baksmaliPath, 'd "%s" -o "%s"' % (outDex, outPath))
  764. if ret:
  765. return ret
  766. # 将生成的文件拷贝到目标目录
  767. print('copy all log smali ...')
  768. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  769. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  770. if ret:
  771. return ret
  772. return 0
  773. def splitDex(game, sdk, subChannel, config):
  774. '''
  775. 分割dex
  776. '''
  777. # 判断是否已经存在application
  778. # 存在,则往原application添加内容
  779. # 不存在,则拷贝一个默认的android.support.multidex.MultiDexApplication
  780. print('add MultiDex support...')
  781. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  782. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  783. application = xml_utils.getApplicationAttr(manifest, 'name')
  784. if application is None:
  785. ret = xml_utils.changeApplicationAttr(manifest, 'name', 'android.support.multidex.MultiDexApplication')
  786. if ret:
  787. return ret
  788. else:
  789. smaliPath = os.path.join(decompliePath, 'smali')
  790. applicationFile = file_utils.getPackagePath(smaliPath, application)
  791. applicationFile += '.smali'
  792. ret = changeApplicationDex(applicationFile)
  793. if ret:
  794. return ret
  795. return splitSmali(game, sdk, subChannel, config, application)
  796. def changeApplicationDex(file):
  797. '''
  798. 修改application的smali文件,增加MultiDex操作
  799. '''
  800. index = file_utils.getApplicationSmaliIndex(file)
  801. file_utils.insertApplicationSmali(file, index)
  802. return 0
  803. def splitSmali(game, sdk, subChannel, config, application):
  804. '''
  805. 如果函数上限超过限制,自动拆分smali,以便生成多个dex文件
  806. '''
  807. print('splitSmali...')
  808. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  809. smaliPath = os.path.join(decompliePath, 'smali')
  810. appPackage = None
  811. if application:
  812. appPackage = application[:application.rfind('.')]
  813. appPackage = appPackage.replace('.', '/')
  814. allFiles = []
  815. allFiles = file_utils.list_files(smaliPath, allFiles)
  816. #print('file count is %d' % len(allFiles))
  817. #maxFuncNum = 65535
  818. # 留一点空间,防止计算误差
  819. maxFuncNum = 64000
  820. currFucNum = 0
  821. totalFucNum = 0
  822. currDexIndex = 1
  823. allRefs = []
  824. #保证Application等类在第一个classex.dex文件中
  825. for f in allFiles:
  826. f = f.replace('\\', '/')
  827. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  828. currFucNum += smali_utils.get_smali_method_count(f, allRefs)
  829. totalFucNum = currFucNum
  830. for f in allFiles:
  831. f = f.replace('\\', '/')
  832. if not f.endswith('.smali'):
  833. continue
  834. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  835. continue
  836. thisFucNum = smali_utils.get_smali_method_count(f, allRefs)
  837. totalFucNum += thisFucNum
  838. #print('%d # %d ==> %s' % (thisFucNum, currDexIndex, f))
  839. #print('totalFucNum is %d' % totalFucNum)
  840. if currFucNum + thisFucNum >= maxFuncNum:
  841. currFucNum = thisFucNum
  842. currDexIndex += 1
  843. newDexPath = os.path.join(decompliePath, 'smali_classes%d' % currDexIndex)
  844. os.makedirs(newDexPath)
  845. else:
  846. currFucNum += thisFucNum
  847. if currDexIndex > 1:
  848. newDexPath = os.path.join(decompliePath, 'smali_classes%d' % currDexIndex)
  849. targetFile = newDexPath + f[len(smaliPath):]
  850. file_utils.copyFile(f, targetFile, True)
  851. return 0
  852. def changeVersion(game, sdk, subChannel, config):
  853. '''
  854. 更改版本号
  855. '''
  856. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  857. yml = os.path.join(decompliePath, 'apktool.yml')
  858. versionCode = None
  859. versionName = None
  860. targetSdkVersion = None
  861. if 'versionCode' in config:
  862. versionCode = config['versionCode']
  863. if 'versionName' in config:
  864. versionName = config['versionName']
  865. if 'targetSdkVersion' in config:
  866. targetSdkVersion = config['targetSdkVersion']
  867. print('changeVersion versionCode=%s,versionName=%s,targetSdkVersion=%s' % (versionCode, versionName, targetSdkVersion))
  868. return file_utils.changeVersion(yml, versionCode, versionName, targetSdkVersion)
  869. def recomplie(game, sdk, subChannel, config):
  870. '''
  871. 回编译
  872. '''
  873. print('recomplie apk...')
  874. apktoolPath = file_utils.getApkToolPath()
  875. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  876. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  877. useAppt2 = ' --use-aapt2'
  878. if config['aapt2disable']:
  879. useAppt2 = ''
  880. return file_utils.execJarCmd(apktoolPath, 'b -f "%s" -o "%s"%s' % (decompliePath, outApk, useAppt2))
  881. def alignApk(game, sdk, subChannel, config):
  882. '''
  883. 对齐apk
  884. '''
  885. print('align apk...')
  886. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  887. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  888. alignapkTool = file_utils.getAlignPath()
  889. if os.path.exists(alignApk):
  890. os.remove(alignApk)
  891. ret = file_utils.getExecPermission(alignapkTool)
  892. if ret:
  893. return ret
  894. # zipalign.exe -v -p 4 input.apk output.apk
  895. return file_utils.execFormatCmd('"%s" -f -p 4 "%s" "%s"' % (alignapkTool, outApk, alignApk))
  896. def apksignerApk(game, sdk, subChannel, config):
  897. '''
  898. 签名apk
  899. '''
  900. print('sign apk...')
  901. path = os.path.join(file_utils.getCurrentPath(), 'keystore', 'key.json')
  902. jsonText = file_utils.readFile(path)
  903. signConfig = json.loads(jsonText)
  904. keystore = {}
  905. if game in signConfig:
  906. if sdk in signConfig[game] and subChannel in signConfig[game][sdk]:
  907. keystore = signConfig[game][sdk][subChannel]
  908. else:
  909. keystore = signConfig['default']
  910. else:
  911. keystore = signConfig['default']
  912. print('storeFile is "%s"' % keystore['storeFile'])
  913. apksigner = file_utils.getApksignerPath()
  914. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  915. signedApk = file_utils.getSignApkPath(game, sdk, subChannel, config['cache'])
  916. storeFile = os.path.join(file_utils.getCurrentPath(), 'keystore', keystore['storeFile'])
  917. if 'outName' in config and 'outPath' in config:
  918. if not os.path.exists(config['outPath']):
  919. os.makedirs(config['outPath'])
  920. signedApk = os.path.join(config['outPath'], config['outName'] + '.apk')
  921. elif 'outName' in config:
  922. signedApk = file_utils.getRenameApkPath(game, sdk, config['cache'], config['outName'])
  923. # java -jar apksigner.jar sign --ks key.jks --ks-key-alias releasekey --ks-pass pass:pp123456 --key-pass pass:pp123456 --out output.apk input.apk
  924. v2disable = ''
  925. if 'v2disable' in config and config['v2disable']:
  926. v2disable = ' --v2-signing-enabled=false'
  927. return file_utils.execJarCmd(apksigner, 'sign%s --ks "%s" --ks-key-alias %s --ks-pass pass:%s --key-pass pass:%s --out "%s" "%s"' % (v2disable, storeFile, keystore['keyAlias'], keystore['storePassword'], keystore['keyPassword'], signedApk, alignApk))
  928. def addChannel(game, sdk, subChannel, config):
  929. '''
  930. 添加渠道信息
  931. '''
  932. if 'v2disable' in config and config['v2disable']:
  933. return 0
  934. walle = file_utils.getWallePath()
  935. signedApk = file_utils.getSignApkPath(game, sdk, subChannel, config['cache'])
  936. if 'outName' in config and 'outPath' in config:
  937. signedApk = os.path.join(config['outPath'], config['outName'] + '.apk')
  938. elif 'outName' in config:
  939. signedApk = file_utils.getRenameApkPath(game, sdk, config['cache'], config['outName'])
  940. properties = config['properties']
  941. appid = ''
  942. appkey = ''
  943. host = ''
  944. if 'appid' in properties:
  945. appid = properties['appid']
  946. if 'appkey' in properties:
  947. appkey = properties['appkey']
  948. if 'host' in properties:
  949. host = properties['host']
  950. return file_utils.execJarCmd(walle, 'put -e version=%s,agent=%s,appid=%s,appkey=%s,host=%s "%s" "%s"' % (config_utils.getDate(), properties['agent'], appid, appkey, host, signedApk, signedApk))
  951. def clearTemp(game, sdk, subChannel, config):
  952. '''
  953. 清空中间产生的文件
  954. '''
  955. print('clear temp...')
  956. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  957. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  958. if os.path.exists(alignApk):
  959. os.remove(alignApk)
  960. if os.path.exists(outApk):
  961. os.remove(outApk)
  962. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  963. file_utils.deleteFolder(decompliePath)
  964. print('clear temp end')
  965. def packConsoleInput():
  966. '''
  967. 控制台打包
  968. '''
  969. if len(sys.argv) < 3:
  970. print('argument is missing')
  971. return 1
  972. # 校验参数
  973. game = sys.argv[1]
  974. sdk = sys.argv[2]
  975. # 可选参数,没有则默认打全部渠道
  976. subChannel = None
  977. if len(sys.argv) > 3:
  978. subChannel = sys.argv[3]
  979. return packConsole(game, sdk, subChannel)
  980. def packConsole(game, sdk, subChannel):
  981. '''
  982. 控制台打包
  983. '''
  984. if not os.path.exists(file_utils.getFullGameApk(game)):
  985. print('game "%s" not exists' % game)
  986. return 1
  987. if not os.path.exists(file_utils.getFullSDKPath(sdk)):
  988. print('sdk "%s" not exists' % sdk)
  989. return 1
  990. # 读取配置
  991. channelPath = file_utils.getChannelPath(game, sdk)
  992. configPath = os.path.join(channelPath, 'config.json')
  993. if not os.path.exists(configPath):
  994. print('%s not exists' % configPath)
  995. return 1
  996. jsonText = file_utils.readFile(configPath)
  997. config = json.loads(jsonText)
  998. # 检查参数
  999. if not config_utils.checkConfig(config):
  1000. return 1
  1001. # 处理参数
  1002. config_utils.replaceArgs(config)
  1003. successCount = 0
  1004. failureCount = 0
  1005. if type(config) == dict:
  1006. if subChannel is None or config['subChannel'] == subChannel:
  1007. ret = pack(game, sdk, config)
  1008. if ret:
  1009. failureCount += 1
  1010. else:
  1011. successCount += 1
  1012. else:
  1013. print('subChannel "%s" no found' % subChannel)
  1014. return 1
  1015. elif type(config) == list:
  1016. found = False
  1017. for itemConfig in config:
  1018. if subChannel is None or itemConfig['subChannel'] == subChannel:
  1019. found = True
  1020. ret = pack(game, sdk, itemConfig)
  1021. if ret:
  1022. failureCount += 1
  1023. else:
  1024. successCount += 1
  1025. if not found:
  1026. print('subChannel "%s" no found' % subChannel)
  1027. return 1
  1028. print('success %d, failure %d' % (successCount, failureCount))
  1029. return 0