inbound.go 52 KB

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