package_utils_record.py 34 KB

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