package_utils_record.py 34 KB

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