package_utils.py 36 KB

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