attachmentApi.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. import { Meteor } from 'meteor/meteor';
  2. import { WebApp } from 'meteor/webapp';
  3. import { ReactiveCache } from '/imports/reactiveCache';
  4. import { Attachments, fileStoreStrategyFactory } from '/models/attachments';
  5. import { moveToStorage } from '/models/lib/fileStoreStrategy';
  6. import { STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS, STORAGE_NAME_S3 } from '/models/lib/fileStoreStrategy';
  7. import AttachmentStorageSettings from '/models/attachmentStorageSettings';
  8. import fs from 'fs';
  9. import path from 'path';
  10. import { ObjectID } from 'bson';
  11. // Attachment API HTTP routes
  12. if (Meteor.isServer) {
  13. // Helper function to authenticate API requests
  14. function authenticateApiRequest(req) {
  15. const authHeader = req.headers.authorization;
  16. if (!authHeader || !authHeader.startsWith('Bearer ')) {
  17. throw new Meteor.Error('unauthorized', 'Missing or invalid authorization header');
  18. }
  19. const token = authHeader.substring(7);
  20. // Here you would validate the token and get the user ID
  21. // For now, we'll use a simple approach - in production, you'd want proper JWT validation
  22. const userId = token; // This should be replaced with proper token validation
  23. if (!userId) {
  24. throw new Meteor.Error('unauthorized', 'Invalid token');
  25. }
  26. return userId;
  27. }
  28. // Helper function to send JSON response
  29. function sendJsonResponse(res, statusCode, data) {
  30. res.writeHead(statusCode, { 'Content-Type': 'application/json' });
  31. res.end(JSON.stringify(data));
  32. }
  33. // Helper function to send error response
  34. function sendErrorResponse(res, statusCode, message) {
  35. sendJsonResponse(res, statusCode, { success: false, error: message });
  36. }
  37. // Upload attachment endpoint
  38. WebApp.connectHandlers.use('/api/attachment/upload', (req, res, next) => {
  39. if (req.method !== 'POST') {
  40. return next();
  41. }
  42. try {
  43. const userId = authenticateApiRequest(req);
  44. let body = '';
  45. req.on('data', chunk => {
  46. body += chunk.toString();
  47. });
  48. req.on('end', () => {
  49. try {
  50. const data = JSON.parse(body);
  51. const { boardId, swimlaneId, listId, cardId, fileData, fileName, fileType, storageBackend } = data;
  52. // Validate parameters
  53. if (!boardId || !swimlaneId || !listId || !cardId || !fileData || !fileName) {
  54. return sendErrorResponse(res, 400, 'Missing required parameters');
  55. }
  56. // Check if user has permission to modify the card
  57. const card = ReactiveCache.getCard(cardId);
  58. if (!card) {
  59. return sendErrorResponse(res, 404, 'Card not found');
  60. }
  61. const board = ReactiveCache.getBoard(boardId);
  62. if (!board) {
  63. return sendErrorResponse(res, 404, 'Board not found');
  64. }
  65. // Check permissions
  66. if (!board.isBoardMember(userId)) {
  67. return sendErrorResponse(res, 403, 'You do not have permission to modify this card');
  68. }
  69. // Check if board allows attachments
  70. if (!board.allowsAttachments) {
  71. return sendErrorResponse(res, 403, 'Attachments are not allowed on this board');
  72. }
  73. // Get default storage backend if not specified
  74. let targetStorage = storageBackend;
  75. if (!targetStorage) {
  76. try {
  77. const settings = AttachmentStorageSettings.findOne({});
  78. targetStorage = settings ? settings.getDefaultStorage() : STORAGE_NAME_FILESYSTEM;
  79. } catch (error) {
  80. targetStorage = STORAGE_NAME_FILESYSTEM;
  81. }
  82. }
  83. // Validate storage backend
  84. if (![STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS, STORAGE_NAME_S3].includes(targetStorage)) {
  85. return sendErrorResponse(res, 400, 'Invalid storage backend');
  86. }
  87. // Create file object from base64 data
  88. const fileBuffer = Buffer.from(fileData, 'base64');
  89. const file = new File([fileBuffer], fileName, { type: fileType || 'application/octet-stream' });
  90. // Create attachment metadata
  91. const fileId = new ObjectID().toString();
  92. const meta = {
  93. boardId: boardId,
  94. swimlaneId: swimlaneId,
  95. listId: listId,
  96. cardId: cardId,
  97. fileId: fileId,
  98. source: 'api',
  99. storageBackend: targetStorage
  100. };
  101. // Create attachment
  102. const uploader = Attachments.insert({
  103. file: file,
  104. meta: meta,
  105. isBase64: false,
  106. transport: 'http'
  107. });
  108. if (uploader) {
  109. // Move to target storage if not filesystem
  110. if (targetStorage !== STORAGE_NAME_FILESYSTEM) {
  111. Meteor.defer(() => {
  112. try {
  113. moveToStorage(uploader, targetStorage, fileStoreStrategyFactory);
  114. } catch (error) {
  115. console.error('Error moving attachment to target storage:', error);
  116. }
  117. });
  118. }
  119. sendJsonResponse(res, 200, {
  120. success: true,
  121. attachmentId: uploader._id,
  122. fileName: fileName,
  123. fileSize: fileBuffer.length,
  124. storageBackend: targetStorage,
  125. message: 'Attachment uploaded successfully'
  126. });
  127. } else {
  128. sendErrorResponse(res, 500, 'Failed to upload attachment');
  129. }
  130. } catch (error) {
  131. console.error('API attachment upload error:', error);
  132. sendErrorResponse(res, 500, error.message);
  133. }
  134. });
  135. } catch (error) {
  136. sendErrorResponse(res, 401, error.message);
  137. }
  138. });
  139. // Download attachment endpoint
  140. WebApp.connectHandlers.use('/api/attachment/download/([^/]+)', (req, res, next) => {
  141. if (req.method !== 'GET') {
  142. return next();
  143. }
  144. try {
  145. const userId = authenticateApiRequest(req);
  146. const attachmentId = req.params[0];
  147. // Get attachment
  148. const attachment = ReactiveCache.getAttachment(attachmentId);
  149. if (!attachment) {
  150. return sendErrorResponse(res, 404, 'Attachment not found');
  151. }
  152. // Check permissions
  153. const board = ReactiveCache.getBoard(attachment.meta.boardId);
  154. if (!board || !board.isBoardMember(userId)) {
  155. return sendErrorResponse(res, 403, 'You do not have permission to access this attachment');
  156. }
  157. // Get file strategy
  158. const strategy = fileStoreStrategyFactory.getFileStrategy(attachment, 'original');
  159. const readStream = strategy.getReadStream();
  160. if (!readStream) {
  161. return sendErrorResponse(res, 404, 'File not found in storage');
  162. }
  163. // Read file data
  164. const chunks = [];
  165. readStream.on('data', (chunk) => {
  166. chunks.push(chunk);
  167. });
  168. readStream.on('end', () => {
  169. const fileBuffer = Buffer.concat(chunks);
  170. const base64Data = fileBuffer.toString('base64');
  171. sendJsonResponse(res, 200, {
  172. success: true,
  173. attachmentId: attachmentId,
  174. fileName: attachment.name,
  175. fileSize: attachment.size,
  176. fileType: attachment.type,
  177. base64Data: base64Data,
  178. storageBackend: strategy.getStorageName()
  179. });
  180. });
  181. readStream.on('error', (error) => {
  182. console.error('Download error:', error);
  183. sendErrorResponse(res, 500, error.message);
  184. });
  185. } catch (error) {
  186. sendErrorResponse(res, 401, error.message);
  187. }
  188. });
  189. // List attachments endpoint
  190. WebApp.connectHandlers.use('/api/attachment/list/([^/]+)/([^/]+)/([^/]+)/([^/]+)', (req, res, next) => {
  191. if (req.method !== 'GET') {
  192. return next();
  193. }
  194. try {
  195. const userId = authenticateApiRequest(req);
  196. const boardId = req.params[0];
  197. const swimlaneId = req.params[1];
  198. const listId = req.params[2];
  199. const cardId = req.params[3];
  200. // Check permissions
  201. const board = ReactiveCache.getBoard(boardId);
  202. if (!board || !board.isBoardMember(userId)) {
  203. return sendErrorResponse(res, 403, 'You do not have permission to access this board');
  204. }
  205. let query = { 'meta.boardId': boardId };
  206. if (swimlaneId && swimlaneId !== 'null') {
  207. query['meta.swimlaneId'] = swimlaneId;
  208. }
  209. if (listId && listId !== 'null') {
  210. query['meta.listId'] = listId;
  211. }
  212. if (cardId && cardId !== 'null') {
  213. query['meta.cardId'] = cardId;
  214. }
  215. const attachments = ReactiveCache.getAttachments(query);
  216. const attachmentList = attachments.map(attachment => {
  217. const strategy = fileStoreStrategyFactory.getFileStrategy(attachment, 'original');
  218. return {
  219. attachmentId: attachment._id,
  220. fileName: attachment.name,
  221. fileSize: attachment.size,
  222. fileType: attachment.type,
  223. storageBackend: strategy.getStorageName(),
  224. boardId: attachment.meta.boardId,
  225. swimlaneId: attachment.meta.swimlaneId,
  226. listId: attachment.meta.listId,
  227. cardId: attachment.meta.cardId,
  228. createdAt: attachment.uploadedAt,
  229. isImage: attachment.isImage
  230. };
  231. });
  232. sendJsonResponse(res, 200, {
  233. success: true,
  234. attachments: attachmentList,
  235. count: attachmentList.length
  236. });
  237. } catch (error) {
  238. sendErrorResponse(res, 401, error.message);
  239. }
  240. });
  241. // Copy attachment endpoint
  242. WebApp.connectHandlers.use('/api/attachment/copy', (req, res, next) => {
  243. if (req.method !== 'POST') {
  244. return next();
  245. }
  246. try {
  247. const userId = authenticateApiRequest(req);
  248. let body = '';
  249. req.on('data', chunk => {
  250. body += chunk.toString();
  251. });
  252. req.on('end', () => {
  253. try {
  254. const data = JSON.parse(body);
  255. const { attachmentId, targetBoardId, targetSwimlaneId, targetListId, targetCardId } = data;
  256. // Get source attachment
  257. const sourceAttachment = ReactiveCache.getAttachment(attachmentId);
  258. if (!sourceAttachment) {
  259. return sendErrorResponse(res, 404, 'Source attachment not found');
  260. }
  261. // Check source permissions
  262. const sourceBoard = ReactiveCache.getBoard(sourceAttachment.meta.boardId);
  263. if (!sourceBoard || !sourceBoard.isBoardMember(userId)) {
  264. return sendErrorResponse(res, 403, 'You do not have permission to access the source attachment');
  265. }
  266. // Check target permissions
  267. const targetBoard = ReactiveCache.getBoard(targetBoardId);
  268. if (!targetBoard || !targetBoard.isBoardMember(userId)) {
  269. return sendErrorResponse(res, 403, 'You do not have permission to modify the target card');
  270. }
  271. // Check if target board allows attachments
  272. if (!targetBoard.allowsAttachments) {
  273. return sendErrorResponse(res, 403, 'Attachments are not allowed on the target board');
  274. }
  275. // Get source file strategy
  276. const sourceStrategy = fileStoreStrategyFactory.getFileStrategy(sourceAttachment, 'original');
  277. const readStream = sourceStrategy.getReadStream();
  278. if (!readStream) {
  279. return sendErrorResponse(res, 404, 'Source file not found in storage');
  280. }
  281. // Read source file data
  282. const chunks = [];
  283. readStream.on('data', (chunk) => {
  284. chunks.push(chunk);
  285. });
  286. readStream.on('end', () => {
  287. try {
  288. const fileBuffer = Buffer.concat(chunks);
  289. const file = new File([fileBuffer], sourceAttachment.name, { type: sourceAttachment.type });
  290. // Create new attachment metadata
  291. const fileId = new ObjectID().toString();
  292. const meta = {
  293. boardId: targetBoardId,
  294. swimlaneId: targetSwimlaneId,
  295. listId: targetListId,
  296. cardId: targetCardId,
  297. fileId: fileId,
  298. source: 'api-copy',
  299. copyFrom: attachmentId,
  300. copyStorage: sourceStrategy.getStorageName()
  301. };
  302. // Create new attachment
  303. const uploader = Attachments.insert({
  304. file: file,
  305. meta: meta,
  306. isBase64: false,
  307. transport: 'http'
  308. });
  309. if (uploader) {
  310. sendJsonResponse(res, 200, {
  311. success: true,
  312. sourceAttachmentId: attachmentId,
  313. newAttachmentId: uploader._id,
  314. fileName: sourceAttachment.name,
  315. fileSize: sourceAttachment.size,
  316. message: 'Attachment copied successfully'
  317. });
  318. } else {
  319. sendErrorResponse(res, 500, 'Failed to copy attachment');
  320. }
  321. } catch (error) {
  322. sendErrorResponse(res, 500, error.message);
  323. }
  324. });
  325. readStream.on('error', (error) => {
  326. sendErrorResponse(res, 500, error.message);
  327. });
  328. } catch (error) {
  329. console.error('API attachment copy error:', error);
  330. sendErrorResponse(res, 500, error.message);
  331. }
  332. });
  333. } catch (error) {
  334. sendErrorResponse(res, 401, error.message);
  335. }
  336. });
  337. // Move attachment endpoint
  338. WebApp.connectHandlers.use('/api/attachment/move', (req, res, next) => {
  339. if (req.method !== 'POST') {
  340. return next();
  341. }
  342. try {
  343. const userId = authenticateApiRequest(req);
  344. let body = '';
  345. req.on('data', chunk => {
  346. body += chunk.toString();
  347. });
  348. req.on('end', () => {
  349. try {
  350. const data = JSON.parse(body);
  351. const { attachmentId, targetBoardId, targetSwimlaneId, targetListId, targetCardId } = data;
  352. // Get source attachment
  353. const sourceAttachment = ReactiveCache.getAttachment(attachmentId);
  354. if (!sourceAttachment) {
  355. return sendErrorResponse(res, 404, 'Source attachment not found');
  356. }
  357. // Check source permissions
  358. const sourceBoard = ReactiveCache.getBoard(sourceAttachment.meta.boardId);
  359. if (!sourceBoard || !sourceBoard.isBoardMember(userId)) {
  360. return sendErrorResponse(res, 403, 'You do not have permission to access the source attachment');
  361. }
  362. // Check target permissions
  363. const targetBoard = ReactiveCache.getBoard(targetBoardId);
  364. if (!targetBoard || !targetBoard.isBoardMember(userId)) {
  365. return sendErrorResponse(res, 403, 'You do not have permission to modify the target card');
  366. }
  367. // Check if target board allows attachments
  368. if (!targetBoard.allowsAttachments) {
  369. return sendErrorResponse(res, 403, 'Attachments are not allowed on the target board');
  370. }
  371. // Update attachment metadata
  372. Attachments.update(attachmentId, {
  373. $set: {
  374. 'meta.boardId': targetBoardId,
  375. 'meta.swimlaneId': targetSwimlaneId,
  376. 'meta.listId': targetListId,
  377. 'meta.cardId': targetCardId,
  378. 'meta.source': 'api-move',
  379. 'meta.movedAt': new Date()
  380. }
  381. });
  382. sendJsonResponse(res, 200, {
  383. success: true,
  384. attachmentId: attachmentId,
  385. fileName: sourceAttachment.name,
  386. fileSize: sourceAttachment.size,
  387. sourceBoardId: sourceAttachment.meta.boardId,
  388. targetBoardId: targetBoardId,
  389. message: 'Attachment moved successfully'
  390. });
  391. } catch (error) {
  392. console.error('API attachment move error:', error);
  393. sendErrorResponse(res, 500, error.message);
  394. }
  395. });
  396. } catch (error) {
  397. sendErrorResponse(res, 401, error.message);
  398. }
  399. });
  400. // Delete attachment endpoint
  401. WebApp.connectHandlers.use('/api/attachment/delete/([^/]+)', (req, res, next) => {
  402. if (req.method !== 'DELETE') {
  403. return next();
  404. }
  405. try {
  406. const userId = authenticateApiRequest(req);
  407. const attachmentId = req.params[0];
  408. // Get attachment
  409. const attachment = ReactiveCache.getAttachment(attachmentId);
  410. if (!attachment) {
  411. return sendErrorResponse(res, 404, 'Attachment not found');
  412. }
  413. // Check permissions
  414. const board = ReactiveCache.getBoard(attachment.meta.boardId);
  415. if (!board || !board.isBoardMember(userId)) {
  416. return sendErrorResponse(res, 403, 'You do not have permission to delete this attachment');
  417. }
  418. // Delete attachment
  419. Attachments.remove(attachmentId);
  420. sendJsonResponse(res, 200, {
  421. success: true,
  422. attachmentId: attachmentId,
  423. fileName: attachment.name,
  424. message: 'Attachment deleted successfully'
  425. });
  426. } catch (error) {
  427. sendErrorResponse(res, 401, error.message);
  428. }
  429. });
  430. // Get attachment info endpoint
  431. WebApp.connectHandlers.use('/api/attachment/info/([^/]+)', (req, res, next) => {
  432. if (req.method !== 'GET') {
  433. return next();
  434. }
  435. try {
  436. const userId = authenticateApiRequest(req);
  437. const attachmentId = req.params[0];
  438. // Get attachment
  439. const attachment = ReactiveCache.getAttachment(attachmentId);
  440. if (!attachment) {
  441. return sendErrorResponse(res, 404, 'Attachment not found');
  442. }
  443. // Check permissions
  444. const board = ReactiveCache.getBoard(attachment.meta.boardId);
  445. if (!board || !board.isBoardMember(userId)) {
  446. return sendErrorResponse(res, 403, 'You do not have permission to access this attachment');
  447. }
  448. const strategy = fileStoreStrategyFactory.getFileStrategy(attachment, 'original');
  449. sendJsonResponse(res, 200, {
  450. success: true,
  451. attachmentId: attachment._id,
  452. fileName: attachment.name,
  453. fileSize: attachment.size,
  454. fileType: attachment.type,
  455. storageBackend: strategy.getStorageName(),
  456. boardId: attachment.meta.boardId,
  457. swimlaneId: attachment.meta.swimlaneId,
  458. listId: attachment.meta.listId,
  459. cardId: attachment.meta.cardId,
  460. createdAt: attachment.uploadedAt,
  461. isImage: attachment.isImage,
  462. versions: Object.keys(attachment.versions).map(versionName => ({
  463. versionName: versionName,
  464. storage: attachment.versions[versionName].storage,
  465. size: attachment.versions[versionName].size,
  466. type: attachment.versions[versionName].type
  467. }))
  468. });
  469. } catch (error) {
  470. sendErrorResponse(res, 401, error.message);
  471. }
  472. });
  473. }