avatars.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { Meteor } from 'meteor/meteor';
  2. import { FilesCollection } from 'meteor/ostrio:files';
  3. import fs from 'fs';
  4. import path from 'path';
  5. import { createBucket } from './lib/grid/createBucket';
  6. import { createOnAfterUpload } from './lib/fsHooks/createOnAfterUpload';
  7. import { createInterceptDownload } from './lib/fsHooks/createInterceptDownload';
  8. import { createOnAfterRemove } from './lib/fsHooks/createOnAfterRemove';
  9. let avatarsBucket;
  10. if (Meteor.isServer) {
  11. avatarsBucket = createBucket('avatars');
  12. }
  13. Avatars = new FilesCollection({
  14. debug: false, // Change to `true` for debugging
  15. collectionName: 'avatars',
  16. allowClientCode: true,
  17. storagePath() {
  18. if (process.env.WRITABLE_PATH) {
  19. return path.join(process.env.WRITABLE_PATH, 'uploads', 'avatars');
  20. }
  21. return path.normalize(`assets/app/uploads/${this.collectionName}`);;
  22. },
  23. onBeforeUpload(file) {
  24. if (file.size <= 72000 && file.type.startsWith('image/')) {
  25. return true;
  26. }
  27. return 'avatar-too-big';
  28. },
  29. onAfterUpload: createOnAfterUpload(avatarsBucket),
  30. interceptDownload: createInterceptDownload(avatarsBucket),
  31. onAfterRemove: createOnAfterRemove(avatarsBucket),
  32. });
  33. function isOwner(userId, doc) {
  34. return userId && userId === doc.userId;
  35. }
  36. if (Meteor.isServer) {
  37. Avatars.allow({
  38. insert: isOwner,
  39. update: isOwner,
  40. remove: isOwner,
  41. fetch: ['userId'],
  42. });
  43. Meteor.startup(() => {
  44. const storagePath = Avatars.storagePath();
  45. if (!fs.existsSync(storagePath)) {
  46. console.log("create storagePath because it doesn't exist: " + storagePath);
  47. fs.mkdirSync(storagePath, { recursive: true });
  48. }
  49. });
  50. }
  51. export default Avatars;