package_utils.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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
  17. import game_utils
  18. import os
  19. import os.path
  20. import json
  21. import sys
  22. import importlib
  23. import uuid
  24. ignoreLauncher = ['jm_ysdk', 'jm_yijie', 'jm_quick', 'jm_beiyu', 'jm_xq_jrtt']
  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. # 增加配置文件
  69. ret = addConfig(game, sdk, subChannel, config)
  70. if ret:
  71. return ret
  72. # 复制app res资源
  73. ret = copyAppRes(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. # 更改app名
  82. if 'name' in config and config['name'] != '':
  83. ret = changeAppName(game, sdk, subChannel, config)
  84. if ret:
  85. return ret
  86. # 更改app icon
  87. if config['changeIcon']:
  88. ret = changeAppIcon(game, sdk, subChannel, config)
  89. if ret:
  90. return ret
  91. # 添加启动图操作
  92. if config['addLauncher']:
  93. ret = addLauncher(game, sdk, subChannel, config)
  94. if ret:
  95. return ret
  96. # 添加多图标
  97. #ret = addMoreIcon(game, sdk, subChannel, config)
  98. #if ret:
  99. # return ret
  100. # 打包lib依赖
  101. ret = packJar(game, sdk, subChannel, config)
  102. if ret:
  103. return ret
  104. # sdk脚本处理
  105. ret = doSDKPostScript(game, sdk, config)
  106. if ret:
  107. return ret
  108. # 乐变sdk的特殊处理
  109. ret = game_utils.sdkLebianChange(game, sdk, config)
  110. if ret:
  111. return ret
  112. # 游戏脚本处理
  113. ret = doGamePostScript(game, sdk, config)
  114. if ret:
  115. return ret
  116. # log sdk
  117. if 'logSdk' in config:
  118. for log in config['logSdk']:
  119. ret = addLogSdk(game, sdk, subChannel, config, log)
  120. if ret:
  121. return ret
  122. # 生成R文件
  123. ret = generateNewRFile(game, sdk, subChannel, config)
  124. if ret:
  125. return ret
  126. # 添加MultiDex支持
  127. if config['splitDex']:
  128. ret = splitDex(game, sdk, subChannel, config)
  129. if ret:
  130. return ret
  131. # 更改版本号
  132. ret = changeVersion(game, sdk, subChannel, config)
  133. if ret:
  134. return ret
  135. # 回编译
  136. ret = recomplie(game, sdk, subChannel, config)
  137. if ret:
  138. return ret
  139. # 对齐apk
  140. ret = alignApk(game, sdk, subChannel, config)
  141. if ret:
  142. return ret
  143. # 签名
  144. ret = apksignerApk(game, sdk, subChannel, config)
  145. if ret:
  146. return ret
  147. # 添加渠道信息
  148. ret = addChannel(game, sdk, subChannel, config)
  149. if ret:
  150. return ret
  151. # 清理产生的中间文件
  152. if config['clearCache']:
  153. clearTemp(game, sdk, subChannel, config)
  154. return 0
  155. def decomplie(game, sdk, subChannel, config):
  156. '''
  157. 解包
  158. '''
  159. apktoolPath = file_utils.getApkToolPath()
  160. gamePath = file_utils.getFullGameApk(game)
  161. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  162. if os.path.exists(decompliePath):
  163. print('delete decomplie folder...')
  164. file_utils.deleteFolder(decompliePath)
  165. print('decomplie apk...')
  166. return file_utils.execJarCmd(apktoolPath, 'd -f "%s" -o "%s"' % (gamePath, decompliePath))
  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', 'sdk')
  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 changeAppName(game, sdk, subChannel, config):
  370. '''
  371. 更改app名
  372. '''
  373. # 生成string.xml文件
  374. name = config['name']
  375. resName = 'common_sdk_name'
  376. if 'outName' in config:
  377. resName = resName + '_' + config['outName']
  378. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  379. stringFile = os.path.join(decompliePath, 'res', 'values', 'sdk_strings.xml')
  380. content = '<?xml version="1.0" encoding="utf-8"?><resources><string name="%s">%s</string></resources>' % (resName, name)
  381. file_utils.createFile(stringFile, content)
  382. # 修改主文件的app名的值
  383. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  384. xml_utils.changeAppName(manifest, '@string/%s' % resName)
  385. print('change app name %s' % name)
  386. return 0
  387. def changeAppIcon(game, sdk, subChannel, config):
  388. '''
  389. 更改app icon
  390. '''
  391. print('change app icon...')
  392. resName = 'common_sdk_icon'
  393. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  394. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  395. xml_utils.changeAppIcon(manifest, '@mipmap/%s' % resName)
  396. return 0
  397. def addMetaData(game, sdk, subChannel, config):
  398. '''
  399. 添加meta-data
  400. '''
  401. if 'metaData' not in config:
  402. return 0
  403. print('add meta-data...')
  404. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  405. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  406. xml_utils.addMetaData(manifest, config['metaData'])
  407. return 0
  408. def addConfig(game, sdk, subChannel, config):
  409. '''
  410. 添加config.json
  411. '''
  412. if 'configData' not in config:
  413. return 0
  414. print('add config.json...')
  415. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  416. configJson = os.path.join(decompliePath, 'assets', 'jmhy_config.json')
  417. jsonText = json.dumps(config['configData'], ensure_ascii=False)
  418. file_utils.createFile(configJson, jsonText)
  419. return 0
  420. def changePlaceholders(game, sdk, subChannel, config):
  421. '''
  422. 处理掉占位符
  423. '''
  424. if 'placeholders' not in config:
  425. return 0
  426. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  427. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  428. placeholders = config['placeholders']
  429. for placeholder in placeholders:
  430. oldText = '${%s}' % placeholder
  431. newText = placeholders[placeholder]
  432. print('change placeholder %s -> %s' % (oldText, newText))
  433. file_utils.replaceContent(manifest, oldText, newText)
  434. return 0
  435. def addLauncher(game, sdk, subChannel, config):
  436. '''
  437. 添加启动图
  438. '''
  439. # ysdk的特殊处理
  440. if sdk in ignoreLauncher:
  441. return 0
  442. channelPath = file_utils.getSubChannelPath(game, sdk, subChannel)
  443. splashPath = os.path.join(channelPath, 'splash')
  444. if len(os.listdir(splashPath)) == 0:
  445. print('dir splash is empty')
  446. return 0
  447. print('add launcher...')
  448. # 添加关联资源
  449. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  450. internalPath = file_utils.getFullInternalPath()
  451. ret = copyAppResWithType(decompliePath, internalPath, 'launcher_res')
  452. if ret:
  453. return ret
  454. # 拷贝代码
  455. print('copy launcher code...')
  456. codePath = os.path.join(internalPath, 'launcher_code', 'smali')
  457. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  458. ret = file_utils.copyFileAllDir(codePath, smaliPath)
  459. if ret:
  460. return ret
  461. # 修改主文件信息
  462. print('change launcher config...')
  463. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  464. orientation = xml_utils.getScreenOrientation(manifest)
  465. activity = xml_utils.removeLauncherActivity(manifest)
  466. xml_utils.addLauncherActivity(manifest, orientation, 'com.jmhy.sdk.template.LauncherActivity')
  467. # 修改跳转的
  468. launcherActivity = os.path.join(decompliePath, 'smali', 'com', 'jmhy', 'sdk', 'template', 'LauncherActivity.smali')
  469. file_utils.replaceContent(launcherActivity, '{class}', activity)
  470. print('change launcher %s to %s' % (activity, 'com.jmhy.sdk.template.LauncherActivity'))
  471. # config['oldLauncher'] = activity
  472. if 'launcherTime' in config:
  473. timeHex = formatHex(config['launcherTime'])
  474. file_utils.replaceContent(launcherActivity, '0x0BB8', timeHex)
  475. return 0
  476. def addMoreIcon(game, sdk, subChannel, config):
  477. '''
  478. 添加多个图标
  479. '''
  480. print('add more icon support...')
  481. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  482. icon = '@mipmap/common_sdk_icon'
  483. if not config['changeIcon']:
  484. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  485. icon = xml_utils.getApplicationAttr(manifest, 'icon')
  486. switchIcon = icon
  487. if config['switchIcon']:
  488. switchIcon = '@mipmap/common_sdk_icon2'
  489. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  490. return xml_utils.addMoreIcon(manifest, icon, switchIcon)
  491. def formatHex(millisecond):
  492. '''
  493. 将毫秒转为16进制,4位格式
  494. '''
  495. timeHex = str(hex(millisecond)).upper()
  496. timeHex = timeHex[2:]
  497. formatHex = ''
  498. if len(timeHex) == 3:
  499. formatHex = '0x0' + timeHex
  500. elif len(timeHex) == 4:
  501. formatHex = '0x' + timeHex
  502. else:
  503. formatHex = '0x0BB8'
  504. return formatHex
  505. def doSDKPostScript(game, sdk, config):
  506. '''
  507. 执行sdk相关特殊处理脚本
  508. '''
  509. sdkPath = file_utils.getFullSDKPath(sdk)
  510. scriptPath = os.path.join(sdkPath, 'script')
  511. targetScript = os.path.join(scriptPath, 'sdk_script.py')
  512. if not os.path.exists(targetScript):
  513. print('sdk_script no exists')
  514. return 0
  515. print('doSDKPostScript...')
  516. sys.path.append(scriptPath)
  517. module = importlib.import_module('sdk_script')
  518. ret = module.execute(game, sdk, config)
  519. sys.path.remove(scriptPath)
  520. return ret
  521. def doGamePostScript(game, sdk, config):
  522. '''
  523. 执行游戏相关特殊处理脚本
  524. '''
  525. channelPath = file_utils.getFullGamePath(game)
  526. scriptPath = os.path.join(channelPath, 'script')
  527. targetScript = os.path.join(scriptPath, 'game_script.py')
  528. if not os.path.exists(targetScript):
  529. print('game_script no exists')
  530. return 0
  531. print('doGamePostScript...')
  532. sys.path.append(scriptPath)
  533. module = importlib.import_module('game_script')
  534. ret = module.execute(game, sdk, config)
  535. sys.path.remove(scriptPath)
  536. return ret
  537. def addLogSdk(game, sdk, subChannel, config, logSdk):
  538. # 拷贝jniLibs
  539. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  540. sdkPath = file_utils.getFullLogSDKPath(logSdk)
  541. print('copy log jniLibs...')
  542. jniPath = file_utils.getFullPath(sdkPath, 'jniLibs')
  543. decomplieJniPath = file_utils.getFullPath(decompliePath, 'lib')
  544. abiFilters = []
  545. if os.path.exists(decomplieJniPath):
  546. for abi in os.listdir(decomplieJniPath):
  547. if abi == 'armeabi-v7a' or abi == 'armeabi':
  548. abiFilters.append(abi)
  549. else:
  550. abiFilters = ['armeabi-v7a']
  551. if os.path.exists(jniPath):
  552. ret = file_utils.copyFileAllDir(jniPath, decomplieJniPath, False, abiFilters)
  553. if ret:
  554. return ret
  555. print('merge log AndroidManifest...')
  556. libManifest = file_utils.getFullPath(sdkPath, 'manifest.xml')
  557. if os.path.exists(libManifest):
  558. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  559. ret = xml_utils.mergeManifestRes(manifest, libManifest)
  560. if ret:
  561. return ret
  562. return packLogJar(game, sdk, subChannel, config, logSdk)
  563. def generateNewRFile(game, sdk, subChannel, config):
  564. '''
  565. 生成新的R文件
  566. '''
  567. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  568. aapt = file_utils.getAAPTPath()
  569. androidPlatforms = file_utils.getAndroidCompileToolPath()
  570. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  571. decomplieResPath = file_utils.getFullPath(decompliePath, 'res')
  572. compliePath = file_utils.getFullPath(decompliePath, 'gen')
  573. if not os.path.exists(compliePath):
  574. os.makedirs(compliePath)
  575. ret = file_utils.getExecPermission(aapt)
  576. if ret:
  577. return ret
  578. # 生成R文件
  579. print('create R.java ...')
  580. createRCmd = '"%s" p -f -m -J "%s" -S "%s" -I "%s" -M "%s"' % (aapt, compliePath, decomplieResPath, androidPlatforms, manifest)
  581. ret = file_utils.execFormatCmd(createRCmd)
  582. if ret:
  583. return ret
  584. # 编译R文件
  585. print('complie R.java ...')
  586. packageName = xml_utils.getPackageName(manifest)
  587. packagePath = file_utils.getPackagePath(compliePath, packageName)
  588. RSourceFile = os.path.join(packagePath, 'R.java')
  589. complieRCmd = 'javac -source 1.7 -target 1.7 -encoding UTF-8 "%s"' % RSourceFile
  590. ret = file_utils.execFormatCmd(complieRCmd)
  591. if ret:
  592. return ret
  593. # 生成dex
  594. print('dex R.class ...')
  595. dx = file_utils.getDxPath()
  596. outDex = os.path.join(compliePath, 'classes.dex')
  597. ret = file_utils.execJarCmd(dx, '--dex --output="%s" "%s"' % (outDex, compliePath))
  598. if ret:
  599. return ret
  600. # 反向dex生成smali
  601. # 存放在out目录
  602. print('baksmali classes.dex ...')
  603. baksmaliPath = file_utils.getBaksmaliPath()
  604. outPath = file_utils.getFullPath(decompliePath, 'out')
  605. ret = file_utils.execJarCmd(baksmaliPath, '-o "%s" "%s"' % (outPath, outDex))
  606. if ret:
  607. return ret
  608. # 将生成的文件拷贝到目标目录
  609. print('copy R.smali ...')
  610. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  611. file_utils.copyFileAllDir(outPath, smaliPath)
  612. return 0
  613. def packJar(game, sdk, subChannel, config):
  614. '''
  615. 打包所有的jar
  616. '''
  617. splitDex = config['splitDex']
  618. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  619. outPath = file_utils.getFullPath(decompliePath, 'gen')
  620. dx = file_utils.getDxPath()
  621. if not os.path.exists(outPath):
  622. os.makedirs(outPath)
  623. # --no-warning
  624. dexCmd = '--dex --multi-dex --no-warning --output="%s"' % outPath
  625. # 找到所有lib依赖
  626. sdkPath = file_utils.getFullSDKPath(sdk)
  627. libs = os.path.join(sdkPath, 'libs')
  628. libConfig = os.path.join(libs, 'config.json')
  629. # 存在配置文件
  630. if os.path.exists(libConfig):
  631. jsonText = file_utils.readFile(libConfig)
  632. libConf = json.loads(jsonText)
  633. if 'libConfig' in config and config['libConfig'] in libConf:
  634. conf = config['libConfig']
  635. libList = libConf[conf]
  636. for jar in libList:
  637. dexCmd += ' ' + os.path.join(libs, jar)
  638. else:
  639. for jar in os.listdir(libs):
  640. if not jar.endswith('.jar'):
  641. continue
  642. dexCmd += ' ' + os.path.join(libs, jar)
  643. else:
  644. for jar in os.listdir(libs):
  645. if not jar.endswith('.jar'):
  646. continue
  647. dexCmd += ' ' + os.path.join(libs, jar)
  648. # multidex.jar
  649. if splitDex:
  650. dexCmd += ' ' + file_utils.getMultiDexPath()
  651. # sdk实现类
  652. print('packageing all jar ...')
  653. dexCmd += ' ' + os.path.join(sdkPath, '%s.jar' % sdk)
  654. ret = file_utils.execJarCmd(dx, dexCmd)
  655. if ret:
  656. return ret
  657. # 反向dex生成smali
  658. # 存放在out目录
  659. print('baksmali classes.dex ...')
  660. outDex = os.path.join(outPath, 'classes.dex')
  661. baksmaliPath = file_utils.getBaksmaliPath()
  662. outPath = file_utils.getFullPath(decompliePath, 'out')
  663. ret = file_utils.execJarCmd(baksmaliPath, '-o "%s" "%s"' % (outPath, outDex))
  664. if ret:
  665. return ret
  666. # 将生成的文件拷贝到目标目录
  667. print('copy all smali ...')
  668. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  669. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  670. if ret:
  671. return ret
  672. return 0
  673. def packLogJar(game, sdk, subChannel, config, logSdk):
  674. '''
  675. 打包所有的jar
  676. '''
  677. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  678. outPath = file_utils.getFullPath(decompliePath, 'gen')
  679. dx = file_utils.getDxPath()
  680. if not os.path.exists(outPath):
  681. os.makedirs(outPath)
  682. # --no-warning
  683. dexCmd = '--dex --multi-dex --no-warning --output="%s"' % outPath
  684. # 找到所有lib依赖
  685. sdkPath = file_utils.getFullLogSDKPath(logSdk)
  686. libs = os.path.join(sdkPath, 'libs')
  687. for jar in os.listdir(libs):
  688. if not jar.endswith('.jar'):
  689. continue
  690. dexCmd += ' ' + os.path.join(libs, jar)
  691. # sdk实现类
  692. print('packageing all log jar ...')
  693. dexCmd += ' ' + os.path.join(sdkPath, '%s.jar' % logSdk)
  694. ret = file_utils.execJarCmd(dx, dexCmd)
  695. if ret:
  696. return ret
  697. # 反向dex生成smali
  698. # 存放在out目录
  699. print('baksmali classes.dex ...')
  700. outDex = os.path.join(outPath, 'classes.dex')
  701. baksmaliPath = file_utils.getBaksmaliPath()
  702. outPath = file_utils.getFullPath(decompliePath, 'out')
  703. ret = file_utils.execJarCmd(baksmaliPath, '-o "%s" "%s"' % (outPath, outDex))
  704. if ret:
  705. return ret
  706. # 将生成的文件拷贝到目标目录
  707. print('copy all log smali ...')
  708. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  709. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  710. if ret:
  711. return ret
  712. return 0
  713. def splitDex(game, sdk, subChannel, config):
  714. '''
  715. 分割dex
  716. '''
  717. # 判断是否已经存在application
  718. # 存在,则往原application添加内容
  719. # 不存在,则拷贝一个默认的android.support.multidex.MultiDexApplication
  720. print('add MultiDex support...')
  721. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  722. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  723. application = xml_utils.getApplicationAttr(manifest, 'name')
  724. if application is None:
  725. ret = xml_utils.changeApplicationAttr(manifest, 'name', 'android.support.multidex.MultiDexApplication')
  726. if ret:
  727. return ret
  728. else:
  729. smaliPath = os.path.join(decompliePath, 'smali')
  730. applicationFile = file_utils.getPackagePath(smaliPath, application)
  731. applicationFile += '.smali'
  732. ret = changeApplicationDex(applicationFile)
  733. if ret:
  734. return ret
  735. return splitSmali(game, sdk, subChannel, config, application)
  736. def changeApplicationDex(file):
  737. '''
  738. 修改application的smali文件,增加MultiDex操作
  739. '''
  740. index = file_utils.getApplicationSmaliIndex(file)
  741. file_utils.insertApplicationSmali(file, index)
  742. return 0
  743. def splitSmali(game, sdk, subChannel, config, application):
  744. '''
  745. 如果函数上限超过限制,自动拆分smali,以便生成多个dex文件
  746. '''
  747. print('splitSmali...')
  748. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  749. smaliPath = os.path.join(decompliePath, 'smali')
  750. appPackage = None
  751. if application:
  752. appPackage = application[:application.rfind('.')]
  753. appPackage = appPackage.replace('.', '/')
  754. allFiles = []
  755. allFiles = file_utils.list_files(smaliPath, allFiles)
  756. #print('file count is %d' % len(allFiles))
  757. #maxFuncNum = 65535
  758. # 留一点空间,防止计算误差
  759. maxFuncNum = 64000
  760. currFucNum = 0
  761. totalFucNum = 0
  762. currDexIndex = 1
  763. allRefs = []
  764. #保证Application等类在第一个classex.dex文件中
  765. for f in allFiles:
  766. f = f.replace('\\', '/')
  767. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  768. currFucNum += smali_utils.get_smali_method_count(f, allRefs)
  769. totalFucNum = currFucNum
  770. for f in allFiles:
  771. f = f.replace('\\', '/')
  772. if not f.endswith('.smali'):
  773. continue
  774. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  775. continue
  776. thisFucNum = smali_utils.get_smali_method_count(f, allRefs)
  777. totalFucNum += thisFucNum
  778. #print('%d # %d ==> %s' % (thisFucNum, currDexIndex, f))
  779. #print('totalFucNum is %d' % totalFucNum)
  780. if currFucNum + thisFucNum >= maxFuncNum:
  781. currFucNum = thisFucNum
  782. currDexIndex += 1
  783. newDexPath = os.path.join(decompliePath, 'smali_classes%d' % currDexIndex)
  784. os.makedirs(newDexPath)
  785. else:
  786. currFucNum += thisFucNum
  787. if currDexIndex > 1:
  788. newDexPath = os.path.join(decompliePath, 'smali_classes%d' % currDexIndex)
  789. targetFile = newDexPath + f[len(smaliPath):]
  790. file_utils.copyFile(f, targetFile, True)
  791. return 0
  792. def changeVersion(game, sdk, subChannel, config):
  793. '''
  794. 更改版本号
  795. '''
  796. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  797. yml = os.path.join(decompliePath, 'apktool.yml')
  798. versionCode = None
  799. versionName = None
  800. targetSdkVersion = None
  801. if 'versionCode' in config:
  802. versionCode = config['versionCode']
  803. if 'versionName' in config:
  804. versionName = config['versionName']
  805. if 'targetSdkVersion' in config:
  806. targetSdkVersion = config['targetSdkVersion']
  807. return file_utils.changeVersion(yml, versionCode, versionName, targetSdkVersion)
  808. def recomplie(game, sdk, subChannel, config):
  809. '''
  810. 回编译
  811. '''
  812. print('recomplie apk...')
  813. apktoolPath = file_utils.getApkToolPath()
  814. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  815. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  816. return file_utils.execJarCmd(apktoolPath, 'b -f "%s" -o "%s"' % (decompliePath, outApk))
  817. def alignApk(game, sdk, subChannel, config):
  818. '''
  819. 对齐apk
  820. '''
  821. print('align apk...')
  822. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  823. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  824. alignapkTool = file_utils.getAlignPath()
  825. if os.path.exists(alignApk):
  826. os.remove(alignApk)
  827. ret = file_utils.getExecPermission(alignapkTool)
  828. if ret:
  829. return ret
  830. # zipalign.exe -v -p 4 input.apk output.apk
  831. return file_utils.execFormatCmd('"%s" -f -p 4 "%s" "%s"' % (alignapkTool, outApk, alignApk))
  832. def apksignerApk(game, sdk, subChannel, config):
  833. '''
  834. 签名apk
  835. '''
  836. print('sign apk...')
  837. path = os.path.join(file_utils.getCurrentPath(), 'keystore', 'key.json')
  838. jsonText = file_utils.readFile(path)
  839. signConfig = json.loads(jsonText)
  840. keystore = {}
  841. if game in signConfig:
  842. if sdk in signConfig[game] and subChannel in signConfig[game][sdk]:
  843. keystore = signConfig[game][sdk][subChannel]
  844. else:
  845. keystore = signConfig['default']
  846. else:
  847. keystore = signConfig['default']
  848. print('storeFile is "%s"' % keystore['storeFile'])
  849. apksigner = file_utils.getApksignerPath()
  850. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  851. signedApk = file_utils.getSignApkPath(game, sdk, subChannel, config['cache'])
  852. storeFile = os.path.join(file_utils.getCurrentPath(), 'keystore', keystore['storeFile'])
  853. if 'outName' in config and 'outPath' in config:
  854. if not os.path.exists(config['outPath']):
  855. os.makedirs(config['outPath'])
  856. signedApk = os.path.join(config['outPath'], config['outName'] + '.apk')
  857. elif 'outName' in config:
  858. signedApk = file_utils.getRenameApkPath(game, sdk, config['cache'], config['outName'])
  859. # 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
  860. v2disable = ''
  861. if 'v2disable' in config and config['v2disable']:
  862. v2disable = ' --v2-signing-enabled=false'
  863. 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))
  864. def addChannel(game, sdk, subChannel, config):
  865. '''
  866. 添加渠道信息
  867. '''
  868. if 'v2disable' in config and config['v2disable']:
  869. return 0
  870. walle = file_utils.getWallePath()
  871. signedApk = file_utils.getSignApkPath(game, sdk, subChannel, config['cache'])
  872. if 'outName' in config and 'outPath' in config:
  873. signedApk = os.path.join(config['outPath'], config['outName'] + '.apk')
  874. elif 'outName' in config:
  875. signedApk = file_utils.getRenameApkPath(game, sdk, config['cache'], config['outName'])
  876. properties = config['properties']
  877. appid = ''
  878. appkey = ''
  879. if 'appid' in properties:
  880. appid = properties['appid']
  881. if 'appkey' in properties:
  882. appkey = properties['appkey']
  883. return file_utils.execJarCmd(walle, 'put -e version=%s,agent=%s,appid=%s,appkey=%s,host=%s "%s" "%s"' % (config_utils.getDate(), properties['agent'], appid, appkey, properties['host'], signedApk, signedApk))
  884. def clearTemp(game, sdk, subChannel, config):
  885. '''
  886. 清空中间产生的文件
  887. '''
  888. print('clear temp...')
  889. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  890. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  891. if os.path.exists(alignApk):
  892. os.remove(alignApk)
  893. if os.path.exists(outApk):
  894. os.remove(outApk)
  895. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  896. file_utils.deleteFolder(decompliePath)
  897. print('clear temp end')
  898. def packConsoleInput():
  899. '''
  900. 控制台打包
  901. '''
  902. if len(sys.argv) < 3:
  903. print('argument is missing')
  904. return 1
  905. # 校验参数
  906. game = sys.argv[1]
  907. sdk = sys.argv[2]
  908. # 可选参数,没有则默认打全部渠道
  909. subChannel = None
  910. if len(sys.argv) > 3:
  911. subChannel = sys.argv[3]
  912. return packConsole(game, sdk, subChannel)
  913. def packConsole(game, sdk, subChannel):
  914. '''
  915. 控制台打包
  916. '''
  917. if not os.path.exists(file_utils.getFullGameApk(game)):
  918. print('game "%s" not exists' % game)
  919. return 1
  920. if not os.path.exists(file_utils.getFullSDKPath(sdk)):
  921. print('sdk "%s" not exists' % sdk)
  922. return 1
  923. # 读取配置
  924. channelPath = file_utils.getChannelPath(game, sdk)
  925. configPath = os.path.join(channelPath, 'config.json')
  926. if not os.path.exists(configPath):
  927. print('%s not exists' % configPath)
  928. return 1
  929. jsonText = file_utils.readFile(configPath)
  930. config = json.loads(jsonText)
  931. # 检查参数
  932. if not config_utils.checkConfig(config):
  933. return 1
  934. # 处理参数
  935. config_utils.replaceArgs(config)
  936. successCount = 0
  937. failureCount = 0
  938. if type(config) == dict:
  939. if subChannel is None or config['subChannel'] == subChannel:
  940. ret = pack(game, sdk, config)
  941. if ret:
  942. failureCount += 1
  943. else:
  944. successCount += 1
  945. else:
  946. print('subChannel "%s" no found' % subChannel)
  947. return 1
  948. elif type(config) == list:
  949. found = False
  950. for itemConfig in config:
  951. if subChannel is None or itemConfig['subChannel'] == subChannel:
  952. found = True
  953. ret = pack(game, sdk, itemConfig)
  954. if ret:
  955. failureCount += 1
  956. else:
  957. successCount += 1
  958. if not found:
  959. print('subChannel "%s" no found' % subChannel)
  960. return 1
  961. print('success %d, failure %d' % (successCount, failureCount))
  962. return 0