inbound.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/mhsanaei/3x-ui/v2/database"
  12. "github.com/mhsanaei/3x-ui/v2/database/model"
  13. "github.com/mhsanaei/3x-ui/v2/logger"
  14. "github.com/mhsanaei/3x-ui/v2/util/common"
  15. "github.com/mhsanaei/3x-ui/v2/xray"
  16. "gorm.io/gorm"
  17. )
  18. // InboundService provides business logic for managing Xray inbound configurations.
  19. // It handles CRUD operations for inbounds, client management, traffic monitoring,
  20. // and integration with the Xray API for real-time updates.
  21. type InboundService struct {
  22. xrayApi xray.XrayAPI
  23. }
  24. // GetInbounds retrieves all inbounds for a specific user.
  25. // Returns a slice of inbound models with their associated client statistics.
  26. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  27. db := database.GetDB()
  28. var inbounds []*model.Inbound
  29. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  30. if err != nil && err != gorm.ErrRecordNotFound {
  31. return nil, err
  32. }
  33. return inbounds, nil
  34. }
  35. // GetAllInbounds retrieves all inbounds from the database.
  36. // Returns a slice of all inbound models with their associated client statistics.
  37. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  38. db := database.GetDB()
  39. var inbounds []*model.Inbound
  40. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  41. if err != nil && err != gorm.ErrRecordNotFound {
  42. return nil, err
  43. }
  44. return inbounds, nil
  45. }
  46. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  47. db := database.GetDB()
  48. var inbounds []*model.Inbound
  49. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  50. if err != nil && err != gorm.ErrRecordNotFound {
  51. return nil, err
  52. }
  53. return inbounds, nil
  54. }
  55. func (s *InboundService) checkPortExist(listen string, port int, ignoreId int) (bool, error) {
  56. db := database.GetDB()
  57. if listen == "" || listen == "0.0.0.0" || listen == "::" || listen == "::0" {
  58. db = db.Model(model.Inbound{}).Where("port = ?", port)
  59. } else {
  60. db = db.Model(model.Inbound{}).
  61. Where("port = ?", port).
  62. Where(
  63. db.Model(model.Inbound{}).Where(
  64. "listen = ?", listen,
  65. ).Or(
  66. "listen = \"\"",
  67. ).Or(
  68. "listen = \"0.0.0.0\"",
  69. ).Or(
  70. "listen = \"::\"",
  71. ).Or(
  72. "listen = \"::0\""))
  73. }
  74. if ignoreId > 0 {
  75. db = db.Where("id != ?", ignoreId)
  76. }
  77. var count int64
  78. err := db.Count(&count).Error
  79. if err != nil {
  80. return false, err
  81. }
  82. return count > 0, nil
  83. }
  84. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  85. settings := map[string][]model.Client{}
  86. json.Unmarshal([]byte(inbound.Settings), &settings)
  87. if settings == nil {
  88. return nil, fmt.Errorf("setting is null")
  89. }
  90. clients := settings["clients"]
  91. if clients == nil {
  92. return nil, nil
  93. }
  94. return clients, nil
  95. }
  96. func (s *InboundService) getAllEmails() ([]string, error) {
  97. db := database.GetDB()
  98. var emails []string
  99. err := db.Raw(`
  100. SELECT JSON_EXTRACT(client.value, '$.email')
  101. FROM inbounds,
  102. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  103. `).Scan(&emails).Error
  104. if err != nil {
  105. return nil, err
  106. }
  107. return emails, nil
  108. }
  109. func (s *InboundService) contains(slice []string, str string) bool {
  110. lowerStr := strings.ToLower(str)
  111. for _, s := range slice {
  112. if strings.ToLower(s) == lowerStr {
  113. return true
  114. }
  115. }
  116. return false
  117. }
  118. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  119. allEmails, err := s.getAllEmails()
  120. if err != nil {
  121. return "", err
  122. }
  123. var emails []string
  124. for _, client := range clients {
  125. if client.Email != "" {
  126. if s.contains(emails, client.Email) {
  127. return client.Email, nil
  128. }
  129. if s.contains(allEmails, client.Email) {
  130. return client.Email, nil
  131. }
  132. emails = append(emails, client.Email)
  133. }
  134. }
  135. return "", nil
  136. }
  137. func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) {
  138. clients, err := s.GetClients(inbound)
  139. if err != nil {
  140. return "", err
  141. }
  142. allEmails, err := s.getAllEmails()
  143. if err != nil {
  144. return "", err
  145. }
  146. var emails []string
  147. for _, client := range clients {
  148. if client.Email != "" {
  149. if s.contains(emails, client.Email) {
  150. return client.Email, nil
  151. }
  152. if s.contains(allEmails, client.Email) {
  153. return client.Email, nil
  154. }
  155. emails = append(emails, client.Email)
  156. }
  157. }
  158. return "", nil
  159. }
  160. // AddInbound creates a new inbound configuration.
  161. // It validates port uniqueness, client email uniqueness, and required fields,
  162. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  163. // Returns the created inbound, whether Xray needs restart, and any error.
  164. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  165. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, 0)
  166. if err != nil {
  167. return inbound, false, err
  168. }
  169. if exist {
  170. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  171. }
  172. existEmail, err := s.checkEmailExistForInbound(inbound)
  173. if err != nil {
  174. return inbound, false, err
  175. }
  176. if existEmail != "" {
  177. return inbound, false, common.NewError("Duplicate email:", existEmail)
  178. }
  179. clients, err := s.GetClients(inbound)
  180. if err != nil {
  181. return inbound, false, err
  182. }
  183. // Ensure created_at and updated_at on clients in settings
  184. if len(clients) > 0 {
  185. var settings map[string]any
  186. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  187. now := time.Now().Unix() * 1000
  188. updatedClients := make([]model.Client, 0, len(clients))
  189. for _, c := range clients {
  190. if c.CreatedAt == 0 {
  191. c.CreatedAt = now
  192. }
  193. c.UpdatedAt = now
  194. updatedClients = append(updatedClients, c)
  195. }
  196. settings["clients"] = updatedClients
  197. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  198. inbound.Settings = string(bs)
  199. } else {
  200. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  201. }
  202. } else if err2 != nil {
  203. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  204. }
  205. }
  206. // Secure client ID
  207. for _, client := range clients {
  208. switch inbound.Protocol {
  209. case "trojan":
  210. if client.Password == "" {
  211. return inbound, false, common.NewError("empty client ID")
  212. }
  213. case "shadowsocks":
  214. if client.Email == "" {
  215. return inbound, false, common.NewError("empty client ID")
  216. }
  217. default:
  218. if client.ID == "" {
  219. return inbound, false, common.NewError("empty client ID")
  220. }
  221. }
  222. }
  223. db := database.GetDB()
  224. tx := db.Begin()
  225. defer func() {
  226. if err == nil {
  227. tx.Commit()
  228. } else {
  229. tx.Rollback()
  230. }
  231. }()
  232. err = tx.Save(inbound).Error
  233. if err == nil {
  234. if len(inbound.ClientStats) == 0 {
  235. for _, client := range clients {
  236. s.AddClientStat(tx, inbound.Id, &client)
  237. }
  238. }
  239. } else {
  240. return inbound, false, err
  241. }
  242. needRestart := false
  243. if inbound.Enable {
  244. s.xrayApi.Init(p.GetAPIPort())
  245. inboundJson, err1 := json.MarshalIndent(inbound.GenXrayInboundConfig(), "", " ")
  246. if err1 != nil {
  247. logger.Debug("Unable to marshal inbound config:", err1)
  248. }
  249. err1 = s.xrayApi.AddInbound(inboundJson)
  250. if err1 == nil {
  251. logger.Debug("New inbound added by api:", inbound.Tag)
  252. } else {
  253. logger.Debug("Unable to add inbound by api:", err1)
  254. needRestart = true
  255. }
  256. s.xrayApi.Close()
  257. }
  258. return inbound, needRestart, err
  259. }
  260. // DelInbound deletes an inbound configuration by ID.
  261. // It removes the inbound from the database and the running Xray instance if active.
  262. // Returns whether Xray needs restart and any error.
  263. func (s *InboundService) DelInbound(id int) (bool, error) {
  264. db := database.GetDB()
  265. var tag string
  266. needRestart := false
  267. result := db.Model(model.Inbound{}).Select("tag").Where("id = ? and enable = ?", id, true).First(&tag)
  268. if result.Error == nil {
  269. s.xrayApi.Init(p.GetAPIPort())
  270. err1 := s.xrayApi.DelInbound(tag)
  271. if err1 == nil {
  272. logger.Debug("Inbound deleted by api:", tag)
  273. } else {
  274. logger.Debug("Unable to delete inbound by api:", err1)
  275. needRestart = true
  276. }
  277. s.xrayApi.Close()
  278. } else {
  279. logger.Debug("No enabled inbound founded to removing by api", tag)
  280. }
  281. // Delete client traffics of inbounds
  282. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  283. if err != nil {
  284. return false, err
  285. }
  286. inbound, err := s.GetInbound(id)
  287. if err != nil {
  288. return false, err
  289. }
  290. clients, err := s.GetClients(inbound)
  291. if err != nil {
  292. return false, err
  293. }
  294. for _, client := range clients {
  295. err := s.DelClientIPs(db, client.Email)
  296. if err != nil {
  297. return false, err
  298. }
  299. }
  300. return needRestart, db.Delete(model.Inbound{}, id).Error
  301. }
  302. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  303. db := database.GetDB()
  304. inbound := &model.Inbound{}
  305. err := db.Model(model.Inbound{}).First(inbound, id).Error
  306. if err != nil {
  307. return nil, err
  308. }
  309. return inbound, nil
  310. }
  311. // UpdateInbound modifies an existing inbound configuration.
  312. // It validates changes, updates the database, and syncs with the running Xray instance.
  313. // Returns the updated inbound, whether Xray needs restart, and any error.
  314. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  315. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, inbound.Id)
  316. if err != nil {
  317. return inbound, false, err
  318. }
  319. if exist {
  320. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  321. }
  322. oldInbound, err := s.GetInbound(inbound.Id)
  323. if err != nil {
  324. return inbound, false, err
  325. }
  326. tag := oldInbound.Tag
  327. db := database.GetDB()
  328. tx := db.Begin()
  329. defer func() {
  330. if err != nil {
  331. tx.Rollback()
  332. } else {
  333. tx.Commit()
  334. }
  335. }()
  336. err = s.updateClientTraffics(tx, oldInbound, inbound)
  337. if err != nil {
  338. return inbound, false, err
  339. }
  340. // Ensure created_at and updated_at exist in inbound.Settings clients
  341. {
  342. var oldSettings map[string]any
  343. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  344. emailToCreated := map[string]int64{}
  345. emailToUpdated := map[string]int64{}
  346. if oldSettings != nil {
  347. if oc, ok := oldSettings["clients"].([]any); ok {
  348. for _, it := range oc {
  349. if m, ok2 := it.(map[string]any); ok2 {
  350. if email, ok3 := m["email"].(string); ok3 {
  351. switch v := m["created_at"].(type) {
  352. case float64:
  353. emailToCreated[email] = int64(v)
  354. case int64:
  355. emailToCreated[email] = v
  356. }
  357. switch v := m["updated_at"].(type) {
  358. case float64:
  359. emailToUpdated[email] = int64(v)
  360. case int64:
  361. emailToUpdated[email] = v
  362. }
  363. }
  364. }
  365. }
  366. }
  367. }
  368. var newSettings map[string]any
  369. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  370. now := time.Now().Unix() * 1000
  371. if nSlice, ok := newSettings["clients"].([]any); ok {
  372. for i := range nSlice {
  373. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  374. email, _ := m["email"].(string)
  375. if _, ok3 := m["created_at"]; !ok3 {
  376. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  377. m["created_at"] = v
  378. } else {
  379. m["created_at"] = now
  380. }
  381. }
  382. // Preserve client's updated_at if present; do not bump on parent inbound update
  383. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  384. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  385. m["updated_at"] = v
  386. }
  387. }
  388. nSlice[i] = m
  389. }
  390. }
  391. newSettings["clients"] = nSlice
  392. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  393. inbound.Settings = string(bs)
  394. }
  395. }
  396. }
  397. }
  398. oldInbound.Up = inbound.Up
  399. oldInbound.Down = inbound.Down
  400. oldInbound.Total = inbound.Total
  401. oldInbound.Remark = inbound.Remark
  402. oldInbound.Enable = inbound.Enable
  403. oldInbound.ExpiryTime = inbound.ExpiryTime
  404. oldInbound.TrafficReset = inbound.TrafficReset
  405. oldInbound.Listen = inbound.Listen
  406. oldInbound.Port = inbound.Port
  407. oldInbound.Protocol = inbound.Protocol
  408. oldInbound.Settings = inbound.Settings
  409. oldInbound.StreamSettings = inbound.StreamSettings
  410. oldInbound.Sniffing = inbound.Sniffing
  411. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  412. oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  413. } else {
  414. oldInbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  415. }
  416. needRestart := false
  417. s.xrayApi.Init(p.GetAPIPort())
  418. if s.xrayApi.DelInbound(tag) == nil {
  419. logger.Debug("Old inbound deleted by api:", tag)
  420. }
  421. if inbound.Enable {
  422. inboundJson, err2 := json.MarshalIndent(oldInbound.GenXrayInboundConfig(), "", " ")
  423. if err2 != nil {
  424. logger.Debug("Unable to marshal updated inbound config:", err2)
  425. needRestart = true
  426. } else {
  427. err2 = s.xrayApi.AddInbound(inboundJson)
  428. if err2 == nil {
  429. logger.Debug("Updated inbound added by api:", oldInbound.Tag)
  430. } else {
  431. logger.Debug("Unable to update inbound by api:", err2)
  432. needRestart = true
  433. }
  434. }
  435. }
  436. s.xrayApi.Close()
  437. return inbound, needRestart, tx.Save(oldInbound).Error
  438. }
  439. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  440. oldClients, err := s.GetClients(oldInbound)
  441. if err != nil {
  442. return err
  443. }
  444. newClients, err := s.GetClients(newInbound)
  445. if err != nil {
  446. return err
  447. }
  448. var emailExists bool
  449. for _, oldClient := range oldClients {
  450. emailExists = false
  451. for _, newClient := range newClients {
  452. if oldClient.Email == newClient.Email {
  453. emailExists = true
  454. break
  455. }
  456. }
  457. if !emailExists {
  458. err = s.DelClientStat(tx, oldClient.Email)
  459. if err != nil {
  460. return err
  461. }
  462. }
  463. }
  464. for _, newClient := range newClients {
  465. emailExists = false
  466. for _, oldClient := range oldClients {
  467. if newClient.Email == oldClient.Email {
  468. emailExists = true
  469. break
  470. }
  471. }
  472. if !emailExists {
  473. err = s.AddClientStat(tx, oldInbound.Id, &newClient)
  474. if err != nil {
  475. return err
  476. }
  477. }
  478. }
  479. return nil
  480. }
  481. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  482. clients, err := s.GetClients(data)
  483. if err != nil {
  484. return false, err
  485. }
  486. var settings map[string]any
  487. err = json.Unmarshal([]byte(data.Settings), &settings)
  488. if err != nil {
  489. return false, err
  490. }
  491. interfaceClients := settings["clients"].([]any)
  492. // Add timestamps for new clients being appended
  493. nowTs := time.Now().Unix() * 1000
  494. for i := range interfaceClients {
  495. if cm, ok := interfaceClients[i].(map[string]any); ok {
  496. if _, ok2 := cm["created_at"]; !ok2 {
  497. cm["created_at"] = nowTs
  498. }
  499. cm["updated_at"] = nowTs
  500. interfaceClients[i] = cm
  501. }
  502. }
  503. existEmail, err := s.checkEmailsExistForClients(clients)
  504. if err != nil {
  505. return false, err
  506. }
  507. if existEmail != "" {
  508. return false, common.NewError("Duplicate email:", existEmail)
  509. }
  510. oldInbound, err := s.GetInbound(data.Id)
  511. if err != nil {
  512. return false, err
  513. }
  514. // Secure client ID
  515. for _, client := range clients {
  516. switch oldInbound.Protocol {
  517. case "trojan":
  518. if client.Password == "" {
  519. return false, common.NewError("empty client ID")
  520. }
  521. case "shadowsocks":
  522. if client.Email == "" {
  523. return false, common.NewError("empty client ID")
  524. }
  525. default:
  526. if client.ID == "" {
  527. return false, common.NewError("empty client ID")
  528. }
  529. }
  530. }
  531. var oldSettings map[string]any
  532. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  533. if err != nil {
  534. return false, err
  535. }
  536. oldClients := oldSettings["clients"].([]any)
  537. oldClients = append(oldClients, interfaceClients...)
  538. oldSettings["clients"] = oldClients
  539. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  540. if err != nil {
  541. return false, err
  542. }
  543. oldInbound.Settings = string(newSettings)
  544. db := database.GetDB()
  545. tx := db.Begin()
  546. defer func() {
  547. if err != nil {
  548. tx.Rollback()
  549. } else {
  550. tx.Commit()
  551. }
  552. }()
  553. needRestart := false
  554. s.xrayApi.Init(p.GetAPIPort())
  555. for _, client := range clients {
  556. if len(client.Email) > 0 {
  557. s.AddClientStat(tx, data.Id, &client)
  558. if client.Enable {
  559. cipher := ""
  560. if oldInbound.Protocol == "shadowsocks" {
  561. cipher = oldSettings["method"].(string)
  562. }
  563. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  564. "email": client.Email,
  565. "id": client.ID,
  566. "security": client.Security,
  567. "flow": client.Flow,
  568. "password": client.Password,
  569. "cipher": cipher,
  570. })
  571. if err1 == nil {
  572. logger.Debug("Client added by api:", client.Email)
  573. } else {
  574. logger.Debug("Error in adding client by api:", err1)
  575. needRestart = true
  576. }
  577. }
  578. } else {
  579. needRestart = true
  580. }
  581. }
  582. s.xrayApi.Close()
  583. return needRestart, tx.Save(oldInbound).Error
  584. }
  585. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  586. oldInbound, err := s.GetInbound(inboundId)
  587. if err != nil {
  588. logger.Error("Load Old Data Error")
  589. return false, err
  590. }
  591. var settings map[string]any
  592. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  593. if err != nil {
  594. return false, err
  595. }
  596. email := ""
  597. client_key := "id"
  598. if oldInbound.Protocol == "trojan" {
  599. client_key = "password"
  600. }
  601. if oldInbound.Protocol == "shadowsocks" {
  602. client_key = "email"
  603. }
  604. interfaceClients := settings["clients"].([]any)
  605. var newClients []any
  606. needApiDel := false
  607. for _, client := range interfaceClients {
  608. c := client.(map[string]any)
  609. c_id := c[client_key].(string)
  610. if c_id == clientId {
  611. email, _ = c["email"].(string)
  612. needApiDel, _ = c["enable"].(bool)
  613. } else {
  614. newClients = append(newClients, client)
  615. }
  616. }
  617. if len(newClients) == 0 {
  618. return false, common.NewError("no client remained in Inbound")
  619. }
  620. settings["clients"] = newClients
  621. newSettings, err := json.MarshalIndent(settings, "", " ")
  622. if err != nil {
  623. return false, err
  624. }
  625. oldInbound.Settings = string(newSettings)
  626. db := database.GetDB()
  627. err = s.DelClientIPs(db, email)
  628. if err != nil {
  629. logger.Error("Error in delete client IPs")
  630. return false, err
  631. }
  632. needRestart := false
  633. if len(email) > 0 {
  634. notDepleted := true
  635. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  636. if err != nil {
  637. logger.Error("Get stats error")
  638. return false, err
  639. }
  640. err = s.DelClientStat(db, email)
  641. if err != nil {
  642. logger.Error("Delete stats Data Error")
  643. return false, err
  644. }
  645. if needApiDel && notDepleted {
  646. s.xrayApi.Init(p.GetAPIPort())
  647. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  648. if err1 == nil {
  649. logger.Debug("Client deleted by api:", email)
  650. needRestart = false
  651. } else {
  652. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  653. logger.Debug("User is already deleted. Nothing to do more...")
  654. } else {
  655. logger.Debug("Error in deleting client by api:", err1)
  656. needRestart = true
  657. }
  658. }
  659. s.xrayApi.Close()
  660. }
  661. }
  662. return needRestart, db.Save(oldInbound).Error
  663. }
  664. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  665. // TODO: check if TrafficReset field is updating
  666. clients, err := s.GetClients(data)
  667. if err != nil {
  668. return false, err
  669. }
  670. var settings map[string]any
  671. err = json.Unmarshal([]byte(data.Settings), &settings)
  672. if err != nil {
  673. return false, err
  674. }
  675. interfaceClients := settings["clients"].([]any)
  676. oldInbound, err := s.GetInbound(data.Id)
  677. if err != nil {
  678. return false, err
  679. }
  680. oldClients, err := s.GetClients(oldInbound)
  681. if err != nil {
  682. return false, err
  683. }
  684. oldEmail := ""
  685. newClientId := ""
  686. clientIndex := -1
  687. for index, oldClient := range oldClients {
  688. oldClientId := ""
  689. switch oldInbound.Protocol {
  690. case "trojan":
  691. oldClientId = oldClient.Password
  692. newClientId = clients[0].Password
  693. case "shadowsocks":
  694. oldClientId = oldClient.Email
  695. newClientId = clients[0].Email
  696. default:
  697. oldClientId = oldClient.ID
  698. newClientId = clients[0].ID
  699. }
  700. if clientId == oldClientId {
  701. oldEmail = oldClient.Email
  702. clientIndex = index
  703. break
  704. }
  705. }
  706. // Validate new client ID
  707. if newClientId == "" || clientIndex == -1 {
  708. return false, common.NewError("empty client ID")
  709. }
  710. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  711. existEmail, err := s.checkEmailsExistForClients(clients)
  712. if err != nil {
  713. return false, err
  714. }
  715. if existEmail != "" {
  716. return false, common.NewError("Duplicate email:", existEmail)
  717. }
  718. }
  719. var oldSettings map[string]any
  720. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  721. if err != nil {
  722. return false, err
  723. }
  724. settingsClients := oldSettings["clients"].([]any)
  725. // Preserve created_at and set updated_at for the replacing client
  726. var preservedCreated any
  727. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  728. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  729. if v, ok2 := oldMap["created_at"]; ok2 {
  730. preservedCreated = v
  731. }
  732. }
  733. }
  734. if len(interfaceClients) > 0 {
  735. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  736. if preservedCreated == nil {
  737. preservedCreated = time.Now().Unix() * 1000
  738. }
  739. newMap["created_at"] = preservedCreated
  740. newMap["updated_at"] = time.Now().Unix() * 1000
  741. interfaceClients[0] = newMap
  742. }
  743. }
  744. settingsClients[clientIndex] = interfaceClients[0]
  745. oldSettings["clients"] = settingsClients
  746. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  747. if err != nil {
  748. return false, err
  749. }
  750. oldInbound.Settings = string(newSettings)
  751. db := database.GetDB()
  752. tx := db.Begin()
  753. defer func() {
  754. if err != nil {
  755. tx.Rollback()
  756. } else {
  757. tx.Commit()
  758. }
  759. }()
  760. if len(clients[0].Email) > 0 {
  761. if len(oldEmail) > 0 {
  762. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  763. if err != nil {
  764. return false, err
  765. }
  766. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  767. if err != nil {
  768. return false, err
  769. }
  770. } else {
  771. s.AddClientStat(tx, data.Id, &clients[0])
  772. }
  773. } else {
  774. err = s.DelClientStat(tx, oldEmail)
  775. if err != nil {
  776. return false, err
  777. }
  778. err = s.DelClientIPs(tx, oldEmail)
  779. if err != nil {
  780. return false, err
  781. }
  782. }
  783. needRestart := false
  784. if len(oldEmail) > 0 {
  785. s.xrayApi.Init(p.GetAPIPort())
  786. if oldClients[clientIndex].Enable {
  787. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  788. if err1 == nil {
  789. logger.Debug("Old client deleted by api:", oldEmail)
  790. } else {
  791. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  792. logger.Debug("User is already deleted. Nothing to do more...")
  793. } else {
  794. logger.Debug("Error in deleting client by api:", err1)
  795. needRestart = true
  796. }
  797. }
  798. }
  799. if clients[0].Enable {
  800. cipher := ""
  801. if oldInbound.Protocol == "shadowsocks" {
  802. cipher = oldSettings["method"].(string)
  803. }
  804. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  805. "email": clients[0].Email,
  806. "id": clients[0].ID,
  807. "security": clients[0].Security,
  808. "flow": clients[0].Flow,
  809. "password": clients[0].Password,
  810. "cipher": cipher,
  811. })
  812. if err1 == nil {
  813. logger.Debug("Client edited by api:", clients[0].Email)
  814. } else {
  815. logger.Debug("Error in adding client by api:", err1)
  816. needRestart = true
  817. }
  818. }
  819. s.xrayApi.Close()
  820. } else {
  821. logger.Debug("Client old email not found")
  822. needRestart = true
  823. }
  824. return needRestart, tx.Save(oldInbound).Error
  825. }
  826. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  827. var err error
  828. db := database.GetDB()
  829. tx := db.Begin()
  830. defer func() {
  831. if err != nil {
  832. tx.Rollback()
  833. } else {
  834. tx.Commit()
  835. }
  836. }()
  837. err = s.addInboundTraffic(tx, inboundTraffics)
  838. if err != nil {
  839. return err, false
  840. }
  841. err = s.addClientTraffic(tx, clientTraffics)
  842. if err != nil {
  843. return err, false
  844. }
  845. needRestart0, count, err := s.autoRenewClients(tx)
  846. if err != nil {
  847. logger.Warning("Error in renew clients:", err)
  848. } else if count > 0 {
  849. logger.Debugf("%v clients renewed", count)
  850. }
  851. needRestart1, count, err := s.disableInvalidClients(tx)
  852. if err != nil {
  853. logger.Warning("Error in disabling invalid clients:", err)
  854. } else if count > 0 {
  855. logger.Debugf("%v clients disabled", count)
  856. }
  857. needRestart2, count, err := s.disableInvalidInbounds(tx)
  858. if err != nil {
  859. logger.Warning("Error in disabling invalid inbounds:", err)
  860. } else if count > 0 {
  861. logger.Debugf("%v inbounds disabled", count)
  862. }
  863. return nil, (needRestart0 || needRestart1 || needRestart2)
  864. }
  865. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  866. if len(traffics) == 0 {
  867. return nil
  868. }
  869. var err error
  870. for _, traffic := range traffics {
  871. if traffic.IsInbound {
  872. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  873. Updates(map[string]any{
  874. "up": gorm.Expr("up + ?", traffic.Up),
  875. "down": gorm.Expr("down + ?", traffic.Down),
  876. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  877. }).Error
  878. if err != nil {
  879. return err
  880. }
  881. }
  882. }
  883. return nil
  884. }
  885. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  886. if len(traffics) == 0 {
  887. // Empty onlineUsers
  888. if p != nil {
  889. p.SetOnlineClients(nil)
  890. }
  891. return nil
  892. }
  893. var onlineClients []string
  894. emails := make([]string, 0, len(traffics))
  895. for _, traffic := range traffics {
  896. emails = append(emails, traffic.Email)
  897. }
  898. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  899. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  900. if err != nil {
  901. return err
  902. }
  903. // Avoid empty slice error
  904. if len(dbClientTraffics) == 0 {
  905. return nil
  906. }
  907. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  908. if err != nil {
  909. return err
  910. }
  911. for dbTraffic_index := range dbClientTraffics {
  912. for traffic_index := range traffics {
  913. if dbClientTraffics[dbTraffic_index].Email == traffics[traffic_index].Email {
  914. dbClientTraffics[dbTraffic_index].Up += traffics[traffic_index].Up
  915. dbClientTraffics[dbTraffic_index].Down += traffics[traffic_index].Down
  916. dbClientTraffics[dbTraffic_index].AllTime += (traffics[traffic_index].Up + traffics[traffic_index].Down)
  917. // Add user in onlineUsers array on traffic
  918. if traffics[traffic_index].Up+traffics[traffic_index].Down > 0 {
  919. onlineClients = append(onlineClients, traffics[traffic_index].Email)
  920. dbClientTraffics[dbTraffic_index].LastOnline = time.Now().UnixMilli()
  921. }
  922. break
  923. }
  924. }
  925. }
  926. // Set onlineUsers
  927. p.SetOnlineClients(onlineClients)
  928. err = tx.Save(dbClientTraffics).Error
  929. if err != nil {
  930. logger.Warning("AddClientTraffic update data ", err)
  931. }
  932. return nil
  933. }
  934. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  935. inboundIds := make([]int, 0, len(dbClientTraffics))
  936. for _, dbClientTraffic := range dbClientTraffics {
  937. if dbClientTraffic.ExpiryTime < 0 {
  938. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  939. }
  940. }
  941. if len(inboundIds) > 0 {
  942. var inbounds []*model.Inbound
  943. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  944. if err != nil {
  945. return nil, err
  946. }
  947. for inbound_index := range inbounds {
  948. settings := map[string]any{}
  949. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  950. clients, ok := settings["clients"].([]any)
  951. if ok {
  952. var newClients []any
  953. for client_index := range clients {
  954. c := clients[client_index].(map[string]any)
  955. for traffic_index := range dbClientTraffics {
  956. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  957. oldExpiryTime := c["expiryTime"].(float64)
  958. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  959. c["expiryTime"] = newExpiryTime
  960. c["updated_at"] = time.Now().Unix() * 1000
  961. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  962. break
  963. }
  964. }
  965. // Backfill created_at and updated_at
  966. if _, ok := c["created_at"]; !ok {
  967. c["created_at"] = time.Now().Unix() * 1000
  968. }
  969. c["updated_at"] = time.Now().Unix() * 1000
  970. newClients = append(newClients, any(c))
  971. }
  972. settings["clients"] = newClients
  973. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  974. if err != nil {
  975. return nil, err
  976. }
  977. inbounds[inbound_index].Settings = string(modifiedSettings)
  978. }
  979. }
  980. err = tx.Save(inbounds).Error
  981. if err != nil {
  982. logger.Warning("AddClientTraffic update inbounds ", err)
  983. logger.Error(inbounds)
  984. }
  985. }
  986. return dbClientTraffics, nil
  987. }
  988. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  989. // check for time expired
  990. var traffics []*xray.ClientTraffic
  991. now := time.Now().Unix() * 1000
  992. var err, err1 error
  993. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  994. if err != nil {
  995. return false, 0, err
  996. }
  997. // return if there is no client to renew
  998. if len(traffics) == 0 {
  999. return false, 0, nil
  1000. }
  1001. var inbound_ids []int
  1002. var inbounds []*model.Inbound
  1003. needRestart := false
  1004. var clientsToAdd []struct {
  1005. protocol string
  1006. tag string
  1007. client map[string]any
  1008. }
  1009. for _, traffic := range traffics {
  1010. inbound_ids = append(inbound_ids, traffic.InboundId)
  1011. }
  1012. err = tx.Model(model.Inbound{}).Where("id IN ?", inbound_ids).Find(&inbounds).Error
  1013. if err != nil {
  1014. return false, 0, err
  1015. }
  1016. for inbound_index := range inbounds {
  1017. settings := map[string]any{}
  1018. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1019. clients := settings["clients"].([]any)
  1020. for client_index := range clients {
  1021. c := clients[client_index].(map[string]any)
  1022. for traffic_index, traffic := range traffics {
  1023. if traffic.Email == c["email"].(string) {
  1024. newExpiryTime := traffic.ExpiryTime
  1025. for newExpiryTime < now {
  1026. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1027. }
  1028. c["expiryTime"] = newExpiryTime
  1029. traffics[traffic_index].ExpiryTime = newExpiryTime
  1030. traffics[traffic_index].Down = 0
  1031. traffics[traffic_index].Up = 0
  1032. if !traffic.Enable {
  1033. traffics[traffic_index].Enable = true
  1034. clientsToAdd = append(clientsToAdd,
  1035. struct {
  1036. protocol string
  1037. tag string
  1038. client map[string]any
  1039. }{
  1040. protocol: string(inbounds[inbound_index].Protocol),
  1041. tag: inbounds[inbound_index].Tag,
  1042. client: c,
  1043. })
  1044. }
  1045. clients[client_index] = any(c)
  1046. break
  1047. }
  1048. }
  1049. }
  1050. settings["clients"] = clients
  1051. newSettings, err := json.MarshalIndent(settings, "", " ")
  1052. if err != nil {
  1053. return false, 0, err
  1054. }
  1055. inbounds[inbound_index].Settings = string(newSettings)
  1056. }
  1057. err = tx.Save(inbounds).Error
  1058. if err != nil {
  1059. return false, 0, err
  1060. }
  1061. err = tx.Save(traffics).Error
  1062. if err != nil {
  1063. return false, 0, err
  1064. }
  1065. if p != nil {
  1066. err1 = s.xrayApi.Init(p.GetAPIPort())
  1067. if err1 != nil {
  1068. return true, int64(len(traffics)), nil
  1069. }
  1070. for _, clientToAdd := range clientsToAdd {
  1071. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1072. if err1 != nil {
  1073. needRestart = true
  1074. }
  1075. }
  1076. s.xrayApi.Close()
  1077. }
  1078. return needRestart, int64(len(traffics)), nil
  1079. }
  1080. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1081. now := time.Now().Unix() * 1000
  1082. needRestart := false
  1083. if p != nil {
  1084. var tags []string
  1085. err := tx.Table("inbounds").
  1086. Select("inbounds.tag").
  1087. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1088. Scan(&tags).Error
  1089. if err != nil {
  1090. return false, 0, err
  1091. }
  1092. s.xrayApi.Init(p.GetAPIPort())
  1093. for _, tag := range tags {
  1094. err1 := s.xrayApi.DelInbound(tag)
  1095. if err1 == nil {
  1096. logger.Debug("Inbound disabled by api:", tag)
  1097. } else {
  1098. logger.Debug("Error in disabling inbound by api:", err1)
  1099. needRestart = true
  1100. }
  1101. }
  1102. s.xrayApi.Close()
  1103. }
  1104. result := tx.Model(model.Inbound{}).
  1105. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1106. Update("enable", false)
  1107. err := result.Error
  1108. count := result.RowsAffected
  1109. return needRestart, count, err
  1110. }
  1111. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1112. now := time.Now().Unix() * 1000
  1113. needRestart := false
  1114. if p != nil {
  1115. var results []struct {
  1116. Tag string
  1117. Email string
  1118. }
  1119. err := tx.Table("inbounds").
  1120. Select("inbounds.tag, client_traffics.email").
  1121. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  1122. Where("((client_traffics.total > 0 AND client_traffics.up + client_traffics.down >= client_traffics.total) OR (client_traffics.expiry_time > 0 AND client_traffics.expiry_time <= ?)) AND client_traffics.enable = ?", now, true).
  1123. Scan(&results).Error
  1124. if err != nil {
  1125. return false, 0, err
  1126. }
  1127. s.xrayApi.Init(p.GetAPIPort())
  1128. for _, result := range results {
  1129. err1 := s.xrayApi.RemoveUser(result.Tag, result.Email)
  1130. if err1 == nil {
  1131. logger.Debug("Client disabled by api:", result.Email)
  1132. } else {
  1133. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1134. logger.Debug("User is already disabled. Nothing to do more...")
  1135. } else {
  1136. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1137. logger.Debug("User is already disabled. Nothing to do more...")
  1138. } else {
  1139. logger.Debug("Error in disabling client by api:", err1)
  1140. needRestart = true
  1141. }
  1142. }
  1143. }
  1144. }
  1145. s.xrayApi.Close()
  1146. }
  1147. result := tx.Model(xray.ClientTraffic{}).
  1148. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1149. Update("enable", false)
  1150. err := result.Error
  1151. count := result.RowsAffected
  1152. return needRestart, count, err
  1153. }
  1154. func (s *InboundService) GetInboundTags() (string, error) {
  1155. db := database.GetDB()
  1156. var inboundTags []string
  1157. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1158. if err != nil && err != gorm.ErrRecordNotFound {
  1159. return "", err
  1160. }
  1161. tags, _ := json.Marshal(inboundTags)
  1162. return string(tags), nil
  1163. }
  1164. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1165. db := database.GetDB()
  1166. db.Exec(`
  1167. DELETE FROM client_traffics
  1168. WHERE email NOT IN (
  1169. SELECT JSON_EXTRACT(client.value, '$.email')
  1170. FROM inbounds,
  1171. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1172. )
  1173. `)
  1174. }
  1175. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1176. clientTraffic := xray.ClientTraffic{}
  1177. clientTraffic.InboundId = inboundId
  1178. clientTraffic.Email = client.Email
  1179. clientTraffic.Total = client.TotalGB
  1180. clientTraffic.ExpiryTime = client.ExpiryTime
  1181. clientTraffic.Enable = client.Enable
  1182. clientTraffic.Up = 0
  1183. clientTraffic.Down = 0
  1184. clientTraffic.Reset = client.Reset
  1185. result := tx.Create(&clientTraffic)
  1186. err := result.Error
  1187. return err
  1188. }
  1189. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1190. result := tx.Model(xray.ClientTraffic{}).
  1191. Where("email = ?", email).
  1192. Updates(map[string]any{
  1193. "enable": client.Enable,
  1194. "email": client.Email,
  1195. "total": client.TotalGB,
  1196. "expiry_time": client.ExpiryTime,
  1197. "reset": client.Reset,
  1198. })
  1199. err := result.Error
  1200. return err
  1201. }
  1202. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1203. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1204. }
  1205. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1206. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1207. }
  1208. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1209. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1210. }
  1211. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1212. db := database.GetDB()
  1213. var traffics []*xray.ClientTraffic
  1214. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1215. if err != nil {
  1216. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1217. return nil, nil, err
  1218. }
  1219. if len(traffics) > 0 {
  1220. inbound, err = s.GetInbound(traffics[0].InboundId)
  1221. return traffics[0], inbound, err
  1222. }
  1223. return nil, nil, nil
  1224. }
  1225. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1226. db := database.GetDB()
  1227. var traffics []*xray.ClientTraffic
  1228. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1229. if err != nil {
  1230. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1231. return nil, nil, err
  1232. }
  1233. if len(traffics) > 0 {
  1234. inbound, err = s.GetInbound(traffics[0].InboundId)
  1235. return traffics[0], inbound, err
  1236. }
  1237. return nil, nil, nil
  1238. }
  1239. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1240. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1241. if err != nil {
  1242. return nil, nil, err
  1243. }
  1244. if inbound == nil {
  1245. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1246. }
  1247. clients, err := s.GetClients(inbound)
  1248. if err != nil {
  1249. return nil, nil, err
  1250. }
  1251. for _, client := range clients {
  1252. if client.Email == clientEmail {
  1253. return traffic, &client, nil
  1254. }
  1255. }
  1256. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1257. }
  1258. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1259. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1260. if err != nil {
  1261. return false, err
  1262. }
  1263. if inbound == nil {
  1264. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1265. }
  1266. clientEmail := traffic.Email
  1267. oldClients, err := s.GetClients(inbound)
  1268. if err != nil {
  1269. return false, err
  1270. }
  1271. clientId := ""
  1272. for _, oldClient := range oldClients {
  1273. if oldClient.Email == clientEmail {
  1274. switch inbound.Protocol {
  1275. case "trojan":
  1276. clientId = oldClient.Password
  1277. case "shadowsocks":
  1278. clientId = oldClient.Email
  1279. default:
  1280. clientId = oldClient.ID
  1281. }
  1282. break
  1283. }
  1284. }
  1285. if len(clientId) == 0 {
  1286. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1287. }
  1288. var settings map[string]any
  1289. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1290. if err != nil {
  1291. return false, err
  1292. }
  1293. clients := settings["clients"].([]any)
  1294. var newClients []any
  1295. for client_index := range clients {
  1296. c := clients[client_index].(map[string]any)
  1297. if c["email"] == clientEmail {
  1298. c["tgId"] = tgId
  1299. c["updated_at"] = time.Now().Unix() * 1000
  1300. newClients = append(newClients, any(c))
  1301. }
  1302. }
  1303. settings["clients"] = newClients
  1304. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1305. if err != nil {
  1306. return false, err
  1307. }
  1308. inbound.Settings = string(modifiedSettings)
  1309. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1310. return needRestart, err
  1311. }
  1312. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1313. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1314. if err != nil {
  1315. return false, err
  1316. }
  1317. if inbound == nil {
  1318. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1319. }
  1320. clients, err := s.GetClients(inbound)
  1321. if err != nil {
  1322. return false, err
  1323. }
  1324. isEnable := false
  1325. for _, client := range clients {
  1326. if client.Email == clientEmail {
  1327. isEnable = client.Enable
  1328. break
  1329. }
  1330. }
  1331. return isEnable, err
  1332. }
  1333. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1334. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1335. if err != nil {
  1336. return false, false, err
  1337. }
  1338. if inbound == nil {
  1339. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1340. }
  1341. oldClients, err := s.GetClients(inbound)
  1342. if err != nil {
  1343. return false, false, err
  1344. }
  1345. clientId := ""
  1346. clientOldEnabled := false
  1347. for _, oldClient := range oldClients {
  1348. if oldClient.Email == clientEmail {
  1349. switch inbound.Protocol {
  1350. case "trojan":
  1351. clientId = oldClient.Password
  1352. case "shadowsocks":
  1353. clientId = oldClient.Email
  1354. default:
  1355. clientId = oldClient.ID
  1356. }
  1357. clientOldEnabled = oldClient.Enable
  1358. break
  1359. }
  1360. }
  1361. if len(clientId) == 0 {
  1362. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1363. }
  1364. var settings map[string]any
  1365. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1366. if err != nil {
  1367. return false, false, err
  1368. }
  1369. clients := settings["clients"].([]any)
  1370. var newClients []any
  1371. for client_index := range clients {
  1372. c := clients[client_index].(map[string]any)
  1373. if c["email"] == clientEmail {
  1374. c["enable"] = !clientOldEnabled
  1375. c["updated_at"] = time.Now().Unix() * 1000
  1376. newClients = append(newClients, any(c))
  1377. }
  1378. }
  1379. settings["clients"] = newClients
  1380. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1381. if err != nil {
  1382. return false, false, err
  1383. }
  1384. inbound.Settings = string(modifiedSettings)
  1385. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1386. if err != nil {
  1387. return false, needRestart, err
  1388. }
  1389. return !clientOldEnabled, needRestart, nil
  1390. }
  1391. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1392. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1393. if err != nil {
  1394. return false, err
  1395. }
  1396. if inbound == nil {
  1397. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1398. }
  1399. oldClients, err := s.GetClients(inbound)
  1400. if err != nil {
  1401. return false, err
  1402. }
  1403. clientId := ""
  1404. for _, oldClient := range oldClients {
  1405. if oldClient.Email == clientEmail {
  1406. switch inbound.Protocol {
  1407. case "trojan":
  1408. clientId = oldClient.Password
  1409. case "shadowsocks":
  1410. clientId = oldClient.Email
  1411. default:
  1412. clientId = oldClient.ID
  1413. }
  1414. break
  1415. }
  1416. }
  1417. if len(clientId) == 0 {
  1418. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1419. }
  1420. var settings map[string]any
  1421. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1422. if err != nil {
  1423. return false, err
  1424. }
  1425. clients := settings["clients"].([]any)
  1426. var newClients []any
  1427. for client_index := range clients {
  1428. c := clients[client_index].(map[string]any)
  1429. if c["email"] == clientEmail {
  1430. c["limitIp"] = count
  1431. c["updated_at"] = time.Now().Unix() * 1000
  1432. newClients = append(newClients, any(c))
  1433. }
  1434. }
  1435. settings["clients"] = newClients
  1436. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1437. if err != nil {
  1438. return false, err
  1439. }
  1440. inbound.Settings = string(modifiedSettings)
  1441. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1442. return needRestart, err
  1443. }
  1444. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1445. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1446. if err != nil {
  1447. return false, err
  1448. }
  1449. if inbound == nil {
  1450. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1451. }
  1452. oldClients, err := s.GetClients(inbound)
  1453. if err != nil {
  1454. return false, err
  1455. }
  1456. clientId := ""
  1457. for _, oldClient := range oldClients {
  1458. if oldClient.Email == clientEmail {
  1459. switch inbound.Protocol {
  1460. case "trojan":
  1461. clientId = oldClient.Password
  1462. case "shadowsocks":
  1463. clientId = oldClient.Email
  1464. default:
  1465. clientId = oldClient.ID
  1466. }
  1467. break
  1468. }
  1469. }
  1470. if len(clientId) == 0 {
  1471. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1472. }
  1473. var settings map[string]any
  1474. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1475. if err != nil {
  1476. return false, err
  1477. }
  1478. clients := settings["clients"].([]any)
  1479. var newClients []any
  1480. for client_index := range clients {
  1481. c := clients[client_index].(map[string]any)
  1482. if c["email"] == clientEmail {
  1483. c["expiryTime"] = expiry_time
  1484. c["updated_at"] = time.Now().Unix() * 1000
  1485. newClients = append(newClients, any(c))
  1486. }
  1487. }
  1488. settings["clients"] = newClients
  1489. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1490. if err != nil {
  1491. return false, err
  1492. }
  1493. inbound.Settings = string(modifiedSettings)
  1494. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1495. return needRestart, err
  1496. }
  1497. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1498. if totalGB < 0 {
  1499. return false, common.NewError("totalGB must be >= 0")
  1500. }
  1501. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1502. if err != nil {
  1503. return false, err
  1504. }
  1505. if inbound == nil {
  1506. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1507. }
  1508. oldClients, err := s.GetClients(inbound)
  1509. if err != nil {
  1510. return false, err
  1511. }
  1512. clientId := ""
  1513. for _, oldClient := range oldClients {
  1514. if oldClient.Email == clientEmail {
  1515. switch inbound.Protocol {
  1516. case "trojan":
  1517. clientId = oldClient.Password
  1518. case "shadowsocks":
  1519. clientId = oldClient.Email
  1520. default:
  1521. clientId = oldClient.ID
  1522. }
  1523. break
  1524. }
  1525. }
  1526. if len(clientId) == 0 {
  1527. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1528. }
  1529. var settings map[string]any
  1530. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1531. if err != nil {
  1532. return false, err
  1533. }
  1534. clients := settings["clients"].([]any)
  1535. var newClients []any
  1536. for client_index := range clients {
  1537. c := clients[client_index].(map[string]any)
  1538. if c["email"] == clientEmail {
  1539. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1540. c["updated_at"] = time.Now().Unix() * 1000
  1541. newClients = append(newClients, any(c))
  1542. }
  1543. }
  1544. settings["clients"] = newClients
  1545. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1546. if err != nil {
  1547. return false, err
  1548. }
  1549. inbound.Settings = string(modifiedSettings)
  1550. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1551. return needRestart, err
  1552. }
  1553. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1554. db := database.GetDB()
  1555. // Reset traffic stats in ClientTraffic table
  1556. result := db.Model(xray.ClientTraffic{}).
  1557. Where("email = ?", clientEmail).
  1558. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1559. err := result.Error
  1560. if err != nil {
  1561. return err
  1562. }
  1563. return nil
  1564. }
  1565. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1566. needRestart := false
  1567. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1568. if err != nil {
  1569. return false, err
  1570. }
  1571. if !traffic.Enable {
  1572. inbound, err := s.GetInbound(id)
  1573. if err != nil {
  1574. return false, err
  1575. }
  1576. clients, err := s.GetClients(inbound)
  1577. if err != nil {
  1578. return false, err
  1579. }
  1580. for _, client := range clients {
  1581. if client.Email == clientEmail && client.Enable {
  1582. s.xrayApi.Init(p.GetAPIPort())
  1583. cipher := ""
  1584. if string(inbound.Protocol) == "shadowsocks" {
  1585. var oldSettings map[string]any
  1586. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1587. if err != nil {
  1588. return false, err
  1589. }
  1590. cipher = oldSettings["method"].(string)
  1591. }
  1592. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  1593. "email": client.Email,
  1594. "id": client.ID,
  1595. "security": client.Security,
  1596. "flow": client.Flow,
  1597. "password": client.Password,
  1598. "cipher": cipher,
  1599. })
  1600. if err1 == nil {
  1601. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1602. } else {
  1603. logger.Debug("Error in enabling client by api:", err1)
  1604. needRestart = true
  1605. }
  1606. s.xrayApi.Close()
  1607. break
  1608. }
  1609. }
  1610. }
  1611. traffic.Up = 0
  1612. traffic.Down = 0
  1613. traffic.Enable = true
  1614. db := database.GetDB()
  1615. err = db.Save(traffic).Error
  1616. if err != nil {
  1617. return false, err
  1618. }
  1619. return needRestart, nil
  1620. }
  1621. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1622. db := database.GetDB()
  1623. now := time.Now().Unix() * 1000
  1624. return db.Transaction(func(tx *gorm.DB) error {
  1625. whereText := "inbound_id "
  1626. if id == -1 {
  1627. whereText += " > ?"
  1628. } else {
  1629. whereText += " = ?"
  1630. }
  1631. // Reset client traffics
  1632. result := tx.Model(xray.ClientTraffic{}).
  1633. Where(whereText, id).
  1634. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1635. if result.Error != nil {
  1636. return result.Error
  1637. }
  1638. // Update lastTrafficResetTime for the inbound(s)
  1639. inboundWhereText := "id "
  1640. if id == -1 {
  1641. inboundWhereText += " > ?"
  1642. } else {
  1643. inboundWhereText += " = ?"
  1644. }
  1645. result = tx.Model(model.Inbound{}).
  1646. Where(inboundWhereText, id).
  1647. Update("last_traffic_reset_time", now)
  1648. return result.Error
  1649. })
  1650. }
  1651. func (s *InboundService) ResetAllTraffics() error {
  1652. db := database.GetDB()
  1653. result := db.Model(model.Inbound{}).
  1654. Where("user_id > ?", 0).
  1655. Updates(map[string]any{"up": 0, "down": 0})
  1656. err := result.Error
  1657. return err
  1658. }
  1659. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1660. db := database.GetDB()
  1661. tx := db.Begin()
  1662. defer func() {
  1663. if err == nil {
  1664. tx.Commit()
  1665. } else {
  1666. tx.Rollback()
  1667. }
  1668. }()
  1669. whereText := "reset = 0 and inbound_id "
  1670. if id < 0 {
  1671. whereText += "> ?"
  1672. } else {
  1673. whereText += "= ?"
  1674. }
  1675. // Only consider truly depleted clients: expired OR traffic exhausted
  1676. now := time.Now().Unix() * 1000
  1677. depletedClients := []xray.ClientTraffic{}
  1678. err = db.Model(xray.ClientTraffic{}).
  1679. Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).
  1680. Select("inbound_id, GROUP_CONCAT(email) as email").
  1681. Group("inbound_id").
  1682. Find(&depletedClients).Error
  1683. if err != nil {
  1684. return err
  1685. }
  1686. for _, depletedClient := range depletedClients {
  1687. emails := strings.Split(depletedClient.Email, ",")
  1688. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  1689. if err != nil {
  1690. return err
  1691. }
  1692. var oldSettings map[string]any
  1693. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1694. if err != nil {
  1695. return err
  1696. }
  1697. oldClients := oldSettings["clients"].([]any)
  1698. var newClients []any
  1699. for _, client := range oldClients {
  1700. deplete := false
  1701. c := client.(map[string]any)
  1702. for _, email := range emails {
  1703. if email == c["email"].(string) {
  1704. deplete = true
  1705. break
  1706. }
  1707. }
  1708. if !deplete {
  1709. newClients = append(newClients, client)
  1710. }
  1711. }
  1712. if len(newClients) > 0 {
  1713. oldSettings["clients"] = newClients
  1714. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1715. if err != nil {
  1716. return err
  1717. }
  1718. oldInbound.Settings = string(newSettings)
  1719. err = tx.Save(oldInbound).Error
  1720. if err != nil {
  1721. return err
  1722. }
  1723. } else {
  1724. // Delete inbound if no client remains
  1725. s.DelInbound(depletedClient.InboundId)
  1726. }
  1727. }
  1728. // Delete stats only for truly depleted clients
  1729. err = tx.Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).Delete(xray.ClientTraffic{}).Error
  1730. if err != nil {
  1731. return err
  1732. }
  1733. return nil
  1734. }
  1735. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  1736. db := database.GetDB()
  1737. var inbounds []*model.Inbound
  1738. // Retrieve inbounds where settings contain the given tgId
  1739. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  1740. if err != nil && err != gorm.ErrRecordNotFound {
  1741. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  1742. return nil, err
  1743. }
  1744. var emails []string
  1745. for _, inbound := range inbounds {
  1746. clients, err := s.GetClients(inbound)
  1747. if err != nil {
  1748. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  1749. continue
  1750. }
  1751. for _, client := range clients {
  1752. if client.TgID == tgId {
  1753. emails = append(emails, client.Email)
  1754. }
  1755. }
  1756. }
  1757. var traffics []*xray.ClientTraffic
  1758. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  1759. if err != nil {
  1760. if err == gorm.ErrRecordNotFound {
  1761. logger.Warning("No ClientTraffic records found for emails:", emails)
  1762. return nil, nil
  1763. }
  1764. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", emails, err)
  1765. return nil, err
  1766. }
  1767. return traffics, nil
  1768. }
  1769. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1770. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  1771. t, client, err := s.GetClientByEmail(email)
  1772. if err != nil {
  1773. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1774. return nil, err
  1775. }
  1776. if t != nil && client != nil {
  1777. t.Enable = client.Enable
  1778. t.SubId = client.SubID
  1779. return t, nil
  1780. }
  1781. return nil, nil
  1782. }
  1783. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1784. db := database.GetDB()
  1785. result := db.Model(xray.ClientTraffic{}).
  1786. Where("email = ?", email).
  1787. Updates(map[string]any{"up": upload, "down": download})
  1788. err := result.Error
  1789. if err != nil {
  1790. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1791. return err
  1792. }
  1793. return nil
  1794. }
  1795. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  1796. db := database.GetDB()
  1797. var traffics []xray.ClientTraffic
  1798. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  1799. SELECT JSON_EXTRACT(client.value, '$.email') as email
  1800. FROM inbounds,
  1801. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1802. WHERE
  1803. JSON_EXTRACT(client.value, '$.id') in (?)
  1804. )`, id).Find(&traffics).Error
  1805. if err != nil {
  1806. logger.Debug(err)
  1807. return nil, err
  1808. }
  1809. // Reconcile enable flag with client settings per email to avoid stale DB value
  1810. for i := range traffics {
  1811. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1812. traffics[i].Enable = client.Enable
  1813. traffics[i].SubId = client.SubID
  1814. }
  1815. }
  1816. return traffics, err
  1817. }
  1818. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1819. db := database.GetDB()
  1820. inbound := &model.Inbound{}
  1821. traffic = &xray.ClientTraffic{}
  1822. // Search for inbound settings that contain the query
  1823. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1824. if err != nil {
  1825. if err == gorm.ErrRecordNotFound {
  1826. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1827. return nil, err
  1828. }
  1829. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1830. return nil, err
  1831. }
  1832. traffic.InboundId = inbound.Id
  1833. // Unmarshal settings to get clients
  1834. settings := map[string][]model.Client{}
  1835. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1836. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1837. return nil, err
  1838. }
  1839. clients := settings["clients"]
  1840. for _, client := range clients {
  1841. if (client.ID == query || client.Password == query) && client.Email != "" {
  1842. traffic.Email = client.Email
  1843. break
  1844. }
  1845. }
  1846. if traffic.Email == "" {
  1847. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1848. return nil, gorm.ErrRecordNotFound
  1849. }
  1850. // Retrieve ClientTraffic based on the found email
  1851. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1852. if err != nil {
  1853. if err == gorm.ErrRecordNotFound {
  1854. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1855. return nil, err
  1856. }
  1857. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1858. return nil, err
  1859. }
  1860. return traffic, nil
  1861. }
  1862. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  1863. db := database.GetDB()
  1864. InboundClientIps := &model.InboundClientIps{}
  1865. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  1866. if err != nil {
  1867. return "", err
  1868. }
  1869. return InboundClientIps.Ips, nil
  1870. }
  1871. func (s *InboundService) ClearClientIps(clientEmail string) error {
  1872. db := database.GetDB()
  1873. result := db.Model(model.InboundClientIps{}).
  1874. Where("client_email = ?", clientEmail).
  1875. Update("ips", "")
  1876. err := result.Error
  1877. if err != nil {
  1878. return err
  1879. }
  1880. return nil
  1881. }
  1882. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1883. db := database.GetDB()
  1884. var inbounds []*model.Inbound
  1885. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1886. if err != nil && err != gorm.ErrRecordNotFound {
  1887. return nil, err
  1888. }
  1889. return inbounds, nil
  1890. }
  1891. func (s *InboundService) MigrationRequirements() {
  1892. db := database.GetDB()
  1893. tx := db.Begin()
  1894. var err error
  1895. defer func() {
  1896. if err == nil {
  1897. tx.Commit()
  1898. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  1899. logger.Warningf("VACUUM failed: %v", dbErr)
  1900. }
  1901. } else {
  1902. tx.Rollback()
  1903. }
  1904. }()
  1905. // Calculate and backfill all_time from up+down for inbounds and clients
  1906. err = tx.Exec(`
  1907. UPDATE inbounds
  1908. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  1909. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  1910. `).Error
  1911. if err != nil {
  1912. return
  1913. }
  1914. err = tx.Exec(`
  1915. UPDATE client_traffics
  1916. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  1917. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  1918. `).Error
  1919. if err != nil {
  1920. return
  1921. }
  1922. // Fix inbounds based problems
  1923. var inbounds []*model.Inbound
  1924. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  1925. if err != nil && err != gorm.ErrRecordNotFound {
  1926. return
  1927. }
  1928. for inbound_index := range inbounds {
  1929. settings := map[string]any{}
  1930. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1931. clients, ok := settings["clients"].([]any)
  1932. if ok {
  1933. // Fix Client configuration problems
  1934. var newClients []any
  1935. for client_index := range clients {
  1936. c := clients[client_index].(map[string]any)
  1937. // Add email='' if it is not exists
  1938. if _, ok := c["email"]; !ok {
  1939. c["email"] = ""
  1940. }
  1941. // Convert string tgId to int64
  1942. if _, ok := c["tgId"]; ok {
  1943. var tgId any = c["tgId"]
  1944. if tgIdStr, ok2 := tgId.(string); ok2 {
  1945. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  1946. if err == nil {
  1947. c["tgId"] = tgIdInt64
  1948. }
  1949. }
  1950. }
  1951. // Remove "flow": "xtls-rprx-direct"
  1952. if _, ok := c["flow"]; ok {
  1953. if c["flow"] == "xtls-rprx-direct" {
  1954. c["flow"] = ""
  1955. }
  1956. }
  1957. // Backfill created_at and updated_at
  1958. if _, ok := c["created_at"]; !ok {
  1959. c["created_at"] = time.Now().Unix() * 1000
  1960. }
  1961. c["updated_at"] = time.Now().Unix() * 1000
  1962. newClients = append(newClients, any(c))
  1963. }
  1964. settings["clients"] = newClients
  1965. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1966. if err != nil {
  1967. return
  1968. }
  1969. inbounds[inbound_index].Settings = string(modifiedSettings)
  1970. }
  1971. // Add client traffic row for all clients which has email
  1972. modelClients, err := s.GetClients(inbounds[inbound_index])
  1973. if err != nil {
  1974. return
  1975. }
  1976. for _, modelClient := range modelClients {
  1977. if len(modelClient.Email) > 0 {
  1978. var count int64
  1979. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  1980. if count == 0 {
  1981. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  1982. }
  1983. }
  1984. }
  1985. }
  1986. tx.Save(inbounds)
  1987. // Remove orphaned traffics
  1988. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  1989. // Migrate old MultiDomain to External Proxy
  1990. var externalProxy []struct {
  1991. Id int
  1992. Port int
  1993. StreamSettings []byte
  1994. }
  1995. err = tx.Raw(`select id, port, stream_settings
  1996. from inbounds
  1997. WHERE protocol in ('vmess','vless','trojan')
  1998. AND json_extract(stream_settings, '$.security') = 'tls'
  1999. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2000. if err != nil || len(externalProxy) == 0 {
  2001. return
  2002. }
  2003. for _, ep := range externalProxy {
  2004. var reverses any
  2005. var stream map[string]any
  2006. json.Unmarshal(ep.StreamSettings, &stream)
  2007. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2008. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2009. if domains, ok := settings["domains"].([]any); ok {
  2010. for _, domain := range domains {
  2011. if domainMap, ok := domain.(map[string]any); ok {
  2012. domainMap["forceTls"] = "same"
  2013. domainMap["port"] = ep.Port
  2014. domainMap["dest"] = domainMap["domain"].(string)
  2015. delete(domainMap, "domain")
  2016. }
  2017. }
  2018. }
  2019. reverses = settings["domains"]
  2020. delete(settings, "domains")
  2021. }
  2022. }
  2023. stream["externalProxy"] = reverses
  2024. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2025. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2026. }
  2027. err = tx.Raw(`UPDATE inbounds
  2028. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2029. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2030. if err != nil {
  2031. return
  2032. }
  2033. }
  2034. func (s *InboundService) MigrateDB() {
  2035. s.MigrationRequirements()
  2036. s.MigrationRemoveOrphanedTraffics()
  2037. }
  2038. func (s *InboundService) GetOnlineClients() []string {
  2039. return p.GetOnlineClients()
  2040. }
  2041. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2042. db := database.GetDB()
  2043. var rows []xray.ClientTraffic
  2044. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2045. if err != nil && err != gorm.ErrRecordNotFound {
  2046. return nil, err
  2047. }
  2048. result := make(map[string]int64, len(rows))
  2049. for _, r := range rows {
  2050. result[r.Email] = r.LastOnline
  2051. }
  2052. return result, nil
  2053. }
  2054. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2055. db := database.GetDB()
  2056. // Step 1: Get ClientTraffic records for emails in the input list
  2057. var clients []xray.ClientTraffic
  2058. err := db.Where("email IN ?", emails).Find(&clients).Error
  2059. if err != nil && err != gorm.ErrRecordNotFound {
  2060. return nil, nil, err
  2061. }
  2062. // Step 2: Sort clients by (Up + Down) descending
  2063. sort.Slice(clients, func(i, j int) bool {
  2064. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2065. })
  2066. // Step 3: Extract sorted valid emails and track found ones
  2067. validEmails := make([]string, 0, len(clients))
  2068. found := make(map[string]bool)
  2069. for _, client := range clients {
  2070. validEmails = append(validEmails, client.Email)
  2071. found[client.Email] = true
  2072. }
  2073. // Step 4: Identify emails that were not found in the database
  2074. extraEmails := make([]string, 0)
  2075. for _, email := range emails {
  2076. if !found[email] {
  2077. extraEmails = append(extraEmails, email)
  2078. }
  2079. }
  2080. return validEmails, extraEmails, nil
  2081. }
  2082. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  2083. oldInbound, err := s.GetInbound(inboundId)
  2084. if err != nil {
  2085. logger.Error("Load Old Data Error")
  2086. return false, err
  2087. }
  2088. var settings map[string]any
  2089. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2090. return false, err
  2091. }
  2092. interfaceClients, ok := settings["clients"].([]any)
  2093. if !ok {
  2094. return false, common.NewError("invalid clients format in inbound settings")
  2095. }
  2096. var newClients []any
  2097. needApiDel := false
  2098. found := false
  2099. for _, client := range interfaceClients {
  2100. c, ok := client.(map[string]any)
  2101. if !ok {
  2102. continue
  2103. }
  2104. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2105. // matched client, drop it
  2106. found = true
  2107. needApiDel, _ = c["enable"].(bool)
  2108. } else {
  2109. newClients = append(newClients, client)
  2110. }
  2111. }
  2112. if !found {
  2113. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2114. }
  2115. if len(newClients) == 0 {
  2116. return false, common.NewError("no client remained in Inbound")
  2117. }
  2118. settings["clients"] = newClients
  2119. newSettings, err := json.MarshalIndent(settings, "", " ")
  2120. if err != nil {
  2121. return false, err
  2122. }
  2123. oldInbound.Settings = string(newSettings)
  2124. db := database.GetDB()
  2125. // remove IP bindings
  2126. if err := s.DelClientIPs(db, email); err != nil {
  2127. logger.Error("Error in delete client IPs")
  2128. return false, err
  2129. }
  2130. needRestart := false
  2131. // remove stats too
  2132. if len(email) > 0 {
  2133. traffic, err := s.GetClientTrafficByEmail(email)
  2134. if err != nil {
  2135. return false, err
  2136. }
  2137. if traffic != nil {
  2138. if err := s.DelClientStat(db, email); err != nil {
  2139. logger.Error("Delete stats Data Error")
  2140. return false, err
  2141. }
  2142. }
  2143. if needApiDel {
  2144. s.xrayApi.Init(p.GetAPIPort())
  2145. if err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email); err1 == nil {
  2146. logger.Debug("Client deleted by api:", email)
  2147. needRestart = false
  2148. } else {
  2149. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2150. logger.Debug("User is already deleted. Nothing to do more...")
  2151. } else {
  2152. logger.Debug("Error in deleting client by api:", err1)
  2153. needRestart = true
  2154. }
  2155. }
  2156. s.xrayApi.Close()
  2157. }
  2158. }
  2159. return needRestart, db.Save(oldInbound).Error
  2160. }