inbound.go 52 KB

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