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.

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