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(
23 username: str = typer.Option(..., *utils.FLAGS["username"], prompt=True)
24):
25 """
26 Prints the given user's subscription link.
27
28 NOTE: This command needs `XRAY_SUBSCRIPTION_URL_PREFIX` environment variable to be set
29 in order to work correctly.
30 """
31 with GetDB() as db:
32 user: UserResponse = UserResponse.from_orm(utils.get_user(db, username))
33 print(user.subscription_url)
34
35
36@app.command(name="get-config")
37def get_config(
38 username: str = typer.Option(..., *utils.FLAGS["username"], prompt=True),
39 config_format: ConfigFormat = typer.Option(..., *utils.FLAGS["format"], prompt=True),
40 output_file: Optional[str] = typer.Option(
41 None, *utils.FLAGS["output_file"], help="Writes the generated config in the file if provided"
42 ),
43 as_base64: bool = typer.Option(
44 False, "--base64", is_flag=True, help="Encodes output in base64 format if present"
45 )
46):
47 """
48 Generates a subscription config.
49
50 Generates a subscription config for the given user in the given format.
51
52 The output will be written in the output file when the `output-file` is present,
53 otherwise will be shown in the terminal.
54 """
55 with GetDB() as db:
56 user: UserResponse = UserResponse.from_orm(utils.get_user(db, username))
57 conf: str = generate_subscription(
58 user=user, config_format=config_format.name, as_base64=as_base64
59 )
60
61 if output_file:
62 with open(output_file, "w") as out_file:
63 out_file.write(conf)
64
65 utils.success(
66 f'{username}\'s configuration in "{config_format.value}" format'
67 f' successfully save to "{output_file}".'
68 )
69 else:
70 utils.success(
71 'No output file specified.'
72 f' using pager for {username}\'s config in "{config_format}" format.',
73 auto_exit=False
74 )
75 utils.paginate(conf)