client.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. package gate
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. _ "runtime/debug"
  8. "strconv"
  9. "time"
  10. badge "bet24.com/servers/micros/badge/proto"
  11. utils2 "bet24.com/servers/insecureframe/gate/Utils"
  12. "bet24.com/event"
  13. "bet24.com/log"
  14. "bet24.com/network"
  15. "bet24.com/redis"
  16. coreservice "bet24.com/servers/coreservice/client"
  17. "bet24.com/servers/insecureframe/message"
  18. dotservice "bet24.com/servers/micros/dotservice/proto"
  19. item "bet24.com/servers/micros/item_inventory/proto"
  20. remotemessage "bet24.com/servers/micros/remotemessage/proto"
  21. userlabel "bet24.com/servers/micros/userlabel/proto"
  22. userservices "bet24.com/servers/micros/userservices/proto"
  23. vipservice "bet24.com/servers/micros/userservices/proto"
  24. "bet24.com/servers/transaction"
  25. "bet24.com/servers/user"
  26. "bet24.com/utils"
  27. uuid "github.com/satori/go.uuid"
  28. )
  29. const EXPIRE_TIME = 1800
  30. func NewClient(userIndex int32, conn *network.WSConn, gate *Gate, isRobot bool) *client {
  31. ret := new(client)
  32. ret.userInfo = user.NewUserInfo(userIndex)
  33. ret.gate = gate
  34. ret.conn = conn
  35. if isRobot {
  36. ret.userInfo.SetRobot()
  37. } else {
  38. ret.userInfo.SetUserIp(ret.IP())
  39. }
  40. return ret
  41. }
  42. type client struct {
  43. conn *network.WSConn
  44. gate *Gate
  45. userInfo *user.UserInfo
  46. // 用户主线程退出信号
  47. onMainExit func()
  48. // 主控context
  49. m_ctx context.Context
  50. // 来自服务器的消息
  51. chan_channel_msg chan interface{}
  52. // event chan
  53. chan_event chan interface{}
  54. lastPing time.Time
  55. Log_login_time time.Time
  56. destroyed bool
  57. loginGold int
  58. }
  59. func (this *client) GetEventChannel() chan interface{} {
  60. return this.chan_event
  61. }
  62. func (this *client) Run() {
  63. this.lastPing = time.Now()
  64. socket_channel := make(chan *message.BaseMsg)
  65. ctx, cancel := context.WithCancel(context.Background())
  66. this.onMainExit = cancel
  67. this.m_ctx = ctx
  68. this.destroyed = false
  69. go this.readSocketData(socket_channel)
  70. go this.checkPingTimeOut(ctx)
  71. this.chan_event = make(chan interface{})
  72. this.Log_login_time = time.Now()
  73. gate.addUser(this.userIndex(), this)
  74. if this.userInfo.IsRobot() || this.conn == nil {
  75. return
  76. }
  77. for {
  78. select {
  79. case msg := <-socket_channel: //来自socket消息处理
  80. this.handleMsg(msg)
  81. case msg := <-this.chan_event: // event handler
  82. go this.handleEvent(msg)
  83. case <-ctx.Done():
  84. this.Destroy()
  85. return
  86. }
  87. }
  88. }
  89. func (this *client) userIndex() int32 {
  90. return this.userInfo.GetUserIndex()
  91. }
  92. func (this *client) isLogined() bool {
  93. return this.userInfo.GetUserId() > 0
  94. }
  95. func (this *client) isRobot() bool {
  96. return this.userInfo.IsRobot()
  97. }
  98. func (this *client) checkPingTimeOut(ctx context.Context) {
  99. if this.userInfo.IsRobot() || this.conn == nil {
  100. return
  101. }
  102. count := 0
  103. for {
  104. c, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  105. select {
  106. case <-ctx.Done():
  107. //log.Debug("exit ping ---------------------userID=%d err=%v", this.UserId, ctx.Err())
  108. cancel()
  109. return
  110. case <-c.Done():
  111. this.handlePing()
  112. count++
  113. if count == 100 {
  114. count = 0
  115. this.checkSection(this.userInfo.GetUserId(), this.userInfo.GetUserSession())
  116. }
  117. }
  118. cancel()
  119. }
  120. }
  121. func (this *client) handlePing() {
  122. // 很长时间没有ping了
  123. if this.isForceToCloseConnect() {
  124. this.Close()
  125. this.onMainExit()
  126. }
  127. }
  128. func (this *client) isForceToCloseConnect() bool {
  129. if this.userInfo.IsRobot() {
  130. return false
  131. }
  132. pastSeconds := int(time.Now().Sub(this.lastPing).Seconds())
  133. if pastSeconds > 180 {
  134. log.Debug("isForceToCloseConnect pastSeconds = %d,userid = %d", pastSeconds, this.userInfo.GetUserId())
  135. return true
  136. }
  137. return false
  138. }
  139. func (this *client) handleEvent(evt interface{}) {
  140. t := evt.(event.IEventChan)
  141. defer utils.TimeCost(fmt.Sprintf("client.handleEvent"))()
  142. t.OnEvent()
  143. }
  144. func (this *client) readSocketData(ch chan<- *message.BaseMsg) {
  145. if this.userInfo.IsRobot() || this.conn == nil {
  146. return
  147. }
  148. for {
  149. if this.conn == nil {
  150. return
  151. }
  152. data, err := this.conn.ReadMsg()
  153. if err != nil {
  154. log.Release("read message: %v", err)
  155. this.onMainExit()
  156. break
  157. }
  158. var msg *message.BaseMsg = new(message.BaseMsg)
  159. e := json.Unmarshal(data, msg)
  160. if e != nil {
  161. log.Release("readSocketData Unmarshal failed %v", string(data))
  162. } else {
  163. if msg.Msg == "" && msg.Data == "" {
  164. msg.Data = string(data)
  165. }
  166. ch <- msg
  167. }
  168. }
  169. }
  170. func (this *client) handleMsg(msg *message.BaseMsg) {
  171. defer utils.TimeCost(fmt.Sprintf("client.handleMsg %v", msg.Msg))()
  172. this.lastPing = time.Now()
  173. switch msg.Msg {
  174. case "ping":
  175. this.WriteMsg(msg.Msg, msg)
  176. //大厅功能类操作
  177. case "loginByIMei": // 登录
  178. this.loginByIMei(msg.Msg, msg.Data)
  179. case "login": // 到数据库查询
  180. this.Login(msg.Msg, msg.Data)
  181. case "loginByToken":
  182. this.loginByToken(msg.Msg, msg.Data)
  183. case "loginBySection":
  184. this.loginByToken(msg.Msg, msg.Data)
  185. default:
  186. gate.addMessageRecord(this.userInfo.GetUserId(), fmt.Sprintf("[%s]:{%s}", msg.Msg, msg.Data))
  187. if !sink.OnGameMessage(this.userIndex(), this.userInfo.GetUserId(), msg.Msg, msg.Data) {
  188. log.Debug("unhandled message %v data %v", msg.Msg, msg.Data)
  189. }
  190. }
  191. }
  192. func (this *client) OnClose() {
  193. this.Destroy()
  194. }
  195. func (this *client) WriteMsg(cmdName string, msg interface{}) bool {
  196. buf, err := json.Marshal(msg)
  197. if err != nil {
  198. log.Release("WriteMsg Marshal faild cmdName:%v msg:%v", cmdName, msg)
  199. return false
  200. }
  201. if this.userInfo.IsRobot() || this.conn == nil || this.destroyed {
  202. return true
  203. }
  204. e := this.conn.WriteData(buf)
  205. if e != nil {
  206. log.Debug("client.WriteMsg %v", e)
  207. }
  208. return true
  209. }
  210. func (this *client) writeRawData(data string) {
  211. this.conn.WriteData([]byte(data))
  212. }
  213. func (this *client) LocalAddr() net.Addr {
  214. if this.conn == nil {
  215. return nil
  216. }
  217. return this.conn.LocalAddr()
  218. }
  219. func (this *client) RemoteAddr() net.Addr {
  220. if this.conn == nil {
  221. return nil
  222. }
  223. return this.conn.RemoteAddr()
  224. }
  225. func (this *client) IP() string {
  226. if this.userInfo.IsRobot() || this.conn == nil {
  227. return "127.0.0.1"
  228. }
  229. return this.RemoteAddr().(*net.TCPAddr).IP.String()
  230. }
  231. func (this *client) Close() {
  232. if this.conn != nil {
  233. this.conn.Close()
  234. } else {
  235. // 机器人
  236. this.Destroy()
  237. }
  238. }
  239. func (this *client) Destroy() {
  240. if this.destroyed {
  241. log.Debug("Destroy userID=%d this.destroyed", this.userIndex())
  242. return
  243. }
  244. this.destroyed = true
  245. userId := this.userInfo.GetUserId()
  246. log.Debug("Destroy userID=%d:%d err=%v", this.userIndex(), userId, this.m_ctx.Err())
  247. //log.Debug("%s", debug.Stack())
  248. sink.OnUserExit(this.userIndex())
  249. event.RemoveAllEvent(this.GetEventChannel())
  250. if userId > 0 {
  251. if sink.GetGameID() > 0 {
  252. go userlabel.TriggerEvent(userId, userlabel.Type_Game, userlabel.Scope{
  253. GameId: sink.GetGameID(),
  254. IsFriendRoom: sink.IsPrivateRoom(),
  255. OnlineSeconds: int(time.Now().Unix() - this.Log_login_time.Unix()),
  256. GoldAmount: this.userInfo.GetUserGold() - this.loginGold,
  257. })
  258. }
  259. if sink.IsChipRoom() {
  260. go transaction.WriteChipSync(userId, sink.GetGameID(), 0, 0,
  261. 0, sink.GetGameID()*100+99, sink.GetRoomName(), this.IP())
  262. } else {
  263. go transaction.WriteMoneySync(userId, sink.GetGameID(), 0, 0,
  264. 0, sink.GetGameID()*100+99, sink.GetRoomName(), this.IP())
  265. }
  266. }
  267. if this.conn != nil {
  268. this.conn.Destroy()
  269. this.conn = nil
  270. }
  271. // 为保证上层应用在处理离开的时候数据还在,延迟删除
  272. time.AfterFunc(time.Duration(50)*time.Millisecond, func() {
  273. if userId > 0 {
  274. transaction.Trans_SetGameStatus(userId, sink.GetGameID(), 0, sink.GetRoomName(), sink.IsChipRoom())
  275. coreservice.FriendSetUserStatus(userId, 0, sink.GetRoomName())
  276. }
  277. this.gate.removeUser(this.userIndex())
  278. this.userInfo.Clear()
  279. })
  280. }
  281. func (this *client) Dump() {
  282. idle_time := int(time.Now().Sub(this.lastPing).Seconds())
  283. log.Release("Login[%v],Idle[%d 秒],%s",
  284. this.Log_login_time.Format("2006-01-02 15:04:05"), idle_time, this.userInfo.DumpUserInfo())
  285. if idle_time > 180 {
  286. log.Release("cleaning idle client")
  287. this.Close()
  288. this.onMainExit()
  289. }
  290. }
  291. func (this *client) logout() {
  292. // 为了防止新进的链接被清理掉,这里先把userid置0
  293. sink.OnUserExit(this.userIndex())
  294. this.userInfo.Clear()
  295. var retMsg message.BaseMsg
  296. retMsg.Msg = "logout"
  297. data, _ := json.Marshal(struct{ ErrorMsg string }{ErrorMsg: "账号已在其他地方登录,请留意账号安全!"})
  298. retMsg.Data = string(data)
  299. this.WriteMsg(retMsg.Msg, retMsg)
  300. }
  301. func (this *client) Login(msg, data string) {
  302. this.Log_login_time = time.Now()
  303. obj := transaction.NewCheckUserPassword()
  304. e := json.Unmarshal([]byte(data), &obj.IN)
  305. if e != nil {
  306. this.onLoginFailed("login Unmarshal data failed")
  307. return
  308. }
  309. obj.DoAction(nil)
  310. ret := obj.State
  311. if !ret || obj.Out.RetCode != 1 {
  312. this.onLoginFailed("CheckUserPassword DoAction fail")
  313. return
  314. }
  315. // this.userInfo.YyfUid=obj.In.YyfUid
  316. // this.userInfo.YyfName=obj.In.YyfName
  317. this.userInfo.YyfGold=9000000
  318. // this.userInfo.YyfFaceId=obj.In.YyfFaceId
  319. this.userInfo.SetUserId(obj.IN.UserID)
  320. this.userInfo.SetUserGold(obj.Out.Amount)
  321. this.userInfo.SetUserBankamount(obj.Out.Bank)
  322. this.userInfo.SetUserNickName(obj.Out.NickName)
  323. this.userInfo.SetUserFaceId(obj.Out.FaceID)
  324. this.userInfo.SetUserFaceUrl(obj.Out.FaceUrl)
  325. this.userInfo.SetUserSex(obj.Out.Sex)
  326. this.userInfo.SetUserSession(this.genSection())
  327. this.userInfo.SetUserWords(obj.Out.UserWords)
  328. this.userInfo.SetLogonTime(this.Log_login_time.Unix())
  329. this.userInfo.SetUserTeacher(obj.Out.TeacherID)
  330. this.userInfo.SetHigherUserID(obj.Out.HigherUserID)
  331. this.userInfo.SetGrade(obj.Out.Grade)
  332. this.userInfo.SetChip(obj.Out.ChipAmount)
  333. this.userInfo.SetChipBank(obj.Out.ChipBank)
  334. this.userInfo.SetCurrency(obj.Out.Currency)
  335. this.userInfo.SetCurrencyIsModify(obj.Out.CurrencyIsModify)
  336. this.userInfo.SetUTMSource(obj.Out.UTMSource)
  337. this.userInfo.SetPartnerId(obj.IN.PartnerId)
  338. this.userInfo.SetVersionCode(obj.IN.Version)
  339. this.userInfo.SetUserCharm(obj.Out.Charm)
  340. this.onLoginSuccess(msg, obj.Out.Code, obj.Out.IsGuest, 0, false)
  341. }
  342. func (this *client) loginByIMei(msg, data string) {
  343. this.Log_login_time = time.Now()
  344. fmt.Println("data====",data)
  345. //var obj2 *transaction.Trans_login2
  346. //e2 := json.Unmarshal([]byte(data), &obj2.In)
  347. obj := transaction.NewTransLogin()
  348. e := json.Unmarshal([]byte(data), &obj.In)
  349. if e != nil {
  350. this.onLoginFailed("loginByIMei Unmarshal data failed")
  351. return
  352. }
  353. log.Debug("client.loginByIMei %s", data)
  354. obj.In.IpAddress = this.IP()
  355. obj.In.NickName = coreservice.ParseKeyword(obj.In.NickName)
  356. if obj.In.PlatType==1{
  357. user := utils2.GetUserInfoData(obj.In.YyfUid)
  358. fmt.Printf("user===",user)
  359. this.userInfo.YyfUid=user.Data[0].UserId
  360. this.userInfo.YyfName=user.Data[0].NickName
  361. this.userInfo.YyfGold=user.Data[0].GoldCoins
  362. this.userInfo.YyfFaceId=user.Data[0].Avatar
  363. }else if obj.In.PlatType==2{
  364. this.userInfo.YyfUid=obj.In.YyfUid
  365. this.userInfo.YyfName=obj.In.YyfName
  366. this.userInfo.YyfGold=200000
  367. this.userInfo.YyfFaceId=obj.In.YyfFaceId
  368. }
  369. fmt.Printf("yyfuid===",obj.In.YyfUid,obj.In.YyfFaceId,obj.In.YyfName)
  370. obj.DoAction(nil,this.userInfo.YyfGold)
  371. ret := obj.State
  372. if !ret || obj.Out.RetCode != 1 {
  373. if obj.Out.RetCode == 13 {
  374. this.onLoginFailed("13")
  375. return
  376. }
  377. log.Release("loginByIMei DoAction fail RetCode = %d", obj.Out.RetCode)
  378. this.onLoginFailed("13")
  379. return
  380. }
  381. // 非普通金币大厅不自动进入
  382. if sink.GetChipRoom() != 0 {
  383. obj.Out.AutoLoginChip = 0
  384. obj.Out.Chip = 0
  385. obj.Out.ChipBank = 0
  386. }
  387. log.Debug("client.loginByIMei [%d] logined", obj.Out.UserID)
  388. //this.userInfo.SetUserId(user.Data[0].UserId)
  389. //this.userInfo.SetUserGold(user.Data[0].GoldCoins)
  390. // this.userInfo.SetUserBankamount(obj.Out.Bank)
  391. //this.userInfo.SetUserNickName(user.Data[0].NickName)
  392. //this.userInfo.SetUserNickName("zhangsan")
  393. //this.userInfo.SetUserFaceId(obj.Out.FaceID)
  394. //this.userInfo.SetUserFaceUrl(user.Data[0].Avatar)
  395. //this.userInfo.SetUserSex(user.Data[0].Gender)
  396. this.userInfo.SetUserId(obj.Out.UserID)
  397. this.userInfo.SetUserNickName(obj.Out.NickName)
  398. this.userInfo.SetUserFaceId(obj.Out.FaceID)
  399. this.userInfo.SetUserFaceUrl(obj.Out.FaceUrl)
  400. this.userInfo.SetUserSex(obj.Out.Sex)
  401. this.userInfo.SetUserGold(obj.Out.Money)
  402. this.userInfo.SetUserBankamount(obj.Out.Bank)
  403. this.userInfo.SetUserPayAmount(obj.Out.PayAmount)
  404. this.userInfo.SetUserSession(this.genSection())
  405. this.userInfo.SetUserWords(obj.Out.UserWords)
  406. this.userInfo.SetLogonTime(this.Log_login_time.Unix())
  407. this.userInfo.SetUserTeacher(obj.Out.TeacherId)
  408. this.userInfo.SetHigherUserID(obj.Out.HigherUserID)
  409. this.userInfo.SetGrade(obj.Out.Grade)
  410. this.userInfo.SetChip(obj.Out.Chip)
  411. this.userInfo.SetChipBank(obj.Out.ChipBank)
  412. this.userInfo.SetCurrency(obj.Out.Currency)
  413. this.userInfo.SetCurrencyIsModify(obj.Out.CurrencyIsModify)
  414. this.userInfo.SetUTMSource(obj.Out.UTMSource)
  415. this.userInfo.SetAutoLoginChip(obj.Out.AutoLoginChip)
  416. this.userInfo.SetPartnerId(obj.In.PartnerID)
  417. this.userInfo.SetVersionCode(obj.In.Version)
  418. this.userInfo.SetUserCharm(obj.Out.Charm)
  419. //头像有变化,更新头像
  420. if obj.In.FaceUrl != "" && obj.In.FaceUrl != obj.Out.FaceUrl {
  421. this.userInfo.SetUserFaceUrl(obj.In.FaceUrl)
  422. objFace := transaction.NewChangeFace()
  423. objFace.IN.UserID = obj.Out.UserID
  424. objFace.IN.Sex = obj.Out.Sex
  425. objFace.IN.FaceUrl = obj.In.FaceUrl
  426. go objFace.DoAction(nil)
  427. }
  428. this.userInfo.SetUserGold(this.userInfo.YyfGold)
  429. obj.ChangeCoin(this.userInfo.YyfGold,obj.Out.UserID)
  430. gate.addMessageRecord(obj.Out.UserID, fmt.Sprintf("[%s]:{%s}", msg, data))
  431. // 新注册
  432. if obj.Out.IsRegister {
  433. // 昵称有变化
  434. if obj.In.NickName != "" && obj.In.NickName != obj.Out.NickName {
  435. this.userInfo.SetUserNickName(obj.In.NickName)
  436. objNick := transaction.NewTransChangeNickName()
  437. objNick.In.UserID = obj.Out.UserID
  438. objNick.In.NewNickName = obj.In.NickName
  439. go objNick.DoAction(nil)
  440. }
  441. // 记录渠道流量
  442. if source, content := obj.UTMInsert(); len(source) > 0 {
  443. this.userInfo.SetUTMSource(source)
  444. // 代理自动绑定
  445. if source == "agentinvite" {
  446. // 上级id
  447. higherUserId, err := strconv.Atoi(content)
  448. if err != nil {
  449. log.Error("loginByIMei UTM content error %v", err)
  450. }
  451. // 绑定代理
  452. if this.bindAgent(obj.Out.UserID, higherUserId, obj.In.IpAddress) {
  453. this.userInfo.SetHigherUserID(higherUserId)
  454. }
  455. }
  456. }
  457. }
  458. // 打点统计
  459. go dotservice.AddDot(obj.Out.UserID, dotservice.DotScope{
  460. Scene: dotservice.Scene_Login,
  461. Action: dotservice.Action_Complete,
  462. Extra: this.userInfo.GetUTMSource(),
  463. })
  464. // 触发用户标签
  465. go userlabel.TriggerEvent(obj.Out.UserID, userlabel.Type_Login, userlabel.Scope{
  466. IPAddress: obj.In.IpAddress,
  467. IMei: obj.In.Deviceid,
  468. IsRegister: obj.Out.IsRegister,
  469. UTMSource: this.userInfo.GetUTMSource(),
  470. IsReturn: obj.Out.IsReturn,
  471. })
  472. this.onLoginSuccess(msg, obj.Out.Code, obj.Out.IsGuest, obj.Out.ChipSend, obj.Out.IsRegister)
  473. log.Debug("client.loginByIMei [%d] loginSuccess", obj.Out.UserID)
  474. if obj.In.MessageToken != "" {
  475. deviceType := obj.In.PartnerID/10000 - 1
  476. remotemessage.SetUserToken(obj.Out.UserID, deviceType, obj.In.MessageToken)
  477. }
  478. // 领取回归奖励
  479. go func(userId int, isReturn bool) {
  480. if !isReturn {
  481. return
  482. }
  483. time.Sleep(1 * time.Second)
  484. coreservice.GiftReturnAward(userId)
  485. }(obj.Out.UserID, obj.Out.IsReturn)
  486. }
  487. func (this *client) bindAgent(userId, higherUserId int, ipAddress string) bool {
  488. var ret struct {
  489. RetCode int
  490. Items []item.ItemPack
  491. }
  492. // 去绑定师徒
  493. resp := coreservice.AgentBind(userId, higherUserId, ipAddress)
  494. if resp.RetCode == 1 {
  495. if err := json.Unmarshal([]byte(resp.Data), &ret); err != nil {
  496. log.Error("client.bindAgent unmarshal err %v", err)
  497. }
  498. }
  499. log.Debug("client.bindAgent userId=%d higherUserId=%d ipAddress=%s resp.Data=%+v", userId, higherUserId, ipAddress, resp.Data)
  500. return ret.RetCode == 1
  501. }
  502. func (this *client) loginByToken(msg, data string) {
  503. var section struct {
  504. UserId int
  505. Token string
  506. PartnerId int
  507. VersionCode int
  508. YyfUid int // 用户ID
  509. YyfFaceId string // 用户ID
  510. YyfName string // 用户ID
  511. YyfGold int // 金币
  512. }
  513. e := json.Unmarshal([]byte(data), &section)
  514. fmt.Printf("section===",section.YyfUid,section.YyfName,section.YyfFaceId)
  515. if e != nil {
  516. errorstring := fmt.Sprintf("send session login return Marshal failed err=%v,data = %v", e, data)
  517. this.onLoginFailed(errorstring)
  518. return
  519. }
  520. if section.UserId == 0 {
  521. log.Release("client.loginByToken section.UserId == 0")
  522. return
  523. }
  524. if !this.checkSection(section.UserId, section.Token) {
  525. this.onLoginFailed("登录已超时,请重新登录")
  526. return
  527. }
  528. this.doLoginByToken(section.UserId, section.Token, msg, section.PartnerId, section.VersionCode,section.YyfUid,section.YyfFaceId,section.YyfName)
  529. }
  530. func (this *client) doLoginByToken(userId int, token string, msg string, partnerId, versionCode int,YyfUid int,YyfFaceId string,YyfName string) {
  531. this.userInfo.SetUserId(userId)
  532. this.userInfo.SetUserSession(token)
  533. // 登陆成功,需要获取所有的登陆数据
  534. obj := transaction.NewTransGetMyInfo()
  535. obj.In.UserID = userId
  536. obj.DoAction(nil)
  537. ret := obj.State
  538. if !ret {
  539. this.onLoginFailed("登录失败,获取个人信息失败")
  540. return
  541. }
  542. this.userInfo.YyfUid=YyfUid
  543. this.userInfo.YyfName=YyfName
  544. this.userInfo.YyfGold=20000
  545. this.userInfo.YyfFaceId=YyfFaceId
  546. fmt.Println("uid===",this.userInfo.YyfUid,this.userInfo.YyfName,this.userInfo.YyfFaceId)
  547. this.userInfo.SetUserNickName(obj.Out.NickName)
  548. this.userInfo.SetUserFaceId(obj.Out.FaceID)
  549. this.userInfo.SetUserFaceUrl(obj.Out.FaceUrl)
  550. this.userInfo.SetUserSex(obj.Out.Sex)
  551. this.userInfo.SetUserGold(obj.Out.Amount)
  552. this.userInfo.SetUserBankamount(obj.Out.Bank)
  553. this.userInfo.SetUserPayAmount(obj.Out.PayMoney)
  554. this.userInfo.SetUserWords(obj.Out.UserWords)
  555. this.userInfo.SetLogonTime(this.Log_login_time.Unix())
  556. this.userInfo.SetUserTeacher(obj.Out.TeacherId)
  557. this.userInfo.SetHigherUserID(obj.Out.HigherUserID)
  558. this.userInfo.SetGrade(obj.Out.Grade)
  559. this.userInfo.SetChip(obj.Out.ChipAmount)
  560. this.userInfo.SetChipBank(obj.Out.ChipBank)
  561. this.userInfo.SetCurrency(obj.Out.Currency)
  562. this.userInfo.SetCurrencyIsModify(obj.Out.CurrencyIsModify)
  563. this.userInfo.SetUTMSource(obj.Out.UTMSource)
  564. this.userInfo.SetPartnerId(partnerId)
  565. this.userInfo.SetVersionCode(versionCode)
  566. this.userInfo.SetUserCharm(obj.Out.Charm)
  567. this.onLoginSuccess(msg, obj.Out.Code, obj.Out.IsGuest, 0, false)
  568. }
  569. func (this *client) forceLogin(userId int) {
  570. sectionKey := this.getSectionKey(userId)
  571. t, ok := redis.String_Get(sectionKey)
  572. if !ok {
  573. t = this.genSectionByUserId(userId)
  574. }
  575. this.doLoginByToken(userId, t, "loginByToken", 0, 0,0,"","")
  576. }
  577. func (this *client) checkSection(userID int, token string) bool {
  578. if token == "" {
  579. return false
  580. }
  581. sectionKey := this.getSectionKey(userID)
  582. t, ok := redis.String_Get(sectionKey)
  583. if !ok {
  584. log.Release("redis error")
  585. return false
  586. }
  587. if t != token {
  588. return false
  589. }
  590. // 刷新有效期
  591. redis.String_SetEx(sectionKey, t, EXPIRE_TIME)
  592. return true
  593. }
  594. func (this *client) getSectionKey(userID int) string {
  595. return fmt.Sprintf("Section:%d", userID)
  596. }
  597. func (this *client) genSectionByUserId(userId int) string {
  598. id, err := uuid.NewV4()
  599. token := ""
  600. if err != nil {
  601. log.Release("genSection failed %v", err)
  602. token = fmt.Sprintf("%v", time.Now())
  603. } else {
  604. token = id.String()
  605. }
  606. redis.String_SetEx(this.getSectionKey(userId), token, EXPIRE_TIME)
  607. return token
  608. }
  609. func (this *client) genSection() string {
  610. userId := this.userInfo.GetUserId()
  611. if userId <= 0 {
  612. log.Debug("client.genSection UserId = %d", userId)
  613. return ""
  614. }
  615. id, err := uuid.NewV4()
  616. token := ""
  617. if err != nil {
  618. log.Release("genSection failed %v", err)
  619. token = fmt.Sprintf("%v", time.Now())
  620. } else {
  621. token = id.String()
  622. }
  623. redis.String_SetEx(this.getSectionKey(userId), token, EXPIRE_TIME)
  624. return token
  625. }
  626. func (this *client) onLoginFailed(errorstring string) {
  627. var retMsg message.BaseMsg
  628. retMsg.Msg = "login_failed"
  629. log.Release("client.onLoginFailed %s", errorstring)
  630. retMsg.Data = errorstring
  631. this.WriteMsg(retMsg.Msg, retMsg)
  632. // 因为发送数据为异步过程,延迟结束网络
  633. go func() {
  634. time.Sleep(100 * time.Millisecond)
  635. this.onMainExit()
  636. }()
  637. }
  638. func (this *client) onLoginSuccess(msg string, code, isGuest, chipSend int, isRegister bool) {
  639. userId := this.userInfo.GetUserId()
  640. this.loginGold = this.userInfo.GetUserGold()
  641. // 发送成功指令
  642. this.userInfo.SetUserStatus(user.UserStatus_Free)
  643. // 获取用户的装扮
  644. this.userInfo.SetDecorations(userservices.GetUserDecoration(userId))
  645. // 获取徽章
  646. this.userInfo.SetBadges(badge.GetBadgeWearAndShow(userId))
  647. userVip := vipservice.GetUserVipInfo(userId)
  648. if userVip != nil {
  649. this.userInfo.SetUserVipLevel(userVip.Level, userVip.Point, userVip.Expire)
  650. }
  651. loginAward, isWhite := this.getLevel(userId)
  652. if !this.isRobot() {
  653. this.checkRedPoint(userId)
  654. }
  655. // 数据库币种为空,允许修改
  656. if this.userInfo.GetCurrency() == "" {
  657. // 根据ip获取币种
  658. //currency := coreservice.GetCurrency(userId, this.IP())
  659. currency := "SAR"
  660. //log.Debug("getCurrency userId=%d ipAddress=%s currency=%s", userId, this.IP(), currency)
  661. this.userInfo.SetCurrency(currency)
  662. }
  663. var retMsg message.BaseMsg
  664. retMsg.Msg = msg
  665. ul := this.userInfo.GetUserInfo_Login(code, isGuest, chipSend, loginAward, isWhite, isRegister)
  666. d, _ := json.Marshal(ul)
  667. retMsg.Data = string(d)
  668. this.WriteMsg(retMsg.Msg, retMsg)
  669. info := message.IsChipRoom{IsChipRoom: sink.IsChipRoom(), IsLadderRoom: sink.IsLadderRoom()}
  670. retMsg.Msg = message.IsChipRoomMsg
  671. d, _ = json.Marshal(info)
  672. retMsg.Data = string(d)
  673. this.WriteMsg(retMsg.Msg, retMsg)
  674. go transaction.Trans_SetGameStatus(userId, sink.GetGameID(), 1, sink.GetRoomName(), sink.IsChipRoom())
  675. go coreservice.FriendSetUserStatus(userId, 1, sink.GetRoomName())
  676. this.gate.userLogined(this.userIndex(), userId)
  677. }
  678. func (this *client) getLevel(userId int) (int, int) {
  679. info := userservices.GetUserLevel(userId)
  680. this.userInfo.SetUserLevel(info.Level)
  681. this.userInfo.SetUserExperience(info.Experience)
  682. return info.LoginAward, info.IsWhite
  683. }
  684. func (this *client) refreshGold() {
  685. userId := this.userInfo.GetUserId()
  686. if userId == 0 {
  687. log.Debug("user.refreshGold userId = 0")
  688. return
  689. }
  690. obj := transaction.NewTransGetMyInfo()
  691. obj.In.UserID = userId
  692. obj.DoAction(nil)
  693. ret := obj.State
  694. if !ret {
  695. log.Debug("client.refreshGold failed")
  696. return
  697. }
  698. if sink.GetGameID() != 0 {
  699. this.userInfo.SetUserGold(obj.Out.Amount)
  700. this.userInfo.SetChip(obj.Out.ChipAmount)
  701. d, _ := json.Marshal(message.UserScoreChange{UserId: userId, Gold: obj.Out.Amount, Chip: obj.Out.ChipAmount,YyfGold:300000})
  702. fmt.Printf("WriteUserMoney===refreshGold")
  703. gate.broadcastData(message.Frame_UserScoreChange, string(d))
  704. }
  705. }
  706. func (this *client) checkRedPoint(userId int) {
  707. var info struct {
  708. MailVipTip bool // 重要邮件(含附件)
  709. }
  710. resp := coreservice.CheckRedPoint(userId)
  711. if err := json.Unmarshal([]byte(resp.Data), &info); err != nil {
  712. log.Error("checkRedPoint unmarshal data failed %v", err)
  713. }
  714. this.userInfo.SetMailVipTip(info.MailVipTip)
  715. }