localdata.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. "use strict";
  2. var path = require('path'),
  3. loki = require('lokijs'),
  4. Promise = require('bluebird'),
  5. fs = Promise.promisifyAll(require('fs-extra')),
  6. _ = require('lodash');
  7. var regFolderName = new RegExp("^[a-z0-9][a-z0-9\-]*[a-z0-9]$");
  8. /**
  9. * Local Data Storage
  10. *
  11. * @param {Object} appconfig The application configuration
  12. */
  13. module.exports = {
  14. _uploadsPath: './repo/uploads',
  15. _uploadsThumbsPath: './data/thumbs',
  16. _uploadsFolders: [],
  17. _uploadsDb: null,
  18. /**
  19. * Initialize Local Data Storage model
  20. *
  21. * @param {Object} appconfig The application config
  22. * @return {Object} Local Data Storage model instance
  23. */
  24. init(appconfig, mode = 'server') {
  25. let self = this;
  26. self._uploadsPath = path.resolve(ROOTPATH, appconfig.datadir.repo, 'uploads');
  27. self._uploadsThumbsPath = path.resolve(ROOTPATH, appconfig.datadir.db, 'thumbs');
  28. // Start in full or bare mode
  29. switch(mode) {
  30. case 'agent':
  31. //todo
  32. break;
  33. case 'server':
  34. self.createBaseDirectories(appconfig);
  35. break;
  36. case 'ws':
  37. self.initDb(appconfig);
  38. break;
  39. }
  40. return self;
  41. },
  42. /**
  43. * Initialize Uploads DB
  44. *
  45. * @param {Object} appconfig The application config
  46. * @return {boolean} Void
  47. */
  48. initDb(appconfig) {
  49. let self = this;
  50. let dbReadyResolve;
  51. let dbReady = new Promise((resolve, reject) => {
  52. dbReadyResolve = resolve;
  53. });
  54. // Initialize Loki.js
  55. let dbModel = {
  56. Store: new loki(path.join(appconfig.datadir.db, 'uploads.db'), {
  57. env: 'NODEJS',
  58. autosave: true,
  59. autosaveInterval: 15000
  60. }),
  61. onReady: dbReady
  62. };
  63. // Load Models
  64. dbModel.Store.loadDatabase({}, () => {
  65. dbModel.Files = dbModel.Store.getCollection('Files');
  66. if(!dbModel.Files) {
  67. dbModel.Files = dbModel.Store.addCollection('Files', {
  68. indices: ['category', 'folder']
  69. });
  70. }
  71. dbReadyResolve();
  72. });
  73. self._uploadsDb = dbModel;
  74. return true;
  75. },
  76. /**
  77. * Gets the thumbnails folder path.
  78. *
  79. * @return {String} The thumbs path.
  80. */
  81. getThumbsPath() {
  82. return this._uploadsThumbsPath;
  83. },
  84. /**
  85. * Creates a base directories (Synchronous).
  86. *
  87. * @param {Object} appconfig The application config
  88. * @return {Void} Void
  89. */
  90. createBaseDirectories(appconfig) {
  91. winston.info('[SERVER] Checking data directories...');
  92. try {
  93. fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.datadir.db));
  94. fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.datadir.db, './cache'));
  95. fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.datadir.db, './thumbs'));
  96. fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.datadir.repo));
  97. fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.datadir.repo, './uploads'));
  98. } catch (err) {
  99. winston.error(err);
  100. }
  101. winston.info('[SERVER] Data and Repository directories are OK.');
  102. return;
  103. },
  104. /**
  105. * Sets the uploads folders.
  106. *
  107. * @param {Array<String>} arrFolders The arr folders
  108. * @return {Void} Void
  109. */
  110. setUploadsFolders(arrFolders) {
  111. this._uploadsFolders = arrFolders;
  112. return;
  113. },
  114. /**
  115. * Gets the uploads folders.
  116. *
  117. * @return {Array<String>} The uploads folders.
  118. */
  119. getUploadsFolders() {
  120. return this._uploadsFolders;
  121. },
  122. /**
  123. * Creates an uploads folder.
  124. *
  125. * @param {String} folderName The folder name
  126. * @return {Promise} Promise of the operation
  127. */
  128. createUploadsFolder(folderName) {
  129. let self = this;
  130. folderName = _.kebabCase(_.trim(folderName));
  131. if(_.isEmpty(folderName) || !regFolderName.test(folderName)) {
  132. return Promise.resolve(self.getUploadsFolders());
  133. }
  134. return fs.ensureDirAsync(path.join(self._uploadsPath, folderName)).then(() => {
  135. if(!_.includes(self._uploadsFolders, folderName)) {
  136. self._uploadsFolders.push(folderName);
  137. self._uploadsFolders = _.sortBy(self._uploadsFolders);
  138. }
  139. return self.getUploadsFolders();
  140. });
  141. },
  142. /**
  143. * Sets the uploads files.
  144. *
  145. * @param {Array<Object>} arrFiles The uploads files
  146. * @return {Void} Void
  147. */
  148. setUploadsFiles(arrFiles) {
  149. let self = this;
  150. if(_.isArray(arrFiles) && arrFiles.length > 0) {
  151. self._uploadsDb.Files.clear();
  152. self._uploadsDb.Files.insert(arrFiles);
  153. self._uploadsDb.Files.ensureIndex('category', true);
  154. self._uploadsDb.Files.ensureIndex('folder', true);
  155. }
  156. return;
  157. },
  158. /**
  159. * Gets the uploads files.
  160. *
  161. * @param {String} cat Category type
  162. * @param {String} fld Folder
  163. * @return {Array<Object>} The files matching the query
  164. */
  165. getUploadsFiles(cat, fld) {
  166. return this._uploadsDb.Files.chain().find({
  167. '$and': [{ 'category' : cat },{ 'folder' : fld }]
  168. }).simplesort('filename').data();
  169. },
  170. /**
  171. * Generate thumbnail of image
  172. *
  173. * @param {String} sourcePath The source path
  174. * @return {Promise<Object>} Promise returning the resized image info
  175. */
  176. generateThumbnail(sourcePath, destPath) {
  177. let sharp = require('sharp');
  178. return sharp(sourcePath)
  179. .withoutEnlargement()
  180. .resize(150,150)
  181. .background('white')
  182. .embed()
  183. .flatten()
  184. .toFormat('png')
  185. .toFile(destPath);
  186. },
  187. /**
  188. * Gets the image metadata.
  189. *
  190. * @param {String} sourcePath The source path
  191. * @return {Object} The image metadata.
  192. */
  193. getImageMetadata(sourcePath) {
  194. let sharp = require('sharp');
  195. return sharp(sourcePath).metadata();
  196. }
  197. };