package_utils.py 47 KB

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