package_utils_shanshen.py 33 KB

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