inbound.go 58 KB

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