gitscope
← marzneshin / nightly / cli/subscription.py
https://dev.kronoz.win/r/marzneshin.git
cli/subscription.py · Python
Blame Raw
 1import typer
 2from enum import StrEnum
 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(StrEnum):
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(
33            utils.get_user(db, username)
34        )
35        print(user.subscription_url)
36
37
38@app.command(name="get-config")
39def get_config(
40    username: str = typer.Option(..., *utils.FLAGS["username"], prompt=True),
41    config_format: ConfigFormat = typer.Option(
42        ..., *utils.FLAGS["format"], prompt=True
43    ),
44    output_file: Optional[str] = typer.Option(
45        None,
46        *utils.FLAGS["output_file"],
47        help="Writes the generated config in the file if provided",
48    ),
49    as_base64: bool = typer.Option(
50        False,
51        "--base64",
52        is_flag=True,
53        help="Encodes output in base64 format if present",
54    ),
55):
56    """
57    Generates a subscription config.
58
59    Generates a subscription config for the given user in the given format.
60
61    The output will be written in the output file when the `output-file` is present,
62      otherwise will be shown in the terminal.
63    """
64    with GetDB() as db:
65        user: UserResponse = UserResponse.from_orm(
66            utils.get_user(db, username)
67        )
68        conf: str = generate_subscription(
69            user=user, config_format=config_format.name, as_base64=as_base64
70        )
71
72        if output_file:
73            with open(output_file, "w") as out_file:
74                out_file.write(conf)
75
76            utils.success(
77                f'{username}\'s configuration in "{config_format.value}" format'
78                f' successfully save to "{output_file}".'
79            )
80        else:
81            utils.success(
82                "No output file specified."
83                f' using pager for {username}\'s config in "{config_format}" format.',
84                auto_exit=False,
85            )
86            utils.paginate(conf)