index.js 9.8 KB

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