forked from MoreliaTalk/morelia_server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manage.py
749 lines (648 loc) · 22.2 KB
/
manage.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
"""
Copyright (c) 2020 - present MoreliaTalk team and other.
Look at the file AUTHORS.md(located at the root of the project) to get the
full list.
This file is part of Morelia Server.
Morelia Server is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Morelia Server is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Morelia Server. If not, see <https://www.gnu.org/licenses/>.
"""
import asyncio
from functools import wraps
import os
from pathlib import Path
import random
from time import time
from typing import Callable
from uuid import uuid4
import click
from sqlobject import SQLObjectNotFound
import uvicorn
from websockets import client as ws_client
from websockets import exceptions as ws_exceptions
from mod.config.config import ConfigHandler
from mod.db.dbhandler import DatabaseAccessError
from mod.db.dbhandler import DatabaseReadError
from mod.db.dbhandler import DatabaseWriteError
from mod.db.dbhandler import DBHandler
from mod.lib import Hash
from mod.protocol.mtp.api import BaseUser
from mod.protocol.mtp.api import BaseVersion
from mod.protocol.mtp.api import DataRequest
from mod.protocol.mtp.api import FlowRequest
from mod.protocol.mtp.api import Request
VERSION = 'v0.3'
DEFAULT_CONFIG = 'config.ini'
DEFAULT_EXAMPLE_CONFIG = 'example_config.ini'
DEFAULT_DB = 'db_sqlite.db'
SYMBOLS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
class CopyConfigError(Exception):
"""
Occurs when the original configuration file does not exist.
"""
async def connect_ws_and_send(message: Request,
address: str) -> None:
"""
Connect and send message to address.
Args:
message: message for send
address(str): server address
"""
try:
ws = await ws_client.connect(address)
except ConnectionRefusedError:
click.echo("Unable to connect to the server, please check the server")
else:
await ws.send(message.json())
try:
response = await ws.recv()
except ws_exceptions.ConnectionClosedError as error:
click.echo(f"Server disconnected not normal, error: {error}")
else:
click.echo(response)
await ws.close(1000)
def click_async(func: Callable):
"""
Wrapper to call the click function asynchronously.
Args:
func: function
Returns:
(wrapper)
"""
@wraps(func)
def wrapper(*args, **kwargs):
return asyncio.run(func(*args, **kwargs))
return wrapper
def copy_config(source: str,
destination: str) -> None:
"""
Copies the configuration file.
File example_config.ini copied to config.ini in root directory with
project files.
Args:
source: source file name, default example_config.ini
destination: destination file name, default config.ini
"""
src = Path(source)
dst = Path(destination)
if src.is_file():
with open(dst.absolute(), "w+") as new_file:
old_file = open(src.absolute(), 'r')
new_file.write(old_file.read())
old_file.close()
else:
raise CopyConfigError(f"There is no such file={src.name}")
def create_table() -> None:
"""
Creates a database file and fills it with empty tables.
"""
config = ConfigHandler(log=False)
config_options = config.read()
db = DBHandler(uri=config_options.uri)
db.create_table()
def create_administrator(username: str,
password: str) -> None:
"""
Creates an administrator account to manage the server.
Args:
username: name for new administrator user
password: password for new administrator user
"""
config = ConfigHandler(log=False)
config_read = config.read()
db = DBHandler(uri=config_read.uri)
user_uuid = str(uuid4().int)
db.add_admin(username=username,
hash_password=Hash(password, user_uuid).password_hash())
@click.group(name="Main group for all options.",
help="Morelia Talk server manager.")
@click.version_option(version=VERSION,
package_name="MoreliaTalk server")
@click.help_option()
def cli() -> None:
"""
Morelia Talk server manager.
It's main tool for working with the MoreliaTalk server,
allowing you to start and configure server.
"""
@cli.group("create",
help="Tools for creating object in database.")
@click.option("--uri",
default="sqlite:db_sqlite.db",
show_default=True,
help="Connection to database.")
@click.pass_context
def create(context: click.Context,
uri: str) -> None:
"""
Tools for creating object in database.
Args:
context: click call context
uri: Connection to database, like: sqlite:db_sqlite.db
"""
context.ensure_object(dict)
context.obj['uri'] = uri
@create.command("db",
help="Create all table with all data")
@click.pass_context
def create_db(context: click.Context) -> None:
"""
Create database, and create all table which contain in models.
"""
db = DBHandler(context.obj["uri"])
try:
db.create_table()
except (DatabaseReadError,
DatabaseAccessError,
DatabaseWriteError) as err:
click.echo(f"The database is unavailable, table not created. {err}")
else:
click.echo("Database is created.")
@create.command("user",
help="Creates a user in the database, \
if login and password are empty, \
then generates them randomly")
@click.option("--login",
type=str,
default="".join(random.sample(SYMBOLS, 6)),
help="New user login name.")
@click.option("--username",
type=str,
default="User",
show_default=True,
help="New user name.")
@click.option("--password",
type=str,
default="".join(random.sample(SYMBOLS, 20)),
help="New user password.")
@click.pass_context
def create_user(context: click.Context,
login: str,
username: str,
password: str) -> None:
"""
Create user in database.
Args:
context: click call context
login: user login
username: username
password: user password
"""
db = DBHandler(context.obj["uri"])
try:
db.create_table()
except DatabaseWriteError as error:
click.echo(f"Failed to create database. Error text: {error}")
return None
user_uuid = str(uuid4().int)
try:
db.add_user(uuid=user_uuid,
login=login,
password=password,
hash_password=Hash(password, user_uuid).password_hash(),
username=username,
salt=b"salt",
key=b"key")
except Exception as err:
click.echo(f"{err}")
else:
click.echo(f"User with name={username}, login={login}, ")
click.echo(f"and password={password} is created")
@create.command("flow",
help="Create flow type group in database")
@click.option("--login",
type=str,
help="Use login which you specified when create user")
@click.pass_context
def create_flow(context: click.Context,
login: str) -> None:
"""
Creating and adding test flow (group) to database.
Args:
context: click call context.
login: use login which you specified when create user.
"""
db = DBHandler(context.obj["uri"])
try:
db.create_table()
except DatabaseWriteError as error:
click.echo(f"Failed to create database. Error text: {error}")
return None
try:
user = db.get_user_by_login(login=login)
except (DatabaseReadError,
DatabaseAccessError,
DatabaseWriteError) as error:
click.echo(f'Failed to create a flow. Error text: {error}')
else:
new_flow = db.add_flow(uuid=str(uuid4().int),
users=[user.uuid],
time_created=int(time()),
flow_type="group",
title="Test",
info="Test flow",
owner=user.uuid)
new_flow.addUserConfig(user)
click.echo("Flow created.")
@create.command("admin",
help="Create user for admin panel")
@click.option("--username",
type=str,
prompt=True,
help="Name for administrator user.")
@click.option("--password",
type=str,
prompt=True,
hide_input=True,
help="New password for administrator user.")
@click.pass_context
def create_admin(context: click.Context,
username: str,
password: str) -> None:
"""
Create Admin user to management server with admin panel.
Args:
context: click call context
username: name of admin user
password: password of admin user
"""
db = DBHandler(context.obj["uri"])
try:
db.create_table()
except DatabaseWriteError as error:
click.echo(f"Failed to create database. Error text: {error}")
return None
generator = Hash(password,
str(uuid4().int),
key=b"key",
salt=b"salt")
try:
db.add_admin(username=username,
hash_password=generator.password_hash())
except (DatabaseReadError,
DatabaseAccessError,
DatabaseWriteError) as error:
click.echo(f'Failed to create a flow. Error text: {error}')
else:
click.echo("Admin created.")
click.echo(f"User name={username}, password={password}")
@cli.group("delete",
help="Tools for deleting object in database.")
@click.option("--uri",
default="sqlite:db_sqlite.db",
show_default=True,
help="Connection to database.")
@click.pass_context
def delete(context: click.Context,
uri: str) -> None:
"""
Tools for deleting object in database.
Args:
context: click call context
uri: Connection to database, like: sqlite:db_sqlite.db
"""
context.ensure_object(dict)
context.obj['uri'] = uri
@delete.command("db",
help="Delete all table with all data")
@click.pass_context
def delete_db(context: click.Context) -> None:
"""
Delete all tables which contains data.
This function not delete database file.
Args:
context: click call context
"""
db = DBHandler(context.obj["uri"])
try:
db.delete_table()
except (DatabaseReadError,
DatabaseAccessError,
DatabaseWriteError) as err:
click.echo(f"The database is unavailable, table not deleted. {err}")
else:
click.echo("All table is deleted.")
@cli.group("client",
help="Mini-client for send message to the MoreliaTalk server.")
def client() -> None:
"""
Mini-client for send message to the MoreliaTalk server.
"""
@client.command("send",
help="Send message to server used API method name.")
@click.option("--login",
type=str,
help="User login.")
@click.option("--username",
type=str,
help="User name.")
@click.option("--password",
type=str,
help="User password.")
@click.option("--user-uuid",
type=str,
help="User unique ID.")
@click.option("--user-auth-id",
type=str,
help="User authentication ID.")
@click.option("--flow-uuid",
type=str,
help="Flow unique ID.")
@click.option("--type",
"type_",
type=click.Choice(("register_user",
"get_update",
"send_message",
"all_messages",
"add_flow",
"all_flow",
"user_info",
"authentication",
"ping_pong")),
default="send_message",
show_default=True,
help="MTP protocol API method name.")
@click.option("--address",
type=str,
default="ws://127.0.0.1:8080/ws",
show_default=True,
help="Server address and port.")
@click_async
async def send(login: str,
username: str,
password: str,
user_uuid: str,
flow_uuid: str,
user_auth_id: str,
type_: str,
address: str) -> None:
"""
Connect and send message protocol method.
Args:
login: user login.
username: user name.
password: user password.
user_uuid: user uuid.
flow_uuid: flow uuid.
user_auth_id: user authentication ID.
type_: name of API method.
address: server address.
"""
message = Request(type=type_,
jsonapi=BaseVersion(version="1.0"))
message.data = DataRequest()
message.data.user = []
message.data.user.append(BaseUser())
message.parse_file(Path(Path(__file__).parent,
"tests",
"fixtures",
"".join((type_, ".json"))))
match type_:
case ("register_user",):
message.data.user[0].username = username
message.data.user[0].password = password
case ("get_update",
"add_flow",
"all_flow",
"ping_pong",
"user_info"):
message.data.user[0].uuid = user_uuid
message.data.user[0].auth_id = user_auth_id
case ("all_message", "send_message"):
message.data.flow = []
message.data.flow.append(FlowRequest())
message.data.flow[0].uuid = flow_uuid
message.data.user[0].uuid = user_uuid
message.data.user[0].auth_id = user_auth_id
case ("authentication"):
message.data.user[0].password = password
message.data.user[0].login = login
await connect_ws_and_send(message, address)
@cli.group("run",
help="Tools for running server in production or developing mode.")
def run() -> None:
"""
Tools for running server in production or developing mode.
"""
@run.command("init")
@click.option("--username",
type=str,
prompt=True,
help="Name for new user.")
@click.option("--password",
type=str,
prompt=True,
hide_input=True,
help="Password for new user.")
@click.option("--source",
type=str,
show_default=True,
default=DEFAULT_EXAMPLE_CONFIG,
help="source file name")
@click.option("--destination",
type=str,
show_default=True,
default=DEFAULT_CONFIG,
help="destination file name")
def init(username: str,
password: str,
source: str,
destination: str) -> None:
"""
Preparing the MoreliaTalk server for work.
This command will copy config.ini from example_config.ini,
create a database and an administrator account.
Args:
username: name for new administrator user
password: password for new administrator user
source: source file name, default example_config.ini
destination: destination file name, default config.ini
"""
try:
copy_config(source,
destination)
except (CopyConfigError, OSError):
click.echo("Example of config file not found, or ")
click.echo("no write access rights in the current directory.")
return
except Exception as err:
click.echo(f"Config =>x Bad. An unknown error occurred. {err}")
return
else:
click.echo("Config => Ok.")
try:
create_table()
except SQLObjectNotFound:
click.echo("Database file not found, or ")
click.echo("no write access rights in the current directory.")
except Exception as err:
click.echo(f"Database =>x Bad. An unknown error occurred. {err}")
return
else:
click.echo("Database => Ok.")
try:
create_administrator(username,
password)
except DatabaseWriteError:
click.echo("Database file not found, or ")
click.echo("no write access rights in the current directory.")
except Exception as err:
click.echo(f"Create admin =>x Bad. An unknown error occurred. {err}")
else:
click.echo("Create admin => Ok.")
click.echo(f"User name={username} is created")
click.echo("<=====================================================>")
click.echo("For run server in normal mode: ./manage.py run server")
click.echo("For run server in develop mode: ./manage.py run devserver")
@run.command("devserver",
help="Run server in debug (developing) mode.")
@click.option("--host",
type=str,
default="127.0.0.1",
show_default=True,
help="IP or DNS name for running server")
@click.option("--port",
type=int,
default=8080,
show_default=True,
help="IP port for running server")
@click.option("--log-level",
type=click.Choice(("critical",
"error",
"warning",
"info",
"debug",
"trace")),
default="debug",
show_default=True,
help="level logs")
@click.option("--use-colors",
is_flag=True,
default=True,
show_default=True,
help="enable use colors in terminal")
@click.option("--reload",
is_flag=True,
default=True,
show_default=True,
help="enable hot reloaded")
def devserver(host: str,
port: int,
log_level: str,
use_colors: bool,
reload: bool) -> None:
"""
Run server in debug (developing) mode.
Args:
host: IP or DNS name for running server
port: IP port for running server
log_level: level logs
use_colors: enable use colors in terminal
reload: enable hot reloaded
"""
click.echo(f"Develop server started at address=https//{host}:{port}")
uvicorn.run("server:app",
host=host,
port=port,
http="h11",
ws="websockets",
log_level=log_level,
use_colors=use_colors,
debug=True,
reload=reload)
@run.command("server",
help="Run server in production (normal) mode.")
@click.option("--host",
type=str,
default="localhost",
show_default=True,
help="IP or DNS name for running server")
@click.option("--port",
type=int,
default=8080,
show_default=True,
help="IP port for running server")
@click.option("--log-level",
type=click.Choice(("critical",
"error",
"warning",
"info",
"debug",
"trace")),
default="error",
show_default=True,
help="level logs")
@click.option("--use-colors",
is_flag=True,
default=False,
show_default=True,
help="enable use colors in terminal")
@click.option("--reload",
is_flag=True,
default=False,
show_default=True,
help="enable hot reloaded")
def server(host: str,
port: int,
log_level: str,
use_colors: bool,
reload: bool) -> None:
"""
Run server in production (normal) mode.
Args:
host: IP or DNS name for running server
port: IP port for running server
log_level: level logs
use_colors: enable use colors in terminal
reload: enable hot reloaded
"""
click.echo(f"Server started at address=https//{host}:{port}")
uvicorn.run("server:app",
host=host,
port=port,
http="h11",
ws="websockets",
log_level=log_level,
use_colors=use_colors,
debug=False,
reload=reload)
@run.command("clean",
help="Clean created config and database file.")
@click.option("--config-name",
type=str,
show_default=True,
default=DEFAULT_CONFIG,
help="name of config file")
@click.option("--db-name",
type=str,
show_default=True,
default=DEFAULT_DB,
help="name of database file")
@click.confirmation_option(prompt='Are you sure you want to drop file?')
def clean_init(config_name: str,
db_name: str) -> None:
"""
Clean created config and database file.
Args:
config_name: name of config file.
db_name: name of database file.
"""
if Path(config_name).is_file():
os.remove(config_name)
click.echo("Config file => deleted.")
else:
click.echo("Config file => NOT deleted.")
if Path(db_name).is_file():
os.remove(db_name)
click.echo("Database file => deleted.")
else:
click.echo("Database file => NOT deleted.")
if __name__ == "__main__":
cli()