package_utils.py 48 KB

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