package_utils.py 39 KB

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