index.js 8.9 KB

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