package_utils_shanshen.py 36 KB

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