base.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. class Sessions::Event::Base
  2. def initialize(params)
  3. params.each { |key, value|
  4. instance_variable_set "@#{key}", value
  5. }
  6. @is_web_socket = false
  7. return if !@clients[@client_id]
  8. @is_web_socket = true
  9. end
  10. def websocket_send(recipient_client_id, data)
  11. msg = if data.class != Array
  12. "[#{data.to_json}]"
  13. else
  14. data.to_json
  15. end
  16. if @clients[recipient_client_id]
  17. log 'debug', "ws send #{msg}", recipient_client_id
  18. @clients[recipient_client_id][:websocket].send(msg)
  19. else
  20. log 'debug', "fs send #{msg}", recipient_client_id
  21. Sessions.send(recipient_client_id, data)
  22. end
  23. end
  24. def valid_session?
  25. if !@session
  26. error = {
  27. event: 'error',
  28. data: {
  29. state: 'no_session',
  30. },
  31. }
  32. Sessions.send(@client_id, error)
  33. return
  34. end
  35. if !@session['id']
  36. error = {
  37. event: 'error',
  38. data: {
  39. state: 'no_session_user_id',
  40. },
  41. }
  42. Sessions.send(@client_id, error)
  43. return
  44. end
  45. true
  46. end
  47. def permission_check(key, event)
  48. if !@session
  49. error = {
  50. event: "#{event}_error",
  51. data: {
  52. state: 'no_session',
  53. },
  54. }
  55. Sessions.send(@client_id, error)
  56. return
  57. end
  58. if !@session['id']
  59. error = {
  60. event: "#{event}_error",
  61. data: {
  62. state: 'no_session_user_id',
  63. },
  64. }
  65. Sessions.send(@client_id, error)
  66. return
  67. end
  68. user = User.lookup(id: @session['id'])
  69. if !user
  70. error = {
  71. event: "#{event}_error",
  72. data: {
  73. state: 'no_such_user',
  74. },
  75. }
  76. Sessions.send(@client_id, error)
  77. return
  78. end
  79. if !user.permissions?(key)
  80. error = {
  81. event: "#{event}_error",
  82. data: {
  83. state: 'no_permission',
  84. },
  85. }
  86. Sessions.send(@client_id, error)
  87. return
  88. end
  89. true
  90. end
  91. def log(level, data, client_id = nil)
  92. if !@options[:v]
  93. return if level == 'debug'
  94. end
  95. if !client_id
  96. client_id = @client_id
  97. end
  98. # rubocop:disable Rails/Output
  99. puts "#{Time.now.utc.iso8601}:client(#{client_id}) #{data}"
  100. #puts "#{Time.now.utc.iso8601}:#{ level }:client(#{ client_id }) #{ data }"
  101. # rubocop:enable Rails/Output
  102. end
  103. def destroy
  104. end
  105. end