goliveapi-censoredjson.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "goliveapi-censoredjson.hpp"
  2. #include <unordered_map>
  3. #include <nlohmann/json.hpp>
  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. obs_data_array_t *child_array = obs_data_item_get_array(item);
  23. censorRecurseArray(child_array);
  24. obs_data_array_release(child_array);
  25. }
  26. }
  27. }
  28. void censorRecurseArray(obs_data_array_t *array)
  29. {
  30. const size_t sz = obs_data_array_count(array);
  31. for (size_t i = 0; i < sz; i++) {
  32. obs_data_t *item = obs_data_array_item(array, i);
  33. censorRecurse(item);
  34. obs_data_release(item);
  35. }
  36. }
  37. QString censoredJson(obs_data_t *data, bool pretty)
  38. {
  39. if (!data) {
  40. return "";
  41. }
  42. // Ugly clone via JSON write/read
  43. const char *j = obs_data_get_json(data);
  44. obs_data_t *clone = obs_data_create_from_json(j);
  45. // Censor our copy
  46. censorRecurse(clone);
  47. // Turn our copy into JSON
  48. QString s = pretty ? obs_data_get_json_pretty(clone) : obs_data_get_json(clone);
  49. // Eliminate our copy
  50. obs_data_release(clone);
  51. return s;
  52. }
  53. using json = nlohmann::json;
  54. void censorRecurse(json &data)
  55. {
  56. if (!data.is_structured())
  57. return;
  58. auto it = data.find("authentication");
  59. if (it != data.end() && it->is_string()) {
  60. *it = "CENSORED";
  61. }
  62. for (auto &child : data) {
  63. censorRecurse(child);
  64. }
  65. }
  66. QString censoredJson(json data, bool pretty)
  67. {
  68. censorRecurse(data);
  69. return QString::fromStdString(data.dump(pretty ? 4 : -1));
  70. }