WebsocketController.coffee 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. logger = require "logger-sharelatex"
  2. metrics = require "metrics-sharelatex"
  3. WebApiManager = require "./WebApiManager"
  4. AuthorizationManager = require "./AuthorizationManager"
  5. DocumentUpdaterManager = require "./DocumentUpdaterManager"
  6. ConnectedUsersManager = require "./ConnectedUsersManager"
  7. WebsocketLoadBalancer = require "./WebsocketLoadBalancer"
  8. Utils = require "./Utils"
  9. module.exports = WebsocketController =
  10. # If the protocol version changes when the client reconnects,
  11. # it will force a full refresh of the page. Useful for non-backwards
  12. # compatible protocol changes. Use only in extreme need.
  13. PROTOCOL_VERSION: 2
  14. joinProject: (client, user, project_id, callback = (error, project, privilegeLevel, protocolVersion) ->) ->
  15. user_id = user?._id
  16. logger.log {user_id, project_id, client_id: client.id}, "user joining project"
  17. metrics.inc "editor.join-project"
  18. WebApiManager.joinProject project_id, user_id, (error, project, privilegeLevel) ->
  19. return callback(error) if error?
  20. if !privilegeLevel or privilegeLevel == ""
  21. err = new Error("not authorized")
  22. logger.error {err, project_id, user_id, client_id: client.id}, "user is not authorized to join project"
  23. return callback(err)
  24. client.join project_id
  25. client.set("privilege_level", privilegeLevel)
  26. client.set("user_id", user_id)
  27. client.set("project_id", project_id)
  28. client.set("owner_id", project?.owner?._id)
  29. client.set("first_name", user?.first_name)
  30. client.set("last_name", user?.last_name)
  31. client.set("email", user?.email)
  32. client.set("connected_time", new Date())
  33. client.set("signup_date", user?.signUpDate)
  34. client.set("login_count", user?.loginCount)
  35. callback null, project, privilegeLevel, WebsocketController.PROTOCOL_VERSION
  36. logger.log {user_id, project_id, client_id: client.id}, "user joined project"
  37. # No need to block for setting the user as connected in the cursor tracking
  38. ConnectedUsersManager.updateUserPosition project_id, client.id, user, null, () ->
  39. # We want to flush a project if there are no more (local) connected clients
  40. # but we need to wait for the triggering client to disconnect. How long we wait
  41. # is determined by FLUSH_IF_EMPTY_DELAY.
  42. FLUSH_IF_EMPTY_DELAY: 500 #ms
  43. leaveProject: (io, client, callback = (error) ->) ->
  44. metrics.inc "editor.leave-project"
  45. Utils.getClientAttributes client, ["project_id", "user_id"], (error, {project_id, user_id}) ->
  46. return callback(error) if error?
  47. # bail out if the client had not managed to authenticate or join
  48. # the project. Prevents downstream errors in docupdater from
  49. # flushProjectToMongoAndDelete with null project_id.
  50. if not user_id?
  51. logger.log {client_id: client.id}, "client leaving, unknown user"
  52. return callback()
  53. if not project_id?
  54. logger.log {user_id: user_id, client_id: client.id}, "client leaving, not in project"
  55. return callback()
  56. logger.log {project_id, user_id, client_id: client.id}, "client leaving project"
  57. WebsocketLoadBalancer.emitToRoom project_id, "clientTracking.clientDisconnected", client.id
  58. # We can do this in the background
  59. ConnectedUsersManager.markUserAsDisconnected project_id, client.id, (err) ->
  60. if err?
  61. logger.error {err, project_id, user_id, client_id: client.id}, "error marking client as disconnected"
  62. setTimeout () ->
  63. remainingClients = io.sockets.clients(project_id)
  64. if remainingClients.length == 0
  65. # Flush project in the background
  66. DocumentUpdaterManager.flushProjectToMongoAndDelete project_id, (err) ->
  67. if err?
  68. logger.error {err, project_id, user_id, client_id: client.id}, "error flushing to doc updater after leaving project"
  69. callback()
  70. , WebsocketController.FLUSH_IF_EMPTY_DELAY
  71. joinDoc: (client, doc_id, fromVersion = -1, options, callback = (error, doclines, version, ops, ranges) ->) ->
  72. metrics.inc "editor.join-doc"
  73. Utils.getClientAttributes client, ["project_id", "user_id"], (error, {project_id, user_id}) ->
  74. return callback(error) if error?
  75. return callback(new Error("no project_id found on client")) if !project_id?
  76. logger.log {user_id, project_id, doc_id, fromVersion, client_id: client.id}, "client joining doc"
  77. AuthorizationManager.assertClientCanViewProject client, (error) ->
  78. return callback(error) if error?
  79. DocumentUpdaterManager.getDocument project_id, doc_id, fromVersion, (error, lines, version, ranges, ops) ->
  80. return callback(error) if error?
  81. # Encode any binary bits of data so it can go via WebSockets
  82. # See http://ecmanaut.blogspot.co.uk/2006/07/encoding-decoding-utf8-in-javascript.html
  83. encodeForWebsockets = (text) -> unescape(encodeURIComponent(text))
  84. escapedLines = []
  85. for line in lines
  86. try
  87. line = encodeForWebsockets(line)
  88. catch err
  89. logger.err {err, project_id, doc_id, fromVersion, line, client_id: client.id}, "error encoding line uri component"
  90. return callback(err)
  91. escapedLines.push line
  92. if options.encodeRanges
  93. try
  94. for comment in ranges?.comments or []
  95. comment.op.c = encodeForWebsockets(comment.op.c) if comment.op.c?
  96. for change in ranges?.changes or []
  97. change.op.i = encodeForWebsockets(change.op.i) if change.op.i?
  98. change.op.d = encodeForWebsockets(change.op.d) if change.op.d?
  99. catch err
  100. logger.err {err, project_id, doc_id, fromVersion, ranges, client_id: client.id}, "error encoding range uri component"
  101. return callback(err)
  102. AuthorizationManager.addAccessToDoc client, doc_id
  103. client.join(doc_id)
  104. callback null, escapedLines, version, ops, ranges
  105. logger.log {user_id, project_id, doc_id, fromVersion, client_id: client.id}, "client joined doc"
  106. leaveDoc: (client, doc_id, callback = (error) ->) ->
  107. metrics.inc "editor.leave-doc"
  108. Utils.getClientAttributes client, ["project_id", "user_id"], (error, {project_id, user_id}) ->
  109. logger.log {user_id, project_id, doc_id, client_id: client.id}, "client leaving doc"
  110. client.leave doc_id
  111. # we could remove permission when user leaves a doc, but because
  112. # the connection is per-project, we continue to allow access
  113. # after the initial joinDoc since we know they are already authorised.
  114. ## AuthorizationManager.removeAccessToDoc client, doc_id
  115. callback()
  116. updateClientPosition: (client, cursorData, callback = (error) ->) ->
  117. metrics.inc "editor.update-client-position", 0.1
  118. Utils.getClientAttributes client, [
  119. "project_id", "first_name", "last_name", "email", "user_id"
  120. ], (error, {project_id, first_name, last_name, email, user_id}) ->
  121. return callback(error) if error?
  122. logger.log {user_id, project_id, client_id: client.id, cursorData: cursorData}, "updating client position"
  123. AuthorizationManager.assertClientCanViewProjectAndDoc client, cursorData.doc_id, (error) ->
  124. if error?
  125. logger.warn {err: error, client_id: client.id, project_id, user_id}, "silently ignoring unauthorized updateClientPosition. Client likely hasn't called joinProject yet."
  126. return callback()
  127. cursorData.id = client.id
  128. cursorData.user_id = user_id if user_id?
  129. cursorData.email = email if email?
  130. if first_name? and last_name?
  131. cursorData.name = first_name + " " + last_name
  132. ConnectedUsersManager.updateUserPosition(project_id, client.id, {
  133. first_name: first_name,
  134. last_name: last_name,
  135. email: email,
  136. _id: user_id
  137. }, {
  138. row: cursorData.row,
  139. column: cursorData.column,
  140. doc_id: cursorData.doc_id
  141. }, callback)
  142. else
  143. cursorData.name = "Anonymous"
  144. callback()
  145. WebsocketLoadBalancer.emitToRoom(project_id, "clientTracking.clientUpdated", cursorData)
  146. getConnectedUsers: (client, callback = (error, users) ->) ->
  147. metrics.inc "editor.get-connected-users"
  148. Utils.getClientAttributes client, ["project_id", "user_id"], (error, {project_id, user_id}) ->
  149. return callback(error) if error?
  150. return callback(new Error("no project_id found on client")) if !project_id?
  151. logger.log {user_id, project_id, client_id: client.id}, "getting connected users"
  152. AuthorizationManager.assertClientCanViewProject client, (error) ->
  153. return callback(error) if error?
  154. ConnectedUsersManager.getConnectedUsers project_id, (error, users) ->
  155. return callback(error) if error?
  156. callback null, users
  157. logger.log {user_id, project_id, client_id: client.id}, "got connected users"
  158. applyOtUpdate: (client, doc_id, update, callback = (error) ->) ->
  159. Utils.getClientAttributes client, ["user_id", "project_id"], (error, {user_id, project_id}) ->
  160. return callback(error) if error?
  161. return callback(new Error("no project_id found on client")) if !project_id?
  162. WebsocketController._assertClientCanApplyUpdate client, doc_id, update, (error) ->
  163. if error?
  164. logger.error {err: error, doc_id, client_id: client.id, version: update.v}, "client is not authorized to make update"
  165. setTimeout () ->
  166. # Disconnect, but give the client the chance to receive the error
  167. client.disconnect()
  168. , 100
  169. return callback(error)
  170. update.meta ||= {}
  171. update.meta.source = client.id
  172. update.meta.user_id = user_id
  173. metrics.inc "editor.doc-update", 0.3
  174. metrics.set "editor.active-projects", project_id, 0.3
  175. metrics.set "editor.active-users", user_id, 0.3
  176. logger.log {user_id, doc_id, project_id, client_id: client.id, version: update.v}, "sending update to doc updater"
  177. DocumentUpdaterManager.queueChange project_id, doc_id, update, (error) ->
  178. if error?
  179. logger.error {err: error, project_id, doc_id, client_id: client.id, version: update.v}, "document was not available for update"
  180. client.disconnect()
  181. callback(error)
  182. _assertClientCanApplyUpdate: (client, doc_id, update, callback) ->
  183. AuthorizationManager.assertClientCanEditProjectAndDoc client, doc_id, (error) ->
  184. if error?
  185. if error.message == "not authorized" and WebsocketController._isCommentUpdate(update)
  186. # This might be a comment op, which we only need read-only priveleges for
  187. AuthorizationManager.assertClientCanViewProjectAndDoc client, doc_id, callback
  188. else
  189. return callback(error)
  190. else
  191. return callback(null)
  192. _isCommentUpdate: (update) ->
  193. for op in update.op
  194. if !op.c?
  195. return false
  196. return true