package_utils_record.py 36 KB

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