package_utils.py 48 KB

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