package_utils.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  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 re
  14. import file_utils
  15. import xml_utils
  16. import smali_utils
  17. import config_utils
  18. import game_utils
  19. import common_utils
  20. import os
  21. import os.path
  22. import json
  23. import sys
  24. import importlib
  25. import uuid
  26. import zipfile
  27. import time
  28. import datetime
  29. ignoreLauncher = ['jm_ysdk', 'jm_yijie', 'jm_quick',
  30. 'jm_beiyu', 'jm_xq_jrtt', 'jm_zy_ysdk']
  31. adaptApp = ['yjzx']
  32. startTime = ''
  33. def pack(game, sdk, config):
  34. config['cache'] = uuid.uuid1()
  35. subChannel = config['subChannel']
  36. print('game = %s, sdk = %s, subChannel = %s, ...' %
  37. (game, sdk, subChannel))
  38. # 解包
  39. ret = decomplie(game, sdk, subChannel, config)
  40. if ret:
  41. return ret
  42. # 删除旧代码
  43. ret = removeOldCode(game, sdk, subChannel, config)
  44. if ret:
  45. return ret
  46. # 删除一些不支持的属性
  47. ret = removeNoSupportAttr(game, sdk, subChannel, config)
  48. if ret:
  49. return ret
  50. # 删除一些不支持的配置
  51. ret = fixUnSupportConfig(game, sdk, subChannel, config)
  52. if ret:
  53. return ret
  54. # 合并Drawable-v4目录
  55. ret = mergeDrawableRes(game, sdk, subChannel, config)
  56. if ret:
  57. return ret
  58. # 移除相同的资源
  59. ret = removeSameRes(game, sdk, subChannel, config)
  60. if ret:
  61. return ret
  62. # 复制res资源
  63. ret = copyRes(game, sdk, subChannel, config)
  64. if ret:
  65. return ret
  66. # 合并主文件
  67. ret = mergeManifestRes(game, sdk, subChannel, config)
  68. if ret:
  69. return ret
  70. # 替换占位符
  71. ret = changePlaceholders(game, sdk, subChannel, config)
  72. if ret:
  73. return ret
  74. # 添加meta-data
  75. ret = addMetaData(game, sdk, subChannel, config)
  76. if ret:
  77. return ret
  78. # 增加配置文件
  79. ret = addConfig(game, sdk, subChannel, config)
  80. if ret:
  81. return ret
  82. # 复制app res资源
  83. ret = copyAppRes(game, sdk, subChannel, config)
  84. if ret:
  85. return ret
  86. # 更改包名
  87. if 'packageName' in config and config['packageName'] != '':
  88. ret = changePackageName(game, sdk, subChannel, config)
  89. if ret:
  90. return ret
  91. # 更改app名
  92. if 'name' in config and config['name'] != '':
  93. ret = changeAppName(game, sdk, subChannel, config)
  94. if ret:
  95. return ret
  96. # 更改app icon
  97. if config['changeIcon']:
  98. ret = changeAppIcon(game, sdk, subChannel, config)
  99. if ret:
  100. return ret
  101. # 添加启动图操作
  102. if config['addLauncher']:
  103. ret = addLauncher(game, sdk, subChannel, config)
  104. if ret:
  105. return ret
  106. # 添加多图标
  107. # ret = addMoreIcon(game, sdk, subChannel, config)
  108. # 复制icon图标到res
  109. ret = copyIcon(game, sdk, subChannel, config)
  110. # if ret:
  111. # return ret
  112. # 打包lib依赖
  113. ret = packJar(game, sdk, subChannel, config)
  114. if ret:
  115. return ret
  116. # 继承JMApplication
  117. common_utils.changeApplication(
  118. game, sdk, subChannel, config, 'com.jmhy.sdk.common.JMApplication')
  119. # sdk脚本处理
  120. ret = doSDKPostScript(game, sdk, config)
  121. if ret:
  122. return ret
  123. # 乐变sdk的特殊处理
  124. ret = game_utils.sdkLebianChange(game, sdk, config)
  125. if ret:
  126. return ret
  127. # 游戏脚本处理
  128. ret = doGamePostScript(game, sdk, config)
  129. if ret:
  130. return ret
  131. # 游戏独立处理
  132. ret = doGameScript(game, sdk, config)
  133. if ret:
  134. return ret
  135. # 格式化Xml
  136. # ret = formatXml(game, sdk, subChannel, config)
  137. # if ret:
  138. # return ret
  139. # log sdk
  140. if 'logSdk' in config:
  141. for log in config['logSdk']:
  142. ret = addLogSdk(game, sdk, subChannel, config, log)
  143. if ret:
  144. return ret
  145. # oaid sdk
  146. ret = addOaidSdk(game, sdk, subChannel, config, "1.0.10")
  147. if ret:
  148. return ret
  149. # 生成R文件
  150. '''ret = generateNewRFile(game, sdk, subChannel, config)
  151. if ret:
  152. return ret'''
  153. # 添加MultiDex支持
  154. if config['splitDex']:
  155. ret = splitDex(game, sdk, subChannel, config)
  156. if ret:
  157. return ret
  158. # 更改版本号
  159. ret = changeVersion(game, sdk, subChannel, config)
  160. if ret:
  161. return ret
  162. # 更改HardwareAccelerated属性
  163. ret = replaceAmHardwareAccelerated(game, sdk, subChannel, config)
  164. if ret:
  165. return ret
  166. # 回编译
  167. ret = recomplie(game, sdk, subChannel, config)
  168. if ret:
  169. return ret
  170. # 对齐apk
  171. ret = alignApk(game, sdk, subChannel, config)
  172. if ret:
  173. return ret
  174. # 签名
  175. ret = apksignerApk(game, sdk, subChannel, config)
  176. if ret:
  177. return ret
  178. # 添加渠道信息
  179. ret = addChannel(game, sdk, subChannel, config)
  180. if ret:
  181. return ret
  182. ret = copyApk2OutDir(game, sdk, subChannel, config)
  183. if ret:
  184. return ret
  185. # 清理产生的中间文件
  186. if config['clearCache']:
  187. clearTemp(game, sdk, subChannel, config)
  188. endTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  189. d1 = datetime.datetime.strptime(endTime, '%Y-%m-%d %H:%M:%S')
  190. d2 = datetime.datetime.strptime(startTime, '%Y-%m-%d %H:%M:%S')
  191. d = d1 - d2
  192. print('开始时间:' + startTime)
  193. print('结束时间:' + endTime)
  194. print('用时:{}'.format(config_utils.getTime(d.seconds)))
  195. return 0
  196. def decomplie(game, sdk, subChannel, config):
  197. '''
  198. 解包
  199. '''
  200. apktoolPath = file_utils.getApkToolPath()
  201. # gamePath = file_utils.getFullGameApk(game)
  202. cacheGameApk = file_utils.getCacheGameApk(game, config['random'], sdk)
  203. decompliePath = file_utils.getDecompliePath(
  204. game, sdk, subChannel, config['cache'])
  205. if os.path.exists(decompliePath):
  206. print('delete decomplie folder...')
  207. file_utils.deleteFolder(decompliePath)
  208. print('decomplie apk...')
  209. return file_utils.execJarCmd(apktoolPath, 'd -f "%s" -o "%s"' % (cacheGameApk, decompliePath))
  210. def removeOldCode(game, sdk, subChannel, config):
  211. '''
  212. 删除旧代码
  213. '''
  214. decompliePath = file_utils.getDecompliePath(
  215. game, sdk, subChannel, config['cache'])
  216. codePath = os.path.join(decompliePath, 'smali', 'com', 'jmhy', 'sdk')
  217. # file_utils.deleteFolder(codePath)
  218. allFiles = []
  219. allFiles = file_utils.list_files(codePath, allFiles)
  220. for f in allFiles:
  221. fpath, fname = os.path.split(f) # 分离文件名和路径
  222. if fname == 'R.smali' or fname.startswith('R$'):
  223. continue
  224. os.remove(f)
  225. # print('remove %s' % f)
  226. return 0
  227. def copyRes(game, sdk, subChannel, config):
  228. '''
  229. 复制res资源
  230. '''
  231. # 拷贝sdk资源
  232. print('copy res...')
  233. decompliePath = file_utils.getDecompliePath(
  234. game, sdk, subChannel, config['cache'])
  235. sdkPath = file_utils.getFullSDKPath(sdk)
  236. resPath = os.path.join(sdkPath, 'res')
  237. decomplieResPath = file_utils.getFullPath(decompliePath, 'res')
  238. for d in os.listdir(resPath):
  239. copyResWithType(resPath, decomplieResPath, d)
  240. # 拷贝assets
  241. print('copy assets...')
  242. assetsPath = file_utils.getFullPath(sdkPath, 'assets')
  243. decomplieAssetsPath = file_utils.getFullPath(decompliePath, 'assets')
  244. if os.path.exists(assetsPath):
  245. ret = file_utils.copyFileAllDir(assetsPath, decomplieAssetsPath)
  246. if ret:
  247. return ret
  248. # 拷贝jniLib
  249. print('copy jniLibs...')
  250. jniPath = file_utils.getFullPath(sdkPath, 'jniLibs')
  251. decomplieJniPath = file_utils.getFullPath(decompliePath, 'lib')
  252. abiFilters = []
  253. if os.path.exists(decomplieJniPath):
  254. for abi in os.listdir(decomplieJniPath):
  255. # if abi == 'armeabi-v7a' or abi == 'armeabi' or abi == 'arm64-v8a':
  256. print('append : ' + abi)
  257. abiFilters.append(abi)
  258. else:
  259. abiFilters = ['armeabi-v7a']
  260. if os.path.exists(jniPath):
  261. ret = file_utils.copyFileAllDir(
  262. jniPath, decomplieJniPath, False, abiFilters)
  263. if ret:
  264. return ret
  265. return 0
  266. def mergeDrawableRes(game, sdk, subChannel, config):
  267. '''
  268. 合并Drawable-v4目录
  269. '''
  270. print('merge drawable path...')
  271. decompliePath = file_utils.getDecompliePath(
  272. game, sdk, subChannel, config['cache'])
  273. resPath = os.path.join(decompliePath, 'res')
  274. for path in os.listdir(resPath):
  275. # print('res path %s' % path)
  276. if (path.startswith('drawable') or path.startswith('mipmap')) and path.endswith('-v4'):
  277. # print('merge path %s' % path)
  278. v4DrawablePath = os.path.join(resPath, path)
  279. drawablePath = os.path.join(resPath, path[:-3])
  280. if os.path.exists(drawablePath):
  281. ret = file_utils.copyFileAllDir(
  282. v4DrawablePath, drawablePath, True)
  283. if ret:
  284. return ret
  285. else:
  286. os.rename(v4DrawablePath, drawablePath)
  287. return 0
  288. def removeSameRes(game, sdk, subChannel, config):
  289. '''
  290. 移除相同的资源
  291. '''
  292. # 读取sdk的资源
  293. print('remove same res...')
  294. sdkPath = file_utils.getFullSDKPath(sdk)
  295. sdkResPath = os.path.join(sdkPath, 'res')
  296. resList = []
  297. for path in os.listdir(sdkResPath):
  298. if not path.startswith('values'):
  299. continue
  300. absPath = os.path.join(sdkResPath, path)
  301. for resFile in os.listdir(absPath):
  302. '''if not resFile.startswith('jm_'):
  303. continue'''
  304. if resFile.endswith('.DS_Store'):
  305. continue
  306. # print('readAllRes -- > ' + os.path.join(absPath, resFile))
  307. resList = xml_utils.readAllRes(
  308. os.path.join(absPath, resFile), resList)
  309. if len(resList) == 0:
  310. print('no same res found')
  311. return 0
  312. # 移除相同的资源
  313. decompliePath = file_utils.getDecompliePath(
  314. game, sdk, subChannel, config['cache'])
  315. resPath = os.path.join(decompliePath, 'res')
  316. for path in os.listdir(resPath):
  317. if not path.startswith('values'):
  318. continue
  319. absPath = os.path.join(resPath, path)
  320. for resFile in os.listdir(absPath):
  321. xml_utils.removeSameRes(os.path.join(absPath, resFile), resList)
  322. return 0
  323. def mergeManifestRes(game, sdk, subChannel, config):
  324. '''
  325. 合并主文件
  326. '''
  327. print('merge AndroidManifest...')
  328. decompliePath = file_utils.getDecompliePath(
  329. game, sdk, subChannel, config['cache'])
  330. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  331. sdkPath = file_utils.getFullSDKPath(sdk)
  332. libManifest = file_utils.getFullPath(sdkPath, 'manifest.xml')
  333. return xml_utils.mergeManifestRes(manifest, libManifest)
  334. def copyAppRes(game, sdk, subChannel, config):
  335. '''
  336. 拷贝app的资源,比如app icon、启动图等
  337. '''
  338. random = config['random']
  339. channelPath = file_utils.getSubChannelPath(game, sdk, random, subChannel)
  340. decompliePath = file_utils.getDecompliePath(
  341. game, sdk, subChannel, config['cache'])
  342. # assets
  343. print('copy assets...')
  344. # 适配一剑斩仙
  345. if game in adaptApp:
  346. print('适配一剑斩仙...')
  347. decomplieAssetsPath = file_utils.getFullPath(decompliePath, 'assets')
  348. skinZipPath = os.path.join(decomplieAssetsPath, 'skin.zip')
  349. skinPath = os.path.join(decomplieAssetsPath, 'skin')
  350. if os.path.exists(skinZipPath):
  351. with zipfile.ZipFile(skinZipPath) as zf:
  352. zf.extractall(decomplieAssetsPath)
  353. print('create unzip skin')
  354. assetsPath = file_utils.getFullPath(channelPath, 'assets')
  355. decomplieAssetsPath = file_utils.getFullPath(
  356. decompliePath, 'assets')
  357. if os.path.exists(assetsPath):
  358. ret = file_utils.copyFileAllDir(
  359. assetsPath, decomplieAssetsPath)
  360. with zipfile.ZipFile(skinZipPath, 'w') as z:
  361. for root, dirs, files in os.walk(skinPath):
  362. for single_file in files:
  363. filepath = os.path.join(root, single_file)
  364. print('create zip ---> ' + filepath)
  365. temPath = 'skin/' + single_file
  366. z.write(filepath, temPath)
  367. z.close()
  368. else:
  369. print('normal copy assets...')
  370. assetsPath = file_utils.getFullPath(channelPath, 'assets')
  371. decomplieAssetsPath = file_utils.getFullPath(
  372. decompliePath, 'assets')
  373. if os.path.exists(assetsPath):
  374. ret = file_utils.copyFileAllDir(
  375. assetsPath, decomplieAssetsPath)
  376. if ret:
  377. return ret
  378. else:
  379. print('normal copy assets...')
  380. assetsPath = file_utils.getFullPath(channelPath, 'assets')
  381. decomplieAssetsPath = file_utils.getFullPath(decompliePath, 'assets')
  382. if os.path.exists(assetsPath):
  383. ret = file_utils.copyFileAllDir(assetsPath, decomplieAssetsPath)
  384. if ret:
  385. return ret
  386. # icon
  387. print('copy icon...')
  388. ret = copyAppResWithType(decompliePath, channelPath, 'icon')
  389. if ret:
  390. return ret
  391. # 启动图
  392. print('copy splash...')
  393. ret = copyAppResWithType(decompliePath, channelPath, 'splash')
  394. if ret:
  395. return ret
  396. # 其他图片
  397. print('copy image...')
  398. ret = copyAppResWithType(decompliePath, channelPath, 'image')
  399. if ret:
  400. return ret
  401. return 0
  402. def copyAppResWithType(decompliePath, channelPath, typeName):
  403. decomplieResPath = os.path.join(decompliePath, 'res')
  404. iconPath = os.path.join(channelPath, typeName)
  405. if not os.path.exists(iconPath):
  406. print('dir "%s" not exists' % iconPath)
  407. return 0
  408. for d in os.listdir(iconPath):
  409. ret = copyResWithType(iconPath, decomplieResPath, d)
  410. if ret:
  411. return ret
  412. return 0
  413. def copyResWithType(resPath, decomplieResPath, typeName):
  414. # appt的打包目录会带-v4后缀
  415. resDir = os.path.join(resPath, typeName)
  416. target = os.path.join(decomplieResPath, typeName)
  417. targetV4 = os.path.join(decomplieResPath, typeName + '-v4')
  418. if not os.path.exists(target) and not os.path.exists(targetV4):
  419. os.makedirs(target)
  420. return file_utils.copyFileAllDir(resDir, target, False)
  421. elif not os.path.exists(target):
  422. return file_utils.copyFileAllDir(resDir, targetV4, False)
  423. else:
  424. return file_utils.copyFileAllDir(resDir, target, False)
  425. def removeNoSupportAttr(game, sdk, subChannel, config):
  426. '''
  427. 删除一些不支持的属性
  428. '''
  429. decompliePath = file_utils.getDecompliePath(
  430. game, sdk, subChannel, config['cache'])
  431. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  432. xml_utils.removeRootAttr(manifest, 'compileSdkVersion')
  433. xml_utils.removeRootAttr(manifest, 'compileSdkVersionCodename')
  434. return 0
  435. def fixUnSupportConfig(game, sdk, subChannel, config):
  436. '''
  437. 删除一些不支持的配置
  438. '''
  439. # 检查minSdkVersion
  440. decompliePath = file_utils.getDecompliePath(
  441. game, sdk, subChannel, config['cache'])
  442. yml = os.path.join(decompliePath, 'apktool.yml')
  443. minSdkVersion = 15
  444. file_utils.changeMinSdkVersion(yml, minSdkVersion)
  445. resPath = os.path.join(decompliePath, 'res')
  446. tag = '-v'
  447. for res in os.listdir(resPath):
  448. # print('res = ' + res)
  449. if res.startswith('values') and tag in res:
  450. start = res.index(tag)
  451. version = res[start + len(tag):]
  452. if not version.isdigit():
  453. continue
  454. version = int(version)
  455. print('version = %d' % version)
  456. if version < minSdkVersion:
  457. unSopportPath = os.path.join(resPath, res)
  458. print('unSopportPath = ' + unSopportPath)
  459. file_utils.deleteFolder(unSopportPath)
  460. print('deleteFolder = ' + unSopportPath)
  461. return 0
  462. def changePackageName(game, sdk, subChannel, config):
  463. '''
  464. 更改包名
  465. '''
  466. # 全局替换AndroidManifest里面的包名
  467. newPackageName = config['packageName']
  468. decompliePath = file_utils.getDecompliePath(
  469. game, sdk, subChannel, config['cache'])
  470. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  471. packageName = xml_utils.getPackageName(manifest)
  472. xml_utils.changePackageName(manifest, newPackageName)
  473. print('change package name %s --> %s' % (packageName, newPackageName))
  474. return 0
  475. def changeAppName(game, sdk, subChannel, config):
  476. '''
  477. 更改app名
  478. '''
  479. # 生成string.xml文件
  480. name = config['name']
  481. resName = 'common_sdk_name'
  482. if 'outName' in config:
  483. resName = resName + '_' + config['outName']
  484. decompliePath = file_utils.getDecompliePath(
  485. game, sdk, subChannel, config['cache'])
  486. stringFile = os.path.join(decompliePath, 'res',
  487. 'values', 'sdk_strings_temp.xml')
  488. content = '<?xml version="1.0" encoding="utf-8"?><resources><string name="%s">%s</string></resources>' % (
  489. resName, name)
  490. file_utils.createFile(stringFile, content)
  491. # 修改主文件的app名的值
  492. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  493. xml_utils.changeAppName(manifest, '@string/%s' % resName)
  494. print('change app name %s' % name)
  495. return 0
  496. def changeAppIcon(game, sdk, subChannel, config):
  497. '''
  498. 更改app icon
  499. '''
  500. print('change app icon...')
  501. resName = 'common_sdk_icon'
  502. decompliePath = file_utils.getDecompliePath(
  503. game, sdk, subChannel, config['cache'])
  504. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  505. xml_utils.changeAppIcon(manifest, '@mipmap/%s' % resName)
  506. return 0
  507. def addMetaData(game, sdk, subChannel, config):
  508. '''
  509. 添加meta-data
  510. '''
  511. if 'metaData' not in config:
  512. return 0
  513. print('add meta-data...')
  514. decompliePath = file_utils.getDecompliePath(
  515. game, sdk, subChannel, config['cache'])
  516. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  517. xml_utils.addMetaData(manifest, config['metaData'])
  518. return 0
  519. def addConfig(game, sdk, subChannel, config):
  520. '''
  521. 添加config.json
  522. '''
  523. if 'configData' not in config:
  524. return 0
  525. print('add config.json...')
  526. decompliePath = file_utils.getDecompliePath(
  527. game, sdk, subChannel, config['cache'])
  528. configJson = os.path.join(decompliePath, 'assets', 'jmhy_config.json')
  529. jsonText = json.dumps(config['configData'], ensure_ascii=False)
  530. file_utils.createFile(configJson, jsonText)
  531. return 0
  532. def changePlaceholders(game, sdk, subChannel, config):
  533. '''
  534. 处理掉占位符
  535. '''
  536. if 'placeholders' not in config:
  537. return 0
  538. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  539. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  540. placeholders = config['placeholders']
  541. for placeholder in placeholders:
  542. oldText = '${%s}' % placeholder
  543. newText = placeholders[placeholder]
  544. print('change placeholder %s -> %s' % (oldText, newText))
  545. file_utils.replaceContent(manifest, oldText, newText)
  546. return 0
  547. def addLauncher(game, sdk, subChannel, config):
  548. '''
  549. 添加启动图
  550. '''
  551. # ysdk的特殊处理
  552. if sdk in ignoreLauncher:
  553. return 0
  554. random = config['random']
  555. channelPath = file_utils.getSubChannelPath(game, sdk, random, subChannel)
  556. splashPath = os.path.join(channelPath, 'splash')
  557. if len(os.listdir(splashPath)) == 0:
  558. print('dir splash is empty')
  559. return 0
  560. print('add launcher...')
  561. decompliePath = file_utils.getDecompliePath(
  562. game, sdk, subChannel, config['cache'])
  563. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  564. activity = xml_utils.getLauncherActivityName(manifest)
  565. if activity == 'com.jmhy.sdk.template.LauncherActivity':
  566. print('add launcher already exist...')
  567. return 1
  568. # 添加关联资源
  569. internalPath = file_utils.getFullInternalPath()
  570. ret = copyAppResWithType(decompliePath, internalPath, 'launcher_res')
  571. if ret:
  572. return ret
  573. # 拷贝代码
  574. print('copy launcher code...')
  575. codePath = os.path.join(internalPath, 'launcher_code', 'smali')
  576. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  577. ret = file_utils.copyFileAllDir(codePath, smaliPath)
  578. if ret:
  579. return ret
  580. # 修改主文件信息
  581. print('change launcher config...')
  582. orientation = xml_utils.getScreenOrientation(manifest)
  583. activity = xml_utils.removeLauncherActivity(manifest)
  584. xml_utils.addLauncherActivity(
  585. manifest, orientation, 'com.jmhy.sdk.template.LauncherActivity')
  586. # 修改跳转的
  587. launcherActivity = os.path.join(
  588. decompliePath, 'smali', 'com', 'jmhy', 'sdk', 'template', 'LauncherActivity.smali')
  589. file_utils.replaceContent(launcherActivity, '{class}', activity)
  590. print('change launcher %s to %s' %
  591. (activity, 'com.jmhy.sdk.template.LauncherActivity'))
  592. # config['oldLauncher'] = activity
  593. if 'launcherTime' in config:
  594. timeHex = formatHex(config['launcherTime'])
  595. file_utils.replaceContent(launcherActivity, '0x0BB8', timeHex)
  596. return 0
  597. def addMoreIcon(game, sdk, subChannel, config):
  598. '''
  599. 添加多个图标
  600. '''
  601. print('add more icon support...')
  602. decompliePath = file_utils.getDecompliePath(
  603. game, sdk, subChannel, config['cache'])
  604. icon = '@mipmap/common_sdk_icon'
  605. if not config['changeIcon']:
  606. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  607. icon = xml_utils.getApplicationAttr(manifest, 'icon')
  608. switchIcon = icon
  609. if config['switchIcon']:
  610. switchIcon = '@mipmap/common_sdk_icon2'
  611. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  612. return xml_utils.addMoreIcon(manifest, icon, switchIcon)
  613. def copyIcon(game, sdk, subChannel, config):
  614. '''
  615. 复制icon到res ,一键登录使用
  616. '''
  617. if config['changeIcon']:
  618. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  619. decomplieResPath = file_utils.getFullPath(decompliePath, 'res')
  620. iconPath = os.path.join(decomplieResPath, 'mipmap-xhdpi', 'common_sdk_icon.png')
  621. desPath = os.path.join(
  622. decomplieResPath, 'drawable-hdpi', 'jm_cmcc_icon.png')
  623. file_utils.copyFile(iconPath, desPath)
  624. else:
  625. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  626. decomplieResPath = file_utils.getFullPath(decompliePath, 'res')
  627. desPath = os.path.join(decomplieResPath, 'drawable-hdpi', 'jm_cmcc_icon.png')
  628. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  629. icon = xml_utils.getApplicationAttr(manifest, 'icon')
  630. tag = icon[1:].split("/")
  631. if len(tag) < 1:
  632. return
  633. hdpi = ['-xhdpi', '-xxhdpi', '-xxxhdpi']
  634. for h in hdpi:
  635. p1 = '%s%s' % (tag[0], h)
  636. png = tag[1] + ".png"
  637. iconPath = os.path.join(decomplieResPath, p1, png)
  638. if os.path.exists(iconPath):
  639. print('iconPath = ' + iconPath)
  640. file_utils.copyFile(iconPath, desPath)
  641. break
  642. def formatHex(millisecond):
  643. '''
  644. 将毫秒转为16进制,4位格式
  645. '''
  646. timeHex = str(hex(millisecond)).upper()
  647. timeHex = timeHex[2:]
  648. formatHex = ''
  649. if len(timeHex) == 3:
  650. formatHex = '0x0' + timeHexaddLauncher
  651. elif len(timeHex) == 4:
  652. formatHex = '0x' + timeHex
  653. else:
  654. formatHex = '0x0BB8'
  655. return formatHex
  656. def doSDKPostScript(game, sdk, config):
  657. '''
  658. 执行sdk相关特殊处理脚本
  659. '''
  660. sdkPath = file_utils.getFullSDKPath(sdk)
  661. scriptPath = os.path.join(sdkPath, 'script')
  662. targetScript = os.path.join(scriptPath, 'sdk_script.py')
  663. if not os.path.exists(targetScript):
  664. print('sdk_script no exists')
  665. return 0
  666. print('doSDKPostScript...')
  667. sys.path.append(scriptPath)
  668. module = importlib.import_module('sdk_script')
  669. ret = module.execute(game, sdk, config)
  670. sys.path.remove(scriptPath)
  671. return ret
  672. def doGamePostScript(game, sdk, config):
  673. '''
  674. 执行游戏相关特殊处理脚本
  675. '''
  676. channelPath = file_utils.getFullGamePath(game)
  677. scriptPath = os.path.join(channelPath, 'script')
  678. targetScript = os.path.join(scriptPath, 'game_script.py')
  679. if not os.path.exists(targetScript):
  680. print('game_script no exists')
  681. return 0
  682. print('doGamePostScript...')
  683. sys.path.append(scriptPath)
  684. module = importlib.import_module('game_script')
  685. ret = module.execute(game, sdk, config)
  686. sys.path.remove(scriptPath)
  687. return ret
  688. def doGameScript(game, sdk, config):
  689. '''
  690. 执行游戏相关特殊处理脚本
  691. '''
  692. channelPath = file_utils.getFullPath('game_script', game)
  693. targetScript = os.path.join(channelPath, 'game_script.py')
  694. print(targetScript + "--------")
  695. if not os.path.exists(targetScript):
  696. print('game_script no exists')
  697. return 0
  698. print('doGameScript...')
  699. sys.path.append(channelPath)
  700. module = importlib.import_module('game_script')
  701. ret = module.execute(game, sdk, config)
  702. sys.path.remove(channelPath)
  703. return ret
  704. def addLogSdk(game, sdk, subChannel, config, logSdk):
  705. # 拷贝jniLibs
  706. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  707. sdkPath = ''
  708. print('add log sdk, sdk:' + sdk)
  709. if sdk == 'jm_beta_sdk' or sdk == 'beta_sdk':
  710. sdkPath = file_utils.getFullLogSDKPath(logSdk, True)
  711. else:
  712. sdkPath = file_utils.getFullLogSDKPath(logSdk)
  713. print('copy log jniLibs...')
  714. jniPath = file_utils.getFullPath(sdkPath, 'jniLibs')
  715. decomplieJniPath = file_utils.getFullPath(decompliePath, 'lib')
  716. abiFilters = []
  717. if os.path.exists(decomplieJniPath):
  718. for abi in os.listdir(decomplieJniPath):
  719. if abi == 'armeabi-v7a' or abi == 'armeabi' or abi == 'arm64-v8a':
  720. abiFilters.append(abi)
  721. else:
  722. abiFilters = ['armeabi-v7a']
  723. if os.path.exists(jniPath):
  724. ret = file_utils.copyFileAllDir(
  725. jniPath, decomplieJniPath, False, abiFilters)
  726. if ret:
  727. return ret
  728. print('merge log AndroidManifest...')
  729. libManifest = file_utils.getFullPath(sdkPath, 'manifest.xml')
  730. if os.path.exists(libManifest):
  731. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  732. ret = xml_utils.mergeManifestRes(manifest, libManifest)
  733. if ret:
  734. return ret
  735. changePlaceholders(game, sdk, subChannel, config)
  736. return packLogJar(game, sdk, subChannel, config, logSdk)
  737. def addOaidSdk(game, sdk, subChannel, config, oaidVersion):
  738. sdkPath = file_utils.getFullOaidSDKPath(oaidVersion)
  739. decompliePath = file_utils.getDecompliePath(
  740. game, sdk, subChannel, config['cache'])
  741. # 拷贝assets
  742. print('copy oaid assets...')
  743. assetsPath = file_utils.getFullPath(sdkPath, 'assets')
  744. decomplieAssetsPath = file_utils.getFullPath(decompliePath, 'assets')
  745. if os.path.exists(assetsPath):
  746. ret = file_utils.copyFileAllDir(assetsPath, decomplieAssetsPath)
  747. if ret:
  748. return ret
  749. # 拷贝jniLibs
  750. print('copy oaid jniLibs...')
  751. jniPath = file_utils.getFullPath(sdkPath, 'jniLibs')
  752. decomplieJniPath = file_utils.getFullPath(decompliePath, 'lib')
  753. abiFilters = []
  754. if os.path.exists(decomplieJniPath):
  755. for abi in os.listdir(decomplieJniPath):
  756. if abi == 'armeabi-v7a' or abi == 'armeabi':
  757. abiFilters.append(abi)
  758. else:
  759. abiFilters = ['armeabi-v7a']
  760. if os.path.exists(jniPath):
  761. ret = file_utils.copyFileAllDir(
  762. jniPath, decomplieJniPath, False, abiFilters)
  763. if ret:
  764. return ret
  765. print('merge oaid AndroidManifest...')
  766. libManifest = file_utils.getFullPath(sdkPath, 'manifest.xml')
  767. if os.path.exists(libManifest):
  768. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  769. ret = xml_utils.mergeManifestRes(manifest, libManifest)
  770. if ret:
  771. return ret
  772. return packOaidJar(game, sdk, subChannel, config, oaidVersion)
  773. def generateNewRFile(game, sdk, subChannel, config):
  774. '''
  775. 生成新的R文件
  776. '''
  777. decompliePath = file_utils.getDecompliePath(
  778. game, sdk, subChannel, config['cache'])
  779. androidPlatforms = file_utils.getAndroidCompileToolPath()
  780. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  781. decomplieResPath = file_utils.getFullPath(decompliePath, 'res')
  782. compliePath = file_utils.getFullPath(decompliePath, 'gen')
  783. if not os.path.exists(compliePath):
  784. os.makedirs(compliePath)
  785. # 生成R文件
  786. print('生成R文件 ...')
  787. if config['aapt2disable']:
  788. aapt = file_utils.getAAPTPath()
  789. ret = file_utils.getExecPermission(aapt)
  790. if ret:
  791. return ret
  792. createRCmd = '"%s" p -f -m -J "%s" -S "%s" -I "%s" -M "%s"' % (
  793. aapt, compliePath, decomplieResPath, androidPlatforms, manifest)
  794. ret = file_utils.execFormatCmd(createRCmd)
  795. if ret:
  796. return ret
  797. else:
  798. # compile
  799. aapt = file_utils.getAAPT2Path()
  800. ret = file_utils.getExecPermission(aapt)
  801. if ret:
  802. return ret
  803. print('compiled res ...')
  804. complieResPath = os.path.join(compliePath, 'compiled')
  805. complieResCmd = '"%s" compile --dir "%s" -o "%s"' % (
  806. aapt, decomplieResPath, complieResPath)
  807. file_utils.execFormatCmd(complieResCmd)
  808. # unzip
  809. print('unzip compiled res ...')
  810. unzipResPath = os.path.join(compliePath, 'aapt2_res')
  811. with zipfile.ZipFile(complieResPath) as zf:
  812. zf.extractall(unzipResPath)
  813. print('create unzip %s' % unzipResPath)
  814. # link
  815. print('link res ...')
  816. outApk = os.path.join(compliePath, 'res.apk')
  817. linkResCmd = '"%s" link -o "%s" -I "%s" --manifest "%s" --java "%s" --auto-add-overlay' % (
  818. aapt, outApk, androidPlatforms, manifest, compliePath)
  819. for filename in os.listdir(unzipResPath):
  820. linkResCmd += ' %s' % filename
  821. print('link cmd len is %s' % len(linkResCmd))
  822. ret = file_utils.execFormatCmd(linkResCmd, unzipResPath)
  823. if ret:
  824. return ret
  825. # 编译R文件
  826. print('complie R.java ...')
  827. packageName = xml_utils.getPackageName(manifest)
  828. packagePath = file_utils.getPackagePath(compliePath, packageName)
  829. RSourceFile = os.path.join(packagePath, 'R.java')
  830. complieRCmd = 'javac -source 1.8 -target 1.8 -encoding UTF-8 "%s"' % RSourceFile
  831. ret = file_utils.execFormatCmd(complieRCmd)
  832. if ret:
  833. return ret
  834. # 生成dex
  835. print('dex R.class ...')
  836. outDex = os.path.join(compliePath, 'classes.dex')
  837. if config['aapt2disable']:
  838. dx = file_utils.getDxPath()
  839. dexCmd = '--dex --no-warning --output="%s" "%s"' % (
  840. outDex, compliePath)
  841. else:
  842. dx = file_utils.getD8Path()
  843. clazz = os.path.join(packagePath, '*.class')
  844. dexCmd = '--lib "%s" --output "%s" %s' % (
  845. androidPlatforms, compliePath, clazz)
  846. ret = file_utils.execJarCmd(dx, dexCmd)
  847. if ret:
  848. return ret
  849. # 反向dex生成smali
  850. # 存放在out目录
  851. print('baksmali classes.dex ...')
  852. baksmaliPath = file_utils.getBaksmaliPath()
  853. outPath = file_utils.getFullPath(decompliePath, 'out')
  854. ret = file_utils.execJarCmd(
  855. baksmaliPath, 'd "%s" -o "%s"' % (outDex, outPath))
  856. if ret:
  857. return ret
  858. # 将生成的文件拷贝到目标目录
  859. print('copy R.smali ...')
  860. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  861. file_utils.copyFileAllDir(outPath, smaliPath)
  862. return 0
  863. def packJar(game, sdk, subChannel, config):
  864. '''
  865. 打包所有的jar
  866. '''
  867. splitDex = config['splitDex']
  868. decompliePath = file_utils.getDecompliePath(
  869. game, sdk, subChannel, config['cache'])
  870. outPath = file_utils.getFullPath(decompliePath, 'gen')
  871. if not os.path.exists(outPath):
  872. os.makedirs(outPath)
  873. if config['aapt2disable']:
  874. dx = file_utils.getDxPath()
  875. dexCmd = '--dex --no-warning --output="%s"' % outPath
  876. else:
  877. dx = file_utils.getD8Path()
  878. androidPlatforms = file_utils.getAndroidCompileToolPath()
  879. dexCmd = '--lib "%s" --output "%s"' % (androidPlatforms, outPath)
  880. # 找到所有lib依赖
  881. sdkPath = file_utils.getFullSDKPath(sdk)
  882. libs = os.path.join(sdkPath, 'libs')
  883. libConfig = os.path.join(libs, 'config.json')
  884. #
  885. # 存在配置文件
  886. if os.path.exists(libConfig):
  887. jsonText = file_utils.readFile(libConfig)
  888. libConf = json.loads(jsonText)
  889. if 'libConfig' in config and config['libConfig'] in libConf:
  890. conf = config['libConfig']
  891. libList = libConf[conf]
  892. for jar in libList:
  893. dexCmd += ' ' + os.path.join(libs, jar)
  894. elif 'default' in libConf:
  895. libList = libConf['default']
  896. for jar in libList:
  897. dexCmd += ' ' + os.path.join(libs, jar)
  898. else:
  899. for jar in os.listdir(libs):
  900. if not jar.endswith('.jar'):
  901. continue
  902. dexCmd += ' ' + os.path.join(libs, jar)
  903. else:
  904. for jar in os.listdir(libs):
  905. if not jar.endswith('.jar'):
  906. continue
  907. dexCmd += ' ' + os.path.join(libs, jar)
  908. # multidex.jar
  909. if splitDex:
  910. print('getMultiDexPath ...')
  911. dexCmd += ' ' + file_utils.getMultiDexPath()
  912. # sdk实现类
  913. print('packageing all jar ...')
  914. dexCmd += ' ' + os.path.join(sdkPath, '%s.jar' % sdk)
  915. ret = file_utils.execJarCmd(dx, dexCmd)
  916. if ret:
  917. return ret
  918. # 反向dex生成smali
  919. # 存放在out目录
  920. print('baksmali classes.dex ...')
  921. outDex = os.path.join(outPath, 'classes.dex')
  922. baksmaliPath = file_utils.getBaksmaliPath()
  923. outPath = file_utils.getFullPath(decompliePath, 'out')
  924. ret = file_utils.execJarCmd(
  925. baksmaliPath, 'd "%s" -o "%s"' % (outDex, outPath))
  926. if ret:
  927. return ret
  928. # 将生成的文件拷贝到目标目录
  929. print('copy all smali ...')
  930. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  931. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  932. if ret:
  933. return ret
  934. return 0
  935. def packLogJar(game, sdk, subChannel, config, logSdk):
  936. '''
  937. 打包Log jar
  938. '''
  939. decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
  940. outPath = file_utils.getFullPath(decompliePath, 'gen')
  941. if not os.path.exists(outPath):
  942. os.makedirs(outPath)
  943. if config['aapt2disable']:
  944. dx = file_utils.getDxPath()
  945. dexCmd = '--dex --multi-dex --no-warning --output="%s"' % outPath
  946. else:
  947. dx = file_utils.getD8Path()
  948. androidPlatforms = file_utils.getAndroidCompileToolPath()
  949. dexCmd = '--lib "%s" --output "%s"' % (androidPlatforms, outPath)
  950. # 找到所有lib依赖
  951. if sdk == 'jm_beta_sdk' or sdk == 'beta_sdk':
  952. sdkPath = file_utils.getFullLogSDKPath(logSdk, True)
  953. else:
  954. sdkPath = file_utils.getFullLogSDKPath(logSdk)
  955. libs = os.path.join(sdkPath, 'libs')
  956. libConfig = os.path.join(libs, 'config.json')
  957. # 存在配置文件
  958. if os.path.exists(libConfig):
  959. jsonText = file_utils.readFile(libConfig)
  960. libList = json.loads(jsonText)
  961. for jar in libList:
  962. if not jar.endswith('.jar'):
  963. continue
  964. dexCmd += ' ' + os.path.join(libs, jar)
  965. else:
  966. for jar in os.listdir(libs):
  967. if not jar.endswith('.jar'):
  968. continue
  969. dexCmd += ' ' + os.path.join(libs, jar)
  970. # sdk实现类
  971. print('packageing all log jar ...')
  972. dexCmd += ' ' + os.path.join(sdkPath, '%s.jar' % logSdk)
  973. ret = file_utils.execJarCmd(dx, dexCmd)
  974. if ret:
  975. return ret
  976. # 反向dex生成smali
  977. # 存放在out目录
  978. print('baksmali classes.dex ...')
  979. outDex = os.path.join(outPath, 'classes.dex')
  980. baksmaliPath = file_utils.getBaksmaliPath()
  981. outPath = file_utils.getFullPath(decompliePath, 'out')
  982. ret = file_utils.execJarCmd(
  983. baksmaliPath, 'd "%s" -o "%s"' % (outDex, outPath))
  984. if ret:
  985. return ret
  986. # 将生成的文件拷贝到目标目录
  987. print('copy all log smali ...')
  988. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  989. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  990. if ret:
  991. return ret
  992. return 0
  993. def packOaidJar(game, sdk, subChannel, config, oaidVerion):
  994. '''
  995. 打包oaid jar
  996. '''
  997. decompliePath = file_utils.getDecompliePath(
  998. game, sdk, subChannel, config['cache'])
  999. outPath = file_utils.getFullPath(decompliePath, 'gen')
  1000. if not os.path.exists(outPath):
  1001. os.makedirs(outPath)
  1002. if config['aapt2disable']:
  1003. dx = file_utils.getDxPath()
  1004. dexCmd = '--dex --multi-dex --no-warning --output="%s"' % outPath
  1005. else:
  1006. dx = file_utils.getD8Path()
  1007. androidPlatforms = file_utils.getAndroidCompileToolPath()
  1008. dexCmd = '--lib "%s" --output "%s"' % (androidPlatforms, outPath)
  1009. # 找到所有lib依赖
  1010. sdkPath = file_utils.getFullOaidSDKPath(oaidVerion)
  1011. libs = os.path.join(sdkPath, 'libs')
  1012. libConfig = os.path.join(libs, 'config.json')
  1013. # 存在配置文件
  1014. # if os.path.exists(libConfig):
  1015. # jsonText = file_utils.readFile(libConfig)
  1016. # libList = json.loads(jsonText)
  1017. # for jar in libList:
  1018. # if not jar.endswith('.jar'):
  1019. # continue
  1020. # dexCmd += ' ' + os.path.join(libs, jar)
  1021. # else:
  1022. # for jar in os.listdir(libs):
  1023. # if not jar.endswith('.jar'):
  1024. # continue
  1025. # dexCmd += ' ' + os.path.join(libs, jar)
  1026. # sdk实现类
  1027. print('packageing oaid jar ...')
  1028. dexCmd += ' ' + os.path.join(libs, 'miit_mdid_%s.jar' % oaidVerion)
  1029. ret = file_utils.execJarCmd(dx, dexCmd)
  1030. if ret:
  1031. return ret
  1032. # 反向dex生成smali
  1033. # 存放在out目录
  1034. print('baksmali classes.dex ...')
  1035. outDex = os.path.join(outPath, 'classes.dex')
  1036. baksmaliPath = file_utils.getBaksmaliPath()
  1037. outPath = file_utils.getFullPath(decompliePath, 'out')
  1038. ret = file_utils.execJarCmd(
  1039. baksmaliPath, 'd "%s" -o "%s"' % (outDex, outPath))
  1040. if ret:
  1041. return ret
  1042. # 将生成的文件拷贝到目标目录
  1043. print('copy all log smali ...')
  1044. smaliPath = file_utils.getFullPath(decompliePath, 'smali')
  1045. ret = file_utils.copyFileAllDir(outPath, smaliPath, True)
  1046. if ret:
  1047. return ret
  1048. return 0
  1049. def splitDex(game, sdk, subChannel, config):
  1050. '''
  1051. 分割dex
  1052. '''
  1053. # 判断是否已经存在application
  1054. # 存在,则往原application添加内容
  1055. # 不存在,则拷贝一个默认的android.support.multidex.MultiDexApplication
  1056. print('add MultiDex support...')
  1057. decompliePath = file_utils.getDecompliePath(
  1058. game, sdk, subChannel, config['cache'])
  1059. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  1060. application = xml_utils.getApplicationAttr(manifest, 'name')
  1061. if application is None:
  1062. ret = xml_utils.changeApplicationAttr(
  1063. manifest, 'name', 'android.support.multidex.MultiDexApplication')
  1064. if ret:
  1065. return ret
  1066. else:
  1067. smaliPath = os.path.join(decompliePath, 'smali')
  1068. applicationFile = file_utils.getPackagePath(smaliPath, application)
  1069. applicationFile += '.smali'
  1070. ret = changeApplicationDex(applicationFile)
  1071. if ret:
  1072. return ret
  1073. return splitSmali(game, sdk, subChannel, config, application)
  1074. def changeApplicationDex(file):
  1075. '''
  1076. 修改application的smali文件,增加MultiDex操作
  1077. '''
  1078. index = file_utils.getApplicationSmaliIndex(file)
  1079. file_utils.insertApplicationSmali(file, index)
  1080. return 0
  1081. def splitSmali(game, sdk, subChannel, config, application):
  1082. '''
  1083. 如果函数上限超过限制,自动拆分smali,以便生成多个dex文件
  1084. '''
  1085. print('splitSmali...')
  1086. decompliePath = file_utils.getDecompliePath(
  1087. game, sdk, subChannel, config['cache'])
  1088. smaliPath = os.path.join(decompliePath, 'smali')
  1089. appPackage = None
  1090. if application:
  1091. appPackage = application[:application.rfind('.')]
  1092. appPackage = appPackage.replace('.', '/')
  1093. allFiles = []
  1094. allFiles = file_utils.list_files(smaliPath, allFiles)
  1095. # print('file count is %d' % len(allFiles))
  1096. # maxFuncNum = 65535
  1097. # 留一点空间,防止计算误差
  1098. maxFuncNum = 64000
  1099. currFucNum = 0
  1100. totalFucNum = 0
  1101. currDexIndex = 1
  1102. allRefs = []
  1103. # 保证Application等类在第一个classex.dex文件中
  1104. for f in allFiles:
  1105. f = f.replace('\\', '/')
  1106. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  1107. currFucNum += smali_utils.get_smali_method_count(f, allRefs)
  1108. totalFucNum = currFucNum
  1109. for f in allFiles:
  1110. f = f.replace('\\', '/')
  1111. if not f.endswith('.smali'):
  1112. continue
  1113. if (appPackage and appPackage in f) or '/android/support/multidex' in f:
  1114. continue
  1115. thisFucNum = smali_utils.get_smali_method_count(f, allRefs)
  1116. totalFucNum += thisFucNum
  1117. # print('%d # %d ==> %s' % (thisFucNum, currDexIndex, f))
  1118. # print('totalFucNum is %d' % totalFucNum)
  1119. if currFucNum + thisFucNum >= maxFuncNum:
  1120. currFucNum = thisFucNum
  1121. currDexIndex += 1
  1122. newDexPath = os.path.join(
  1123. decompliePath, 'smali_classes%d' % currDexIndex)
  1124. os.makedirs(newDexPath)
  1125. else:
  1126. currFucNum += thisFucNum
  1127. if currDexIndex > 1:
  1128. newDexPath = os.path.join(
  1129. decompliePath, 'smali_classes%d' % currDexIndex)
  1130. targetFile = newDexPath + f[len(smaliPath):]
  1131. file_utils.copyFile(f, targetFile, True)
  1132. return 0
  1133. def changeVersion(game, sdk, subChannel, config):
  1134. '''
  1135. 更改版本号
  1136. '''
  1137. decompliePath = file_utils.getDecompliePath(
  1138. game, sdk, subChannel, config['cache'])
  1139. yml = os.path.join(decompliePath, 'apktool.yml')
  1140. versionCode = None
  1141. versionName = None
  1142. targetSdkVersion = None
  1143. if 'versionCode' in config:
  1144. versionCode = config['versionCode']
  1145. if 'versionName' in config:
  1146. versionName = config['versionName']
  1147. if 'targetSdkVersion' in config:
  1148. targetSdkVersion = config['targetSdkVersion']
  1149. else:
  1150. targetSdkVersion = 26
  1151. print('changeVersion versionCode=%s,versionName=%s,targetSdkVersion=%s' %
  1152. (versionCode, versionName, targetSdkVersion))
  1153. return file_utils.changeVersion(yml, versionCode, versionName, targetSdkVersion)
  1154. def recomplie(game, sdk, subChannel, config):
  1155. '''
  1156. 回编译
  1157. '''
  1158. print('recomplie apk...')
  1159. apktoolPath = file_utils.getApkToolPath()
  1160. decompliePath = file_utils.getDecompliePath(
  1161. game, sdk, subChannel, config['cache'])
  1162. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  1163. useAppt2 = ' --use-aapt2'
  1164. if config['aapt2disable']:
  1165. useAppt2 = ''
  1166. return file_utils.execJarCmd(apktoolPath, 'b -f "%s" -o "%s"%s' % (decompliePath, outApk, useAppt2))
  1167. def alignApk(game, sdk, subChannel, config):
  1168. '''
  1169. 对齐apk
  1170. '''
  1171. print('align apk...')
  1172. outApk = file_utils.getOutApkPath(game, sdk, subChannel, config['cache'])
  1173. alignApk = file_utils.getAlignApkPath(
  1174. game, sdk, subChannel, config['cache'])
  1175. alignapkTool = file_utils.getAlignPath()
  1176. if os.path.exists(alignApk):
  1177. os.remove(alignApk)
  1178. ret = file_utils.getExecPermission(alignapkTool)
  1179. if ret:
  1180. return ret
  1181. # zipalign.exe -v -p 4 input.apk output.apk
  1182. return file_utils.execFormatCmd('"%s" -f -p 4 "%s" "%s"' % (alignapkTool, outApk, alignApk))
  1183. def apksignerApk(game, sdk, subChannel, config):
  1184. '''
  1185. 签名apk
  1186. '''
  1187. print('sign apk...')
  1188. print('game = %s, sdk = %s, subChannel = %s, ...' %
  1189. (game, sdk, subChannel))
  1190. path = os.path.join(file_utils.getCurrentPath(), 'keystore', 'key.json')
  1191. jsonText = file_utils.readFile(path)
  1192. signConfig = json.loads(jsonText)
  1193. keystore = {}
  1194. for key in signConfig.keys():
  1195. print(key)
  1196. if game.find(key) > -1 or game == key:
  1197. if sdk in signConfig[key]:
  1198. keystore = signConfig[key][sdk]
  1199. break
  1200. else:
  1201. keystore = signConfig['default']
  1202. else:
  1203. keystore = signConfig['default']
  1204. # if game in signConfig:
  1205. # if sdk in signConfig[game]:
  1206. # keystore = signConfig[game][sdk]
  1207. # else:
  1208. # keystore = signConfig['default']
  1209. # else:
  1210. # keystore = signConfig['default']
  1211. print('storeFile is "%s"' % keystore['storeFile'])
  1212. apksigner = file_utils.getApksignerPath()
  1213. alignApk = file_utils.getAlignApkPath(
  1214. game, sdk, subChannel, config['cache'])
  1215. signedApk = file_utils.getSiginedApkPath(
  1216. game, sdk, subChannel, config['cache'])
  1217. storeFile = os.path.join(file_utils.getCurrentPath(),
  1218. 'keystore', keystore['storeFile'])
  1219. # 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
  1220. v2disable = ''
  1221. if 'v2disable' in config and config['v2disable']:
  1222. v2disable = ' --v2-signing-enabled=false'
  1223. return file_utils.execJarCmd(apksigner,
  1224. 'sign%s --ks "%s" --ks-key-alias %s --ks-pass pass:%s --key-pass pass:%s --out "%s" "%s"' % (
  1225. v2disable, storeFile, keystore['keyAlias'], keystore['storePassword'],
  1226. keystore['keyPassword'], signedApk, alignApk))
  1227. def addChannel(game, sdk, subChannel, config):
  1228. '''
  1229. 添加渠道信息
  1230. '''
  1231. if 'v2disable' in config and config['v2disable']:
  1232. return 0
  1233. walle = file_utils.getWallePath()
  1234. signedApk = file_utils.getSiginedApkPath(
  1235. game, sdk, subChannel, config['cache'])
  1236. walleApk = file_utils.getWalleApkPath(
  1237. game, sdk, subChannel, config['cache'])
  1238. properties = config['properties']
  1239. appid = ''
  1240. appkey = ''
  1241. host = ''
  1242. if 'appid' in properties:
  1243. appid = properties['appid']
  1244. if 'appkey' in properties:
  1245. appkey = properties['appkey']
  1246. if 'host' in properties:
  1247. host = properties['host']
  1248. return file_utils.execJarCmd(walle, 'put -e version=%s,agent=%s,appid=%s,appkey=%s,host=%s "%s" "%s"' % (
  1249. config_utils.getDate(), properties['agent'], appid, appkey, host, signedApk, walleApk))
  1250. def clearTemp(game, sdk, subChannel, config):
  1251. '''
  1252. 清空中间产生的文件
  1253. '''
  1254. print('clear temp...')
  1255. targetApkPath = file_utils.getTargetApkPath(game, sdk, config['cache'])
  1256. if os.path.exists(targetApkPath):
  1257. file_utils.deleteFolder(targetApkPath)
  1258. decompliePath = file_utils.getDecompliePath(
  1259. game, sdk, subChannel, config['cache'])
  1260. if os.path.exists(decompliePath):
  1261. file_utils.deleteFolder(decompliePath)
  1262. random = config['random']
  1263. channelPath = file_utils.getChannelPath(game, random, sdk)
  1264. if os.path.exists(channelPath):
  1265. file_utils.deleteFolder(channelPath)
  1266. print('clear temp end')
  1267. def packConsoleInput():
  1268. '''
  1269. 控制台打包
  1270. '''
  1271. if len(sys.argv) < 3:
  1272. print('argument is missing')
  1273. return 1
  1274. # 校验参数
  1275. game = sys.argv[1]
  1276. sdk = sys.argv[2]
  1277. # 可选参数,没有则默认打全部渠道
  1278. subChannel = None
  1279. if len(sys.argv) > 3:
  1280. subChannel = sys.argv[3]
  1281. return packConsole(game, sdk, subChannel)
  1282. def packConsole(game, sdk, config, subChannel):
  1283. '''
  1284. 控制台打包
  1285. '''
  1286. cache_game_apk_path = file_utils.getCacheGameApk(game, config['random'], sdk)
  1287. print('cache game apk path %s' % cache_game_apk_path)
  1288. if not os.path.exists(cache_game_apk_path):
  1289. print('game "%s" not exists' % game)
  1290. return 1
  1291. if not os.path.exists(file_utils.getFullSDKPath(sdk)):
  1292. print('sdk "%s" not exists' % sdk)
  1293. return 1
  1294. global startTime
  1295. startTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1296. # 读取配置
  1297. random = config['random']
  1298. channelPath = file_utils.getChannelPath(game, random, sdk)
  1299. configPath = os.path.join(channelPath, 'config.json')
  1300. if not os.path.exists(configPath):
  1301. print('%s not exists' % configPath)
  1302. return 1
  1303. jsonText = file_utils.readFile(configPath)
  1304. config = json.loads(jsonText)
  1305. # 检查参数
  1306. if not config_utils.checkConfig(config):
  1307. return 1
  1308. # 处理参数
  1309. config_utils.replaceArgs(config)
  1310. successCount = 0
  1311. failureCount = 0
  1312. if type(config) == dict:
  1313. if subChannel is None or config['subChannel'] == subChannel:
  1314. ret = pack(game, sdk, config)
  1315. if ret:
  1316. failureCount += 1
  1317. else:
  1318. successCount += 1
  1319. else:
  1320. print('subChannel "%s" no found' % subChannel)
  1321. return 1
  1322. elif type(config) == list:
  1323. found = False
  1324. for itemConfig in config:
  1325. if subChannel is None or itemConfig['subChannel'] == subChannel:
  1326. found = True
  1327. ret = pack(game, sdk, itemConfig)
  1328. if ret:
  1329. failureCount += 1
  1330. else:
  1331. successCount += 1
  1332. if not found:
  1333. print('subChannel "%s" no found' % subChannel)
  1334. return 1
  1335. print('success %d, failure %d' % (successCount, failureCount))
  1336. subChannelPath = os.path.join(channelPath, subChannel)
  1337. print('------subChannelPath 目录清空:%s -------' % subChannelPath)
  1338. file_utils.deleteFolder(subChannelPath)
  1339. return 0
  1340. def formatXml(game, sdk, subChannel, config):
  1341. decompliePath = file_utils.getDecompliePath(
  1342. game, sdk, subChannel, config['cache'])
  1343. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  1344. return xml_utils.formatXml(manifest)
  1345. def copyApk2OutDir(game, sdk, subChannel, config):
  1346. walleApk = file_utils.getWalleApkPath(
  1347. game, sdk, subChannel, config['cache'])
  1348. releaseApkPath = ""
  1349. if 'outName' in config and 'outPath' in config:
  1350. if not os.path.exists(config['outPath']):
  1351. os.makedirs(config['outPath'])
  1352. releaseApkPath = os.path.join(
  1353. config['outPath'], config['outName'] + '.apk')
  1354. elif 'outName' in config:
  1355. releaseApkPath = file_utils.getRenameApkPath(
  1356. game, sdk, config['cache'], config['outName'])
  1357. print('------生成正式包路径 %s -------' % releaseApkPath)
  1358. file_utils.copyFile(walleApk, releaseApkPath)
  1359. def replaceAmHardwareAccelerated(game, sdk, subChannel, config):
  1360. decompliePath = file_utils.getDecompliePath(
  1361. game, sdk, subChannel, config['cache'])
  1362. manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
  1363. lines = open(manifest).readlines()
  1364. fp = open(manifest, "w")
  1365. isReplaced = False
  1366. for l in lines:
  1367. if isReplaced == False and l.find("android:hardwareAccelerated=") >= 0:
  1368. isReplace = True
  1369. l = re.sub("android:hardwareAccelerated=\"false\"",
  1370. "android:hardwareAccelerated=\"true\"", l)
  1371. fp.write(l)
  1372. fp.close()
  1373. pass
  1374. def openFile(file, mode):
  1375. return open(file, mode, encoding='UTF-8')