app.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import 'dotenv/config'
  2. import grpc from "grpc"
  3. import express from "express"
  4. import bodyParser from "body-parser"
  5. import basicAuth from "express-basic-auth"
  6. import {
  7. CommandService_v1Client as CommandService,
  8. QueryService_v1Client as QueryService
  9. } from 'iroha-helpers/lib/proto/endpoint_grpc_pb'
  10. import { queries } from 'iroha-helpers'
  11. import util from 'util'
  12. import { exec } from 'child_process'
  13. import cors from 'cors'
  14. const app = express();
  15. app.use(bodyParser.json());
  16. //TODO is cors package necesary? basic middleware could suffice
  17. app.use(cors()); //TODO: set only safe origins
  18. app.use(basicAuth({
  19. users: { admin: 'superPasswd' }
  20. }));
  21. const asyncExec = util.promisify(exec);
  22. const IROHA_ADMIN_PRIV = "f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70";
  23. const IROHA_ADMIN = "admin@test";
  24. const IROHA_ADDRESS = process.env.IROHA_ADDRESS || "localhost:50051";
  25. const queryService = new QueryService(IROHA_ADDRESS, grpc.credentials.createInsecure());
  26. const CHAIN4ALL_RASTER_CLIP_SCRIPT_PATH = process.env.CHAIN4ALL_RASTER_CLIP_SCRIPT_PATH || '/home/kunickyd/Documents/chain4all/chain4all_raster_clip.sh';
  27. const CHAIN4ALL_SERVICE_PORT = process.env.CHAIN4ALL_SERVICE_PORT || 3000;
  28. const PRICE_MODIFIER: number = parseFloat(process.env.PRICE_MODIFIER || "0.5");
  29. app.get("/", (req, res) => {
  30. res.send("Chain4All Blockchain service");
  31. });
  32. app.post("/price", (req, res) => { //add caching of same requests
  33. if (req.body && req.body.area) {
  34. res.send({ price: getPrice(req.body.area) });
  35. }
  36. else {
  37. res.status(400);
  38. throw Error(JSON.stringify({ error: { name: "Error, request has no body with \"area\" property!" } }));
  39. }
  40. });
  41. app.post("/buy", async (req, res, next) => {
  42. try {
  43. if (!req.body) {
  44. res.status(400);
  45. throw Error(JSON.stringify({ error: { name: "Error, request has no body!" } }));
  46. }
  47. if (!req.body.txHash) {
  48. res.status(400);
  49. throw Error(JSON.stringify({ error: { name: "Error, request body has no \"txHash\" property!" } }));
  50. }
  51. //TODO load from http headers, or something like that??
  52. if (!req.body.user) {
  53. res.status(400);
  54. throw Error(JSON.stringify({ error: { name: "Error, request body has no \"user\" property!" } }));
  55. }
  56. //TODO validate this properly
  57. let txDetail = await getTransactionDetail(req.body.txHash, req.body.user);
  58. let extent: Array<Array<number>> = JSON.parse(txDetail.description).extent as Array<Array<number>>;
  59. let dataFileId: string = Date.now().toString();
  60. let dataCommand = CHAIN4ALL_RASTER_CLIP_SCRIPT_PATH + ' ' + extent[3][1] + ' ' + extent[3][0] + ' ' + extent[1][1] + ' ' + extent[1][0] + ' ' + dataFileId;
  61. console.debug(dataCommand);
  62. const { stdout, stderr } = await asyncExec(dataCommand);
  63. console.debug(stdout);
  64. if(stderr){
  65. console.warn(stderr);
  66. }
  67. res.send({dataUrl: "https://gis.lesprojekt.cz/chain4all/raster_" + dataFileId + ".tif"});
  68. }
  69. catch (err) {
  70. next(err);
  71. }
  72. });
  73. async function getTransactionDetail(txHash: string, user: string) {
  74. let quer: any = await queries.getAccountTransactions({
  75. privateKey: IROHA_ADMIN_PRIV,
  76. creatorAccountId: IROHA_ADMIN,
  77. queryService,
  78. timeoutLimit: 5000
  79. }, {
  80. accountId: user,
  81. pageSize: 10,
  82. firstTxHash: txHash,
  83. ordering: {
  84. field: undefined,
  85. direction: undefined
  86. },
  87. firstTxTime: undefined,
  88. lastTxTime: undefined,
  89. firstTxHeight: 1,
  90. lastTxHeight: 3
  91. });
  92. //TODO find better way to look for transferAssets command in transaction
  93. return quer.transactionsList[0].payload.reducedPayload.commandsList[0].transferAsset;
  94. }
  95. function getArea(extent: Array<Array<number>>): number {
  96. let y1 = extent[0][1];
  97. let y4 = extent[3][1];
  98. let x1 = extent[0][0];
  99. let x2 = extent[1][0];
  100. let height = Math.abs(y1 - y4);
  101. let width = Math.abs(x1 - x2);
  102. return height * width;
  103. }
  104. function getPrice(area: number) : number {
  105. return area * PRICE_MODIFIER;
  106. }
  107. function errorMiddleware(err: any, req: any, res: any, next: any): void { //TODO: add custom Exception class
  108. console.log(err);
  109. res.status(500);
  110. res.send(err);
  111. }
  112. app.use(errorMiddleware);
  113. app.listen(CHAIN4ALL_SERVICE_PORT, () => {
  114. console.log(`Listening at http://localhost:${CHAIN4ALL_SERVICE_PORT}`)
  115. });