package_utils_shanshen.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. else:
  636. for jar in os.listdir(libs):
  637. if not jar.endswith('.jar'):
  638. continue
  639. dexCmd += ' ' + os.path.join(libs, jar)
  640. else:
  641. for jar in os.listdir(libs):
  642. if not jar.endswith('.jar'):
  643. continue
  644. dexCmd += ' ' + os.path.join(libs, jar)
  645. # multidex.jar
  646. if splitDex:
  647. dexCmd += ' ' + file_utils.getMultiDexPath()
  648. # sdk实现类
  649. print('packageing all jar ...')
  650. ret = file_utils.execJarCmd(dx, dexCmd)
  651. if ret:
  652. return ret
  653. # 反向dex生成smali
  654. # 存放在out目录
  655. print('baksmali classes.dex ...')
  656. outDex = os.path.join(outPath, 'classes.dex')
  657. baksmaliPath = file_utils.getBaksmaliPath()
  658. outPath = file_utils.getFullPath(decompliePath, 'out')
  659. ret = file_utils.execJarCmd(baksmaliPath, 'd "%s" -o "%s"' % (outDex, outPath))
  660. if ret:
  661. return ret
  662. # 将生成的文件拷贝到目标目录
  663. print('copy all smali ...')
  664. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  665. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  666. if ret:
  667. return ret
  668. return 0
  669. def splitDex(game, sdk, subChannel, config):
  670. '''
  671. 分割dex
  672. '''
  673. # 判断是否已经存在application
  674. # 存在,则往原application添加内容
  675. # 不存在,则拷贝一个默认的android.support.multidex.MultiDexApplication
  676. print('add MultiDex support...')
  677. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  678. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  679. application = xml_utils.getApplicationAttr(manifest, 'name')
  680. if application is None:
  681. ret = xml_utils.changeApplicationAttr(manifest, 'name', 'android.support.multidex.MultiDexApplication')
  682. if ret:
  683. return ret
  684. else:
  685. smaliPath = os.path.join(decompliePath, 'smali')
  686. applicationFile = file_utils.getPackagePath(smaliPath, application)
  687. applicationFile += '.smali'
  688. ret = changeApplicationDex(applicationFile)
  689. if ret:
  690. return ret
  691. return splitSmali(game, sdk, subChannel, config, application)
  692. def changeApplicationDex(file):
  693. '''
  694. 修改application的smali文件,增加MultiDex操作
  695. '''
  696. index = file_utils.getApplicationSmaliIndex(file)
  697. file_utils.insertApplicationSmali(file, index)
  698. return 0
  699. def splitSmali(game, sdk, subChannel, config, application):
  700. '''
  701. 如果函数上限超过限制,自动拆分smali,以便生成多个dex文件
  702. '''
  703. print('splitSmali...')
  704. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  705. smaliPath = os.path.join(decompliePath, 'smali')
  706. appPackage = None
  707. if application:
  708. appPackage = application[:application.rfind('.')]
  709. appPackage = appPackage.replace('.', '/')
  710. allFiles = []
  711. allFiles = file_utils.list_files(smaliPath, allFiles)
  712. #print('file count is %d' % len(allFiles))
  713. #maxFuncNum = 65535
  714. # 留一点空间,防止计算误差
  715. maxFuncNum = 64000
  716. currFucNum = 0
  717. totalFucNum = 0
  718. currDexIndex = 1
  719. allRefs = []
  720. #保证Application等类在第一个classex.dex文件中
  721. for f in allFiles:
  722. f = f.replace('\\', '/')
  723. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  724. currFucNum += smali_utils.get_smali_method_count(f, allRefs)
  725. totalFucNum = currFucNum
  726. for f in allFiles:
  727. f = f.replace('\\', '/')
  728. if not f.endswith('.smali'):
  729. continue
  730. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  731. continue
  732. thisFucNum = smali_utils.get_smali_method_count(f, allRefs)
  733. totalFucNum += thisFucNum
  734. #print('%d # %d ==> %s' % (thisFucNum, currDexIndex, f))
  735. #print('totalFucNum is %d' % totalFucNum)
  736. if currFucNum + thisFucNum >= maxFuncNum:
  737. currFucNum = thisFucNum
  738. currDexIndex += 1
  739. newDexPath = os.path.join(decompliePath, 'smali_classes%d' % currDexIndex)
  740. os.makedirs(newDexPath)
  741. else:
  742. currFucNum += thisFucNum
  743. if currDexIndex > 1:
  744. newDexPath = os.path.join(decompliePath, 'smali_classes%d' % currDexIndex)
  745. targetFile = newDexPath + f[len(smaliPath):]
  746. file_utils.copyFile(f, targetFile, True)
  747. return 0
  748. def changeVersion(game, sdk, subChannel, config):
  749. '''
  750. 更改版本号
  751. '''
  752. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  753. yml = os.path.join(decompliePath, 'apktool.yml')
  754. versionCode = None
  755. versionName = None
  756. targetSdkVersion = None
  757. if 'versionCode' in config:
  758. versionCode = config['versionCode']
  759. if 'versionName' in config:
  760. versionName = config['versionName']
  761. if 'targetSdkVersion' in config:
  762. targetSdkVersion = config['targetSdkVersion']
  763. return file_utils.changeVersion(yml, versionCode, versionName, targetSdkVersion)
  764. def recomplie(game, sdk, subChannel, config):
  765. '''
  766. 回编译
  767. '''
  768. print('recomplie apk...')
  769. apktoolPath = file_utils.getApkToolPath()
  770. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  771. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  772. useAppt2 = ' --use-aapt2'
  773. if config['aapt2disable']:
  774. useAppt2 = ''
  775. return file_utils.execJarCmd(apktoolPath, 'b -f "%s" -o "%s"%s' % (decompliePath, outApk, useAppt2))
  776. def alignApk(game, sdk, subChannel, config):
  777. '''
  778. 对齐apk
  779. '''
  780. print('align apk...')
  781. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  782. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  783. alignapkTool = file_utils.getAlignPath()
  784. if os.path.exists(alignApk):
  785. os.remove(alignApk)
  786. ret = file_utils.getExecPermission(alignapkTool)
  787. if ret:
  788. return ret
  789. # zipalign.exe -v -p 4 input.apk output.apk
  790. return file_utils.execFormatCmd('"%s" -f -p 4 "%s" "%s"' % (alignapkTool, outApk, alignApk))
  791. def apksignerApk(game, sdk, subChannel, config):
  792. '''
  793. 签名apk
  794. '''
  795. print('sign apk...')
  796. path = os.path.join(file_utils.getCurrentPath(), 'keystore', 'key.json')
  797. jsonText = file_utils.readFile(path)
  798. signConfig = json.loads(jsonText)
  799. keystore = {}
  800. if game in signConfig:
  801. if sdk in signConfig[game] and subChannel in signConfig[game][sdk]:
  802. keystore = signConfig[game][sdk][subChannel]
  803. else:
  804. keystore = signConfig['default']
  805. else:
  806. keystore = signConfig['default']
  807. print('storeFile is "%s"' % keystore['storeFile'])
  808. apksigner = file_utils.getApksignerPath()
  809. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  810. signedApk = file_utils.getSignApkPath(game, sdk, subChannel, config['cache'])
  811. storeFile = os.path.join(file_utils.getCurrentPath(), 'keystore', keystore['storeFile'])
  812. if 'outName' in config and 'outPath' in config:
  813. if not os.path.exists(config['outPath']):
  814. os.makedirs(config['outPath'])
  815. signedApk = os.path.join(config['outPath'], config['outName'] + '.apk')
  816. elif 'outName' in config:
  817. signedApk = file_utils.getRenameApkPath(game, sdk, config['cache'], config['outName'])
  818. # 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
  819. v2disable = ''
  820. if 'v2disable' in config and config['v2disable']:
  821. v2disable = ' --v2-signing-enabled=false'
  822. 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))
  823. def addChannel(game, sdk, subChannel, config):
  824. '''
  825. 添加渠道信息
  826. '''
  827. if 'v2disable' in config and config['v2disable']:
  828. return 0
  829. walle = file_utils.getWallePath()
  830. signedApk = file_utils.getSignApkPath(game, sdk, subChannel, config['cache'])
  831. if 'outName' in config and 'outPath' in config:
  832. signedApk = os.path.join(config['outPath'], config['outName'] + '.apk')
  833. elif 'outName' in config:
  834. signedApk = file_utils.getRenameApkPath(game, sdk, config['cache'], config['outName'])
  835. properties = config['properties']
  836. appid = ''
  837. appkey = ''
  838. if 'appid' in properties:
  839. appid = properties['appid']
  840. if 'appkey' in properties:
  841. appkey = properties['appkey']
  842. 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))
  843. def clearTemp(game, sdk, subChannel, config):
  844. '''
  845. 清空中间产生的文件
  846. '''
  847. print('clear temp...')
  848. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  849. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  850. if os.path.exists(alignApk):
  851. os.remove(alignApk)
  852. if os.path.exists(outApk):
  853. os.remove(outApk)
  854. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  855. file_utils.deleteFolder(decompliePath)
  856. print('clear temp end')
  857. def packConsoleInput():
  858. '''
  859. 控制台打包
  860. '''
  861. if len(sys.argv) < 3:
  862. print('argument is missing')
  863. return 1
  864. # 校验参数
  865. game = sys.argv[1]
  866. sdk = sys.argv[2]
  867. # 可选参数,没有则默认打全部渠道
  868. subChannel = None
  869. if len(sys.argv) > 3:
  870. subChannel = sys.argv[3]
  871. return packConsole(game, sdk, subChannel)
  872. def packConsole(game, sdk, subChannel):
  873. '''
  874. 控制台打包
  875. '''
  876. if not os.path.exists(file_utils.getFullGameApk(game)):
  877. print('game "%s" not exists' % game)
  878. return 1
  879. if not os.path.exists(file_utils.getFullSDKPath(sdk)):
  880. print('sdk "%s" not exists' % sdk)
  881. return 1
  882. # 读取配置
  883. channelPath = file_utils.getChannelPath(game, sdk)
  884. configPath = os.path.join(channelPath, 'config.json')
  885. if not os.path.exists(configPath):
  886. print('%s not exists' % configPath)
  887. return 1
  888. jsonText = file_utils.readFile(configPath)
  889. config = json.loads(jsonText)
  890. # 检查参数
  891. if not config_utils_shanshen.checkConfig(config):
  892. return 1
  893. # 处理参数
  894. config_utils_shanshen.replaceArgs(config)
  895. successCount = 0
  896. failureCount = 0
  897. if type(config) == dict:
  898. if subChannel is None or config['subChannel'] == subChannel:
  899. ret = pack(game, sdk, config)
  900. if ret:
  901. failureCount += 1
  902. else:
  903. successCount += 1
  904. else:
  905. print('subChannel "%s" no found' % subChannel)
  906. return 1
  907. elif type(config) == list:
  908. found = False
  909. for itemConfig in config:
  910. if subChannel is None or itemConfig['subChannel'] == subChannel:
  911. found = True
  912. ret = pack(game, sdk, itemConfig)
  913. if ret:
  914. failureCount += 1
  915. else:
  916. successCount += 1
  917. if not found:
  918. print('subChannel "%s" no found' % subChannel)
  919. return 1
  920. print('success %d, failure %d' % (successCount, failureCount))
  921. return 0