Skip to content

Commit

Permalink
fix: 修复启动报错的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
hanxi committed Jul 14, 2024
1 parent 6d7d90d commit dd77176
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
11 changes: 6 additions & 5 deletions xiaomusic/httpserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,13 @@ def no_verification():
)


def reset_dependency():
if not config.disable_httpauth:
def reset_http_server():
log.info(f"disable_httpauth:{config.disable_httpauth}")
if config.disable_httpauth:
app.dependency_overrides[verification] = no_verification
else:
app.dependency_overrides = {}
app.mount("/music", StaticFiles(directory=config.music_path), name="music")


def HttpInit(_xiaomusic):
Expand All @@ -81,8 +83,7 @@ def HttpInit(_xiaomusic):
log = xiaomusic.log

app.mount("/static", StaticFiles(directory="xiaomusic/static"), name="static")
app.mount("/music", StaticFiles(directory=config.music_path), name="music")
reset_dependency()
reset_http_server()


@app.get("/")
Expand Down Expand Up @@ -179,7 +180,7 @@ async def savesetting(request: Request):
debug_data = deepcopy_data_no_sensitive_info(data)
log.info(f"saveconfig: {debug_data}")
await xiaomusic.saveconfig(data)
reset_dependency()
reset_http_server()
return "save success"
except json.JSONDecodeError as err:
raise HTTPException(status_code=400, detail="Invalid JSON") from err
Expand Down
31 changes: 20 additions & 11 deletions xiaomusic/xiaomusic.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ def __init__(self, config: Config):
# 初始化插件
self.plugin_manager = PluginManager(self)

# 更新设备列表
self.update_devices()

debug_config = deepcopy_data_no_sensitive_info(self.config)
self.log.info(f"Startup OK. {debug_config}")

Expand All @@ -100,8 +103,6 @@ def init_config(self):
self.exclude_dirs = set(self.config.exclude_dirs.split(","))
self.music_path_depth = self.config.music_path_depth

self.update_devices()

def update_devices(self):
self.device_id_did = {} # key 为 device_id
self.groups = {} # key 为 group_name, value 为 device_id_list
Expand Down Expand Up @@ -144,24 +145,24 @@ def setup_logger(self):
async def poll_latest_ask(self):
async with ClientSession() as session:
while True:
self.log.debug(
f"Listening new message, timestamp: {self.last_timestamp}"
)
#self.log.debug(
# f"Listening new message, timestamp: {self.last_timestamp}"
#)
session._cookie_jar = self.cookie_jar

# 拉取所有音箱的对话记录
tasks = [
self.get_latest_ask_from_xiaoai(session, device_id)
for device_id in self.config.devices
for device_id in self.device_id_did
]
await asyncio.gather(*tasks)

start = time.perf_counter()
self.log.debug(f"Polling_event, timestamp: {self.last_timestamp}")
#self.log.debug(f"Polling_event, timestamp: {self.last_timestamp}")
await self.polling_event.wait()
if (d := time.perf_counter() - start) < 1:
# sleep to avoid too many request
self.log.debug(f"Sleep {d}, timestamp: {self.last_timestamp}")
#self.log.debug(f"Sleep {d}, timestamp: {self.last_timestamp}")
await asyncio.sleep(1 - d)

async def init_all_data(self, session):
Expand Down Expand Up @@ -268,7 +269,7 @@ async def get_latest_ask_from_xiaoai(self, session, device_id):
hardware=hardware,
timestamp=str(int(time.time() * 1000)),
)
self.log.debug(f"url:{url}")
#self.log.debug(f"url:{url} device_id:{device_id} hardware:{hardware}")
r = await session.get(url, timeout=timeout, cookies=cookies)
except Exception as e:
self.log.exception(f"Execption {e}")
Expand Down Expand Up @@ -363,9 +364,13 @@ def get_music_url(self, name):
return url

filename = self.get_filename(name).replace("\\", "/")
if filename.startswith(self.config.music_path):
filename = filename[len(self.config.music_path) :]
if filename.startswith("/"):
filename = filename[1:]
self.log.debug(f"get_music_url local music. name:{name}, filename:{filename}")
encoded_name = urllib.parse.quote(filename)
return f"http://{self.hostname}:{self.public_port}/{encoded_name}"
return f"http://{self.hostname}:{self.public_port}/music/{encoded_name}"

# 获取目录下所有歌曲,生成随机播放列表
def _gen_all_music_list(self):
Expand Down Expand Up @@ -474,7 +479,7 @@ async def run_forever(self):
self.polling_event.clear() # stop polling when processing the question
query = new_record.get("query", "").strip()
did = new_record.get("did", "").strip()
await self._do_check_cmd(did, query, False)
await self.do_check_cmd(did, query, False)

# 匹配命令
async def do_check_cmd(self, did="", query="", ctrl_panel=True, **kwargs):
Expand All @@ -491,6 +496,9 @@ async def do_check_cmd(self, did="", query="", ctrl_panel=True, **kwargs):
except Exception as e:
self.log.exception(f"Execption {e}")

async def check_replay(self, did):
return await self.devices[did].check_replay()

# 检查是否匹配到完全一样的指令
def check_full_match_cmd(self, did, query, ctrl_panel):
if query in self.config.key_match_order:
Expand Down Expand Up @@ -754,6 +762,7 @@ async def reinit(self, **kwargs):
self.setup_logger()
await self.init_all_data(self.session)
self._gen_all_music_list()
self.update_devices()

debug_config = deepcopy_data_no_sensitive_info(self.config)
self.log.info(f"reinit success. data:{debug_config}")
Expand Down

0 comments on commit dd77176

Please sign in to comment.