Skip to content

Commit

Permalink
Merge pull request #175 from AirportR/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
AirportR authored Mar 5, 2024
2 parents c301d97 + 52cc110 commit 0a1fd3a
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 53 deletions.
14 changes: 8 additions & 6 deletions botmodule/init_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
from utils.collector import get_latest_tag, Download, DownloadError

admin = config.getAdmin() # 管理员
config.add_user(admin) # 管理员同时也是用户
config.reload()


def check_args():
Expand Down Expand Up @@ -73,6 +71,11 @@ class Init:
ftcore_owner = repo_owner
ftcore_name = "FullTCore"

@staticmethod
def init_user():
config.add_user(admin) # 管理员同时也是用户
config.reload()

@staticmethod
def init_emoji():
emoji_source = config.config.get('emoji', {}).get('emoji-source', 'TwemojiLocalSource')
Expand Down Expand Up @@ -206,14 +209,13 @@ def check_py_version() -> None:


def check_init():
check_py_version()
check_args()
if config.getClashBranch() == 'meta':
logger.info('✅检测到启用clash.meta系内核配置')
check_py_version()
Init.init_emoji()
Init.init_dir()
Init.init_permission()
Init.init_proxy_client()
Init.init_permission()
Init.init_user()


def parse_bot_proxy():
Expand Down
47 changes: 1 addition & 46 deletions utils/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1036,49 +1036,4 @@ def select_core(index: Union[int, str], progress_func: Tuple[Union[Callable, Cor


if __name__ == '__main__':
import sys
import getopt

check_init()
# os.chdir(os.path.abspath(os.path.join(os.getcwd(), os.pardir)))
# sys.path.append(os.path.abspath(os.path.join(os.getcwd(), os.pardir)))
help_text = """
Usage(使用帮助):
-h, --help Display the help info.
输出帮助
-f, --file Subscription file path
订阅文件路径
-c, --core Select the test type(speed,topo,script)
测试类型(speed,topo,script)
"""
config_path = ''
core = None
try:
opts, _args = getopt.getopt(sys.argv[1:], "hf:c:", ["help", "file=", "core="])
except getopt.GetoptError:
print(help_text)
sys.exit(1)
for opt, arg in opts:
if opt in ('-h', '--help'):
print(help_text)
sys.exit()
elif opt in ("-c", "--core"):
if arg == 'speed':
core = SpeedCore()
elif arg == 'script':
core = ScriptCore()
elif arg == 'topo':
core = TopoCore()
else:
raise TypeError("Unknown test type, please input again.\n未知的测试类型,请重新输入!")
elif opt in ("-f", "--file"):
config_path = arg
if core is None and not config_path:
raise ValueError("Unable start the tasks,please input the config path.\n请输入配置文件路径")
with open(config_path, 'r', encoding='utf-8') as fp:
data = cleaner.ClashCleaner(fp)
my_proxies = data.getProxies()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
resd = loop.run_until_complete(core.core(my_proxies))
print(resd)
pass
2 changes: 1 addition & 1 deletion utils/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ def draw_watermark(self, original_image: Image.Image) -> Image.Image:
if not shadow:
font = ImageFont.truetype(self.config.getFont(), int(watermark['font_size']))
_, __, wm_width, wm_height = font.getbbox(watermark_text)
text_image = Image.new('RGBA', (wm_width, wm_width), (255, 255, 255, 0))
text_image = Image.new('RGBA', (wm_width, wm_height), (255, 255, 255, 0))
text_draw = ImageDraw.Draw(text_image)

rgb = ImageColor.getrgb(watermark['color'])
Expand Down
118 changes: 118 additions & 0 deletions utils/tool/console.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import asyncio
import sys
from os import getcwd, chdir
from pathlib import Path


def change_cwd():
if "utils" in getcwd():
chdir("..")
change_cwd()
else:
sys.path.append(getcwd())
return


change_cwd()

if __name__ == "__main__":
import argparse
from utils import cleaner
from utils.backend import check_init, SpeedCore, ScriptCore, TopoCore

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
check_init()

config_path = ''
core = None


def get_proxies(path: str):
url = cleaner.geturl(path)
if url:
from utils.collector import SubCollector
subcontent = loop.run_until_complete(SubCollector(url).getSubConfig(inmemory=True))
pre_cl = cleaner.ClashCleaner(':memory:', subcontent)
pre_cl.node_filter(include_text, exclude_text)
return pre_cl.getProxies()
else:
with open(path, 'r', encoding='utf-8') as fp:
data = cleaner.ClashCleaner(fp)
data.node_filter(include_text, exclude_text)
return data.getProxies()


def export_to_image():
file_name = ""
if args.temp and _test_type != "script":
print("测试结果:", resd)
return
from utils.export import ExportCommon, ExportSpeed, ExportTopo
if _test_type == "speed":
file_name = ExportSpeed(name=None, info=resd).exportImage()
elif _test_type == "topo":
info1 = resd.get('inbound', {})
info1['task'] = resd.get('task', {})
info2 = resd.get('outbound', {})
info2['task'] = resd.get('task', {})
clone_info2 = {}
clone_info2.update(info2)
ex1 = ExportTopo()
_, __, image_width2 = ex1.exportTopoOutbound(None, clone_info2)
ex2 = ExportTopo(name=None, info=info1)
file_name, _ = ex2.exportTopoInbound(info2.get('节点名称', []), info2, image_width2)
elif _test_type == "script":
temp = True if args.temp else False
file_name = ExportCommon(resd.pop("节点名称", []), resd).draw(debug=temp)
if file_name:
if args.temp and _test_type == "script":
print("测试结果:", resd)
else:
print("测试结果图片已保存在: ", str(Path(getcwd()).joinpath(f"results/{file_name}")))


parser = argparse.ArgumentParser(description="FullTClash命令行简易测试,不用启动bot。")
parser.add_argument("-f", "--file", required=True, type=str, help="订阅文件路径")
parser.add_argument("-c", "--core", required=True, type=str, help="订阅文件路径,支持本地路径和URL路径")
parser.add_argument("-i", "--include", required=False, type=str, help="包含过滤器")
parser.add_argument("-e", "--exclude", required=False, type=str, help="排除过滤器")
parser.add_argument("--temp", action='store_true', help="临时输出测试结果,将自动打开测试结果图片(仅对script类型有效),"
"图片不保存到本地。")

args = parser.parse_args()
if args.core == 'speed':
core = SpeedCore()
_test_type = str(args.core)
elif args.core == 'script':
core = ScriptCore()
_test_type = str(args.core)
elif args.core == 'topo':
core = TopoCore()
_test_type = str(args.core)
else:
raise TypeError("Unknown test type, please input again.\n未知的测试类型,请重新输入!")
include_text = ""
exclude_text = ""
file_path = ""
if args.include:
include_text = args.include
if args.exclude:
exclude_text = args.exclude
if args.file:
file_path = args.file

try:
if core is None:
print("未找到核心")
sys.exit()
my_proxies = get_proxies(file_path)
resd: dict = loop.run_until_complete(core.core(my_proxies))
except Exception as e:
print(e)
sys.exit()
try:
export_to_image()
except Exception as _e:
print(_e)
print("测试结果绘图失败!以下是原始测试结果: \n", resd)

0 comments on commit 0a1fd3a

Please sign in to comment.