remark_vars.go 20 KB

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