cleanup_dangling_user_stubs.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const { db } = require('../app/src/infrastructure/mongojs')
  2. const async = require('async')
  3. const minimist = require('minimist')
  4. const UserMapper = require('../modules/overleaf-integration/app/src/OverleafUsers/UserMapper')
  5. const argv = minimist(process.argv.slice(2))
  6. const commit = argv.commit !== undefined
  7. if (!commit) {
  8. console.log('Doing dry run without --commit')
  9. }
  10. db.userstubs.aggregate(
  11. [
  12. {
  13. $lookup: {
  14. localField: 'overleaf.id',
  15. from: 'users',
  16. foreignField: 'overleaf.id',
  17. as: 'users'
  18. }
  19. },
  20. {
  21. $project: {
  22. email: 1,
  23. overleaf: 1,
  24. _id: 1,
  25. 'users.email': 1,
  26. 'users.emails': 1,
  27. 'users.overleaf': 1,
  28. 'users._id': 1
  29. }
  30. },
  31. {
  32. $match: {
  33. users: { $exists: 1 },
  34. 'overleaf.id': { $exists: 1 }
  35. }
  36. }
  37. ],
  38. (err, stubs) => {
  39. if (err) {
  40. throw err
  41. }
  42. console.log('Found ' + stubs.length + ' dangling stubs')
  43. async.mapLimit(
  44. stubs,
  45. Number(argv.limit || '10'),
  46. (stub, callback) => {
  47. if (commit) {
  48. if (stub.users.length === 0) {
  49. console.log('Deleting stub without users:', stub._id)
  50. return db.userstubs.remove({ _id: stub._id }, callback)
  51. }
  52. if (stub.users.length > 1) {
  53. console.log('Found stub with multiple users:', stub)
  54. return callback()
  55. }
  56. console.log(
  57. 'Processing stub',
  58. stub._id,
  59. 'for user',
  60. stub.users[0]._id
  61. )
  62. UserMapper._updateUserStubReferences(
  63. stub.overleaf,
  64. stub._id,
  65. stub.users[0]._id,
  66. callback
  67. )
  68. } else {
  69. if (stub.users.length === 0) {
  70. console.log('Would delete stub without users:', stub._id)
  71. return callback()
  72. }
  73. if (stub.users.length > 1) {
  74. console.log('Found stub with multiple users:', stub)
  75. return callback()
  76. }
  77. console.log(
  78. 'Would call UserMapper._updateUserStubReferences with:',
  79. stub.overleaf,
  80. stub._id,
  81. stub.users[0]._id
  82. )
  83. callback()
  84. }
  85. },
  86. err => {
  87. if (err) {
  88. throw err
  89. }
  90. console.log('All done')
  91. process.exit(0)
  92. }
  93. )
  94. }
  95. )