Skip to content

Commit

Permalink
Merge pull request #19 from TingluoHuang/users/tihuang/decodepayload
Browse files Browse the repository at this point in the history
decode snappy compressed base64 json.
  • Loading branch information
TingluoHuang authored Dec 30, 2021
2 parents d8d6f57 + e63facc commit c5f90a9
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"react-codemirror2": "^7.1.0",
"react-copy-to-clipboard": "^5.0.2",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
"react-scripts": "3.4.1",
"snappyjs": "^0.6.1"
},
"scripts": {
"start": "react-scripts start",
Expand Down
30 changes: 23 additions & 7 deletions src/components/JSONFormatter/JSONFormatter.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import React, { Component } from "react";
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { UnControlled as CodeMirror } from 'react-codemirror2'
import SnappyJS from 'snappyjs'
import { Buffer } from "buffer";

const zlib = require('zlib');
require('codemirror/mode/javascript/javascript');
Expand Down Expand Up @@ -61,16 +63,30 @@ export class JSONFormatter extends Component {

formatJSON(input) {
if (input) {
var jsonString = "";
if (!input.startsWith("0x")) {
throw new Error("input needs to be a Hex String starts with '0x'.");
input = input.replace(/\r?\n|\r/g, "");
// check whether the input is a base64 string and then try use snappy to decompress it
var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
if (base64regex.test(input)) {
var uncompressed = SnappyJS.uncompress(Buffer.from(input, 'base64'));
let utf8decoder = new TextDecoder()
jsonString = utf8decoder.decode(uncompressed);
}
else {
throw new Error("input needs to be a Hex String starts with '0x' or valid base64 string.");
}
}
input = input.substring(2);
var hex = Buffer.from(input, 'hex');
if (input.toLowerCase().startsWith("1f8b")) {
// gzip string, need to unzip first
hex = zlib.gunzipSync(hex);
else {
input = input.substring(2);
var hex = Buffer.from(input, 'hex');
if (input.toLowerCase().startsWith("1f8b")) {
// gzip string, need to unzip first
hex = zlib.gunzipSync(hex);
}
jsonString = hex.toString('utf-8');
}
var jsonString = hex.toString('utf-8');

var parsedData = JSON.parse(jsonString);
var outputText = JSON.stringify(parsedData, null, 4);
return outputText;
Expand Down

0 comments on commit c5f90a9

Please sign in to comment.