swdb.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. const dateFormat = require('/usr/local/lib/node_modules/dateformat');
  2. var querystring = require('querystring');
  3. var http = require('http');
  4. module.exports = {
  5. defaultConfig: {
  6. enabled: true,
  7. debug: true,
  8. runs: true,
  9. apiKey: '',
  10. //host: 'http://localhost',
  11. host: 'localhost',
  12. port: '80',
  13. },
  14. defaultConfigDetails: {
  15. debug: { label: 'Print debug messages' },
  16. runs: { label: 'Also log runs' },
  17. apiKey: { label: 'SWDB instance API key', type: 'textarea' },
  18. host: { label: 'Host running the SWDB instance', type: 'textarea' },
  19. port: { label: 'Port', type: 'textarea' }
  20. },
  21. pluginName: 'SWDB',
  22. pluginDescription: 'Uploads data to SWDB.',
  23. temp: {},
  24. proxy: null,
  25. config: null,
  26. request: null,
  27. eventStartReq: null,
  28. eventStartRes: null,
  29. /**
  30. * Initializes he plugin.
  31. *
  32. * @param proxy The proxy.
  33. * @param config Global configurations.
  34. */
  35. init(proxy, config) {
  36. this.proxy = proxy;
  37. this.config = config;
  38. proxy.on('apiCommand', (req, resp) => {
  39. try {
  40. wizardID = '';
  41. command = '';
  42. apiKey = config.Config.Plugins[this.pluginName].apiKey;
  43. if (config.Config.Plugins[this.pluginName].enabled) {
  44. command = req["command"];
  45. // Check the API key.
  46. if (!apiKey) {
  47. this.log('error', `Profile upload is enabled, but missing API key. Check ${this.pluginName} settings.`);
  48. return;
  49. }
  50. this.processCommand(command, req, resp);
  51. }
  52. }
  53. catch (e) {
  54. this.log('error', `An unexpected error occured: ${e.message}`);
  55. }
  56. });
  57. },
  58. /**
  59. * Switches the command and calls the appropiate function.
  60. *
  61. * @param command The command nade.
  62. * @param req The full request data.
  63. * @param res The full response.
  64. */
  65. processCommand(command, req, res){
  66. // Process the command
  67. var apiCommand = "";
  68. var method = "";
  69. var params = {'key': config.Config.Plugins[this.pluginName].apiKey};
  70. var success = null;
  71. var start = false;
  72. switch (command){
  73. // Start events. Save in case they are needed.
  74. case 'BattleDungeonStart':
  75. case 'BattleScenarioStart':
  76. case 'BattleDimensionHoleDungeonStart':
  77. case 'BattleTrialTowerStart_v2':
  78. case 'BattleRiftDungeonStart':
  79. this.eventStartReq = req;
  80. this.eventStartRes = res;
  81. break;
  82. // Profile login
  83. case 'HubUserLogin':
  84. apiCommand = "profile/";
  85. method = "PUT";
  86. success = "Profile uploaded sucesfully!";
  87. params['response'] = JSON.stringify(res);
  88. break;
  89. // Catalog status
  90. case 'GetUnitCollection':
  91. //command = "update_collection";
  92. //success = "Collection updated sucesfully!"
  93. break;
  94. // Profile logbook
  95. case 'GetLobbyWizardLog':
  96. //command = "update_logbook";
  97. //success = "Logbook updated succesfully!";
  98. break;
  99. // Battle runs
  100. case 'BattleDungeonResult_V2':
  101. apiCommand = "run/";
  102. method = "POST";
  103. success = "Cairos run logged sucesfully!"
  104. params['result_response'] = JSON.stringify(res);
  105. params['result_request'] = JSON.stringify(req);
  106. break;
  107. case 'BattleScenarioResult':
  108. //command = "log_run_scenario";
  109. //success = "Scenario run logged sucesfully!"
  110. start = true;
  111. break;
  112. case 'BattleDimensionHoleDungeonResult':
  113. //command = "log_run_dh";
  114. //success = "Dimension Hole run logged sucesfully!"
  115. break;
  116. case 'BattleTrialTowerResult_v2':
  117. //command = "log_run_toa";
  118. //success = "TOA run logged sucesfully!"
  119. break;
  120. case 'BattleRiftDungeonResult':
  121. //command = "log_run_rift_dungeon";
  122. //success = "Rift Dungeon run logged sucesfully!"
  123. start = true;
  124. break;
  125. }
  126. if (apiCommand != ""){
  127. this.command(apiCommand, method, params, success);
  128. }
  129. },
  130. /**
  131. * Calls an arbitrary command on the SWDB APIv3.
  132. *
  133. * @param command Command nade.
  134. * @param req The full request data.
  135. * @param res The full response data.
  136. * @param start Indicates if event start request and response are needed.
  137. * @param success Optional. Message to show on success.
  138. */
  139. command(command, method, params, success = null){
  140. // Override success message if empty
  141. if (success == null || success == ""){
  142. sucess = `Command ${command} succesfully executed!`
  143. }
  144. this.log('debug', `Starting ${command}...`);
  145. // Generate POST data
  146. var data = querystring.stringify(params);
  147. // Configure POST requets
  148. var post_options = {
  149. host: config.Config.Plugins[this.pluginName].host,
  150. port: config.Config.Plugins[this.pluginName].port,
  151. path: '/API/v3/' + command,
  152. method: method,
  153. headers: {
  154. 'Content-Type': 'application/x-www-form-urlencoded',
  155. 'Content-Length': Buffer.byteLength(data)
  156. }
  157. };
  158. // Set up the request
  159. var req = http.request(post_options, (function(res) {
  160. res.setEncoding('utf8');
  161. res.on('data', (function (body) {
  162. switch (res.statusCode){
  163. case 200:
  164. case 201:
  165. this.log('success', `${success} [${res.statusCode}]`);
  166. break;
  167. case 400:
  168. this.log('error', `[HTTP/1.1 400] There were errors importing the data: ${JSON.stringify(body)}`);
  169. break;
  170. case 404:
  171. this.log('error', '[HTTP/1.1 404] URL not found.');
  172. break;
  173. case 500:
  174. this.log('error', '[HTTP/1.1 500] The server returned an error.');
  175. break;
  176. default:
  177. this.log('error', `[HTTP/1.1 ${res.statusCode}] Unexpected error.`);
  178. }
  179. }).bind(this));
  180. }).bind(this));
  181. // Perform the request
  182. req.write(data);
  183. req.end();
  184. },
  185. /**
  186. * Prints a message to the SWEX output and to the console.
  187. *
  188. * @param type Log type. Debug type will be printed depending on config.
  189. * @param msg The message to log.
  190. */
  191. log(type, msg){
  192. if (type != "debug" || this.config.Config.Plugins[this.pluginName].debug == true){
  193. this.proxy.log({ type: type, source: 'plugin', name: this.pluginName, message: msg });
  194. pad_type = type.substring(0, 5).padEnd(5, ' ');
  195. pad_plugin = this.pluginName.substring(0, 4).padEnd(4, ' ');
  196. console.log(`[${pad_plugin}][${pad_type}] ${msg}`);
  197. }
  198. }
  199. };