WebsocketController.coffee 11 KB

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