package_utils.py 46 KB

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