remark_vars.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 "STATUS_EMOJI":
  252. return statusEmoji(st)
  253. case "USAGE_PERCENTAGE":
  254. return usagePercentage(st)
  255. case "PROTOCOL":
  256. if ctx.inbound != nil {
  257. return strings.ToUpper(string(ctx.inbound.Protocol))
  258. }
  259. return ""
  260. case "TRANSPORT":
  261. return ctx.transport
  262. case "SECURITY":
  263. return strings.ToUpper(ctx.security)
  264. case "TIME_LEFT":
  265. return timeLeftLabel(st.ExpiryTime)
  266. case "JALALI_EXPIRE_DATE":
  267. return jalaliExpireDateLabel(st.ExpiryTime)
  268. }
  269. return ""
  270. }
  271. // clientStatus collapses enable/expiry/quota into a single word.
  272. func clientStatus(st xray.ClientTraffic) string {
  273. if !st.Enable {
  274. return "disabled"
  275. }
  276. if st.ExpiryTime > 0 && st.ExpiryTime/1000 < time.Now().Unix() {
  277. return "expired"
  278. }
  279. if st.Total > 0 && st.Up+st.Down >= st.Total {
  280. return "depleted"
  281. }
  282. return "active"
  283. }
  284. // daysLeftLabel is the whole-days form of remainingTimeLabel: "∞" for unlimited,
  285. // "0" once past expiry.
  286. func daysLeftLabel(expiryMs int64) string {
  287. if expiryMs == 0 {
  288. return unlimitedMark
  289. }
  290. exp := expiryMs / 1000
  291. var secs int64
  292. if exp > 0 {
  293. secs = exp - time.Now().Unix()
  294. } else {
  295. secs = -exp // delayed-start: value is the duration itself
  296. }
  297. days := secs / 86400
  298. if days < 0 {
  299. return "0"
  300. }
  301. return strconv.FormatInt(days, 10)
  302. }
  303. // expireDateLabel renders a fixed expiry as YYYY-MM-DD (local time). Unlimited
  304. // and delayed-start (no fixed calendar date yet) expiries yield "".
  305. func expireDateLabel(expiryMs int64) string {
  306. if expiryMs <= 0 {
  307. return ""
  308. }
  309. return time.Unix(expiryMs/1000, 0).In(time.Local).Format("2006-01-02")
  310. }
  311. func max64(a, b int64) int64 {
  312. if a > b {
  313. return a
  314. }
  315. return b
  316. }
  317. // statusEmoji maps clientStatus to a single emoji character.
  318. func statusEmoji(st xray.ClientTraffic) string {
  319. switch clientStatus(st) {
  320. case "active":
  321. return "✅"
  322. case "expired":
  323. return "⏳"
  324. case "depleted":
  325. return "🚫"
  326. case "disabled":
  327. return "🚫"
  328. default:
  329. return ""
  330. }
  331. }
  332. // usagePercentage computes the traffic usage as a percentage string (e.g. "52.3%").
  333. // Returns "" when the client has no traffic limit.
  334. func usagePercentage(st xray.ClientTraffic) string {
  335. if st.Total <= 0 {
  336. return ""
  337. }
  338. used := st.Up + st.Down
  339. pct := float64(used) / float64(st.Total) * 100
  340. if pct > 100 {
  341. pct = 100 // clamp over-quota usage, consistent with TRAFFIC_LEFT
  342. }
  343. return fmt.Sprintf("%.1f%%", pct)
  344. }
  345. // timeLeftLabel renders remaining time as "Xd Xh Xm" (or shorter when days/hours
  346. // are zero). Returns "∞" for unlimited and "0" when past expiry.
  347. func timeLeftLabel(expiryMs int64) string {
  348. if expiryMs == 0 {
  349. return unlimitedMark
  350. }
  351. exp := expiryMs / 1000
  352. var secs int64
  353. if exp > 0 {
  354. secs = exp - time.Now().Unix()
  355. } else {
  356. secs = -exp
  357. }
  358. if secs <= 0 {
  359. return "0"
  360. }
  361. days := secs / 86400
  362. hours := (secs % 86400) / 3600
  363. mins := (secs % 3600) / 60
  364. if days > 0 {
  365. return fmt.Sprintf("%dd %dh %dm", days, hours, mins)
  366. }
  367. if hours > 0 {
  368. return fmt.Sprintf("%dh %dm", hours, mins)
  369. }
  370. return fmt.Sprintf("%dm", mins)
  371. }
  372. // jalaliExpireDateLabel converts a Gregorian expiry timestamp to Jalali
  373. // (Persian/Solar Hijri) date format "YYYY/MM/DD". Returns "" for unlimited
  374. // or delayed-start expiries.
  375. func jalaliExpireDateLabel(expiryMs int64) string {
  376. if expiryMs <= 0 {
  377. return ""
  378. }
  379. t := time.Unix(expiryMs/1000, 0).In(time.Local)
  380. y, m, d := gregorianToJalali(t.Year(), int(t.Month()), t.Day())
  381. return fmt.Sprintf("%d/%02d/%02d", y, m, d)
  382. }
  383. // gregorianToJalali converts a Gregorian date to Jalali (Solar Hijri) date.
  384. // Uses a reference-date approach: counts days from a known reference point
  385. // (2024-01-01 = 1402-10-11 JAL) and walks the Jalali calendar forward/backward.
  386. func gregorianToJalali(gy, gm, gd int) (jy, jm, jd int) {
  387. // Compute Julian Day Number for the input Gregorian date
  388. a := (14 - gm) / 12
  389. y := gy + 4800 - a
  390. m := gm + 12*a - 3
  391. jdn := gd + (153*m+2)/5 + 365*y + y/4 - y/100 + y/400 - 32045
  392. // Reference: 2024-01-01 = JDN 2460311 = 1402-10-11 JAL
  393. refJDN := 2460311
  394. days := int64(jdn - refJDN)
  395. jy, jm, jd = 1402, 10, 11
  396. // Walk forward
  397. for days > 0 {
  398. remaining := int64(jalaliMonthDays(jy, jm) - jd + 1)
  399. if days < remaining {
  400. jd += int(days)
  401. return
  402. }
  403. days -= remaining
  404. jm++
  405. if jm > 12 {
  406. jm = 1
  407. jy++
  408. }
  409. jd = 1
  410. }
  411. // Walk backward
  412. for days < 0 {
  413. jd += int(days)
  414. for jd < 1 {
  415. jm--
  416. if jm < 1 {
  417. jm = 12
  418. jy--
  419. }
  420. jd += jalaliMonthDays(jy, jm)
  421. }
  422. days = 0
  423. }
  424. return
  425. }
  426. func jalaliMonthDays(y, m int) int {
  427. if m <= 6 {
  428. return 31
  429. }
  430. if m <= 11 {
  431. return 30
  432. }
  433. if isJalaliLeap(y) {
  434. return 30
  435. }
  436. return 29
  437. }
  438. // isJalaliLeap reports whether the given Jalali year is a leap year.
  439. // The leap pattern repeats every 33 years with 8 leap years.
  440. func isJalaliLeap(y int) bool {
  441. switch y % 33 {
  442. case 1, 5, 9, 13, 17, 22, 26, 30:
  443. return true
  444. }
  445. return false
  446. }
  447. // statsForClient returns the client's live traffic record, or a minimal one
  448. // synthesized from the client (enable/expiry/total) when no live stats exist —
  449. // so expiry/total/status tokens still resolve on links that have no counters yet.
  450. func (s *SubService) statsForClient(inbound *model.Inbound, client model.Client) xray.ClientTraffic {
  451. if stats, ok := s.findClientStats(inbound, client.Email); ok {
  452. return stats
  453. }
  454. // client_traffics.email is globally unique, so a client shared across several
  455. // inbounds of one subscription has a single traffic row owned by exactly one
  456. // inbound. On every other inbound's link findClientStats misses; fall back to
  457. // the per-request map built from all the subscription's inbounds so
  458. // {{TRAFFIC_*}} reflect real usage instead of the full quota (#5443).
  459. if stats, ok := s.statsByEmail[client.Email]; ok {
  460. return stats
  461. }
  462. // Both in-memory paths key off client_traffics.inbound_id, which goes stale
  463. // when an inbound is deleted and recreated, orphaning the row from every
  464. // loaded inbound. Fall back to a direct lookup by the globally-unique email
  465. // so usage still resolves for clients predating that recreation (#5567).
  466. if stats, ok := s.statsByEmailFromDB(client.Email); ok {
  467. return stats
  468. }
  469. return xray.ClientTraffic{
  470. Enable: client.Enable,
  471. ExpiryTime: client.ExpiryTime,
  472. Total: client.TotalGB,
  473. }
  474. }
  475. // lookupClient resolves the full client (TgID, SubID, comment, …) for an email,
  476. // needed when a global remark template references client-only tokens. Falls back
  477. // to an email-only client if not found.
  478. func (s *SubService) lookupClient(inbound *model.Inbound, email string) model.Client {
  479. if c, ok := s.clientForLink(inbound, email); ok {
  480. return c
  481. }
  482. return model.Client{Email: email}
  483. }
  484. var usageInfoTokens = map[string]bool{
  485. "TRAFFIC_USED": true, "TRAFFIC_LEFT": true, "TRAFFIC_TOTAL": true,
  486. "TRAFFIC_USED_BYTES": true, "TRAFFIC_LEFT_BYTES": true, "TRAFFIC_TOTAL_BYTES": true,
  487. "UP": true, "DOWN": true, "DAYS_LEFT": true, "EXPIRE_DATE": true, "EXPIRE_UNIX": true,
  488. "STATUS": true, "STATUS_EMOJI": true, "USAGE_PERCENTAGE": true, "TIME_LEFT": true,
  489. "JALALI_EXPIRE_DATE": true,
  490. }
  491. var connectionTokens = map[string]bool{
  492. "PROTOCOL": true,
  493. "TRANSPORT": true,
  494. "SECURITY": true,
  495. }
  496. var displayRemoveTokens = mergeTokenSets(usageInfoTokens, connectionTokens)
  497. // firstLinkOnlyBodyTokens are stripped from every subscription-body link after a
  498. // client's first one: the usage/info tokens plus the per-client EMAIL/USERNAME
  499. // identity. A client app needs the email once, so repeating it on every link of
  500. // the same subscription is noise — show it on the first link only, like traffic.
  501. var firstLinkOnlyBodyTokens = mergeTokenSets(usageInfoTokens, map[string]bool{
  502. "EMAIL": true,
  503. "USERNAME": true,
  504. })
  505. func mergeTokenSets(sets ...map[string]bool) map[string]bool {
  506. out := make(map[string]bool)
  507. for _, set := range sets {
  508. for tok := range set {
  509. out[tok] = true
  510. }
  511. }
  512. return out
  513. }
  514. func filterRemarkTemplate(template string, remove map[string]bool) string {
  515. segments := strings.Split(template, "|")
  516. kept := make([]string, 0, len(segments))
  517. for _, seg := range segments {
  518. if out := filterRemarkSegment(seg, remove); out != "" {
  519. kept = append(kept, out)
  520. }
  521. }
  522. return strings.Join(kept, "|")
  523. }
  524. // filterRemarkSegment drops whole token categories from one segment while it is
  525. // still a template, before any value is known. Literal text touching a removed
  526. // token goes with it and the surviving runs rejoin with a space, so filtering the
  527. // usage tokens out of "{{EMAIL}} 📊{{TRAFFIC_LEFT}}" leaves "{{EMAIL}}". This is
  528. // the template-level counterpart to expandSegment, which works one layer later on
  529. // tokens that survive here but resolve to an empty value.
  530. func filterRemarkSegment(seg string, remove map[string]bool) string {
  531. tokens := remarkTokens(seg)
  532. hasRemove := false
  533. for _, tok := range tokens {
  534. if remove[tok.name] {
  535. hasRemove = true
  536. break
  537. }
  538. }
  539. if !hasRemove {
  540. return strings.TrimSpace(seg)
  541. }
  542. runs := make([]string, 0, 2)
  543. runStart, leftRemoved := 0, false
  544. for _, tok := range tokens {
  545. if !remove[tok.name] {
  546. continue
  547. }
  548. runs = appendKeptRun(runs, seg[runStart:tok.start], leftRemoved, true)
  549. runStart, leftRemoved = tok.end, true
  550. }
  551. runs = appendKeptRun(runs, seg[runStart:], leftRemoved, false)
  552. return strings.Join(runs, " ")
  553. }
  554. func appendKeptRun(runs []string, run string, leftRemoved, rightRemoved bool) []string {
  555. tokens := remarkTokens(run)
  556. if len(tokens) == 0 {
  557. return runs
  558. }
  559. start, end := 0, len(run)
  560. if leftRemoved {
  561. start = tokens[0].start
  562. }
  563. if rightRemoved {
  564. end = tokens[len(tokens)-1].end
  565. }
  566. if frag := strings.TrimSpace(run[start:end]); frag != "" {
  567. runs = append(runs, frag)
  568. }
  569. return runs
  570. }
  571. func (s *SubService) effectiveTemplate(email string) string {
  572. translated := translateUISingleBrackets(s.remarkTemplate)
  573. if s.usageShown == nil {
  574. s.usageShown = map[string]bool{}
  575. }
  576. if s.usageShown[email] {
  577. remove := firstLinkOnlyBodyTokens
  578. if s.showIdentityOnAllLinks {
  579. remove = usageInfoTokens
  580. }
  581. return filterRemarkTemplate(translated, remove)
  582. }
  583. s.usageShown[email] = true
  584. return translated
  585. }
  586. func inboundSecurity(inbound *model.Inbound) string {
  587. if inbound == nil {
  588. return ""
  589. }
  590. stream := unmarshalStreamSettings(inbound.StreamSettings)
  591. security, _ := stream["security"].(string)
  592. return security
  593. }
  594. // genTemplatedRemark expands the remark template for one client. hostRemark is
  595. // the host endpoint's remark (empty for a plain inbound); it backs the {{HOST}}
  596. // token only and never substitutes the inbound remark as the config name.
  597. func (s *SubService) genTemplatedRemark(inbound *model.Inbound, client model.Client, hostRemark string, transport string) string {
  598. ctx := remarkContext{
  599. client: client,
  600. stats: s.statsForClient(inbound, client),
  601. inbound: inbound,
  602. hostRemark: hostRemark,
  603. transport: transport,
  604. security: inboundSecurity(inbound),
  605. }
  606. var tmpl string
  607. if s.subscriptionBody {
  608. tmpl = s.effectiveTemplate(client.Email)
  609. } else {
  610. tmpl = filterRemarkTemplate(translateUISingleBrackets(s.remarkTemplate), displayRemoveTokens)
  611. }
  612. if out := expandRemarkVars(tmpl, ctx); strings.TrimSpace(out) != "" {
  613. return out
  614. }
  615. return ctx.configName()
  616. }
  617. // genHostRemark builds one host endpoint's remark for a specific client. With a
  618. // remark template set it is template-driven (body shows the full template on the
  619. // first link and the name-only part thereafter; displays render the name-only
  620. // part). With no template it falls back to inbound, host and email joined by "-".
  621. func (s *SubService) genHostRemark(inbound *model.Inbound, client model.Client, hostRemark string, transport string) string {
  622. if s.remarkTemplate != "" {
  623. return s.genTemplatedRemark(inbound, client, hostRemark, transport)
  624. }
  625. return fallbackRemark(inbound.Remark, hostRemark, client.Email)
  626. }