1
0

subService.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "net/url"
  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/web/service"
  13. "x-ui/xray"
  14. "github.com/goccy/go-json"
  15. ptime "github.com/yaa110/go-persian-calendar"
  16. )
  17. type SubService struct {
  18. address string
  19. inboundService service.InboundService
  20. settingServics service.SettingService
  21. }
  22. func (s *SubService) GetSubs(subId string, host string) ([]string, []string, error) {
  23. s.address = host
  24. var result []string
  25. var headers []string
  26. var traffic xray.ClientTraffic
  27. var clientTraffics []xray.ClientTraffic
  28. inbounds, err := s.getInboundsBySubId(subId)
  29. if err != nil {
  30. return nil, nil, err
  31. }
  32. for _, inbound := range inbounds {
  33. clients, err := s.inboundService.GetClients(inbound)
  34. if err != nil {
  35. logger.Error("SubService - GetSub: Unable to get clients from inbound")
  36. }
  37. if clients == nil {
  38. continue
  39. }
  40. if len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  41. fallbackMaster, err := s.getFallbackMaster(inbound.Listen)
  42. if err == nil {
  43. inbound.Listen = fallbackMaster.Listen
  44. inbound.Port = fallbackMaster.Port
  45. var stream map[string]interface{}
  46. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  47. var masterStream map[string]interface{}
  48. json.Unmarshal([]byte(fallbackMaster.StreamSettings), &masterStream)
  49. stream["security"] = masterStream["security"]
  50. stream["tlsSettings"] = masterStream["tlsSettings"]
  51. modifiedStream, _ := json.MarshalIndent(stream, "", " ")
  52. inbound.StreamSettings = string(modifiedStream)
  53. }
  54. }
  55. for _, client := range clients {
  56. if client.Enable && client.SubID == subId {
  57. link := s.getLink(inbound, client.Email, client.ExpiryTime)
  58. result = append(result, link)
  59. clientTraffics = append(clientTraffics, s.getClientTraffics(inbound.ClientStats, client.Email))
  60. }
  61. }
  62. }
  63. for index, clientTraffic := range clientTraffics {
  64. if index == 0 {
  65. traffic.Up = clientTraffic.Up
  66. traffic.Down = clientTraffic.Down
  67. traffic.Total = clientTraffic.Total
  68. if clientTraffic.ExpiryTime > 0 {
  69. traffic.ExpiryTime = clientTraffic.ExpiryTime
  70. }
  71. } else {
  72. traffic.Up += clientTraffic.Up
  73. traffic.Down += clientTraffic.Down
  74. if traffic.Total == 0 || clientTraffic.Total == 0 {
  75. traffic.Total = 0
  76. } else {
  77. traffic.Total += clientTraffic.Total
  78. }
  79. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  80. traffic.ExpiryTime = 0
  81. }
  82. }
  83. }
  84. headers = append(headers, fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000))
  85. updateInterval, _ := s.settingServics.GetSubUpdates()
  86. headers = append(headers, fmt.Sprintf("%d", updateInterval))
  87. headers = append(headers, subId)
  88. return result, headers, nil
  89. }
  90. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  91. db := database.GetDB()
  92. var inbounds []*model.Inbound
  93. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("settings like ? and enable = ?", fmt.Sprintf(`%%"subId": "%s"%%`, subId), true).Find(&inbounds).Error
  94. if err != nil {
  95. return nil, err
  96. }
  97. return inbounds, nil
  98. }
  99. func (s *SubService) getClientTraffics(traffics []xray.ClientTraffic, email string) xray.ClientTraffic {
  100. for _, traffic := range traffics {
  101. if traffic.Email == email {
  102. return traffic
  103. }
  104. }
  105. return xray.ClientTraffic{}
  106. }
  107. func (s *SubService) getFallbackMaster(dest string) (*model.Inbound, error) {
  108. db := database.GetDB()
  109. var inbound *model.Inbound
  110. err := db.Model(model.Inbound{}).
  111. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  112. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", dest).
  113. Find(&inbound).Error
  114. if err != nil {
  115. return nil, err
  116. }
  117. return inbound, nil
  118. }
  119. func (s *SubService) getLink(inbound *model.Inbound, email string, expiryTime int64) string {
  120. switch inbound.Protocol {
  121. case "vmess":
  122. return s.genVmessLink(inbound, email, expiryTime)
  123. case "vless":
  124. return s.genVlessLink(inbound, email, expiryTime)
  125. case "trojan":
  126. return s.genTrojanLink(inbound, email, expiryTime)
  127. case "shadowsocks":
  128. return s.genShadowsocksLink(inbound, email, expiryTime)
  129. }
  130. return ""
  131. }
  132. func (s *SubService) genVmessLink(inbound *model.Inbound, email string, expiryTime int64) string {
  133. if inbound.Protocol != model.VMess {
  134. return ""
  135. }
  136. remainedTraffic := s.getRemainedTraffic(email)
  137. expiryTimeString := getExpiryTime(expiryTime)
  138. remark := fmt.Sprintf("%s: %s- %s", email, remainedTraffic, expiryTimeString)
  139. obj := map[string]interface{}{
  140. "v": "2",
  141. "ps": remark,
  142. "add": s.address,
  143. "port": inbound.Port,
  144. "type": "none",
  145. }
  146. var stream map[string]interface{}
  147. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  148. network, _ := stream["network"].(string)
  149. obj["net"] = network
  150. switch network {
  151. case "tcp":
  152. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  153. header, _ := tcp["header"].(map[string]interface{})
  154. typeStr, _ := header["type"].(string)
  155. obj["type"] = typeStr
  156. if typeStr == "http" {
  157. request := header["request"].(map[string]interface{})
  158. requestPath, _ := request["path"].([]interface{})
  159. obj["path"] = requestPath[0].(string)
  160. headers, _ := request["headers"].(map[string]interface{})
  161. obj["host"] = searchHost(headers)
  162. }
  163. case "kcp":
  164. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  165. header, _ := kcp["header"].(map[string]interface{})
  166. obj["type"], _ = header["type"].(string)
  167. obj["path"], _ = kcp["seed"].(string)
  168. case "ws":
  169. ws, _ := stream["wsSettings"].(map[string]interface{})
  170. obj["path"] = ws["path"].(string)
  171. headers, _ := ws["headers"].(map[string]interface{})
  172. obj["host"] = searchHost(headers)
  173. case "http":
  174. obj["net"] = "h2"
  175. http, _ := stream["httpSettings"].(map[string]interface{})
  176. obj["path"], _ = http["path"].(string)
  177. obj["host"] = searchHost(http)
  178. case "quic":
  179. quic, _ := stream["quicSettings"].(map[string]interface{})
  180. header := quic["header"].(map[string]interface{})
  181. obj["type"], _ = header["type"].(string)
  182. obj["host"], _ = quic["security"].(string)
  183. obj["path"], _ = quic["key"].(string)
  184. case "grpc":
  185. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  186. obj["path"] = grpc["serviceName"].(string)
  187. if grpc["multiMode"].(bool) {
  188. obj["type"] = "multi"
  189. }
  190. }
  191. security, _ := stream["security"].(string)
  192. var domains []interface{}
  193. obj["tls"] = security
  194. if security == "tls" {
  195. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  196. alpns, _ := tlsSetting["alpn"].([]interface{})
  197. if len(alpns) > 0 {
  198. var alpn []string
  199. for _, a := range alpns {
  200. alpn = append(alpn, a.(string))
  201. }
  202. obj["alpn"] = strings.Join(alpn, ",")
  203. }
  204. tlsSettings, _ := searchKey(tlsSetting, "settings")
  205. if tlsSetting != nil {
  206. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  207. obj["sni"], _ = sniValue.(string)
  208. }
  209. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  210. obj["fp"], _ = fpValue.(string)
  211. }
  212. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  213. obj["allowInsecure"], _ = insecure.(bool)
  214. }
  215. if domainSettings, ok := searchKey(tlsSettings, "domains"); ok {
  216. domains, _ = domainSettings.([]interface{})
  217. }
  218. }
  219. serverName, _ := tlsSetting["serverName"].(string)
  220. if serverName != "" {
  221. obj["add"] = serverName
  222. }
  223. }
  224. clients, _ := s.inboundService.GetClients(inbound)
  225. clientIndex := -1
  226. for i, client := range clients {
  227. if client.Email == email {
  228. clientIndex = i
  229. break
  230. }
  231. }
  232. obj["id"] = clients[clientIndex].ID
  233. if len(domains) > 0 {
  234. links := ""
  235. for index, d := range domains {
  236. domain := d.(map[string]interface{})
  237. obj["ps"] = remark + "-" + domain["remark"].(string)
  238. obj["add"] = domain["domain"].(string)
  239. if index > 0 {
  240. links += "\n"
  241. }
  242. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  243. links += "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  244. }
  245. return links
  246. }
  247. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  248. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  249. }
  250. func (s *SubService) genVlessLink(inbound *model.Inbound, email string, expiryTime int64) string {
  251. address := s.address
  252. if inbound.Protocol != model.VLESS {
  253. return ""
  254. }
  255. var stream map[string]interface{}
  256. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  257. clients, _ := s.inboundService.GetClients(inbound)
  258. clientIndex := -1
  259. for i, client := range clients {
  260. if client.Email == email {
  261. clientIndex = i
  262. break
  263. }
  264. }
  265. uuid := clients[clientIndex].ID
  266. port := inbound.Port
  267. streamNetwork := stream["network"].(string)
  268. params := make(map[string]string)
  269. params["type"] = streamNetwork
  270. switch streamNetwork {
  271. case "tcp":
  272. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  273. header, _ := tcp["header"].(map[string]interface{})
  274. typeStr, _ := header["type"].(string)
  275. if typeStr == "http" {
  276. request := header["request"].(map[string]interface{})
  277. requestPath, _ := request["path"].([]interface{})
  278. params["path"] = requestPath[0].(string)
  279. headers, _ := request["headers"].(map[string]interface{})
  280. params["host"] = searchHost(headers)
  281. params["headerType"] = "http"
  282. }
  283. case "kcp":
  284. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  285. header, _ := kcp["header"].(map[string]interface{})
  286. params["headerType"] = header["type"].(string)
  287. params["seed"] = kcp["seed"].(string)
  288. case "ws":
  289. ws, _ := stream["wsSettings"].(map[string]interface{})
  290. params["path"] = ws["path"].(string)
  291. headers, _ := ws["headers"].(map[string]interface{})
  292. params["host"] = searchHost(headers)
  293. case "http":
  294. http, _ := stream["httpSettings"].(map[string]interface{})
  295. params["path"] = http["path"].(string)
  296. params["host"] = searchHost(http)
  297. case "quic":
  298. quic, _ := stream["quicSettings"].(map[string]interface{})
  299. params["quicSecurity"] = quic["security"].(string)
  300. params["key"] = quic["key"].(string)
  301. header := quic["header"].(map[string]interface{})
  302. params["headerType"] = header["type"].(string)
  303. case "grpc":
  304. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  305. params["serviceName"] = grpc["serviceName"].(string)
  306. if grpc["multiMode"].(bool) {
  307. params["mode"] = "multi"
  308. }
  309. }
  310. security, _ := stream["security"].(string)
  311. var domains []interface{}
  312. if security == "tls" {
  313. params["security"] = "tls"
  314. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  315. alpns, _ := tlsSetting["alpn"].([]interface{})
  316. var alpn []string
  317. for _, a := range alpns {
  318. alpn = append(alpn, a.(string))
  319. }
  320. if len(alpn) > 0 {
  321. params["alpn"] = strings.Join(alpn, ",")
  322. }
  323. tlsSettings, _ := searchKey(tlsSetting, "settings")
  324. if tlsSetting != nil {
  325. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  326. params["sni"], _ = sniValue.(string)
  327. }
  328. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  329. params["fp"], _ = fpValue.(string)
  330. }
  331. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  332. if insecure.(bool) {
  333. params["allowInsecure"] = "1"
  334. }
  335. }
  336. if domainSettings, ok := searchKey(tlsSettings, "domains"); ok {
  337. domains, _ = domainSettings.([]interface{})
  338. }
  339. }
  340. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  341. params["flow"] = clients[clientIndex].Flow
  342. }
  343. serverName, _ := tlsSetting["serverName"].(string)
  344. if serverName != "" {
  345. address = serverName
  346. }
  347. }
  348. if security == "reality" {
  349. params["security"] = "reality"
  350. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  351. realitySettings, _ := searchKey(realitySetting, "settings")
  352. if realitySetting != nil {
  353. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  354. sNames, _ := sniValue.([]interface{})
  355. params["sni"], _ = sNames[0].(string)
  356. }
  357. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  358. params["pbk"], _ = pbkValue.(string)
  359. }
  360. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  361. shortIds, _ := sidValue.([]interface{})
  362. params["sid"], _ = shortIds[0].(string)
  363. }
  364. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  365. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  366. params["fp"] = fp
  367. }
  368. }
  369. if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
  370. if spx, ok := spxValue.(string); ok && len(spx) > 0 {
  371. params["spx"] = spx
  372. }
  373. }
  374. if serverName, ok := searchKey(realitySettings, "serverName"); ok {
  375. if sname, ok := serverName.(string); ok && len(sname) > 0 {
  376. address = sname
  377. }
  378. }
  379. }
  380. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  381. params["flow"] = clients[clientIndex].Flow
  382. }
  383. }
  384. if security == "xtls" {
  385. params["security"] = "xtls"
  386. xtlsSetting, _ := stream["xtlsSettings"].(map[string]interface{})
  387. alpns, _ := xtlsSetting["alpn"].([]interface{})
  388. var alpn []string
  389. for _, a := range alpns {
  390. alpn = append(alpn, a.(string))
  391. }
  392. if len(alpn) > 0 {
  393. params["alpn"] = strings.Join(alpn, ",")
  394. }
  395. xtlsSettings, _ := searchKey(xtlsSetting, "settings")
  396. if xtlsSetting != nil {
  397. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  398. params["fp"], _ = fpValue.(string)
  399. }
  400. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  401. if insecure.(bool) {
  402. params["allowInsecure"] = "1"
  403. }
  404. }
  405. if sniValue, ok := searchKey(xtlsSettings, "serverName"); ok {
  406. params["sni"], _ = sniValue.(string)
  407. }
  408. }
  409. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  410. params["flow"] = clients[clientIndex].Flow
  411. }
  412. serverName, _ := xtlsSetting["serverName"].(string)
  413. if serverName != "" {
  414. address = serverName
  415. }
  416. }
  417. if security != "tls" && security != "reality" && security != "xtls" {
  418. params["security"] = "none"
  419. }
  420. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  421. url, _ := url.Parse(link)
  422. q := url.Query()
  423. for k, v := range params {
  424. q.Add(k, v)
  425. }
  426. // Set the new query values on the URL
  427. url.RawQuery = q.Encode()
  428. remainedTraffic := s.getRemainedTraffic(email)
  429. expiryTimeString := getExpiryTime(expiryTime)
  430. remark := fmt.Sprintf("%s: %s- %s", email, remainedTraffic, expiryTimeString)
  431. if len(domains) > 0 {
  432. links := ""
  433. for index, d := range domains {
  434. domain := d.(map[string]interface{})
  435. url.Fragment = remark + "-" + domain["remark"].(string)
  436. url.Host = fmt.Sprintf("%s:%d", domain["domain"].(string), port)
  437. if index > 0 {
  438. links += "\n"
  439. }
  440. links += url.String()
  441. }
  442. return links
  443. }
  444. url.Fragment = remark
  445. return url.String()
  446. }
  447. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string, expiryTime int64) string {
  448. address := s.address
  449. if inbound.Protocol != model.Trojan {
  450. return ""
  451. }
  452. var stream map[string]interface{}
  453. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  454. clients, _ := s.inboundService.GetClients(inbound)
  455. clientIndex := -1
  456. for i, client := range clients {
  457. if client.Email == email {
  458. clientIndex = i
  459. break
  460. }
  461. }
  462. password := clients[clientIndex].Password
  463. port := inbound.Port
  464. streamNetwork := stream["network"].(string)
  465. params := make(map[string]string)
  466. params["type"] = streamNetwork
  467. switch streamNetwork {
  468. case "tcp":
  469. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  470. header, _ := tcp["header"].(map[string]interface{})
  471. typeStr, _ := header["type"].(string)
  472. if typeStr == "http" {
  473. request := header["request"].(map[string]interface{})
  474. requestPath, _ := request["path"].([]interface{})
  475. params["path"] = requestPath[0].(string)
  476. headers, _ := request["headers"].(map[string]interface{})
  477. params["host"] = searchHost(headers)
  478. params["headerType"] = "http"
  479. }
  480. case "kcp":
  481. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  482. header, _ := kcp["header"].(map[string]interface{})
  483. params["headerType"] = header["type"].(string)
  484. params["seed"] = kcp["seed"].(string)
  485. case "ws":
  486. ws, _ := stream["wsSettings"].(map[string]interface{})
  487. params["path"] = ws["path"].(string)
  488. headers, _ := ws["headers"].(map[string]interface{})
  489. params["host"] = searchHost(headers)
  490. case "http":
  491. http, _ := stream["httpSettings"].(map[string]interface{})
  492. params["path"] = http["path"].(string)
  493. params["host"] = searchHost(http)
  494. case "quic":
  495. quic, _ := stream["quicSettings"].(map[string]interface{})
  496. params["quicSecurity"] = quic["security"].(string)
  497. params["key"] = quic["key"].(string)
  498. header := quic["header"].(map[string]interface{})
  499. params["headerType"] = header["type"].(string)
  500. case "grpc":
  501. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  502. params["serviceName"] = grpc["serviceName"].(string)
  503. if grpc["multiMode"].(bool) {
  504. params["mode"] = "multi"
  505. }
  506. }
  507. security, _ := stream["security"].(string)
  508. var domains []interface{}
  509. if security == "tls" {
  510. params["security"] = "tls"
  511. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  512. alpns, _ := tlsSetting["alpn"].([]interface{})
  513. var alpn []string
  514. for _, a := range alpns {
  515. alpn = append(alpn, a.(string))
  516. }
  517. if len(alpn) > 0 {
  518. params["alpn"] = strings.Join(alpn, ",")
  519. }
  520. tlsSettings, _ := searchKey(tlsSetting, "settings")
  521. if tlsSetting != nil {
  522. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  523. params["sni"], _ = sniValue.(string)
  524. }
  525. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  526. params["fp"], _ = fpValue.(string)
  527. }
  528. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  529. if insecure.(bool) {
  530. params["allowInsecure"] = "1"
  531. }
  532. }
  533. if domainSettings, ok := searchKey(tlsSettings, "domains"); ok {
  534. domains, _ = domainSettings.([]interface{})
  535. }
  536. }
  537. serverName, _ := tlsSetting["serverName"].(string)
  538. if serverName != "" {
  539. address = serverName
  540. }
  541. }
  542. if security == "reality" {
  543. params["security"] = "reality"
  544. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  545. realitySettings, _ := searchKey(realitySetting, "settings")
  546. if realitySetting != nil {
  547. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  548. sNames, _ := sniValue.([]interface{})
  549. params["sni"], _ = sNames[0].(string)
  550. }
  551. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  552. params["pbk"], _ = pbkValue.(string)
  553. }
  554. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  555. shortIds, _ := sidValue.([]interface{})
  556. params["sid"], _ = shortIds[0].(string)
  557. }
  558. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  559. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  560. params["fp"] = fp
  561. }
  562. }
  563. if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
  564. if spx, ok := spxValue.(string); ok && len(spx) > 0 {
  565. params["spx"] = spx
  566. }
  567. }
  568. if serverName, ok := searchKey(realitySettings, "serverName"); ok {
  569. if sname, ok := serverName.(string); ok && len(sname) > 0 {
  570. address = sname
  571. }
  572. }
  573. }
  574. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  575. params["flow"] = clients[clientIndex].Flow
  576. }
  577. }
  578. if security == "xtls" {
  579. params["security"] = "xtls"
  580. xtlsSetting, _ := stream["xtlsSettings"].(map[string]interface{})
  581. alpns, _ := xtlsSetting["alpn"].([]interface{})
  582. var alpn []string
  583. for _, a := range alpns {
  584. alpn = append(alpn, a.(string))
  585. }
  586. if len(alpn) > 0 {
  587. params["alpn"] = strings.Join(alpn, ",")
  588. }
  589. xtlsSettings, _ := searchKey(xtlsSetting, "settings")
  590. if xtlsSetting != nil {
  591. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  592. params["fp"], _ = fpValue.(string)
  593. }
  594. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  595. if insecure.(bool) {
  596. params["allowInsecure"] = "1"
  597. }
  598. }
  599. if sniValue, ok := searchKey(xtlsSettings, "serverName"); ok {
  600. params["sni"], _ = sniValue.(string)
  601. }
  602. }
  603. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  604. params["flow"] = clients[clientIndex].Flow
  605. }
  606. serverName, _ := xtlsSetting["serverName"].(string)
  607. if serverName != "" {
  608. address = serverName
  609. }
  610. }
  611. if security != "tls" && security != "reality" && security != "xtls" {
  612. params["security"] = "none"
  613. }
  614. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  615. url, _ := url.Parse(link)
  616. q := url.Query()
  617. for k, v := range params {
  618. q.Add(k, v)
  619. }
  620. // Set the new query values on the URL
  621. url.RawQuery = q.Encode()
  622. remainedTraffic := s.getRemainedTraffic(email)
  623. expiryTimeString := getExpiryTime(expiryTime)
  624. remark := fmt.Sprintf("%s: %s- %s", email, remainedTraffic, expiryTimeString)
  625. if len(domains) > 0 {
  626. links := ""
  627. for index, d := range domains {
  628. domain := d.(map[string]interface{})
  629. url.Fragment = remark + "-" + domain["remark"].(string)
  630. url.Host = fmt.Sprintf("%s:%d", domain["domain"].(string), port)
  631. if index > 0 {
  632. links += "\n"
  633. }
  634. links += url.String()
  635. }
  636. return links
  637. }
  638. url.Fragment = remark
  639. return url.String()
  640. }
  641. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string, expiryTime int64) string {
  642. address := s.address
  643. if inbound.Protocol != model.Shadowsocks {
  644. return ""
  645. }
  646. var stream map[string]interface{}
  647. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  648. clients, _ := s.inboundService.GetClients(inbound)
  649. var settings map[string]interface{}
  650. json.Unmarshal([]byte(inbound.Settings), &settings)
  651. inboundPassword := settings["password"].(string)
  652. method := settings["method"].(string)
  653. clientIndex := -1
  654. for i, client := range clients {
  655. if client.Email == email {
  656. clientIndex = i
  657. break
  658. }
  659. }
  660. streamNetwork := stream["network"].(string)
  661. params := make(map[string]string)
  662. params["type"] = streamNetwork
  663. switch streamNetwork {
  664. case "tcp":
  665. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  666. header, _ := tcp["header"].(map[string]interface{})
  667. typeStr, _ := header["type"].(string)
  668. if typeStr == "http" {
  669. request := header["request"].(map[string]interface{})
  670. requestPath, _ := request["path"].([]interface{})
  671. params["path"] = requestPath[0].(string)
  672. headers, _ := request["headers"].(map[string]interface{})
  673. params["host"] = searchHost(headers)
  674. params["headerType"] = "http"
  675. }
  676. case "kcp":
  677. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  678. header, _ := kcp["header"].(map[string]interface{})
  679. params["headerType"] = header["type"].(string)
  680. params["seed"] = kcp["seed"].(string)
  681. case "ws":
  682. ws, _ := stream["wsSettings"].(map[string]interface{})
  683. params["path"] = ws["path"].(string)
  684. headers, _ := ws["headers"].(map[string]interface{})
  685. params["host"] = searchHost(headers)
  686. case "http":
  687. http, _ := stream["httpSettings"].(map[string]interface{})
  688. params["path"] = http["path"].(string)
  689. params["host"] = searchHost(http)
  690. case "quic":
  691. quic, _ := stream["quicSettings"].(map[string]interface{})
  692. params["quicSecurity"] = quic["security"].(string)
  693. params["key"] = quic["key"].(string)
  694. header := quic["header"].(map[string]interface{})
  695. params["headerType"] = header["type"].(string)
  696. case "grpc":
  697. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  698. params["serviceName"] = grpc["serviceName"].(string)
  699. if grpc["multiMode"].(bool) {
  700. params["mode"] = "multi"
  701. }
  702. }
  703. encPart := fmt.Sprintf("%s:%s:%s", method, inboundPassword, clients[clientIndex].Password)
  704. link := fmt.Sprintf("ss://%s@%s:%d", base64.StdEncoding.EncodeToString([]byte(encPart)), address, inbound.Port)
  705. url, _ := url.Parse(link)
  706. q := url.Query()
  707. for k, v := range params {
  708. q.Add(k, v)
  709. }
  710. // Set the new query values on the URL
  711. url.RawQuery = q.Encode()
  712. remainedTraffic := s.getRemainedTraffic(email)
  713. expiryTimeString := getExpiryTime(expiryTime)
  714. remark := fmt.Sprintf("%s: %s- %s", clients[clientIndex].Email, remainedTraffic, expiryTimeString)
  715. url.Fragment = remark
  716. return url.String()
  717. }
  718. func searchKey(data interface{}, key string) (interface{}, bool) {
  719. switch val := data.(type) {
  720. case map[string]interface{}:
  721. for k, v := range val {
  722. if k == key {
  723. return v, true
  724. }
  725. if result, ok := searchKey(v, key); ok {
  726. return result, true
  727. }
  728. }
  729. case []interface{}:
  730. for _, v := range val {
  731. if result, ok := searchKey(v, key); ok {
  732. return result, true
  733. }
  734. }
  735. }
  736. return nil, false
  737. }
  738. func searchHost(headers interface{}) string {
  739. data, _ := headers.(map[string]interface{})
  740. for k, v := range data {
  741. if strings.EqualFold(k, "host") {
  742. switch v.(type) {
  743. case []interface{}:
  744. hosts, _ := v.([]interface{})
  745. if len(hosts) > 0 {
  746. return hosts[0].(string)
  747. } else {
  748. return ""
  749. }
  750. case interface{}:
  751. return v.(string)
  752. }
  753. }
  754. }
  755. return ""
  756. }
  757. func getExpiryTime(expiryTime int64) string {
  758. now := time.Now().Unix()
  759. expiryString := ""
  760. timeDifference := expiryTime/1000 - now
  761. if expiryTime == 0 {
  762. expiryString = "♾ ⏳"
  763. } else if timeDifference > 172800 {
  764. expiryString = fmt.Sprintf("%s ⏳", ptime.Unix((expiryTime/1000), 0).Format("yy-MM-dd hh:mm"))
  765. } else if expiryTime < 0 {
  766. expiryString = fmt.Sprintf("%d ⏳", expiryTime/-86400000)
  767. } else {
  768. expiryString = fmt.Sprintf("%s %d ⏳", "ساعت", timeDifference/3600)
  769. }
  770. return expiryString
  771. }
  772. func (s *SubService) getRemainedTraffic(email string) string {
  773. traffic, err := s.inboundService.GetClientTrafficByEmail(email)
  774. if err != nil {
  775. logger.Warning(err)
  776. }
  777. remainedTraffic := ""
  778. if traffic.Total == 0 {
  779. remainedTraffic = "♾ 📊"
  780. } else {
  781. remainedTraffic = fmt.Sprintf("%s%s", common.FormatTraffic(traffic.Total-(traffic.Up+traffic.Down)), "📊")
  782. }
  783. return remainedTraffic
  784. }