1
0

inbound.go 76 KB

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