index.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. const http = require('http');
  2. const pages = require('./oauth.js');
  3. const dashboard = require('./guilds.js');
  4. const {db, settingsData} = require('./util.js');
  5. global.isDebug = ( process.argv[2] === 'debug' );
  6. const posts = {
  7. settings: require('./settings.js').post,
  8. verification: require('./verification.js').post,
  9. rcscript: require('./rcscript.js').post
  10. };
  11. const fs = require('fs');
  12. const path = require('path');
  13. const files = new Map([
  14. ...fs.readdirSync( './dashboard/src' ).map( file => {
  15. return [`/src/${file}`, `./dashboard/src/${file}`];
  16. } ),
  17. ...fs.readdirSync( './i18n/widgets' ).map( file => {
  18. return [`/src/widgets/${file}`, `./i18n/widgets/${file}`];
  19. } ),
  20. ...fs.readdirSync( './RcGcDb/locale/widgets' ).map( file => {
  21. return [`/src/widgets/RcGcDb/${file}`, `./RcGcDb/locale/widgets/${file}`];
  22. } )
  23. ].map( ([file, filepath]) => {
  24. let contentType = 'text/html';
  25. switch ( path.extname(file) ) {
  26. case '.css':
  27. contentType = 'text/css';
  28. break;
  29. case '.js':
  30. contentType = 'text/javascript';
  31. break;
  32. case '.json':
  33. contentType = 'application/json';
  34. break;
  35. case '.svg':
  36. contentType = 'image/svg+xml';
  37. break;
  38. case '.png':
  39. contentType = 'image/png';
  40. break;
  41. case '.jpg':
  42. contentType = 'image/jpg';
  43. break;
  44. }
  45. return [file, {path: filepath, contentType}];
  46. } ));
  47. const server = http.createServer((req, res) => {
  48. if ( req.method === 'POST' && req.url.startsWith( '/guild/' ) ) {
  49. let args = req.url.split('/');
  50. let state = req.headers.cookie?.split('; ')?.filter( cookie => {
  51. return cookie.split('=')[0] === 'wikibot';
  52. } )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)?)"$/, '$1' ) )?.join();
  53. if ( args.length === 5 && ['settings', 'verification', 'rcscript'].includes( args[3] )
  54. && /^(?:default|new|\d+)$/.test(args[4]) && settingsData.has(state)
  55. && settingsData.get(state).guilds.isMember.has(args[2]) ) {
  56. if ( process.env.READONLY ) return save_response(`${req.url}?save=failed`);
  57. let body = '';
  58. req.on( 'data', chunk => {
  59. body += chunk.toString();
  60. } );
  61. req.on( 'error', () => {
  62. console.log( error );
  63. res.end('error');
  64. } );
  65. return req.on( 'end', () => {
  66. var settings = {};
  67. body.split('&').forEach( arg => {
  68. if ( arg ) {
  69. let setting = decodeURIComponent(arg.replace( /\+/g, ' ' )).split('=');
  70. if ( setting[0] && setting.slice(1).join('=').trim() ) {
  71. if ( settings[setting[0]] ) {
  72. settings[setting[0]] += '|' + setting.slice(1).join('=').trim();
  73. }
  74. else settings[setting[0]] = setting.slice(1).join('=').trim();
  75. }
  76. }
  77. } );
  78. if ( isDebug ) console.log( '- Dashboard:', req.url, settings, settingsData.get(state).user.id );
  79. return posts[args[3]](save_response, settingsData.get(state), args[2], args[4], settings);
  80. } );
  81. /**
  82. * @param {String} [resURL]
  83. * @param {String} [action]
  84. * @param {String[]} [actionArgs]
  85. */
  86. function save_response(resURL = '/', action, ...actionArgs) {
  87. return dashboard(res, state, new URL(resURL, process.env.dashboard), action, actionArgs);
  88. }
  89. }
  90. }
  91. if ( req.method !== 'GET' ) {
  92. let body = '<img width="400" src="https://http.cat/418"><br><strong>' + http.STATUS_CODES[418] + '</strong>';
  93. res.writeHead(418, {
  94. 'Content-Type': 'text/html',
  95. 'Content-Length': body.length
  96. });
  97. res.write( body );
  98. return res.end();
  99. }
  100. var reqURL = new URL(req.url, process.env.dashboard);
  101. if ( reqURL.pathname === '/favicon.ico' ) reqURL.pathname = '/src/icon.png';
  102. if ( files.has(reqURL.pathname) ) {
  103. let file = files.get(reqURL.pathname);
  104. res.writeHead(200, {'Content-Type': file.contentType});
  105. return fs.createReadStream(file.path).pipe(res);
  106. }
  107. res.setHeader('Content-Type', 'text/html');
  108. res.setHeader('Content-Language', ['en']);
  109. var lastGuild = req.headers?.cookie?.split('; ')?.filter( cookie => {
  110. return cookie.split('=')[0] === 'guild' && /^"\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?"$/.test(( cookie.split('=')[1] || '' ));
  111. } )?.map( cookie => cookie.replace( /^guild="(\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?)"$/, '$1' ) )?.join();
  112. if ( lastGuild ) res.setHeader('Set-Cookie', ['guild=""; HttpOnly; Path=/; Max-Age=0']);
  113. var state = req.headers.cookie?.split('; ')?.filter( cookie => {
  114. return cookie.split('=')[0] === 'wikibot' && /^"(\w*(?:-\d+)?)"$/.test(( cookie.split('=')[1] || '' ));
  115. } )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)?)"$/, '$1' ) )?.join();
  116. if ( reqURL.pathname === '/login' ) {
  117. let action = '';
  118. if ( reqURL.searchParams.get('action') === 'failed' ) action = 'loginfail';
  119. return pages.login(res, state, action);
  120. }
  121. if ( reqURL.pathname === '/logout' ) {
  122. settingsData.delete(state);
  123. res.setHeader('Set-Cookie', [
  124. ...( res.getHeader('Set-Cookie') || [] ),
  125. 'wikibot=""; HttpOnly; Path=/; Max-Age=0'
  126. ]);
  127. return pages.login(res, state, 'logout');
  128. }
  129. if ( !state ) {
  130. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  131. let pathGuild = reqURL.pathname.split('/').slice(2, 5).join('/');
  132. if ( /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(pathGuild) ) {
  133. res.setHeader('Set-Cookie', [`guild="${pathGuild}"; HttpOnly; Path=/`]);
  134. }
  135. }
  136. return pages.login(res, state, ( reqURL.pathname === '/' ? '' : 'unauthorized' ));
  137. }
  138. if ( reqURL.pathname === '/oauth' ) {
  139. return pages.oauth(res, state, reqURL.searchParams, lastGuild);
  140. }
  141. if ( !settingsData.has(state) ) {
  142. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  143. let pathGuild = reqURL.pathname.split('/').slice(2, 5).join('/');
  144. if ( /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(pathGuild) ) {
  145. res.setHeader('Set-Cookie', [`guild="${pathGuild}"; HttpOnly; Path=/`]);
  146. }
  147. }
  148. return pages.login(res, state, ( reqURL.pathname === '/' ? '' : 'unauthorized' ));
  149. }
  150. if ( reqURL.pathname === '/refresh' ) {
  151. let returnLocation = reqURL.searchParams.get('return');
  152. if ( !/^\/guild\/\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(returnLocation) ) {
  153. returnLocation = '/';
  154. }
  155. return pages.refresh(res, state, returnLocation);
  156. }
  157. if ( reqURL.pathname === '/api' ) {
  158. let wiki = reqURL.searchParams.get('wiki');
  159. if ( wiki ) return pages.api(res, wiki);
  160. }
  161. let action = '';
  162. if ( reqURL.searchParams.get('refresh') === 'success' ) action = 'refresh';
  163. if ( reqURL.searchParams.get('refresh') === 'failed' ) action = 'refreshfail';
  164. return dashboard(res, state, reqURL, action);
  165. });
  166. server.listen(8080, 'localhost', () => {
  167. console.log( '- Dashboard: Server running at http://localhost:8080/' );
  168. });
  169. String.prototype.replaceSave = function(pattern, replacement) {
  170. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  171. };
  172. /**
  173. * End the process gracefully.
  174. * @param {NodeJS.Signals} signal - The signal received.
  175. */
  176. function graceful(signal) {
  177. console.log( '- Dashboard: ' + signal + ': Closing the dashboard...' );
  178. server.close( () => {
  179. console.log( '- Dashboard: ' + signal + ': Closed the dashboard server.' );
  180. } );
  181. db.close( dberror => {
  182. if ( dberror ) {
  183. console.log( '- Dashboard: ' + signal + ': Error while closing the database connection: ' + dberror );
  184. return dberror;
  185. }
  186. console.log( '- Dashboard: ' + signal + ': Closed the database connection.' );
  187. process.exit(0);
  188. } );
  189. }
  190. process.once( 'SIGINT', graceful );
  191. process.once( 'SIGTERM', graceful );