goliveapi-censoredjson.cpp 2.0 KB

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