package_utils_record.py 34 KB

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