1
0

client_crud.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. package service
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/google/uuid"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  13. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. "gorm.io/gorm"
  16. )
  17. func hasForbiddenClientChar(s string) bool {
  18. for _, r := range s {
  19. if r == '/' || r == '\\' || r == ' ' || r < 0x20 || r == 0x7f {
  20. return true
  21. }
  22. }
  23. return false
  24. }
  25. func validateClientEmail(email string) error {
  26. if hasForbiddenClientChar(email) {
  27. return common.NewError("client email contains an invalid character:", email)
  28. }
  29. return nil
  30. }
  31. func validateClientSubID(subID string) error {
  32. if hasForbiddenClientChar(subID) {
  33. return common.NewError("client subId contains an invalid character:", subID)
  34. }
  35. return nil
  36. }
  37. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  38. if payload == nil {
  39. return false, common.NewError("empty payload")
  40. }
  41. client := payload.Client
  42. if strings.TrimSpace(client.Email) == "" {
  43. return false, common.NewError("client email is required")
  44. }
  45. if err := validateClientEmail(client.Email); err != nil {
  46. return false, err
  47. }
  48. if err := validateClientSubID(client.SubID); err != nil {
  49. return false, err
  50. }
  51. if len(payload.InboundIds) == 0 {
  52. return false, common.NewError("at least one inbound is required")
  53. }
  54. if client.SubID == "" {
  55. client.SubID = uuid.NewString()
  56. }
  57. if !client.Enable {
  58. client.Enable = true
  59. }
  60. now := time.Now().UnixMilli()
  61. if client.CreatedAt == 0 {
  62. client.CreatedAt = now
  63. }
  64. client.UpdatedAt = now
  65. existing := &model.ClientRecord{}
  66. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  67. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  68. return false, err
  69. }
  70. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  71. if emailTaken {
  72. if existing.SubID == "" || existing.SubID != client.SubID {
  73. return false, common.NewError("email already in use:", client.Email)
  74. }
  75. }
  76. if client.SubID != "" {
  77. var subTaken int64
  78. if err := database.GetDB().Model(&model.ClientRecord{}).
  79. Where("sub_id = ? AND email <> ?", client.SubID, client.Email).
  80. Count(&subTaken).Error; err != nil {
  81. return false, err
  82. }
  83. if subTaken > 0 {
  84. return false, common.NewError("subId already in use:", client.SubID)
  85. }
  86. }
  87. needRestart := false
  88. for _, ibId := range payload.InboundIds {
  89. inbound, getErr := inboundSvc.GetInbound(ibId)
  90. if getErr != nil {
  91. return needRestart, getErr
  92. }
  93. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  94. return needRestart, err
  95. }
  96. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(client, inbound)}})
  97. if mErr != nil {
  98. return needRestart, mErr
  99. }
  100. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  101. Id: ibId,
  102. Settings: string(settingsPayload),
  103. })
  104. if addErr != nil {
  105. return needRestart, addErr
  106. }
  107. if nr {
  108. needRestart = true
  109. }
  110. }
  111. return needRestart, nil
  112. }
  113. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  114. switch ib.Protocol {
  115. case model.VMESS, model.VLESS:
  116. if c.ID == "" {
  117. c.ID = uuid.NewString()
  118. }
  119. case model.Trojan:
  120. if c.Password == "" {
  121. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  122. }
  123. case model.Shadowsocks:
  124. method := shadowsocksMethodFromSettings(ib.Settings)
  125. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  126. c.Password = randomShadowsocksClientKey(method)
  127. }
  128. case model.Hysteria:
  129. if c.Auth == "" {
  130. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  131. }
  132. case model.MTProto:
  133. if c.Secret == "" {
  134. c.Secret = model.GenerateFakeTLSSecret(mtprotoDomainFromSettings(ib.Settings))
  135. }
  136. }
  137. return nil
  138. }
  139. // defaultMtprotoDomain is the FakeTLS fronting domain used when an mtproto
  140. // inbound carries no fakeTlsDomain of its own; it mirrors the frontend default.
  141. const defaultMtprotoDomain = "www.cloudflare.com"
  142. // mtprotoDomainFromSettings returns the inbound-level FakeTLS domain, falling
  143. // back to the default when unset, so a generated client secret always fronts a
  144. // real hostname.
  145. func mtprotoDomainFromSettings(settings string) string {
  146. domain := ""
  147. if settings != "" {
  148. var m map[string]any
  149. if err := json.Unmarshal([]byte(settings), &m); err == nil {
  150. domain, _ = m["fakeTlsDomain"].(string)
  151. }
  152. }
  153. domain = strings.TrimSpace(domain)
  154. if domain == "" {
  155. return defaultMtprotoDomain
  156. }
  157. return domain
  158. }
  159. func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
  160. if !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
  161. c.Flow = ""
  162. }
  163. return c
  164. }
  165. func shadowsocksMethodFromSettings(settings string) string {
  166. if settings == "" {
  167. return ""
  168. }
  169. var m map[string]any
  170. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  171. return ""
  172. }
  173. method, _ := m["method"].(string)
  174. return method
  175. }
  176. func randomShadowsocksClientKey(method string) string {
  177. if n := shadowsocksKeyBytes(method); n > 0 {
  178. return random.Base64Bytes(n)
  179. }
  180. return strings.ReplaceAll(uuid.NewString(), "-", "")
  181. }
  182. func validShadowsocksClientKey(method, key string) bool {
  183. n := shadowsocksKeyBytes(method)
  184. if n == 0 {
  185. return key != ""
  186. }
  187. decoded, err := base64.StdEncoding.DecodeString(key)
  188. if err != nil {
  189. return false
  190. }
  191. return len(decoded) == n
  192. }
  193. func shadowsocksKeyBytes(method string) int {
  194. switch method {
  195. case "2022-blake3-aes-128-gcm":
  196. return 16
  197. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  198. return 32
  199. }
  200. return 0
  201. }
  202. // normalizeShadowsocksClientKeys rewrites any Shadowsocks-2022 client password
  203. // whose decoded length no longer matches settings.method, which happens after the
  204. // inbound method is switched between ciphers of different key sizes (e.g.
  205. // aes-256↔aes-128). A wrong-length uPSK makes xray reject the user, so the link
  206. // fails to connect; regenerating restores a valid key (clients must re-fetch).
  207. // Non-Shadowsocks / legacy-SS settings pass through unchanged.
  208. func normalizeShadowsocksClientKeys(settings string) (string, bool) {
  209. method := shadowsocksMethodFromSettings(settings)
  210. if shadowsocksKeyBytes(method) == 0 {
  211. return settings, false
  212. }
  213. var m map[string]any
  214. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  215. return settings, false
  216. }
  217. clients, ok := m["clients"].([]any)
  218. if !ok {
  219. return settings, false
  220. }
  221. changed := false
  222. for i := range clients {
  223. c, ok := clients[i].(map[string]any)
  224. if !ok {
  225. continue
  226. }
  227. if pw, _ := c["password"].(string); validShadowsocksClientKey(method, pw) {
  228. continue
  229. }
  230. c["password"] = randomShadowsocksClientKey(method)
  231. clients[i] = c
  232. changed = true
  233. }
  234. if !changed {
  235. return settings, false
  236. }
  237. m["clients"] = clients
  238. bs, err := json.MarshalIndent(m, "", " ")
  239. if err != nil {
  240. return settings, false
  241. }
  242. return string(bs), true
  243. }
  244. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  245. method, _ := settings["method"].(string)
  246. is2022 := strings.HasPrefix(method, "2022-blake3-")
  247. for i := range clients {
  248. cm, ok := clients[i].(map[string]any)
  249. if !ok {
  250. continue
  251. }
  252. if is2022 {
  253. if _, hasKey := cm["method"]; hasKey {
  254. delete(cm, "method")
  255. clients[i] = cm
  256. }
  257. continue
  258. }
  259. if method == "" {
  260. continue
  261. }
  262. if existing, _ := cm["method"].(string); existing != "" {
  263. continue
  264. }
  265. cm["method"] = method
  266. clients[i] = cm
  267. }
  268. }
  269. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client, inboundFilter ...int) (bool, error) {
  270. existing, err := s.GetByID(id)
  271. if err != nil {
  272. return false, err
  273. }
  274. inboundIds, err := s.GetInboundIdsForRecord(id)
  275. if err != nil {
  276. return false, err
  277. }
  278. if len(inboundFilter) > 0 {
  279. allow := make(map[int]struct{}, len(inboundFilter))
  280. for _, fid := range inboundFilter {
  281. allow[fid] = struct{}{}
  282. }
  283. filtered := inboundIds[:0:0]
  284. for _, ibId := range inboundIds {
  285. if _, ok := allow[ibId]; ok {
  286. filtered = append(filtered, ibId)
  287. }
  288. }
  289. inboundIds = filtered
  290. }
  291. if strings.TrimSpace(updated.Email) == "" {
  292. return false, common.NewError("client email is required")
  293. }
  294. if err := validateClientEmail(updated.Email); err != nil {
  295. return false, err
  296. }
  297. if err := validateClientSubID(updated.SubID); err != nil {
  298. return false, err
  299. }
  300. if updated.SubID == "" {
  301. updated.SubID = existing.SubID
  302. }
  303. if updated.SubID == "" {
  304. updated.SubID = uuid.NewString()
  305. }
  306. updated.UpdatedAt = time.Now().UnixMilli()
  307. if updated.CreatedAt == 0 {
  308. updated.CreatedAt = existing.CreatedAt
  309. }
  310. // Preserve existing credentials when the caller omits them, so a partial
  311. // update (e.g. only changing traffic/expiry) doesn't silently rotate the
  312. // client's UUID/password/auth via fillProtocolDefaults. Supplying a new
  313. // value still rotates it intentionally.
  314. if updated.ID == "" {
  315. updated.ID = existing.UUID
  316. }
  317. if updated.Password == "" {
  318. updated.Password = existing.Password
  319. }
  320. if updated.Auth == "" {
  321. updated.Auth = existing.Auth
  322. }
  323. if updated.Email != existing.Email {
  324. var collisionCount int64
  325. if err := database.GetDB().Model(&model.ClientRecord{}).
  326. Where("email = ? AND id <> ?", updated.Email, id).
  327. Count(&collisionCount).Error; err != nil {
  328. return false, err
  329. }
  330. if collisionCount > 0 {
  331. return false, common.NewError("Duplicate email:", updated.Email)
  332. }
  333. if err := database.GetDB().Model(&model.ClientRecord{}).
  334. Where("id = ?", id).
  335. Update("email", updated.Email).Error; err != nil {
  336. return false, err
  337. }
  338. }
  339. if updated.SubID != "" {
  340. var subCollision int64
  341. if err := database.GetDB().Model(&model.ClientRecord{}).
  342. Where("sub_id = ? AND id <> ?", updated.SubID, id).
  343. Count(&subCollision).Error; err != nil {
  344. return false, err
  345. }
  346. if subCollision > 0 {
  347. return false, common.NewError("Duplicate subId:", updated.SubID)
  348. }
  349. }
  350. needRestart := false
  351. for _, ibId := range inboundIds {
  352. inbound, getErr := inboundSvc.GetInbound(ibId)
  353. if getErr != nil {
  354. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  355. if err := database.GetDB().
  356. Where("client_id = ? AND inbound_id = ?", id, ibId).
  357. Delete(&model.ClientInbound{}).Error; err != nil {
  358. return needRestart, err
  359. }
  360. continue
  361. }
  362. return needRestart, getErr
  363. }
  364. if existing.Email == "" {
  365. continue
  366. }
  367. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  368. return needRestart, err
  369. }
  370. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(updated, inbound)}})
  371. if mErr != nil {
  372. return needRestart, mErr
  373. }
  374. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  375. Id: ibId,
  376. Settings: string(settingsPayload),
  377. }, existing.Email)
  378. if upErr != nil {
  379. return needRestart, upErr
  380. }
  381. if nr {
  382. needRestart = true
  383. }
  384. }
  385. reverseStr := ""
  386. if updated.Reverse != nil && strings.TrimSpace(updated.Reverse.Tag) != "" {
  387. if b, mErr := json.Marshal(updated.Reverse); mErr == nil {
  388. reverseStr = string(b)
  389. }
  390. }
  391. if err := database.GetDB().Model(&model.ClientRecord{}).
  392. Where("id = ?", id).
  393. Update("reverse", reverseStr).Error; err != nil {
  394. return needRestart, err
  395. }
  396. // Persist the group explicitly. SyncInbound deliberately preserves the
  397. // stored group when the inbound settings carry none — so a node snapshot or a
  398. // group-less settings rebuild can't wipe it (see SyncInbound + its tests).
  399. // That guard also meant clearing the group in the client editor never took
  400. // effect. The editor always round-trips the field, so apply it here,
  401. // including the empty string that removes the client from its group.
  402. if err := database.GetDB().Model(&model.ClientRecord{}).
  403. Where("id = ?", id).
  404. UpdateColumn("group_name", updated.Group).Error; err != nil {
  405. return needRestart, err
  406. }
  407. if err := database.GetDB().Model(&model.ClientRecord{}).
  408. Where("id = ?", id).
  409. UpdateColumn("enable", updated.Enable).Error; err != nil {
  410. return needRestart, err
  411. }
  412. if err := database.GetDB().Model(&model.ClientRecord{}).
  413. Where("id = ?", id).
  414. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  415. return needRestart, err
  416. }
  417. return needRestart, nil
  418. }
  419. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  420. existing, err := s.GetByID(id)
  421. if err != nil {
  422. return false, err
  423. }
  424. tombstoneClientEmail(existing.Email)
  425. inboundIds, err := s.GetInboundIdsForRecord(id)
  426. if err != nil {
  427. return false, err
  428. }
  429. needRestart := false
  430. for _, ibId := range inboundIds {
  431. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  432. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  433. continue
  434. }
  435. return needRestart, getErr
  436. }
  437. // Always delete by email — the client's stable identity. This removes
  438. // every matching entry from the inbound's settings even when the stored
  439. // credential (UUID/password/auth) drifted from the inbound JSON, or a
  440. // duplicate entry with the same email exists.
  441. if existing.Email == "" {
  442. continue
  443. }
  444. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, false, true)
  445. if delErr != nil {
  446. // The client is already absent from this inbound (data drift or a
  447. // retried delete). Skip it — deletion stays idempotent.
  448. if errors.Is(delErr, ErrClientNotInInbound) {
  449. continue
  450. }
  451. return needRestart, delErr
  452. }
  453. if nr {
  454. needRestart = true
  455. }
  456. }
  457. db := database.GetDB()
  458. if err := db.Transaction(func(tx *gorm.DB) error {
  459. if existing.Email != "" {
  460. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
  461. return err
  462. }
  463. }
  464. if err := tx.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  465. return err
  466. }
  467. if err := tx.Where("client_id = ?", id).Delete(&model.ClientExternalLink{}).Error; err != nil {
  468. return err
  469. }
  470. if !keepTraffic && existing.Email != "" {
  471. if err := tx.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  472. return err
  473. }
  474. if err := clearGlobalTraffic(tx, existing.Email); err != nil {
  475. return err
  476. }
  477. if err := tx.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  478. return err
  479. }
  480. }
  481. return tx.Delete(&model.ClientRecord{}, id).Error
  482. }); err != nil {
  483. return needRestart, err
  484. }
  485. return needRestart, nil
  486. }
  487. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  488. existing, err := s.GetByID(id)
  489. if err != nil {
  490. return false, err
  491. }
  492. currentIds, err := s.GetInboundIdsForRecord(id)
  493. if err != nil {
  494. return false, err
  495. }
  496. have := make(map[int]struct{}, len(currentIds))
  497. for _, x := range currentIds {
  498. have[x] = struct{}{}
  499. }
  500. clientWire := existing.ToClient()
  501. flow, ffErr := s.EffectiveFlow(nil, id)
  502. if ffErr != nil {
  503. return false, ffErr
  504. }
  505. clientWire.Flow = flow
  506. clientWire.UpdatedAt = time.Now().UnixMilli()
  507. needRestart := false
  508. for _, ibId := range inboundIds {
  509. if _, attached := have[ibId]; attached {
  510. continue
  511. }
  512. inbound, getErr := inboundSvc.GetInbound(ibId)
  513. if getErr != nil {
  514. return needRestart, getErr
  515. }
  516. copyClient := *clientWire
  517. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  518. return needRestart, err
  519. }
  520. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
  521. if mErr != nil {
  522. return needRestart, mErr
  523. }
  524. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  525. Id: ibId,
  526. Settings: string(settingsPayload),
  527. })
  528. if addErr != nil {
  529. return needRestart, addErr
  530. }
  531. if nr {
  532. needRestart = true
  533. }
  534. }
  535. return needRestart, nil
  536. }
  537. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  538. return s.Create(inboundSvc, &ClientCreatePayload{
  539. Client: client,
  540. InboundIds: []int{inboundId},
  541. })
  542. }
  543. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  544. if email == "" {
  545. return false, common.NewError("client email is required")
  546. }
  547. rec, err := s.GetRecordByEmail(nil, email)
  548. if err != nil {
  549. return false, err
  550. }
  551. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  552. }
  553. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  554. if email == "" {
  555. return false, common.NewError("client email is required")
  556. }
  557. rec, err := s.GetRecordByEmail(nil, email)
  558. if err != nil {
  559. return false, err
  560. }
  561. return s.Attach(inboundSvc, rec.Id, inboundIds)
  562. }
  563. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  564. if email == "" {
  565. return false, common.NewError("client email is required")
  566. }
  567. rec, err := s.GetRecordByEmail(nil, email)
  568. if err != nil {
  569. return false, err
  570. }
  571. return s.Detach(inboundSvc, rec.Id, inboundIds)
  572. }
  573. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  574. if email == "" {
  575. return false, common.NewError("client email is required")
  576. }
  577. rec, err := s.GetRecordByEmail(nil, email)
  578. if err == nil {
  579. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  580. }
  581. if !errors.Is(err, gorm.ErrRecordNotFound) {
  582. return false, err
  583. }
  584. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  585. if idsErr != nil {
  586. return false, idsErr
  587. }
  588. if len(inboundIds) == 0 {
  589. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  590. }
  591. needRestart := false
  592. for _, ibId := range inboundIds {
  593. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email, false, true)
  594. if delErr != nil {
  595. if errors.Is(delErr, ErrClientNotInInbound) {
  596. continue
  597. }
  598. return needRestart, delErr
  599. }
  600. if nr {
  601. needRestart = true
  602. }
  603. }
  604. if !keepTraffic {
  605. db := database.GetDB()
  606. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  607. return needRestart, err
  608. }
  609. if err := clearGlobalTraffic(db, email); err != nil {
  610. return needRestart, err
  611. }
  612. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  613. return needRestart, err
  614. }
  615. }
  616. return needRestart, nil
  617. }
  618. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client, inboundFilter ...int) (bool, error) {
  619. if email == "" {
  620. return false, common.NewError("client email is required")
  621. }
  622. rec, err := s.GetRecordByEmail(nil, email)
  623. if err != nil {
  624. return false, err
  625. }
  626. return s.Update(inboundSvc, rec.Id, updated, inboundFilter...)
  627. }
  628. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  629. existing, err := s.GetByID(id)
  630. if err != nil {
  631. return false, err
  632. }
  633. currentIds, err := s.GetInboundIdsForRecord(id)
  634. if err != nil {
  635. return false, err
  636. }
  637. have := make(map[int]struct{}, len(currentIds))
  638. for _, x := range currentIds {
  639. have[x] = struct{}{}
  640. }
  641. needRestart := false
  642. for _, ibId := range inboundIds {
  643. if _, attached := have[ibId]; !attached {
  644. continue
  645. }
  646. if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil {
  647. return needRestart, getErr
  648. }
  649. // Detach by email — the client's stable identity (see Delete).
  650. if existing.Email == "" {
  651. continue
  652. }
  653. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false)
  654. if delErr != nil {
  655. if errors.Is(delErr, ErrClientNotInInbound) {
  656. continue
  657. }
  658. return needRestart, delErr
  659. }
  660. if nr {
  661. needRestart = true
  662. }
  663. }
  664. return needRestart, nil
  665. }