index.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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.headers['content-type'] === 'application/x-www-form-urlencoded' && 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' && /^"(\w*(?:-\d+)*)"$/.test(( cookie.split('=')[1] || '' ));
  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.push(chunk);
  62. } );
  63. req.on( 'error', () => {
  64. console.log( '- Dashboard: ' + error );
  65. res.end('error');
  66. } );
  67. return req.on( 'end', () => {
  68. var settings = {};
  69. Buffer.concat(body).toString().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 themeCookie = ( req.headers?.cookie?.split('; ')?.find( cookie => {
  90. return cookie.split('=')[0] === 'theme' && /^"(?:light|dark)"$/.test(( cookie.split('=')[1] || '' ));
  91. } ) || 'dark' ).replace( /^theme="(light|dark)"$/, '$1' );
  92. var langCookie = ( req.headers?.cookie?.split('; ')?.filter( cookie => {
  93. return cookie.split('=')[0] === 'language' && /^"[a-z\-]+"$/.test(( cookie.split('=')[1] || '' ));
  94. } )?.map( cookie => cookie.replace( /^language="([a-z\-]+)"$/, '$1' ) ) || [] );
  95. var dashboardLang = new Lang(...langCookie, ...( req.headers?.['accept-language']?.split(',')?.map( lang => {
  96. lang = lang.split(';')[0].toLowerCase();
  97. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  98. lang = lang.replace( /-\w+$/, '' );
  99. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  100. lang = lang.replace( /-\w+$/, '' );
  101. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  102. return '';
  103. } ) || [] ));
  104. dashboardLang.fromCookie = langCookie;
  105. return dashboard(res, dashboardLang, themeCookie, state, new URL(resURL, process.env.dashboard), action, actionArgs);
  106. }
  107. }
  108. }
  109. if ( req.method !== 'GET' ) {
  110. let body = '<img width="400" src="https://http.cat/418"><br><strong>' + http.STATUS_CODES[418] + '</strong>';
  111. res.writeHead(418, {
  112. 'Content-Type': 'text/html',
  113. 'Content-Length': Buffer.byteLength(body)
  114. });
  115. res.write( body );
  116. return res.end();
  117. }
  118. var reqURL = new URL(req.url, process.env.dashboard);
  119. if ( reqURL.pathname === '/favicon.ico' ) reqURL.pathname = '/src/icon.png';
  120. if ( files.has(reqURL.pathname) ) {
  121. let file = files.get(reqURL.pathname);
  122. res.writeHead(200, {'Content-Type': file.contentType});
  123. return fs.createReadStream(file.path).pipe(res);
  124. }
  125. res.setHeader('Content-Type', 'text/html');
  126. var themeCookie = ( req.headers?.cookie?.split('; ')?.find( cookie => {
  127. return cookie.split('=')[0] === 'theme' && /^"(?:light|dark)"$/.test(( cookie.split('=')[1] || '' ));
  128. } ) || 'dark' ).replace( /^theme="(light|dark)"$/, '$1' );
  129. var langCookie = ( req.headers?.cookie?.split('; ')?.filter( cookie => {
  130. return cookie.split('=')[0] === 'language' && /^"[a-z\-]+"$/.test(( cookie.split('=')[1] || '' ));
  131. } )?.map( cookie => cookie.replace( /^language="([a-z\-]+)"$/, '$1' ) ) || [] );
  132. var dashboardLang = new Lang(...langCookie, ...( req.headers?.['accept-language']?.split(',')?.map( lang => {
  133. lang = lang.split(';')[0].toLowerCase();
  134. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  135. lang = lang.replace( /-\w+$/, '' );
  136. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  137. lang = lang.replace( /-\w+$/, '' );
  138. if ( allLangs.map.hasOwnProperty(lang) ) return lang;
  139. return '';
  140. } ) || [] ));
  141. dashboardLang.fromCookie = langCookie;
  142. res.setHeader('Content-Language', [dashboardLang.lang]);
  143. var lastGuild = req.headers?.cookie?.split('; ')?.filter( cookie => {
  144. return cookie.split('=')[0] === 'guild' && /^"\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?"$/.test(( cookie.split('=')[1] || '' ));
  145. } )?.map( cookie => cookie.replace( /^guild="(\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?)"$/, '$1' ) )?.join();
  146. if ( lastGuild ) res.setHeader('Set-Cookie', ['guild=""; HttpOnly; Path=/; Max-Age=0']);
  147. var state = req.headers.cookie?.split('; ')?.filter( cookie => {
  148. return cookie.split('=')[0] === 'wikibot' && /^"(\w*(?:-\d+)*)"$/.test(( cookie.split('=')[1] || '' ));
  149. } )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)*)"$/, '$1' ) )?.join();
  150. if ( reqURL.pathname === '/login' ) {
  151. let action = '';
  152. if ( reqURL.searchParams.get('action') === 'failed' ) action = 'loginfail';
  153. return pages.login(res, dashboardLang, themeCookie, state, action);
  154. }
  155. if ( reqURL.pathname === '/logout' ) {
  156. settingsData.delete(state);
  157. res.setHeader('Set-Cookie', [
  158. ...( res.getHeader('Set-Cookie') || [] ),
  159. 'wikibot=""; HttpOnly; Path=/; Max-Age=0'
  160. ]);
  161. return pages.login(res, dashboardLang, themeCookie, state, 'logout');
  162. }
  163. if ( !state ) {
  164. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  165. let pathGuild = reqURL.pathname.split('/').slice(2, 5).join('/');
  166. if ( /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(pathGuild) ) {
  167. res.setHeader('Set-Cookie', [`guild="${pathGuild}"; HttpOnly; Path=/`]);
  168. }
  169. }
  170. return pages.login(res, dashboardLang, themeCookie, state, ( reqURL.pathname === '/' ? '' : 'unauthorized' ));
  171. }
  172. if ( reqURL.pathname === '/oauth' ) {
  173. return pages.oauth(res, state, reqURL.searchParams, lastGuild);
  174. }
  175. if ( !settingsData.has(state) ) {
  176. if ( reqURL.pathname.startsWith( '/guild/' ) ) {
  177. let pathGuild = reqURL.pathname.split('/').slice(2, 5).join('/');
  178. if ( /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(pathGuild) ) {
  179. res.setHeader('Set-Cookie', [`guild="${pathGuild}"; HttpOnly; Path=/`]);
  180. }
  181. }
  182. return pages.login(res, dashboardLang, themeCookie, state, ( reqURL.pathname === '/' ? '' : 'unauthorized' ));
  183. }
  184. if ( reqURL.pathname === '/refresh' ) {
  185. let returnLocation = reqURL.searchParams.get('return');
  186. if ( !/^\/guild\/\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(returnLocation) ) {
  187. returnLocation = '/';
  188. }
  189. return pages.refresh(res, state, returnLocation);
  190. }
  191. if ( reqURL.pathname === '/api' ) {
  192. let wiki = reqURL.searchParams.get('wiki');
  193. if ( wiki ) return pages.api(res, wiki);
  194. }
  195. let action = '';
  196. if ( reqURL.searchParams.get('refresh') === 'success' ) action = 'refresh';
  197. if ( reqURL.searchParams.get('refresh') === 'failed' ) action = 'refreshfail';
  198. return dashboard(res, dashboardLang, themeCookie, state, reqURL, action);
  199. } );
  200. server.listen( 8080, 'localhost', () => {
  201. console.log( '- Dashboard: Server running at http://localhost:8080/' );
  202. } );
  203. String.prototype.replaceSave = function(pattern, replacement) {
  204. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  205. };
  206. /**
  207. * End the process gracefully.
  208. * @param {NodeJS.Signals} signal - The signal received.
  209. */
  210. function graceful(signal) {
  211. console.log( '- Dashboard: ' + signal + ': Closing the dashboard...' );
  212. server.close( () => {
  213. console.log( '- Dashboard: ' + signal + ': Closed the dashboard server.' );
  214. db.end().then( () => {
  215. console.log( '- Dashboard: ' + signal + ': Closed the database connection.' );
  216. process.exit(0);
  217. }, dberror => {
  218. console.log( '- Dashboard: ' + signal + ': Error while closing the database connection: ' + dberror );
  219. } );
  220. } );
  221. }
  222. process.once( 'SIGINT', graceful );
  223. process.once( 'SIGTERM', graceful );