package_utils_shanshen.py 35 KB

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