package_utils.py 48 KB

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