package_utils.py 39 KB

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