1import typer
2from enum import Enum
3from typing import Optional
4from rich.console import Console
5
6from app.db import GetDB
7from app.models.user import UserResponse
8from app.utils.share import generate_subscription
9
10from . import utils
11
12app = typer.Typer(no_args_is_help=True)
13console = Console()
14
15
16class ConfigFormat(str, Enum):
17 v2ray = "v2ray"
18 clash = "clash"
19
20
21@app.command(name="get-link")
22def get_link(username: str = typer.Option(..., *utils.FLAGS["username"], prompt=True)):
23 """
24 Prints the given user's subscription link.
25
26 NOTE: This command needs `XRAY_SUBSCRIPTION_URL_PREFIX` environment variable to be set
27 in order to work correctly.
28 """
29 with GetDB() as db:
30 user: UserResponse = UserResponse.from_orm(utils.get_user(db, username))
31 print(user.subscription_url)
32
33
34@app.command(name="get-config")
35def get_config(
36 username: str = typer.Option(..., *utils.FLAGS["username"], prompt=True),
37 config_format: ConfigFormat = typer.Option(
38 ..., *utils.FLAGS["format"], prompt=True
39 ),
40 output_file: Optional[str] = typer.Option(
41 None,
42 *utils.FLAGS["output_file"],
43 help="Writes the generated config in the file if provided",
44 ),
45 as_base64: bool = typer.Option(
46 False,
47 "--base64",
48 is_flag=True,
49 help="Encodes output in base64 format if present",
50 ),
51):
52 """
53 Generates a subscription config.
54
55 Generates a subscription config for the given user in the given format.
56
57 The output will be written in the output file when the `output-file` is present,
58 otherwise will be shown in the terminal.
59 """
60 with GetDB() as db:
61 user: UserResponse = UserResponse.from_orm(utils.get_user(db, username))
62 conf: str = generate_subscription(
63 user=user, config_format=config_format.name, as_base64=as_base64
64 )
65
66 if output_file:
67 with open(output_file, "w") as out_file:
68 out_file.write(conf)
69
70 utils.success(
71 f'{username}\'s configuration in "{config_format.value}" format'
72 f' successfully save to "{output_file}".'
73 )
74 else:
75 utils.success(
76 "No output file specified."
77 f' using pager for {username}\'s config in "{config_format}" format.',
78 auto_exit=False,
79 )
80 utils.paginate(conf)