inbound.go 57 KB

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