1
0

remark_vars.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. package sub
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  10. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  11. )
  12. // remarkContext carries the per-client data a remark template can interpolate.
  13. // stats holds the live traffic record when one exists; when it doesn't, the
  14. // caller synthesizes a minimal one from the client so expiry/total/status tokens
  15. // still resolve. hostRemark is the host endpoint's own remark; it backs the
  16. // {{HOST}} token only — it never substitutes the inbound's remark as the config
  17. // name (use {{INBOUND}} and {{HOST}} side by side to show both).
  18. type remarkContext struct {
  19. client model.Client
  20. stats xray.ClientTraffic
  21. inbound *model.Inbound
  22. hostRemark string
  23. transport string
  24. security string
  25. }
  26. // configName is the display name for a link: always the inbound's own remark.
  27. // The host endpoint's remark is surfaced only through the {{HOST}} token.
  28. func (ctx remarkContext) configName() string {
  29. if ctx.inbound != nil {
  30. return ctx.inbound.Remark
  31. }
  32. return ""
  33. }
  34. // remarkVarRe matches a {{TOKEN}} placeholder. Tokens are uppercase letters and
  35. // underscores only, so ordinary braces in a remark are left untouched.
  36. var remarkVarRe = regexp.MustCompile(`\{\{([A-Z_]+)\}\}`)
  37. // unlimitedMark is the value the human-readable quota/expiry tokens render when
  38. // the client has no limit. A segment built only around such a token carries no
  39. // information, so it is dropped rather than printed as "∞" (see expandRemarkVars).
  40. const unlimitedMark = "∞"
  41. // unlimitedDropTokens are the tokens that render unlimitedMark for an unlimited
  42. // client. A "|"-separated segment whose only value comes from one of these is
  43. // dropped whole when unlimited, so the operator never sees "📊∞|⏳∞D".
  44. var unlimitedDropTokens = map[string]bool{
  45. "TRAFFIC_LEFT": true,
  46. "TRAFFIC_TOTAL": true,
  47. "DAYS_LEFT": true,
  48. "TIME_LEFT": true,
  49. }
  50. // uiTokenMap translates user-friendly single-brace tokens (used in the frontend
  51. // Remark/Host Name fields) to their internal double-brace equivalents. Tokens
  52. // not present in this map are left untouched.
  53. var uiTokenMap = map[string]string{
  54. "EMAIL": "EMAIL",
  55. "DATA_USAGE": "TRAFFIC_USED",
  56. "DATA_LEFT": "TRAFFIC_LEFT",
  57. "DATA_LIMIT": "TRAFFIC_TOTAL",
  58. "DAYS_LEFT": "DAYS_LEFT",
  59. "EXPIRE_DATE": "EXPIRE_DATE",
  60. "JALALI_EXPIRE_DATE": "JALALI_EXPIRE_DATE",
  61. "TIME_LEFT": "TIME_LEFT",
  62. "STATUS_EMOJI": "STATUS_EMOJI",
  63. "USAGE_PERCENTAGE": "USAGE_PERCENTAGE",
  64. "PROTOCOL": "PROTOCOL",
  65. "TRANSPORT": "TRANSPORT",
  66. "SECURITY": "SECURITY",
  67. }
  68. // translateUISingleBrackets converts user-friendly single-brace tokens to the
  69. // internal double-brace format before regex expansion. Only {TOKEN} patterns
  70. // that are NOT part of {{TOKEN}} are translated. Unknown tokens stay as-is.
  71. func translateUISingleBrackets(template string) string {
  72. var result strings.Builder
  73. i := 0
  74. for i < len(template) {
  75. if template[i] == '{' && (i == 0 || template[i-1] != '{') {
  76. j := i + 1
  77. for j < len(template) && template[j] != '}' {
  78. j++
  79. }
  80. if j < len(template) && template[j] == '}' {
  81. token := template[i+1 : j]
  82. if internal, ok := uiTokenMap[token]; ok {
  83. result.WriteString("{{")
  84. result.WriteString(internal)
  85. result.WriteString("}}")
  86. i = j + 1
  87. continue
  88. }
  89. }
  90. }
  91. result.WriteByte(template[i])
  92. i++
  93. }
  94. return result.String()
  95. }
  96. // expandRemarkVars substitutes every {{TOKEN}} in template with its per-client
  97. // value. Unknown tokens resolve to "" (never the literal text). The template is
  98. // split on "|" into segments: a segment whose only value is an unlimited quota
  99. // or expiry (∞) drops out whole — decoration and separator included — so an
  100. // unlimited client gets "host" instead of "host|📊∞|⏳∞D".
  101. func expandRemarkVars(template string, ctx remarkContext) string {
  102. template = translateUISingleBrackets(template)
  103. if !strings.Contains(template, "{{") {
  104. return template
  105. }
  106. segments := strings.Split(template, "|")
  107. kept := make([]string, 0, len(segments))
  108. for _, seg := range segments {
  109. if out, drop := expandSegment(seg, ctx); !drop {
  110. kept = append(kept, out)
  111. }
  112. }
  113. return strings.Join(kept, "|")
  114. }
  115. // expandSegment expands one "|" segment and reports whether it should be dropped.
  116. // It drops only when the segment carries an unlimited (∞) quota/expiry token and
  117. // no other token in it resolves to a non-empty value — so a segment mixing, say,
  118. // {{EMAIL}} with {{TRAFFIC_LEFT}} is always kept.
  119. func expandSegment(seg string, ctx remarkContext) (string, bool) {
  120. hasUnlimited, hasOtherValue := false, false
  121. out := remarkVarRe.ReplaceAllStringFunc(seg, func(m string) string {
  122. token := m[2 : len(m)-2]
  123. val := remarkVarValue(token, ctx)
  124. switch {
  125. case unlimitedDropTokens[token] && val == unlimitedMark:
  126. hasUnlimited = true
  127. case val != "":
  128. hasOtherValue = true
  129. }
  130. return val
  131. })
  132. return out, hasUnlimited && !hasOtherValue
  133. }
  134. func remarkVarValue(token string, ctx remarkContext) string {
  135. c := ctx.client
  136. st := ctx.stats
  137. used := st.Up + st.Down
  138. switch token {
  139. case "EMAIL", "USERNAME":
  140. return c.Email
  141. case "INBOUND":
  142. return ctx.configName()
  143. case "HOST":
  144. return ctx.hostRemark
  145. case "ID":
  146. return c.ID
  147. case "SHORT_ID":
  148. if len(c.ID) >= 8 {
  149. return c.ID[:8]
  150. }
  151. return c.ID
  152. case "TELEGRAM_ID":
  153. if c.TgID != 0 {
  154. return strconv.FormatInt(c.TgID, 10)
  155. }
  156. return ""
  157. case "SUB_ID":
  158. return c.SubID
  159. case "COMMENT":
  160. return c.Comment
  161. case "STATUS":
  162. return clientStatus(st)
  163. case "DAYS_LEFT":
  164. return daysLeftLabel(st.ExpiryTime)
  165. case "EXPIRE_DATE":
  166. return expireDateLabel(st.ExpiryTime)
  167. case "EXPIRE_UNIX":
  168. if st.ExpiryTime <= 0 {
  169. return "0"
  170. }
  171. return strconv.FormatInt(st.ExpiryTime/1000, 10)
  172. case "CREATED_UNIX":
  173. if c.CreatedAt == 0 {
  174. return ""
  175. }
  176. return strconv.FormatInt(c.CreatedAt/1000, 10)
  177. case "TRAFFIC_USED":
  178. return common.FormatTraffic(used)
  179. case "TRAFFIC_LEFT":
  180. if st.Total <= 0 {
  181. return unlimitedMark
  182. }
  183. return common.FormatTraffic(max64(st.Total-used, 0))
  184. case "TRAFFIC_TOTAL":
  185. if st.Total <= 0 {
  186. return unlimitedMark
  187. }
  188. return common.FormatTraffic(st.Total)
  189. case "TRAFFIC_USED_BYTES":
  190. return strconv.FormatInt(used, 10)
  191. case "TRAFFIC_LEFT_BYTES":
  192. if st.Total <= 0 {
  193. return "0"
  194. }
  195. return strconv.FormatInt(max64(st.Total-used, 0), 10)
  196. case "TRAFFIC_TOTAL_BYTES":
  197. return strconv.FormatInt(st.Total, 10)
  198. case "UP":
  199. return common.FormatTraffic(st.Up)
  200. case "DOWN":
  201. return common.FormatTraffic(st.Down)
  202. case "RESET_DAYS":
  203. if c.Reset > 0 {
  204. return strconv.Itoa(c.Reset)
  205. }
  206. return ""
  207. case "STATUS_EMOJI":
  208. return statusEmoji(st)
  209. case "USAGE_PERCENTAGE":
  210. return usagePercentage(st)
  211. case "PROTOCOL":
  212. if ctx.inbound != nil {
  213. return strings.ToUpper(string(ctx.inbound.Protocol))
  214. }
  215. return ""
  216. case "TRANSPORT":
  217. return ctx.transport
  218. case "SECURITY":
  219. return strings.ToUpper(ctx.security)
  220. case "TIME_LEFT":
  221. return timeLeftLabel(st.ExpiryTime)
  222. case "JALALI_EXPIRE_DATE":
  223. return jalaliExpireDateLabel(st.ExpiryTime)
  224. }
  225. return ""
  226. }
  227. // clientStatus collapses enable/expiry/quota into a single word.
  228. func clientStatus(st xray.ClientTraffic) string {
  229. if !st.Enable {
  230. return "disabled"
  231. }
  232. if st.ExpiryTime > 0 && st.ExpiryTime/1000 < time.Now().Unix() {
  233. return "expired"
  234. }
  235. if st.Total > 0 && st.Up+st.Down >= st.Total {
  236. return "depleted"
  237. }
  238. return "active"
  239. }
  240. // daysLeftLabel is the whole-days form of remainingTimeLabel: "∞" for unlimited,
  241. // "0" once past expiry.
  242. func daysLeftLabel(expiryMs int64) string {
  243. if expiryMs == 0 {
  244. return unlimitedMark
  245. }
  246. exp := expiryMs / 1000
  247. var secs int64
  248. if exp > 0 {
  249. secs = exp - time.Now().Unix()
  250. } else {
  251. secs = -exp // delayed-start: value is the duration itself
  252. }
  253. days := secs / 86400
  254. if days < 0 {
  255. return "0"
  256. }
  257. return strconv.FormatInt(days, 10)
  258. }
  259. // expireDateLabel renders a fixed expiry as YYYY-MM-DD (local time). Unlimited
  260. // and delayed-start (no fixed calendar date yet) expiries yield "".
  261. func expireDateLabel(expiryMs int64) string {
  262. if expiryMs <= 0 {
  263. return ""
  264. }
  265. return time.Unix(expiryMs/1000, 0).In(time.Local).Format("2006-01-02")
  266. }
  267. func max64(a, b int64) int64 {
  268. if a > b {
  269. return a
  270. }
  271. return b
  272. }
  273. // statusEmoji maps clientStatus to a single emoji character.
  274. func statusEmoji(st xray.ClientTraffic) string {
  275. switch clientStatus(st) {
  276. case "active":
  277. return "✅"
  278. case "expired":
  279. return "⏳"
  280. case "depleted":
  281. return "🚫"
  282. case "disabled":
  283. return "🚫"
  284. default:
  285. return ""
  286. }
  287. }
  288. // usagePercentage computes the traffic usage as a percentage string (e.g. "52.3%").
  289. // Returns "" when the client has no traffic limit.
  290. func usagePercentage(st xray.ClientTraffic) string {
  291. if st.Total <= 0 {
  292. return ""
  293. }
  294. used := st.Up + st.Down
  295. pct := float64(used) / float64(st.Total) * 100
  296. if pct > 100 {
  297. pct = 100 // clamp over-quota usage, consistent with TRAFFIC_LEFT
  298. }
  299. return fmt.Sprintf("%.1f%%", pct)
  300. }
  301. // timeLeftLabel renders remaining time as "Xd Xh Xm" (or shorter when days/hours
  302. // are zero). Returns "∞" for unlimited and "0" when past expiry.
  303. func timeLeftLabel(expiryMs int64) string {
  304. if expiryMs == 0 {
  305. return unlimitedMark
  306. }
  307. exp := expiryMs / 1000
  308. var secs int64
  309. if exp > 0 {
  310. secs = exp - time.Now().Unix()
  311. } else {
  312. secs = -exp
  313. }
  314. if secs <= 0 {
  315. return "0"
  316. }
  317. days := secs / 86400
  318. hours := (secs % 86400) / 3600
  319. mins := (secs % 3600) / 60
  320. if days > 0 {
  321. return fmt.Sprintf("%dd %dh %dm", days, hours, mins)
  322. }
  323. if hours > 0 {
  324. return fmt.Sprintf("%dh %dm", hours, mins)
  325. }
  326. return fmt.Sprintf("%dm", mins)
  327. }
  328. // jalaliExpireDateLabel converts a Gregorian expiry timestamp to Jalali
  329. // (Persian/Solar Hijri) date format "YYYY/MM/DD". Returns "" for unlimited
  330. // or delayed-start expiries.
  331. func jalaliExpireDateLabel(expiryMs int64) string {
  332. if expiryMs <= 0 {
  333. return ""
  334. }
  335. t := time.Unix(expiryMs/1000, 0).In(time.Local)
  336. y, m, d := gregorianToJalali(t.Year(), int(t.Month()), t.Day())
  337. return fmt.Sprintf("%d/%02d/%02d", y, m, d)
  338. }
  339. // gregorianToJalali converts a Gregorian date to Jalali (Solar Hijri) date.
  340. // Uses a reference-date approach: counts days from a known reference point
  341. // (2024-01-01 = 1402-10-11 JAL) and walks the Jalali calendar forward/backward.
  342. func gregorianToJalali(gy, gm, gd int) (jy, jm, jd int) {
  343. // Compute Julian Day Number for the input Gregorian date
  344. a := (14 - gm) / 12
  345. y := gy + 4800 - a
  346. m := gm + 12*a - 3
  347. jdn := gd + (153*m+2)/5 + 365*y + y/4 - y/100 + y/400 - 32045
  348. // Reference: 2024-01-01 = JDN 2460311 = 1402-10-11 JAL
  349. refJDN := 2460311
  350. days := int64(jdn - refJDN)
  351. jy, jm, jd = 1402, 10, 11
  352. // Walk forward
  353. for days > 0 {
  354. remaining := int64(jalaliMonthDays(jy, jm) - jd + 1)
  355. if days < remaining {
  356. jd += int(days)
  357. return
  358. }
  359. days -= remaining
  360. jm++
  361. if jm > 12 {
  362. jm = 1
  363. jy++
  364. }
  365. jd = 1
  366. }
  367. // Walk backward
  368. for days < 0 {
  369. jd += int(days)
  370. for jd < 1 {
  371. jm--
  372. if jm < 1 {
  373. jm = 12
  374. jy--
  375. }
  376. jd += jalaliMonthDays(jy, jm)
  377. }
  378. days = 0
  379. }
  380. return
  381. }
  382. func jalaliMonthDays(y, m int) int {
  383. if m <= 6 {
  384. return 31
  385. }
  386. if m <= 11 {
  387. return 30
  388. }
  389. if isJalaliLeap(y) {
  390. return 30
  391. }
  392. return 29
  393. }
  394. // isJalaliLeap reports whether the given Jalali year is a leap year.
  395. // The leap pattern repeats every 33 years with 8 leap years.
  396. func isJalaliLeap(y int) bool {
  397. switch y % 33 {
  398. case 1, 5, 9, 13, 17, 22, 26, 30:
  399. return true
  400. }
  401. return false
  402. }
  403. // statsForClient returns the client's live traffic record, or a minimal one
  404. // synthesized from the client (enable/expiry/total) when no live stats exist —
  405. // so expiry/total/status tokens still resolve on links that have no counters yet.
  406. func (s *SubService) statsForClient(inbound *model.Inbound, client model.Client) xray.ClientTraffic {
  407. if stats, ok := s.findClientStats(inbound, client.Email); ok {
  408. return stats
  409. }
  410. // client_traffics.email is globally unique, so a client shared across several
  411. // inbounds of one subscription has a single traffic row owned by exactly one
  412. // inbound. On every other inbound's link findClientStats misses; fall back to
  413. // the per-request map built from all the subscription's inbounds so
  414. // {{TRAFFIC_*}} reflect real usage instead of the full quota (#5443).
  415. if stats, ok := s.statsByEmail[client.Email]; ok {
  416. return stats
  417. }
  418. return xray.ClientTraffic{
  419. Enable: client.Enable,
  420. ExpiryTime: client.ExpiryTime,
  421. Total: client.TotalGB,
  422. }
  423. }
  424. // lookupClient resolves the full client (TgID, SubID, comment, …) for an email,
  425. // needed when a global remark template references client-only tokens. Falls back
  426. // to an email-only client if not found.
  427. func (s *SubService) lookupClient(inbound *model.Inbound, email string) model.Client {
  428. clients, _ := s.inboundService.GetClients(inbound)
  429. for _, c := range clients {
  430. if c.Email == email {
  431. return c
  432. }
  433. }
  434. return model.Client{Email: email}
  435. }
  436. var usageInfoTokens = map[string]bool{
  437. "TRAFFIC_USED": true, "TRAFFIC_LEFT": true, "TRAFFIC_TOTAL": true,
  438. "TRAFFIC_USED_BYTES": true, "TRAFFIC_LEFT_BYTES": true, "TRAFFIC_TOTAL_BYTES": true,
  439. "UP": true, "DOWN": true, "DAYS_LEFT": true, "EXPIRE_DATE": true, "EXPIRE_UNIX": true,
  440. "STATUS": true, "STATUS_EMOJI": true, "USAGE_PERCENTAGE": true, "TIME_LEFT": true,
  441. "JALALI_EXPIRE_DATE": true,
  442. }
  443. var connectionTokens = map[string]bool{
  444. "PROTOCOL": true,
  445. "TRANSPORT": true,
  446. "SECURITY": true,
  447. }
  448. var displayRemoveTokens = mergeTokenSets(usageInfoTokens, connectionTokens)
  449. func mergeTokenSets(sets ...map[string]bool) map[string]bool {
  450. out := make(map[string]bool)
  451. for _, set := range sets {
  452. for tok := range set {
  453. out[tok] = true
  454. }
  455. }
  456. return out
  457. }
  458. func filterRemarkTemplate(template string, remove map[string]bool) string {
  459. segments := strings.Split(template, "|")
  460. kept := make([]string, 0, len(segments))
  461. for _, seg := range segments {
  462. if out := filterRemarkSegment(seg, remove); out != "" {
  463. kept = append(kept, out)
  464. }
  465. }
  466. return strings.Join(kept, "|")
  467. }
  468. func filterRemarkSegment(seg string, remove map[string]bool) string {
  469. locs := remarkVarRe.FindAllStringSubmatchIndex(seg, -1)
  470. hasRemove := false
  471. for _, loc := range locs {
  472. if remove[seg[loc[2]:loc[3]]] {
  473. hasRemove = true
  474. break
  475. }
  476. }
  477. if !hasRemove {
  478. return strings.TrimSpace(seg)
  479. }
  480. runs := make([]string, 0, 2)
  481. runStart, leftRemoved := 0, false
  482. for _, loc := range locs {
  483. if !remove[seg[loc[2]:loc[3]]] {
  484. continue
  485. }
  486. runs = appendKeptRun(runs, seg[runStart:loc[0]], leftRemoved, true)
  487. runStart, leftRemoved = loc[1], true
  488. }
  489. runs = appendKeptRun(runs, seg[runStart:], leftRemoved, false)
  490. return strings.Join(runs, " ")
  491. }
  492. func appendKeptRun(runs []string, run string, leftRemoved, rightRemoved bool) []string {
  493. locs := remarkVarRe.FindAllStringSubmatchIndex(run, -1)
  494. if len(locs) == 0 {
  495. return runs
  496. }
  497. start, end := 0, len(run)
  498. if leftRemoved {
  499. start = locs[0][0]
  500. }
  501. if rightRemoved {
  502. end = locs[len(locs)-1][1]
  503. }
  504. if frag := strings.TrimSpace(run[start:end]); frag != "" {
  505. runs = append(runs, frag)
  506. }
  507. return runs
  508. }
  509. func (s *SubService) effectiveTemplate(email string) string {
  510. translated := translateUISingleBrackets(s.remarkTemplate)
  511. if s.usageShown == nil {
  512. s.usageShown = map[string]bool{}
  513. }
  514. if s.usageShown[email] {
  515. return filterRemarkTemplate(translated, usageInfoTokens)
  516. }
  517. s.usageShown[email] = true
  518. return translated
  519. }
  520. func inboundSecurity(inbound *model.Inbound) string {
  521. if inbound == nil {
  522. return ""
  523. }
  524. stream := unmarshalStreamSettings(inbound.StreamSettings)
  525. security, _ := stream["security"].(string)
  526. return security
  527. }
  528. // genTemplatedRemark expands the remark template for one client. hostRemark is
  529. // the host endpoint's remark (empty for a plain inbound); it backs the {{HOST}}
  530. // token only and never substitutes the inbound remark as the config name.
  531. func (s *SubService) genTemplatedRemark(inbound *model.Inbound, client model.Client, hostRemark string, transport string) string {
  532. ctx := remarkContext{
  533. client: client,
  534. stats: s.statsForClient(inbound, client),
  535. inbound: inbound,
  536. hostRemark: hostRemark,
  537. transport: transport,
  538. security: inboundSecurity(inbound),
  539. }
  540. var tmpl string
  541. if s.subscriptionBody {
  542. tmpl = s.effectiveTemplate(client.Email)
  543. } else {
  544. tmpl = filterRemarkTemplate(translateUISingleBrackets(s.remarkTemplate), displayRemoveTokens)
  545. }
  546. if out := expandRemarkVars(tmpl, ctx); strings.TrimSpace(out) != "" {
  547. return out
  548. }
  549. return ctx.configName()
  550. }
  551. // genHostRemark builds one host endpoint's remark for a specific client. With a
  552. // remark template set it is template-driven (body shows the full template on the
  553. // first link and the name-only part thereafter; displays render the name-only
  554. // part). With no template it falls back to inbound, host and email joined by "-".
  555. func (s *SubService) genHostRemark(inbound *model.Inbound, client model.Client, hostRemark string, transport string) string {
  556. if s.remarkTemplate != "" {
  557. return s.genTemplatedRemark(inbound, client, hostRemark, transport)
  558. }
  559. return fallbackRemark(inbound.Remark, hostRemark, client.Email)
  560. }