diff --git a/.dockerignore b/.dockerignore index 26cea00e2..a204aa3fe 100644 --- a/.dockerignore +++ b/.dockerignore @@ -17,4 +17,4 @@ db.sqlite3-journal docker-compose*.yml v2ray-core venv -xray-core \ No newline at end of file +xray-core diff --git a/app/dashboard/README.md b/app/dashboard/README.md index 819e840a1..eb955fe06 100644 --- a/app/dashboard/README.md +++ b/app/dashboard/README.md @@ -38,3 +38,13 @@ Copy `example.env` to `.env` then set the backend api address: ## Contribution Feel free to contribute. Go on and fork the project. After commiting the changes, make a PR. It means a lot to us. +### Локальная сборка фронта с собственным API-префиксом + +```bash +cd app/dashboard +VITE_BASE_API=/api/ npm ci +VITE_BASE_API=/api/ npm run build -- --outDir build --assetsDir statics +cp build/index.html build/404.html +``` + +Где `VITE_BASE_API` — базовый префикс для всех API‑запросов фронта (в продакшене `/api/`). diff --git a/app/dashboard/build/404.html b/app/dashboard/build/404.html index 8f45a83ad..36f44c1c5 100644 --- a/app/dashboard/build/404.html +++ b/app/dashboard/build/404.html @@ -34,8 +34,8 @@ - - + + diff --git a/app/dashboard/build/index.html b/app/dashboard/build/index.html index 8f45a83ad..36f44c1c5 100644 --- a/app/dashboard/build/index.html +++ b/app/dashboard/build/index.html @@ -34,8 +34,8 @@ - - + + diff --git a/app/dashboard/build/statics/add_file.2cd9a851.svg b/app/dashboard/build/statics/add_file.4f1404b6.svg similarity index 100% rename from app/dashboard/build/statics/add_file.2cd9a851.svg rename to app/dashboard/build/statics/add_file.4f1404b6.svg diff --git a/app/dashboard/build/statics/index.4535663a.js b/app/dashboard/build/statics/index.4535663a.js new file mode 100644 index 000000000..efbed9b2b --- /dev/null +++ b/app/dashboard/build/statics/index.4535663a.js @@ -0,0 +1,14 @@ +import{i as Bt,B as yn,a as Sn,b as wn,j as Fr,d as $,U as Qt,z as Cn,r as _n,f as kn,Q as In,e as vn,$ as Dn,c as Lt,g as w,h as zn,C as Un,k as At,u as Tt,l as H,m as r,H as k,n as e,T as d,o as En,p as v,s as Rn,q as g,t as Qe,J as Ln,v as y,w as Wr,A as Mt,x as An,y as Tn,M as de,D as he,E as ue,F as pe,G as me,I as we,K as qe,L as Or,N as Mn,O as mt,P as ge,R as L,S as j,V as Hr,W as re,X as R,Y as ye,Z as V,_ as Ne,a0 as Pe,a1 as F,a2 as bt,a3 as ct,a4 as Nn,a5 as Te,a6 as He,a7 as Pn,a8 as jr,a9 as Br,aa as pt,ab as It,ac as Fn,ad as $e,ae as vt,af as ur,ag as Wn,ah as $r,ai as Vr,aj as Gr,ak as Se,al as On,am as Hn,an as jn,ao as Bn,ap as $n,aq as qt,ar as Yr,as as Zr,at as ie,au as pr,av as Vn,aw as Gn,ax as Yn,ay as $t,az as Zn,aA as Qn,aB as qn,aC as Xn,aD as Jn,aE as Kn,aF as Dt,aG as eo,aH as to,aI as ro,aJ as no,aK as oo,aL as xt,aM as Qr,aN as yt,aO as P,aP as Xt,aQ as so,aR as Ge,aS as Ye,aT as Vt,aU as Ze,aV as ao,aW as Ie,aX as ve,aY as De,aZ as ze,a_ as Ue,a$ as Ee,b0 as mr,b1 as io,b2 as zt,b3 as Ve,b4 as Jt,b5 as lo,b6 as co,b7 as ho,b8 as qr,b9 as uo,ba as gt,bb as Ut,bc as Xr,bd as po,be as mo,bf as Jr,bg as We,bh as go,bi as fo,bj as bo,bk as Kt,bl as Pt,bm as gr,bn as Kr,bo as xo,bp as yo,bq as fr,br as So,bs as br,bt as en,bu as wo,bv as tn,bw as Co,bx as _o,by as rn,bz as ko,bA as Io,bB as nn,bC as on,bD as sn,bE as q,bF as vo,bG as an,bH as Ft,bI as Do,bJ as zo,bK as Uo,bL as Eo,bM as Ro,bN as Lo,bO as ln,bP as Ao,bQ as xr,bR as yr,bS as Be,bT as Le,bU as Sr,bV as xe,bW as wr,bX as To,bY as Mo,bZ as No,b_ as Po,b$ as Fo,c0 as Wo,c1 as Oo,c2 as Ho,c3 as jo,c4 as Bo,c5 as $o,c6 as Vo,c7 as Go,c8 as Yo,c9 as Zo,ca as Qo,cb as qo}from"./vendor.e36f197f.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function o(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerpolicy&&(i.referrerPolicy=a.referrerpolicy),a.crossorigin==="use-credentials"?i.credentials="include":a.crossorigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(a){if(a.ep)return;a.ep=!0;const i=o(a);fetch(a.href,i)}})();Bt.use(yn).use(Sn).use(wn).init({debug:{}.NODE_ENV==="development",returnNull:!1,fallbackLng:"en",interpolation:{escapeValue:!1},react:{useSuspense:!1},load:"languageOnly",detection:{caches:["localStorage","sessionStorage","cookie"]},backend:{loadPath:Fr(["/","statics/locales/{{lng}}.json"])}},function(t,n){$.locale(Bt.language)});Bt.on("languageChanged",t=>{$.locale(t)});Qt("zh-cn",Cn);Qt("ru",_n);Qt("fa",kn);const Gt=new In,cn=t=>{const n=document.querySelector('meta[name="theme-color"]');n==null||n.setAttribute("content",t=="dark"?"#1A202C":"#3B81F6")},Xo=vn({shadows:{outline:"0 0 0 2px var(--chakra-colors-primary-200)"},fonts:{body:"Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif"},colors:{"light-border":"#d2d2d4",primary:{50:"#9cb7f2",100:"#88a9ef",200:"#749aec",300:"#618ce9",400:"#4d7de7",500:"#396fe4",600:"#3364cd",700:"#2e59b6",800:"#284ea0",900:"#224389"},gray:{750:"#222C3B"}},components:{Alert:{baseStyle:{container:{borderRadius:"6px",fontSize:"sm"}}},Select:{baseStyle:{field:{_dark:{borderColor:"gray.600",borderRadius:"6px"},_light:{borderRadius:"6px"}}}},FormHelperText:{baseStyle:{fontSize:"xs"}},FormLabel:{baseStyle:{fontSize:"sm",fontWeight:"medium",mb:"1",_dark:{color:"gray.300"}}},Input:{baseStyle:{addon:{_dark:{borderColor:"gray.600",_placeholder:{color:"gray.500"}}},field:{_focusVisible:{boxShadow:"none",borderColor:"primary.200",outlineColor:"primary.200"},_dark:{borderColor:"gray.600",_disabled:{color:"gray.400",borderColor:"gray.500"},_placeholder:{color:"gray.500"}}}}},Table:{baseStyle:{table:{borderCollapse:"separate",borderSpacing:0},thead:{borderBottomColor:"light-border"},th:{background:"#F9FAFB",borderColor:"light-border !important",borderBottomColor:"light-border !important",borderTop:"1px solid ",borderTopColor:"light-border !important",_first:{borderLeft:"1px solid",borderColor:"light-border !important"},_last:{borderRight:"1px solid",borderColor:"light-border !important"},_dark:{borderColor:"gray.600 !important",background:"gray.750"}},td:{transition:"all .1s ease-out",borderColor:"light-border",borderBottomColor:"light-border !important",_first:{borderLeft:"1px solid",borderColor:"light-border",_dark:{borderColor:"gray.600"}},_last:{borderRight:"1px solid",borderColor:"light-border",_dark:{borderColor:"gray.600"}},_dark:{borderColor:"gray.600",borderBottomColor:"gray.600 !important"}},tr:{"&.interactive":{cursor:"pointer",_hover:{"& > td":{bg:"gray.200"},_dark:{"& > td":{bg:"gray.750"}}}},_last:{"& > td":{_first:{borderBottomLeftRadius:"8px"},_last:{borderBottomRightRadius:"8px"}}}}}}}});const Et=()=>localStorage.getItem("token"),Jo=t=>{localStorage.setItem("token",t)},Ko=()=>{localStorage.removeItem("token")},es=Dn.create({baseURL:"/api/"}),ts=(t,n={})=>(Et()&&(n.headers={...(n==null?void 0:n.headers)||{},Authorization:`Bearer ${Et()}`}),es(t,n)),O=ts,rs=Lt(t=>({isLoading:!0,isPostLoading:!1,version:null,started:!1,logs_websocket:null,config:"",fetchCoreSettings:()=>{t({isLoading:!0}),Promise.all([O("/core").then(({version:n,started:o,logs_websocket:s})=>t({version:n,started:o,logs_websocket:s})),O("/core/config").then(n=>t({config:n}))]).finally(()=>t({isLoading:!1}))},updateConfig:n=>(t({isPostLoading:!0}),O("/core/config",{method:"PUT",body:n}).finally(()=>{t({isPostLoading:!1})})),restartCore:()=>O("/core/restart",{method:"POST"})}));function ae(t,n=2,o=!1){if(!+t)return"0 B";const s=1024,a=n<0?0:n,i=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],l=Math.floor(Math.log(t)/Math.log(s));return o?[parseFloat((t/Math.pow(s,l)).toFixed(a)),i[l]]:`${parseFloat((t/Math.pow(s,l)).toFixed(a))} ${i[l]}`}const Cr=t=>{if(t!==null)return t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")},ns=w(zn,{baseStyle:{w:5,h:5,position:"relative",zIndex:"2"}}),os=w(Un,{baseStyle:{w:5,h:5,position:"relative",zIndex:"2"}}),ss=w(At,{baseStyle:{w:5,h:5,position:"relative",zIndex:"2"}}),Wt=({title:t,content:n,icon:o})=>r(En,{p:6,borderWidth:"1px",borderColor:"light-border",bg:"#F9FAFB",_dark:{borderColor:"gray.600",bg:"gray.750"},borderStyle:"solid",boxShadow:"none",borderRadius:"12px",width:"full",display:"flex",justifyContent:"space-between",flexDirection:"row",children:[r(k,{alignItems:"center",columnGap:"4",children:[e(v,{p:"2",position:"relative",color:"white",_before:{content:'""',position:"absolute",top:0,left:0,bg:"primary.400",display:"block",w:"full",h:"full",borderRadius:"5px",opacity:".5",z:"1"},_after:{content:'""',position:"absolute",top:"-5px",left:"-5px",bg:"primary.400",display:"block",w:"calc(100% + 10px)",h:"calc(100% + 10px)",borderRadius:"8px",opacity:".4",z:"1"},children:o}),e(d,{color:"gray.600",_dark:{color:"gray.300"},fontWeight:"medium",textTransform:"capitalize",fontSize:"sm",children:t})]}),e(v,{fontSize:"3xl",fontWeight:"semibold",mt:"2",children:n})]}),Yt="statistics-query-key",as=t=>{const{version:n}=z(),{data:o}=Tt({queryKey:Yt,queryFn:()=>O("/system"),refetchInterval:5e3,onSuccess:({version:a})=>{n!==a&&z.setState({version:a})}}),{t:s}=H();return r(k,{justifyContent:"space-between",gap:0,columnGap:{lg:4,md:0},rowGap:{lg:0,base:4},display:"flex",flexDirection:{lg:"row",base:"column"},...t,children:[e(Wt,{title:s("activeUsers"),content:o&&r(k,{alignItems:"flex-end",children:[e(d,{children:Cr(o.users_active)}),r(d,{fontWeight:"normal",fontSize:"lg",as:"span",display:"inline-block",pb:"5px",children:["/ ",Cr(o.total_user)]})]}),icon:e(ns,{})}),e(Wt,{title:s("dataUsage"),content:o&&ae(o.incoming_bandwidth+o.outgoing_bandwidth),icon:e(os,{})}),e(Wt,{title:s("memoryUsage"),content:o&&r(k,{alignItems:"flex-end",children:[e(d,{children:ae(o.mem_used,1,!0)[0]}),r(d,{fontWeight:"normal",fontSize:"lg",as:"span",display:"inline-block",pb:"5px",children:[ae(o.mem_used,1,!0)[1]," /"," ",ae(o.mem_total,1)]})]}),icon:e(ss,{})})]})},dn="marzban-num-users-per-page",_r=10,is=()=>{const t=localStorage.getItem(dn)||_r.toString();return parseInt(t)||_r},ls=t=>localStorage.setItem(dn,t),cs=t=>{for(const n in t)t[n]||delete t[n];return z.setState({loading:!0}),O("/users",{query:t}).then(n=>(z.setState({users:n}),n)).finally(()=>{z.setState({loading:!1})})},ds=()=>O("/inbounds").then(t=>{z.setState({inbounds:new Map(Object.entries(t))})}).finally(()=>{z.setState({loading:!1})}),z=Lt(Rn((t,n)=>({version:null,editingUser:null,deletingUser:null,isCreatingNewUser:!1,QRcodeLinks:null,subscribeUrl:null,users:{users:[],total:0},loading:!0,isResetingAllUsage:!1,isEditingHosts:!1,isEditingNodes:!1,isShowingNodesUsage:!1,resetUsageUser:null,revokeSubscriptionUser:null,filters:{username:"",limit:is(),sort:"-created_at"},inbounds:new Map,isEditingCore:!1,refetchUsers:()=>{cs(n().filters)},resetAllUsage:()=>O("/users/reset",{method:"POST"}).then(()=>{n().onResetAllUsage(!1),n().refetchUsers()}),onResetAllUsage:o=>t({isResetingAllUsage:o}),onCreateUser:o=>t({isCreatingNewUser:o}),onEditingUser:o=>{t({editingUser:o})},onDeletingUser:o=>{t({deletingUser:o})},onFilterChange:o=>{t({filters:{...n().filters,...o}}),n().refetchUsers()},setQRCode:o=>{t({QRcodeLinks:o})},deleteUser:o=>(t({editingUser:null}),O(`/user/${o.username}`,{method:"DELETE"}).then(()=>{t({deletingUser:null}),n().refetchUsers(),Gt.invalidateQueries(Yt)})),createUser:o=>O("/user",{method:"POST",body:o}).then(()=>{t({editingUser:null}),n().refetchUsers(),Gt.invalidateQueries(Yt)}),editUser:o=>O(`/user/${o.username}`,{method:"PUT",body:o}).then(()=>{n().onEditingUser(null),n().refetchUsers()}),fetchUserUsage:(o,s)=>{for(const a in s)s[a]||delete s[a];return O(`/user/${o.username}/usage`,{method:"GET",query:s})},onEditingHosts:o=>{t({isEditingHosts:o})},onEditingNodes:o=>{t({isEditingNodes:o})},onShowingNodesUsage:o=>{t({isShowingNodesUsage:o})},setSubLink:o=>{t({subscribeUrl:o})},resetDataUsage:o=>O(`/user/${o.username}/reset`,{method:"POST"}).then(()=>{t({resetUsageUser:null}),n().refetchUsers()}),revokeSubscription:o=>O(`/user/${o.username}/revoke_sub`,{method:"POST"}).then(s=>{t({revokeSubscriptionUser:null,editingUser:s}),n().refetchUsers()})}))),fe=({children:t,color:n})=>e(v,{position:"relative",width:"36px",height:"36px",display:"flex",justifyContent:"center",alignItems:"center",_before:{content:'""',display:"block",position:"absolute",top:"0",left:"0",width:"calc(100%)",height:"calc(100%)",bg:`${n}.400`,opacity:".5",borderRadius:"5px",zIndex:"1",_dark:{bg:`${n}.400`}},_after:{content:'""',display:"block",position:"absolute",top:"0",left:"0",width:"calc(100% + 10px)",height:"calc(100% + 10px)",transform:"translate(-5px, -5px)",bg:`${n}.400`,opacity:".4",borderRadius:"8px",zIndex:"1",_dark:{bg:`${n}.400`}},children:e(d,{color:`${n}.500`,_dark:{color:`${n}.900`},position:"relative",zIndex:"2",children:t})});window.ace.define("ace/theme/nord_dark",["require","exports","module","ace/lib/dom"],(t,n,o)=>{n.isDark=!0,n.cssClass="ace-nord-dark",t("../lib/dom").importCssString(n.cssText,n.cssClass)});window.ace.define("ace/theme/dawn",["require","exports","module","ace/lib/dom"],(t,n,o)=>{n.isDark=!1,n.cssClass="ace-dawn",t("../lib/dom").importCssString(n.cssText,n.cssClass)});const hs=g.exports.forwardRef(({json:t,onChange:n,mode:o="code"},s)=>{const{colorMode:a}=Qe(),i={mode:o,onChangeText:n,statusBar:!1,mainMenuBar:!1,theme:a==="dark"?"ace/theme/nord_dark":"ace/theme/dawn"},l=g.exports.useRef(null),m=g.exports.useRef(null);return g.exports.useEffect(()=>(m.current=new Ln(l.current,i),()=>{m.current&&m.current.destroy()}),[]),g.exports.useEffect(()=>{m.current&&m.current.update(t)},[t]),e(v,{ref:s,border:"1px solid",borderColor:"gray.300",_dark:{borderColor:"gray.500"},borderRadius:5,h:"full",children:e(v,{height:"full",ref:l})})}),hn=y.object({name:y.string().min(1),address:y.string().min(1),port:y.number().min(1).or(y.string().transform(t=>parseFloat(t))),api_port:y.number().min(1).or(y.string().transform(t=>parseFloat(t))),xray_version:y.string().nullable().optional(),id:y.number().nullable().optional(),status:y.enum(["connected","connecting","error","disabled"]).nullable().optional(),message:y.string().nullable().optional(),add_as_new_host:y.boolean().optional(),usage_coefficient:y.number().or(y.string().transform(t=>parseFloat(t)))}),us=()=>({name:"",address:"",port:62050,api_port:62051,xray_version:"",usage_coefficient:1}),ft="fetch-nodes-query-key",un=()=>{const{isEditingNodes:t}=z();return Tt({queryKey:ft,queryFn:St.getState().fetchNodes,refetchInterval:t?3e3:void 0,refetchOnWindowFocus:!1})},St=Lt((t,n)=>({nodes:[],addNode(o){return O("/node",{method:"POST",body:o})},fetchNodes(){return O("/nodes")},fetchNodesUsage(o){return O("/nodes/usage",{query:o})},updateNode(o){return O(`/node/${o.id}`,{method:"PUT",body:o})},setDeletingNode(o){t({deletingNode:o})},reconnectNode(o){return O(`/node/${o.id}/reconnect`,{method:"POST"})},deleteNode:()=>{var o;return O(`/node/${(o=n().deletingNode)==null?void 0:o.id}`,{method:"DELETE"})}})),kr=500,ps=w(Wr,{baseStyle:{w:5,h:5}}),ms=w(Mt,{baseStyle:{w:4,h:4}}),gs=w(An,{baseStyle:{w:4,h:4}}),fs=w(Tn,{baseStyle:{w:3,h:3}}),bs=t=>({[ct.ReadyState.CONNECTING]:"connecting",[ct.ReadyState.OPEN]:"connected",[ct.ReadyState.CLOSING]:"closed",[ct.ReadyState.CLOSED]:"closed",[ct.ReadyState.UNINSTANTIATED]:"closed"})[t],xs=t=>{try{let n=new URL("/api/".startsWith("/")?window.location.origin+"/api/":"/api/");return(n.protocol==="https:"?"wss://":"ws://")+Fr([n.host+n.pathname,t?`/node/${t}/logs`:"/core/logs"])+"?interval=1&token="+Et()}catch(n){return console.error("Unable to generate websocket url"),console.error(n),null}};let Fe=[];const ys=()=>{const{colorMode:t}=Qe(),{data:n}=un(),o=!1,[s,a]=g.exports.useState(""),i=(T,K)=>{T!==s&&(T==="host"?(a(""),A([])):(a(T),A([])))},{isEditingCore:l}=z(),{fetchCoreSettings:m,updateConfig:f,isLoading:x,config:b,isPostLoading:C,version:u,restartCore:h}=rs(),_=g.exports.useRef(null),[S,A]=g.exports.useState([]),{t:p}=H(),c=we(),E=qe({defaultValues:{config:b||{}}});g.exports.useEffect(()=>{b&&E.setValue("config",b)},[b]),g.exports.useEffect(()=>{l&&m()},[l]);const B=g.exports.useRef(!0),D=g.exports.useCallback(Or(T=>{var le,J,_e;const K=Math.abs((((le=_.current)==null?void 0:le.scrollTop)||0)-(((J=_.current)==null?void 0:J.scrollHeight)||0)+(((_e=_.current)==null?void 0:_e.offsetHeight)||0))<10;_.current&&K?B.current=!0:B.current=!1,T.length<40&&A(T)},300),[]),{readyState:N}=Mn(xs(s),{onMessage:T=>{Fe.push(T.data),Fe.length>kr&&(Fe=Fe.splice(0,Fe.length-kr)),D([...Fe])},shouldReconnect:()=>!0,reconnectAttempts:10,reconnectInterval:1e3});g.exports.useEffect(()=>{var T;_.current&&B.current&&(_.current.scrollTop=(T=_.current)==null?void 0:T.scrollHeight)},[S]),g.exports.useEffect(()=>()=>{Fe=[]},[]);const Y=bs(N.toString()),{mutate:Z,isLoading:Q}=mt(h),ne=({config:T})=>{f(T).then(()=>{c({title:p("core.successMessage"),status:"success",isClosable:!0,position:"top",duration:3e3})}).catch(K=>{let le=p("core.generalErrorMessage");typeof K.response._data.detail=="object"&&(le=K.response._data.detail[Object.keys(K.response._data.detail)[0]]),typeof K.response._data.detail=="string"&&(le=K.response._data.detail),c({title:le,status:"error",isClosable:!0,position:"top",duration:3e3})})},oe=g.exports.useRef(null),[U,W]=g.exports.useState(!1),X=()=>{var T;document.fullscreenElement?(document.exitFullscreen(),W(!1)):((T=oe.current)==null||T.requestFullscreen(),W(!0))};return r("form",{onSubmit:E.handleSubmit(ne),children:[r(ge,{children:[r(L,{children:[r(k,{justifyContent:"space-between",alignItems:"flex-start",children:[r(j,{children:[p("core.configuration")," ",x&&e(Hr,{isIndeterminate:!0,size:"15px"})]}),e(k,{gap:0,children:e(re,{label:"Xray Version",placement:"top",children:e(R,{height:"100%",textTransform:"lowercase",children:u&&`v${u}`})})})]}),r(v,{position:"relative",ref:oe,minHeight:"300px",children:[e(ye,{control:E.control,name:"config",render:({field:T})=>e(hs,{json:b,onChange:T.onChange})}),e(V,{size:"xs","aria-label":"full screen",variant:"ghost",position:"absolute",top:"2",right:"4",onClick:X,children:U?e(fs,{}):e(gs,{})})]})]}),r(L,{mt:"4",children:[r(k,{justifyContent:"space-between",style:{paddingBottom:"1rem"},children:[r(k,{children:[(n==null?void 0:n[0])&&r(Ne,{size:"sm",style:{width:"auto"},disabled:o,bg:"transparent",_dark:{bg:"transparent"},sx:{option:{backgroundColor:t==="dark"?"#222C3B":"white"}},onChange:T=>i(T.currentTarget.value,T.currentTarget.selectedOptions[0].text),children:[e("option",{value:"host",defaultChecked:!0,children:"Master"},"host"),n&&n.map(T=>e("option",{value:String(T.id),children:p(T.name)},T.address))]}),e(j,{className:"w-au",children:p("core.logs")})]}),e(d,{as:j,children:p(`core.socket.${Y}`)})]}),e(v,{border:"1px solid",borderColor:"gray.300",bg:"#F9F9F9",_dark:{borderColor:"gray.500",bg:"#2e3440"},borderRadius:5,minHeight:"200px",maxHeight:"250px",p:2,overflowY:"auto",ref:_,children:S.map((T,K)=>e(d,{fontSize:"xs",opacity:.8,whiteSpace:"pre-line",children:T},K))})]})]}),e(Pe,{children:r(k,{w:"full",justifyContent:"space-between",children:[e(k,{children:e(v,{children:e(F,{size:"sm",leftIcon:e(ms,{className:bt({"animate-spin":Q})}),onClick:()=>Z(),children:p(Q?"core.restarting":"core.restartCore")})})}),e(k,{children:e(F,{size:"sm",variant:"solid",colorScheme:"primary",px:"5",type:"submit",isDisabled:x||C,isLoading:C,children:p("core.save")})})]})})]})},Ss=()=>{const{isEditingCore:t}=z(),n=z.setState.bind(null,{isEditingCore:!1}),{t:o}=H();return r(de,{isOpen:t,onClose:n,size:"3xl",children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",w:"full",children:[e(pe,{pt:6,children:r(k,{gap:2,children:[e(fe,{color:"primary",children:e(ps,{color:"white"})}),e(d,{fontWeight:"semibold",fontSize:"lg",children:o("core.title")})]})}),e(me,{mt:3}),e(ys,{})]})]})},wt=w(Nn,{baseStyle:{w:5,h:5}}),ws=()=>{const[t,n]=g.exports.useState(!1),{deletingUser:o,onDeletingUser:s,deleteUser:a}=z(),{t:i}=H(),l=we(),m=()=>{s(null)},f=()=>{o&&(n(!0),a(o).then(()=>{l({title:i("deleteUser.deleteSuccess",{username:o.username}),status:"success",isClosable:!0,position:"top",duration:3e3})}).then(m).finally(n.bind(null,!1)))};return r(de,{isCentered:!0,isOpen:!!o,onClose:m,size:"sm",children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",children:[e(pe,{pt:6,children:e(fe,{color:"red",children:e(wt,{})})}),e(me,{mt:3}),r(ge,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:i("deleteUser.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:e(Te,{components:{b:e("b",{})},children:i("deleteUser.prompt",{username:o.username})})})]}),r(Pe,{display:"flex",children:[e(F,{size:"sm",onClick:m,mr:3,w:"full",variant:"outline",children:i("cancel")}),e(F,{size:"sm",w:"full",colorScheme:"red",onClick:f,leftIcon:t?e(He,{size:"xs"}):void 0,children:i("delete")})]})]})]})},er={baseStyle:{w:4,h:4}},Cs=w(Pn,er),_s=w(jr,er),tr=w(Mt,er),ks=Or(t=>{z.getState().onFilterChange({...z.getState().filters,offset:0,search:t})},300),Is=({...t})=>{const{loading:n,filters:o,onFilterChange:s,refetchUsers:a,onCreateUser:i}=z(),{t:l}=H(),[m,f]=g.exports.useState(""),x=C=>{f(C.target.value),ks(C.target.value)},b=()=>{f(""),s({...o,offset:0,search:""})};return r(Br,{id:"filters",templateColumns:{lg:"repeat(3, 1fr)",md:"repeat(4, 1fr)",base:"repeat(1, 1fr)"},position:"sticky",top:0,mx:"-6",px:"6",rowGap:4,gap:{lg:4,base:0},bg:"var(--chakra-colors-chakra-body-bg)",py:4,zIndex:"docked",...t,children:[e(pt,{colSpan:{base:1,md:2,lg:1},order:{base:2,md:1},children:r(It,{children:[e(Fn,{pointerEvents:"none",children:e(Cs,{})}),e($e,{placeholder:l("search"),value:m,borderColor:"light-border",onChange:x}),r(vt,{children:[n&&e(He,{size:"xs"}),o.search&&o.search.length>0&&e(V,{onClick:b,"aria-label":"clear",size:"xs",variant:"ghost",children:e(_s,{})})]})]})}),e(pt,{colSpan:2,order:{base:1,md:2},children:r(k,{justifyContent:"flex-end",alignItems:"center",h:"full",children:[e(V,{"aria-label":"refresh users",disabled:n,onClick:a,size:"sm",variant:"outline",children:e(tr,{className:bt({"animate-spin":n})})}),e(F,{colorScheme:"primary",size:"sm",onClick:()=>i(!0),px:5,children:l("createUser")})]})})]})},pn="https://github.com/Gozargah/Marzban",vs="https://github.com/Gozargah",Ds="https://github.com/Gozargah/Marzban#donation",mn=t=>{const{version:n}=z();return e(k,{w:"full",py:"0",position:"relative",...t,children:r(d,{display:"inline-block",flexGrow:1,textAlign:"center",color:"gray.500",fontSize:"xs",children:[e(ur,{color:"blue.400",href:pn,children:"Marzban"}),n?` (v${n}), `:", ","Made with \u2764\uFE0F in"," ",e(ur,{color:"blue.400",href:vs,children:"Gozargah"})]})})},zs=w(Wn,{baseStyle:{w:4,h:4}}),gn=({actions:t})=>{const{i18n:n}=H();var o=s=>{n.changeLanguage(s)};return r($r,{placement:"bottom-end",children:[e(Vr,{as:V,size:"sm",variant:"outline",icon:e(zs,{}),position:"relative"}),r(Gr,{minW:"100px",zIndex:9999,children:[e(Se,{maxW:"100px",fontSize:"sm",onClick:()=>o("en"),children:"English"}),e(Se,{maxW:"100px",fontSize:"sm",onClick:()=>o("fa"),children:"\u0641\u0627\u0631\u0633\u06CC"}),e(Se,{maxW:"100px",fontSize:"sm",onClick:()=>o("zh-cn"),children:"\u7B80\u4F53\u4E2D\u6587"}),e(Se,{maxW:"100px",fontSize:"sm",onClick:()=>o("ru"),children:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"})]})]})},Us=async()=>await O("/admin"),Es=()=>{const{data:t,isError:n,isLoading:o,isSuccess:s,error:a}=Tt({queryFn:()=>Us()});return{userData:t||{discord_webook:"",is_sudo:!1,telegram_id:"",username:""},getUserIsPending:o,getUserIsSuccess:s,getUserIsError:n,getUserError:a}},Ce={baseStyle:{w:4,h:4}},Rs=w(On,Ce),Ls=w(Hn,Ce),As=w(Wr,Ce),Ts=w(jn,Ce),Ms=w(Bn,Ce),Ns=w($n,Ce),Ps=w(qt,Ce),Fs=w(Yr,Ce),Ws=w(At,Ce),Os=w(Zr,Ce),Ir=w(v,{baseStyle:{bg:"yellow.500",w:"2",h:"2",rounded:"full",position:"absolute"}}),fn="marzban-menu-notification",Hs=()=>{const t=localStorage.getItem(fn);if(!t)return!0;try{return t&&Gn(parseInt(t))?Yn(new Date,new Date(parseInt(t)))>=7:!0}catch{return!0}},js=({actions:t})=>{const{userData:n,getUserIsSuccess:o,getUserIsPending:s}=Es(),a=()=>!s&&o?n.is_sudo:!1,{onEditingHosts:i,onResetAllUsage:l,onEditingNodes:m,onShowingNodesUsage:f}=z(),{t:x}=H(),{colorMode:b,toggleColorMode:C}=Qe(),[u,h]=g.exports.useState(Hs()),_=b==="dark"?"dark_dimmed":b,S=()=>{localStorage.setItem(fn,new Date().getTime().toString()),h(!1)};return r(k,{gap:2,justifyContent:"space-between",__css:{"& .menuList":{direction:"ltr"}},position:"relative",children:[e(d,{as:"h1",fontWeight:"semibold",fontSize:"2xl",children:x("users")}),u&&e(Ir,{top:"0",right:"0",zIndex:9999}),e(v,{overflow:"auto",css:{direction:"rtl"},children:r(k,{alignItems:"center",children:[r($r,{children:[e(Vr,{as:V,size:"sm",variant:"outline",icon:e(ie,{children:e(Ts,{})}),position:"relative"}),r(Gr,{minW:"170px",zIndex:99999,className:"menuList",children:[a()&&r(ie,{children:[e(Se,{maxW:"170px",fontSize:"sm",icon:e(Ps,{}),onClick:i.bind(null,!0),children:x("header.hostSettings")}),e(Se,{maxW:"170px",fontSize:"sm",icon:e(Fs,{}),onClick:m.bind(null,!0),children:x("header.nodeSettings")}),e(Se,{maxW:"170px",fontSize:"sm",icon:e(Ws,{}),onClick:f.bind(null,!0),children:x("header.nodesUsage")}),e(Se,{maxW:"170px",fontSize:"sm",icon:e(Os,{}),onClick:l.bind(null,!0),children:x("resetAllUsage")})]}),e(pr,{to:Ds,target:"_blank",children:r(Se,{maxW:"170px",fontSize:"sm",icon:e(Ns,{}),position:"relative",onClick:S,children:[x("header.donation")," ",u&&e(Ir,{top:"3",right:"2"})]})}),e(pr,{to:"/login",children:e(Se,{maxW:"170px",fontSize:"sm",icon:e(Ms,{}),children:x("header.logout")})})]})]}),a()&&e(V,{size:"sm",variant:"outline","aria-label":"core settings",onClick:()=>{z.setState({isEditingCore:!0})},children:e(As,{})}),e(gn,{}),e(V,{size:"sm",variant:"outline","aria-label":"switch theme",onClick:()=>{cn(b=="dark"?"light":"dark"),C()},children:b==="light"?e(Rs,{}):e(Ls,{})}),e(v,{css:{direction:"ltr"},display:"flex",alignItems:"center",pr:"2",__css:{"& span":{display:"inline-flex"}},children:e(Vn,{href:pn,"data-color-scheme":`no-preference: ${_}; light: ${_}; dark: ${_};`,"data-size":"large","data-show-count":"true","aria-label":"Star Marzban on GitHub",children:"Star"})})]})})]})},Bs=[{title:"Inbound's default",value:"inbound_default"},{title:"TLS",value:"tls"},{title:"None",value:"none"}],$s=[{title:"",value:""},{title:"h3",value:"h3"},{title:"h2",value:"h2"},{title:"http/1.1",value:"http/1.1"},{title:"h3,h2,http/1.1",value:"h3,h2,http/1.1"},{title:"h3,h2",value:"h3,h2"},{title:"h2,http/1.1",value:"h2,http/1.1"}],Vs=[{title:"",value:""},...["chrome","firefox","safari","ios","android","edge","360","qq","random","randomized"].map(t=>({title:t,value:t}))],Gs=[{title:"none",value:""},{title:"xtls-rprx-vision",value:"xtls-rprx-vision"}],Ys=["2022-blake3-aes-256-gcm","2022-blake3-aes-128-gcm","2022-blake3-chacha20-poly1305","aes-128-gcm","aes-256-gcm","chacha20-ietf-poly1305"],Zs=Lt(t=>({isLoading:!1,isPostLoading:!1,hosts:{},fetchHosts:()=>{t({isLoading:!0}),O("/hosts").then(n=>t({hosts:n})).finally(()=>t({isLoading:!1}))},setHosts:n=>(t({isPostLoading:!0}),O("/hosts",{method:"PUT",body:n}).finally(()=>{t({isPostLoading:!1})}))}));const Qs=w(jr,{baseStyle:{w:4,h:4}}),Me=$t.forwardRef(({disabled:t,step:n,label:o,className:s,startAdornment:a,endAdornment:i,type:l="text",placeholder:m,onChange:f,onBlur:x,name:b,value:C,onClick:u,error:h,clearable:_=!1,...S},A)=>{const p=()=>{f&&f({target:{value:"",name:b}})},{size:c="md"}=S,E=l=="number"?eo:$e,B=l=="number"?Zn:$t.Fragment,D=l=="number"?{keepWithinRange:!0,precision:5,format:N=>isNaN(parseFloat(String(N)))||Number(parseFloat(String(N)).toFixed(5))===0?N:Number(parseFloat(String(N)).toFixed(5)),min:0,step:n,name:b,type:l,placeholder:m,onChange:N=>{f&&f(N)},onBlur:x,value:C,onClick:u,disabled:t,flexGrow:1,size:c}:{};return r(L,{isInvalid:!!h,children:[o&&e(j,{children:o}),r(It,{size:c,w:"full",rounded:"md",_focusWithin:{outline:"2px solid",outlineColor:"primary.200"},bg:t?"gray.100":"transparent",_dark:{bg:t?"gray.600":"transparent"},children:[a&&e(Qn,{children:a}),r(B,{...D,children:[e(E,{name:b,ref:A,step:n,className:bt(s),type:l,placeholder:m,onChange:f,onBlur:x,value:C,onClick:u,disabled:t,flexGrow:1,_focusVisible:{outline:"none",borderTopColor:"transparent",borderRightColor:"transparent",borderBottomColor:"transparent"},_disabled:{cursor:"not-allowed"},...S,roundedLeft:a?"0":"md",roundedRight:i?"0":"md"}),l=="number"&&e(ie,{children:r(qn,{children:[e(Xn,{}),e(Jn,{})]})})]}),i&&e(Kn,{borderLeftRadius:0,borderRightRadius:"6px",bg:"transparent",children:i}),_&&C&&C.length&&e(vt,{borderLeftRadius:0,borderRightRadius:"6px",bg:"transparent",onClick:p,cursor:"pointer",children:e(Qs,{})})]}),!!h&&e(Dt,{children:h})]})}),qs=w(to,{baseStyle:{w:5,h:5}}),Xs=w(ro,{baseStyle:{w:5,h:5}}),Js=w(no,{baseStyle:{w:5,h:5}}),Ot=w(Ne,{baseStyle:{bg:"white",_dark:{bg:"gray.700"}}}),Ae=w(Me,{baseStyle:{bg:"white",_dark:{bg:"gray.700"}}}),Ks=w(qt,{baseStyle:{w:5,h:5}}),Re=w(oo,{baseStyle:{w:4,h:4,color:"gray.400",cursor:"pointer"}}),ea=y.record(y.string().min(1),y.array(y.object({remark:y.string().min(1,"Remark is required"),address:y.string().min(1,"Address is required"),port:y.string().or(y.number()).nullable().transform(t=>typeof t=="number"?t:t!==null&&!isNaN(parseInt(t))?Number(parseInt(t)):null),path:y.string().nullable(),sni:y.string().nullable(),host:y.string().nullable(),mux_enable:y.boolean().default(!1),allowinsecure:y.boolean().nullable().default(!1),is_disabled:y.boolean().default(!0),fragment_setting:y.string().nullable(),noise_setting:y.string().nullable(),random_user_agent:y.boolean().default(!1),security:y.string(),alpn:y.string(),fingerprint:y.string(),use_sni_as_host:y.boolean().default(!1)}))),ce=w(Dt,{baseStyle:{color:"red.400",display:"block",textAlign:"left",w:"100%"}}),ta=({hostKey:t,isOpen:n,toggleAccordion:o})=>{const{inbounds:s}=z(),a=[...s.values()].flat().filter(p=>p.tag===t)[0],i=Xt(),{fields:l,append:m,remove:f,insert:x,move:b}=so({control:i.control,name:t}),{errors:C}=i.formState,{t:u}=H(),h=C[t],_=()=>{m({host:"",sni:"",port:null,path:null,address:"",remark:"",mux_enable:!1,allowinsecure:!1,is_disabled:!1,fragment_setting:"",noise_setting:"",random_user_agent:!1,security:"inbound_default",alpn:"",fingerprint:"",use_sni_as_host:!1})},S=p=>{if(p<0||p>=l.length)return;const c=l[p];x(p+1,c)};g.exports.useEffect(()=>{h&&!n&&o()},[h]);const A=(p,c)=>{c==="up"&&p>0?b(p,p-1):c==="down"&&p{var E,B,D,N,Y,Z,Q,ne,oe,U,W,X,T,K,le,J,_e,_t,Je,kt,Ke,et,tt,rt,nt,I,M,ee,se,be,ke,G,ot,st,at,it,lt,je,or,sr,ar,ir,lr,cr,dr;return e(ao.div,{layout:!0,initial:!1,animate:{opacity:1},exit:{opacity:0},transition:{layout:{type:"spring",stiffness:500,damping:30},opacity:{duration:.1}},id:p.id,whileDrag:{scale:1.05,zIndex:10},style:{width:"100%"},children:r(P,{id:p.id,border:"1px solid",_dark:{borderColor:"gray.600",bg:"#273142"},_light:{borderColor:"gray.200",bg:"#fcfbfb"},p:2,w:"full",borderRadius:"4px",children:[e(k,{w:"100%",alignItems:"flex-start",children:r(L,{position:"relative",zIndex:10,isInvalid:!!(h&&((E=h[c])==null?void 0:E.remark)),children:[r(It,{children:[e(Ae,{...i.register(t+"."+c+".remark"),size:"sm",borderRadius:"4px",placeholder:"Remark"}),e(vt,{children:r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(v,{mt:"-8px",children:e(Re,{})})}),e(De,{children:r(ze,{children:[e(Ue,{}),e(Ee,{}),e(mr,{children:r(v,{fontSize:"xs",children:[e(d,{pr:"20px",children:u("hostsDialog.desc")}),r(d,{children:[r(R,{children:["{","SERVER_IP","}"]})," ",u("hostsDialog.currentServer")]}),r(d,{mt:1,children:[r(R,{children:["{","SERVER_IPV6","}"]})," ",u("hostsDialog.currentServerv6")]}),r(d,{mt:1,children:[r(R,{children:["{","USERNAME","}"]})," ",u("hostsDialog.username")]}),r(d,{mt:1,children:[r(R,{children:["{","DATA_USAGE","}"]})," ",u("hostsDialog.dataUsage")]}),r(d,{mt:1,children:[r(R,{children:["{","DATA_LEFT","}"]})," ",u("hostsDialog.remainingData")]}),r(d,{mt:1,children:[r(R,{children:["{","DATA_LIMIT","}"]})," ",u("hostsDialog.dataLimit")]}),r(d,{mt:1,children:[r(R,{children:["{","DAYS_LEFT","}"]})," ",u("hostsDialog.remainingDays")]}),r(d,{mt:1,children:[r(R,{children:["{","EXPIRE_DATE","}"]})," ",u("hostsDialog.expireDate")]}),r(d,{mt:1,children:[r(R,{children:["{","JALALI_EXPIRE_DATE","}"]})," ",u("hostsDialog.jalaliExpireDate")]}),r(d,{mt:1,children:[r(R,{children:["{","TIME_LEFT","}"]})," ",u("hostsDialog.remainingTime")]}),r(d,{mt:1,children:[r(R,{children:["{","STATUS_TEXT","}"]})," ",u("hostsDialog.statusText")]}),r(d,{mt:1,children:[r(R,{children:["{","STATUS_EMOJI","}"]})," ",u("hostsDialog.statusEmoji")]}),r(d,{mt:1,children:[r(R,{children:["{","PROTOCOL","}"]})," ",u("hostsDialog.proxyProtocol")]}),r(d,{mt:1,children:[r(R,{children:["{","TRANSPORT","}"]})," ",u("hostsDialog.proxyMethod")]})]})})]})})]})})]}),h&&((B=h[c])==null?void 0:B.remark)&&e(ce,{children:(N=(D=h[c])==null?void 0:D.remark)==null?void 0:N.message})]})}),r(L,{isInvalid:!!(h&&((Y=h[c])==null?void 0:Y.address)),children:[r(It,{children:[e(Ae,{size:"sm",borderRadius:"4px",placeholder:"Address (e.g. example.com)",...i.register(t+"."+c+".address")}),e(vt,{children:r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(v,{mt:"-8px",children:e(Re,{})})}),e(De,{children:r(ze,{children:[e(Ue,{}),e(Ee,{}),e(mr,{children:r(v,{fontSize:"xs",children:[e(d,{pr:"20px",children:u("hostsDialog.desc")}),r(d,{children:[r(R,{children:["{","SERVER_IP","}"]})," ",u("hostsDialog.currentServer")]}),r(d,{mt:1,children:[r(R,{children:["{","SERVER_IPV6","}"]})," ",u("hostsDialog.currentServerv6")]}),r(d,{mt:1,children:[r(R,{children:["{","USERNAME","}"]})," ",u("hostsDialog.username")]}),r(d,{mt:1,children:[r(R,{children:["{","DATA_USAGE","}"]})," ",u("hostsDialog.dataUsage")]}),r(d,{mt:1,children:[r(R,{children:["{","DATA_LEFT","}"]})," ",u("hostsDialog.remainingData")]}),r(d,{mt:1,children:[r(R,{children:["{","DATA_LIMIT","}"]})," ",u("hostsDialog.dataLimit")]}),r(d,{mt:1,children:[r(R,{children:["{","DAYS_LEFT","}"]})," ",u("hostsDialog.remainingDays")]}),r(d,{mt:1,children:[r(R,{children:["{","EXPIRE_DATE","}"]})," ",u("hostsDialog.expireDate")]}),r(d,{mt:1,children:[r(R,{children:["{","JALALI_EXPIRE_DATE","}"]})," ",u("hostsDialog.jalaliExpireDate")]}),r(d,{mt:1,children:[r(R,{children:["{","TIME_LEFT","}"]})," ",u("hostsDialog.remainingTime")]}),r(d,{mt:1,children:[r(R,{children:["{","STATUS_TEXT","}"]})," ",u("hostsDialog.statusText")]}),r(d,{mt:1,children:[r(R,{children:["{","STATUS_EMOJI","}"]})," ",u("hostsDialog.statusEmoji")]}),r(d,{mt:1,children:[r(R,{children:["{","PROTOCOL","}"]})," ",u("hostsDialog.proxyProtocol")]}),r(d,{mt:1,children:[r(R,{children:["{","TRANSPORT","}"]})," ",u("hostsDialog.proxyMethod")]})]})})]})})]})})]}),h&&((Z=h[c])==null?void 0:Z.address)&&e(ce,{children:(ne=(Q=h[c])==null?void 0:Q.address)==null?void 0:ne.message})]}),e(yt,{w:"full",allowToggle:!0,children:r(Ge,{border:"0",children:[r("div",{style:{display:"flex",alignItems:"center"},children:[r(Ye,{display:"flex",px:0,py:1,borderRadius:3,_hover:{bg:"transparent"},children:[r(d,{flex:"3",align:"start",fontSize:"xs",color:"gray.600",_dark:{color:"gray.500"},pl:1,children:[u("hostsDialog.advancedOptions"),e(Vt,{fontSize:"sm",ml:1})]}),r(io,{flex:"1",px:"0",display:"contents",children:[e(ye,{control:i.control,name:`${t}.${c}.is_disabled`,render:({field:te})=>e(zt,{mx:"1.5",colorScheme:"primary",...te,value:void 0,isChecked:!te.value,onChange:hr=>{console.log(hr.target.checked),te.onChange(!hr.target.checked)}})}),e(re,{label:"Delete",placement:"top",children:e(V,{"aria-label":"Delete",size:"sm",colorScheme:"red",variant:"ghost",onClick:f.bind(null,c),children:e(wt,{})})})]})]}),e(re,{label:"Duplicate",placement:"top",children:e(V,{"aria-label":"Duplicate",size:"sm",colorScheme:"white",variant:"ghost",onClick:()=>S(c),children:e(qs,{})})}),cA(c,"down"),children:e(Js,{})})}),c>0&&e(re,{label:"Move Up",placement:"top",children:e(V,{"aria-label":"UpIcon",size:"sm",colorScheme:"white",variant:"ghost",onClick:()=>A(c,"up"),children:e(Xs,{})})})]}),e(Ze,{w:"full",p:1,children:r(P,{w:"full",borderRadius:"4px",children:[r(L,{isInvalid:!!(h&&((oe=h[c])==null?void 0:oe.port)),children:[r(j,{display:"flex",pb:1,alignItems:"center",justifyContent:"space-between",gap:1,m:"0",children:[e("span",{children:u("hostsDialog.port")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:u("hostsDialog.port.info")})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:String(a.port||"8080"),type:"number",...i.register(t+"."+c+".port")})]}),r(L,{isInvalid:!!(h&&((U=h[c])==null?void 0:U.sni)),children:[r(j,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:u("hostsDialog.sni")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:u("hostsDialog.sni.info")}),e(d,{fontSize:"xs",mt:"2",children:e(Te,{i18nKey:"hostsDialog.host.wildcard",components:{badge:e(R,{})}})}),e(d,{fontSize:"xs",children:e(Te,{i18nKey:"hostsDialog.host.multiHost",components:{badge:e(R,{})}})})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"SNI (e.g. example.com)",...i.register(t+"."+c+".sni")}),h&&((W=h[c])==null?void 0:W.sni)&&e(ce,{children:(T=(X=h[c])==null?void 0:X.sni)==null?void 0:T.message})]}),r(L,{isInvalid:!!(h&&((K=h[c])==null?void 0:K.host)),children:[r(j,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:u("hostsDialog.host")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:u("hostsDialog.host.info")}),e(d,{fontSize:"xs",mt:"2",children:e(Te,{i18nKey:"hostsDialog.host.wildcard",components:{badge:e(R,{})}})}),e(d,{fontSize:"xs",children:e(Te,{i18nKey:"hostsDialog.host.multiHost",components:{badge:e(R,{})}})})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"Host (e.g. example.com)",...i.register(t+"."+c+".host")}),h&&((le=h[c])==null?void 0:le.host)&&e(ce,{children:(_e=(J=h[c])==null?void 0:J.host)==null?void 0:_e.message})]}),r(L,{isInvalid:!!(h&&((_t=h[c])==null?void 0:_t.path)),children:[r(j,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:u("hostsDialog.path")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:u("hostsDialog.path.info")})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"path (e.g. /vless)",...i.register(t+"."+c+".path")}),h&&((Je=h[c])==null?void 0:Je.path)&&e(ce,{children:(Ke=(kt=h[c])==null?void 0:kt.path)==null?void 0:Ke.message})]}),r(L,{height:"66px",children:[r(j,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:u("hostsDialog.security")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:u("hostsDialog.security.info")})]})})]})]}),e(Ot,{size:"sm",...i.register(t+"."+c+".security"),children:Bs.map(te=>e("option",{value:te.value,children:te.title},te.value))})]}),r(L,{height:"66px",children:[e(j,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:e("span",{children:u("hostsDialog.alpn")})}),e(Ot,{size:"sm",...i.register(t+"."+c+".alpn"),children:$s.map(te=>e("option",{value:te.value,children:te.title},te.value))})]}),r(L,{height:"66px",children:[e(j,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:e("span",{children:u("hostsDialog.fingerprint")})}),e(Ot,{size:"sm",...i.register(t+"."+c+".fingerprint"),children:Vs.map(te=>e("option",{value:te.value,children:te.title},te.value))})]}),r(L,{isInvalid:!!(h&&((et=h[c])==null?void 0:et.fragment_setting)),children:[r(j,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:u("hostsDialog.fragment")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:u("hostsDialog.fragment.info")}),e(d,{fontSize:"xs",pr:5,pt:2,pb:1,children:u("hostsDialog.fragment.info.examples")}),e(d,{fontSize:"xs",pr:5,children:"100-200,10-20,tlshello"}),e(d,{fontSize:"xs",pr:5,children:"100-200,10-20,1-3"}),e(d,{fontSize:"xs",pr:5,pt:"3",children:u("hostsDialog.fragment.info.attention")})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"Fragment settings by pattern",...i.register(t+"."+c+".fragment_setting")}),h&&((tt=h[c])==null?void 0:tt.fragment_setting)&&e(ce,{children:(nt=(rt=h[c])==null?void 0:rt.fragment_setting)==null?void 0:nt.message})]}),r(L,{isInvalid:!!(h&&((I=h[c])==null?void 0:I.noise_setting)),children:[r(j,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:u("hostsDialog.noise")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:u("hostsDialog.noise.info")}),e(d,{fontSize:"xs",pr:5,pt:2,pb:1,children:u("hostsDialog.noise.info.examples")}),e(d,{fontSize:"xs",pr:5,children:"rand:10-20,10-20"}),e(d,{fontSize:"xs",pr:5,children:"rand:10-20,10-20&base64:7nQBAAABAAAAAAAABnQtcmluZwZtc2VkZ2UDbmV0AAABAAE=,10-25"}),e(d,{fontSize:"xs",pr:5,pt:"3",children:u("hostsDialog.noise.info.attention")})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"Noise settings by pattern",...i.register(t+"."+c+".noise_setting")}),h&&((M=h[c])==null?void 0:M.noise_setting)&&e(ce,{children:(se=(ee=h[c])==null?void 0:ee.noise_setting)==null?void 0:se.message})]}),r(L,{isInvalid:!!(h&&((be=h[c])==null?void 0:be.use_sni_as_host)),children:[e(Ve,{...i.register(t+"."+c+".use_sni_as_host"),children:e(j,{children:u("hostsDialog.useSniAsHost")})}),h&&((ke=h[c])==null?void 0:ke.use_sni_as_host)&&e(ce,{children:(ot=(G=h[c])==null?void 0:G.use_sni_as_host)==null?void 0:ot.message})]}),e(L,{isInvalid:!!(h&&((st=h[c])==null?void 0:st.allowinsecure)),children:r(Ve,{...i.register(t+"."+c+".allowinsecure"),name:t+"."+c+".allowinsecure",children:[e(j,{children:u("hostsDialog.allowinsecure")}),h&&((at=h[c])==null?void 0:at.allowinsecure)&&e(ce,{children:(lt=(it=h[c])==null?void 0:it.allowinsecure)==null?void 0:lt.message})]})}),r(L,{isInvalid:!!(h&&((je=h[c])==null?void 0:je.mux_enable)),children:[e(Ve,{...i.register(t+"."+c+".mux_enable"),children:e(j,{children:u("hostsDialog.muxEnable")})}),h&&((or=h[c])==null?void 0:or.mux_enable)&&e(ce,{children:(ar=(sr=h[c])==null?void 0:sr.mux_enable)==null?void 0:ar.message})]}),r(L,{isInvalid:!!(h&&((ir=h[c])==null?void 0:ir.random_user_agent)),children:[e(Ve,{...i.register(t+"."+c+".random_user_agent"),children:e(j,{children:u("hostsDialog.randomUserAgent")})}),h&&((lr=h[c])==null?void 0:lr.random_user_agent)&&e(ce,{children:(dr=(cr=h[c])==null?void 0:cr.random_user_agent)==null?void 0:dr.message})]})]},c)})]})})]},p.id)},p.id)}),e(F,{variant:"outline",w:"full",size:"sm",color:"",fontWeight:"normal",onClick:_,children:u("hostsDialog.addHost")})]})})]})},ra=()=>{const{isEditingHosts:t,onEditingHosts:n,refetchUsers:o,inbounds:s}=z(),{isLoading:a,hosts:i,fetchHosts:l,isPostLoading:m,setHosts:f}=Zs(),x=we(),{t:b}=H(),[C,u]=g.exports.useState({});g.exports.useEffect(()=>{t&&l()},[t]);const h=qe({resolver:xt(ea)});g.exports.useEffect(()=>{i&&t&&h.reset(i)},[i]);const _=()=>{u({}),n(!1)},S=p=>{f(p).then(()=>{x({title:b("hostsDialog.savedSuccess"),status:"success",isClosable:!0,position:"top",duration:3e3}),o()}).catch(c=>{var E,B,D,N,Y;(((E=c==null?void 0:c.response)==null?void 0:E.status)===409||((B=c==null?void 0:c.response)==null?void 0:B.status)===400)&&x({title:(N=(D=c.response)==null?void 0:D._data)==null?void 0:N.detail,status:"error",isClosable:!0,position:"top",duration:3e3}),((Y=c==null?void 0:c.response)==null?void 0:Y.status)===422&&Object.keys(c.response._data.detail).forEach(Z=>{x({title:c.response._data.detail[Z]+" ("+Z+")",status:"error",isClosable:!0,position:"top",duration:3e3})})})},A=p=>{C[String(p)]?delete C[String(p)]:C[String(p)]={},u({...C})};return r(de,{isOpen:t,onClose:_,children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",w:"fit-content",maxW:"3xl",children:[e(pe,{pt:6,children:e(fe,{color:"primary",children:e(Ks,{color:"white"})})}),e(me,{mt:3}),e(ge,{w:"440px",pb:3,pt:3,children:e(Qr,{...h,children:r("form",{onSubmit:h.handleSubmit(S),children:[e(d,{mb:3,opacity:.8,fontSize:"sm",children:b("hostsDialog.title")}),a&&b("hostsDialog.loading"),!a&&i&&(Object.keys(i).length>0?e(yt,{w:"full",allowToggle:!0,allowMultiple:!0,index:Object.keys(C).map(p=>parseInt(p)),children:e(P,{w:"full",children:Object.keys(i).map((p,c)=>e(ta,{toggleAccordion:()=>A(c),isOpen:C[String(c)],hostKey:p},p))})}):"No inbound found. Please check your Xray config file."),e(k,{justifyContent:"flex-end",py:2,children:e(F,{variant:"solid",mt:"2",type:"submit",colorScheme:"primary",size:"sm",px:5,isLoading:m,disabled:m,children:b("hostsDialog.apply")})})]})})})]})]})},rr=(t,n,o)=>{if(t.response&&t.response._data){if(typeof t.response._data.detail=="string")return n({title:t.response._data.detail,status:"error",isClosable:!0,position:"top",duration:3e3});if(typeof t.response._data.detail=="object"&&o){Object.keys(t.response._data.detail).forEach(s=>o.setError(s,{message:t.response._data.detail[s]}));return}}return n({title:"Something went wrong!",status:"error",isClosable:!0,position:"top",duration:3e3})},nr=(t,n)=>n({title:t,status:"success",isClosable:!0,position:"top",duration:3e3}),na=({deleteCallback:t})=>{const{deleteNode:n,deletingNode:o,setDeletingNode:s}=St(),{t:a}=H(),i=we(),l=Jt(),m=()=>{s(null)},{isLoading:f,mutate:x}=mt(n,{onSuccess:()=>{nr(a("deleteNode.deleteSuccess",{name:o&&o.name}),i),s(null),l.invalidateQueries(ft),t&&t()},onError:b=>{rr(b,i)}});return r(de,{isCentered:!0,isOpen:!!o,onClose:m,size:"sm",children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",children:[e(pe,{pt:6,children:e(fe,{color:"red",children:e(wt,{})})}),e(me,{mt:3}),r(ge,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:a("deleteNode.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:e(Te,{components:{b:e("b",{})},children:a("deleteNode.prompt",{name:o.name})})})]}),r(Pe,{display:"flex",children:[e(F,{size:"sm",onClick:m,mr:3,w:"full",variant:"outline",children:a("cancel")}),e(F,{size:"sm",w:"full",colorScheme:"red",onClick:()=>x(),leftIcon:f?e(He,{size:"xs"}):void 0,children:a("delete")})]})]})]})},Ct={baseStyle:{strokeWidth:"2px",w:4,h:4}},vr=w(lo,Ct),oa=w(co,Ct),Dr=w(ho,Ct),zr=w(qr,Ct),sa=w(qr,Ct),Zt=[{title:"No",value:"no_reset"},{title:"Daily",value:"day"},{title:"Weekly",value:"week"},{title:"Monthly",value:"month"},{title:"Annually",value:"year"}],Oe={active:{statusColor:"green",bandWidthColor:"primary",icon:vr},connected:{statusColor:"green",bandWidthColor:"primary",icon:vr},disabled:{statusColor:"gray",bandWidthColor:"gray",icon:oa},expired:{statusColor:"orange",bandWidthColor:"orange",icon:zr},on_hold:{statusColor:"purple",bandWidthColor:"purple",icon:sa},connecting:{statusColor:"orange",bandWidthColor:"orange",icon:zr},limited:{statusColor:"red",bandWidthColor:"red",icon:Dr},error:{statusColor:"red",bandWidthColor:"red",icon:Dr}},Nt=t=>{let n={status:"",time:""};if(t){$(t*1e3).utc().isAfter($().utc())?n.status="expires":n.status="expired";const o=[],s=$.duration($(t*1e3).utc().diff($()));s.years()!=0&&o.push(Math.abs(s.years())+" year"+(Math.abs(s.years())!=1?"s":"")),s.months()!=0&&o.push(Math.abs(s.months())+" month"+(Math.abs(s.months())!=1?"s":"")),s.days()!=0&&o.push(Math.abs(s.days())+" day"+(Math.abs(s.days())!=1?"s":"")),o.length===0&&(s.hours()!=0&&o.push(Math.abs(s.hours())+" hour"+(Math.abs(s.hours())!=1?"s":"")),s.minutes()!=0&&o.push(Math.abs(s.minutes())+" min"+(Math.abs(s.minutes())!=1?"s":""))),n.time=o.join(", ")}return n},aa=({expiryDate:t,status:n,compact:o=!1,showDetail:s=!0,extraText:a})=>{const{t:i}=H(),l=Nt(t),m=Oe[n].icon;return r(ie,{children:[r(R,{colorScheme:Oe[n].statusColor,rounded:"full",display:"inline-flex",px:3,py:1,columnGap:o?1:2,alignItems:"center",children:[e(m,{w:o?3:4}),s&&r(d,{textTransform:"capitalize",fontSize:o?".7rem":".875rem",lineHeight:o?"1rem":"1.25rem",fontWeight:"medium",letterSpacing:"tighter",children:[n&&i(`nodeModal.status.${n}`),a&&`: ${a}`]})]}),s&&t&&e(d,{display:"inline-block",fontSize:"xs",fontWeight:"medium",ml:"2",color:"gray.600",_dark:{color:"gray.400"},children:i(l.status,{time:l.time})})]})},dt=w(Me,{baseStyle:{bg:"white",_dark:{bg:"gray.700"}}}),ia=w(Yr,{baseStyle:{w:5,h:5}}),la=w(uo,{baseStyle:{w:5,h:5,strokeWidth:2}}),ca=({toggleAccordion:t,node:n})=>{const{updateNode:o,reconnectNode:s,setDeletingNode:a}=St(),{t:i}=H(),l=Jt(),m=we(),f=qe({defaultValues:n,resolver:xt(hn)}),x=a.bind(null,n),{isLoading:b,mutate:C}=mt(o,{onSuccess:()=>{nr("Node updated successfully",m),l.invalidateQueries(ft)},onError:S=>{rr(S,m,f)}}),{isLoading:u,mutate:h}=mt(s.bind(null,n),{onSuccess:()=>{l.invalidateQueries(ft)}}),_=u?"connecting":n.status?n.status:"error";return r(Ge,{border:"1px solid",_dark:{borderColor:"gray.600"},_light:{borderColor:"gray.200"},borderRadius:"4px",p:1,w:"full",children:[r(Ye,{px:2,borderRadius:"3px",onClick:t,children:[r(k,{w:"full",justifyContent:"space-between",pr:2,children:[e(d,{as:"span",fontWeight:"medium",fontSize:"sm",flex:"1",textAlign:"left",color:"gray.700",_dark:{color:"gray.300"},children:n.name}),r(k,{children:[n.xray_version&&e(R,{colorScheme:"blue",rounded:"full",display:"inline-flex",px:3,py:1,children:r(d,{textTransform:"capitalize",fontSize:"0.7rem",fontWeight:"medium",letterSpacing:"tighter",children:["Xray ",n.xray_version]})}),n.status&&e(aa,{status:_,compact:!0})]})]}),e(Vt,{})]}),r(Ze,{px:2,pb:2,children:[e(P,{pb:3,alignItems:"flex-start",children:_==="error"&&e(gt,{status:"error",size:"xs",children:r(v,{children:[r(k,{w:"full",children:[e(Ut,{w:4}),e(d,{marginInlineEnd:0,children:n.message})]}),e(k,{justifyContent:"flex-end",w:"full",children:e(F,{size:"sm","aria-label":"reconnect node",leftIcon:e(tr,{}),onClick:()=>h(),disabled:u,children:i(u?"nodes.reconnecting":"nodes.reconnect")})})]})})}),e(bn,{form:f,mutate:C,isLoading:b,submitBtnText:i("nodes.editNode"),btnLeftAdornment:e(re,{label:i("delete"),placement:"top",children:e(V,{colorScheme:"red",variant:"ghost",size:"sm","aria-label":"delete node",onClick:x,children:e(wt,{})})})})]})]})},da=({toggleAccordion:t,resetAccordions:n})=>{const o=we(),{t:s}=H(),a=Jt(),{addNode:i}=St(),l=qe({resolver:xt(hn),defaultValues:{...us(),add_as_new_host:!1}}),{isLoading:m,mutate:f}=mt(i,{onSuccess:()=>{nr(s("nodes.addNodeSuccess",{name:l.getValues("name")}),o),a.invalidateQueries(ft),l.reset(),n()},onError:x=>{rr(x,o,l)}});return r(Ge,{border:"1px solid",_dark:{borderColor:"gray.600"},_light:{borderColor:"gray.200"},borderRadius:"4px",p:1,w:"full",children:[e(Ye,{px:2,borderRadius:"3px",onClick:t,children:r(d,{as:"span",fontWeight:"medium",fontSize:"sm",flex:"1",textAlign:"left",color:"gray.700",_dark:{color:"gray.300"},display:"flex",gap:1,children:[e(la,{display:"inline-block"})," ",e("span",{children:s("nodes.addNewMarzbanNode")})]})}),e(Ze,{px:2,py:4,children:e(bn,{form:l,mutate:f,isLoading:m,submitBtnText:s("nodes.addNode"),btnProps:{variant:"solid"},addAsHost:!0})})]})},bn=({form:t,mutate:n,isLoading:o,submitBtnText:s,btnProps:a={},btnLeftAdornment:i,addAsHost:l=!1})=>{var h,_,S,A,p,c,E,B,D,N,Y,Z,Q,ne,oe;const{t:m}=H(),[f,x]=g.exports.useState(!1),{data:b,isLoading:C}=Tt({queryKey:"node-settings",queryFn:()=>O("/node/settings")});function u(U){if(document.body.createTextRange){const W=document.body.createTextRange();W.moveToElementText(U),W.select()}else if(window.getSelection){const W=window.getSelection(),X=document.createRange();X.selectNodeContents(U),W.removeAllRanges(),W.addRange(X)}else console.warn("Could not select text in node: Unsupported browser.")}return e("form",{onSubmit:t.handleSubmit(U=>n(U)),children:r(P,{children:[b&&b.certificate&&e(gt,{status:"info",alignItems:"start",children:r(Xr,{display:"flex",flexDirection:"column",overflow:"hidden",children:[e("span",{children:m("nodes.connection-hint")}),r(k,{justify:"end",py:2,children:[e(F,{as:"a",colorScheme:"primary",size:"xs",download:"ssl_client_cert.pem",href:URL.createObjectURL(new Blob([b.certificate],{type:"text/plain"})),children:m("nodes.download-certificate")}),e(re,{placement:"top",label:m("nodes.show-certificate"),children:e(V,{"aria-label":m("nodes.show-certificate"),onClick:x.bind(null,!f),colorScheme:"whiteAlpha",color:"primary",size:"xs",children:f?e(mo,{width:"15px"}):e(po,{width:"15px"})})})]}),e(Jr,{in:f,animateOpacity:!0,children:e(d,{bg:"rgba(255,255,255,.5)",_dark:{bg:"rgba(255,255,255,.2)"},rounded:"md",p:"2",lineHeight:"1.2",fontSize:"10px",fontFamily:"Courier",whiteSpace:"pre",overflow:"auto",onClick:U=>{u(U.target)},children:b.certificate})})]})}),r(k,{w:"full",children:[e(L,{children:e(dt,{label:m("nodes.nodeName"),size:"sm",placeholder:"Marzban-S2",...t.register("name"),error:(S=(_=(h=t.formState)==null?void 0:h.errors)==null?void 0:_.name)==null?void 0:S.message})}),e(k,{px:1,children:e(ye,{name:"status",control:t.control,render:({field:U})=>e(re,{placement:"top",label:`${m("usersTable.status")}: `+(U.value!=="disabled"?m("active"):m("disabled")),textTransform:"capitalize",children:e(v,{mt:"6",children:e(zt,{colorScheme:"primary",isChecked:U.value!=="disabled",onChange:W=>{W.target.checked?U.onChange("connecting"):U.onChange("disabled")}})})},U.value)})})]}),e(k,{alignItems:"flex-start",w:"100%",children:e(v,{w:"100%",children:e(dt,{label:m("nodes.nodeAddress"),size:"sm",placeholder:"51.20.12.13",...t.register("address"),error:(c=(p=(A=t.formState)==null?void 0:A.errors)==null?void 0:p.address)==null?void 0:c.message})})}),r(k,{alignItems:"flex-start",w:"100%",children:[e(v,{children:e(dt,{label:m("nodes.nodePort"),size:"sm",placeholder:"62050",...t.register("port"),error:(D=(B=(E=t.formState)==null?void 0:E.errors)==null?void 0:B.port)==null?void 0:D.message})}),e(v,{children:e(dt,{label:m("nodes.nodeAPIPort"),size:"sm",placeholder:"62051",...t.register("api_port"),error:(Z=(Y=(N=t.formState)==null?void 0:N.errors)==null?void 0:Y.api_port)==null?void 0:Z.message})}),e(v,{children:e(dt,{label:m("nodes.usageCoefficient"),size:"sm",placeholder:"1",...t.register("usage_coefficient"),error:(oe=(ne=(Q=t.formState)==null?void 0:Q.errors)==null?void 0:ne.usage_coefficient)==null?void 0:oe.message})})]}),l&&e(L,{py:1,children:e(Ve,{...t.register("add_as_new_host"),children:e(j,{m:0,children:m("nodes.addHostForEveryInbound")})})}),r(k,{w:"full",children:[i,e(F,{flexGrow:1,type:"submit",colorScheme:"primary",size:"sm",px:5,w:"full",isLoading:o,...a,children:s})]})]})})},ha=()=>{const{isEditingNodes:t,onEditingNodes:n}=z(),{t:o}=H(),[s,a]=g.exports.useState({}),{data:i,isLoading:l}=un(),m=()=>{a({}),n(!1)},f=x=>{s[String(x)]?delete s[String(x)]:s[String(x)]={},a({...s})};return r(ie,{children:[r(de,{isOpen:t,onClose:m,children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",w:"fit-content",maxW:"3xl",children:[e(pe,{pt:6,children:e(fe,{color:"primary",children:e(ia,{color:"white"})})}),e(me,{mt:3}),r(ge,{w:"440px",pb:6,pt:3,children:[e(d,{mb:3,opacity:.8,fontSize:"sm",children:o("nodes.title")}),l&&"loading...",e(yt,{w:"full",allowToggle:!0,index:Object.keys(s).map(x=>parseInt(x)),children:r(P,{w:"full",children:[!l&&i&&i.map((x,b)=>e(ca,{toggleAccordion:()=>f(b),node:x},x.name)),e(da,{toggleAccordion:()=>f((i||[]).length),resetAccordions:()=>a({})})]})})]})]})]}),e(na,{deleteCallback:()=>a({})})]})};function ua(t){const n=360/t,o=90,s=47,a=[];for(let i=0;i(u<0&&(u+=1),u>1&&(u-=1),u<.16666666666666666?b+(C-b)*6*u:u<.5?C:u<.6666666666666666?b+(C-b)*(.6666666666666666-u)*6:b),f=o<.5?o*(1+n):o+n-o*n,x=2*o-f;s=Math.round(m(x,f,t+1/3)*255),a=Math.round(m(x,f,t)*255),i=Math.round(m(x,f,t-1/3)*255)}const l=m=>{const f=m.toString(16);return f.length===1?"0"+f:f};return`#${l(s)}${l(a)}${l(i)}`}const Ur=({border:t,...n})=>{const{getInputProps:o,getRadioProps:s}=wo(n),a=We({base:"xs",md:"sm"});return r(v,{as:"label",children:[e("input",{...o()}),e(v,{...s(),minW:"48px",w:"full",h:"full",textAlign:"center",cursor:"pointer",fontSize:a,borderWidth:t?"1px":"0px",borderRadius:"md",_checked:{bg:"primary.500",color:"white",borderColor:"primary.500"},_focus:{boxShadow:"outline"},px:3,py:1,children:n.children})]})},xn=({onChange:t,defaultValue:n,...o})=>{const{t:s,i18n:a}=H();Qe();const i=We({base:["7h","1d","3d","1w"],md:["7h","1d","3d","1w","1m","3m"]}),l={h:"hour",d:"day",w:"week",m:"month",y:"year"},m=We({base:[{title:"hours",options:["1h","3h","6h","12h"]},{title:"days",options:["1d","2d","3d","4d"]},{title:"weeks",options:["1w","2w","3w","4w"]},{title:"months",options:["1m","2m","3m","6m"]}],md:[{title:"hours",options:["1h","2h","3h","6h","8h","12h"]},{title:"days",options:["1d","2d","3d","4d","5d","6d"]},{title:"weeks",options:["1w","2w","3w","4w"]},{title:"months",options:["1m","2m","3m","6m","8m"]}]}),{getRootProps:f,getRadioProps:x,setValue:b}=go({name:"filter",defaultValue:n,onChange:U=>{if(U==="custom")return;h(),i.indexOf(U)>=0?(A(s("userDialog.custom")),c(!1)):(A(s("userDialog.custom")+` (${U})`),c(!0));const W=Number(U.substring(0,U.length-1)),X=l[U[U.length-1]];t(U,{start:$().utc().subtract(W,X).format("YYYY-MM-DDTHH:00:00")})}}),{isOpen:C,onOpen:u,onClose:h}=fo(),_=g.exports.useRef(null);bo({ref:_,handler:h});const[S,A]=g.exports.useState(s("userDialog.custom")),[p,c]=g.exports.useState(!1),[E,B]=g.exports.useState(0),D=We({base:1,md:2}),N=We({base:"xs",md:"sm"}),[Y,Z]=g.exports.useState(null),[Q,ne]=g.exports.useState(null),oe=U=>{const[W,X]=U;Q&&!X?(Z(null),ne(null)):(Z(W),ne(X),W&&X&&(h(),t("custom",{start:$(W).format("YYYY-MM-DDT00:00:00"),end:$(X).format("YYYY-MM-DDT23:59:59")})))};return r(P,{...o,children:[E==0&&r(Kt,{...f(),gap:0,display:"flex",borderWidth:"1px",borderRadius:"md",minW:{base:"320px",md:"400px"},children:[i.map(U=>e(Ur,{...x({value:U}),children:U},U)),e(v,{onClick:()=>{Z(null),ne(null),u()},cursor:"pointer",borderRadius:"md",w:"full",fontSize:N,px:3,py:1,bg:p?"primary.500":"unset",color:p?"white":"unset",borderColor:p?"primary.500":"unset",children:r(k,{children:[e(d,{children:S}),e(Pt,{as:gr,boxSize:"18px"})]})})]}),E==1&&r(k,{onClick:u,cursor:"pointer",fontSize:N,borderRadius:"md",px:3,py:1,minW:{base:"320px",md:"400px"},borderWidth:"1px",children:[e(d,{w:"full",color:Y?"unset":"gray.500",children:Y?$(Y).format("YYYY-MM-DD (00:00)"):s("userDialog.startDate")}),e(Pt,{as:Kr,boxSize:"18px"}),e(d,{w:"full",color:Q?"unset":"gray.500",children:Q?$(Q).format("YYYY-MM-DD (23:59)"):s("userDialog.endDate")}),e(Pt,{as:gr,boxSize:"18px"})]}),e(P,{ref:_,marginTop:"40px !important",borderRadius:"md",borderWidth:"1px",position:"absolute",zIndex:"1",backgroundColor:"white",_dark:{backgroundColor:"gray.700"},display:C?"unset":"none",children:r(xo,{onChange:U=>B(U),children:[r(yo,{children:[e(fr,{fontSize:N,children:s("userDialog.relative")}),e(fr,{fontSize:N,children:s("userDialog.absolute")})]}),r(So,{children:[e(br,{children:m.map(U=>e(P,{alignItems:"start",pl:2,pr:2,children:r(k,{justifyItems:"flex-start",mb:4,children:[e(d,{fontSize:N,minW:"60px",children:s("userDialog."+U.title)}),U.options.map(W=>e(Ur,{border:!0,...x({value:W}),children:W},W+".custom"))]})},U.title))}),e(br,{className:"datepicker-panel",children:e(P,{children:e(en,{locale:a.language.toLocaleLowerCase(),selected:Y,onChange:oe,startDate:Y,endDate:Q,selectsRange:!0,maxDate:new Date,monthsShown:D,peekNextMonth:!1,inline:!0})})})]})]})})]})};function Rt(t,n,o=[],s=[]){const a=ae(o.reduce((i,l)=>i+=l,0));return{series:o,options:{labels:s,chart:{width:"100%",height:"100%",type:"donut",animations:{enabled:!1}},title:{text:`${n}${a}`,align:"center",style:{fontWeight:"var(--chakra-fontWeights-medium)",color:t==="dark"?"var(--chakra-colors-gray-300)":void 0}},legend:{position:"bottom",labels:{colors:t==="dark"?"#CBD5E0":void 0,useSeriesColors:!1}},stroke:{width:1,colors:void 0},dataLabels:{formatter:(i,{seriesIndex:l,w:m})=>ae(m.config.series[l],1)},tooltip:{custom:({series:i,seriesIndex:l,dataPointIndex:m,w:f})=>{const x=ae(i[l],1),b=Math.max(i.reduce((u,h)=>u+=h),1),C=Math.round(i[l]/b*1e3)/10+"%";return` +
+ ${f.config.labels[l]}: ${C}, ${x} +
+ `}},colors:ua(o.length)}}}const ma=w(At,{baseStyle:{w:5,h:5}}),ga=()=>{const{isShowingNodesUsage:t,onShowingNodesUsage:n}=z(),{fetchNodesUsage:o}=St(),{t:s}=H(),[a,i]=g.exports.useState(!1),{colorMode:l}=Qe(),m=s("userDialog.total"),[f,x]=g.exports.useState(Rt(l,m)),[b,C]=g.exports.useState("1m"),u=S=>{o(S).then(A=>{const p=[],c=[];for(const E in A.usages){const B=A.usages[E];c.push(B.uplink+B.downlink),p.push(B.node_name)}x(Rt(l,m,c,p))})};g.exports.useEffect(()=>{t&&u({start:$().utc().subtract(30,"day").format("YYYY-MM-DDTHH:00:00")})},[t]);const h=()=>{n(!1),C("1m")},_=a;return r(de,{isOpen:t,onClose:h,size:"2xl",children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",w:"full",children:[e(pe,{pt:6,children:r(k,{gap:2,children:[e(fe,{color:"primary",children:e(ma,{color:"white"})}),e(d,{fontWeight:"semibold",fontSize:"lg",children:s("header.nodesUsage")})]})}),e(me,{mt:3,disabled:_}),e(ge,{children:r(P,{gap:4,children:[e(xn,{defaultValue:b,onChange:(S,A)=>{C(S),u(A)}}),e(v,{justifySelf:"center",w:"full",maxW:"300px",mt:"4",children:e(g.exports.Suspense,{fallback:e(Hr,{isIndeterminate:!0}),children:e(tn,{options:f.options,series:f.series,type:"donut",height:"500px"})})})]})}),e(Pe,{mt:"3"})]})]})},Er=w(Co),fa=w(Kr,{baseStyle:{w:6,h:6,color:"gray.600",_dark:{color:"white"}}}),ba=w(_o,{baseStyle:{w:6,h:6,color:"gray.600",_dark:{color:"white"}}}),xa=w(rn,{baseStyle:{w:5,h:5}}),ya=()=>{const{QRcodeLinks:t,setQRCode:n,setSubLink:o,subscribeUrl:s}=z(),a=t!==null,[i,l]=g.exports.useState(0),{t:m}=H(),f=()=>{n(null),o(null)},x=String(s).startsWith("/")?window.location.origin+s:String(s);return r(de,{isOpen:a,onClose:f,children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",w:"fit-content",maxW:"3xl",children:[e(pe,{pt:6,children:e(fe,{color:"primary",children:e(xa,{color:"white"})})}),e(me,{mt:3}),t&&r(ge,{gap:{base:"20px",lg:"50px"},pr:{lg:"60px"},px:{base:"50px"},display:"flex",justifyContent:"center",flexDirection:{base:"column",lg:"row"},children:[s&&r(P,{children:[e(Er,{mx:"auto",size:300,p:"2",level:"L",includeMargin:!1,value:x,bg:"white"}),e(d,{display:"block",textAlign:"center",pb:3,mt:1,children:m("qrcodeDialog.sublink")})]}),r(v,{w:"300px",children:[e(ko,{centerPadding:"0px",centerMode:!0,slidesToShow:1,slidesToScroll:1,dots:!1,afterChange:l,onInit:()=>l(0),nextArrow:e(V,{size:"sm",position:"absolute",display:"flex !important",_before:{content:'""'},"aria-label":"next",mr:"-4",children:e(fa,{})}),prevArrow:e(V,{size:"sm",position:"absolute",display:"flex !important",_before:{content:'""'},"aria-label":"prev",ml:"-4",children:e(ba,{})}),children:t.map((b,C)=>e(k,{children:e(Er,{mx:"auto",size:300,p:"2",level:"L",includeMargin:!1,value:b,bg:"white"})},C))}),r(d,{display:"block",textAlign:"center",pb:3,mt:1,children:[i+1," / ",t.length]})]})]})]})]})},Sa=w(Zr,{baseStyle:{w:5,h:5}}),wa=()=>{const[t,n]=g.exports.useState(!1),{isResetingAllUsage:o,onResetAllUsage:s,resetAllUsage:a}=z(),{t:i}=H(),l=we(),m=()=>{s(!1)},f=()=>{n(!0),a().then(()=>{l({title:i("resetAllUsage.success"),status:"success",isClosable:!0,position:"top",duration:3e3})}).catch(()=>{l({title:i("resetAllUsage.error"),status:"error",isClosable:!0,position:"top",duration:3e3})}).finally(()=>{n(!1)})};return r(de,{isCentered:!0,isOpen:o,onClose:m,size:"sm",children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",children:[e(pe,{pt:6,children:e(fe,{color:"red",children:e(Sa,{})})}),e(me,{mt:3}),r(ge,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:i("resetAllUsage.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:i("resetAllUsage.prompt")})]}),r(Pe,{display:"flex",children:[e(F,{size:"sm",onClick:m,mr:3,w:"full",variant:"outline",children:i("cancel")}),e(F,{size:"sm",w:"full",colorScheme:"red",onClick:f,leftIcon:t?e(He,{size:"xs"}):void 0,children:i("reset")})]})]})]})},Ca=w(Mt,{baseStyle:{w:5,h:5}}),_a=()=>{const[t,n]=g.exports.useState(!1),{resetUsageUser:o,resetDataUsage:s}=z(),{t:a}=H(),i=we(),l=()=>{z.setState({resetUsageUser:null})},m=()=>{o&&(n(!0),s(o).then(()=>{i({title:a("resetUserUsage.success",{username:o.username}),status:"success",isClosable:!0,position:"top",duration:3e3})}).catch(()=>{i({title:a("resetUserUsage.error"),status:"error",isClosable:!0,position:"top",duration:3e3})}).finally(()=>{n(!1)}))};return r(de,{isCentered:!0,isOpen:!!o,onClose:l,size:"sm",children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",children:[e(pe,{pt:6,children:e(fe,{color:"blue",children:e(Ca,{})})}),e(me,{mt:3}),r(ge,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:a("resetUserUsage.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:e(Te,{components:{b:e("b",{})},children:a("resetUserUsage.prompt",{username:o.username})})})]}),r(Pe,{display:"flex",children:[e(F,{size:"sm",onClick:l,mr:3,w:"full",variant:"outline",children:a("cancel")}),e(F,{size:"sm",w:"full",colorScheme:"blue",onClick:m,leftIcon:t?e(He,{size:"xs"}):void 0,children:a("reset")})]})]})]})},ka=w(Mt,{baseStyle:{w:5,h:5}}),Ia=()=>{const[t,n]=g.exports.useState(!1),{revokeSubscriptionUser:o,revokeSubscription:s}=z(),{t:a}=H(),i=we(),l=()=>{z.setState({revokeSubscriptionUser:null})},m=()=>{o&&(n(!0),s(o).then(()=>{i({title:a("revokeUserSub.success",{username:o.username}),status:"success",isClosable:!0,position:"top",duration:3e3})}).catch(()=>{i({title:a("revokeUserSub.error"),status:"error",isClosable:!0,position:"top",duration:3e3})}).finally(()=>{n(!1)}))};return r(de,{isCentered:!0,isOpen:!!o,onClose:l,size:"sm",children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(ue,{mx:"3",children:[e(pe,{pt:6,children:e(fe,{color:"blue",children:e(ka,{})})}),e(me,{mt:3}),r(ge,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:a("revokeUserSub.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:e(Te,{components:{b:e("b",{})},children:a("revokeUserSub.prompt",{username:o.username})})})]}),r(Pe,{display:"flex",children:[e(F,{size:"sm",onClick:l,mr:3,w:"full",variant:"outline",children:a("cancel")}),e(F,{size:"sm",w:"full",colorScheme:"blue",onClick:m,leftIcon:t?e(He,{size:"xs"}):void 0,children:a("revoke")})]})]})]})},va=w(Io,{baseStyle:{strokeWidth:"2px",w:5,h:5}}),Da=({inbound:t,...n})=>{const{getCheckboxProps:o,getInputProps:s,getLabelProps:a,htmlProps:i}=on(n),l=s();return r(v,{as:"label",children:[e("input",{...l}),r(v,{w:"fll",position:"relative",...i,cursor:"pointer",borderRadius:"sm",border:"1px solid",borderColor:"gray.200",_dark:{borderColor:"gray.600"},display:"flex",alignItems:"center",justifyContent:"space-between",overflow:"hidden",_checked:{bg:"gray.50",outline:"2px",boxShadow:"outline",outlineColor:"primary.500",borderColor:"transparent",fontWeight:"medium",_dark:{bg:"gray.750",borderColor:"transparent"},"& p":{opacity:1}},__css:{"& p":{opacity:.8}},textTransform:"capitalize",px:3,py:2,fontWeight:"medium",...o(),children:[e(Ve,{size:"sm",w:"full",maxW:"full",color:"gray.700",_dark:{color:"gray.300"},textTransform:"uppercase",colorScheme:"primary",className:"inbound-item",isChecked:l.checked,pointerEvents:"none",flexGrow:1,children:e(k,{justify:"space-between",w:"full",maxW:"calc(100% - 20px)",spacing:0,gap:2,overflow:"hidden",children:r(d,{isTruncated:!0,...a(),fontSize:"xs",children:[t.tag," ",r(d,{as:"span",children:["(",t.network,")"]})]})})}),t.tls&&t.tls!="none"&&e(R,{fontSize:"xs",opacity:".8",size:"xs",children:t.tls})]})]})},za=({disabled:t,title:n,description:o,toggleAccordion:s,isSelected:a,ss2022Method:i,...l})=>{const m=Xt(),{inbounds:f}=z(),{getCheckboxProps:x,getInputProps:b,getLabelProps:C,htmlProps:u}=on(l),h=b(),[_]=sn({name:[`inbounds.${n}`],control:m.control}),{getCheckboxProps:S}=nn({value:_,onChange:E=>{if(m.setValue(`inbounds.${n}`,E),E.length===0){const B=m.getValues("selected_proxies");m.setValue("selected_proxies",B.filter(D=>D!==n)),s()}}}),A=_&&a&&(z.getState().inbounds.get(n)||[]).length!==_.length,p=(z.getState().inbounds.get(n)||[]).length>0,c=!a&&!p;return r(Ge,{isDisabled:!p,borderRadius:"md",borderStyle:"solid",border:"1px",borderColor:"gray.200",bg:c?"gray.100":"transparent",_dark:{borderColor:"gray.600",bg:c?"#364154":"transparent"},_checked:{bg:"gray.50",outline:"2px",boxShadow:"outline",outlineColor:"primary.500",borderColor:"transparent"},...x(),children:[r(v,{as:c?"span":"label",position:"relative",children:[A&&e(v,{position:"absolute",w:"2",h:"2",bg:"yellow.500",top:"-1",right:"-1",rounded:"full",zIndex:999}),e("input",{...h}),r(v,{w:"fll",position:"relative",...u,borderRadius:"md",cursor:c?"not-allowed":"pointer",_checked:{fontWeight:"medium",_dark:{bg:"gray.750",borderColor:"transparent"},"& > svg":{opacity:1,"&.checked":{display:"block"},"&.unchecked":{display:"none"}},"& p":{opacity:1}},__css:{"& > svg":{opacity:.3,"&.checked":{display:"none"},"&.unchecked":{display:"block"}},"& p":{opacity:.8}},textTransform:"capitalize",px:3,py:2,fontWeight:"medium",...x(),children:[e(Ye,{display:h.checked&&p?"block":"none",as:"span",className:"checked",color:"primary.200",position:"absolute",right:"3",top:"3",w:"auto",p:0,onClick:s,children:e(V,{size:"sm","aria-label":"inbound settings",children:e(va,{})})}),e(d,{fontSize:"sm",color:c?"gray.400":"gray.700",_dark:{color:c?"gray.500":"gray.300"},...C(),children:n}),e(d,{fontWeight:"medium",color:c?"gray.400":"gray.600",_dark:{color:c?"gray.500":"gray.400"},fontSize:"xs",children:o})]})]}),e(Ze,{px:2,pb:3,roundedBottom:"5px",pt:3,_dark:{bg:h.checked&&"gray.750"},children:r(P,{w:"full",rowGap:2,borderStyle:"solid",borderWidth:"1px",borderRadius:"md",pl:3,pr:3,pt:1.5,_dark:{bg:"gray.700"},children:[r(P,{alignItems:"flex-start",w:"full",children:[e(d,{fontSize:"sm",children:q("inbound")}),e(Kt,{gap:2,alignItems:"flex-start",w:"full",columns:1,spacing:1,children:(f.get(n)||[]).map(E=>e(Da,{...S({value:E.tag}),inbound:E},E.tag))})]}),n==="vmess"&&a&&e(P,{alignItems:"flex-start",w:"full",children:r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:"ID"}),e($e,{fontSize:"xs",size:"sm",borderRadius:"6px",pl:2,pr:2,placeholder:q("userDialog.generatedByDefault"),...m.register("proxies.vmess.id")})]})}),n==="vless"&&a&&r(P,{alignItems:"flex-start",w:"full",children:[r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:"ID"}),e($e,{fontSize:"xs",size:"sm",borderRadius:"6px",pl:2,pr:2,placeholder:q("userDialog.generatedByDefault"),...m.register("proxies.vless.id")})]}),r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:"Flow"}),e(Ne,{fontSize:"xs",size:"sm",borderRadius:"6px",...m.register("proxies.vless.flow"),children:Gs.map(E=>e("option",{value:E.value,children:E.title},E.title))})]})]}),n==="trojan"&&a&&e(P,{alignItems:"flex-start",w:"full",children:r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:q("password")}),e($e,{fontSize:"xs",size:"sm",borderRadius:"6px",pl:2,pr:2,placeholder:q("userDialog.generatedByDefault"),...m.register("proxies.trojan.password")})]})}),n==="shadowsocks"&&a&&r(P,{alignItems:"flex-start",w:"full",children:[r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:q("password")}),e($e,{fontSize:"xs",size:"sm",borderRadius:"6px",pl:2,pr:2,placeholder:q("userDialog.generatedByDefault"),...m.register("proxies.shadowsocks.password")})]}),r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:q("userDialog.method")}),e(Ne,{fontSize:"xs",size:"sm",borderRadius:"6px",isDisabled:Boolean(i),...m.register("proxies.shadowsocks.method"),children:Ys.map(E=>r("option",{value:E,children:[E,i&&E===i?" (inbound)":""]},E))})]})]})]})})]})},Ua=g.exports.forwardRef(({name:t,list:n,onChange:o,disabled:s,...a},i)=>{const l=Xt(),m=z.getState().inbounds.get("shadowsocks")||[],f=g.exports.useMemo(()=>{const h=m.map(_=>_.method).filter(_=>Boolean(_));return h.length&&h.every(_=>_.startsWith("2022-"))?h[0]:null},[m]);g.exports.useEffect(()=>{f&&l.setValue("proxies.shadowsocks.method",f)},[l,f]);const[x,b]=g.exports.useState([]),C=h=>{x.includes(h)?x.splice(x.indexOf(h),1):x.push(h),b([...x])},{getCheckboxProps:u}=nn({value:a.value,onChange:h=>{var S;const _=h.filter(A=>!a.value.includes(A));_[0]&&l.setValue(`inbounds.${_[0]}`,(S=z.getState().inbounds.get(_[0]))==null?void 0:S.map(A=>A.tag)),b(x.filter(A=>h.find(p=>p===n[A].title))),o({target:{value:h,name:t}})}});return e(yt,{allowToggle:!0,index:x,children:e(Kt,{ref:i,gap:2,alignItems:"flex-start",columns:1,spacing:1,children:n.map((h,_)=>e(za,{toggleAccordion:C.bind(null,_),disabled:s,title:h.title,description:h.description,isSelected:!!a.value.find(S=>S===h.title),ss2022Method:f,...u({value:h.title})},h.title))})})}),Ea=w(vo,{baseStyle:{w:5,h:5}}),Ra=w(an,{baseStyle:{w:5,h:5}}),La=w(At,{baseStyle:{w:5,h:5}}),Aa=t=>({...t,data_limit:t.data_limit?Number((t.data_limit/1073741824).toFixed(5)):t.data_limit,on_hold_expire_duration:t.on_hold_expire_duration?Number(t.on_hold_expire_duration/(24*60*60)):t.on_hold_expire_duration,selected_proxies:Object.keys(t.proxies)}),Ht=()=>{const t=Object.fromEntries(z.getState().inbounds),n={};for(const o in t)n[o]=t[o].map(s=>s.tag);return{selected_proxies:Object.keys(t),data_limit:null,expire:null,username:"",data_limit_reset_strategy:"no_reset",status:"active",on_hold_expire_duration:null,note:"",inbounds:n,proxies:{vless:{id:"",flow:""},vmess:{id:""},trojan:{password:""},shadowsocks:{password:"",method:"chacha20-ietf-poly1305"}}}},Ta=(t,n)=>{const o=t.reduce((s,a)=>({...s,[a]:{}}),{});return n&&t.forEach(s=>{n[s]&&(o[s]=n[s])}),o},ht={username:y.string().min(1,{message:"Required"}),selected_proxies:y.array(y.string()).refine(t=>t.length>0,{message:"userDialog.selectOneProtocol"}),note:y.string().nullable(),proxies:y.record(y.string(),y.record(y.string(),y.any())).transform(t=>{const n=(o,s)=>{o&&o[s]===""&&delete o[s]};return n(t.vmess,"id"),n(t.vless,"id"),n(t.trojan,"password"),n(t.shadowsocks,"password"),n(t.shadowsocks,"method"),t}),data_limit:y.string().min(0).or(y.number()).nullable().transform(t=>t?Number((parseFloat(String(t))*1073741824).toFixed(5)):0),expire:y.number().nullable(),data_limit_reset_strategy:y.string(),inbounds:y.record(y.string(),y.array(y.string())).transform(t=>(Object.keys(t).forEach(n=>{var o;Array.isArray(t[n])&&!((o=t[n])!=null&&o.length)&&delete t[n]}),t))},Ma=y.discriminatedUnion("status",[y.object({status:y.literal("active"),...ht}),y.object({status:y.literal("disabled"),...ht}),y.object({status:y.literal("limited"),...ht}),y.object({status:y.literal("expired"),...ht}),y.object({status:y.literal("on_hold"),on_hold_expire_duration:y.coerce.number().min(.1,"Required").transform(t=>t*(24*60*60)),...ht})]),Na=()=>{var Ke,et,tt,rt,nt;const{editingUser:t,isCreatingNewUser:n,onCreateUser:o,editUser:s,fetchUserUsage:a,onEditingUser:i,createUser:l,onDeletingUser:m}=z(),f=!!t,x=n||f,[b,C]=g.exports.useState(!1),[u,h]=g.exports.useState(""),_=we(),{t:S,i18n:A}=H(),{colorMode:p}=Qe(),[c,E]=g.exports.useState(!1),B=()=>{E(I=>!I)},D=qe({defaultValues:Ht(),resolver:xt(Ma)});g.exports.useEffect(()=>z.subscribe(I=>I.inbounds,()=>{D.reset(Ht())}),[]);const[N,Y]=sn({control:D.control,name:["data_limit","status"]}),Z=S("userDialog.total"),[Q,ne]=g.exports.useState(Rt(p,Z)),[oe,U]=g.exports.useState("1m"),W=I=>{a(t,I).then(M=>{const ee=[],se=[];for(const be in M.usages)se.push(M.usages[be].used_traffic),ee.push(M.usages[be].node_name);ne(Rt(p,Z,se,ee))})};g.exports.useEffect(()=>{t&&(D.reset(Aa(t)),W({start:$().utc().subtract(30,"day").format("YYYY-MM-DDTHH:00:00")}))},[t]);const X=I=>{C(!0);const M={edited:s,created:l},ee=f?"edited":"created";h(null);const{selected_proxies:se,...be}=I;let ke={...be,data_limit:I.data_limit,proxies:Ta(se,I.proxies),data_limit_reset_strategy:I.data_limit&&I.data_limit>0?I.data_limit_reset_strategy:"no_reset",status:I.status==="active"||I.status==="disabled"||I.status==="on_hold"?I.status:"active"};M[ee](ke).then(()=>{_({title:S(f?"userDialog.userEdited":"userDialog.userCreated",{username:I.username}),status:"success",isClosable:!0,position:"top",duration:3e3}),T()}).catch(G=>{var ot,st,at,it,lt;(((ot=G==null?void 0:G.response)==null?void 0:ot.status)===409||((st=G==null?void 0:G.response)==null?void 0:st.status)===400)&&h((it=(at=G==null?void 0:G.response)==null?void 0:at._data)==null?void 0:it.detail),((lt=G==null?void 0:G.response)==null?void 0:lt.status)===422&&Object.keys(G.response._data.detail).forEach(je=>{h(G==null?void 0:G.response._data.detail[je]),D.setError(je,{type:"custom",message:G.response._data.detail[je]})})}).finally(()=>{C(!1)})},T=()=>{D.reset(Ht()),o(!1),i(null),h(null),E(!1),U("1m")},K=()=>{z.setState({resetUsageUser:t})},le=()=>{z.setState({revokeSubscriptionUser:t})},J=b,_e=Y==="on_hold",[_t,Je]=g.exports.useState(!1),kt=()=>{Je(!0);let I="";const M="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",ee=M.length;let se=0;for(;se<6;)I+=M.charAt(Math.floor(Math.random()*ee)),se+=1;return I};return r(de,{isOpen:x,onClose:T,size:"2xl",children:[e(he,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),e(Qr,{...D,children:e(ue,{mx:"3",children:r("form",{onSubmit:D.handleSubmit(X),children:[e(pe,{pt:6,children:r(k,{gap:2,children:[e(fe,{color:"primary",children:f?e(Ra,{color:"white"}):e(Ea,{color:"white"})}),e(d,{fontWeight:"semibold",fontSize:"lg",children:S(f?"userDialog.editUserTitle":"createNewUser")})]})}),e(me,{mt:3,disabled:J}),r(ge,{children:[r(Br,{templateColumns:{base:"repeat(1, 1fr)",md:"repeat(2, 1fr)"},gap:3,children:[e(pt,{children:r(P,{justifyContent:"space-between",children:[r(Ft,{flexDirection:"column",gridAutoRows:"min-content",w:"full",children:[r(Ft,{flexDirection:"row",w:"full",gap:2,children:[r(L,{mb:"10px",children:[e(j,{children:r(Ft,{gap:2,alignItems:"center",children:[S("username"),!f&&e(tr,{cursor:"pointer",className:bt({"animate-spin":_t}),onClick:()=>{const I=kt();D.setValue("username",I),setTimeout(()=>{Je(!1)},350)}})]})}),r(k,{children:[e(Me,{size:"sm",type:"text",borderRadius:"6px",error:(Ke=D.formState.errors.username)==null?void 0:Ke.message,disabled:J||f,...D.register("username")}),f&&e(k,{px:1,children:e(ye,{name:"status",control:D.control,render:({field:I})=>e(re,{placement:"top",label:"status: "+S(`status.${I.value}`),textTransform:"capitalize",children:e(v,{children:e(zt,{colorScheme:"primary",isChecked:I.value==="active",onChange:M=>{M.target.checked?I.onChange("active"):I.onChange("disabled")}})})})})})]})]}),!f&&r(L,{flex:"1",children:[e(j,{whiteSpace:"nowrap",children:S("userDialog.onHold")}),e(ye,{name:"status",control:D.control,render:({field:I})=>{const M=I.value;return e(ie,{children:M?e(zt,{colorScheme:"primary",isChecked:M==="on_hold",onChange:ee=>{ee.target.checked?I.onChange("on_hold"):I.onChange("active")}}):""})}})]})]}),r(L,{mb:"10px",children:[e(j,{children:S("userDialog.dataLimit")}),e(ye,{control:D.control,name:"data_limit",render:({field:I})=>{var M;return e(Me,{endAdornment:"GB",type:"number",size:"sm",borderRadius:"6px",onChange:I.onChange,disabled:J,error:(M=D.formState.errors.data_limit)==null?void 0:M.message,value:I.value?String(I.value):""})}})]}),e(Jr,{in:!!(N&&N>0),animateOpacity:!0,style:{width:"100%"},children:r(L,{height:"66px",children:[e(j,{children:S("userDialog.periodicUsageReset")}),e(ye,{control:D.control,name:"data_limit_reset_strategy",render:({field:I})=>e(Ne,{size:"sm",...I,disabled:J,bg:J?"gray.100":"transparent",_dark:{bg:J?"gray.600":"transparent"},sx:{option:{backgroundColor:p==="dark"?"#222C3B":"white"}},children:Zt.map(M=>e("option",{value:M.value,children:S("userDialog.resetStrategy"+M.title)},M.value))})})]})}),r(L,{mb:"10px",children:[e(j,{children:S(_e?"userDialog.onHoldExpireDuration":"userDialog.expiryDate")}),_e&&e(ye,{control:D.control,name:"on_hold_expire_duration",render:({field:I})=>{var M;return e(Me,{endAdornment:"Days",type:"number",size:"sm",borderRadius:"6px",onChange:ee=>{D.setValue("expire",null),I.onChange({target:{value:ee}})},disabled:J,error:(M=D.formState.errors.on_hold_expire_duration)==null?void 0:M.message,value:I.value?String(I.value):""})}}),!_e&&e(ye,{name:"expire",control:D.control,render:({field:I})=>{var be;function M(ke){return $($(ke*1e3).utc()).toDate()}const{status:ee,time:se}=Nt(I.value);return r(ie,{children:[e(en,{locale:A.language.toLocaleLowerCase(),dateFormat:S("dateFormat"),minDate:new Date,selected:I.value?M(I.value):void 0,onChange:ke=>{D.setValue("on_hold_expire_duration",null),I.onChange({target:{value:ke?$($(ke).set("hour",23).set("minute",59).set("second",59)).utc().valueOf()/1e3:0,name:"expire"}})},customInput:e(Me,{size:"sm",type:"text",borderRadius:"6px",clearable:!0,disabled:J,error:(be=D.formState.errors.expire)==null?void 0:be.message})}),I.value?e(Do,{children:S(ee,{time:se})}):""]})}})]}),r(L,{mb:"10px",isInvalid:!!D.formState.errors.note,children:[e(j,{children:S("userDialog.note")}),e(zo,{...D.register("note")}),e(Dt,{children:(tt=(et=D.formState.errors)==null?void 0:et.note)==null?void 0:tt.message})]})]}),u&&r(gt,{status:"error",display:{base:"none",md:"flex"},children:[e(Ut,{}),u]})]})}),e(pt,{children:r(L,{isInvalid:!!((rt=D.formState.errors.selected_proxies)!=null&&rt.message),children:[e(j,{children:S("userDialog.protocols")}),e(ye,{control:D.control,name:"selected_proxies",render:({field:I})=>e(Ua,{list:[{title:"vmess",description:S("userDialog.vmessDesc")},{title:"vless",description:S("userDialog.vlessDesc")},{title:"trojan",description:S("userDialog.trojanDesc")},{title:"shadowsocks",description:S("userDialog.shadowsocksDesc")}],disabled:J,...I})}),e(Dt,{children:S((nt=D.formState.errors.selected_proxies)==null?void 0:nt.message)})]})}),f&&c&&e(pt,{pt:6,colSpan:{base:1,md:2},children:r(P,{gap:4,children:[e(xn,{defaultValue:oe,onChange:(I,M)=>{U(I),W(M)}}),e(v,{width:{base:"100%",md:"70%"},justifySelf:"center",children:e(tn,{options:Q.options,series:Q.series,type:"donut"})})]})})]}),u&&r(gt,{mt:"3",status:"error",display:{base:"flex",md:"none"},children:[e(Ut,{}),u]})]}),e(Pe,{mt:"3",children:r(k,{justifyContent:"space-between",w:"full",gap:3,flexDirection:{base:"column",sm:"row"},children:[e(k,{justifyContent:"flex-start",w:{base:"full",sm:"unset"},children:f&&r(ie,{children:[e(re,{label:S("delete"),placement:"top",children:e(V,{"aria-label":"Delete",size:"sm",onClick:()=>{m(t),T()},children:e(wt,{})})}),e(re,{label:S("userDialog.usage"),placement:"top",children:e(V,{"aria-label":"usage",size:"sm",onClick:B,children:e(La,{})})}),e(F,{onClick:K,size:"sm",children:S("userDialog.resetUsage")}),e(F,{onClick:le,size:"sm",children:S("userDialog.revokeSubscription")})]})}),e(k,{w:"full",maxW:{md:"50%",base:"full"},justify:"end",children:e(F,{type:"submit",size:"sm",px:"8",colorScheme:"primary",leftIcon:b?e(He,{size:"xs"}):void 0,disabled:J,children:S(f?"userDialog.editUser":"createUser")})})]})})]})})})]})},Pa=t=>g.exports.createElement("svg",{xmlns:"http://www.w3.org/2000/svg","data-name":"Layer 1",width:782.04441,height:701.88002,viewBox:"0 0 782.04441 701.88002",xmlnsXlink:"http://www.w3.org/1999/xlink",...t},g.exports.createElement("path",{d:"M609.48783,100.59015l-25.44631,6.56209L270.53735,187.9987,245.091,194.56079A48.17927,48.17927,0,0,0,210.508,253.17865L320.849,681.05606a48.17924,48.17924,0,0,0,58.61776,34.58317l.06572-.01695,364.26536-93.93675.06572-.01695a48.17923,48.17923,0,0,0,34.58309-58.6178l-110.341-427.87741A48.17928,48.17928,0,0,0,609.48783,100.59015Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),g.exports.createElement("path",{d:"M612.94784,114.00532l-30.13945,7.77236L278.68955,200.20385l-30.139,7.77223a34.30949,34.30949,0,0,0-24.6275,41.74308l110.341,427.87741a34.30946,34.30946,0,0,0,41.7431,24.62736l.06572-.01695,364.26536-93.93674.06619-.01707a34.30935,34.30935,0,0,0,24.627-41.7429l-110.341-427.87741A34.30938,34.30938,0,0,0,612.94784,114.00532Z",transform:"translate(-208.9778 -99.05999)",fill:"#fff"}),g.exports.createElement("path",{d:"M590.19,252.56327,405.917,300.08359a8.01411,8.01411,0,0,1-4.00241-15.52046l184.273-47.52033A8.01412,8.01412,0,0,1,590.19,252.56327Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),g.exports.createElement("path",{d:"M628.955,270.49906,412.671,326.27437a8.01411,8.01411,0,1,1-4.00241-15.52046l216.284-55.77531a8.01411,8.01411,0,0,1,4.00242,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),g.exports.createElement("path",{d:"M620.45825,369.93676l-184.273,47.52032a8.01411,8.01411,0,1,1-4.00242-15.52046l184.273-47.52032a8.01411,8.01411,0,1,1,4.00241,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),g.exports.createElement("path",{d:"M659.22329,387.87255l-216.284,55.77531a8.01411,8.01411,0,1,1-4.00242-15.52046l216.284-55.77531a8.01411,8.01411,0,0,1,4.00242,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),g.exports.createElement("path",{d:"M650.72653,487.31025l-184.273,47.52033a8.01412,8.01412,0,0,1-4.00242-15.52047l184.273-47.52032a8.01411,8.01411,0,0,1,4.00242,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),g.exports.createElement("path",{d:"M689.49156,505.246l-216.284,55.77532a8.01412,8.01412,0,1,1-4.00241-15.52047l216.284-55.77531a8.01411,8.01411,0,0,1,4.00242,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),g.exports.createElement("path",{d:"M374.45884,348.80871l-65.21246,16.817a3.847,3.847,0,0,1-4.68062-2.76146L289.5963,304.81607a3.847,3.847,0,0,1,2.76145-4.68061l65.21247-16.817a3.847,3.847,0,0,1,4.68061,2.76145l14.96947,58.04817A3.847,3.847,0,0,1,374.45884,348.80871Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M404.72712,466.1822l-65.21247,16.817a3.847,3.847,0,0,1-4.68062-2.76146l-14.96946-58.04816A3.847,3.847,0,0,1,322.626,417.509l65.21246-16.817a3.847,3.847,0,0,1,4.68062,2.76145l14.96946,58.04817A3.847,3.847,0,0,1,404.72712,466.1822Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M434.99539,583.55569l-65.21246,16.817a3.847,3.847,0,0,1-4.68062-2.76145l-14.96946-58.04817a3.847,3.847,0,0,1,2.76145-4.68062l65.21247-16.817a3.847,3.847,0,0,1,4.68061,2.76146l14.96947,58.04816A3.847,3.847,0,0,1,434.99539,583.55569Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M863.63647,209.0517H487.31811a48.17928,48.17928,0,0,0-48.125,48.12512V699.05261a48.17924,48.17924,0,0,0,48.125,48.12507H863.63647a48.17924,48.17924,0,0,0,48.125-48.12507V257.17682A48.17928,48.17928,0,0,0,863.63647,209.0517Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M863.637,222.90589H487.31811a34.30948,34.30948,0,0,0-34.271,34.27093V699.05261a34.30947,34.30947,0,0,0,34.271,34.27088H863.637a34.30936,34.30936,0,0,0,34.27051-34.27088V257.17682A34.30937,34.30937,0,0,0,863.637,222.90589Z",transform:"translate(-208.9778 -99.05999)",fill:"#fff"}),g.exports.createElement("circle",{cx:694.19401,cy:614.02963,r:87.85039,fill:"#3182CE"}),g.exports.createElement("path",{d:"M945.18722,701.63087H914.63056V671.07421a11.45875,11.45875,0,0,0-22.9175,0v30.55666H861.1564a11.45875,11.45875,0,0,0,0,22.9175h30.55666V755.105a11.45875,11.45875,0,1,0,22.9175,0V724.54837h30.55666a11.45875,11.45875,0,0,0,0-22.9175Z",transform:"translate(-208.9778 -99.05999)",fill:"#fff"}),g.exports.createElement("path",{d:"M807.00068,465.71551H616.699a8.01412,8.01412,0,1,1,0-16.02823H807.00068a8.01412,8.01412,0,0,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M840.05889,492.76314H616.699a8.01412,8.01412,0,1,1,0-16.02823H840.05889a8.01411,8.01411,0,1,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M807.00068,586.929H616.699a8.01412,8.01412,0,1,1,0-16.02823H807.00068a8.01411,8.01411,0,0,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M840.05889,613.97661H616.699a8.01412,8.01412,0,1,1,0-16.02823H840.05889a8.01412,8.01412,0,1,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M574.07028,505.04162H506.72434a3.847,3.847,0,0,1-3.84278-3.84278V441.25158a3.847,3.847,0,0,1,3.84278-3.84278h67.34594a3.847,3.847,0,0,1,3.84278,3.84278v59.94726A3.847,3.847,0,0,1,574.07028,505.04162Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M574.07028,626.25509H506.72434a3.847,3.847,0,0,1-3.84278-3.84278V562.46505a3.847,3.847,0,0,1,3.84278-3.84278h67.34594a3.847,3.847,0,0,1,3.84278,3.84278v59.94726A3.847,3.847,0,0,1,574.07028,626.25509Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),g.exports.createElement("path",{d:"M807.21185,330.781H666.91017a8.01411,8.01411,0,0,1,0-16.02823H807.21185a8.01411,8.01411,0,0,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#ccc"}),g.exports.createElement("path",{d:"M840.27007,357.82862H666.91017a8.01411,8.01411,0,1,1,0-16.02822h173.3599a8.01411,8.01411,0,0,1,0,16.02822Z",transform:"translate(-208.9778 -99.05999)",fill:"#ccc"}),g.exports.createElement("path",{d:"M635.85911,390.6071H506.51316a3.847,3.847,0,0,1-3.84277-3.84277V285.81706a3.847,3.847,0,0,1,3.84277-3.84277H635.85911a3.847,3.847,0,0,1,3.84277,3.84277V386.76433A3.847,3.847,0,0,1,635.85911,390.6071Z",transform:"translate(-208.9778 -99.05999)",fill:"#ccc"})),Fa=t=>{if(!t)return null;const n=new Date(`${t}Z`);return Math.floor(n.getTime()/1e3)},Rr=({lastOnline:t})=>{const n=Math.floor(Date.now()/1e3),o=Fa(t);return!t||o===null?e(v,{border:"1px solid",borderColor:"gray.400",_dark:{borderColor:"gray.600"},className:"circle"}):n-o<=60?e(v,{bg:"green.300",_dark:{bg:"green.500"},className:"circle pulse green"}):e(v,{bg:"gray.400",_dark:{bg:"gray.600"},className:"circle"})},Wa=t=>{if(!t)return null;const n=new Date(t+"Z");return Math.floor(n.getTime()/1e3)},Lr=({lastOnline:t})=>{const n=Math.floor(Date.now()/1e3),o=Wa(t),s=o?n-o:null,a=o?Nt(o):{status:"",time:"Not Connected Yet"};return e(d,{display:"inline-block",fontSize:"xs",fontWeight:"medium",ml:"2",color:"gray.600",_dark:{color:"gray.400"},children:s&&s<=60?"Online":s?`${a.time} ago`:a.time})},Oa=w(Uo,{baseStyle:{w:4,h:4}}),Ha=w(Eo,{baseStyle:{w:4,h:4}}),Ar=5;function ja(t,n,o){if(o0&&(a[0]=0,a[1]="prev-more"),a[a.length-1]{const{filters:t,onFilterChange:n,users:{total:o}}=z(),{limit:s,offset:a}=t,i=(a||0)/(s||1),l=Math.ceil(o/(s||1)),m=ja(l,i,7),f=C=>{n({...t,offset:C*s})},x=C=>{n({...t,limit:parseInt(C.target.value)}),ls(C.target.value)},{t:b}=H();return r(k,{justifyContent:"space-between",mt:4,w:"full",display:"flex",columnGap:{lg:4,md:0},rowGap:{md:0,base:4},flexDirection:{md:"row",base:"column"},children:[e(v,{order:{base:2,md:1},children:r(k,{children:[r(Ne,{minW:"60px",value:s,onChange:x,size:"sm",rounded:"md",children:[e("option",{children:"10"}),e("option",{children:"20"}),e("option",{children:"30"})]}),e(d,{whiteSpace:"nowrap",fontSize:"sm",children:b("itemsPerPage")})]})}),r(Ro,{size:"sm",isAttached:!0,variant:"outline",order:{base:1,md:2},children:[e(F,{leftIcon:e(Oa,{}),onClick:f.bind(null,i-1),isDisabled:i===0||l===0,children:b("previous")}),m.map(C=>typeof C=="string"?e(F,{children:"..."},C):e(F,{variant:C===i?"solid":"outline",onClick:f.bind(null,C),children:C+1},C)),e(F,{rightIcon:e(Ha,{}),onClick:f.bind(null,i+1),isDisabled:i+1===l||l===0,children:b("next")})]})]})},jt=({expiryDate:t,status:n,compact:o=!1,showDetail:s=!0,extraText:a})=>{const{t:i}=H(),l=Nt(t),m=Oe[n].icon;return r(ie,{children:[r(R,{colorScheme:Oe[n].statusColor,rounded:"full",display:"inline-flex",px:3,py:1,columnGap:o?1:2,alignItems:"center",children:[e(m,{w:o?3:4}),s&&r(d,{textTransform:"capitalize",fontSize:o?".7rem":".875rem",lineHeight:o?"1rem":"1.25rem",fontWeight:"medium",letterSpacing:"tighter",children:[n&&i(`status.${n}`),a&&`: ${a}`]})]}),s&&t&&e(d,{display:"inline-block",fontSize:"xs",fontWeight:"medium",ml:"2",color:"gray.600",_dark:{color:"gray.400"},children:i(l.status,{time:l.time})})]})},$a=w(Pa),Xe={baseStyle:{w:{base:4,md:5},h:{base:4,md:5}}},Va=w(Lo,Xe),Ga=w(ln,Xe),Tr=w(Ao,Xe),Ya=w(qt,Xe),Za=w(rn,Xe),Qa=w(an,Xe),qa=w(ln,{baseStyle:{width:"15px",height:"15px"}}),Xa=t=>{for(var n=0;n{const{used:n,total:o,dataLimitResetStrategy:s,totalUsedTraffic:a}=t,i=o===0||o===null;return e(k,{justifyContent:"space-between",fontSize:"xs",fontWeight:"medium",color:"gray.600",_dark:{color:"gray.400"},children:r(d,{children:[ae(n)," /"," ",i?e(d,{as:"span",fontFamily:"system-ui",children:"\u221E"}):ae(o)]})})},Mr=t=>{const{used:n,total:o,dataLimitResetStrategy:s,totalUsedTraffic:a,...i}=t,l=o===0||o===null,m=!l&&n/o*100>=100;return r(ie,{children:[e(To,{orientation:"horizontal",value:l?100:Math.min(n/o*100,100),colorScheme:m?"red":"primary",...i,children:e(Mo,{h:"6px",borderRadius:"full",children:e(No,{borderRadius:"full"})})}),r(k,{justifyContent:"space-between",fontSize:"xs",fontWeight:"medium",color:"gray.600",_dark:{color:"gray.400"},children:[r(d,{children:[ae(n)," /"," ",l?e(d,{as:"span",fontFamily:"system-ui",children:"\u221E"}):ae(o)+(s&&s!=="no_reset"?" "+q("userDialog.resetStrategy"+Xa(s)):"")]}),r(d,{children:[q("usersTable.total"),": ",ae(a)]})]})]})},ut=({sort:t,column:n})=>t.includes(n)?e(qa,{transform:t.startsWith("-")?void 0:"rotate(180deg)"}):null,Ka=t=>{const{filters:n,users:{users:o},users:s,onEditingUser:a,onFilterChange:i}=z(),{t:l}=H(),[m,f]=g.exports.useState(void 0),x=We({base:120,lg:72})||72,[b,C]=g.exports.useState(`${x}px`),u=We({base:!1,md:!0});g.exports.useEffect(()=>{const p=()=>{const c=document.querySelectorAll("#filters")[0];C(`${c.offsetHeight}px`)};window.addEventListener("scroll",p)},[]);const h=o.length!==s.total,_=p=>{let c=n.sort;c.includes(p)?c.startsWith("-")?c="-created_at":c="-"+p:c=p,i({sort:c})},S=p=>{i({status:p.target.value.length>0?p.target.value:void 0})},A=p=>{f(p===m?void 0:p)};return r(v,{id:"users-table",overflowX:{base:"unset",md:"unset"},children:[e(yt,{allowMultiple:!0,display:{base:"block",md:"none"},index:m,children:r(xr,{orientation:"vertical",zIndex:"docked",...t,children:[e(yr,{zIndex:"docked",position:"relative",children:r(Be,{children:[e(Le,{position:"sticky",top:b,minW:"120px",pl:4,pr:4,cursor:"pointer",onClick:_.bind(null,"username"),children:r(k,{children:[e("span",{children:l("users")}),e(ut,{sort:n.sort,column:"username"})]})}),e(Le,{position:"sticky",top:b,minW:"50px",pl:0,pr:0,w:"140px",cursor:"pointer",children:r(k,{spacing:0,position:"relative",children:[r(d,{position:"absolute",_dark:{bg:"gray.750"},_light:{bg:"#F9FAFB"},userSelect:"none",pointerEvents:"none",zIndex:1,w:"100%",children:[l("usersTable.status"),n.status?": "+n.status:""]}),r(Ne,{value:n.sort,fontSize:"xs",fontWeight:"extrabold",textTransform:"uppercase",cursor:"pointer",p:0,border:0,h:"auto",w:"auto",icon:e(ie,{}),_focusVisible:{border:"0 !important"},onChange:S,children:[e("option",{}),e("option",{children:"active"}),e("option",{children:"on_hold"}),e("option",{children:"disabled"}),e("option",{children:"limited"}),e("option",{children:"expired"})]})]})}),e(Le,{position:"sticky",top:b,minW:"100px",cursor:"pointer",pr:0,onClick:_.bind(null,"used_traffic"),children:r(k,{children:[e("span",{children:l("usersTable.dataUsage")}),e(ut,{sort:n.sort,column:"used_traffic"})]})}),e(Le,{position:"sticky",top:b,minW:"32px",w:"32px",p:0,cursor:"pointer"})]})}),e(Sr,{children:!u&&(o==null?void 0:o.map((p,c)=>r(g.exports.Fragment,{children:[r(Be,{onClick:A.bind(null,c),cursor:"pointer",children:[e(xe,{borderBottom:0,minW:"100px",pl:4,pr:4,maxW:"calc(100vw - 50px - 32px - 100px - 48px)",children:r("div",{className:"flex-status",children:[e(Rr,{lastOnline:p.online_at}),e(d,{isTruncated:!0,children:p.username})]})}),e(xe,{borderBottom:0,minW:"50px",pl:0,pr:0,children:e(jt,{compact:!0,showDetail:!1,expiryDate:p.expire,status:p.status})}),e(xe,{borderBottom:0,minW:"100px",pr:0,children:e(Ja,{totalUsedTraffic:p.lifetime_used_traffic,dataLimitResetStrategy:p.data_limit_reset_strategy,used:p.used_traffic,total:p.data_limit,colorScheme:Oe[p.status].bandWidthColor})}),e(xe,{p:0,borderBottom:0,w:"32px",minW:"32px",children:e(Ga,{color:"gray.600",_dark:{color:"gray.400"},transition:"transform .2s ease-out",transform:m===c?"rotate(180deg)":"0deg"})})]}),e(Be,{className:"collapsible",onClick:A.bind(null,c),children:e(xe,{p:0,colSpan:4,children:r(Ge,{border:0,children:[e(Ye,{display:"none"}),e(Ze,{border:0,cursor:"pointer",px:6,py:3,children:r(P,{justifyContent:"space-between",spacing:"4",children:[r(P,{alignItems:"flex-start",w:"full",spacing:-1,children:[e(d,{textTransform:"capitalize",fontSize:"xs",fontWeight:"bold",color:"gray.600",_dark:{color:"gray.400"},children:l("usersTable.dataUsage")}),e(v,{width:"full",minW:"230px",children:e(Mr,{totalUsedTraffic:p.lifetime_used_traffic,dataLimitResetStrategy:p.data_limit_reset_strategy,used:p.used_traffic,total:p.data_limit,colorScheme:Oe[p.status].bandWidthColor})})]}),r(k,{w:"full",justifyContent:"space-between",children:[r(v,{width:"full",children:[e(jt,{compact:!0,expiryDate:p.expire,status:p.status}),e(Lr,{lastOnline:p.online_at})]}),r(k,{children:[e(Nr,{user:p}),e(re,{label:l("userDialog.editUser"),placement:"top",children:e(V,{p:"0 !important","aria-label":"Edit user",bg:"transparent",_dark:{_hover:{bg:"gray.700"}},size:{base:"sm",md:"md"},onClick:E=>{E.stopPropagation(),a(p)},children:e(Qa,{})})})]})]})]})})]})})})]},p.username)))})]})}),r(xr,{orientation:"vertical",display:{base:"none",md:"table"},...t,children:[e(yr,{zIndex:"docked",position:"relative",children:r(Be,{children:[e(Le,{position:"sticky",top:{base:"unset",md:b},minW:"140px",cursor:"pointer",onClick:_.bind(null,"username"),children:r(k,{children:[e("span",{children:l("username")}),e(ut,{sort:n.sort,column:"username"})]})}),e(Le,{position:"sticky",top:{base:"unset",md:b},width:"400px",minW:"150px",cursor:"pointer",children:r(k,{position:"relative",gap:"5px",children:[r(d,{_dark:{bg:"gray.750"},_light:{bg:"#F9FAFB"},userSelect:"none",pointerEvents:"none",zIndex:1,children:[l("usersTable.status"),n.status?": "+n.status:""]}),e(d,{children:"/"}),e(ut,{sort:n.sort,column:"expire"}),e(k,{onClick:_.bind(null,"expire"),children:e(d,{children:"Sort by expire"})}),r(Ne,{fontSize:"xs",fontWeight:"extrabold",textTransform:"uppercase",cursor:"pointer",position:"absolute",p:0,left:"-40px",border:0,h:"auto",w:"auto",icon:e(ie,{}),_focusVisible:{border:"0 !important"},value:n.sort,onChange:S,children:[e("option",{}),e("option",{children:"active"}),e("option",{children:"on_hold"}),e("option",{children:"disabled"}),e("option",{children:"limited"}),e("option",{children:"expired"})]})]})}),e(Le,{position:"sticky",top:{base:"unset",md:b},width:"350px",minW:"230px",cursor:"pointer",onClick:_.bind(null,"used_traffic"),children:r(k,{children:[e("span",{children:l("usersTable.dataUsage")}),e(ut,{sort:n.sort,column:"used_traffic"})]})}),e(Le,{position:"sticky",top:{base:"unset",md:b},width:"200px",minW:"180px"})]})}),r(Sr,{children:[u&&(o==null?void 0:o.map((p,c)=>r(Be,{className:bt("interactive",{"last-row":c===o.length-1}),onClick:()=>a(p),children:[e(xe,{minW:"140px",children:r("div",{className:"flex-status",children:[e(Rr,{lastOnline:p.online_at}),p.username,e(Lr,{lastOnline:p.online_at})]})}),e(xe,{width:"400px",minW:"150px",children:e(jt,{expiryDate:p.expire,status:p.status})}),e(xe,{width:"350px",minW:"230px",children:e(Mr,{totalUsedTraffic:p.lifetime_used_traffic,dataLimitResetStrategy:p.data_limit_reset_strategy,used:p.used_traffic,total:p.data_limit,colorScheme:Oe[p.status].bandWidthColor})}),e(xe,{width:"200px",minW:"180px",children:e(Nr,{user:p})})]},p.username))),o.length==0&&e(Be,{children:e(xe,{colSpan:4,children:e(ei,{isFiltered:h})})})]})]}),e(Ba,{})]})},Nr=({user:t})=>{const{setQRCode:n,setSubLink:o}=z(),s=t.links.join(`\r +`),[a,i]=g.exports.useState([-1,!1]);return g.exports.useEffect(()=>{a[1]&&setTimeout(()=>{i([-1,!1])},1e3)},[a]),r(k,{justifyContent:"flex-end",onClick:l=>{l.preventDefault(),l.stopPropagation()},children:[e(wr,{text:t.subscription_url.startsWith("/")?window.location.origin+t.subscription_url:t.subscription_url,onCopy:()=>{i([0,!0])},children:e("div",{children:e(re,{label:a[0]==0&&a[1]?q("usersTable.copied"):q("usersTable.copyLink"),placement:"top",children:e(V,{p:"0 !important","aria-label":"copy subscription link",bg:"transparent",_dark:{_hover:{bg:"gray.700"}},size:{base:"sm",md:"md"},children:a[0]==0&&a[1]?e(Tr,{}):e(Ya,{})})})})}),e(wr,{text:s,onCopy:()=>{i([1,!0])},children:e("div",{children:e(re,{label:a[0]==1&&a[1]?q("usersTable.copied"):q("usersTable.copyConfigs"),placement:"top",children:e(V,{p:"0 !important","aria-label":"copy configs",bg:"transparent",_dark:{_hover:{bg:"gray.700"}},size:{base:"sm",md:"md"},children:a[0]==1&&a[1]?e(Tr,{}):e(Va,{})})})})}),e(re,{label:"QR Code",placement:"top",children:e(V,{p:"0 !important","aria-label":"qr code",bg:"transparent",_dark:{_hover:{bg:"gray.700"}},size:{base:"sm",md:"md"},onClick:()=>{n(t.links),o(t.subscription_url)},children:e(Za,{})})})]})},ei=({isFiltered:t})=>{const{onCreateUser:n}=z();return r(v,{padding:"5",py:"8",display:"flex",alignItems:"center",flexDirection:"column",gap:4,w:"full",children:[e($a,{maxHeight:"200px",maxWidth:"200px",_dark:{'path[fill="#fff"]':{fill:"gray.800"},'path[fill="#f2f2f2"], path[fill="#e6e6e6"], path[fill="#ccc"]':{fill:"gray.700"},'circle[fill="#3182CE"]':{fill:"primary.300"}},_light:{'path[fill="#f2f2f2"], path[fill="#e6e6e6"], path[fill="#ccc"]':{fill:"gray.300"},'circle[fill="#3182CE"]':{fill:"primary.500"}}}),e(d,{fontWeight:"medium",color:"gray.600",_dark:{color:"gray.400"},children:t?q("usersTable.noUserMatched"):q("usersTable.noUser")}),!t&&e(F,{size:"sm",colorScheme:"primary",onClick:()=>n(!0),children:q("createUser")})]})},ti=()=>(g.exports.useEffect(()=>{z.getState().refetchUsers(),ds()},[]),r(P,{justifyContent:"space-between",minH:"100vh",p:"6",rowGap:4,children:[r(v,{w:"full",children:[e(js,{}),e(as,{mt:"4"}),e(Is,{}),e(Ka,{}),e(Na,{}),e(ws,{}),e(ya,{}),e(ra,{}),e(_a,{}),e(Ia,{}),e(ha,{}),e(ga,{}),e(wa,{}),e(Ss,{})]}),e(mn,{})]})),ri=t=>g.exports.createElement("svg",{viewBox:"0 0 747 747",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t},g.exports.createElement("path",{d:"M746.671 209.652V77.6572C746.671 72.9384 743.827 68.6832 739.468 66.8811C735.108 65.0738 730.093 66.0739 726.754 69.4072L579.354 216.807C577.453 202.386 570.203 189.203 559.037 179.87C547.875 170.542 533.615 165.744 519.083 166.432C504.551 167.12 490.807 173.24 480.573 183.583L414.375 249.776C412.417 235.391 405.141 222.25 393.985 212.959C382.823 203.662 368.594 198.88 354.083 199.552C339.578 200.224 325.849 206.302 315.594 216.588L274.343 257.828L19.9167 3.41515C16.5781 0.0818157 11.5625 -0.918184 7.20306 0.889149C2.84373 2.69648 0 6.94648 0 11.6651V143.649C0 146.743 1.22917 149.712 3.41667 151.899L191.843 340.339L3.41667 528.753C1.2292 530.94 0 533.909 0 537.003V668.997C0 673.716 2.84373 677.971 7.20306 679.773C11.5624 681.581 16.578 680.58 19.9167 677.247L167.317 529.847C169.285 544.233 176.561 557.358 187.718 566.65C198.869 575.947 213.098 580.728 227.603 580.066C242.103 579.404 255.838 573.342 266.098 563.071L332.295 496.874V496.879C334.259 511.264 341.535 524.395 352.691 533.686C363.853 542.977 378.082 547.759 392.587 547.092C407.093 546.421 420.822 540.348 431.077 530.066L472.327 488.826L726.754 743.239C728.941 745.427 731.91 746.656 735.004 746.656C736.535 746.661 738.056 746.359 739.473 745.77C743.832 743.963 746.671 739.708 746.671 734.989V602.994C746.671 599.901 745.442 596.932 743.254 594.744L554.827 406.318L743.254 217.904H743.259C745.447 215.717 746.676 212.748 746.676 209.654L746.671 209.652ZM23.3373 39.8118L257.844 274.318L208.328 323.818L23.3413 138.818L23.3373 39.8118ZM723.337 706.825L488.831 472.318L538.347 422.818L723.333 607.818L723.337 706.825ZM23.3373 541.825L332.097 233.078C338.764 226.719 347.624 223.172 356.843 223.172C366.056 223.172 374.916 226.719 381.588 233.078C388.151 239.641 391.838 248.548 391.838 257.828C391.838 267.114 388.151 276.016 381.588 282.577L23.3347 640.831L23.3373 541.825ZM249.604 546.575C240.755 555.419 227.864 558.872 215.781 555.638C203.703 552.398 194.265 542.961 191.027 530.883C187.792 518.8 191.245 505.91 200.089 497.06L497.076 200.074C505.92 191.23 518.811 187.772 530.893 191.011C542.971 194.246 552.409 203.678 555.648 215.76C558.888 227.839 555.434 240.73 546.591 249.572L249.604 546.575ZM723.337 204.815L414.577 513.562C407.911 519.926 399.051 523.473 389.832 523.473C380.618 523.473 371.753 519.926 365.087 513.562C358.529 506.999 354.842 498.098 354.842 488.816C354.842 479.535 358.529 470.634 365.087 464.071L723.34 105.818L723.337 204.815Z",fill:"currentColor"})),ni=y.object({username:y.string().min(1,"login.fieldRequired"),password:y.string().min(1,"login.fieldRequired")}),oi=w(ri,{baseStyle:{strokeWidth:"10px",w:12,h:12}}),si=w(Po,{baseStyle:{w:5,h:5,strokeWidth:"2px"}}),Pr=()=>{var C,u;const[t,n]=g.exports.useState(""),[o,s]=g.exports.useState(!1),a=Fo(),{t:i}=H();let l=Wo();const{register:m,formState:{errors:f},handleSubmit:x}=qe({resolver:xt(ni)});g.exports.useEffect(()=>{Ko(),l.pathname!=="/login"&&a("/login",{replace:!0})},[]);const b=h=>{n("");const _=new FormData;_.append("username",h.username),_.append("password",h.password),_.append("grant_type","password"),s(!0),O("/admin/token",{method:"post",body:_}).then(({access_token:S})=>{Jo(S),a("/")}).catch(S=>{n(S.response._data.detail)}).finally(s.bind(null,!1))};return r(P,{justifyContent:"space-between",minH:"100vh",p:"6",w:"full",children:[r(v,{w:"full",children:[e(k,{justifyContent:"end",w:"full",children:e(gn,{})}),e(k,{w:"full",justifyContent:"center",alignItems:"center",children:r(v,{w:"full",maxW:"340px",mt:"6",children:[r(P,{alignItems:"center",w:"full",children:[e(oi,{}),e(d,{fontSize:"2xl",fontWeight:"semibold",children:i("login.loginYourAccount")}),e(d,{color:"gray.600",_dark:{color:"gray.400"},children:i("login.welcomeBack")})]}),e(v,{w:"full",maxW:"300px",m:"auto",pt:"4",children:e("form",{onSubmit:x(b),children:r(P,{mt:4,rowGap:2,children:[e(L,{children:e(Me,{w:"full",placeholder:i("username"),...m("username"),error:i((C=f==null?void 0:f.username)==null?void 0:C.message)})}),e(L,{children:e(Me,{w:"full",type:"password",placeholder:i("password"),...m("password"),error:i((u=f==null?void 0:f.password)==null?void 0:u.message)})}),t&&r(gt,{status:"error",rounded:"md",children:[e(Ut,{}),e(Xr,{children:t})]}),r(F,{isLoading:o,type:"submit",w:"full",colorScheme:"primary",children:[e(si,{marginRight:1}),i("login")]})]})})})]})})]}),e(mn,{})]})},ai=()=>O("/admin",{headers:{Authorization:`Bearer ${Et()}`}}),ii=Oo([{path:"/",element:e(ti,{}),errorElement:e(Pr,{}),loader:ai},{path:"/login/",element:e(Pr,{})}]);function li(){return e("main",{className:"p-8",children:e(Ho,{router:ii})})}$.extend(jo);$.extend(Bo);$.extend($o);$.extend(Vo);$.extend(Go);cn(Yo.get()||"light");Zo.createRoot(document.getElementById("root")).render(e($t.StrictMode,{children:e(Qo,{theme:Xo,children:e(qo,{client:Gt,children:e(li,{})})})})); diff --git a/app/dashboard/build/statics/index.8d48a3d3.js b/app/dashboard/build/statics/index.8d48a3d3.js deleted file mode 100644 index 77712d401..000000000 --- a/app/dashboard/build/statics/index.8d48a3d3.js +++ /dev/null @@ -1,14 +0,0 @@ -import{i as Bt,B as gn,a as fn,b as bn,j as Tr,d as $,U as Qt,z as xn,r as yn,f as Sn,Q as wn,e as Cn,$ as _n,c as Lt,g as S,h as kn,C as In,k as At,u as Tt,l as H,m as r,H as _,n as e,T as d,o as vn,p as v,s as Dn,q as f,t as Ze,J as zn,v as y,w as Mr,A as Mt,x as Un,y as En,M as ce,D as de,E as he,F as ue,G as pe,I as we,K as Qe,L as Nr,N as Rn,O as mt,P as me,R as L,S as B,V as Pr,W as re,X as E,Y as ye,Z as V,_ as Ne,a0 as Pe,a1 as P,a2 as bt,a3 as lt,a4 as Ln,a5 as Te,a6 as He,a7 as An,a8 as Fr,a9 as Wr,aa as ut,ab as It,ac as Tn,ad as $e,ae as vt,af as lr,ag as Mn,ah as Or,ai as Hr,aj as jr,ak as Se,al as Nn,am as Pn,an as Fn,ao as Wn,ap as On,aq as qt,ar as Br,as as $r,at as ie,au as cr,av as Hn,aw as jn,ax as Bn,ay as $t,az as $n,aA as Vn,aB as Gn,aC as Yn,aD as Zn,aE as Qn,aF as Dt,aG as qn,aH as Xn,aI as Jn,aJ as Kn,aK as eo,aL as xt,aM as Vr,aN as yt,aO as N,aP as Xt,aQ as to,aR as Ve,aS as Ge,aT as Vt,aU as Ye,aV as ro,aW as Ie,aX as ve,aY as De,aZ as ze,a_ as Ue,a$ as Ee,b0 as dr,b1 as no,b2 as zt,b3 as pt,b4 as Jt,b5 as oo,b6 as so,b7 as ao,b8 as Gr,b9 as io,ba as gt,bb as Ut,bc as Yr,bd as lo,be as co,bf as Zr,bg as We,bh as ho,bi as uo,bj as po,bk as Kt,bl as Pt,bm as hr,bn as Qr,bo as mo,bp as go,bq as ur,br as fo,bs as pr,bt as qr,bu as bo,bv as Xr,bw as xo,bx as yo,by as Jr,bz as So,bA as wo,bB as Kr,bC as en,bD as tn,bE as q,bF as Co,bG as rn,bH as Ft,bI as _o,bJ as ko,bK as Io,bL as vo,bM as Do,bN as zo,bO as nn,bP as Uo,bQ as mr,bR as gr,bS as Be,bT as Le,bU as fr,bV as be,bW as br,bX as Eo,bY as Ro,bZ as Lo,b_ as Ao,b$ as To,c0 as Mo,c1 as No,c2 as Po,c3 as Fo,c4 as Wo,c5 as Oo,c6 as Ho,c7 as jo,c8 as Bo,c9 as $o,ca as Vo,cb as Go}from"./vendor.3f3f0bc0.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function o(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerpolicy&&(i.referrerPolicy=a.referrerpolicy),a.crossorigin==="use-credentials"?i.credentials="include":a.crossorigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(a){if(a.ep)return;a.ep=!0;const i=o(a);fetch(a.href,i)}})();Bt.use(gn).use(fn).use(bn).init({debug:{}.NODE_ENV==="development",returnNull:!1,fallbackLng:"en",interpolation:{escapeValue:!1},react:{useSuspense:!1},load:"languageOnly",detection:{caches:["localStorage","sessionStorage","cookie"]},backend:{loadPath:Tr(["/","statics/locales/{{lng}}.json"])}},function(t,n){$.locale(Bt.language)});Bt.on("languageChanged",t=>{$.locale(t)});Qt("zh-cn",xn);Qt("ru",yn);Qt("fa",Sn);const Gt=new wn,on=t=>{const n=document.querySelector('meta[name="theme-color"]');n==null||n.setAttribute("content",t=="dark"?"#1A202C":"#3B81F6")},Yo=Cn({shadows:{outline:"0 0 0 2px var(--chakra-colors-primary-200)"},fonts:{body:"Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif"},colors:{"light-border":"#d2d2d4",primary:{50:"#9cb7f2",100:"#88a9ef",200:"#749aec",300:"#618ce9",400:"#4d7de7",500:"#396fe4",600:"#3364cd",700:"#2e59b6",800:"#284ea0",900:"#224389"},gray:{750:"#222C3B"}},components:{Alert:{baseStyle:{container:{borderRadius:"6px",fontSize:"sm"}}},Select:{baseStyle:{field:{_dark:{borderColor:"gray.600",borderRadius:"6px"},_light:{borderRadius:"6px"}}}},FormHelperText:{baseStyle:{fontSize:"xs"}},FormLabel:{baseStyle:{fontSize:"sm",fontWeight:"medium",mb:"1",_dark:{color:"gray.300"}}},Input:{baseStyle:{addon:{_dark:{borderColor:"gray.600",_placeholder:{color:"gray.500"}}},field:{_focusVisible:{boxShadow:"none",borderColor:"primary.200",outlineColor:"primary.200"},_dark:{borderColor:"gray.600",_disabled:{color:"gray.400",borderColor:"gray.500"},_placeholder:{color:"gray.500"}}}}},Table:{baseStyle:{table:{borderCollapse:"separate",borderSpacing:0},thead:{borderBottomColor:"light-border"},th:{background:"#F9FAFB",borderColor:"light-border !important",borderBottomColor:"light-border !important",borderTop:"1px solid ",borderTopColor:"light-border !important",_first:{borderLeft:"1px solid",borderColor:"light-border !important"},_last:{borderRight:"1px solid",borderColor:"light-border !important"},_dark:{borderColor:"gray.600 !important",background:"gray.750"}},td:{transition:"all .1s ease-out",borderColor:"light-border",borderBottomColor:"light-border !important",_first:{borderLeft:"1px solid",borderColor:"light-border",_dark:{borderColor:"gray.600"}},_last:{borderRight:"1px solid",borderColor:"light-border",_dark:{borderColor:"gray.600"}},_dark:{borderColor:"gray.600",borderBottomColor:"gray.600 !important"}},tr:{"&.interactive":{cursor:"pointer",_hover:{"& > td":{bg:"gray.200"},_dark:{"& > td":{bg:"gray.750"}}}},_last:{"& > td":{_first:{borderBottomLeftRadius:"8px"},_last:{borderBottomRightRadius:"8px"}}}}}}}});const Et=()=>localStorage.getItem("token"),Zo=t=>{localStorage.setItem("token",t)},Qo=()=>{localStorage.removeItem("token")},qo=_n.create({baseURL:"/api/"}),Xo=(t,n={})=>(Et()&&(n.headers={...(n==null?void 0:n.headers)||{},Authorization:`Bearer ${Et()}`}),qo(t,n)),O=Xo,Jo=Lt(t=>({isLoading:!0,isPostLoading:!1,version:null,started:!1,logs_websocket:null,config:"",fetchCoreSettings:()=>{t({isLoading:!0}),Promise.all([O("/core").then(({version:n,started:o,logs_websocket:s})=>t({version:n,started:o,logs_websocket:s})),O("/core/config").then(n=>t({config:n}))]).finally(()=>t({isLoading:!1}))},updateConfig:n=>(t({isPostLoading:!0}),O("/core/config",{method:"PUT",body:n}).finally(()=>{t({isPostLoading:!1})})),restartCore:()=>O("/core/restart",{method:"POST"})}));function ae(t,n=2,o=!1){if(!+t)return"0 B";const s=1024,a=n<0?0:n,i=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],l=Math.floor(Math.log(t)/Math.log(s));return o?[parseFloat((t/Math.pow(s,l)).toFixed(a)),i[l]]:`${parseFloat((t/Math.pow(s,l)).toFixed(a))} ${i[l]}`}const xr=t=>{if(t!==null)return t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")},Ko=S(kn,{baseStyle:{w:5,h:5,position:"relative",zIndex:"2"}}),es=S(In,{baseStyle:{w:5,h:5,position:"relative",zIndex:"2"}}),ts=S(At,{baseStyle:{w:5,h:5,position:"relative",zIndex:"2"}}),Wt=({title:t,content:n,icon:o})=>r(vn,{p:6,borderWidth:"1px",borderColor:"light-border",bg:"#F9FAFB",_dark:{borderColor:"gray.600",bg:"gray.750"},borderStyle:"solid",boxShadow:"none",borderRadius:"12px",width:"full",display:"flex",justifyContent:"space-between",flexDirection:"row",children:[r(_,{alignItems:"center",columnGap:"4",children:[e(v,{p:"2",position:"relative",color:"white",_before:{content:'""',position:"absolute",top:0,left:0,bg:"primary.400",display:"block",w:"full",h:"full",borderRadius:"5px",opacity:".5",z:"1"},_after:{content:'""',position:"absolute",top:"-5px",left:"-5px",bg:"primary.400",display:"block",w:"calc(100% + 10px)",h:"calc(100% + 10px)",borderRadius:"8px",opacity:".4",z:"1"},children:o}),e(d,{color:"gray.600",_dark:{color:"gray.300"},fontWeight:"medium",textTransform:"capitalize",fontSize:"sm",children:t})]}),e(v,{fontSize:"3xl",fontWeight:"semibold",mt:"2",children:n})]}),Yt="statistics-query-key",rs=t=>{const{version:n}=z(),{data:o}=Tt({queryKey:Yt,queryFn:()=>O("/system"),refetchInterval:5e3,onSuccess:({version:a})=>{n!==a&&z.setState({version:a})}}),{t:s}=H();return r(_,{justifyContent:"space-between",gap:0,columnGap:{lg:4,md:0},rowGap:{lg:0,base:4},display:"flex",flexDirection:{lg:"row",base:"column"},...t,children:[e(Wt,{title:s("activeUsers"),content:o&&r(_,{alignItems:"flex-end",children:[e(d,{children:xr(o.users_active)}),r(d,{fontWeight:"normal",fontSize:"lg",as:"span",display:"inline-block",pb:"5px",children:["/ ",xr(o.total_user)]})]}),icon:e(Ko,{})}),e(Wt,{title:s("dataUsage"),content:o&&ae(o.incoming_bandwidth+o.outgoing_bandwidth),icon:e(es,{})}),e(Wt,{title:s("memoryUsage"),content:o&&r(_,{alignItems:"flex-end",children:[e(d,{children:ae(o.mem_used,1,!0)[0]}),r(d,{fontWeight:"normal",fontSize:"lg",as:"span",display:"inline-block",pb:"5px",children:[ae(o.mem_used,1,!0)[1]," /"," ",ae(o.mem_total,1)]})]}),icon:e(ts,{})})]})},sn="marzban-num-users-per-page",yr=10,ns=()=>{const t=localStorage.getItem(sn)||yr.toString();return parseInt(t)||yr},os=t=>localStorage.setItem(sn,t),ss=t=>{for(const n in t)t[n]||delete t[n];return z.setState({loading:!0}),O("/users",{query:t}).then(n=>(z.setState({users:n}),n)).finally(()=>{z.setState({loading:!1})})},as=()=>O("/inbounds").then(t=>{z.setState({inbounds:new Map(Object.entries(t))})}).finally(()=>{z.setState({loading:!1})}),z=Lt(Dn((t,n)=>({version:null,editingUser:null,deletingUser:null,isCreatingNewUser:!1,QRcodeLinks:null,subscribeUrl:null,users:{users:[],total:0},loading:!0,isResetingAllUsage:!1,isEditingHosts:!1,isEditingNodes:!1,isShowingNodesUsage:!1,resetUsageUser:null,revokeSubscriptionUser:null,filters:{username:"",limit:ns(),sort:"-created_at"},inbounds:new Map,isEditingCore:!1,refetchUsers:()=>{ss(n().filters)},resetAllUsage:()=>O("/users/reset",{method:"POST"}).then(()=>{n().onResetAllUsage(!1),n().refetchUsers()}),onResetAllUsage:o=>t({isResetingAllUsage:o}),onCreateUser:o=>t({isCreatingNewUser:o}),onEditingUser:o=>{t({editingUser:o})},onDeletingUser:o=>{t({deletingUser:o})},onFilterChange:o=>{t({filters:{...n().filters,...o}}),n().refetchUsers()},setQRCode:o=>{t({QRcodeLinks:o})},deleteUser:o=>(t({editingUser:null}),O(`/user/${o.username}`,{method:"DELETE"}).then(()=>{t({deletingUser:null}),n().refetchUsers(),Gt.invalidateQueries(Yt)})),createUser:o=>O("/user",{method:"POST",body:o}).then(()=>{t({editingUser:null}),n().refetchUsers(),Gt.invalidateQueries(Yt)}),editUser:o=>O(`/user/${o.username}`,{method:"PUT",body:o}).then(()=>{n().onEditingUser(null),n().refetchUsers()}),fetchUserUsage:(o,s)=>{for(const a in s)s[a]||delete s[a];return O(`/user/${o.username}/usage`,{method:"GET",query:s})},onEditingHosts:o=>{t({isEditingHosts:o})},onEditingNodes:o=>{t({isEditingNodes:o})},onShowingNodesUsage:o=>{t({isShowingNodesUsage:o})},setSubLink:o=>{t({subscribeUrl:o})},resetDataUsage:o=>O(`/user/${o.username}/reset`,{method:"POST"}).then(()=>{t({resetUsageUser:null}),n().refetchUsers()}),revokeSubscription:o=>O(`/user/${o.username}/revoke_sub`,{method:"POST"}).then(s=>{t({revokeSubscriptionUser:null,editingUser:s}),n().refetchUsers()})}))),ge=({children:t,color:n})=>e(v,{position:"relative",width:"36px",height:"36px",display:"flex",justifyContent:"center",alignItems:"center",_before:{content:'""',display:"block",position:"absolute",top:"0",left:"0",width:"calc(100%)",height:"calc(100%)",bg:`${n}.400`,opacity:".5",borderRadius:"5px",zIndex:"1",_dark:{bg:`${n}.400`}},_after:{content:'""',display:"block",position:"absolute",top:"0",left:"0",width:"calc(100% + 10px)",height:"calc(100% + 10px)",transform:"translate(-5px, -5px)",bg:`${n}.400`,opacity:".4",borderRadius:"8px",zIndex:"1",_dark:{bg:`${n}.400`}},children:e(d,{color:`${n}.500`,_dark:{color:`${n}.900`},position:"relative",zIndex:"2",children:t})});window.ace.define("ace/theme/nord_dark",["require","exports","module","ace/lib/dom"],(t,n,o)=>{n.isDark=!0,n.cssClass="ace-nord-dark",t("../lib/dom").importCssString(n.cssText,n.cssClass)});window.ace.define("ace/theme/dawn",["require","exports","module","ace/lib/dom"],(t,n,o)=>{n.isDark=!1,n.cssClass="ace-dawn",t("../lib/dom").importCssString(n.cssText,n.cssClass)});const is=f.exports.forwardRef(({json:t,onChange:n,mode:o="code"},s)=>{const{colorMode:a}=Ze(),i={mode:o,onChangeText:n,statusBar:!1,mainMenuBar:!1,theme:a==="dark"?"ace/theme/nord_dark":"ace/theme/dawn"},l=f.exports.useRef(null),p=f.exports.useRef(null);return f.exports.useEffect(()=>(p.current=new zn(l.current,i),()=>{p.current&&p.current.destroy()}),[]),f.exports.useEffect(()=>{p.current&&p.current.update(t)},[t]),e(v,{ref:s,border:"1px solid",borderColor:"gray.300",_dark:{borderColor:"gray.500"},borderRadius:5,h:"full",children:e(v,{height:"full",ref:l})})}),an=y.object({name:y.string().min(1),address:y.string().min(1),port:y.number().min(1).or(y.string().transform(t=>parseFloat(t))),api_port:y.number().min(1).or(y.string().transform(t=>parseFloat(t))),xray_version:y.string().nullable().optional(),id:y.number().nullable().optional(),status:y.enum(["connected","connecting","error","disabled"]).nullable().optional(),message:y.string().nullable().optional(),add_as_new_host:y.boolean().optional(),usage_coefficient:y.number().or(y.string().transform(t=>parseFloat(t)))}),ls=()=>({name:"",address:"",port:62050,api_port:62051,xray_version:"",usage_coefficient:1}),ft="fetch-nodes-query-key",ln=()=>{const{isEditingNodes:t}=z();return Tt({queryKey:ft,queryFn:St.getState().fetchNodes,refetchInterval:t?3e3:void 0,refetchOnWindowFocus:!1})},St=Lt((t,n)=>({nodes:[],addNode(o){return O("/node",{method:"POST",body:o})},fetchNodes(){return O("/nodes")},fetchNodesUsage(o){return O("/nodes/usage",{query:o})},updateNode(o){return O(`/node/${o.id}`,{method:"PUT",body:o})},setDeletingNode(o){t({deletingNode:o})},reconnectNode(o){return O(`/node/${o.id}/reconnect`,{method:"POST"})},deleteNode:()=>{var o;return O(`/node/${(o=n().deletingNode)==null?void 0:o.id}`,{method:"DELETE"})}})),Sr=500,cs=S(Mr,{baseStyle:{w:5,h:5}}),ds=S(Mt,{baseStyle:{w:4,h:4}}),hs=S(Un,{baseStyle:{w:4,h:4}}),us=S(En,{baseStyle:{w:3,h:3}}),ps=t=>({[lt.ReadyState.CONNECTING]:"connecting",[lt.ReadyState.OPEN]:"connected",[lt.ReadyState.CLOSING]:"closed",[lt.ReadyState.CLOSED]:"closed",[lt.ReadyState.UNINSTANTIATED]:"closed"})[t],ms=t=>{try{let n=new URL("/api/".startsWith("/")?window.location.origin+"/api/":"/api/");return(n.protocol==="https:"?"wss://":"ws://")+Tr([n.host+n.pathname,t?`/node/${t}/logs`:"/core/logs"])+"?interval=1&token="+Et()}catch(n){return console.error("Unable to generate websocket url"),console.error(n),null}};let Fe=[];const gs=()=>{const{colorMode:t}=Ze(),{data:n}=ln(),o=!1,[s,a]=f.exports.useState(""),i=(R,K)=>{R!==s&&(R==="host"?(a(""),A([])):(a(R),A([])))},{isEditingCore:l}=z(),{fetchCoreSettings:p,updateConfig:g,isLoading:w,config:x,isPostLoading:b,version:h,restartCore:m}=Jo(),I=f.exports.useRef(null),[C,A]=f.exports.useState([]),{t:u}=H(),c=we(),F=Qe({defaultValues:{config:x||{}}});f.exports.useEffect(()=>{x&&F.setValue("config",x)},[x]),f.exports.useEffect(()=>{l&&p()},[l]);const j=f.exports.useRef(!0),D=f.exports.useCallback(Nr(R=>{var le,J,_e;const K=Math.abs((((le=I.current)==null?void 0:le.scrollTop)||0)-(((J=I.current)==null?void 0:J.scrollHeight)||0)+(((_e=I.current)==null?void 0:_e.offsetHeight)||0))<10;I.current&&K?j.current=!0:j.current=!1,R.length<40&&A(R)},300),[]),{readyState:M}=Rn(ms(s),{onMessage:R=>{Fe.push(R.data),Fe.length>Sr&&(Fe=Fe.splice(0,Fe.length-Sr)),D([...Fe])},shouldReconnect:()=>!0,reconnectAttempts:10,reconnectInterval:1e3});f.exports.useEffect(()=>{var R;I.current&&j.current&&(I.current.scrollTop=(R=I.current)==null?void 0:R.scrollHeight)},[C]),f.exports.useEffect(()=>()=>{Fe=[]},[]);const Y=ps(M.toString()),{mutate:Z,isLoading:Q}=mt(m),ne=({config:R})=>{g(R).then(()=>{c({title:u("core.successMessage"),status:"success",isClosable:!0,position:"top",duration:3e3})}).catch(K=>{let le=u("core.generalErrorMessage");typeof K.response._data.detail=="object"&&(le=K.response._data.detail[Object.keys(K.response._data.detail)[0]]),typeof K.response._data.detail=="string"&&(le=K.response._data.detail),c({title:le,status:"error",isClosable:!0,position:"top",duration:3e3})})},oe=f.exports.useRef(null),[U,W]=f.exports.useState(!1),X=()=>{var R;document.fullscreenElement?(document.exitFullscreen(),W(!1)):((R=oe.current)==null||R.requestFullscreen(),W(!0))};return r("form",{onSubmit:F.handleSubmit(ne),children:[r(me,{children:[r(L,{children:[r(_,{justifyContent:"space-between",alignItems:"flex-start",children:[r(B,{children:[u("core.configuration")," ",w&&e(Pr,{isIndeterminate:!0,size:"15px"})]}),e(_,{gap:0,children:e(re,{label:"Xray Version",placement:"top",children:e(E,{height:"100%",textTransform:"lowercase",children:h&&`v${h}`})})})]}),r(v,{position:"relative",ref:oe,minHeight:"300px",children:[e(ye,{control:F.control,name:"config",render:({field:R})=>e(is,{json:x,onChange:R.onChange})}),e(V,{size:"xs","aria-label":"full screen",variant:"ghost",position:"absolute",top:"2",right:"4",onClick:X,children:U?e(us,{}):e(hs,{})})]})]}),r(L,{mt:"4",children:[r(_,{justifyContent:"space-between",style:{paddingBottom:"1rem"},children:[r(_,{children:[(n==null?void 0:n[0])&&r(Ne,{size:"sm",style:{width:"auto"},disabled:o,bg:"transparent",_dark:{bg:"transparent"},sx:{option:{backgroundColor:t==="dark"?"#222C3B":"white"}},onChange:R=>i(R.currentTarget.value,R.currentTarget.selectedOptions[0].text),children:[e("option",{value:"host",defaultChecked:!0,children:"Master"},"host"),n&&n.map(R=>e("option",{value:String(R.id),children:u(R.name)},R.address))]}),e(B,{className:"w-au",children:u("core.logs")})]}),e(d,{as:B,children:u(`core.socket.${Y}`)})]}),e(v,{border:"1px solid",borderColor:"gray.300",bg:"#F9F9F9",_dark:{borderColor:"gray.500",bg:"#2e3440"},borderRadius:5,minHeight:"200px",maxHeight:"250px",p:2,overflowY:"auto",ref:I,children:C.map((R,K)=>e(d,{fontSize:"xs",opacity:.8,whiteSpace:"pre-line",children:R},K))})]})]}),e(Pe,{children:r(_,{w:"full",justifyContent:"space-between",children:[e(_,{children:e(v,{children:e(P,{size:"sm",leftIcon:e(ds,{className:bt({"animate-spin":Q})}),onClick:()=>Z(),children:u(Q?"core.restarting":"core.restartCore")})})}),e(_,{children:e(P,{size:"sm",variant:"solid",colorScheme:"primary",px:"5",type:"submit",isDisabled:w||b,isLoading:b,children:u("core.save")})})]})})]})},fs=()=>{const{isEditingCore:t}=z(),n=z.setState.bind(null,{isEditingCore:!1}),{t:o}=H();return r(ce,{isOpen:t,onClose:n,size:"3xl",children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",w:"full",children:[e(ue,{pt:6,children:r(_,{gap:2,children:[e(ge,{color:"primary",children:e(cs,{color:"white"})}),e(d,{fontWeight:"semibold",fontSize:"lg",children:o("core.title")})]})}),e(pe,{mt:3}),e(gs,{})]})]})},wt=S(Ln,{baseStyle:{w:5,h:5}}),bs=()=>{const[t,n]=f.exports.useState(!1),{deletingUser:o,onDeletingUser:s,deleteUser:a}=z(),{t:i}=H(),l=we(),p=()=>{s(null)},g=()=>{o&&(n(!0),a(o).then(()=>{l({title:i("deleteUser.deleteSuccess",{username:o.username}),status:"success",isClosable:!0,position:"top",duration:3e3})}).then(p).finally(n.bind(null,!1)))};return r(ce,{isCentered:!0,isOpen:!!o,onClose:p,size:"sm",children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",children:[e(ue,{pt:6,children:e(ge,{color:"red",children:e(wt,{})})}),e(pe,{mt:3}),r(me,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:i("deleteUser.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:e(Te,{components:{b:e("b",{})},children:i("deleteUser.prompt",{username:o.username})})})]}),r(Pe,{display:"flex",children:[e(P,{size:"sm",onClick:p,mr:3,w:"full",variant:"outline",children:i("cancel")}),e(P,{size:"sm",w:"full",colorScheme:"red",onClick:g,leftIcon:t?e(He,{size:"xs"}):void 0,children:i("delete")})]})]})]})},er={baseStyle:{w:4,h:4}},xs=S(An,er),ys=S(Fr,er),tr=S(Mt,er),Ss=Nr(t=>{z.getState().onFilterChange({...z.getState().filters,offset:0,search:t})},300),ws=({...t})=>{const{loading:n,filters:o,onFilterChange:s,refetchUsers:a,onCreateUser:i}=z(),{t:l}=H(),[p,g]=f.exports.useState(""),w=b=>{g(b.target.value),Ss(b.target.value)},x=()=>{g(""),s({...o,offset:0,search:""})};return r(Wr,{id:"filters",templateColumns:{lg:"repeat(3, 1fr)",md:"repeat(4, 1fr)",base:"repeat(1, 1fr)"},position:"sticky",top:0,mx:"-6",px:"6",rowGap:4,gap:{lg:4,base:0},bg:"var(--chakra-colors-chakra-body-bg)",py:4,zIndex:"docked",...t,children:[e(ut,{colSpan:{base:1,md:2,lg:1},order:{base:2,md:1},children:r(It,{children:[e(Tn,{pointerEvents:"none",children:e(xs,{})}),e($e,{placeholder:l("search"),value:p,borderColor:"light-border",onChange:w}),r(vt,{children:[n&&e(He,{size:"xs"}),o.search&&o.search.length>0&&e(V,{onClick:x,"aria-label":"clear",size:"xs",variant:"ghost",children:e(ys,{})})]})]})}),e(ut,{colSpan:2,order:{base:1,md:2},children:r(_,{justifyContent:"flex-end",alignItems:"center",h:"full",children:[e(V,{"aria-label":"refresh users",disabled:n,onClick:a,size:"sm",variant:"outline",children:e(tr,{className:bt({"animate-spin":n})})}),e(P,{colorScheme:"primary",size:"sm",onClick:()=>i(!0),px:5,children:l("createUser")})]})})]})},cn="https://github.com/Gozargah/Marzban",Cs="https://github.com/Gozargah",_s="https://github.com/Gozargah/Marzban#donation",dn=t=>{const{version:n}=z();return e(_,{w:"full",py:"0",position:"relative",...t,children:r(d,{display:"inline-block",flexGrow:1,textAlign:"center",color:"gray.500",fontSize:"xs",children:[e(lr,{color:"blue.400",href:cn,children:"Marzban"}),n?` (v${n}), `:", ","Made with \u2764\uFE0F in"," ",e(lr,{color:"blue.400",href:Cs,children:"Gozargah"})]})})},ks=S(Mn,{baseStyle:{w:4,h:4}}),hn=({actions:t})=>{const{i18n:n}=H();var o=s=>{n.changeLanguage(s)};return r(Or,{placement:"bottom-end",children:[e(Hr,{as:V,size:"sm",variant:"outline",icon:e(ks,{}),position:"relative"}),r(jr,{minW:"100px",zIndex:9999,children:[e(Se,{maxW:"100px",fontSize:"sm",onClick:()=>o("en"),children:"English"}),e(Se,{maxW:"100px",fontSize:"sm",onClick:()=>o("fa"),children:"\u0641\u0627\u0631\u0633\u06CC"}),e(Se,{maxW:"100px",fontSize:"sm",onClick:()=>o("zh-cn"),children:"\u7B80\u4F53\u4E2D\u6587"}),e(Se,{maxW:"100px",fontSize:"sm",onClick:()=>o("ru"),children:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"})]})]})},Is=async()=>await O("/admin"),vs=()=>{const{data:t,isError:n,isLoading:o,isSuccess:s,error:a}=Tt({queryFn:()=>Is()});return{userData:t||{discord_webook:"",is_sudo:!1,telegram_id:"",username:""},getUserIsPending:o,getUserIsSuccess:s,getUserIsError:n,getUserError:a}},Ce={baseStyle:{w:4,h:4}},Ds=S(Nn,Ce),zs=S(Pn,Ce),Us=S(Mr,Ce),Es=S(Fn,Ce),Rs=S(Wn,Ce),Ls=S(On,Ce),As=S(qt,Ce),Ts=S(Br,Ce),Ms=S(At,Ce),Ns=S($r,Ce),wr=S(v,{baseStyle:{bg:"yellow.500",w:"2",h:"2",rounded:"full",position:"absolute"}}),un="marzban-menu-notification",Ps=()=>{const t=localStorage.getItem(un);if(!t)return!0;try{return t&&jn(parseInt(t))?Bn(new Date,new Date(parseInt(t)))>=7:!0}catch{return!0}},Fs=({actions:t})=>{const{userData:n,getUserIsSuccess:o,getUserIsPending:s}=vs(),a=()=>!s&&o?n.is_sudo:!1,{onEditingHosts:i,onResetAllUsage:l,onEditingNodes:p,onShowingNodesUsage:g}=z(),{t:w}=H(),{colorMode:x,toggleColorMode:b}=Ze(),[h,m]=f.exports.useState(Ps()),I=x==="dark"?"dark_dimmed":x,C=()=>{localStorage.setItem(un,new Date().getTime().toString()),m(!1)};return r(_,{gap:2,justifyContent:"space-between",__css:{"& .menuList":{direction:"ltr"}},position:"relative",children:[e(d,{as:"h1",fontWeight:"semibold",fontSize:"2xl",children:w("users")}),h&&e(wr,{top:"0",right:"0",zIndex:9999}),e(v,{overflow:"auto",css:{direction:"rtl"},children:r(_,{alignItems:"center",children:[r(Or,{children:[e(Hr,{as:V,size:"sm",variant:"outline",icon:e(ie,{children:e(Es,{})}),position:"relative"}),r(jr,{minW:"170px",zIndex:99999,className:"menuList",children:[a()&&r(ie,{children:[e(Se,{maxW:"170px",fontSize:"sm",icon:e(As,{}),onClick:i.bind(null,!0),children:w("header.hostSettings")}),e(Se,{maxW:"170px",fontSize:"sm",icon:e(Ts,{}),onClick:p.bind(null,!0),children:w("header.nodeSettings")}),e(Se,{maxW:"170px",fontSize:"sm",icon:e(Ms,{}),onClick:g.bind(null,!0),children:w("header.nodesUsage")}),e(Se,{maxW:"170px",fontSize:"sm",icon:e(Ns,{}),onClick:l.bind(null,!0),children:w("resetAllUsage")})]}),e(cr,{to:_s,target:"_blank",children:r(Se,{maxW:"170px",fontSize:"sm",icon:e(Ls,{}),position:"relative",onClick:C,children:[w("header.donation")," ",h&&e(wr,{top:"3",right:"2"})]})}),e(cr,{to:"/login",children:e(Se,{maxW:"170px",fontSize:"sm",icon:e(Rs,{}),children:w("header.logout")})})]})]}),a()&&e(V,{size:"sm",variant:"outline","aria-label":"core settings",onClick:()=>{z.setState({isEditingCore:!0})},children:e(Us,{})}),e(hn,{}),e(V,{size:"sm",variant:"outline","aria-label":"switch theme",onClick:()=>{on(x=="dark"?"light":"dark"),b()},children:x==="light"?e(Ds,{}):e(zs,{})}),e(v,{css:{direction:"ltr"},display:"flex",alignItems:"center",pr:"2",__css:{"& span":{display:"inline-flex"}},children:e(Hn,{href:cn,"data-color-scheme":`no-preference: ${I}; light: ${I}; dark: ${I};`,"data-size":"large","data-show-count":"true","aria-label":"Star Marzban on GitHub",children:"Star"})})]})})]})},Ws=[{title:"Inbound's default",value:"inbound_default"},{title:"TLS",value:"tls"},{title:"None",value:"none"}],Os=[{title:"",value:""},{title:"h3",value:"h3"},{title:"h2",value:"h2"},{title:"http/1.1",value:"http/1.1"},{title:"h3,h2,http/1.1",value:"h3,h2,http/1.1"},{title:"h3,h2",value:"h3,h2"},{title:"h2,http/1.1",value:"h2,http/1.1"}],Hs=[{title:"",value:""},...["chrome","firefox","safari","ios","android","edge","360","qq","random","randomized"].map(t=>({title:t,value:t}))],js=[{title:"none",value:""},{title:"xtls-rprx-vision",value:"xtls-rprx-vision"}],Bs=["aes-128-gcm","aes-256-gcm","chacha20-ietf-poly1305"],$s=Lt(t=>({isLoading:!1,isPostLoading:!1,hosts:{},fetchHosts:()=>{t({isLoading:!0}),O("/hosts").then(n=>t({hosts:n})).finally(()=>t({isLoading:!1}))},setHosts:n=>(t({isPostLoading:!0}),O("/hosts",{method:"PUT",body:n}).finally(()=>{t({isPostLoading:!1})}))}));const Vs=S(Fr,{baseStyle:{w:4,h:4}}),Me=$t.forwardRef(({disabled:t,step:n,label:o,className:s,startAdornment:a,endAdornment:i,type:l="text",placeholder:p,onChange:g,onBlur:w,name:x,value:b,onClick:h,error:m,clearable:I=!1,...C},A)=>{const u=()=>{g&&g({target:{value:"",name:x}})},{size:c="md"}=C,F=l=="number"?qn:$e,j=l=="number"?$n:$t.Fragment,D=l=="number"?{keepWithinRange:!0,precision:5,format:M=>isNaN(parseFloat(String(M)))||Number(parseFloat(String(M)).toFixed(5))===0?M:Number(parseFloat(String(M)).toFixed(5)),min:0,step:n,name:x,type:l,placeholder:p,onChange:M=>{g&&g(M)},onBlur:w,value:b,onClick:h,disabled:t,flexGrow:1,size:c}:{};return r(L,{isInvalid:!!m,children:[o&&e(B,{children:o}),r(It,{size:c,w:"full",rounded:"md",_focusWithin:{outline:"2px solid",outlineColor:"primary.200"},bg:t?"gray.100":"transparent",_dark:{bg:t?"gray.600":"transparent"},children:[a&&e(Vn,{children:a}),r(j,{...D,children:[e(F,{name:x,ref:A,step:n,className:bt(s),type:l,placeholder:p,onChange:g,onBlur:w,value:b,onClick:h,disabled:t,flexGrow:1,_focusVisible:{outline:"none",borderTopColor:"transparent",borderRightColor:"transparent",borderBottomColor:"transparent"},_disabled:{cursor:"not-allowed"},...C,roundedLeft:a?"0":"md",roundedRight:i?"0":"md"}),l=="number"&&e(ie,{children:r(Gn,{children:[e(Yn,{}),e(Zn,{})]})})]}),i&&e(Qn,{borderLeftRadius:0,borderRightRadius:"6px",bg:"transparent",children:i}),I&&b&&b.length&&e(vt,{borderLeftRadius:0,borderRightRadius:"6px",bg:"transparent",onClick:u,cursor:"pointer",children:e(Vs,{})})]}),!!m&&e(Dt,{children:m})]})}),Gs=S(Xn,{baseStyle:{w:5,h:5}}),Ys=S(Jn,{baseStyle:{w:5,h:5}}),Zs=S(Kn,{baseStyle:{w:5,h:5}}),Ot=S(Ne,{baseStyle:{bg:"white",_dark:{bg:"gray.700"}}}),Ae=S(Me,{baseStyle:{bg:"white",_dark:{bg:"gray.700"}}}),Qs=S(qt,{baseStyle:{w:5,h:5}}),Re=S(eo,{baseStyle:{w:4,h:4,color:"gray.400",cursor:"pointer"}}),qs=y.record(y.string().min(1),y.array(y.object({remark:y.string().min(1,"Remark is required"),address:y.string().min(1,"Address is required"),port:y.string().or(y.number()).nullable().transform(t=>typeof t=="number"?t:t!==null&&!isNaN(parseInt(t))?Number(parseInt(t)):null),path:y.string().nullable(),sni:y.string().nullable(),host:y.string().nullable(),mux_enable:y.boolean().default(!1),allowinsecure:y.boolean().nullable().default(!1),is_disabled:y.boolean().default(!0),fragment_setting:y.string().nullable(),noise_setting:y.string().nullable(),random_user_agent:y.boolean().default(!1),security:y.string(),alpn:y.string(),fingerprint:y.string()}))),xe=S(Dt,{baseStyle:{color:"red.400",display:"block",textAlign:"left",w:"100%"}}),Xs=({hostKey:t,isOpen:n,toggleAccordion:o})=>{const{inbounds:s}=z(),a=[...s.values()].flat().filter(u=>u.tag===t)[0],i=Xt(),{fields:l,append:p,remove:g,insert:w,move:x}=to({control:i.control,name:t}),{errors:b}=i.formState,{t:h}=H(),m=b[t],I=()=>{p({host:"",sni:"",port:null,path:null,address:"",remark:"",mux_enable:!1,allowinsecure:!1,is_disabled:!1,fragment_setting:"",noise_setting:"",random_user_agent:!1,security:"inbound_default",alpn:"",fingerprint:""})},C=u=>{if(u<0||u>=l.length)return;const c=l[u];w(u+1,c)};f.exports.useEffect(()=>{m&&!n&&o()},[m]);const A=(u,c)=>{c==="up"&&u>0?x(u,u-1):c==="down"&&u{var F,j,D,M,Y,Z,Q,ne,oe,U,W,X,R,K,le,J,_e,_t,Xe,kt,Je,Ke,et,tt,rt,k,T,ee,se,fe,ke,G,nt,ot,st,at,it,je,or,sr,ar;return e(ro.div,{layout:!0,initial:!1,animate:{opacity:1},exit:{opacity:0},transition:{layout:{type:"spring",stiffness:500,damping:30},opacity:{duration:.1}},id:u.id,whileDrag:{scale:1.05,zIndex:10},style:{width:"100%"},children:r(N,{id:u.id,border:"1px solid",_dark:{borderColor:"gray.600",bg:"#273142"},_light:{borderColor:"gray.200",bg:"#fcfbfb"},p:2,w:"full",borderRadius:"4px",children:[e(_,{w:"100%",alignItems:"flex-start",children:r(L,{position:"relative",zIndex:10,isInvalid:!!(m&&((F=m[c])==null?void 0:F.remark)),children:[r(It,{children:[e(Ae,{...i.register(t+"."+c+".remark"),size:"sm",borderRadius:"4px",placeholder:"Remark"}),e(vt,{children:r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(v,{mt:"-8px",children:e(Re,{})})}),e(De,{children:r(ze,{children:[e(Ue,{}),e(Ee,{}),e(dr,{children:r(v,{fontSize:"xs",children:[e(d,{pr:"20px",children:h("hostsDialog.desc")}),r(d,{children:[r(E,{children:["{","SERVER_IP","}"]})," ",h("hostsDialog.currentServer")]}),r(d,{mt:1,children:[r(E,{children:["{","SERVER_IPV6","}"]})," ",h("hostsDialog.currentServerv6")]}),r(d,{mt:1,children:[r(E,{children:["{","USERNAME","}"]})," ",h("hostsDialog.username")]}),r(d,{mt:1,children:[r(E,{children:["{","DATA_USAGE","}"]})," ",h("hostsDialog.dataUsage")]}),r(d,{mt:1,children:[r(E,{children:["{","DATA_LEFT","}"]})," ",h("hostsDialog.remainingData")]}),r(d,{mt:1,children:[r(E,{children:["{","DATA_LIMIT","}"]})," ",h("hostsDialog.dataLimit")]}),r(d,{mt:1,children:[r(E,{children:["{","DAYS_LEFT","}"]})," ",h("hostsDialog.remainingDays")]}),r(d,{mt:1,children:[r(E,{children:["{","EXPIRE_DATE","}"]})," ",h("hostsDialog.expireDate")]}),r(d,{mt:1,children:[r(E,{children:["{","JALALI_EXPIRE_DATE","}"]})," ",h("hostsDialog.jalaliExpireDate")]}),r(d,{mt:1,children:[r(E,{children:["{","TIME_LEFT","}"]})," ",h("hostsDialog.remainingTime")]}),r(d,{mt:1,children:[r(E,{children:["{","STATUS_TEXT","}"]})," ",h("hostsDialog.statusText")]}),r(d,{mt:1,children:[r(E,{children:["{","STATUS_EMOJI","}"]})," ",h("hostsDialog.statusEmoji")]}),r(d,{mt:1,children:[r(E,{children:["{","PROTOCOL","}"]})," ",h("hostsDialog.proxyProtocol")]}),r(d,{mt:1,children:[r(E,{children:["{","TRANSPORT","}"]})," ",h("hostsDialog.proxyMethod")]})]})})]})})]})})]}),m&&((j=m[c])==null?void 0:j.remark)&&e(xe,{children:(M=(D=m[c])==null?void 0:D.remark)==null?void 0:M.message})]})}),r(L,{isInvalid:!!(m&&((Y=m[c])==null?void 0:Y.address)),children:[r(It,{children:[e(Ae,{size:"sm",borderRadius:"4px",placeholder:"Address (e.g. example.com)",...i.register(t+"."+c+".address")}),e(vt,{children:r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(v,{mt:"-8px",children:e(Re,{})})}),e(De,{children:r(ze,{children:[e(Ue,{}),e(Ee,{}),e(dr,{children:r(v,{fontSize:"xs",children:[e(d,{pr:"20px",children:h("hostsDialog.desc")}),r(d,{children:[r(E,{children:["{","SERVER_IP","}"]})," ",h("hostsDialog.currentServer")]}),r(d,{mt:1,children:[r(E,{children:["{","SERVER_IPV6","}"]})," ",h("hostsDialog.currentServerv6")]}),r(d,{mt:1,children:[r(E,{children:["{","USERNAME","}"]})," ",h("hostsDialog.username")]}),r(d,{mt:1,children:[r(E,{children:["{","DATA_USAGE","}"]})," ",h("hostsDialog.dataUsage")]}),r(d,{mt:1,children:[r(E,{children:["{","DATA_LEFT","}"]})," ",h("hostsDialog.remainingData")]}),r(d,{mt:1,children:[r(E,{children:["{","DATA_LIMIT","}"]})," ",h("hostsDialog.dataLimit")]}),r(d,{mt:1,children:[r(E,{children:["{","DAYS_LEFT","}"]})," ",h("hostsDialog.remainingDays")]}),r(d,{mt:1,children:[r(E,{children:["{","EXPIRE_DATE","}"]})," ",h("hostsDialog.expireDate")]}),r(d,{mt:1,children:[r(E,{children:["{","JALALI_EXPIRE_DATE","}"]})," ",h("hostsDialog.jalaliExpireDate")]}),r(d,{mt:1,children:[r(E,{children:["{","TIME_LEFT","}"]})," ",h("hostsDialog.remainingTime")]}),r(d,{mt:1,children:[r(E,{children:["{","STATUS_TEXT","}"]})," ",h("hostsDialog.statusText")]}),r(d,{mt:1,children:[r(E,{children:["{","STATUS_EMOJI","}"]})," ",h("hostsDialog.statusEmoji")]}),r(d,{mt:1,children:[r(E,{children:["{","PROTOCOL","}"]})," ",h("hostsDialog.proxyProtocol")]}),r(d,{mt:1,children:[r(E,{children:["{","TRANSPORT","}"]})," ",h("hostsDialog.proxyMethod")]})]})})]})})]})})]}),m&&((Z=m[c])==null?void 0:Z.address)&&e(xe,{children:(ne=(Q=m[c])==null?void 0:Q.address)==null?void 0:ne.message})]}),e(yt,{w:"full",allowToggle:!0,children:r(Ve,{border:"0",children:[r("div",{style:{display:"flex",alignItems:"center"},children:[r(Ge,{display:"flex",px:0,py:1,borderRadius:3,_hover:{bg:"transparent"},children:[r(d,{flex:"3",align:"start",fontSize:"xs",color:"gray.600",_dark:{color:"gray.500"},pl:1,children:[h("hostsDialog.advancedOptions"),e(Vt,{fontSize:"sm",ml:1})]}),r(no,{flex:"1",px:"0",display:"contents",children:[e(ye,{control:i.control,name:`${t}.${c}.is_disabled`,render:({field:te})=>e(zt,{mx:"1.5",colorScheme:"primary",...te,value:void 0,isChecked:!te.value,onChange:ir=>{console.log(ir.target.checked),te.onChange(!ir.target.checked)}})}),e(re,{label:"Delete",placement:"top",children:e(V,{"aria-label":"Delete",size:"sm",colorScheme:"red",variant:"ghost",onClick:g.bind(null,c),children:e(wt,{})})})]})]}),e(re,{label:"Dublicate",placement:"top",children:e(V,{"aria-label":"Dublicate",size:"sm",colorScheme:"white",variant:"ghost",onClick:()=>C(c),children:e(Gs,{})})}),cA(c,"down"),children:e(Zs,{})})}),c>0&&e(re,{label:"Move Up",placement:"top",children:e(V,{"aria-label":"UpIcon",size:"sm",colorScheme:"white",variant:"ghost",onClick:()=>A(c,"up"),children:e(Ys,{})})})]}),e(Ye,{w:"full",p:1,children:r(N,{w:"full",borderRadius:"4px",children:[r(L,{isInvalid:!!(m&&((oe=m[c])==null?void 0:oe.port)),children:[r(B,{display:"flex",pb:1,alignItems:"center",justifyContent:"space-between",gap:1,m:"0",children:[e("span",{children:h("hostsDialog.port")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:h("hostsDialog.port.info")})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:String(a.port||"8080"),type:"number",...i.register(t+"."+c+".port")})]}),r(L,{isInvalid:!!(m&&((U=m[c])==null?void 0:U.sni)),children:[r(B,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:h("hostsDialog.sni")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:h("hostsDialog.sni.info")}),e(d,{fontSize:"xs",mt:"2",children:e(Te,{i18nKey:"hostsDialog.host.wildcard",components:{badge:e(E,{})}})}),e(d,{fontSize:"xs",children:e(Te,{i18nKey:"hostsDialog.host.multiHost",components:{badge:e(E,{})}})})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"SNI (e.g. example.com)",...i.register(t+"."+c+".sni")}),m&&((W=m[c])==null?void 0:W.sni)&&e(xe,{children:(R=(X=m[c])==null?void 0:X.sni)==null?void 0:R.message})]}),r(L,{isInvalid:!!(m&&((K=m[c])==null?void 0:K.host)),children:[r(B,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:h("hostsDialog.host")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:h("hostsDialog.host.info")}),e(d,{fontSize:"xs",mt:"2",children:e(Te,{i18nKey:"hostsDialog.host.wildcard",components:{badge:e(E,{})}})}),e(d,{fontSize:"xs",children:e(Te,{i18nKey:"hostsDialog.host.multiHost",components:{badge:e(E,{})}})})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"Host (e.g. example.com)",...i.register(t+"."+c+".host")}),m&&((le=m[c])==null?void 0:le.host)&&e(xe,{children:(_e=(J=m[c])==null?void 0:J.host)==null?void 0:_e.message})]}),r(L,{isInvalid:!!(m&&((_t=m[c])==null?void 0:_t.path)),children:[r(B,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:h("hostsDialog.path")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:h("hostsDialog.path.info")})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"path (e.g. /vless)",...i.register(t+"."+c+".path")}),m&&((Xe=m[c])==null?void 0:Xe.path)&&e(xe,{children:(Je=(kt=m[c])==null?void 0:kt.path)==null?void 0:Je.message})]}),r(L,{height:"66px",children:[r(B,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:h("hostsDialog.security")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:h("hostsDialog.security.info")})]})})]})]}),e(Ot,{size:"sm",...i.register(t+"."+c+".security"),children:Ws.map(te=>e("option",{value:te.value,children:te.title},te.value))})]}),r(L,{height:"66px",children:[e(B,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:e("span",{children:h("hostsDialog.alpn")})}),e(Ot,{size:"sm",...i.register(t+"."+c+".alpn"),children:Os.map(te=>e("option",{value:te.value,children:te.title},te.value))})]}),r(L,{height:"66px",children:[e(B,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:e("span",{children:h("hostsDialog.fingerprint")})}),e(Ot,{size:"sm",...i.register(t+"."+c+".fingerprint"),children:Hs.map(te=>e("option",{value:te.value,children:te.title},te.value))})]}),r(L,{isInvalid:!!(m&&((Ke=m[c])==null?void 0:Ke.fragment_setting)),children:[r(B,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:h("hostsDialog.fragment")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:h("hostsDialog.fragment.info")}),e(d,{fontSize:"xs",pr:5,pt:2,pb:1,children:h("hostsDialog.fragment.info.examples")}),e(d,{fontSize:"xs",pr:5,children:"100-200,10-20,tlshello"}),e(d,{fontSize:"xs",pr:5,children:"100-200,10-20,1-3"}),e(d,{fontSize:"xs",pr:5,pt:"3",children:h("hostsDialog.fragment.info.attention")})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"Fragment settings by pattern",...i.register(t+"."+c+".fragment_setting")}),m&&((et=m[c])==null?void 0:et.fragment_setting)&&e(xe,{children:(rt=(tt=m[c])==null?void 0:tt.fragment_setting)==null?void 0:rt.message})]}),r(L,{isInvalid:!!(m&&((k=m[c])==null?void 0:k.noise_setting)),children:[r(B,{display:"flex",pb:1,alignItems:"center",gap:1,justifyContent:"space-between",m:"0",children:[e("span",{children:h("hostsDialog.noise")}),r(Ie,{isLazy:!0,placement:"right",children:[e(ve,{children:e(Re,{})}),e(De,{children:r(ze,{p:2,children:[e(Ue,{}),e(Ee,{}),e(d,{fontSize:"xs",pr:5,children:h("hostsDialog.noise.info")}),e(d,{fontSize:"xs",pr:5,pt:2,pb:1,children:h("hostsDialog.noise.info.examples")}),e(d,{fontSize:"xs",pr:5,children:"rand:10-20,10-20"}),e(d,{fontSize:"xs",pr:5,children:"rand:10-20,10-20&base64:7nQBAAABAAAAAAAABnQtcmluZwZtc2VkZ2UDbmV0AAABAAE=,10-25"}),e(d,{fontSize:"xs",pr:5,pt:"3",children:h("hostsDialog.noise.info.attention")})]})})]})]}),e(Ae,{size:"sm",borderRadius:"4px",placeholder:"Noise settings by pattern",...i.register(t+"."+c+".noise_setting")}),m&&((T=m[c])==null?void 0:T.noise_setting)&&e(xe,{children:(se=(ee=m[c])==null?void 0:ee.noise_setting)==null?void 0:se.message})]}),e(L,{isInvalid:!!(m&&((fe=m[c])==null?void 0:fe.allowinsecure)),children:r(pt,{...i.register(t+"."+c+".allowinsecure"),name:t+"."+c+".allowinsecure",children:[e(B,{children:h("hostsDialog.allowinsecure")}),m&&((ke=m[c])==null?void 0:ke.allowinsecure)&&e(xe,{children:(nt=(G=m[c])==null?void 0:G.allowinsecure)==null?void 0:nt.message})]})}),r(L,{isInvalid:!!(m&&((ot=m[c])==null?void 0:ot.mux_enable)),children:[e(pt,{...i.register(t+"."+c+".mux_enable"),children:e(B,{children:h("hostsDialog.muxEnable")})}),m&&((st=m[c])==null?void 0:st.mux_enable)&&e(xe,{children:(it=(at=m[c])==null?void 0:at.mux_enable)==null?void 0:it.message})]}),r(L,{isInvalid:!!(m&&((je=m[c])==null?void 0:je.random_user_agent)),children:[e(pt,{...i.register(t+"."+c+".random_user_agent"),children:e(B,{children:h("hostsDialog.randomUserAgent")})}),m&&((or=m[c])==null?void 0:or.random_user_agent)&&e(xe,{children:(ar=(sr=m[c])==null?void 0:sr.random_user_agent)==null?void 0:ar.message})]})]},c)})]})})]},u.id)},u.id)}),e(P,{variant:"outline",w:"full",size:"sm",color:"",fontWeight:"normal",onClick:I,children:h("hostsDialog.addHost")})]})})]})},Js=()=>{const{isEditingHosts:t,onEditingHosts:n,refetchUsers:o,inbounds:s}=z(),{isLoading:a,hosts:i,fetchHosts:l,isPostLoading:p,setHosts:g}=$s(),w=we(),{t:x}=H(),[b,h]=f.exports.useState({});f.exports.useEffect(()=>{t&&l()},[t]);const m=Qe({resolver:xt(qs)});f.exports.useEffect(()=>{i&&t&&m.reset(i)},[i]);const I=()=>{h({}),n(!1)},C=u=>{g(u).then(()=>{w({title:x("hostsDialog.savedSuccess"),status:"success",isClosable:!0,position:"top",duration:3e3}),o()}).catch(c=>{var F,j,D,M,Y;(((F=c==null?void 0:c.response)==null?void 0:F.status)===409||((j=c==null?void 0:c.response)==null?void 0:j.status)===400)&&w({title:(M=(D=c.response)==null?void 0:D._data)==null?void 0:M.detail,status:"error",isClosable:!0,position:"top",duration:3e3}),((Y=c==null?void 0:c.response)==null?void 0:Y.status)===422&&Object.keys(c.response._data.detail).forEach(Z=>{w({title:c.response._data.detail[Z]+" ("+Z+")",status:"error",isClosable:!0,position:"top",duration:3e3})})})},A=u=>{b[String(u)]?delete b[String(u)]:b[String(u)]={},h({...b})};return r(ce,{isOpen:t,onClose:I,children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",w:"fit-content",maxW:"3xl",children:[e(ue,{pt:6,children:e(ge,{color:"primary",children:e(Qs,{color:"white"})})}),e(pe,{mt:3}),e(me,{w:"440px",pb:3,pt:3,children:e(Vr,{...m,children:r("form",{onSubmit:m.handleSubmit(C),children:[e(d,{mb:3,opacity:.8,fontSize:"sm",children:x("hostsDialog.title")}),a&&x("hostsDialog.loading"),!a&&i&&(Object.keys(i).length>0?e(yt,{w:"full",allowToggle:!0,allowMultiple:!0,index:Object.keys(b).map(u=>parseInt(u)),children:e(N,{w:"full",children:Object.keys(i).map((u,c)=>e(Xs,{toggleAccordion:()=>A(c),isOpen:b[String(c)],hostKey:u},u))})}):"No inbound found. Please check your Xray config file."),e(_,{justifyContent:"flex-end",py:2,children:e(P,{variant:"solid",mt:"2",type:"submit",colorScheme:"primary",size:"sm",px:5,isLoading:p,disabled:p,children:x("hostsDialog.apply")})})]})})})]})]})},rr=(t,n,o)=>{if(t.response&&t.response._data){if(typeof t.response._data.detail=="string")return n({title:t.response._data.detail,status:"error",isClosable:!0,position:"top",duration:3e3});if(typeof t.response._data.detail=="object"&&o){Object.keys(t.response._data.detail).forEach(s=>o.setError(s,{message:t.response._data.detail[s]}));return}}return n({title:"Something went wrong!",status:"error",isClosable:!0,position:"top",duration:3e3})},nr=(t,n)=>n({title:t,status:"success",isClosable:!0,position:"top",duration:3e3}),Ks=({deleteCallback:t})=>{const{deleteNode:n,deletingNode:o,setDeletingNode:s}=St(),{t:a}=H(),i=we(),l=Jt(),p=()=>{s(null)},{isLoading:g,mutate:w}=mt(n,{onSuccess:()=>{nr(a("deleteNode.deleteSuccess",{name:o&&o.name}),i),s(null),l.invalidateQueries(ft),t&&t()},onError:x=>{rr(x,i)}});return r(ce,{isCentered:!0,isOpen:!!o,onClose:p,size:"sm",children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",children:[e(ue,{pt:6,children:e(ge,{color:"red",children:e(wt,{})})}),e(pe,{mt:3}),r(me,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:a("deleteNode.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:e(Te,{components:{b:e("b",{})},children:a("deleteNode.prompt",{name:o.name})})})]}),r(Pe,{display:"flex",children:[e(P,{size:"sm",onClick:p,mr:3,w:"full",variant:"outline",children:a("cancel")}),e(P,{size:"sm",w:"full",colorScheme:"red",onClick:()=>w(),leftIcon:g?e(He,{size:"xs"}):void 0,children:a("delete")})]})]})]})},Ct={baseStyle:{strokeWidth:"2px",w:4,h:4}},Cr=S(oo,Ct),ea=S(so,Ct),_r=S(ao,Ct),kr=S(Gr,Ct),ta=S(Gr,Ct),Zt=[{title:"No",value:"no_reset"},{title:"Daily",value:"day"},{title:"Weekly",value:"week"},{title:"Monthly",value:"month"},{title:"Annually",value:"year"}],Oe={active:{statusColor:"green",bandWidthColor:"primary",icon:Cr},connected:{statusColor:"green",bandWidthColor:"primary",icon:Cr},disabled:{statusColor:"gray",bandWidthColor:"gray",icon:ea},expired:{statusColor:"orange",bandWidthColor:"orange",icon:kr},on_hold:{statusColor:"purple",bandWidthColor:"purple",icon:ta},connecting:{statusColor:"orange",bandWidthColor:"orange",icon:kr},limited:{statusColor:"red",bandWidthColor:"red",icon:_r},error:{statusColor:"red",bandWidthColor:"red",icon:_r}},Nt=t=>{let n={status:"",time:""};if(t){$(t*1e3).utc().isAfter($().utc())?n.status="expires":n.status="expired";const o=[],s=$.duration($(t*1e3).utc().diff($()));s.years()!=0&&o.push(Math.abs(s.years())+" year"+(Math.abs(s.years())!=1?"s":"")),s.months()!=0&&o.push(Math.abs(s.months())+" month"+(Math.abs(s.months())!=1?"s":"")),s.days()!=0&&o.push(Math.abs(s.days())+" day"+(Math.abs(s.days())!=1?"s":"")),o.length===0&&(s.hours()!=0&&o.push(Math.abs(s.hours())+" hour"+(Math.abs(s.hours())!=1?"s":"")),s.minutes()!=0&&o.push(Math.abs(s.minutes())+" min"+(Math.abs(s.minutes())!=1?"s":""))),n.time=o.join(", ")}return n},ra=({expiryDate:t,status:n,compact:o=!1,showDetail:s=!0,extraText:a})=>{const{t:i}=H(),l=Nt(t),p=Oe[n].icon;return r(ie,{children:[r(E,{colorScheme:Oe[n].statusColor,rounded:"full",display:"inline-flex",px:3,py:1,columnGap:o?1:2,alignItems:"center",children:[e(p,{w:o?3:4}),s&&r(d,{textTransform:"capitalize",fontSize:o?".7rem":".875rem",lineHeight:o?"1rem":"1.25rem",fontWeight:"medium",letterSpacing:"tighter",children:[n&&i(`nodeModal.status.${n}`),a&&`: ${a}`]})]}),s&&t&&e(d,{display:"inline-block",fontSize:"xs",fontWeight:"medium",ml:"2",color:"gray.600",_dark:{color:"gray.400"},children:i(l.status,{time:l.time})})]})},ct=S(Me,{baseStyle:{bg:"white",_dark:{bg:"gray.700"}}}),na=S(Br,{baseStyle:{w:5,h:5}}),oa=S(io,{baseStyle:{w:5,h:5,strokeWidth:2}}),sa=({toggleAccordion:t,node:n})=>{const{updateNode:o,reconnectNode:s,setDeletingNode:a}=St(),{t:i}=H(),l=Jt(),p=we(),g=Qe({defaultValues:n,resolver:xt(an)}),w=a.bind(null,n),{isLoading:x,mutate:b}=mt(o,{onSuccess:()=>{nr("Node updated successfully",p),l.invalidateQueries(ft)},onError:C=>{rr(C,p,g)}}),{isLoading:h,mutate:m}=mt(s.bind(null,n),{onSuccess:()=>{l.invalidateQueries(ft)}}),I=h?"connecting":n.status?n.status:"error";return r(Ve,{border:"1px solid",_dark:{borderColor:"gray.600"},_light:{borderColor:"gray.200"},borderRadius:"4px",p:1,w:"full",children:[r(Ge,{px:2,borderRadius:"3px",onClick:t,children:[r(_,{w:"full",justifyContent:"space-between",pr:2,children:[e(d,{as:"span",fontWeight:"medium",fontSize:"sm",flex:"1",textAlign:"left",color:"gray.700",_dark:{color:"gray.300"},children:n.name}),r(_,{children:[n.xray_version&&e(E,{colorScheme:"blue",rounded:"full",display:"inline-flex",px:3,py:1,children:r(d,{textTransform:"capitalize",fontSize:"0.7rem",fontWeight:"medium",letterSpacing:"tighter",children:["Xray ",n.xray_version]})}),n.status&&e(ra,{status:I,compact:!0})]})]}),e(Vt,{})]}),r(Ye,{px:2,pb:2,children:[e(N,{pb:3,alignItems:"flex-start",children:I==="error"&&e(gt,{status:"error",size:"xs",children:r(v,{children:[r(_,{w:"full",children:[e(Ut,{w:4}),e(d,{marginInlineEnd:0,children:n.message})]}),e(_,{justifyContent:"flex-end",w:"full",children:e(P,{size:"sm","aria-label":"reconnect node",leftIcon:e(tr,{}),onClick:()=>m(),disabled:h,children:i(h?"nodes.reconnecting":"nodes.reconnect")})})]})})}),e(pn,{form:g,mutate:b,isLoading:x,submitBtnText:i("nodes.editNode"),btnLeftAdornment:e(re,{label:i("delete"),placement:"top",children:e(V,{colorScheme:"red",variant:"ghost",size:"sm","aria-label":"delete node",onClick:w,children:e(wt,{})})})})]})]})},aa=({toggleAccordion:t,resetAccordions:n})=>{const o=we(),{t:s}=H(),a=Jt(),{addNode:i}=St(),l=Qe({resolver:xt(an),defaultValues:{...ls(),add_as_new_host:!1}}),{isLoading:p,mutate:g}=mt(i,{onSuccess:()=>{nr(s("nodes.addNodeSuccess",{name:l.getValues("name")}),o),a.invalidateQueries(ft),l.reset(),n()},onError:w=>{rr(w,o,l)}});return r(Ve,{border:"1px solid",_dark:{borderColor:"gray.600"},_light:{borderColor:"gray.200"},borderRadius:"4px",p:1,w:"full",children:[e(Ge,{px:2,borderRadius:"3px",onClick:t,children:r(d,{as:"span",fontWeight:"medium",fontSize:"sm",flex:"1",textAlign:"left",color:"gray.700",_dark:{color:"gray.300"},display:"flex",gap:1,children:[e(oa,{display:"inline-block"})," ",e("span",{children:s("nodes.addNewMarzbanNode")})]})}),e(Ye,{px:2,py:4,children:e(pn,{form:l,mutate:g,isLoading:p,submitBtnText:s("nodes.addNode"),btnProps:{variant:"solid"},addAsHost:!0})})]})},pn=({form:t,mutate:n,isLoading:o,submitBtnText:s,btnProps:a={},btnLeftAdornment:i,addAsHost:l=!1})=>{var m,I,C,A,u,c,F,j,D,M,Y,Z,Q,ne,oe;const{t:p}=H(),[g,w]=f.exports.useState(!1),{data:x,isLoading:b}=Tt({queryKey:"node-settings",queryFn:()=>O("/node/settings")});function h(U){if(document.body.createTextRange){const W=document.body.createTextRange();W.moveToElementText(U),W.select()}else if(window.getSelection){const W=window.getSelection(),X=document.createRange();X.selectNodeContents(U),W.removeAllRanges(),W.addRange(X)}else console.warn("Could not select text in node: Unsupported browser.")}return e("form",{onSubmit:t.handleSubmit(U=>n(U)),children:r(N,{children:[x&&x.certificate&&e(gt,{status:"info",alignItems:"start",children:r(Yr,{display:"flex",flexDirection:"column",overflow:"hidden",children:[e("span",{children:p("nodes.connection-hint")}),r(_,{justify:"end",py:2,children:[e(P,{as:"a",colorScheme:"primary",size:"xs",download:"ssl_client_cert.pem",href:URL.createObjectURL(new Blob([x.certificate],{type:"text/plain"})),children:p("nodes.download-certificate")}),e(re,{placement:"top",label:p("nodes.show-certificate"),children:e(V,{"aria-label":p("nodes.show-certificate"),onClick:w.bind(null,!g),colorScheme:"whiteAlpha",color:"primary",size:"xs",children:g?e(co,{width:"15px"}):e(lo,{width:"15px"})})})]}),e(Zr,{in:g,animateOpacity:!0,children:e(d,{bg:"rgba(255,255,255,.5)",_dark:{bg:"rgba(255,255,255,.2)"},rounded:"md",p:"2",lineHeight:"1.2",fontSize:"10px",fontFamily:"Courier",whiteSpace:"pre",overflow:"auto",onClick:U=>{h(U.target)},children:x.certificate})})]})}),r(_,{w:"full",children:[e(L,{children:e(ct,{label:p("nodes.nodeName"),size:"sm",placeholder:"Marzban-S2",...t.register("name"),error:(C=(I=(m=t.formState)==null?void 0:m.errors)==null?void 0:I.name)==null?void 0:C.message})}),e(_,{px:1,children:e(ye,{name:"status",control:t.control,render:({field:U})=>e(re,{placement:"top",label:`${p("usersTable.status")}: `+(U.value!=="disabled"?p("active"):p("disabled")),textTransform:"capitalize",children:e(v,{mt:"6",children:e(zt,{colorScheme:"primary",isChecked:U.value!=="disabled",onChange:W=>{W.target.checked?U.onChange("connecting"):U.onChange("disabled")}})})},U.value)})})]}),e(_,{alignItems:"flex-start",w:"100%",children:e(v,{w:"100%",children:e(ct,{label:p("nodes.nodeAddress"),size:"sm",placeholder:"51.20.12.13",...t.register("address"),error:(c=(u=(A=t.formState)==null?void 0:A.errors)==null?void 0:u.address)==null?void 0:c.message})})}),r(_,{alignItems:"flex-start",w:"100%",children:[e(v,{children:e(ct,{label:p("nodes.nodePort"),size:"sm",placeholder:"62050",...t.register("port"),error:(D=(j=(F=t.formState)==null?void 0:F.errors)==null?void 0:j.port)==null?void 0:D.message})}),e(v,{children:e(ct,{label:p("nodes.nodeAPIPort"),size:"sm",placeholder:"62051",...t.register("api_port"),error:(Z=(Y=(M=t.formState)==null?void 0:M.errors)==null?void 0:Y.api_port)==null?void 0:Z.message})}),e(v,{children:e(ct,{label:p("nodes.usageCoefficient"),size:"sm",placeholder:"1",...t.register("usage_coefficient"),error:(oe=(ne=(Q=t.formState)==null?void 0:Q.errors)==null?void 0:ne.usage_coefficient)==null?void 0:oe.message})})]}),l&&e(L,{py:1,children:e(pt,{...t.register("add_as_new_host"),children:e(B,{m:0,children:p("nodes.addHostForEveryInbound")})})}),r(_,{w:"full",children:[i,e(P,{flexGrow:1,type:"submit",colorScheme:"primary",size:"sm",px:5,w:"full",isLoading:o,...a,children:s})]})]})})},ia=()=>{const{isEditingNodes:t,onEditingNodes:n}=z(),{t:o}=H(),[s,a]=f.exports.useState({}),{data:i,isLoading:l}=ln(),p=()=>{a({}),n(!1)},g=w=>{s[String(w)]?delete s[String(w)]:s[String(w)]={},a({...s})};return r(ie,{children:[r(ce,{isOpen:t,onClose:p,children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",w:"fit-content",maxW:"3xl",children:[e(ue,{pt:6,children:e(ge,{color:"primary",children:e(na,{color:"white"})})}),e(pe,{mt:3}),r(me,{w:"440px",pb:6,pt:3,children:[e(d,{mb:3,opacity:.8,fontSize:"sm",children:o("nodes.title")}),l&&"loading...",e(yt,{w:"full",allowToggle:!0,index:Object.keys(s).map(w=>parseInt(w)),children:r(N,{w:"full",children:[!l&&i&&i.map((w,x)=>e(sa,{toggleAccordion:()=>g(x),node:w},w.name)),e(aa,{toggleAccordion:()=>g((i||[]).length),resetAccordions:()=>a({})})]})})]})]})]}),e(Ks,{deleteCallback:()=>a({})})]})};function la(t){const n=360/t,o=90,s=47,a=[];for(let i=0;i(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?x+(b-x)*6*h:h<.5?b:h<.6666666666666666?x+(b-x)*(.6666666666666666-h)*6:x),g=o<.5?o*(1+n):o+n-o*n,w=2*o-g;s=Math.round(p(w,g,t+1/3)*255),a=Math.round(p(w,g,t)*255),i=Math.round(p(w,g,t-1/3)*255)}const l=p=>{const g=p.toString(16);return g.length===1?"0"+g:g};return`#${l(s)}${l(a)}${l(i)}`}const Ir=({border:t,...n})=>{const{getInputProps:o,getRadioProps:s}=bo(n),a=We({base:"xs",md:"sm"});return r(v,{as:"label",children:[e("input",{...o()}),e(v,{...s(),minW:"48px",w:"full",h:"full",textAlign:"center",cursor:"pointer",fontSize:a,borderWidth:t?"1px":"0px",borderRadius:"md",_checked:{bg:"primary.500",color:"white",borderColor:"primary.500"},_focus:{boxShadow:"outline"},px:3,py:1,children:n.children})]})},mn=({onChange:t,defaultValue:n,...o})=>{const{t:s,i18n:a}=H();Ze();const i=We({base:["7h","1d","3d","1w"],md:["7h","1d","3d","1w","1m","3m"]}),l={h:"hour",d:"day",w:"week",m:"month",y:"year"},p=We({base:[{title:"hours",options:["1h","3h","6h","12h"]},{title:"days",options:["1d","2d","3d","4d"]},{title:"weeks",options:["1w","2w","3w","4w"]},{title:"months",options:["1m","2m","3m","6m"]}],md:[{title:"hours",options:["1h","2h","3h","6h","8h","12h"]},{title:"days",options:["1d","2d","3d","4d","5d","6d"]},{title:"weeks",options:["1w","2w","3w","4w"]},{title:"months",options:["1m","2m","3m","6m","8m"]}]}),{getRootProps:g,getRadioProps:w,setValue:x}=ho({name:"filter",defaultValue:n,onChange:U=>{if(U==="custom")return;m(),i.indexOf(U)>=0?(A(s("userDialog.custom")),c(!1)):(A(s("userDialog.custom")+` (${U})`),c(!0));const W=Number(U.substring(0,U.length-1)),X=l[U[U.length-1]];t(U,{start:$().utc().subtract(W,X).format("YYYY-MM-DDTHH:00:00")})}}),{isOpen:b,onOpen:h,onClose:m}=uo(),I=f.exports.useRef(null);po({ref:I,handler:m});const[C,A]=f.exports.useState(s("userDialog.custom")),[u,c]=f.exports.useState(!1),[F,j]=f.exports.useState(0),D=We({base:1,md:2}),M=We({base:"xs",md:"sm"}),[Y,Z]=f.exports.useState(null),[Q,ne]=f.exports.useState(null),oe=U=>{const[W,X]=U;Q&&!X?(Z(null),ne(null)):(Z(W),ne(X),W&&X&&(m(),t("custom",{start:$(W).format("YYYY-MM-DDT00:00:00"),end:$(X).format("YYYY-MM-DDT23:59:59")})))};return r(N,{...o,children:[F==0&&r(Kt,{...g(),gap:0,display:"flex",borderWidth:"1px",borderRadius:"md",minW:{base:"320px",md:"400px"},children:[i.map(U=>e(Ir,{...w({value:U}),children:U},U)),e(v,{onClick:()=>{Z(null),ne(null),h()},cursor:"pointer",borderRadius:"md",w:"full",fontSize:M,px:3,py:1,bg:u?"primary.500":"unset",color:u?"white":"unset",borderColor:u?"primary.500":"unset",children:r(_,{children:[e(d,{children:C}),e(Pt,{as:hr,boxSize:"18px"})]})})]}),F==1&&r(_,{onClick:h,cursor:"pointer",fontSize:M,borderRadius:"md",px:3,py:1,minW:{base:"320px",md:"400px"},borderWidth:"1px",children:[e(d,{w:"full",color:Y?"unset":"gray.500",children:Y?$(Y).format("YYYY-MM-DD (00:00)"):s("userDialog.startDate")}),e(Pt,{as:Qr,boxSize:"18px"}),e(d,{w:"full",color:Q?"unset":"gray.500",children:Q?$(Q).format("YYYY-MM-DD (23:59)"):s("userDialog.endDate")}),e(Pt,{as:hr,boxSize:"18px"})]}),e(N,{ref:I,marginTop:"40px !important",borderRadius:"md",borderWidth:"1px",position:"absolute",zIndex:"1",backgroundColor:"white",_dark:{backgroundColor:"gray.700"},display:b?"unset":"none",children:r(mo,{onChange:U=>j(U),children:[r(go,{children:[e(ur,{fontSize:M,children:s("userDialog.relative")}),e(ur,{fontSize:M,children:s("userDialog.absolute")})]}),r(fo,{children:[e(pr,{children:p.map(U=>e(N,{alignItems:"start",pl:2,pr:2,children:r(_,{justifyItems:"flex-start",mb:4,children:[e(d,{fontSize:M,minW:"60px",children:s("userDialog."+U.title)}),U.options.map(W=>e(Ir,{border:!0,...w({value:W}),children:W},W+".custom"))]})},U.title))}),e(pr,{className:"datepicker-panel",children:e(N,{children:e(qr,{locale:a.language.toLocaleLowerCase(),selected:Y,onChange:oe,startDate:Y,endDate:Q,selectsRange:!0,maxDate:new Date,monthsShown:D,peekNextMonth:!1,inline:!0})})})]})]})})]})};function Rt(t,n,o=[],s=[]){const a=ae(o.reduce((i,l)=>i+=l,0));return{series:o,options:{labels:s,chart:{width:"100%",height:"100%",type:"donut",animations:{enabled:!1}},title:{text:`${n}${a}`,align:"center",style:{fontWeight:"var(--chakra-fontWeights-medium)",color:t==="dark"?"var(--chakra-colors-gray-300)":void 0}},legend:{position:"bottom",labels:{colors:t==="dark"?"#CBD5E0":void 0,useSeriesColors:!1}},stroke:{width:1,colors:void 0},dataLabels:{formatter:(i,{seriesIndex:l,w:p})=>ae(p.config.series[l],1)},tooltip:{custom:({series:i,seriesIndex:l,dataPointIndex:p,w:g})=>{const w=ae(i[l],1),x=Math.max(i.reduce((h,m)=>h+=m),1),b=Math.round(i[l]/x*1e3)/10+"%";return` -
- ${g.config.labels[l]}: ${b}, ${w} -
- `}},colors:la(o.length)}}}const da=S(At,{baseStyle:{w:5,h:5}}),ha=()=>{const{isShowingNodesUsage:t,onShowingNodesUsage:n}=z(),{fetchNodesUsage:o}=St(),{t:s}=H(),[a,i]=f.exports.useState(!1),{colorMode:l}=Ze(),p=s("userDialog.total"),[g,w]=f.exports.useState(Rt(l,p)),[x,b]=f.exports.useState("1m"),h=C=>{o(C).then(A=>{const u=[],c=[];for(const F in A.usages){const j=A.usages[F];c.push(j.uplink+j.downlink),u.push(j.node_name)}w(Rt(l,p,c,u))})};f.exports.useEffect(()=>{t&&h({start:$().utc().subtract(30,"day").format("YYYY-MM-DDTHH:00:00")})},[t]);const m=()=>{n(!1),b("1m")},I=a;return r(ce,{isOpen:t,onClose:m,size:"2xl",children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",w:"full",children:[e(ue,{pt:6,children:r(_,{gap:2,children:[e(ge,{color:"primary",children:e(da,{color:"white"})}),e(d,{fontWeight:"semibold",fontSize:"lg",children:s("header.nodesUsage")})]})}),e(pe,{mt:3,disabled:I}),e(me,{children:r(N,{gap:4,children:[e(mn,{defaultValue:x,onChange:(C,A)=>{b(C),h(A)}}),e(v,{justifySelf:"center",w:"full",maxW:"300px",mt:"4",children:e(f.exports.Suspense,{fallback:e(Pr,{isIndeterminate:!0}),children:e(Xr,{options:g.options,series:g.series,type:"donut",height:"500px"})})})]})}),e(Pe,{mt:"3"})]})]})},vr=S(xo),ua=S(Qr,{baseStyle:{w:6,h:6,color:"gray.600",_dark:{color:"white"}}}),pa=S(yo,{baseStyle:{w:6,h:6,color:"gray.600",_dark:{color:"white"}}}),ma=S(Jr,{baseStyle:{w:5,h:5}}),ga=()=>{const{QRcodeLinks:t,setQRCode:n,setSubLink:o,subscribeUrl:s}=z(),a=t!==null,[i,l]=f.exports.useState(0),{t:p}=H(),g=()=>{n(null),o(null)},w=String(s).startsWith("/")?window.location.origin+s:String(s);return r(ce,{isOpen:a,onClose:g,children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",w:"fit-content",maxW:"3xl",children:[e(ue,{pt:6,children:e(ge,{color:"primary",children:e(ma,{color:"white"})})}),e(pe,{mt:3}),t&&r(me,{gap:{base:"20px",lg:"50px"},pr:{lg:"60px"},px:{base:"50px"},display:"flex",justifyContent:"center",flexDirection:{base:"column",lg:"row"},children:[s&&r(N,{children:[e(vr,{mx:"auto",size:300,p:"2",level:"L",includeMargin:!1,value:w,bg:"white"}),e(d,{display:"block",textAlign:"center",pb:3,mt:1,children:p("qrcodeDialog.sublink")})]}),r(v,{w:"300px",children:[e(So,{centerPadding:"0px",centerMode:!0,slidesToShow:1,slidesToScroll:1,dots:!1,afterChange:l,onInit:()=>l(0),nextArrow:e(V,{size:"sm",position:"absolute",display:"flex !important",_before:{content:'""'},"aria-label":"next",mr:"-4",children:e(ua,{})}),prevArrow:e(V,{size:"sm",position:"absolute",display:"flex !important",_before:{content:'""'},"aria-label":"prev",ml:"-4",children:e(pa,{})}),children:t.map((x,b)=>e(_,{children:e(vr,{mx:"auto",size:300,p:"2",level:"L",includeMargin:!1,value:x,bg:"white"})},b))}),r(d,{display:"block",textAlign:"center",pb:3,mt:1,children:[i+1," / ",t.length]})]})]})]})]})},fa=S($r,{baseStyle:{w:5,h:5}}),ba=()=>{const[t,n]=f.exports.useState(!1),{isResetingAllUsage:o,onResetAllUsage:s,resetAllUsage:a}=z(),{t:i}=H(),l=we(),p=()=>{s(!1)},g=()=>{n(!0),a().then(()=>{l({title:i("resetAllUsage.success"),status:"success",isClosable:!0,position:"top",duration:3e3})}).catch(()=>{l({title:i("resetAllUsage.error"),status:"error",isClosable:!0,position:"top",duration:3e3})}).finally(()=>{n(!1)})};return r(ce,{isCentered:!0,isOpen:o,onClose:p,size:"sm",children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",children:[e(ue,{pt:6,children:e(ge,{color:"red",children:e(fa,{})})}),e(pe,{mt:3}),r(me,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:i("resetAllUsage.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:i("resetAllUsage.prompt")})]}),r(Pe,{display:"flex",children:[e(P,{size:"sm",onClick:p,mr:3,w:"full",variant:"outline",children:i("cancel")}),e(P,{size:"sm",w:"full",colorScheme:"red",onClick:g,leftIcon:t?e(He,{size:"xs"}):void 0,children:i("reset")})]})]})]})},xa=S(Mt,{baseStyle:{w:5,h:5}}),ya=()=>{const[t,n]=f.exports.useState(!1),{resetUsageUser:o,resetDataUsage:s}=z(),{t:a}=H(),i=we(),l=()=>{z.setState({resetUsageUser:null})},p=()=>{o&&(n(!0),s(o).then(()=>{i({title:a("resetUserUsage.success",{username:o.username}),status:"success",isClosable:!0,position:"top",duration:3e3})}).catch(()=>{i({title:a("resetUserUsage.error"),status:"error",isClosable:!0,position:"top",duration:3e3})}).finally(()=>{n(!1)}))};return r(ce,{isCentered:!0,isOpen:!!o,onClose:l,size:"sm",children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",children:[e(ue,{pt:6,children:e(ge,{color:"blue",children:e(xa,{})})}),e(pe,{mt:3}),r(me,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:a("resetUserUsage.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:e(Te,{components:{b:e("b",{})},children:a("resetUserUsage.prompt",{username:o.username})})})]}),r(Pe,{display:"flex",children:[e(P,{size:"sm",onClick:l,mr:3,w:"full",variant:"outline",children:a("cancel")}),e(P,{size:"sm",w:"full",colorScheme:"blue",onClick:p,leftIcon:t?e(He,{size:"xs"}):void 0,children:a("reset")})]})]})]})},Sa=S(Mt,{baseStyle:{w:5,h:5}}),wa=()=>{const[t,n]=f.exports.useState(!1),{revokeSubscriptionUser:o,revokeSubscription:s}=z(),{t:a}=H(),i=we(),l=()=>{z.setState({revokeSubscriptionUser:null})},p=()=>{o&&(n(!0),s(o).then(()=>{i({title:a("revokeUserSub.success",{username:o.username}),status:"success",isClosable:!0,position:"top",duration:3e3})}).catch(()=>{i({title:a("revokeUserSub.error"),status:"error",isClosable:!0,position:"top",duration:3e3})}).finally(()=>{n(!1)}))};return r(ce,{isCentered:!0,isOpen:!!o,onClose:l,size:"sm",children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),r(he,{mx:"3",children:[e(ue,{pt:6,children:e(ge,{color:"blue",children:e(Sa,{})})}),e(pe,{mt:3}),r(me,{children:[e(d,{fontWeight:"semibold",fontSize:"lg",children:a("revokeUserSub.title")}),o&&e(d,{mt:1,fontSize:"sm",_dark:{color:"gray.400"},color:"gray.600",children:e(Te,{components:{b:e("b",{})},children:a("revokeUserSub.prompt",{username:o.username})})})]}),r(Pe,{display:"flex",children:[e(P,{size:"sm",onClick:l,mr:3,w:"full",variant:"outline",children:a("cancel")}),e(P,{size:"sm",w:"full",colorScheme:"blue",onClick:p,leftIcon:t?e(He,{size:"xs"}):void 0,children:a("revoke")})]})]})]})},Ca=S(wo,{baseStyle:{strokeWidth:"2px",w:5,h:5}}),_a=({inbound:t,...n})=>{const{getCheckboxProps:o,getInputProps:s,getLabelProps:a,htmlProps:i}=en(n),l=s();return r(v,{as:"label",children:[e("input",{...l}),r(v,{w:"fll",position:"relative",...i,cursor:"pointer",borderRadius:"sm",border:"1px solid",borderColor:"gray.200",_dark:{borderColor:"gray.600"},display:"flex",alignItems:"center",justifyContent:"space-between",overflow:"hidden",_checked:{bg:"gray.50",outline:"2px",boxShadow:"outline",outlineColor:"primary.500",borderColor:"transparent",fontWeight:"medium",_dark:{bg:"gray.750",borderColor:"transparent"},"& p":{opacity:1}},__css:{"& p":{opacity:.8}},textTransform:"capitalize",px:3,py:2,fontWeight:"medium",...o(),children:[e(pt,{size:"sm",w:"full",maxW:"full",color:"gray.700",_dark:{color:"gray.300"},textTransform:"uppercase",colorScheme:"primary",className:"inbound-item",isChecked:l.checked,pointerEvents:"none",flexGrow:1,children:e(_,{justify:"space-between",w:"full",maxW:"calc(100% - 20px)",spacing:0,gap:2,overflow:"hidden",children:r(d,{isTruncated:!0,...a(),fontSize:"xs",children:[t.tag," ",r(d,{as:"span",children:["(",t.network,")"]})]})})}),t.tls&&t.tls!="none"&&e(E,{fontSize:"xs",opacity:".8",size:"xs",children:t.tls})]})]})},ka=({disabled:t,title:n,description:o,toggleAccordion:s,isSelected:a,...i})=>{const l=Xt(),{inbounds:p}=z(),{getCheckboxProps:g,getInputProps:w,getLabelProps:x,htmlProps:b}=en(i),h=w(),[m]=tn({name:[`inbounds.${n}`],control:l.control}),{getCheckboxProps:I}=Kr({value:m,onChange:c=>{if(l.setValue(`inbounds.${n}`,c),c.length===0){const F=l.getValues("selected_proxies");l.setValue("selected_proxies",F.filter(j=>j!==n)),s()}}}),C=m&&a&&(z.getState().inbounds.get(n)||[]).length!==m.length,A=(z.getState().inbounds.get(n)||[]).length>0,u=!a&&!A;return r(Ve,{isDisabled:!A,borderRadius:"md",borderStyle:"solid",border:"1px",borderColor:"gray.200",bg:u?"gray.100":"transparent",_dark:{borderColor:"gray.600",bg:u?"#364154":"transparent"},_checked:{bg:"gray.50",outline:"2px",boxShadow:"outline",outlineColor:"primary.500",borderColor:"transparent"},...g(),children:[r(v,{as:u?"span":"label",position:"relative",children:[C&&e(v,{position:"absolute",w:"2",h:"2",bg:"yellow.500",top:"-1",right:"-1",rounded:"full",zIndex:999}),e("input",{...h}),r(v,{w:"fll",position:"relative",...b,borderRadius:"md",cursor:u?"not-allowed":"pointer",_checked:{fontWeight:"medium",_dark:{bg:"gray.750",borderColor:"transparent"},"& > svg":{opacity:1,"&.checked":{display:"block"},"&.unchecked":{display:"none"}},"& p":{opacity:1}},__css:{"& > svg":{opacity:.3,"&.checked":{display:"none"},"&.unchecked":{display:"block"}},"& p":{opacity:.8}},textTransform:"capitalize",px:3,py:2,fontWeight:"medium",...g(),children:[e(Ge,{display:h.checked&&A?"block":"none",as:"span",className:"checked",color:"primary.200",position:"absolute",right:"3",top:"3",w:"auto",p:0,onClick:s,children:e(V,{size:"sm","aria-label":"inbound settings",children:e(Ca,{})})}),e(d,{fontSize:"sm",color:u?"gray.400":"gray.700",_dark:{color:u?"gray.500":"gray.300"},...x(),children:n}),e(d,{fontWeight:"medium",color:u?"gray.400":"gray.600",_dark:{color:u?"gray.500":"gray.400"},fontSize:"xs",children:o})]})]}),e(Ye,{px:2,pb:3,roundedBottom:"5px",pt:3,_dark:{bg:h.checked&&"gray.750"},children:r(N,{w:"full",rowGap:2,borderStyle:"solid",borderWidth:"1px",borderRadius:"md",pl:3,pr:3,pt:1.5,_dark:{bg:"gray.700"},children:[r(N,{alignItems:"flex-start",w:"full",children:[e(d,{fontSize:"sm",children:q("inbound")}),e(Kt,{gap:2,alignItems:"flex-start",w:"full",columns:1,spacing:1,children:(p.get(n)||[]).map(c=>e(_a,{...I({value:c.tag}),inbound:c},c.tag))})]}),n==="vmess"&&a&&e(N,{alignItems:"flex-start",w:"full",children:r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:"ID"}),e($e,{fontSize:"xs",size:"sm",borderRadius:"6px",pl:2,pr:2,placeholder:q("userDialog.generatedByDefault"),...l.register("proxies.vmess.id")})]})}),n==="vless"&&a&&r(N,{alignItems:"flex-start",w:"full",children:[r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:"ID"}),e($e,{fontSize:"xs",size:"sm",borderRadius:"6px",pl:2,pr:2,placeholder:q("userDialog.generatedByDefault"),...l.register("proxies.vless.id")})]}),r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:"Flow"}),e(Ne,{fontSize:"xs",size:"sm",borderRadius:"6px",...l.register("proxies.vless.flow"),children:js.map(c=>e("option",{value:c.value,children:c.title},c.title))})]})]}),n==="trojan"&&a&&e(N,{alignItems:"flex-start",w:"full",children:r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:q("password")}),e($e,{fontSize:"xs",size:"sm",borderRadius:"6px",pl:2,pr:2,placeholder:q("userDialog.generatedByDefault"),...l.register("proxies.trojan.password")})]})}),n==="shadowsocks"&&a&&r(N,{alignItems:"flex-start",w:"full",children:[r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:q("password")}),e($e,{fontSize:"xs",size:"sm",borderRadius:"6px",pl:2,pr:2,placeholder:q("userDialog.generatedByDefault"),...l.register("proxies.shadowsocks.password")})]}),r(L,{height:"66px",children:[e(d,{fontSize:"sm",pb:1,children:q("userDialog.method")}),e(Ne,{fontSize:"xs",size:"sm",borderRadius:"6px",...l.register("proxies.shadowsocks.method"),children:Bs.map(c=>e("option",{value:c,children:c},c))})]})]})]})})]})},Ia=f.exports.forwardRef(({name:t,list:n,onChange:o,disabled:s,...a},i)=>{const l=Xt(),[p,g]=f.exports.useState([]),w=b=>{p.includes(b)?p.splice(p.indexOf(b),1):p.push(b),g([...p])},{getCheckboxProps:x}=Kr({value:a.value,onChange:b=>{var m;const h=b.filter(I=>!a.value.includes(I));h[0]&&l.setValue(`inbounds.${h[0]}`,(m=z.getState().inbounds.get(h[0]))==null?void 0:m.map(I=>I.tag)),g(p.filter(I=>b.find(C=>C===n[I].title))),o({target:{value:b,name:t}})}});return e(yt,{allowToggle:!0,index:p,children:e(Kt,{ref:i,gap:2,alignItems:"flex-start",columns:1,spacing:1,children:n.map((b,h)=>e(ka,{toggleAccordion:w.bind(null,h),disabled:s,title:b.title,description:b.description,isSelected:!!a.value.find(m=>m===b.title),...x({value:b.title})},b.title))})})}),va=S(Co,{baseStyle:{w:5,h:5}}),Da=S(rn,{baseStyle:{w:5,h:5}}),za=S(At,{baseStyle:{w:5,h:5}}),Ua=t=>({...t,data_limit:t.data_limit?Number((t.data_limit/1073741824).toFixed(5)):t.data_limit,on_hold_expire_duration:t.on_hold_expire_duration?Number(t.on_hold_expire_duration/(24*60*60)):t.on_hold_expire_duration,selected_proxies:Object.keys(t.proxies)}),Ht=()=>{const t=Object.fromEntries(z.getState().inbounds),n={};for(const o in t)n[o]=t[o].map(s=>s.tag);return{selected_proxies:Object.keys(t),data_limit:null,expire:null,username:"",data_limit_reset_strategy:"no_reset",status:"active",on_hold_expire_duration:null,note:"",inbounds:n,proxies:{vless:{id:"",flow:""},vmess:{id:""},trojan:{password:""},shadowsocks:{password:"",method:"chacha20-ietf-poly1305"}}}},Ea=(t,n)=>{const o=t.reduce((s,a)=>({...s,[a]:{}}),{});return n&&t.forEach(s=>{n[s]&&(o[s]=n[s])}),o},dt={username:y.string().min(1,{message:"Required"}),selected_proxies:y.array(y.string()).refine(t=>t.length>0,{message:"userDialog.selectOneProtocol"}),note:y.string().nullable(),proxies:y.record(y.string(),y.record(y.string(),y.any())).transform(t=>{const n=(o,s)=>{o&&o[s]===""&&delete o[s]};return n(t.vmess,"id"),n(t.vless,"id"),n(t.trojan,"password"),n(t.shadowsocks,"password"),n(t.shadowsocks,"method"),t}),data_limit:y.string().min(0).or(y.number()).nullable().transform(t=>t?Number((parseFloat(String(t))*1073741824).toFixed(5)):0),expire:y.number().nullable(),data_limit_reset_strategy:y.string(),inbounds:y.record(y.string(),y.array(y.string())).transform(t=>(Object.keys(t).forEach(n=>{var o;Array.isArray(t[n])&&!((o=t[n])!=null&&o.length)&&delete t[n]}),t))},Ra=y.discriminatedUnion("status",[y.object({status:y.literal("active"),...dt}),y.object({status:y.literal("disabled"),...dt}),y.object({status:y.literal("limited"),...dt}),y.object({status:y.literal("expired"),...dt}),y.object({status:y.literal("on_hold"),on_hold_expire_duration:y.coerce.number().min(.1,"Required").transform(t=>t*(24*60*60)),...dt})]),La=()=>{var Je,Ke,et,tt,rt;const{editingUser:t,isCreatingNewUser:n,onCreateUser:o,editUser:s,fetchUserUsage:a,onEditingUser:i,createUser:l,onDeletingUser:p}=z(),g=!!t,w=n||g,[x,b]=f.exports.useState(!1),[h,m]=f.exports.useState(""),I=we(),{t:C,i18n:A}=H(),{colorMode:u}=Ze(),[c,F]=f.exports.useState(!1),j=()=>{F(k=>!k)},D=Qe({defaultValues:Ht(),resolver:xt(Ra)});f.exports.useEffect(()=>z.subscribe(k=>k.inbounds,()=>{D.reset(Ht())}),[]);const[M,Y]=tn({control:D.control,name:["data_limit","status"]}),Z=C("userDialog.total"),[Q,ne]=f.exports.useState(Rt(u,Z)),[oe,U]=f.exports.useState("1m"),W=k=>{a(t,k).then(T=>{const ee=[],se=[];for(const fe in T.usages)se.push(T.usages[fe].used_traffic),ee.push(T.usages[fe].node_name);ne(Rt(u,Z,se,ee))})};f.exports.useEffect(()=>{t&&(D.reset(Ua(t)),W({start:$().utc().subtract(30,"day").format("YYYY-MM-DDTHH:00:00")}))},[t]);const X=k=>{b(!0);const T={edited:s,created:l},ee=g?"edited":"created";m(null);const{selected_proxies:se,...fe}=k;let ke={...fe,data_limit:k.data_limit,proxies:Ea(se,k.proxies),data_limit_reset_strategy:k.data_limit&&k.data_limit>0?k.data_limit_reset_strategy:"no_reset",status:k.status==="active"||k.status==="disabled"||k.status==="on_hold"?k.status:"active"};T[ee](ke).then(()=>{I({title:C(g?"userDialog.userEdited":"userDialog.userCreated",{username:k.username}),status:"success",isClosable:!0,position:"top",duration:3e3}),R()}).catch(G=>{var nt,ot,st,at,it;(((nt=G==null?void 0:G.response)==null?void 0:nt.status)===409||((ot=G==null?void 0:G.response)==null?void 0:ot.status)===400)&&m((at=(st=G==null?void 0:G.response)==null?void 0:st._data)==null?void 0:at.detail),((it=G==null?void 0:G.response)==null?void 0:it.status)===422&&Object.keys(G.response._data.detail).forEach(je=>{m(G==null?void 0:G.response._data.detail[je]),D.setError(je,{type:"custom",message:G.response._data.detail[je]})})}).finally(()=>{b(!1)})},R=()=>{D.reset(Ht()),o(!1),i(null),m(null),F(!1),U("1m")},K=()=>{z.setState({resetUsageUser:t})},le=()=>{z.setState({revokeSubscriptionUser:t})},J=x,_e=Y==="on_hold",[_t,Xe]=f.exports.useState(!1),kt=()=>{Xe(!0);let k="";const T="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",ee=T.length;let se=0;for(;se<6;)k+=T.charAt(Math.floor(Math.random()*ee)),se+=1;return k};return r(ce,{isOpen:w,onClose:R,size:"2xl",children:[e(de,{bg:"blackAlpha.300",backdropFilter:"blur(10px)"}),e(Vr,{...D,children:e(he,{mx:"3",children:r("form",{onSubmit:D.handleSubmit(X),children:[e(ue,{pt:6,children:r(_,{gap:2,children:[e(ge,{color:"primary",children:g?e(Da,{color:"white"}):e(va,{color:"white"})}),e(d,{fontWeight:"semibold",fontSize:"lg",children:C(g?"userDialog.editUserTitle":"createNewUser")})]})}),e(pe,{mt:3,disabled:J}),r(me,{children:[r(Wr,{templateColumns:{base:"repeat(1, 1fr)",md:"repeat(2, 1fr)"},gap:3,children:[e(ut,{children:r(N,{justifyContent:"space-between",children:[r(Ft,{flexDirection:"column",gridAutoRows:"min-content",w:"full",children:[r(Ft,{flexDirection:"row",w:"full",gap:2,children:[r(L,{mb:"10px",children:[e(B,{children:r(Ft,{gap:2,alignItems:"center",children:[C("username"),!g&&e(tr,{cursor:"pointer",className:bt({"animate-spin":_t}),onClick:()=>{const k=kt();D.setValue("username",k),setTimeout(()=>{Xe(!1)},350)}})]})}),r(_,{children:[e(Me,{size:"sm",type:"text",borderRadius:"6px",error:(Je=D.formState.errors.username)==null?void 0:Je.message,disabled:J||g,...D.register("username")}),g&&e(_,{px:1,children:e(ye,{name:"status",control:D.control,render:({field:k})=>e(re,{placement:"top",label:"status: "+C(`status.${k.value}`),textTransform:"capitalize",children:e(v,{children:e(zt,{colorScheme:"primary",isChecked:k.value==="active",onChange:T=>{T.target.checked?k.onChange("active"):k.onChange("disabled")}})})})})})]})]}),!g&&r(L,{flex:"1",children:[e(B,{whiteSpace:"nowrap",children:C("userDialog.onHold")}),e(ye,{name:"status",control:D.control,render:({field:k})=>{const T=k.value;return e(ie,{children:T?e(zt,{colorScheme:"primary",isChecked:T==="on_hold",onChange:ee=>{ee.target.checked?k.onChange("on_hold"):k.onChange("active")}}):""})}})]})]}),r(L,{mb:"10px",children:[e(B,{children:C("userDialog.dataLimit")}),e(ye,{control:D.control,name:"data_limit",render:({field:k})=>{var T;return e(Me,{endAdornment:"GB",type:"number",size:"sm",borderRadius:"6px",onChange:k.onChange,disabled:J,error:(T=D.formState.errors.data_limit)==null?void 0:T.message,value:k.value?String(k.value):""})}})]}),e(Zr,{in:!!(M&&M>0),animateOpacity:!0,style:{width:"100%"},children:r(L,{height:"66px",children:[e(B,{children:C("userDialog.periodicUsageReset")}),e(ye,{control:D.control,name:"data_limit_reset_strategy",render:({field:k})=>e(Ne,{size:"sm",...k,disabled:J,bg:J?"gray.100":"transparent",_dark:{bg:J?"gray.600":"transparent"},sx:{option:{backgroundColor:u==="dark"?"#222C3B":"white"}},children:Zt.map(T=>e("option",{value:T.value,children:C("userDialog.resetStrategy"+T.title)},T.value))})})]})}),r(L,{mb:"10px",children:[e(B,{children:C(_e?"userDialog.onHoldExpireDuration":"userDialog.expiryDate")}),_e&&e(ye,{control:D.control,name:"on_hold_expire_duration",render:({field:k})=>{var T;return e(Me,{endAdornment:"Days",type:"number",size:"sm",borderRadius:"6px",onChange:ee=>{D.setValue("expire",null),k.onChange({target:{value:ee}})},disabled:J,error:(T=D.formState.errors.on_hold_expire_duration)==null?void 0:T.message,value:k.value?String(k.value):""})}}),!_e&&e(ye,{name:"expire",control:D.control,render:({field:k})=>{var fe;function T(ke){return $($(ke*1e3).utc()).toDate()}const{status:ee,time:se}=Nt(k.value);return r(ie,{children:[e(qr,{locale:A.language.toLocaleLowerCase(),dateFormat:C("dateFormat"),minDate:new Date,selected:k.value?T(k.value):void 0,onChange:ke=>{D.setValue("on_hold_expire_duration",null),k.onChange({target:{value:ke?$($(ke).set("hour",23).set("minute",59).set("second",59)).utc().valueOf()/1e3:0,name:"expire"}})},customInput:e(Me,{size:"sm",type:"text",borderRadius:"6px",clearable:!0,disabled:J,error:(fe=D.formState.errors.expire)==null?void 0:fe.message})}),k.value?e(_o,{children:C(ee,{time:se})}):""]})}})]}),r(L,{mb:"10px",isInvalid:!!D.formState.errors.note,children:[e(B,{children:C("userDialog.note")}),e(ko,{...D.register("note")}),e(Dt,{children:(et=(Ke=D.formState.errors)==null?void 0:Ke.note)==null?void 0:et.message})]})]}),h&&r(gt,{status:"error",display:{base:"none",md:"flex"},children:[e(Ut,{}),h]})]})}),e(ut,{children:r(L,{isInvalid:!!((tt=D.formState.errors.selected_proxies)!=null&&tt.message),children:[e(B,{children:C("userDialog.protocols")}),e(ye,{control:D.control,name:"selected_proxies",render:({field:k})=>e(Ia,{list:[{title:"vmess",description:C("userDialog.vmessDesc")},{title:"vless",description:C("userDialog.vlessDesc")},{title:"trojan",description:C("userDialog.trojanDesc")},{title:"shadowsocks",description:C("userDialog.shadowsocksDesc")}],disabled:J,...k})}),e(Dt,{children:C((rt=D.formState.errors.selected_proxies)==null?void 0:rt.message)})]})}),g&&c&&e(ut,{pt:6,colSpan:{base:1,md:2},children:r(N,{gap:4,children:[e(mn,{defaultValue:oe,onChange:(k,T)=>{U(k),W(T)}}),e(v,{width:{base:"100%",md:"70%"},justifySelf:"center",children:e(Xr,{options:Q.options,series:Q.series,type:"donut"})})]})})]}),h&&r(gt,{mt:"3",status:"error",display:{base:"flex",md:"none"},children:[e(Ut,{}),h]})]}),e(Pe,{mt:"3",children:r(_,{justifyContent:"space-between",w:"full",gap:3,flexDirection:{base:"column",sm:"row"},children:[e(_,{justifyContent:"flex-start",w:{base:"full",sm:"unset"},children:g&&r(ie,{children:[e(re,{label:C("delete"),placement:"top",children:e(V,{"aria-label":"Delete",size:"sm",onClick:()=>{p(t),R()},children:e(wt,{})})}),e(re,{label:C("userDialog.usage"),placement:"top",children:e(V,{"aria-label":"usage",size:"sm",onClick:j,children:e(za,{})})}),e(P,{onClick:K,size:"sm",children:C("userDialog.resetUsage")}),e(P,{onClick:le,size:"sm",children:C("userDialog.revokeSubscription")})]})}),e(_,{w:"full",maxW:{md:"50%",base:"full"},justify:"end",children:e(P,{type:"submit",size:"sm",px:"8",colorScheme:"primary",leftIcon:x?e(He,{size:"xs"}):void 0,disabled:J,children:C(g?"userDialog.editUser":"createUser")})})]})})]})})})]})},Aa=t=>f.exports.createElement("svg",{xmlns:"http://www.w3.org/2000/svg","data-name":"Layer 1",width:782.04441,height:701.88002,viewBox:"0 0 782.04441 701.88002",xmlnsXlink:"http://www.w3.org/1999/xlink",...t},f.exports.createElement("path",{d:"M609.48783,100.59015l-25.44631,6.56209L270.53735,187.9987,245.091,194.56079A48.17927,48.17927,0,0,0,210.508,253.17865L320.849,681.05606a48.17924,48.17924,0,0,0,58.61776,34.58317l.06572-.01695,364.26536-93.93675.06572-.01695a48.17923,48.17923,0,0,0,34.58309-58.6178l-110.341-427.87741A48.17928,48.17928,0,0,0,609.48783,100.59015Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),f.exports.createElement("path",{d:"M612.94784,114.00532l-30.13945,7.77236L278.68955,200.20385l-30.139,7.77223a34.30949,34.30949,0,0,0-24.6275,41.74308l110.341,427.87741a34.30946,34.30946,0,0,0,41.7431,24.62736l.06572-.01695,364.26536-93.93674.06619-.01707a34.30935,34.30935,0,0,0,24.627-41.7429l-110.341-427.87741A34.30938,34.30938,0,0,0,612.94784,114.00532Z",transform:"translate(-208.9778 -99.05999)",fill:"#fff"}),f.exports.createElement("path",{d:"M590.19,252.56327,405.917,300.08359a8.01411,8.01411,0,0,1-4.00241-15.52046l184.273-47.52033A8.01412,8.01412,0,0,1,590.19,252.56327Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),f.exports.createElement("path",{d:"M628.955,270.49906,412.671,326.27437a8.01411,8.01411,0,1,1-4.00241-15.52046l216.284-55.77531a8.01411,8.01411,0,0,1,4.00242,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),f.exports.createElement("path",{d:"M620.45825,369.93676l-184.273,47.52032a8.01411,8.01411,0,1,1-4.00242-15.52046l184.273-47.52032a8.01411,8.01411,0,1,1,4.00241,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),f.exports.createElement("path",{d:"M659.22329,387.87255l-216.284,55.77531a8.01411,8.01411,0,1,1-4.00242-15.52046l216.284-55.77531a8.01411,8.01411,0,0,1,4.00242,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),f.exports.createElement("path",{d:"M650.72653,487.31025l-184.273,47.52033a8.01412,8.01412,0,0,1-4.00242-15.52047l184.273-47.52032a8.01411,8.01411,0,0,1,4.00242,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),f.exports.createElement("path",{d:"M689.49156,505.246l-216.284,55.77532a8.01412,8.01412,0,1,1-4.00241-15.52047l216.284-55.77531a8.01411,8.01411,0,0,1,4.00242,15.52046Z",transform:"translate(-208.9778 -99.05999)",fill:"#f2f2f2"}),f.exports.createElement("path",{d:"M374.45884,348.80871l-65.21246,16.817a3.847,3.847,0,0,1-4.68062-2.76146L289.5963,304.81607a3.847,3.847,0,0,1,2.76145-4.68061l65.21247-16.817a3.847,3.847,0,0,1,4.68061,2.76145l14.96947,58.04817A3.847,3.847,0,0,1,374.45884,348.80871Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M404.72712,466.1822l-65.21247,16.817a3.847,3.847,0,0,1-4.68062-2.76146l-14.96946-58.04816A3.847,3.847,0,0,1,322.626,417.509l65.21246-16.817a3.847,3.847,0,0,1,4.68062,2.76145l14.96946,58.04817A3.847,3.847,0,0,1,404.72712,466.1822Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M434.99539,583.55569l-65.21246,16.817a3.847,3.847,0,0,1-4.68062-2.76145l-14.96946-58.04817a3.847,3.847,0,0,1,2.76145-4.68062l65.21247-16.817a3.847,3.847,0,0,1,4.68061,2.76146l14.96947,58.04816A3.847,3.847,0,0,1,434.99539,583.55569Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M863.63647,209.0517H487.31811a48.17928,48.17928,0,0,0-48.125,48.12512V699.05261a48.17924,48.17924,0,0,0,48.125,48.12507H863.63647a48.17924,48.17924,0,0,0,48.125-48.12507V257.17682A48.17928,48.17928,0,0,0,863.63647,209.0517Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M863.637,222.90589H487.31811a34.30948,34.30948,0,0,0-34.271,34.27093V699.05261a34.30947,34.30947,0,0,0,34.271,34.27088H863.637a34.30936,34.30936,0,0,0,34.27051-34.27088V257.17682A34.30937,34.30937,0,0,0,863.637,222.90589Z",transform:"translate(-208.9778 -99.05999)",fill:"#fff"}),f.exports.createElement("circle",{cx:694.19401,cy:614.02963,r:87.85039,fill:"#3182CE"}),f.exports.createElement("path",{d:"M945.18722,701.63087H914.63056V671.07421a11.45875,11.45875,0,0,0-22.9175,0v30.55666H861.1564a11.45875,11.45875,0,0,0,0,22.9175h30.55666V755.105a11.45875,11.45875,0,1,0,22.9175,0V724.54837h30.55666a11.45875,11.45875,0,0,0,0-22.9175Z",transform:"translate(-208.9778 -99.05999)",fill:"#fff"}),f.exports.createElement("path",{d:"M807.00068,465.71551H616.699a8.01412,8.01412,0,1,1,0-16.02823H807.00068a8.01412,8.01412,0,0,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M840.05889,492.76314H616.699a8.01412,8.01412,0,1,1,0-16.02823H840.05889a8.01411,8.01411,0,1,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M807.00068,586.929H616.699a8.01412,8.01412,0,1,1,0-16.02823H807.00068a8.01411,8.01411,0,0,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M840.05889,613.97661H616.699a8.01412,8.01412,0,1,1,0-16.02823H840.05889a8.01412,8.01412,0,1,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M574.07028,505.04162H506.72434a3.847,3.847,0,0,1-3.84278-3.84278V441.25158a3.847,3.847,0,0,1,3.84278-3.84278h67.34594a3.847,3.847,0,0,1,3.84278,3.84278v59.94726A3.847,3.847,0,0,1,574.07028,505.04162Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M574.07028,626.25509H506.72434a3.847,3.847,0,0,1-3.84278-3.84278V562.46505a3.847,3.847,0,0,1,3.84278-3.84278h67.34594a3.847,3.847,0,0,1,3.84278,3.84278v59.94726A3.847,3.847,0,0,1,574.07028,626.25509Z",transform:"translate(-208.9778 -99.05999)",fill:"#e6e6e6"}),f.exports.createElement("path",{d:"M807.21185,330.781H666.91017a8.01411,8.01411,0,0,1,0-16.02823H807.21185a8.01411,8.01411,0,0,1,0,16.02823Z",transform:"translate(-208.9778 -99.05999)",fill:"#ccc"}),f.exports.createElement("path",{d:"M840.27007,357.82862H666.91017a8.01411,8.01411,0,1,1,0-16.02822h173.3599a8.01411,8.01411,0,0,1,0,16.02822Z",transform:"translate(-208.9778 -99.05999)",fill:"#ccc"}),f.exports.createElement("path",{d:"M635.85911,390.6071H506.51316a3.847,3.847,0,0,1-3.84277-3.84277V285.81706a3.847,3.847,0,0,1,3.84277-3.84277H635.85911a3.847,3.847,0,0,1,3.84277,3.84277V386.76433A3.847,3.847,0,0,1,635.85911,390.6071Z",transform:"translate(-208.9778 -99.05999)",fill:"#ccc"})),Ta=t=>{if(!t)return null;const n=new Date(`${t}Z`);return Math.floor(n.getTime()/1e3)},Dr=({lastOnline:t})=>{const n=Math.floor(Date.now()/1e3),o=Ta(t);return!t||o===null?e(v,{border:"1px solid",borderColor:"gray.400",_dark:{borderColor:"gray.600"},className:"circle"}):n-o<=60?e(v,{bg:"green.300",_dark:{bg:"green.500"},className:"circle pulse green"}):e(v,{bg:"gray.400",_dark:{bg:"gray.600"},className:"circle"})},Ma=t=>{if(!t)return null;const n=new Date(t+"Z");return Math.floor(n.getTime()/1e3)},zr=({lastOnline:t})=>{const n=Math.floor(Date.now()/1e3),o=Ma(t),s=o?n-o:null,a=o?Nt(o):{status:"",time:"Not Connected Yet"};return e(d,{display:"inline-block",fontSize:"xs",fontWeight:"medium",ml:"2",color:"gray.600",_dark:{color:"gray.400"},children:s&&s<=60?"Online":s?`${a.time} ago`:a.time})},Na=S(Io,{baseStyle:{w:4,h:4}}),Pa=S(vo,{baseStyle:{w:4,h:4}}),Ur=5;function Fa(t,n,o){if(o0&&(a[0]=0,a[1]="prev-more"),a[a.length-1]{const{filters:t,onFilterChange:n,users:{total:o}}=z(),{limit:s,offset:a}=t,i=(a||0)/(s||1),l=Math.ceil(o/(s||1)),p=Fa(l,i,7),g=b=>{n({...t,offset:b*s})},w=b=>{n({...t,limit:parseInt(b.target.value)}),os(b.target.value)},{t:x}=H();return r(_,{justifyContent:"space-between",mt:4,w:"full",display:"flex",columnGap:{lg:4,md:0},rowGap:{md:0,base:4},flexDirection:{md:"row",base:"column"},children:[e(v,{order:{base:2,md:1},children:r(_,{children:[r(Ne,{minW:"60px",value:s,onChange:w,size:"sm",rounded:"md",children:[e("option",{children:"10"}),e("option",{children:"20"}),e("option",{children:"30"})]}),e(d,{whiteSpace:"nowrap",fontSize:"sm",children:x("itemsPerPage")})]})}),r(Do,{size:"sm",isAttached:!0,variant:"outline",order:{base:1,md:2},children:[e(P,{leftIcon:e(Na,{}),onClick:g.bind(null,i-1),isDisabled:i===0||l===0,children:x("previous")}),p.map(b=>typeof b=="string"?e(P,{children:"..."},b):e(P,{variant:b===i?"solid":"outline",onClick:g.bind(null,b),children:b+1},b)),e(P,{rightIcon:e(Pa,{}),onClick:g.bind(null,i+1),isDisabled:i+1===l||l===0,children:x("next")})]})]})},jt=({expiryDate:t,status:n,compact:o=!1,showDetail:s=!0,extraText:a})=>{const{t:i}=H(),l=Nt(t),p=Oe[n].icon;return r(ie,{children:[r(E,{colorScheme:Oe[n].statusColor,rounded:"full",display:"inline-flex",px:3,py:1,columnGap:o?1:2,alignItems:"center",children:[e(p,{w:o?3:4}),s&&r(d,{textTransform:"capitalize",fontSize:o?".7rem":".875rem",lineHeight:o?"1rem":"1.25rem",fontWeight:"medium",letterSpacing:"tighter",children:[n&&i(`status.${n}`),a&&`: ${a}`]})]}),s&&t&&e(d,{display:"inline-block",fontSize:"xs",fontWeight:"medium",ml:"2",color:"gray.600",_dark:{color:"gray.400"},children:i(l.status,{time:l.time})})]})},Oa=S(Aa),qe={baseStyle:{w:{base:4,md:5},h:{base:4,md:5}}},Ha=S(zo,qe),ja=S(nn,qe),Er=S(Uo,qe),Ba=S(qt,qe),$a=S(Jr,qe),Va=S(rn,qe),Ga=S(nn,{baseStyle:{width:"15px",height:"15px"}}),Ya=t=>{for(var n=0;n{const{used:n,total:o,dataLimitResetStrategy:s,totalUsedTraffic:a}=t,i=o===0||o===null;return e(_,{justifyContent:"space-between",fontSize:"xs",fontWeight:"medium",color:"gray.600",_dark:{color:"gray.400"},children:r(d,{children:[ae(n)," /"," ",i?e(d,{as:"span",fontFamily:"system-ui",children:"\u221E"}):ae(o)]})})},Rr=t=>{const{used:n,total:o,dataLimitResetStrategy:s,totalUsedTraffic:a,...i}=t,l=o===0||o===null,p=!l&&n/o*100>=100;return r(ie,{children:[e(Eo,{orientation:"horizontal",value:l?100:Math.min(n/o*100,100),colorScheme:p?"red":"primary",...i,children:e(Ro,{h:"6px",borderRadius:"full",children:e(Lo,{borderRadius:"full"})})}),r(_,{justifyContent:"space-between",fontSize:"xs",fontWeight:"medium",color:"gray.600",_dark:{color:"gray.400"},children:[r(d,{children:[ae(n)," /"," ",l?e(d,{as:"span",fontFamily:"system-ui",children:"\u221E"}):ae(o)+(s&&s!=="no_reset"?" "+q("userDialog.resetStrategy"+Ya(s)):"")]}),r(d,{children:[q("usersTable.total"),": ",ae(a)]})]})]})},ht=({sort:t,column:n})=>t.includes(n)?e(Ga,{transform:t.startsWith("-")?void 0:"rotate(180deg)"}):null,Qa=t=>{const{filters:n,users:{users:o},users:s,onEditingUser:a,onFilterChange:i}=z(),{t:l}=H(),[p,g]=f.exports.useState(void 0),w=We({base:120,lg:72})||72,[x,b]=f.exports.useState(`${w}px`),h=We({base:!1,md:!0});f.exports.useEffect(()=>{const u=()=>{const c=document.querySelectorAll("#filters")[0];b(`${c.offsetHeight}px`)};window.addEventListener("scroll",u)},[]);const m=o.length!==s.total,I=u=>{let c=n.sort;c.includes(u)?c.startsWith("-")?c="-created_at":c="-"+u:c=u,i({sort:c})},C=u=>{i({status:u.target.value.length>0?u.target.value:void 0})},A=u=>{g(u===p?void 0:u)};return r(v,{id:"users-table",overflowX:{base:"unset",md:"unset"},children:[e(yt,{allowMultiple:!0,display:{base:"block",md:"none"},index:p,children:r(mr,{orientation:"vertical",zIndex:"docked",...t,children:[e(gr,{zIndex:"docked",position:"relative",children:r(Be,{children:[e(Le,{position:"sticky",top:x,minW:"120px",pl:4,pr:4,cursor:"pointer",onClick:I.bind(null,"username"),children:r(_,{children:[e("span",{children:l("users")}),e(ht,{sort:n.sort,column:"username"})]})}),e(Le,{position:"sticky",top:x,minW:"50px",pl:0,pr:0,w:"140px",cursor:"pointer",children:r(_,{spacing:0,position:"relative",children:[r(d,{position:"absolute",_dark:{bg:"gray.750"},_light:{bg:"#F9FAFB"},userSelect:"none",pointerEvents:"none",zIndex:1,w:"100%",children:[l("usersTable.status"),n.status?": "+n.status:""]}),r(Ne,{value:n.sort,fontSize:"xs",fontWeight:"extrabold",textTransform:"uppercase",cursor:"pointer",p:0,border:0,h:"auto",w:"auto",icon:e(ie,{}),_focusVisible:{border:"0 !important"},onChange:C,children:[e("option",{}),e("option",{children:"active"}),e("option",{children:"on_hold"}),e("option",{children:"disabled"}),e("option",{children:"limited"}),e("option",{children:"expired"})]})]})}),e(Le,{position:"sticky",top:x,minW:"100px",cursor:"pointer",pr:0,onClick:I.bind(null,"used_traffic"),children:r(_,{children:[e("span",{children:l("usersTable.dataUsage")}),e(ht,{sort:n.sort,column:"used_traffic"})]})}),e(Le,{position:"sticky",top:x,minW:"32px",w:"32px",p:0,cursor:"pointer"})]})}),e(fr,{children:!h&&(o==null?void 0:o.map((u,c)=>r(f.exports.Fragment,{children:[r(Be,{onClick:A.bind(null,c),cursor:"pointer",children:[e(be,{borderBottom:0,minW:"100px",pl:4,pr:4,maxW:"calc(100vw - 50px - 32px - 100px - 48px)",children:r("div",{className:"flex-status",children:[e(Dr,{lastOnline:u.online_at}),e(d,{isTruncated:!0,children:u.username})]})}),e(be,{borderBottom:0,minW:"50px",pl:0,pr:0,children:e(jt,{compact:!0,showDetail:!1,expiryDate:u.expire,status:u.status})}),e(be,{borderBottom:0,minW:"100px",pr:0,children:e(Za,{totalUsedTraffic:u.lifetime_used_traffic,dataLimitResetStrategy:u.data_limit_reset_strategy,used:u.used_traffic,total:u.data_limit,colorScheme:Oe[u.status].bandWidthColor})}),e(be,{p:0,borderBottom:0,w:"32px",minW:"32px",children:e(ja,{color:"gray.600",_dark:{color:"gray.400"},transition:"transform .2s ease-out",transform:p===c?"rotate(180deg)":"0deg"})})]}),e(Be,{className:"collapsible",onClick:A.bind(null,c),children:e(be,{p:0,colSpan:4,children:r(Ve,{border:0,children:[e(Ge,{display:"none"}),e(Ye,{border:0,cursor:"pointer",px:6,py:3,children:r(N,{justifyContent:"space-between",spacing:"4",children:[r(N,{alignItems:"flex-start",w:"full",spacing:-1,children:[e(d,{textTransform:"capitalize",fontSize:"xs",fontWeight:"bold",color:"gray.600",_dark:{color:"gray.400"},children:l("usersTable.dataUsage")}),e(v,{width:"full",minW:"230px",children:e(Rr,{totalUsedTraffic:u.lifetime_used_traffic,dataLimitResetStrategy:u.data_limit_reset_strategy,used:u.used_traffic,total:u.data_limit,colorScheme:Oe[u.status].bandWidthColor})})]}),r(_,{w:"full",justifyContent:"space-between",children:[r(v,{width:"full",children:[e(jt,{compact:!0,expiryDate:u.expire,status:u.status}),e(zr,{lastOnline:u.online_at})]}),r(_,{children:[e(Lr,{user:u}),e(re,{label:l("userDialog.editUser"),placement:"top",children:e(V,{p:"0 !important","aria-label":"Edit user",bg:"transparent",_dark:{_hover:{bg:"gray.700"}},size:{base:"sm",md:"md"},onClick:F=>{F.stopPropagation(),a(u)},children:e(Va,{})})})]})]})]})})]})})})]},u.username)))})]})}),r(mr,{orientation:"vertical",display:{base:"none",md:"table"},...t,children:[e(gr,{zIndex:"docked",position:"relative",children:r(Be,{children:[e(Le,{position:"sticky",top:{base:"unset",md:x},minW:"140px",cursor:"pointer",onClick:I.bind(null,"username"),children:r(_,{children:[e("span",{children:l("username")}),e(ht,{sort:n.sort,column:"username"})]})}),e(Le,{position:"sticky",top:{base:"unset",md:x},width:"400px",minW:"150px",cursor:"pointer",children:r(_,{position:"relative",gap:"5px",children:[r(d,{_dark:{bg:"gray.750"},_light:{bg:"#F9FAFB"},userSelect:"none",pointerEvents:"none",zIndex:1,children:[l("usersTable.status"),n.status?": "+n.status:""]}),e(d,{children:"/"}),e(ht,{sort:n.sort,column:"expire"}),e(_,{onClick:I.bind(null,"expire"),children:e(d,{children:"Sort by expire"})}),r(Ne,{fontSize:"xs",fontWeight:"extrabold",textTransform:"uppercase",cursor:"pointer",position:"absolute",p:0,left:"-40px",border:0,h:"auto",w:"auto",icon:e(ie,{}),_focusVisible:{border:"0 !important"},value:n.sort,onChange:C,children:[e("option",{}),e("option",{children:"active"}),e("option",{children:"on_hold"}),e("option",{children:"disabled"}),e("option",{children:"limited"}),e("option",{children:"expired"})]})]})}),e(Le,{position:"sticky",top:{base:"unset",md:x},width:"350px",minW:"230px",cursor:"pointer",onClick:I.bind(null,"used_traffic"),children:r(_,{children:[e("span",{children:l("usersTable.dataUsage")}),e(ht,{sort:n.sort,column:"used_traffic"})]})}),e(Le,{position:"sticky",top:{base:"unset",md:x},width:"200px",minW:"180px"})]})}),r(fr,{children:[h&&(o==null?void 0:o.map((u,c)=>r(Be,{className:bt("interactive",{"last-row":c===o.length-1}),onClick:()=>a(u),children:[e(be,{minW:"140px",children:r("div",{className:"flex-status",children:[e(Dr,{lastOnline:u.online_at}),u.username,e(zr,{lastOnline:u.online_at})]})}),e(be,{width:"400px",minW:"150px",children:e(jt,{expiryDate:u.expire,status:u.status})}),e(be,{width:"350px",minW:"230px",children:e(Rr,{totalUsedTraffic:u.lifetime_used_traffic,dataLimitResetStrategy:u.data_limit_reset_strategy,used:u.used_traffic,total:u.data_limit,colorScheme:Oe[u.status].bandWidthColor})}),e(be,{width:"200px",minW:"180px",children:e(Lr,{user:u})})]},u.username))),o.length==0&&e(Be,{children:e(be,{colSpan:4,children:e(qa,{isFiltered:m})})})]})]}),e(Wa,{})]})},Lr=({user:t})=>{const{setQRCode:n,setSubLink:o}=z(),s=t.links.join(`\r -`),[a,i]=f.exports.useState([-1,!1]);return f.exports.useEffect(()=>{a[1]&&setTimeout(()=>{i([-1,!1])},1e3)},[a]),r(_,{justifyContent:"flex-end",onClick:l=>{l.preventDefault(),l.stopPropagation()},children:[e(br,{text:t.subscription_url.startsWith("/")?window.location.origin+t.subscription_url:t.subscription_url,onCopy:()=>{i([0,!0])},children:e("div",{children:e(re,{label:a[0]==0&&a[1]?q("usersTable.copied"):q("usersTable.copyLink"),placement:"top",children:e(V,{p:"0 !important","aria-label":"copy subscription link",bg:"transparent",_dark:{_hover:{bg:"gray.700"}},size:{base:"sm",md:"md"},children:a[0]==0&&a[1]?e(Er,{}):e(Ba,{})})})})}),e(br,{text:s,onCopy:()=>{i([1,!0])},children:e("div",{children:e(re,{label:a[0]==1&&a[1]?q("usersTable.copied"):q("usersTable.copyConfigs"),placement:"top",children:e(V,{p:"0 !important","aria-label":"copy configs",bg:"transparent",_dark:{_hover:{bg:"gray.700"}},size:{base:"sm",md:"md"},children:a[0]==1&&a[1]?e(Er,{}):e(Ha,{})})})})}),e(re,{label:"QR Code",placement:"top",children:e(V,{p:"0 !important","aria-label":"qr code",bg:"transparent",_dark:{_hover:{bg:"gray.700"}},size:{base:"sm",md:"md"},onClick:()=>{n(t.links),o(t.subscription_url)},children:e($a,{})})})]})},qa=({isFiltered:t})=>{const{onCreateUser:n}=z();return r(v,{padding:"5",py:"8",display:"flex",alignItems:"center",flexDirection:"column",gap:4,w:"full",children:[e(Oa,{maxHeight:"200px",maxWidth:"200px",_dark:{'path[fill="#fff"]':{fill:"gray.800"},'path[fill="#f2f2f2"], path[fill="#e6e6e6"], path[fill="#ccc"]':{fill:"gray.700"},'circle[fill="#3182CE"]':{fill:"primary.300"}},_light:{'path[fill="#f2f2f2"], path[fill="#e6e6e6"], path[fill="#ccc"]':{fill:"gray.300"},'circle[fill="#3182CE"]':{fill:"primary.500"}}}),e(d,{fontWeight:"medium",color:"gray.600",_dark:{color:"gray.400"},children:t?q("usersTable.noUserMatched"):q("usersTable.noUser")}),!t&&e(P,{size:"sm",colorScheme:"primary",onClick:()=>n(!0),children:q("createUser")})]})},Xa=()=>(f.exports.useEffect(()=>{z.getState().refetchUsers(),as()},[]),r(N,{justifyContent:"space-between",minH:"100vh",p:"6",rowGap:4,children:[r(v,{w:"full",children:[e(Fs,{}),e(rs,{mt:"4"}),e(ws,{}),e(Qa,{}),e(La,{}),e(bs,{}),e(ga,{}),e(Js,{}),e(ya,{}),e(wa,{}),e(ia,{}),e(ha,{}),e(ba,{}),e(fs,{})]}),e(dn,{})]})),Ja=t=>f.exports.createElement("svg",{viewBox:"0 0 747 747",fill:"none",xmlns:"http://www.w3.org/2000/svg",...t},f.exports.createElement("path",{d:"M746.671 209.652V77.6572C746.671 72.9384 743.827 68.6832 739.468 66.8811C735.108 65.0738 730.093 66.0739 726.754 69.4072L579.354 216.807C577.453 202.386 570.203 189.203 559.037 179.87C547.875 170.542 533.615 165.744 519.083 166.432C504.551 167.12 490.807 173.24 480.573 183.583L414.375 249.776C412.417 235.391 405.141 222.25 393.985 212.959C382.823 203.662 368.594 198.88 354.083 199.552C339.578 200.224 325.849 206.302 315.594 216.588L274.343 257.828L19.9167 3.41515C16.5781 0.0818157 11.5625 -0.918184 7.20306 0.889149C2.84373 2.69648 0 6.94648 0 11.6651V143.649C0 146.743 1.22917 149.712 3.41667 151.899L191.843 340.339L3.41667 528.753C1.2292 530.94 0 533.909 0 537.003V668.997C0 673.716 2.84373 677.971 7.20306 679.773C11.5624 681.581 16.578 680.58 19.9167 677.247L167.317 529.847C169.285 544.233 176.561 557.358 187.718 566.65C198.869 575.947 213.098 580.728 227.603 580.066C242.103 579.404 255.838 573.342 266.098 563.071L332.295 496.874V496.879C334.259 511.264 341.535 524.395 352.691 533.686C363.853 542.977 378.082 547.759 392.587 547.092C407.093 546.421 420.822 540.348 431.077 530.066L472.327 488.826L726.754 743.239C728.941 745.427 731.91 746.656 735.004 746.656C736.535 746.661 738.056 746.359 739.473 745.77C743.832 743.963 746.671 739.708 746.671 734.989V602.994C746.671 599.901 745.442 596.932 743.254 594.744L554.827 406.318L743.254 217.904H743.259C745.447 215.717 746.676 212.748 746.676 209.654L746.671 209.652ZM23.3373 39.8118L257.844 274.318L208.328 323.818L23.3413 138.818L23.3373 39.8118ZM723.337 706.825L488.831 472.318L538.347 422.818L723.333 607.818L723.337 706.825ZM23.3373 541.825L332.097 233.078C338.764 226.719 347.624 223.172 356.843 223.172C366.056 223.172 374.916 226.719 381.588 233.078C388.151 239.641 391.838 248.548 391.838 257.828C391.838 267.114 388.151 276.016 381.588 282.577L23.3347 640.831L23.3373 541.825ZM249.604 546.575C240.755 555.419 227.864 558.872 215.781 555.638C203.703 552.398 194.265 542.961 191.027 530.883C187.792 518.8 191.245 505.91 200.089 497.06L497.076 200.074C505.92 191.23 518.811 187.772 530.893 191.011C542.971 194.246 552.409 203.678 555.648 215.76C558.888 227.839 555.434 240.73 546.591 249.572L249.604 546.575ZM723.337 204.815L414.577 513.562C407.911 519.926 399.051 523.473 389.832 523.473C380.618 523.473 371.753 519.926 365.087 513.562C358.529 506.999 354.842 498.098 354.842 488.816C354.842 479.535 358.529 470.634 365.087 464.071L723.34 105.818L723.337 204.815Z",fill:"currentColor"})),Ka=y.object({username:y.string().min(1,"login.fieldRequired"),password:y.string().min(1,"login.fieldRequired")}),ei=S(Ja,{baseStyle:{strokeWidth:"10px",w:12,h:12}}),ti=S(Ao,{baseStyle:{w:5,h:5,strokeWidth:"2px"}}),Ar=()=>{var b,h;const[t,n]=f.exports.useState(""),[o,s]=f.exports.useState(!1),a=To(),{t:i}=H();let l=Mo();const{register:p,formState:{errors:g},handleSubmit:w}=Qe({resolver:xt(Ka)});f.exports.useEffect(()=>{Qo(),l.pathname!=="/login"&&a("/login",{replace:!0})},[]);const x=m=>{n("");const I=new FormData;I.append("username",m.username),I.append("password",m.password),I.append("grant_type","password"),s(!0),O("/admin/token",{method:"post",body:I}).then(({access_token:C})=>{Zo(C),a("/")}).catch(C=>{n(C.response._data.detail)}).finally(s.bind(null,!1))};return r(N,{justifyContent:"space-between",minH:"100vh",p:"6",w:"full",children:[r(v,{w:"full",children:[e(_,{justifyContent:"end",w:"full",children:e(hn,{})}),e(_,{w:"full",justifyContent:"center",alignItems:"center",children:r(v,{w:"full",maxW:"340px",mt:"6",children:[r(N,{alignItems:"center",w:"full",children:[e(ei,{}),e(d,{fontSize:"2xl",fontWeight:"semibold",children:i("login.loginYourAccount")}),e(d,{color:"gray.600",_dark:{color:"gray.400"},children:i("login.welcomeBack")})]}),e(v,{w:"full",maxW:"300px",m:"auto",pt:"4",children:e("form",{onSubmit:w(x),children:r(N,{mt:4,rowGap:2,children:[e(L,{children:e(Me,{w:"full",placeholder:i("username"),...p("username"),error:i((b=g==null?void 0:g.username)==null?void 0:b.message)})}),e(L,{children:e(Me,{w:"full",type:"password",placeholder:i("password"),...p("password"),error:i((h=g==null?void 0:g.password)==null?void 0:h.message)})}),t&&r(gt,{status:"error",rounded:"md",children:[e(Ut,{}),e(Yr,{children:t})]}),r(P,{isLoading:o,type:"submit",w:"full",colorScheme:"primary",children:[e(ti,{marginRight:1}),i("login")]})]})})})]})})]}),e(dn,{})]})},ri=()=>O("/admin",{headers:{Authorization:`Bearer ${Et()}`}}),ni=No([{path:"/",element:e(Xa,{}),errorElement:e(Ar,{}),loader:ri},{path:"/login/",element:e(Ar,{})}]);function oi(){return e("main",{className:"p-8",children:e(Po,{router:ni})})}$.extend(Fo);$.extend(Wo);$.extend(Oo);$.extend(Ho);$.extend(jo);on(Bo.get()||"light");$o.createRoot(document.getElementById("root")).render(e($t.StrictMode,{children:e(Vo,{theme:Yo,children:e(Go,{client:Gt,children:e(oi,{})})})})); diff --git a/app/dashboard/build/statics/locales/en.json b/app/dashboard/build/statics/locales/en.json index a20a4dab9..f8a09fdae 100644 --- a/app/dashboard/build/statics/locales/en.json +++ b/app/dashboard/build/statics/locales/en.json @@ -37,6 +37,7 @@ "hostsDialog.addHost": "Add host", "hostsDialog.advancedOptions": "Advanced options", "hostsDialog.allowinsecure": "Allow Insecure", + "hostsDialog.useSniAsHost": "Use sni as host", "hostsDialog.alpn": "ALPN", "hostsDialog.apply": "Apply", "hostsDialog.currentServer": "IP Address of current server", diff --git a/app/dashboard/build/statics/locales/fa.json b/app/dashboard/build/statics/locales/fa.json index a85930811..734e1c215 100644 --- a/app/dashboard/build/statics/locales/fa.json +++ b/app/dashboard/build/statics/locales/fa.json @@ -42,6 +42,7 @@ "hostsDialog.addHost": "افزودن هاست", "hostsDialog.advancedOptions": "تنظیمات پیشرفته", "hostsDialog.allowinsecure": "Allow Insecure", + "hostsDialog.useSniAsHost": "استفاده از sni به عنوان هاست", "hostsDialog.alpn": "ALPN", "hostsDialog.apply": "اعمال", "hostsDialog.currentServer": "IP کنونی سرور", diff --git a/app/dashboard/build/statics/locales/ru.json b/app/dashboard/build/statics/locales/ru.json index 4ad11a232..2a57c5f7d 100644 --- a/app/dashboard/build/statics/locales/ru.json +++ b/app/dashboard/build/statics/locales/ru.json @@ -37,6 +37,7 @@ "hostsDialog.addHost": "Добавить хост", "hostsDialog.advancedOptions": "Дополнительные опции", "hostsDialog.allowinsecure": "Allow Insecure", + "hostsDialog.useSniAsHost": "Use sni as host", "hostsDialog.alpn": "ALPN", "hostsDialog.apply": "Применить", "hostsDialog.currentServer": "IP текущего сервера", @@ -188,4 +189,4 @@ "usersTable.noUserMatched": "Похоже, нет пользователя, соответствующего вашему запросу", "usersTable.status": "Статус", "usersTable.total": "Всего" -} +} \ No newline at end of file diff --git a/app/dashboard/build/statics/locales/zh.json b/app/dashboard/build/statics/locales/zh.json index d43e52dbd..59ead3914 100644 --- a/app/dashboard/build/statics/locales/zh.json +++ b/app/dashboard/build/statics/locales/zh.json @@ -37,6 +37,7 @@ "hostsDialog.addHost": "添加主机", "hostsDialog.advancedOptions": "高级选项", "hostsDialog.allowinsecure": "允许不安全连接", + "hostsDialog.useSniAsHost": "Use sni as host", "hostsDialog.alpn": "ALPN", "hostsDialog.apply": "保存", "hostsDialog.currentServer": "当前服务器的 IP 地址", @@ -188,5 +189,5 @@ "usersTable.noUserMatched": "没有找到您搜索的用户", "usersTable.status": "状态", "usersTable.sortByExpire": "按过期时间排序", - "usersTable.total": "总共", -} + "usersTable.total": "总共" +} \ No newline at end of file diff --git a/app/dashboard/build/statics/logo.2507bd68.svg b/app/dashboard/build/statics/logo.3890828c.svg similarity index 100% rename from app/dashboard/build/statics/logo.2507bd68.svg rename to app/dashboard/build/statics/logo.3890828c.svg diff --git a/app/dashboard/build/statics/vendor.3f3f0bc0.js b/app/dashboard/build/statics/vendor.e36f197f.js similarity index 100% rename from app/dashboard/build/statics/vendor.3f3f0bc0.js rename to app/dashboard/build/statics/vendor.e36f197f.js diff --git a/app/dashboard/src/components/RadioGroup.tsx b/app/dashboard/src/components/RadioGroup.tsx index 38725dcf7..41fe5455c 100644 --- a/app/dashboard/src/components/RadioGroup.tsx +++ b/app/dashboard/src/components/RadioGroup.tsx @@ -27,7 +27,14 @@ import { useDashboard, } from "contexts/DashboardContext"; import { t } from "i18next"; -import { FC, forwardRef, PropsWithChildren, useState } from "react"; +import { + FC, + forwardRef, + PropsWithChildren, + useEffect, + useMemo, + useState, +} from "react"; import { ControllerRenderProps, useFormContext, @@ -136,6 +143,7 @@ const RadioCard: FC< description: string; toggleAccordion: () => void; isSelected: boolean; + ss2022Method?: string | null; } > > = ({ @@ -144,6 +152,7 @@ const RadioCard: FC< description, toggleAccordion, isSelected, + ss2022Method, ...props }) => { const form = useFormContext(); @@ -437,11 +446,13 @@ const RadioCard: FC< fontSize="xs" size="sm" borderRadius="6px" + isDisabled={Boolean(ss2022Method)} {...form.register("proxies.shadowsocks.method")} > {shadowsocksMethods.map((method) => ( ))} @@ -467,6 +478,23 @@ export type RadioGroupProps = ControllerRenderProps & { export const RadioGroup = forwardRef( ({ name, list, onChange, disabled, ...props }, ref) => { const form = useFormContext(); + const ssInbounds = + useDashboard.getState().inbounds.get("shadowsocks") || []; + const ss2022Method = useMemo(() => { + const methods = ssInbounds + .map((i) => i.method) + .filter((m): m is string => Boolean(m)); + if (methods.length && methods.every((m) => m.startsWith("2022-"))) { + return methods[0]; + } + return null; + }, [ssInbounds]); + + useEffect(() => { + if (ss2022Method) { + form.setValue("proxies.shadowsocks.method", ss2022Method); + } + }, [form, ss2022Method]); const [expandedAccordions, setExpandedAccordions] = useState([]); const toggleAccordion = (i: number) => { @@ -526,6 +554,7 @@ export const RadioGroup = forwardRef( isSelected={ !!(props.value as string[]).find((v) => v === value.title) } + ss2022Method={ss2022Method} {...getCheckboxProps({ value: value.title })} /> ); diff --git a/app/dashboard/src/constants/Proxies.tsx b/app/dashboard/src/constants/Proxies.tsx index 7a1aa46af..47520c479 100644 --- a/app/dashboard/src/constants/Proxies.tsx +++ b/app/dashboard/src/constants/Proxies.tsx @@ -72,6 +72,9 @@ export const XTLSFlows = [ ]; export const shadowsocksMethods = [ + "2022-blake3-aes-256-gcm", + "2022-blake3-aes-128-gcm", + "2022-blake3-chacha20-poly1305", "aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305", diff --git a/app/dashboard/src/contexts/DashboardContext.tsx b/app/dashboard/src/contexts/DashboardContext.tsx index 16a006bb3..046a33ea9 100644 --- a/app/dashboard/src/contexts/DashboardContext.tsx +++ b/app/dashboard/src/contexts/DashboardContext.tsx @@ -25,7 +25,9 @@ export type InboundType = { protocol: ProtocolType; network: string; tls: string; - port?: number; + port?: number | string | null; + method?: string | null; + server_psk?: string | null; }; export type Inbounds = Map; diff --git a/app/models/proxy.py b/app/models/proxy.py index 174922b65..79e0d8862 100644 --- a/app/models/proxy.py +++ b/app/models/proxy.py @@ -1,12 +1,14 @@ +import base64 +import binascii import json import re from enum import Enum from typing import Optional, Union from uuid import UUID, uuid4 -from pydantic import BaseModel, ConfigDict, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator -from app.utils.system import random_password +from app.utils.system import generate_ss2022_key, random_password from xray_api.types.account import ( ShadowsocksAccount, ShadowsocksMethods, @@ -94,6 +96,29 @@ class ShadowsocksSettings(ProxySettings): def revoke(self): self.password = random_password() + @field_validator("password", mode="after") + @classmethod + def ensure_ss2022_key(cls, v: str, info: ValidationInfo): + method = info.data.get("method") + + if isinstance(method, ShadowsocksMethods): + method_value = method.value + else: + method_value = str(method) if method else "" + + if not method_value.startswith("2022-"): + return v + + expected_size = 16 if method_value.endswith("aes-128-gcm") else 32 + try: + decoded = base64.b64decode(v or "", validate=True) + if len(decoded) == expected_size: + return v + except (binascii.Error, TypeError, ValueError): + pass + + return generate_ss2022_key(method_value) + class ProxyHostSecurity(str, Enum): inbound_default = "inbound_default" @@ -204,4 +229,6 @@ class ProxyInbound(BaseModel): protocol: ProxyTypes network: str tls: str - port: Union[int, str] + port: Optional[Union[int, str]] = None + method: Optional[str] = None + server_psk: Optional[str] = None diff --git a/app/subscription/clash.py b/app/subscription/clash.py index b987d5eb2..df92434c8 100644 --- a/app/subscription/clash.py +++ b/app/subscription/clash.py @@ -260,6 +260,9 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): proxy_remark = self._remark_validation(remark) + inbound_method = inbound.get("method") or inbound.get("settings", {}).get("method", "") + inbound_psk = inbound.get("server_psk") or inbound.get("settings", {}).get("password", "") + node = self.make_node( name=remark, remark=proxy_remark, @@ -288,8 +291,12 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): node['password'] = settings['password'] elif inbound['protocol'] == 'shadowsocks': - node['password'] = settings['password'] - node['cipher'] = settings['method'] + if inbound_method.startswith("2022-"): + node['password'] = f"{inbound_psk}:{settings['password']}" + node['cipher'] = inbound_method + else: + node['password'] = settings['password'] + node['cipher'] = settings['method'] else: return @@ -351,6 +358,9 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): proxy_remark = self._remark_validation(remark) + inbound_method = inbound.get("method") or inbound.get("settings", {}).get("method", "") + inbound_psk = inbound.get("server_psk") or inbound.get("settings", {}).get("password", "") + node = self.make_node( name=remark, remark=proxy_remark, @@ -388,8 +398,12 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): node['password'] = settings['password'] elif inbound['protocol'] == 'shadowsocks': - node['password'] = settings['password'] - node['cipher'] = settings['method'] + if inbound_method.startswith("2022-"): + node['password'] = f"{inbound_psk}:{settings['password']}" + node['cipher'] = inbound_method + else: + node['password'] = settings['password'] + node['cipher'] = settings['method'] else: return diff --git a/app/subscription/singbox.py b/app/subscription/singbox.py index 57c1eee52..fa974eca0 100644 --- a/app/subscription/singbox.py +++ b/app/subscription/singbox.py @@ -287,6 +287,8 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): net = inbound["network"] path = inbound["path"] + inbound_method = inbound.get("method") or inbound.get("settings", {}).get("method", "") + inbound_psk = inbound.get("server_psk") or inbound.get("settings", {}).get("password", "") # not supported by sing-box if net in ("kcp", "splithttp", "xhttp") or (net == "quic" and inbound["header_type"] != "none"): @@ -330,7 +332,11 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): outbound['password'] = settings['password'] elif inbound['protocol'] == 'shadowsocks': - outbound['password'] = settings['password'] - outbound['method'] = settings['method'] + if inbound_method.startswith("2022-"): + outbound['password'] = f"{inbound_psk}:{settings['password']}" + outbound['method'] = inbound_method + else: + outbound['password'] = settings['password'] + outbound['method'] = settings['method'] self.add_outbound(outbound) diff --git a/app/subscription/v2ray.py b/app/subscription/v2ray.py index 30c0b60ba..70d6a3a70 100644 --- a/app/subscription/v2ray.py +++ b/app/subscription/v2ray.py @@ -148,12 +148,23 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): ) elif inbound["protocol"] == "shadowsocks": + inbound_method = inbound.get("method") or inbound.get("settings", {}).get("method", "") + inbound_psk = inbound.get("server_psk") or inbound.get("settings", {}).get("password", "") + + if inbound_method.startswith("2022-"): + user_key = settings.get("password", "") + password = f"{inbound_psk}:{user_key}" + method = inbound_method + else: + password = settings["password"] + method = settings["method"] + link = self.shadowsocks( remark=remark, address=address, port=inbound["port"], - password=settings["password"], - method=settings["method"], + password=password, + method=method, ) else: return @@ -998,6 +1009,8 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): noise = inbound['noise_setting'] path = inbound["path"] multi_mode = inbound.get("multiMode", False) + inbound_method = inbound.get("method") or inbound.get("settings", {}).get("method", "") + inbound_psk = inbound.get("server_psk") or inbound.get("settings", {}).get("password", "") if net in ["grpc", "gun"]: if multi_mode: @@ -1032,10 +1045,20 @@ def add(self, remark: str, address: str, inbound: dict, settings: dict): password=settings['password']) elif inbound['protocol'] == 'shadowsocks': - outbound["settings"] = self.shadowsocks_config(address=address, - port=port, - password=settings['password'], - method=settings['method']) + if inbound_method.startswith("2022-"): + outbound["settings"] = self.shadowsocks_config( + address=address, + port=port, + password=f"{inbound_psk}:{settings['password']}", + method=inbound_method, + ) + else: + outbound["settings"] = self.shadowsocks_config( + address=address, + port=port, + password=settings['password'], + method=settings['method'], + ) outbounds = [outbound] dialer_proxy = '' diff --git a/app/utils/system.py b/app/utils/system.py index b7a40eacb..32b2b4202 100644 --- a/app/utils/system.py +++ b/app/utils/system.py @@ -1,3 +1,4 @@ +import base64 import ipaddress import math import secrets @@ -97,6 +98,13 @@ def random_password() -> str: return secrets.token_urlsafe(16) +def generate_ss2022_key(method: str = "2022-blake3-aes-256-gcm") -> str: + """Generate a base64-encoded PSK for Shadowsocks 2022.""" + + size = 16 if method.endswith("aes-128-gcm") else 32 + return base64.b64encode(secrets.token_bytes(size)).decode() + + def check_port(port: int) -> bool: s = socket.socket() try: diff --git a/app/xray/config.py b/app/xray/config.py index 75d7d19d5..284af120f 100644 --- a/app/xray/config.py +++ b/app/xray/config.py @@ -1,5 +1,7 @@ from __future__ import annotations +import base64 +import binascii import json from collections import defaultdict from copy import deepcopy @@ -9,11 +11,13 @@ import commentjson from sqlalchemy import func +from app import logger from app.db import GetDB from app.db import models as db_models from app.models.proxy import ProxyTypes from app.models.user import UserStatus from app.utils.crypto import get_cert_SANs +from app.utils.system import generate_ss2022_key from config import DEBUG, XRAY_EXCLUDE_INBOUND_TAGS, XRAY_FALLBACKS_INBOUND_TAG @@ -26,6 +30,18 @@ def merge_dicts(a, b): # B will override A dictionary key and values return a +def _ss2022_expected_key_size(method: str) -> int: + return 16 if str(method).endswith("aes-128-gcm") else 32 + + +def _is_valid_ss2022_key(key: str, method: str) -> bool: + try: + decoded = base64.b64decode(key or "", validate=True) + return len(decoded) == _ss2022_expected_key_size(method) + except (binascii.Error, ValueError, TypeError): + return False + + class XRayConfig(dict): def __init__(self, config: Union[dict, str, PosixPath] = {}, @@ -140,7 +156,31 @@ def _validate(self): if not outbound.get("tag"): raise ValueError("all outbounds must have a unique tag") + def _validate_ss2022_server_psk(self, inbound_tag: str, method: str, server_psk: str): + if not server_psk: + raise ValueError(f"Inbound {inbound_tag}: invalid SS2022 server_psk (missing)") + + if not _is_valid_ss2022_key(server_psk, method): + raise ValueError( + f"Inbound {inbound_tag}: invalid SS2022 server_psk (must be base64 with {_ss2022_expected_key_size(method)} bytes)" + ) + def _resolve_inbounds(self): + # At the moment Marzban stores a single Shadowsocks method/password per user. + # To avoid silently generating wrong keys, forbid multiple SS2022 inbounds. + ss2022_tags = [ + inbound.get("tag") + for inbound in self.get("inbounds", []) + if inbound.get("protocol") == ProxyTypes.Shadowsocks.value + and isinstance(inbound.get("settings", {}).get("method"), str) + and inbound.get("settings", {}).get("method", "").startswith("2022-") + ] + if len(ss2022_tags) > 1: + raise ValueError( + "Only one Shadowsocks 2022 inbound is supported because users hold a single SS2022 credential. " + f"Found multiple SS2022 inbounds: {', '.join(filter(None, ss2022_tags))}" + ) + for inbound in self['inbounds']: if not inbound['protocol'] in ProxyTypes._value2member_map_: continue @@ -334,6 +374,23 @@ def _resolve_inbounds(self): elif host and isinstance(host, list): settings['host'] = host[0] + inbound_settings = inbound.get('settings', {}) + + if inbound['protocol'] == ProxyTypes.Shadowsocks.value: + method = inbound_settings.get('method', '') + settings['method'] = method + settings['server_psk'] = inbound_settings.get('password', '') + + if isinstance(method, str) and method.startswith('2022-'): + self._validate_ss2022_server_psk(inbound['tag'], method, settings['server_psk']) + # Ensure Xray treats the inbound as UserManager: keep at least one placeholder client. + clients = inbound_settings.get('clients') + if isinstance(clients, list) and len(clients) == 0: + inbound_settings['clients'].append({ + "email": "__bootstrap__", + "password": generate_ss2022_key(method) + }) + self.inbounds.append(settings) self.inbounds_by_tag[inbound['tag']] = settings @@ -358,6 +415,28 @@ def to_json(self, **json_kwargs): def copy(self): return deepcopy(self) + def _ensure_ss2022_user_key(self, db, user_id: int, inbound_method: str, key: str): + if _is_valid_ss2022_key(key, inbound_method): + return key, False + + new_key = generate_ss2022_key(inbound_method) + + try: + dbproxy = db.query(db_models.Proxy).filter( + db_models.Proxy.user_id == user_id, + db_models.Proxy.type == ProxyTypes.Shadowsocks + ).first() + + if dbproxy: + settings = dict(dbproxy.settings or {}) + settings["password"] = new_key + dbproxy.settings = settings + db.commit() + except Exception: + db.rollback() + + return new_key, True + def include_db_users(self) -> XRayConfig: config = self.copy() @@ -402,15 +481,42 @@ def include_db_users(self) -> XRayConfig: for inbound in inbounds: clients = config.get_inbound(inbound['tag'])['settings']['clients'] + raw_inbound = config.get_inbound(inbound['tag']) or {} + inbound_settings = raw_inbound.get('settings', {}) + inbound_method = inbound.get('method') or inbound_settings.get('method', '') + inbound_server_psk = inbound.get('server_psk') or inbound_settings.get('password', '') + is_ss2022 = ( + inbound.get('protocol') == ProxyTypes.Shadowsocks.value + and isinstance(inbound_method, str) + and inbound_method.startswith('2022-') + ) + + if is_ss2022: + self._validate_ss2022_server_psk(inbound['tag'], inbound_method, inbound_server_psk) + for row in rows: user_id, username, settings, excluded_inbound_tags = row if excluded_inbound_tags and inbound['tag'] in excluded_inbound_tags: continue + settings = settings or {} + client_settings = dict(settings) + + if is_ss2022: + client_settings.pop('method', None) + user_key, regenerated = self._ensure_ss2022_user_key( + db, user_id, inbound_method, client_settings.get('password') + ) + client_settings['password'] = user_key + if regenerated: + logger.warning( + f"Regenerated SS2022 key for user {username} (id={user_id}) on inbound {inbound['tag']}" + ) + client = { "email": f"{user_id}.{username}", - **settings + **client_settings } # XTLS currently only supports transmission methods of TCP and mKCP diff --git a/app/xray/operations.py b/app/xray/operations.py index 081949fce..7709d2434 100644 --- a/app/xray/operations.py +++ b/app/xray/operations.py @@ -10,7 +10,7 @@ from app.utils.concurrency import threaded_function from app.xray.node import XRayNode from xray_api import XRay as XRayAPI -from xray_api.types.account import Account, XTLSFlows +from xray_api.types.account import Account, Shadowsocks2022Account, XTLSFlows if TYPE_CHECKING: from app.db import User as DBUser @@ -63,12 +63,42 @@ def add_user(dbuser: "DBUser"): for proxy_type, inbound_tags in user.inbounds.items(): for inbound_tag in inbound_tags: inbound = xray.config.inbounds_by_tag.get(inbound_tag, {}) + raw_inbound = xray.config.get_inbound(inbound_tag) or {} try: proxy_settings = user.proxies[proxy_type].dict(no_obj=True) except KeyError: - pass - account = proxy_type.account_model(email=email, **proxy_settings) + continue + + if proxy_type.name == "Shadowsocks": + inbound_settings = raw_inbound.get("settings", {}) + inbound_method = inbound.get("method") or inbound_settings.get("method", "") + inbound_server_psk = inbound.get("server_psk") or inbound_settings.get("password", "") + user_method = proxy_settings.get("method", "") + + is_ss2022_inbound = isinstance(inbound_method, str) and inbound_method.startswith("2022-") + is_ss2022_user = isinstance(user_method, str) and user_method.startswith("2022-") + + if is_ss2022_inbound: + if not inbound_server_psk: + raise ValueError( + f"Inbound '{inbound_tag}' has SS2022 method but missing server_psk" + ) + + account = Shadowsocks2022Account( + email=email, + key=proxy_settings.get("password", ""), + method=inbound_method, + ) + elif is_ss2022_user: + raise ValueError( + f"Inbound '{inbound_tag}' is not SS2022 but user selected SS2022 method" + ) + else: + account = proxy_type.account_model(email=email, **proxy_settings) + + else: + account = proxy_type.account_model(email=email, **proxy_settings) # XTLS currently only supports transmission methods of TCP and mKCP if getattr(account, 'flow', None) and ( @@ -109,12 +139,42 @@ def update_user(dbuser: "DBUser"): for inbound_tag in inbound_tags: active_inbounds.append(inbound_tag) inbound = xray.config.inbounds_by_tag.get(inbound_tag, {}) + raw_inbound = xray.config.get_inbound(inbound_tag) or {} try: proxy_settings = user.proxies[proxy_type].dict(no_obj=True) except KeyError: - pass - account = proxy_type.account_model(email=email, **proxy_settings) + continue + + if proxy_type.name == "Shadowsocks": + inbound_settings = raw_inbound.get("settings", {}) + inbound_method = inbound.get("method") or inbound_settings.get("method", "") + inbound_server_psk = inbound.get("server_psk") or inbound_settings.get("password", "") + user_method = proxy_settings.get("method", "") + + is_ss2022_inbound = isinstance(inbound_method, str) and inbound_method.startswith("2022-") + is_ss2022_user = isinstance(user_method, str) and user_method.startswith("2022-") + + if is_ss2022_inbound: + if not inbound_server_psk: + raise ValueError( + f"Inbound '{inbound_tag}' has SS2022 method but missing server_psk" + ) + + account = Shadowsocks2022Account( + email=email, + key=proxy_settings.get("password", ""), + method=inbound_method, + ) + elif is_ss2022_user: + raise ValueError( + f"Inbound '{inbound_tag}' is not SS2022 but user selected SS2022 method" + ) + else: + account = proxy_type.account_model(email=email, **proxy_settings) + + else: + account = proxy_type.account_model(email=email, **proxy_settings) # XTLS currently only supports transmission methods of TCP and mKCP if getattr(account, 'flow', None) and ( @@ -225,6 +285,15 @@ def connect_node(node_id, config=None): _change_node_status(node_id, NodeStatus.connected, version=version) logger.info(f"Connected to \"{dbnode.name}\" node, xray run on v{version}") + try: + version_parts = tuple(int(part) for part in str(version).split('.')[:3]) + if version_parts and version_parts < (1, 8, 0): + logger.warning( + f"Node '{dbnode.name}' runs xray-core v{version}; SS2022 gRPC user management may be unsupported" + ) + except Exception: + pass + except Exception as e: _change_node_status(node_id, NodeStatus.error, message=str(e)) logger.info(f"Unable to connect to \"{dbnode.name}\" node") diff --git a/xray_api/types/__init__.py b/xray_api/types/__init__.py index 50ca48b96..744e23040 100644 --- a/xray_api/types/__init__.py +++ b/xray_api/types/__init__.py @@ -1,3 +1,11 @@ -from .account import (Account, ShadowsocksAccount, TrojanAccount, VLESSAccount, - VMessAccount) +from .account import ( + Account, + Shadowsocks2022Account, + ShadowsocksAccount, + ShadowsocksMethods, + TrojanAccount, + VLESSAccount, + VMessAccount, + XTLSFlows, +) from .message import Message, TypedMessage diff --git a/xray_api/types/account.py b/xray_api/types/account.py index 3f2343609..01af6d2ab 100755 --- a/xray_api/types/account.py +++ b/xray_api/types/account.py @@ -1,4 +1,4 @@ -from abc import ABC, abstractmethod +from abc import ABC, abstractmethod from enum import Enum from uuid import UUID @@ -13,6 +13,7 @@ from ..proto.proxy.vless.account_pb2 import Account as VLESSAccountPb2 from ..proto.proxy.vmess.account_pb2 import Account as VMessAccountPb2 from .message import Message +from ..proto.common.serial.typed_message_pb2 import TypedMessage class Account(BaseModel, ABC): @@ -59,11 +60,15 @@ def message(self): return Message(TrojanAccountPb2(password=self.password)) -class ShadowsocksMethods(Enum): +class ShadowsocksMethods(str, Enum): AES_128_GCM = 'aes-128-gcm' AES_256_GCM = 'aes-256-gcm' CHACHA20_POLY1305 = 'chacha20-ietf-poly1305' + SS_2022_BLAKE3_AES_128_GCM = '2022-blake3-aes-128-gcm' + SS_2022_BLAKE3_AES_256_GCM = '2022-blake3-aes-256-gcm' + SS_2022_BLAKE3_CHACHA20_POLY1305 = '2022-blake3-chacha20-poly1305' + class ShadowsocksAccount(Account): password: str @@ -71,8 +76,40 @@ class ShadowsocksAccount(Account): @property def cipher_type(self): + if self.method.value.startswith('2022-'): + raise ValueError('Use Shadowsocks2022Account for 2022 methods') return self.method.name @property def message(self): return Message(ShadowsocksAccountPb2(password=self.password, cipher_type=self.cipher_type)) + + +class Shadowsocks2022Account(Account): + key: str + method: str + + @property + def message(self): + # SS2022 AddUser in xray-core expects account type "xray.proxy.shadowsocks_2022.Account" + # with a single string field `key` (field number 1). Build the wire payload manually + # to avoid depending on mismatched/generated proto stubs. + def _varint(n: int) -> bytes: + out = bytearray() + while True: + to_write = n & 0x7F + n >>= 7 + if n: + out.append(0x80 | to_write) + else: + out.append(to_write) + break + return bytes(out) + + key_bytes = self.key.encode("utf-8") + # field 1, wire type 2 (length‑delimited) -> tag 0x0A + payload = b"\x0a" + _varint(len(key_bytes)) + key_bytes + return TypedMessage( + type="xray.proxy.shadowsocks_2022.Account", + value=payload, + )