swdb.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. case 'BattleRiftOfWorldsRaidStart':
  80. this.eventStartReq = req;
  81. this.eventStartRes = res;
  82. break;
  83. // Profile login
  84. case 'HubUserLogin':
  85. apiCommand = "profile/";
  86. method = "PUT";
  87. success = "Profile uploaded sucesfully!";
  88. params['response'] = JSON.stringify(res);
  89. break;
  90. // Catalog status
  91. case 'GetUnitCollection':
  92. //command = "update_collection";
  93. //success = "Collection updated sucesfully!"
  94. break;
  95. // Profile logbook
  96. case 'GetLobbyWizardLog':
  97. //command = "update_logbook";
  98. //success = "Logbook updated succesfully!";
  99. break;
  100. // Battle runs
  101. case 'BattleDungeonResult_V2':
  102. apiCommand = "run/";
  103. method = "POST";
  104. success = "Cairos run logged sucesfully!"
  105. params['result_response'] = JSON.stringify(res);
  106. params['result_request'] = JSON.stringify(req);
  107. break;
  108. case 'BattleDimensionHoleDungeonResult_v2':
  109. apiCommand = "run/";
  110. method = "POST";
  111. success = "Dimension Hole run logged sucesfully!"
  112. params['result_response'] = JSON.stringify(res);
  113. params['result_request'] = JSON.stringify(req);
  114. break;
  115. case 'BattleRiftOfWorldsRaidResult':
  116. apiCommand = "run/";
  117. method = "POST";
  118. success = "Rift Rarid run logged sucesfully!"
  119. params['result_response'] = JSON.stringify(res);
  120. params['start_response'] = JSON.stringify(this.eventStartRes);
  121. break;
  122. case 'BattleScenarioResult':
  123. //command = "log_run_scenario";
  124. //success = "Scenario run logged sucesfully!"
  125. start = true;
  126. break;
  127. case 'BattleTrialTowerResult_v2':
  128. //command = "log_run_toa";
  129. //success = "TOA run logged sucesfully!"
  130. break;
  131. }
  132. if (apiCommand != ""){
  133. this.command(apiCommand, method, params, success);
  134. }
  135. },
  136. /**
  137. * Calls an arbitrary command on the SWDB APIv3.
  138. *
  139. * @param command Command nade.
  140. * @param req The full request data.
  141. * @param res The full response data.
  142. * @param start Indicates if event start request and response are needed.
  143. * @param success Optional. Message to show on success.
  144. */
  145. command(command, method, params, success = null){
  146. // Override success message if empty
  147. if (success == null || success == ""){
  148. sucess = `Command ${command} succesfully executed!`
  149. }
  150. this.log('debug', `Starting ${command}...`);
  151. // Generate POST data
  152. var data = querystring.stringify(params);
  153. // Configure POST requets
  154. var post_options = {
  155. host: config.Config.Plugins[this.pluginName].host,
  156. port: config.Config.Plugins[this.pluginName].port,
  157. path: '/API/v3/' + command,
  158. method: method,
  159. headers: {
  160. 'Content-Type': 'application/x-www-form-urlencoded',
  161. 'Content-Length': Buffer.byteLength(data)
  162. }
  163. };
  164. // Set up the request
  165. var req = http.request(post_options, (function(res) {
  166. res.setEncoding('utf8');
  167. res.on('data', (function (body) {
  168. switch (res.statusCode){
  169. case 200:
  170. case 201:
  171. this.log('success', `${success} [${res.statusCode}]`);
  172. break;
  173. case 400:
  174. this.log('error', `[HTTP/1.1 400] There were errors importing the data: ${JSON.stringify(body)}`);
  175. break;
  176. case 404:
  177. this.log('error', '[HTTP/1.1 404] URL not found.');
  178. break;
  179. case 500:
  180. this.log('error', '[HTTP/1.1 500] The server returned an error.');
  181. break;
  182. default:
  183. this.log('error', `[HTTP/1.1 ${res.statusCode}] Unexpected error.`);
  184. }
  185. }).bind(this));
  186. }).bind(this));
  187. // Perform the request
  188. req.write(data);
  189. req.end();
  190. },
  191. /**
  192. * Prints a message to the SWEX output and to the console.
  193. *
  194. * @param type Log type. Debug type will be printed depending on config.
  195. * @param msg The message to log.
  196. */
  197. log(type, msg){
  198. if (type != "debug" || this.config.Config.Plugins[this.pluginName].debug == true){
  199. this.proxy.log({ type: type, source: 'plugin', name: this.pluginName, message: msg });
  200. pad_type = type.substring(0, 5).padEnd(5, ' ');
  201. pad_plugin = this.pluginName.substring(0, 4).padEnd(4, ' ');
  202. console.log(`[${pad_plugin}][${pad_type}] ${msg}`);
  203. }
  204. }
  205. };