Skip to content

Commit

Permalink
fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
hiddify-com committed Feb 1, 2024
1 parent fa679e3 commit b4ce515
Show file tree
Hide file tree
Showing 16 changed files with 100 additions and 64 deletions.
8 changes: 0 additions & 8 deletions app.cfg

This file was deleted.

1 change: 1 addition & 0 deletions app.cfg
7 changes: 4 additions & 3 deletions hiddifypanel/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ def exception_handler(e, original_fn, args, kwargs):

def key_serializer(args):
from .models import ConfigEnum
return dumps([f'{r}' if isinstance(r, ConfigEnum) else r for r in args])
# return dumps([f'{r}' if isinstance(r, ConfigEnum) else r for r in args])
return dumps(args)


# cache = RedisCache(redis_client=redis_client, exception_handler=exception_handler)
Expand Down Expand Up @@ -48,7 +49,7 @@ class DisableCache:
cache = CacheDecorator


# cache = DisableCache()
cache = DisableCache()
try:
@cache.cache()
def test():
Expand All @@ -57,4 +58,4 @@ def test():
except Exception as e:
import sys
print('Caching Error! Disabling cache', e, file=sys.stderr)
cache = DisableCache()
# cache = DisableCache()
2 changes: 1 addition & 1 deletion hiddifypanel/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import re
import os

db = SQLAlchemy()
db:SQLAlchemy = SQLAlchemy()
db.UUID = UUIDType # type: ignore


Expand Down
6 changes: 4 additions & 2 deletions hiddifypanel/hutils/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from hiddifypanel.models.config import hconfig
from hiddifypanel.models.config_enum import ConfigEnum

from flask_babel import gettext as _

def is_int(input: str) -> bool:
try:
Expand All @@ -15,8 +15,10 @@ def is_int(input: str) -> bool:
return False


def to_int(s: str) -> int:
def to_int(s: str|None) -> int|None:
'''Returns 0 if <s> is not a number'''
if not s:
return None
try:
return int(s)
except:
Expand Down
2 changes: 1 addition & 1 deletion hiddifypanel/hutils/importer/xui.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def __create_hiddify_domain_from_xui_values(domain: str, values: Dict[str, Any])
return d


def __extract_users_and_domains_from_xui_db(db_path: str) -> Tuple[List[User], List[Domain]]:
def __extract_users_and_domains_from_xui_db(db_path: str) -> Tuple[List["User"], List["Domain"]]:
users = {}
reality_domains = {}

Expand Down
31 changes: 30 additions & 1 deletion hiddifypanel/hutils/random.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import random
import string

from hiddifypanel.models import hconfig,ConfigEnum

def get_random_string(min_: int = 10, max_: int = 30) -> str:
# With combination of lower and upper case
Expand All @@ -17,3 +17,32 @@ def get_random_password(length: int = 16) -> str:
passwd = ''.join(random.choice(characters) for i in range(length))
if (any(c.islower() for c in passwd) and any(c.isupper() for c in passwd) and sum(c.isdigit() for c in passwd) > 1):
return passwd


def __is_port_in_range(port, start_port:int|str|None,count:int):
if start_port==None:
return False
start_port=int(start_port)
if port<start_port:
return False

if port>start_port+count:
return False
return True


def __is_in_used_port(port):
if __is_port_in_range(port,hconfig(ConfigEnum.reality_port),100):
return True
if __is_port_in_range(port,hconfig(ConfigEnum.hysteria_port),100):
return True

if __is_port_in_range(port,hconfig(ConfigEnum.tuic_port),100):
return True
if port in [443,80,9000,10085,10086]:
return True
def get_random_unused_port():
port=random.randint(11000, 60000)
while __is_in_used_port(port):
port=random.randint(11000, 60000)
return port
2 changes: 1 addition & 1 deletion hiddifypanel/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from .role import Role, AccountType
from .child import Child, ChildMode
from .config import StrConfig, BoolConfig, get_hconfigs, hconfig, set_hconfig, add_or_update_config, bulk_register_configs, get_hconfigs_childs
from .config_enum import ConfigCategory, ConfigEnum, Lang
from .child import Child, ChildMode

# from .parent_domain import ParentDomain
from .domain import Domain, DomainType, ShowDomain, get_domain, get_current_proxy_domains, get_panel_domains, get_proxy_domains, get_proxy_domains_db, get_hdomains, hdomain, add_or_update_domain, bulk_register_domains
Expand Down
1 change: 1 addition & 0 deletions hiddifypanel/models/base_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def by_username_password(cls, username: str, password: str):

@classmethod
def add_or_update(cls, commit: bool = True, **data):
from hiddifypanel import hutils
db_account = cls.by_uuid(data['uuid'], create=True)
db_account.name = data.get('name') or ''
db_account.comment = data.get('comment', '')
Expand Down
24 changes: 12 additions & 12 deletions hiddifypanel/models/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@
from hiddifypanel import Events
from hiddifypanel.database import db
from hiddifypanel.cache import cache
from hiddifypanel.models.child import Child

from hiddifypanel.models.child import Child,ChildMode
from sqlalchemy import Column, String, Boolean, Enum,ForeignKey,Integer

def error(st):
from hiddifypanel.hutils.utils import error as err
err(st)


class BoolConfig(db.Model, SerializerMixin):
child_id = db.Column(db.Integer, db.ForeignKey('child.id'), primary_key=True, default=0)
child_id = Column(Integer, ForeignKey('child.id'), primary_key=True, default=0)
# category = db.Column(db.String(128), primary_key=True)
key = db.Column(db.Enum(ConfigEnum, values_callable=ConfigEnum.dbvalues), primary_key=True)
value = db.Column(db.Boolean)
key = Column(Enum(ConfigEnum, values_callable=ConfigEnum.dbvalues), primary_key=True)
value = Column(Boolean)

def to_dict(d):
return {
Expand All @@ -27,10 +27,10 @@ def to_dict(d):


class StrConfig(db.Model, SerializerMixin):
child_id = db.Column(db.Integer, db.ForeignKey('child.id'), primary_key=True, default=0)
child_id = Column(Integer, ForeignKey('child.id'), primary_key=True, default=0)
# category = db.Column(db.String(128), primary_key=True)
key = db.Column(db.Enum(ConfigEnum, values_callable=ConfigEnum.dbvalues), primary_key=True, default=ConfigEnum.admin_secret)
value = db.Column(db.String(2048))
key = Column(Enum(ConfigEnum, values_callable=ConfigEnum.dbvalues), primary_key=True, default=ConfigEnum.admin_secret)
value = Column(String(2048))

def to_dict(d):
return {
Expand All @@ -41,7 +41,7 @@ def to_dict(d):


@cache.cache(ttl=500)
def hconfig(key: ConfigEnum, child_id: int = None) -> str | int | None:
def hconfig(key: ConfigEnum, child_id: int|None = None) -> str | int | None:
if child_id == None:
child_id = Child.current.id

Expand Down Expand Up @@ -69,7 +69,7 @@ def hconfig(key: ConfigEnum, child_id: int = None) -> str | int | None:
return value


def set_hconfig(key: ConfigEnum, value: str | bool, child_id: int = None, commit: bool = True):
def set_hconfig(key: ConfigEnum, value: str|int | bool, child_id: int = None, commit: bool = True):
if child_id == None:
child_id = Child.current.id
# hconfig.invalidate(key, child_id)
Expand Down Expand Up @@ -109,7 +109,7 @@ def set_hconfig(key: ConfigEnum, value: str | bool, child_id: int = None, commit


@cache.cache(ttl=500,)
def get_hconfigs(child_id: int = None, json=False):
def get_hconfigs(child_id: int|None = None, json=False):
if child_id == None:
child_id = Child.current.id

Expand Down Expand Up @@ -141,7 +141,7 @@ def add_or_update_config(commit: bool = True, child_id: int = None, override_uni
set_hconfig(ckey, v, child_id, commit=commit)


def bulk_register_configs(hconfigs, commit: bool = True, override_child_id: int = None, override_unique_id: bool = True):
def bulk_register_configs(hconfigs, commit: bool = True, override_child_id: int|None = None, override_unique_id: bool = True):
from hiddifypanel.panel import hiddify
for conf in hconfigs:
# print(conf)
Expand Down
3 changes: 2 additions & 1 deletion hiddifypanel/models/config_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ def __neq__(self, other):

def endswith(self, suffix):
return f'{self}'.endswith(suffix)

def __reduce__(self):
return self.name

class ConfigEnum(__BaseConfigEnum):
wireguard_enable = _BoolConfigDscr(ConfigCategory.wireguard, ApplyMode.apply, hide_in_virtual_child=True)
Expand Down
1 change: 1 addition & 0 deletions hiddifypanel/models/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def internal_port_hysteria2(self):
if self.mode not in [DomainType.direct, DomainType.relay, DomainType.fake]:
return 0
# TODO: check validity of the range of the port
# print("child_id",self.child_id)
return int(hconfig(ConfigEnum.hysteria_port, self.child_id))+self.port_index

@property
Expand Down
2 changes: 1 addition & 1 deletion hiddifypanel/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def by_uuid(cls, uuid: str, create: bool = False):

@classmethod
def add_or_update(cls, commit: bool = True, **data):

from hiddifypanel import hutils
dbuser = super().add_or_update(commit=commit, **data)
if data.get('added_by_uuid'):
admin = AdminUser.by_uuid(data.get('added_by_uuid'), create=True) or AdminUser.current_admin_or_owner()
Expand Down
4 changes: 2 additions & 2 deletions hiddifypanel/panel/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ def all_configs():
"users": valid_users,
"domains": [u.to_dict(dump_ports=True, dump_child_id=True) for u in Domain.query.filter(Domain.child_id.in_(host_child_ids)).all() if "*" not in u.domain],
# "parent_domains": [hiddify.parent_domain_dict(u) for u in ParentDomain.query.all()],
"hconfigs": get_hconfigs(json=True),
# "hconfigs": get_hconfigs(json=True),
"chconfigs": get_hconfigs_childs(host_child_ids, json=True)
}

def_user = None if len(User.query.all()) > 1 else User.query.filter(User.name == 'default').first()
domains = Domain.query.all()
sslip_domains = [d.domain for d in domains if "sslip.io" in d.domain]

configs['hconfigs']['first_setup'] = def_user != None and len(sslip_domains) > 0
configs['chconfigs'][0]['first_setup'] = def_user != None and len(sslip_domains) > 0
server_ip = hutils.network.get_ip_str(4)
owner = AdminUser.get_super_admin()

Expand Down
4 changes: 2 additions & 2 deletions hiddifypanel/panel/hiddify.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,8 @@ def set_db_from_json(json_data, override_child_id=None, set_users=True, set_doma
User.bulk_register(json_data['users'], commit=False, remove=remove_users)
if set_domains and 'domains' in json_data:
bulk_register_domains(json_data['domains'], commit=False, remove=remove_domains, override_child_id=override_child_id)
if set_domains and 'parent_domains' in json_data:
ParentDomain.bulk_register(json_data['parent_domains'], commit=False, remove=remove_domains)
# if set_domains and 'parent_domains' in json_data:
# ParentDomain.bulk_register(json_data['parent_domains'], commit=False, remove=remove_domains)
if set_settings and 'hconfigs' in json_data:
bulk_register_configs(json_data["hconfigs"], commit=True, override_child_id=override_child_id, override_unique_id=override_unique_id)
if 'proxies' in json_data:
Expand Down
32 changes: 18 additions & 14 deletions hiddifypanel/panel/init_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@

from dateutil import relativedelta

from hiddifypanel import Events, hutils
from hiddifypanel import Events,hutils
from hiddifypanel.models import *
from hiddifypanel.models import ConfigEnum,User,set_hconfig, ChildMode
from hiddifypanel.panel import hiddify
from hiddifypanel.database import db
import hiddifypanel.models.utils as model_utils
Expand All @@ -18,6 +19,11 @@

MAX_DB_VERSION = 80

def _v71(child_id):
add_config_if_not_exist(ConfigEnum.tuic_port, hutils.random.get_random_unused_port())
add_config_if_not_exist(ConfigEnum.hysteria_port, hutils.random.get_random_unused_port())
add_config_if_not_exist(ConfigEnum.ssh_server_port, hutils.random.get_random_unused_port())
add_config_if_not_exist(ConfigEnum.wireguard_port, hutils.random.get_random_unused_port())

def _v70(child_id):
Domain.query.filter(Domain.child_id != 0).delete()
Expand All @@ -37,7 +43,7 @@ def _v70(child_id):
def _v69():
db.session.bulk_save_objects(get_proxy_rows_v1())
add_config_if_not_exist(ConfigEnum.wireguard_enable, True)
add_config_if_not_exist(ConfigEnum.wireguard_port, random.randint(30000, 40000))
add_config_if_not_exist(ConfigEnum.wireguard_port, hutils.random.get_random_unused_port())
add_config_if_not_exist(ConfigEnum.wireguard_ipv4, "10.90.0.1")
add_config_if_not_exist(ConfigEnum.wireguard_ipv6, "fd42:42:90::1")
wg_pk, wg_pub, _ = hiddify.get_wg_private_public_psk_pair()
Expand All @@ -64,9 +70,10 @@ def _v64():
set_hconfig(ConfigEnum.ssh_server_redis_url, "unix:///opt/hiddify-manager/other/redis/run.sock?db=1")



def _v63():
add_config_if_not_exist(ConfigEnum.hysteria_enable, True)
add_config_if_not_exist(ConfigEnum.hysteria_port, "11478")
add_config_if_not_exist(ConfigEnum.hysteria_port, hutils.random.get_random_unused_port())
add_config_if_not_exist(ConfigEnum.hysteria_obfs_enable, True)
add_config_if_not_exist(ConfigEnum.hysteria_up_mbps, "150")
add_config_if_not_exist(ConfigEnum.hysteria_down_mbps, "300")
Expand Down Expand Up @@ -108,13 +115,12 @@ def _v57():


def _v56():
reality_port = random.randint(20000, 30000)
set_hconfig(ConfigEnum.reality_port, reality_port)
set_hconfig(ConfigEnum.reality_port, hutils.random.get_random_unused_port())


def _v55():
tuic_port = random.randint(20000, 30000)
hystria_port = random.randint(10000, 20000)
tuic_port = hutils.random.get_random_unused_port()
hystria_port = hutils.random.get_random_unused_port()
set_hconfig(ConfigEnum.tuic_port, tuic_port)
set_hconfig(ConfigEnum.hysteria_port, hystria_port)
set_hconfig(ConfigEnum.tuic_enable, True)
Expand Down Expand Up @@ -158,11 +164,7 @@ def _v45():
if not Proxy.query.filter(Proxy.name == "SSH").first():
db.session.add(Proxy(l3='ssh', transport='ssh', cdn='direct', proto='ssh', enable=True, name="SSH"))
add_config_if_not_exist(ConfigEnum.ssh_server_redis_url, "unix:///opt/hiddify-manager/other/redis/run.sock?db=1")
while 1:
port = random.randint(5000, 40000)
if port not in [10085, 10086]:
break
add_config_if_not_exist(ConfigEnum.ssh_server_port, port)
add_config_if_not_exist(ConfigEnum.ssh_server_port, hutils.random.get_random_unused_port())
add_config_if_not_exist(ConfigEnum.ssh_server_enable, False)
# def _v43():
# if not (Domain.query.filter(Domain.domain==hconfig(ConfigEnum.domain_fronting_domain)).first()):
Expand Down Expand Up @@ -471,10 +473,12 @@ def make_proxy_rows(cfgs):
yield Proxy(l3=l3, transport=transport, cdn=cdn, proto=proto, enable=enable, name=name)


def add_config_if_not_exist(key: ConfigEnum, val, child_id=None):
def add_config_if_not_exist(key: ConfigEnum, val:str|int, child_id:int|None=None):
if child_id == None:
child_id = Child.current.id

old_val = hconfig(key, child_id)
print(key,val,child_id,old_val)
if old_val is None:
set_hconfig(key, val)

Expand Down Expand Up @@ -581,8 +585,8 @@ def init_db():
db.create_all()
hconfig.invalidate_all()
get_hconfigs.invalidate_all()
# set_hconfig(ConfigEnum.db_version, 62)
db_version = int(hconfig(ConfigEnum.db_version) or 0)
# set_hconfig(ConfigEnum.db_version, 69)
if db_version == latest_db_version():
return
migrate(db_version)
Expand Down
Loading

0 comments on commit b4ce515

Please sign in to comment.