remote-text.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /******************************************************************************
  2. Copyright (C) 2015 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <curl/curl.h>
  15. #include "obs-app.hpp"
  16. #include "qt-wrappers.hpp"
  17. #include "remote-text.hpp"
  18. using namespace std;
  19. static size_t string_write(char *ptr, size_t size, size_t nmemb, string &str)
  20. {
  21. size_t total = size * nmemb;
  22. if (total)
  23. str.append(ptr, total);
  24. return total;
  25. }
  26. void RemoteTextThread::run()
  27. {
  28. char error[CURL_ERROR_SIZE];
  29. CURLcode code;
  30. string versionString("User-Agent: obs-basic ");
  31. versionString += App()->GetVersionString();
  32. string contentTypeString;
  33. if (!contentType.empty()) {
  34. contentTypeString += "Content-Type: ";
  35. contentTypeString += contentType;
  36. }
  37. auto curl_deleter = [] (CURL *curl) {curl_easy_cleanup(curl);};
  38. using Curl = unique_ptr<CURL, decltype(curl_deleter)>;
  39. Curl curl{curl_easy_init(), curl_deleter};
  40. if (curl) {
  41. struct curl_slist *header = nullptr;
  42. string str;
  43. header = curl_slist_append(header,
  44. versionString.c_str());
  45. if (!contentTypeString.empty()) {
  46. header = curl_slist_append(header,
  47. contentTypeString.c_str());
  48. }
  49. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  50. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER,
  51. header);
  52. curl_easy_setopt(curl.get(), CURLOPT_ERRORBUFFER,
  53. error);
  54. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION,
  55. string_write);
  56. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA,
  57. &str);
  58. if (!postData.empty()) {
  59. curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS,
  60. postData.c_str());
  61. }
  62. code = curl_easy_perform(curl.get());
  63. if (code != CURLE_OK) {
  64. emit Result(QString(), QT_UTF8(error));
  65. } else {
  66. emit Result(QT_UTF8(str.c_str()), QString());
  67. }
  68. curl_slist_free_all(header);
  69. }
  70. }