You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

302 lines
8.1 KiB

  1. // ===========================================
  2. // REQUARKS WIKI - Background Agent
  3. // 1.0.0
  4. // Licensed under AGPLv3
  5. // ===========================================
  6. global.ROOTPATH = __dirname;
  7. // ----------------------------------------
  8. // Load Winston
  9. // ----------------------------------------
  10. var _isDebug = process.env.NODE_ENV === 'development';
  11. global.winston = require('winston');
  12. winston.remove(winston.transports.Console)
  13. winston.add(winston.transports.Console, {
  14. level: (_isDebug) ? 'info' : 'warn',
  15. prettyPrint: true,
  16. colorize: true,
  17. silent: false,
  18. timestamp: true
  19. });
  20. // ----------------------------------------
  21. // Fetch internal handshake key
  22. // ----------------------------------------
  23. if(!process.argv[2] || process.argv[2].length !== 40) {
  24. winston.error('[WS] Illegal process start. Missing handshake key.');
  25. process.exit(1);
  26. }
  27. global.WSInternalKey = process.argv[2];
  28. // ----------------------------------------
  29. // Load modules
  30. // ----------------------------------------
  31. winston.info('[AGENT] Background Agent is initializing...');
  32. var appconfig = require('./models/config')('./config.yml');
  33. let lcdata = require('./models/localdata').init(appconfig, 'agent');
  34. global.git = require('./models/git').init(appconfig);
  35. global.entries = require('./models/entries').init(appconfig);
  36. global.mark = require('./models/markdown');
  37. var _ = require('lodash');
  38. var moment = require('moment');
  39. var Promise = require('bluebird');
  40. var fs = Promise.promisifyAll(require("fs-extra"));
  41. var path = require('path');
  42. var cron = require('cron').CronJob;
  43. var readChunk = require('read-chunk');
  44. var fileType = require('file-type');
  45. global.ws = require('socket.io-client')('http://localhost:' + appconfig.wsPort, { reconnectionAttempts: 10 });
  46. const mimeImgTypes = ['image/png', 'image/jpg']
  47. // ----------------------------------------
  48. // Start Cron
  49. // ----------------------------------------
  50. var jobIsBusy = false;
  51. var job = new cron({
  52. cronTime: '0 */5 * * * *',
  53. onTick: () => {
  54. // Make sure we don't start two concurrent jobs
  55. if(jobIsBusy) {
  56. winston.warn('[AGENT] Previous job has not completed gracefully or is still running! Skipping for now. (This is not normal, you should investigate)');
  57. return;
  58. }
  59. winston.info('[AGENT] Running all jobs...');
  60. jobIsBusy = true;
  61. // Prepare async job collector
  62. let jobs = [];
  63. let repoPath = path.resolve(ROOTPATH, appconfig.datadir.repo);
  64. let dataPath = path.resolve(ROOTPATH, appconfig.datadir.db);
  65. let uploadsPath = path.join(repoPath, 'uploads');
  66. // ----------------------------------------
  67. // Compile Jobs
  68. // ----------------------------------------
  69. //*****************************************
  70. //-> Resync with Git remote
  71. //*****************************************
  72. jobs.push(git.onReady.then(() => {
  73. return git.resync().then(() => {
  74. //-> Stream all documents
  75. let cacheJobs = [];
  76. let jobCbStreamDocs_resolve = null,
  77. jobCbStreamDocs = new Promise((resolve, reject) => {
  78. jobCbStreamDocs_resolve = resolve;
  79. });
  80. fs.walk(repoPath).on('data', function (item) {
  81. if(path.extname(item.path) === '.md') {
  82. let entryPath = entries.parsePath(entries.getEntryPathFromFullPath(item.path));
  83. let cachePath = entries.getCachePath(entryPath);
  84. //-> Purge outdated cache
  85. cacheJobs.push(
  86. fs.statAsync(cachePath).then((st) => {
  87. return moment(st.mtime).isBefore(item.stats.mtime) ? 'expired' : 'active';
  88. }).catch((err) => {
  89. return (err.code !== 'EEXIST') ? err : 'new';
  90. }).then((fileStatus) => {
  91. //-> Delete expired cache file
  92. if(fileStatus === 'expired') {
  93. return fs.unlinkAsync(cachePath).return(fileStatus);
  94. }
  95. return fileStatus;
  96. }).then((fileStatus) => {
  97. //-> Update cache and search index
  98. if(fileStatus !== 'active') {
  99. return entries.updateCache(entryPath);
  100. }
  101. return true;
  102. })
  103. );
  104. }
  105. }).on('end', () => {
  106. jobCbStreamDocs_resolve(Promise.all(cacheJobs));
  107. });
  108. return jobCbStreamDocs;
  109. });
  110. }));
  111. //*****************************************
  112. //-> Refresh uploads data
  113. //*****************************************
  114. jobs.push(fs.readdirAsync(uploadsPath).then((ls) => {
  115. return Promise.map(ls, (f) => {
  116. return fs.statAsync(path.join(uploadsPath, f)).then((s) => { return { filename: f, stat: s }; });
  117. }).filter((s) => { return s.stat.isDirectory(); }).then((arrDirs) => {
  118. let folderNames = _.map(arrDirs, 'filename');
  119. folderNames.unshift('');
  120. ws.emit('uploadsSetFolders', {
  121. auth: WSInternalKey,
  122. content: folderNames
  123. });
  124. let allFiles = [];
  125. // Travel each directory
  126. return Promise.map(folderNames, (fldName) => {
  127. let fldPath = path.join(uploadsPath, fldName);
  128. return fs.readdirAsync(fldPath).then((fList) => {
  129. return Promise.map(fList, (f) => {
  130. let fPath = path.join(fldPath, f);
  131. let fPathObj = path.parse(fPath);
  132. return fs.statAsync(fPath)
  133. .then((s) => {
  134. if(!s.isFile()) { return false; }
  135. // Get MIME info
  136. let mimeInfo = fileType(readChunk.sync(fPath, 0, 262));
  137. // Images
  138. if(s.size < 3145728) { // ignore files larger than 3MB
  139. if(_.includes(['image/png', 'image/jpeg', 'image/gif', 'image/webp'], mimeInfo.mime)) {
  140. return lcdata.getImageMetadata(fPath).then((mData) => {
  141. let cacheThumbnailPath = path.parse(path.join(dataPath, 'thumbs', fldName, fPathObj.name + '.png'));
  142. let cacheThumbnailPathStr = path.format(cacheThumbnailPath);
  143. mData = _.pick(mData, ['format', 'width', 'height', 'density', 'hasAlpha', 'orientation']);
  144. mData.category = 'image';
  145. mData.mime = mimeInfo.mime;
  146. mData.folder = fldName;
  147. mData.filename = f;
  148. mData.basename = fPathObj.name;
  149. mData.filesize = s.size;
  150. mData.uploadedOn = moment().utc();
  151. allFiles.push(mData);
  152. // Generate thumbnail
  153. return fs.statAsync(cacheThumbnailPathStr).then((st) => {
  154. return st.isFile();
  155. }).catch((err) => {
  156. return false;
  157. }).then((thumbExists) => {
  158. return (thumbExists) ? true : fs.ensureDirAsync(cacheThumbnailPath.dir).then(() => {
  159. return lcdata.generateThumbnail(fPath, cacheThumbnailPathStr);
  160. });
  161. });
  162. })
  163. }
  164. }
  165. // Other Files
  166. allFiles.push({
  167. category: 'file',
  168. mime: mimeInfo.mime,
  169. folder: fldName,
  170. filename: f,
  171. basename: fPathObj.name,
  172. filesize: s.size,
  173. uploadedOn: moment().utc()
  174. });
  175. });
  176. }, {concurrency: 3});
  177. });
  178. }, {concurrency: 1}).finally(() => {
  179. ws.emit('uploadsSetFiles', {
  180. auth: WSInternalKey,
  181. content: allFiles
  182. });
  183. });
  184. return true;
  185. });
  186. }));
  187. // ----------------------------------------
  188. // Run
  189. // ----------------------------------------
  190. Promise.all(jobs).then(() => {
  191. winston.info('[AGENT] All jobs completed successfully! Going to sleep for now.');
  192. }).catch((err) => {
  193. winston.error('[AGENT] One or more jobs have failed: ', err);
  194. }).finally(() => {
  195. jobIsBusy = false;
  196. });
  197. },
  198. start: false,
  199. timeZone: 'UTC',
  200. runOnInit: true
  201. });
  202. // ----------------------------------------
  203. // Connect to local WebSocket server
  204. // ----------------------------------------
  205. ws.on('connect', function () {
  206. winston.info('[AGENT] Background Agent started successfully! [RUNNING]');
  207. job.start();
  208. });
  209. ws.on('connect_error', function () {
  210. winston.warn('[AGENT] Unable to connect to WebSocket server! Retrying...');
  211. });
  212. ws.on('reconnect_failed', function () {
  213. winston.error('[AGENT] Failed to reconnect to WebSocket server too many times! Stopping agent...');
  214. process.exit(1);
  215. });
  216. // ----------------------------------------
  217. // Shutdown gracefully
  218. // ----------------------------------------
  219. process.on('disconnect', () => {
  220. winston.warn('[AGENT] Lost connection to main server. Exiting...');
  221. job.stop();
  222. process.exit();
  223. });
  224. process.on('exit', () => {
  225. job.stop();
  226. });