1
0

inbound.go 62 KB

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