agent.js 8.1 KB

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