fixAllFileUrls.js 7.2 KB

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