V1SubscriptionManager.coffee 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. UserGetter = require "../User/UserGetter"
  2. request = require "request"
  3. settings = require "settings-sharelatex"
  4. logger = require "logger-sharelatex"
  5. module.exports = V1SubscriptionManager =
  6. # Returned planCode = 'v1_pro' | 'v1_pro_plus' | 'v1_student' | 'v1_free' | null
  7. # For this to work, we need plans in settings with plan-codes:
  8. # - 'v1_pro'
  9. # - 'v1_pro_plus'
  10. # - 'v1_student'
  11. # - 'v1_free'
  12. getPlanCodeFromV1: (userId, callback=(err, planCode)->) ->
  13. logger.log {userId}, "[V1SubscriptionManager] fetching v1 plan for user"
  14. V1SubscriptionManager._v1Request userId, {
  15. method: 'GET',
  16. url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/plan_code"
  17. }, (error, body) ->
  18. return callback(error) if error?
  19. planName = body?.plan_name
  20. logger.log {userId, planName, body}, "[V1SubscriptionManager] fetched v1 plan for user"
  21. if planName in ['pro', 'pro_plus', 'student', 'free']
  22. planName = "v1_#{planName}"
  23. else
  24. # Throw away 'anonymous', etc as being equivalent to null
  25. planName = null
  26. return callback(null, planName)
  27. notifyV1OfFeaturesChange: (userId, callback = (error) ->) ->
  28. V1SubscriptionManager._v1Request userId, {
  29. method: 'POST',
  30. url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/sync"
  31. }, callback
  32. getSubscriptionsFromV1: (userId, callback=(err, subscriptions) ->) ->
  33. V1SubscriptionManager._v1Request userId, {
  34. method: 'GET',
  35. url: (v1Id) -> "/api/v1/sharelatex/users/#{v1Id}/subscriptions"
  36. }, callback
  37. _v1Request: (userId, options, callback=(err, body)->) ->
  38. if !settings?.apis?.v1
  39. return callback null, null
  40. UserGetter.getUser userId, {'overleaf.id': 1}, (err, user) ->
  41. return callback(err) if err?
  42. v1Id = user?.overleaf?.id
  43. if !v1Id?
  44. logger.log {userId}, "[V1SubscriptionManager] no v1 id found for user"
  45. return callback(null, null)
  46. request {
  47. baseUrl: settings.apis.v1.url
  48. url: options.url(v1Id)
  49. method: options.method
  50. auth:
  51. user: settings.apis.v1.user
  52. pass: settings.apis.v1.pass
  53. sendImmediately: true
  54. json: true,
  55. timeout: 5 * 1000
  56. }, (error, response, body) ->
  57. return callback(error) if error?
  58. if 200 <= response.statusCode < 300
  59. return callback null, body
  60. else
  61. return callback new Error("non-success code from v1: #{response.statusCode}")