remark_vars.go 16 KB

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