GoLiveAPI_CensoredJson.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "GoLiveAPI_CensoredJson.hpp"
  2. #include <nlohmann/json.hpp>
  3. #include <unordered_map>
  4. void censorRecurse(obs_data_t *);
  5. void censorRecurseArray(obs_data_array_t *);
  6. void censorRecurse(obs_data_t *data)
  7. {
  8. // if we found what we came to censor, censor it
  9. const char *a = obs_data_get_string(data, "authentication");
  10. if (a && *a) {
  11. obs_data_set_string(data, "authentication", "CENSORED");
  12. }
  13. // recurse to child objects and arrays
  14. obs_data_item_t *item = obs_data_first(data);
  15. for (; item != NULL; obs_data_item_next(&item)) {
  16. enum obs_data_type typ = obs_data_item_gettype(item);
  17. if (typ == OBS_DATA_OBJECT) {
  18. obs_data_t *child_data = obs_data_item_get_obj(item);
  19. censorRecurse(child_data);
  20. obs_data_release(child_data);
  21. } else if (typ == OBS_DATA_ARRAY) {
  22. OBSDataArrayAutoRelease child_array = obs_data_item_get_array(item);
  23. censorRecurseArray(child_array);
  24. }
  25. }
  26. }
  27. void censorRecurseArray(obs_data_array_t *array)
  28. {
  29. const size_t sz = obs_data_array_count(array);
  30. for (size_t i = 0; i < sz; i++) {
  31. obs_data_t *item = obs_data_array_item(array, i);
  32. censorRecurse(item);
  33. obs_data_release(item);
  34. }
  35. }
  36. QString censoredJson(obs_data_t *data, bool pretty)
  37. {
  38. if (!data) {
  39. return "";
  40. }
  41. // Ugly clone via JSON write/read
  42. const char *j = obs_data_get_json(data);
  43. obs_data_t *clone = obs_data_create_from_json(j);
  44. // Censor our copy
  45. censorRecurse(clone);
  46. // Turn our copy into JSON
  47. QString s = pretty ? obs_data_get_json_pretty(clone) : obs_data_get_json(clone);
  48. // Eliminate our copy
  49. obs_data_release(clone);
  50. return s;
  51. }
  52. using json = nlohmann::json;
  53. void censorRecurse(json &data)
  54. {
  55. if (!data.is_structured())
  56. return;
  57. auto it = data.find("authentication");
  58. if (it != data.end() && it->is_string()) {
  59. *it = "CENSORED";
  60. }
  61. for (auto &child : data) {
  62. censorRecurse(child);
  63. }
  64. }
  65. QString censoredJson(json data, bool pretty)
  66. {
  67. censorRecurse(data);
  68. return QString::fromStdString(data.dump(pretty ? 4 : -1));
  69. }