user_inventory.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. package handler
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "runtime/debug"
  6. "sync"
  7. "time"
  8. "bet24.com/log"
  9. "bet24.com/servers/common"
  10. item "bet24.com/servers/micros/item_inventory/proto"
  11. cash "bet24.com/servers/micros/money/proto"
  12. chip "bet24.com/servers/micros/money/proto"
  13. notification "bet24.com/servers/micros/notification/proto"
  14. userservices "bet24.com/servers/micros/userservices/proto"
  15. vipservice "bet24.com/servers/micros/userservices/proto"
  16. )
  17. const (
  18. Item_ID_Lottery = 4 //抽奖券
  19. )
  20. type user_inventory struct {
  21. lock *sync.RWMutex
  22. userId int
  23. ipAddress string
  24. userItemList map[int]*item.UserItem
  25. endChan chan int
  26. }
  27. // InventoryAction
  28. const (
  29. Inventory_Consume = iota // 使用 0
  30. Inventory_Add // 增加 1
  31. Inventory_Expire // 到期 2
  32. Inventory_Update // 数据有变化 3
  33. Inventory_Sell // 出售 4
  34. )
  35. func newUserInventory(userId int, ipAddress string) *user_inventory {
  36. ret := new(user_inventory)
  37. ret.lock = &sync.RWMutex{}
  38. ret.userItemList = make(map[int]*item.UserItem)
  39. ret.userId = userId
  40. ret.ipAddress = ipAddress
  41. ret.endChan = make(chan int)
  42. //TODO: 去数据库取自己的背包道具
  43. ret.loadUserInventory()
  44. // 遍历一下是否有时效道具,使用掉
  45. for _, v := range ret.userItemList {
  46. sysItem := getItemManager().getItem(v.ItemId)
  47. if sysItem == nil {
  48. continue
  49. }
  50. if sysItem.Duration == 0 {
  51. continue
  52. }
  53. if sysItem.ActiveId == 0 || sysItem.ActiveId == v.ItemId {
  54. continue
  55. }
  56. go ret.consume(v.ItemId, 0, 0, 0, 0)
  57. }
  58. userTicker := time.NewTicker(time.Duration(5) * time.Second)
  59. go func(t *time.Ticker) {
  60. for { //循环
  61. select {
  62. case <-ret.endChan:
  63. t.Stop()
  64. return
  65. case <-t.C:
  66. ret.Timer_checkExpire()
  67. }
  68. }
  69. }(userTicker)
  70. return ret
  71. }
  72. func (this *user_inventory) loadUserInventory() {
  73. userItems := getUserItemList(this.userId)
  74. this.lock.Lock()
  75. this.userItemList = userItems
  76. /*for _, v := range userItems {
  77. // 如果是永久道具,直接使用
  78. if v.Duration == -1 {
  79. go this.consume(v.ItemId, 0, 1, 0, 0)
  80. }
  81. }*/
  82. this.lock.Unlock()
  83. }
  84. // 析构,停止计时器等
  85. func (this *user_inventory) destructor() {
  86. close(this.endChan)
  87. }
  88. func (this *user_inventory) Timer_checkExpire() {
  89. //检查道具是否时效
  90. var toRemove []*item.UserItem
  91. this.lock.RLock()
  92. for _, u := range this.userItemList {
  93. if this.IsExpired(u) {
  94. log.Debug("user_inventory.Timer_checkExpire userId=%d ==> %+v", this.userId, u)
  95. // 如果是装扮道具,通知一下用户信息那边修改
  96. sysItem := getItemManager().getItem(u.ItemId)
  97. if sysItem == nil {
  98. log.Debug("user_inventory.Timer_checkExpire itemId[%d] invalid", u.ItemId)
  99. toRemove = append(toRemove, u)
  100. continue
  101. }
  102. if sysItem.Type == item.Item_Decoration {
  103. userservices.OnDecorationExpired(this.userId, u.ItemId)
  104. }
  105. //道具时效, 通知客户端
  106. d, _ := json.Marshal(notification.NotificationInventory{ItemIds: []int{u.ItemId}, Action: Inventory_Expire})
  107. go notification.AddNotification(this.userId, notification.Notification_Inventory, string(d))
  108. //删除道具
  109. toRemove = append(toRemove, u)
  110. }
  111. }
  112. this.lock.RUnlock()
  113. if len(toRemove) <= 0 {
  114. return
  115. }
  116. this.lock.Lock()
  117. for _, v := range toRemove {
  118. //TODO:写道具日志
  119. go this.addLog(v.ItemId, v.Count, -v.Count, 0, 0, "道具过期", this.ipAddress)
  120. //TODO:通知数据库道具过期
  121. delUserItem(this.userId, v)
  122. delete(this.userItemList, v.ItemId)
  123. }
  124. this.lock.Unlock()
  125. }
  126. func (this *user_inventory) getItemList() []*item.UserItem {
  127. var l []*item.UserItem
  128. this.lock.RLock()
  129. defer this.lock.RUnlock()
  130. for _, v := range this.userItemList {
  131. l = append(l, v)
  132. }
  133. return l
  134. }
  135. func (this *user_inventory) getItemCount(itemId int) int {
  136. this.lock.RLock()
  137. defer this.lock.RUnlock()
  138. for _, v := range this.userItemList {
  139. if v.ItemId == itemId {
  140. return v.Count
  141. }
  142. }
  143. return 0
  144. }
  145. // 获取抽奖券
  146. func (this *user_inventory) getLottery() *item.UserItem {
  147. this.lock.RLock()
  148. defer this.lock.RUnlock()
  149. for _, v := range this.userItemList {
  150. if v.ItemId == Item_ID_Lottery {
  151. return v
  152. }
  153. }
  154. return nil
  155. }
  156. // 消耗抽奖券
  157. func (this *user_inventory) consumeLottery(count int) (bool, string) {
  158. return this.consume(Item_ID_Lottery, 0, count, 0, 0)
  159. }
  160. func (this *user_inventory) consumeBulk(items []item.ItemPack, logType int) bool {
  161. var rollBackItems []item.ItemPack
  162. allOk := true
  163. for _, v := range items {
  164. ok, _ := this.consume(v.ItemId, 0, v.Count, logType, 0)
  165. if ok {
  166. rollBackItems = append(rollBackItems, v)
  167. } else {
  168. allOk = false
  169. break
  170. }
  171. }
  172. if !allOk {
  173. for _, v := range rollBackItems {
  174. this.addItem(v, logType)
  175. }
  176. }
  177. return allOk
  178. }
  179. func (this *user_inventory) consume(itemId int, bullet int, count int, logType int, isGift int) (bool, string) {
  180. // log.Debug("user_inventory.consume userId=%d itemId=%d bullet=%d count=%d logType=%d isGift=%d",
  181. // this.userId, itemId, bullet, count, logType, isGift)
  182. sysItem := getItemManager().getItem(itemId)
  183. if sysItem == nil {
  184. log.Debug("user_inventory.consume itemId[%d] invalid", itemId)
  185. return false, "无效的道具ID"
  186. }
  187. // 非背包展示道具,直接调数据库接口更新
  188. if sysItem.Type == item.Item_Gold || sysItem.Type == item.Item_Chip || sysItem.Type == item.Item_Vitality {
  189. // TODO: 通知数据库刷新
  190. ok := false
  191. errMsg := ""
  192. switch sysItem.Type {
  193. case item.Item_Gold:
  194. ok = cash.ReduceMoney(this.userId, count, logType, "道具模块", "扣金币", this.ipAddress)
  195. if !ok {
  196. errMsg = "金币不足"
  197. }
  198. case item.Item_Chip:
  199. ok = chip.ReduceChip(this.userId, count, logType, "道具模块", "扣筹码", this.ipAddress) == 1
  200. if !ok {
  201. errMsg = "筹码不足"
  202. }
  203. }
  204. return ok, errMsg
  205. }
  206. if count == 0 {
  207. count = 1
  208. }
  209. this.lock.Lock()
  210. defer this.lock.Unlock()
  211. // 我有没有这个道具?
  212. myItem, ok := this.userItemList[itemId]
  213. if !ok {
  214. log.Debug("user_inventory.consume itemId[%d] not exist", itemId)
  215. return false, "道具不存在"
  216. }
  217. if myItem.Start > 0 && !this.IsExpired(myItem) {
  218. // 本身是已使用的道具,这里只是切换成激活状态
  219. return true, "使用成功"
  220. }
  221. if myItem.Count < count {
  222. log.Debug("user_inventory.consume itemId[%d] not enough %d < %d", itemId, myItem.Count, count)
  223. return false, "道具数量不够"
  224. }
  225. //时效道具, 加时间
  226. retMsg := "使用成功"
  227. isDuration := false
  228. if sysItem.ActiveId > 0 && isGift == 0 {
  229. isDuration = true
  230. if l, ok := this.userItemList[sysItem.ActiveId]; ok {
  231. // 如果本身为永久道具,则折现
  232. if l.Duration == -1 {
  233. gold := sysItem.Value * count
  234. go this.addItem(item.ItemPack{ItemId: item.Item_Gold, Count: gold}, common.LOGTYPE_TOOL_CONVERT)
  235. retMsg = fmt.Sprintf("道具已折算成[%d]金币", gold)
  236. } else if myItem.Duration == -1 {
  237. l.Duration = -1
  238. } else {
  239. // 根据个数确定时长
  240. l.Duration += myItem.Duration * count
  241. }
  242. } else {
  243. //新增使用中的时效道具
  244. ui := &item.UserItem{
  245. ItemId: sysItem.ActiveId,
  246. Count: 1,
  247. Start: common.GetTimeStamp(),
  248. Duration: myItem.Duration * count,
  249. }
  250. this.userItemList[sysItem.ActiveId] = ui
  251. }
  252. go updateUserItem(this.userId, this.userItemList[sysItem.ActiveId])
  253. }
  254. // 如果是兑换券
  255. if sysItem.Type == item.Item_GiftCard {
  256. ok, retMsg = getGiftCardManager().useCard(this.userId, sysItem.Id)
  257. // log.Debug("user_inventory.consume.useCard userId=%d itemId=%d ret=%v retMsg=%s", this.userId, sysItem.Id, ok, retMsg)
  258. if !ok {
  259. return ok, retMsg
  260. }
  261. }
  262. currCount := myItem.Count
  263. myItem.Count -= count
  264. remark := "使用道具" + common.GetLogTypeName(bullet)
  265. go this.addLog(itemId, currCount, -count, myItem.Count, 0, remark, this.ipAddress)
  266. //道具用完了, 删除
  267. if myItem.Count == 0 {
  268. //TODO:通知数据库道具删除
  269. go delUserItem(this.userId, myItem)
  270. delete(this.userItemList, itemId)
  271. } else {
  272. //TODO:通知数据库道具消耗
  273. go updateUserItem(this.userId, myItem)
  274. }
  275. //通知客户端
  276. if !isDuration {
  277. d, _ := json.Marshal(notification.NotificationInventory{ItemIds: []int{itemId}, Action: Inventory_Consume})
  278. go notification.AddNotification(this.userId, notification.Notification_Inventory, string(d))
  279. }
  280. return true, retMsg
  281. }
  282. func (this *user_inventory) sell(itemId, count, logType int) (bool, string) {
  283. log.Debug("user_inventory.sell userId=%d itemId=%d count=%d logType=%d",
  284. this.userId, itemId, count, logType)
  285. sysItem := getItemManager().getItem(itemId)
  286. if sysItem == nil {
  287. log.Debug("user_inventory.sell itemId[%d] invalid", itemId)
  288. return false, "无效的道具ID"
  289. }
  290. if sysItem.Value <= 0 {
  291. log.Debug("user_inventory.sell itemId[%d] is not sell", itemId)
  292. return false, "该道具无法出售"
  293. }
  294. if sysItem.ShowPrice <= 0 {
  295. return false, "该道具无法出售"
  296. }
  297. if logType <= 0 {
  298. logType = common.LOGTYPE_TOOL_SELL
  299. }
  300. if count == 0 {
  301. count = 1
  302. }
  303. this.lock.Lock()
  304. defer this.lock.Unlock()
  305. // 我有没有这个道具?
  306. myItem, ok := this.userItemList[itemId]
  307. if !ok {
  308. log.Debug("user_inventory.sell itemId[%d] not exist", itemId)
  309. return false, "道具不存在"
  310. }
  311. if myItem.Count <= 0 {
  312. log.Debug("user_inventory.sell itemId[%d] is zero", itemId)
  313. return false, "道具不存在"
  314. }
  315. if myItem.Count < count {
  316. return false, "道具数量不够"
  317. }
  318. currCount := myItem.Count
  319. myItem.Count -= count
  320. gold := sysItem.Value * count
  321. go this.addItem(item.ItemPack{ItemId: item.Item_Gold, Count: gold}, logType)
  322. retMsg := fmt.Sprintf("道具已折算成[%d]金币", gold)
  323. go this.addLog(itemId, currCount, -count, myItem.Count, logType, "扣减", this.ipAddress)
  324. // 道具用完了, 删除
  325. if myItem.Count == 0 {
  326. // TODO:通知数据库道具删除
  327. go delUserItem(this.userId, myItem)
  328. delete(this.userItemList, itemId)
  329. } else {
  330. // TODO:通知数据库道具消耗
  331. go updateUserItem(this.userId, myItem)
  332. }
  333. // 通知客户端
  334. d, _ := json.Marshal(notification.NotificationInventory{ItemIds: []int{itemId}, Action: Inventory_Sell})
  335. go notification.AddNotification(this.userId, notification.Notification_Inventory, string(d))
  336. return true, retMsg
  337. }
  338. func (this *user_inventory) addLog(itemId, currCount, wantCount, stillCount, logType int, remark, ipAddress string) {
  339. // log.Debug("user_inventory addLog %d:%d currCount=%d wantCount=%d stillCount=%d logType=%d remark=%s",
  340. // this.userId, itemId, currCount, wantCount, stillCount, logType, remark)
  341. remark = common.GetLogTypeName(logType) + remark
  342. go addLog(this.userId, itemId, currCount, wantCount, stillCount, remark, ipAddress)
  343. }
  344. func (this *user_inventory) addItemsWithExpireTime(items []item.ItemPack, logType int, expireTime int) bool {
  345. // 特殊接口,只处理时效道具
  346. now := int(time.Now().Unix())
  347. if expireTime < now {
  348. log.Error("user_inventory.addItemsWithExpireTime userId[%d] expireTime[%d] < now[%d]", this.userId, expireTime, now)
  349. return false
  350. }
  351. for _, v := range items {
  352. sysItem := getItemManager().getItem(v.ItemId)
  353. if sysItem == nil {
  354. log.Error("user_inventory.addItemsWithExpireTime invalid userId[%d] ItemId %d", this.userId, v.ItemId)
  355. continue
  356. }
  357. itemId := v.ItemId
  358. if sysItem.ActiveId != 0 {
  359. itemId = sysItem.ActiveId
  360. }
  361. // 我本身有没有
  362. this.lock.Lock()
  363. myItem, ok := this.userItemList[itemId]
  364. if ok {
  365. myItem.Start = now
  366. myItem.Duration = expireTime - now
  367. } else {
  368. this.userItemList[itemId] = &item.UserItem{ItemId: itemId, Start: now, Duration: expireTime - now, Count: 1}
  369. myItem = this.userItemList[itemId]
  370. }
  371. this.lock.Unlock()
  372. //TODO: 写道具日志
  373. go this.addLog(myItem.ItemId, 0, v.Count, myItem.Count, logType, "添加道具", this.ipAddress)
  374. //TODO: 通知数据库更新道具信息
  375. go updateUserItem(this.userId, myItem)
  376. }
  377. return true
  378. }
  379. func (this *user_inventory) addItem(it item.ItemPack, logType int) bool {
  380. // log.Debug("user_inventory.addItem userId=%d ipAddress=%s it=%+v", this.userId, this.ipAddress, it)
  381. if it.Count <= 0 {
  382. log.Debug("user_inventory.addItem userId[%d] %v", this.userId, it)
  383. log.Debug("%s", debug.Stack())
  384. return false
  385. }
  386. s := getItemManager().getItem(it.ItemId)
  387. if s == nil {
  388. log.Error("user_inventory.addItem invalid userId[%d] ItemId %d", this.userId, it.ItemId)
  389. return false
  390. }
  391. //log.Debug("user_inventory.addItem UserId[%d] sys[%+v]", this.userId, s)
  392. // 非背包展示道具,直接调数据库接口更新
  393. if s.Type == item.Item_Gold || s.Type == item.Item_Chip || s.Type == item.Item_Vitality || s.Type == item.Item_Vip {
  394. // TODO: 通知数据库刷新
  395. switch s.Type {
  396. case item.Item_Gold:
  397. cash.GiveMoney(this.userId, it.Count, logType, "道具模块", "加金币", this.ipAddress)
  398. case item.Item_Chip:
  399. chip.GiveChip(this.userId, it.Count, logType, "道具模块", "加筹码", this.ipAddress)
  400. case item.Item_Vip:
  401. // 添加vip时长
  402. log.Debug("user_inventory.addItem UserId[%d] AddVipSeconds %d", this.userId, s.Duration)
  403. vipservice.AddVipSeconds(this.userId, s.Duration)
  404. }
  405. return true
  406. } else if s.Type == item.Item_Addminutes || s.Type == item.Item_Physical || s.Type == item.Item_Cash { //实物
  407. return true
  408. }
  409. // 如果是虚拟道具(限时道具本体),不添加
  410. if getItemManager().isVirtualItem(it.ItemId) {
  411. log.Release("user_inventory.addItem virtual item [%d]", it.ItemId)
  412. return false
  413. }
  414. this.lock.Lock()
  415. myItem, ok := this.userItemList[it.ItemId]
  416. if ok {
  417. currCount := 0
  418. currCount = myItem.Count
  419. myItem.Count += it.Count
  420. this.lock.Unlock()
  421. //TODO: 写道具日志
  422. go this.addLog(myItem.ItemId, currCount, it.Count, myItem.Count, logType, "添加道具", this.ipAddress)
  423. // 如果是兑换券
  424. if s.Type == item.Item_GiftCard {
  425. go getGiftCardManager().genCard(this.userId, s.Id, it.Count)
  426. }
  427. //TODO: 通知数据库更新道具信息
  428. updateUserItem(this.userId, myItem)
  429. return true
  430. }
  431. this.lock.Unlock()
  432. // 如果是时效道具,直接使用
  433. if s.Duration != 0 {
  434. this.lock.Lock()
  435. this.userItemList[it.ItemId] = &item.UserItem{ItemId: s.Id, Start: 0, Duration: s.Duration, Count: it.Count}
  436. this.lock.Unlock()
  437. //TODO: 写道具日志
  438. this.addLog(it.ItemId, 0, it.Count, 0, logType, "新增道具", this.ipAddress)
  439. this.consume(it.ItemId, 0, it.Count, 0, 0)
  440. return true
  441. }
  442. //玩家还没有该道具,新增
  443. ui := &item.UserItem{
  444. ItemId: s.Id,
  445. Start: 0,
  446. Duration: s.Duration,
  447. }
  448. ui.Count = it.Count
  449. this.lock.Lock()
  450. this.userItemList[ui.ItemId] = ui
  451. this.lock.Unlock()
  452. //TODO: 写道具日志
  453. this.addLog(ui.ItemId, 0, it.Count, ui.Count, logType, "新增道具", this.ipAddress)
  454. // 如果是兑换券
  455. if s.Type == item.Item_GiftCard {
  456. go getGiftCardManager().genCard(this.userId, s.Id, it.Count)
  457. }
  458. //TODO: 通知数据库更新道具信息
  459. go updateUserItem(this.userId, ui)
  460. return true
  461. }
  462. func (this *user_inventory) IsExpired(u *item.UserItem) bool {
  463. if u.Duration <= 0 {
  464. return false
  465. }
  466. if u.Start == 0 || u.Duration == 0 {
  467. return false
  468. }
  469. now := common.GetTimeStamp()
  470. return (now - u.Start) > u.Duration
  471. }
  472. func (this *user_inventory) reduceItemByAdmin(opUserId int, opUserName string, itemId, count int) (bool, string) {
  473. if count <= 0 {
  474. return false, "扣减失败,无效参数"
  475. }
  476. sysItem := getItemManager().getItem(itemId)
  477. if sysItem == nil {
  478. log.Debug("user_inventory.reduceItemByAdmin itemId[%d] invalid", itemId)
  479. return false, "扣减失败,无效的道具ID"
  480. }
  481. this.lock.Lock()
  482. defer this.lock.Unlock()
  483. // 我有没有这个道具?
  484. myItem, ok := this.userItemList[itemId]
  485. if !ok {
  486. log.Debug("user_inventory.reduceItemByAdmin itemId[%d] not exist", itemId)
  487. return false, "扣减失败,道具不存在"
  488. }
  489. if myItem.Count <= 0 {
  490. log.Debug("user_inventory.reduceItemByAdmin itemId[%d] is zero", itemId)
  491. return false, "扣减失败,道具不存在"
  492. }
  493. currCount := myItem.Count
  494. myItem.Count -= count
  495. msg := fmt.Sprintf("后台扣减道具(opUserId:%d opUserName:%s)", opUserId, opUserName)
  496. go this.addLog(itemId, currCount, -count, myItem.Count, 0, msg, this.ipAddress)
  497. //道具用完了, 删除
  498. if myItem.Count == 0 {
  499. //TODO:通知数据库道具删除
  500. delUserItem(this.userId, myItem)
  501. delete(this.userItemList, itemId)
  502. } else {
  503. //TODO:通知数据库道具消耗
  504. updateUserItem(this.userId, myItem)
  505. }
  506. //通知客户端
  507. d, _ := json.Marshal(notification.NotificationInventory{ItemIds: []int{itemId}, Action: Inventory_Consume})
  508. go notification.AddNotification(this.userId, notification.Notification_Inventory, string(d))
  509. retmsg := fmt.Sprintf("扣减成功,道具id=%d 道具名称=%s 扣减道具数=%d 剩余道具数=%d",
  510. myItem.ItemId, sysItem.Name, count, myItem.Count)
  511. return true, retmsg
  512. }