tgbot_client_expiry_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package tgbot
  2. import (
  3. "encoding/json"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database"
  8. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  9. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  10. "github.com/nicksnyder/go-i18n/v2/i18n"
  11. "golang.org/x/text/language"
  12. )
  13. // clientInfoLocalizer renders the lines clientInfoMsg prints with the templates
  14. // the translation files carry; without it I18n returns the bare keys.
  15. func clientInfoLocalizer(t *testing.T) {
  16. t.Helper()
  17. bundle := i18n.NewBundle(language.MustParse("en-US"))
  18. bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
  19. _ = bundle.AddMessages(language.MustParse("en-US"),
  20. &i18n.Message{ID: "tgbot.messages.email", Other: "Email: {{ .Email }}\r\n"},
  21. &i18n.Message{ID: "tgbot.days", Other: "Days"},
  22. &i18n.Message{ID: "tgbot.messages.expireIn", Other: "Expire In: {{ .Time }}\r\n"},
  23. &i18n.Message{ID: "tgbot.messages.expire", Other: "Expire Date: {{ .Time }}\r\n"},
  24. &i18n.Message{ID: "tgbot.wentWrong", Other: "went wrong"},
  25. )
  26. orig := locale.LocalizerBot
  27. t.Cleanup(func() { locale.LocalizerBot = orig })
  28. locale.LocalizerBot = i18n.NewLocalizer(bundle, "en-US")
  29. }
  30. // Regression test: a start-after-first-use client is stored as a negative duration,
  31. // and a disabled one rendered it as a 1969 date.
  32. func TestClientInfoShowsStartAfterFirstUseWhenDisabled(t *testing.T) {
  33. if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  34. t.Fatalf("InitDB: %v", err)
  35. }
  36. t.Cleanup(func() { _ = database.CloseDB() })
  37. clientInfoLocalizer(t)
  38. traffic := &xray.ClientTraffic{
  39. Email: "[email protected]",
  40. Enable: false,
  41. ExpiryTime: -30 * 24 * 60 * 60000,
  42. }
  43. out := (&Tgbot{}).clientInfoMsg(traffic, false, false, false, true, false, false)
  44. if strings.Contains(out, "1969") {
  45. t.Errorf("client info = %q, want the days left, not a 1969 date", out)
  46. }
  47. if !strings.Contains(out, "Expire In: 30 Days") {
  48. t.Errorf("client info = %q, want it to contain %q", out, "Expire In: 30 Days")
  49. }
  50. }