fixAllFileUrls.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /**
  2. * Fix All File URLs Migration
  3. * Ensures all attachment and avatar URLs are universal and work regardless of ROOT_URL and PORT settings
  4. */
  5. import { Meteor } from 'meteor/meteor';
  6. import { check } from 'meteor/check';
  7. import { ReactiveCache } from '/imports/reactiveCache';
  8. import Boards from '/models/boards';
  9. import Users from '/models/users';
  10. import Attachments from '/models/attachments';
  11. import Avatars from '/models/avatars';
  12. import Cards from '/models/cards';
  13. import { generateUniversalAttachmentUrl, generateUniversalAvatarUrl, cleanFileUrl, extractFileIdFromUrl, isUniversalFileUrl } from '/models/lib/universalUrlGenerator';
  14. class FixAllFileUrlsMigration {
  15. constructor() {
  16. this.name = 'fixAllFileUrls';
  17. this.version = 1;
  18. }
  19. /**
  20. * Check if migration is needed for a board
  21. */
  22. needsMigration(boardId) {
  23. // Get all users who are members of this board
  24. const board = ReactiveCache.getBoard(boardId);
  25. if (!board || !board.members) {
  26. return false;
  27. }
  28. const memberIds = board.members.map(m => m.userId);
  29. // Check for problematic avatar URLs for board members
  30. const users = ReactiveCache.getUsers({ _id: { $in: memberIds } });
  31. for (const user of users) {
  32. if (user.profile && user.profile.avatarUrl) {
  33. const avatarUrl = user.profile.avatarUrl;
  34. if (this.hasProblematicUrl(avatarUrl)) {
  35. return true;
  36. }
  37. }
  38. }
  39. // Check for problematic attachment URLs on this board
  40. const cards = ReactiveCache.getCards({ boardId });
  41. const cardIds = cards.map(c => c._id);
  42. const attachments = ReactiveCache.getAttachments({ cardId: { $in: cardIds } });
  43. for (const attachment of attachments) {
  44. if (attachment.url && this.hasProblematicUrl(attachment.url)) {
  45. return true;
  46. }
  47. }
  48. return false;
  49. }
  50. /**
  51. * Check if a URL has problematic patterns
  52. */
  53. hasProblematicUrl(url) {
  54. if (!url) return false;
  55. // Check for auth parameters
  56. if (url.includes('auth=false') || url.includes('brokenIsFine=true')) {
  57. return true;
  58. }
  59. // Check for absolute URLs with domains
  60. if (url.startsWith('http://') || url.startsWith('https://')) {
  61. return true;
  62. }
  63. // Check for ROOT_URL dependencies
  64. if (Meteor.isServer && process.env.ROOT_URL) {
  65. try {
  66. const rootUrl = new URL(process.env.ROOT_URL);
  67. if (rootUrl.pathname && rootUrl.pathname !== '/' && url.includes(rootUrl.pathname)) {
  68. return true;
  69. }
  70. } catch (e) {
  71. // Ignore URL parsing errors
  72. }
  73. }
  74. // Check for non-universal file URLs
  75. if (url.includes('/cfs/files/') && !isUniversalFileUrl(url, 'attachment') && !isUniversalFileUrl(url, 'avatar')) {
  76. return true;
  77. }
  78. return false;
  79. }
  80. /**
  81. * Execute the migration for a board
  82. */
  83. async execute(boardId) {
  84. let filesFixed = 0;
  85. let errors = [];
  86. console.log(`Starting universal file URL migration for board ${boardId}...`);
  87. try {
  88. // Fix avatar URLs for board members
  89. const avatarFixed = await this.fixAvatarUrls(boardId);
  90. filesFixed += avatarFixed;
  91. // Fix attachment URLs for board cards
  92. const attachmentFixed = await this.fixAttachmentUrls(boardId);
  93. filesFixed += attachmentFixed;
  94. // Fix card attachment references
  95. const cardFixed = await this.fixCardAttachmentUrls(boardId);
  96. filesFixed += cardFixed;
  97. } catch (error) {
  98. console.error('Error during file URL migration for board', boardId, ':', error);
  99. errors.push(error.message);
  100. }
  101. console.log(`Universal file URL migration completed for board ${boardId}. Fixed ${filesFixed} file URLs.`);
  102. return {
  103. success: errors.length === 0,
  104. filesFixed,
  105. errors,
  106. changes: [`Fixed ${filesFixed} file URLs for this board`]
  107. };
  108. }
  109. /**
  110. * Fix avatar URLs in user profiles for board members
  111. */
  112. async fixAvatarUrls(boardId) {
  113. const board = ReactiveCache.getBoard(boardId);
  114. if (!board || !board.members) {
  115. return 0;
  116. }
  117. const memberIds = board.members.map(m => m.userId);
  118. const users = ReactiveCache.getUsers({ _id: { $in: memberIds } });
  119. let avatarsFixed = 0;
  120. for (const user of users) {
  121. if (user.profile && user.profile.avatarUrl) {
  122. const avatarUrl = user.profile.avatarUrl;
  123. if (this.hasProblematicUrl(avatarUrl)) {
  124. try {
  125. // Extract file ID from URL
  126. const fileId = extractFileIdFromUrl(avatarUrl, 'avatar');
  127. let cleanUrl;
  128. if (fileId) {
  129. // Generate universal URL
  130. cleanUrl = generateUniversalAvatarUrl(fileId);
  131. } else {
  132. // Clean existing URL
  133. cleanUrl = cleanFileUrl(avatarUrl, 'avatar');
  134. }
  135. if (cleanUrl && cleanUrl !== avatarUrl) {
  136. // Update user's avatar URL
  137. Users.update(user._id, {
  138. $set: {
  139. 'profile.avatarUrl': cleanUrl,
  140. modifiedAt: new Date()
  141. }
  142. });
  143. avatarsFixed++;
  144. if (process.env.DEBUG === 'true') {
  145. console.log(`Fixed avatar URL for user ${user.username}: ${avatarUrl} -> ${cleanUrl}`);
  146. }
  147. }
  148. } catch (error) {
  149. console.error(`Error fixing avatar URL for user ${user.username}:`, error);
  150. }
  151. }
  152. }
  153. }
  154. return avatarsFixed;
  155. }
  156. /**
  157. * Fix attachment URLs in attachment records for this board
  158. */
  159. async fixAttachmentUrls(boardId) {
  160. const cards = ReactiveCache.getCards({ boardId });
  161. const cardIds = cards.map(c => c._id);
  162. const attachments = ReactiveCache.getAttachments({ cardId: { $in: cardIds } });
  163. let attachmentsFixed = 0;
  164. for (const attachment of attachments) {
  165. // Check if attachment has URL field that needs fixing
  166. if (attachment.url && this.hasProblematicUrl(attachment.url)) {
  167. try {
  168. const fileId = attachment._id;
  169. const cleanUrl = generateUniversalAttachmentUrl(fileId);
  170. if (cleanUrl && cleanUrl !== attachment.url) {
  171. // Update attachment URL
  172. Attachments.update(attachment._id, {
  173. $set: {
  174. url: cleanUrl,
  175. modifiedAt: new Date()
  176. }
  177. });
  178. attachmentsFixed++;
  179. if (process.env.DEBUG === 'true') {
  180. console.log(`Fixed attachment URL: ${attachment.url} -> ${cleanUrl}`);
  181. }
  182. }
  183. } catch (error) {
  184. console.error(`Error fixing attachment URL for ${attachment._id}:`, error);
  185. }
  186. }
  187. }
  188. return attachmentsFixed;
  189. }
  190. /**
  191. * Fix attachment URLs in the Attachments collection for this board
  192. */
  193. async fixCardAttachmentUrls(boardId) {
  194. const cards = ReactiveCache.getCards({ boardId });
  195. const cardIds = cards.map(c => c._id);
  196. const attachments = ReactiveCache.getAttachments({ cardId: { $in: cardIds } });
  197. let attachmentsFixed = 0;
  198. for (const attachment of attachments) {
  199. if (attachment.url && this.hasProblematicUrl(attachment.url)) {
  200. try {
  201. const fileId = attachment._id || extractFileIdFromUrl(attachment.url, 'attachment');
  202. const cleanUrl = fileId ? generateUniversalAttachmentUrl(fileId) : cleanFileUrl(attachment.url, 'attachment');
  203. if (cleanUrl && cleanUrl !== attachment.url) {
  204. // Update attachment with fixed URL
  205. Attachments.update(attachment._id, {
  206. $set: {
  207. url: cleanUrl,
  208. modifiedAt: new Date()
  209. }
  210. });
  211. attachmentsFixed++;
  212. if (process.env.DEBUG === 'true') {
  213. console.log(`Fixed attachment URL ${attachment._id}`);
  214. }
  215. }
  216. } catch (error) {
  217. console.error(`Error fixing attachment URL:`, error);
  218. }
  219. }
  220. }
  221. return attachmentsFixed;
  222. }
  223. }
  224. // Export singleton instance
  225. export const fixAllFileUrlsMigration = new FixAllFileUrlsMigration();
  226. // Meteor methods
  227. Meteor.methods({
  228. 'fixAllFileUrls.execute'(boardId) {
  229. check(boardId, String);
  230. if (!this.userId) {
  231. throw new Meteor.Error('not-authorized', 'You must be logged in');
  232. }
  233. // Check if user is board admin
  234. const board = ReactiveCache.getBoard(boardId);
  235. if (!board) {
  236. throw new Meteor.Error('board-not-found', 'Board not found');
  237. }
  238. const user = ReactiveCache.getUser(this.userId);
  239. if (!user) {
  240. throw new Meteor.Error('user-not-found', 'User not found');
  241. }
  242. // Only board admins can run migrations
  243. const isBoardAdmin = board.members && board.members.some(
  244. member => member.userId === this.userId && member.isAdmin
  245. );
  246. if (!isBoardAdmin && !user.isAdmin) {
  247. throw new Meteor.Error('not-authorized', 'Only board administrators can run migrations');
  248. }
  249. return fixAllFileUrlsMigration.execute(boardId);
  250. },
  251. 'fixAllFileUrls.needsMigration'(boardId) {
  252. check(boardId, String);
  253. if (!this.userId) {
  254. throw new Meteor.Error('not-authorized', 'You must be logged in');
  255. }
  256. return fixAllFileUrlsMigration.needsMigration(boardId);
  257. }
  258. });