package_utils_record.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  452. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  453. activity = xml_utils.getLauncherActivityName(manifest)
  454. if activity == 'com.shanshen.sdk.template.LauncherActivity':
  455. print('add launcher already exist...')
  456. return 1
  457. # 添加关联资源
  458. internalPath = os.path.join(file_utils.getCurrentPath(), 'internal_shanshen')
  459. ret = copyAppResWithType(decompliePath, internalPath, 'launcher_res')
  460. if ret:
  461. return ret
  462. # 拷贝代码
  463. print('copy launcher code...')
  464. codePath = os.path.join(internalPath, 'launcher_code', 'smali')
  465. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  466. ret = file_utils.copyFileAllDir(codePath, smaliPath)
  467. if ret:
  468. return ret
  469. # 修改主文件信息
  470. print('change launcher config...')
  471. orientation = xml_utils.getScreenOrientation(manifest)
  472. activity = xml_utils.removeLauncherActivity(manifest)
  473. xml_utils.addLauncherActivity(manifest, orientation, 'com.shanshen.sdk.template.LauncherActivity')
  474. # 修改跳转的
  475. launcherActivity = os.path.join(decompliePath, 'smali', 'com', 'shanshen', 'sdk', 'template', 'LauncherActivity.smali')
  476. file_utils.replaceContent(launcherActivity, '{class}', activity)
  477. print('change launcher %s to %s' % (activity, 'com.shanshen.sdk.template.LauncherActivity'))
  478. # config['oldLauncher'] = activity
  479. if 'launcherTime' in config:
  480. timeHex = formatHex(config['launcherTime'])
  481. file_utils.replaceContent(launcherActivity, '0x0BB8', timeHex)
  482. return 0
  483. def addMoreIcon(game, sdk, subChannel, config):
  484. '''
  485. 添加多个图标
  486. '''
  487. print('add more icon support...')
  488. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  489. icon = '@mipmap/common_sdk_icon'
  490. if not config['changeIcon']:
  491. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  492. icon = xml_utils.getApplicationAttr(manifest, 'icon')
  493. switchIcon = icon
  494. if config['switchIcon']:
  495. switchIcon = '@mipmap/common_sdk_icon2'
  496. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  497. return xml_utils.addMoreIcon(manifest, icon, switchIcon)
  498. def formatHex(millisecond):
  499. '''
  500. 将毫秒转为16进制,4位格式
  501. '''
  502. timeHex = str(hex(millisecond)).upper()
  503. timeHex = timeHex[2:]
  504. formatHex = ''
  505. if len(timeHex) == 3:
  506. formatHex = '0x0' + timeHex
  507. elif len(timeHex) == 4:
  508. formatHex = '0x' + timeHex
  509. else:
  510. formatHex = '0x0BB8'
  511. return formatHex
  512. def doSDKPostScript(game, sdk, config):
  513. '''
  514. 执行sdk相关特殊处理脚本
  515. '''
  516. sdkPath = file_utils.getFullSDKPath(sdk)
  517. scriptPath = os.path.join(sdkPath, 'script')
  518. targetScript = os.path.join(scriptPath, 'sdk_script.py')
  519. if not os.path.exists(targetScript):
  520. print('sdk_script no exists')
  521. return 0
  522. print('doSDKPostScript...')
  523. sys.path.append(scriptPath)
  524. module = importlib.import_module('sdk_script')
  525. ret = module.execute(game, sdk, config)
  526. sys.path.remove(scriptPath)
  527. return ret
  528. def doGamePostScript(game, sdk, config):
  529. '''
  530. 执行游戏相关特殊处理脚本
  531. '''
  532. channelPath = file_utils.getFullGamePath(game)
  533. scriptPath = os.path.join(channelPath, 'script')
  534. targetScript = os.path.join(scriptPath, 'game_script.py')
  535. if not os.path.exists(targetScript):
  536. print('game_script no exists')
  537. return 0
  538. print('doGamePostScript...')
  539. sys.path.append(scriptPath)
  540. module = importlib.import_module('game_script')
  541. ret = module.execute(game, sdk, config)
  542. sys.path.remove(scriptPath)
  543. return ret
  544. def generateNewRFile(game, sdk, subChannel, config):
  545. '''
  546. 生成新的R文件
  547. '''
  548. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  549. aapt = file_utils.getAAPTPath()
  550. androidPlatforms = file_utils.getAndroidCompileToolPath()
  551. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  552. decomplieResPath = file_utils.getFullPath(decompliePath, 'res')
  553. compliePath = file_utils.getFullPath(decompliePath, 'gen')
  554. if not os.path.exists(compliePath):
  555. os.makedirs(compliePath)
  556. ret = file_utils.getExecPermission(aapt)
  557. if ret:
  558. return ret
  559. # 生成R文件
  560. print('create R.java ...')
  561. createRCmd = '"%s" p -f -m -J "%s" -S "%s" -I "%s" -M "%s"' % (aapt, compliePath, decomplieResPath, androidPlatforms, manifest)
  562. ret = file_utils.execFormatCmd(createRCmd)
  563. if ret:
  564. return ret
  565. # 编译R文件
  566. print('complie R.java ...')
  567. packageName = xml_utils.getPackageName(manifest)
  568. packagePath = file_utils.getPackagePath(compliePath, packageName)
  569. RSourceFile = os.path.join(packagePath, 'R.java')
  570. complieRCmd = 'javac -source 1.7 -target 1.7 -encoding UTF-8 "%s"' % RSourceFile
  571. ret = file_utils.execFormatCmd(complieRCmd)
  572. if ret:
  573. return ret
  574. # 生成dex
  575. print('dex R.class ...')
  576. dx = file_utils.getDxPath()
  577. outDex = os.path.join(compliePath, 'classes.dex')
  578. ret = file_utils.execJarCmd(dx, '--dex --output="%s" "%s"' % (outDex, compliePath))
  579. if ret:
  580. return ret
  581. # 反向dex生成smali
  582. # 存放在out目录
  583. print('baksmali classes.dex ...')
  584. baksmaliPath = file_utils.getBaksmaliPath()
  585. outPath = file_utils.getFullPath(decompliePath, 'out')
  586. ret = file_utils.execJarCmd(baksmaliPath, '-o "%s" "%s"' % (outPath, outDex))
  587. if ret:
  588. return ret
  589. # 将生成的文件拷贝到目标目录
  590. print('copy R.smali ...')
  591. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  592. file_utils.copyFileAllDir(outPath, smaliPath)
  593. return 0
  594. def packJar(game, sdk, subChannel, config):
  595. '''
  596. 打包所有的jar
  597. '''
  598. splitDex = config['splitDex']
  599. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  600. outPath = file_utils.getFullPath(decompliePath, 'gen')
  601. dx = file_utils.getDxPath()
  602. if not os.path.exists(outPath):
  603. os.makedirs(outPath)
  604. # --no-warning
  605. dexCmd = '--dex --multi-dex --no-warning --output="%s"' % outPath
  606. # 找到所有lib依赖
  607. sdkPath = file_utils.getFullSDKPath(sdk)
  608. libs = os.path.join(sdkPath, 'libs')
  609. libConfig = os.path.join(libs, 'config.json')
  610. # 存在配置文件
  611. if os.path.exists(libConfig):
  612. jsonText = file_utils.readFile(libConfig)
  613. libConf = json.loads(jsonText)
  614. if 'libConfig' in config and config['libConfig'] in libConf:
  615. conf = config['libConfig']
  616. libList = libConf[conf]
  617. for jar in libList:
  618. dexCmd += ' ' + os.path.join(libs, jar)
  619. else:
  620. for jar in os.listdir(libs):
  621. if not jar.endswith('.jar'):
  622. continue
  623. dexCmd += ' ' + os.path.join(libs, jar)
  624. else:
  625. for jar in os.listdir(libs):
  626. if not jar.endswith('.jar'):
  627. continue
  628. dexCmd += ' ' + os.path.join(libs, jar)
  629. # multidex.jar
  630. if splitDex:
  631. dexCmd += ' ' + file_utils.getMultiDexPath()
  632. # sdk实现类
  633. print('packageing all jar ...')
  634. ret = file_utils.execJarCmd(dx, dexCmd)
  635. if ret:
  636. return ret
  637. # 反向dex生成smali
  638. # 存放在out目录
  639. print('baksmali classes.dex ...')
  640. outDex = os.path.join(outPath, 'classes.dex')
  641. baksmaliPath = file_utils.getBaksmaliPath()
  642. outPath = file_utils.getFullPath(decompliePath, 'out')
  643. ret = file_utils.execJarCmd(baksmaliPath, '-o "%s" "%s"' % (outPath, outDex))
  644. if ret:
  645. return ret
  646. # 将生成的文件拷贝到目标目录
  647. print('copy all smali ...')
  648. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  649. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  650. if ret:
  651. return ret
  652. return 0
  653. def splitDex(game, sdk, subChannel, config):
  654. '''
  655. 分割dex
  656. '''
  657. # 判断是否已经存在application
  658. # 存在,则往原application添加内容
  659. # 不存在,则拷贝一个默认的android.support.multidex.MultiDexApplication
  660. print('add MultiDex support...')
  661. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  662. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  663. application = xml_utils.getApplicationAttr(manifest, 'name')
  664. if application is None:
  665. ret = xml_utils.changeApplicationAttr(manifest, 'name', 'android.support.multidex.MultiDexApplication')
  666. if ret:
  667. return ret
  668. else:
  669. smaliPath = os.path.join(decompliePath, 'smali')
  670. applicationFile = file_utils.getPackagePath(smaliPath, application)
  671. applicationFile += '.smali'
  672. ret = changeApplicationDex(applicationFile)
  673. if ret:
  674. return ret
  675. return splitSmali(game, sdk, subChannel, config, application)
  676. def changeApplicationDex(file):
  677. '''
  678. 修改application的smali文件,增加MultiDex操作
  679. '''
  680. index = file_utils.getApplicationSmaliIndex(file)
  681. file_utils.insertApplicationSmali(file, index)
  682. return 0
  683. def splitSmali(game, sdk, subChannel, config, application):
  684. '''
  685. 如果函数上限超过限制,自动拆分smali,以便生成多个dex文件
  686. '''
  687. print('splitSmali...')
  688. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  689. smaliPath = os.path.join(decompliePath, 'smali')
  690. appPackage = None
  691. if application:
  692. appPackage = application[:application.rfind('.')]
  693. appPackage = appPackage.replace('.', '/')
  694. allFiles = []
  695. allFiles = file_utils.list_files(smaliPath, allFiles)
  696. #print('file count is %d' % len(allFiles))
  697. #maxFuncNum = 65535
  698. # 留一点空间,防止计算误差
  699. maxFuncNum = 64000
  700. currFucNum = 0
  701. totalFucNum = 0
  702. currDexIndex = 1
  703. allRefs = []
  704. #保证Application等类在第一个classex.dex文件中
  705. for f in allFiles:
  706. f = f.replace('\\', '/')
  707. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  708. currFucNum += smali_utils.get_smali_method_count(f, allRefs)
  709. totalFucNum = currFucNum
  710. for f in allFiles:
  711. f = f.replace('\\', '/')
  712. if not f.endswith('.smali'):
  713. continue
  714. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  715. continue
  716. thisFucNum = smali_utils.get_smali_method_count(f, allRefs)
  717. totalFucNum += thisFucNum
  718. #print('%d # %d ==> %s' % (thisFucNum, currDexIndex, f))
  719. #print('totalFucNum is %d' % totalFucNum)
  720. if currFucNum + thisFucNum >= maxFuncNum:
  721. currFucNum = thisFucNum
  722. currDexIndex += 1
  723. newDexPath = os.path.join(decompliePath, 'smali_classes%d' % currDexIndex)
  724. os.makedirs(newDexPath)
  725. else:
  726. currFucNum += thisFucNum
  727. if currDexIndex > 1:
  728. newDexPath = os.path.join(decompliePath, 'smali_classes%d' % currDexIndex)
  729. targetFile = newDexPath + f[len(smaliPath):]
  730. file_utils.copyFile(f, targetFile, True)
  731. return 0
  732. def changeVersion(game, sdk, subChannel, config):
  733. '''
  734. 更改版本号
  735. '''
  736. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  737. yml = os.path.join(decompliePath, 'apktool.yml')
  738. versionCode = None
  739. versionName = None
  740. targetSdkVersion = None
  741. if 'versionCode' in config:
  742. versionCode = config['versionCode']
  743. if 'versionName' in config:
  744. versionName = config['versionName']
  745. if 'targetSdkVersion' in config:
  746. targetSdkVersion = config['targetSdkVersion']
  747. return file_utils.changeVersion(yml, versionCode, versionName, targetSdkVersion)
  748. def recomplie(game, sdk, subChannel, config):
  749. '''
  750. 回编译
  751. '''
  752. print('recomplie apk...')
  753. apktoolPath = file_utils.getApkToolPath()
  754. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  755. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  756. return file_utils.execJarCmd(apktoolPath, 'b -f "%s" -o "%s"' % (decompliePath, outApk))
  757. def alignApk(game, sdk, subChannel, config):
  758. '''
  759. 对齐apk
  760. '''
  761. print('align apk...')
  762. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  763. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  764. alignapkTool = file_utils.getAlignPath()
  765. if os.path.exists(alignApk):
  766. os.remove(alignApk)
  767. ret = file_utils.getExecPermission(alignapkTool)
  768. if ret:
  769. return ret
  770. # zipalign.exe -v -p 4 input.apk output.apk
  771. return file_utils.execFormatCmd('"%s" -f -p 4 "%s" "%s"' % (alignapkTool, outApk, alignApk))
  772. def apksignerApk(game, sdk, subChannel, config):
  773. '''
  774. 签名apk
  775. '''
  776. print('sign apk...')
  777. path = os.path.join(file_utils.getCurrentPath(), 'keystore', 'key.json')
  778. jsonText = file_utils.readFile(path)
  779. signConfig = json.loads(jsonText)
  780. keystore = {}
  781. if game in signConfig:
  782. if sdk in signConfig[game] and subChannel in signConfig[game][sdk]:
  783. keystore = signConfig[game][sdk][subChannel]
  784. else:
  785. keystore = signConfig['default']
  786. else:
  787. keystore = signConfig['default']
  788. print('storeFile is "%s"' % keystore['storeFile'])
  789. apksigner = file_utils.getApksignerPath()
  790. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  791. signedApk = file_utils.getSignApkPath(game, sdk, subChannel, config['cache'])
  792. storeFile = os.path.join(file_utils.getCurrentPath(), 'keystore', keystore['storeFile'])
  793. if 'outName' in config and 'outPath' in config:
  794. if not os.path.exists(config['outPath']):
  795. os.makedirs(config['outPath'])
  796. signedApk = os.path.join(config['outPath'], config['outName'] + '.apk')
  797. elif 'outName' in config:
  798. signedApk = file_utils.getRenameApkPath(game, sdk, config['cache'], config['outName'])
  799. # 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
  800. v2disable = ''
  801. if 'v2disable' in config and config['v2disable']:
  802. v2disable = ' --v2-signing-enabled=false'
  803. 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))
  804. def addChannel(game, sdk, subChannel, config):
  805. '''
  806. 添加渠道信息
  807. '''
  808. if 'v2disable' in config and config['v2disable']:
  809. return 0
  810. walle = file_utils.getWallePath()
  811. signedApk = file_utils.getSignApkPath(game, sdk, subChannel, config['cache'])
  812. if 'outName' in config and 'outPath' in config:
  813. signedApk = os.path.join(config['outPath'], config['outName'] + '.apk')
  814. elif 'outName' in config:
  815. signedApk = file_utils.getRenameApkPath(game, sdk, config['cache'], config['outName'])
  816. properties = config['properties']
  817. appid = ''
  818. appkey = ''
  819. if 'appid' in properties:
  820. appid = properties['appid']
  821. if 'appkey' in properties:
  822. appkey = properties['appkey']
  823. 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))
  824. def clearTemp(game, sdk, subChannel, config):
  825. '''
  826. 清空中间产生的文件
  827. '''
  828. print('clear temp...')
  829. alignApk = file_utils.getAlignApkPath(game, sdk, subChannel, config['cache'])
  830. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  831. if os.path.exists(alignApk):
  832. os.remove(alignApk)
  833. if os.path.exists(outApk):
  834. os.remove(outApk)
  835. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  836. file_utils.deleteFolder(decompliePath)
  837. print('clear temp end')
  838. def packConsoleInput():
  839. '''
  840. 控制台打包
  841. '''
  842. if len(sys.argv) < 3:
  843. print('argument is missing')
  844. return 1
  845. # 校验参数
  846. game = sys.argv[1]
  847. sdk = sys.argv[2]
  848. # 可选参数,没有则默认打全部渠道
  849. subChannel = None
  850. if len(sys.argv) > 3:
  851. subChannel = sys.argv[3]
  852. return packConsole(game, sdk, subChannel)
  853. def packConsole(game, sdk, subChannel):
  854. '''
  855. 控制台打包
  856. '''
  857. if not os.path.exists(file_utils.getFullGameApk(game)):
  858. print('game "%s" not exists' % game)
  859. return 1
  860. if not os.path.exists(file_utils.getFullSDKPath(sdk)):
  861. print('sdk "%s" not exists' % sdk)
  862. return 1
  863. # 读取配置
  864. channelPath = file_utils.getChannelPath(game, sdk)
  865. configPath = os.path.join(channelPath, 'config.json')
  866. if not os.path.exists(configPath):
  867. print('%s not exists' % configPath)
  868. return 1
  869. jsonText = file_utils.readFile(configPath)
  870. config = json.loads(jsonText)
  871. # 检查参数
  872. if not config_utils_record.checkConfig(config):
  873. return 1
  874. # 处理参数
  875. config_utils_record.replaceArgs(config)
  876. successCount = 0
  877. failureCount = 0
  878. if type(config) == dict:
  879. if subChannel is None or config['subChannel'] == subChannel:
  880. ret = pack(game, sdk, config)
  881. if ret:
  882. failureCount += 1
  883. else:
  884. successCount += 1
  885. else:
  886. print('subChannel "%s" no found' % subChannel)
  887. return 1
  888. elif type(config) == list:
  889. found = False
  890. for itemConfig in config:
  891. if subChannel is None or itemConfig['subChannel'] == subChannel:
  892. found = True
  893. ret = pack(game, sdk, itemConfig)
  894. if ret:
  895. failureCount += 1
  896. else:
  897. successCount += 1
  898. if not found:
  899. print('subChannel "%s" no found' % subChannel)
  900. return 1
  901. print('success %d, failure %d' % (successCount, failureCount))
  902. return 0