package_utils_record.py 34 KB

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