forked from yanjisheng/blivechat
-
Notifications
You must be signed in to change notification settings - Fork 51
/
main.py
169 lines (131 loc) · 4.05 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# -*- coding: utf-8 -*-
import argparse
import asyncio
import logging
import logging.handlers
import os
import signal
import sys
import webbrowser
from typing import *
import tornado.ioloop
import tornado.web
import api.chat
import api.main
import api.open_live
import config
import models.database
import services.avatar
import services.chat
import services.translate
import update
import utils.request
logger = logging.getLogger(__name__)
ROUTES = [
*api.main.ROUTES,
*api.chat.ROUTES,
*api.open_live.ROUTES,
*api.main.LAST_ROUTES,
]
server: Optional[tornado.httpserver.HTTPServer] = None
shut_down_event: Optional[asyncio.Event] = None
async def main():
if not init():
return 1
try:
await run()
finally:
await shut_down()
return 0
def init():
init_signal_handlers()
args = parse_args()
init_logging(args.debug)
logger.info('App started, initializing')
config.init()
utils.request.init()
models.database.init(args.debug)
services.avatar.init()
services.translate.init()
services.chat.init()
update.check_update()
init_server(args.host, args.port, args.debug)
return server is not None
def init_signal_handlers():
global shut_down_event
shut_down_event = asyncio.Event()
signums = (signal.SIGINT, signal.SIGTERM)
try:
loop = asyncio.get_running_loop()
for signum in signums:
loop.add_signal_handler(signum, on_shut_down_signal)
except NotImplementedError:
# 不太安全,但Windows只能用这个
for signum in signums:
signal.signal(signum, on_shut_down_signal)
def on_shut_down_signal(*_args):
shut_down_event.set()
def parse_args():
parser = argparse.ArgumentParser(description='用于OBS的仿YouTube风格的bilibili直播评论栏')
parser.add_argument('--host', help='服务器host,默认和配置中的一样', default=None)
parser.add_argument('--port', help='服务器端口,默认和配置中的一样', type=int, default=None)
parser.add_argument('--debug', help='调试模式', action='store_true')
return parser.parse_args()
def init_logging(debug):
filename = os.path.join(config.BASE_PATH, 'log', 'blivechat.log')
stream_handler = logging.StreamHandler()
file_handler = logging.handlers.TimedRotatingFileHandler(
filename, encoding='utf-8', when='midnight', backupCount=7, delay=True
)
logging.basicConfig(
format='{asctime} {levelname} [{name}]: {message}',
style='{',
level=logging.INFO if not debug else logging.DEBUG,
handlers=[stream_handler, file_handler]
)
# 屏蔽访问日志
logging.getLogger('tornado.access').setLevel(logging.WARNING)
def init_server(host, port, debug):
cfg = config.get_config()
if host is None:
host = cfg.host
if port is None:
port = cfg.port
app = tornado.web.Application(
ROUTES,
websocket_ping_interval=10,
debug=debug,
autoreload=False
)
try:
global server
server = app.listen(
port,
host,
xheaders=cfg.tornado_xheaders,
max_body_size=1024 * 1024,
max_buffer_size=1024 * 1024
)
except OSError:
logger.warning('Address is used %s:%d', host, port)
return
finally:
if cfg.open_browser_at_startup:
url = 'http://localhost/' if port == 80 else f'http://localhost:{port}/'
url += '?_v=' + update.DOODLEBEAR_VERSION
webbrowser.open(url)
logger.info('Server started: %s:%d', host, port)
async def run():
logger.info('Running event loop')
await shut_down_event.wait()
logger.info('Received shutdown signal')
async def shut_down():
logger.info('Closing server')
server.stop()
await server.close_all_connections()
logger.info('Closing websocket connections')
await services.chat.shut_down()
await utils.request.shut_down()
logger.info('App shut down')
if __name__ == '__main__':
sys.exit(asyncio.run(main()))