fixAllFileUrls.js 7.6 KB

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