GithubClient.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #include <GithubClient.h>
  2. #include <FS.h>
  3. Stream& GithubClient::stream(const String& path) {
  4. if (!client.connect(GITHUB_RAW_DOMAIN, 443)) {
  5. Serial.println(F("Failed to connect to github over HTTPS."));
  6. }
  7. if (!client.verify(sslFingerprint.c_str(), domain.c_str())) {
  8. Serial.println(F("Failed to verify github certificate"));
  9. }
  10. client.printf(
  11. "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n",
  12. path.c_str(),
  13. domain.c_str()
  14. );
  15. return client;
  16. }
  17. bool GithubClient::download(const String& path, Stream& dest) {
  18. Stream& client = stream(path);
  19. if (client.available()) {
  20. if (!client.find("\r\n\r\n")) {
  21. Serial.println(F("Error seeking to body"));
  22. return false;
  23. }
  24. } else {
  25. Serial.println(F("Failed to open stream to Github"));
  26. return false;
  27. }
  28. Serial.println(F("Downloading..."));
  29. size_t bytes = 0;
  30. size_t nextCheckpoint = 4096;
  31. while (client.available()) {
  32. size_t l = client.readBytes(buffer, GITHUB_CLIENT_BUFFER_SIZE);
  33. size_t w = dest.write(buffer, l);
  34. dest.flush();
  35. if (w != l) {
  36. printf_P(PSTR("Error writing to stream. Expected to write %d bytes, but only wrote %d\n"), l, w);
  37. return false;
  38. }
  39. bytes += w;
  40. if (bytes % 10 == 0) {
  41. printf_P(".");
  42. }
  43. if (bytes >= nextCheckpoint) {
  44. printf("[%d KB]\n", bytes/1024);
  45. nextCheckpoint += 4096;
  46. }
  47. yield();
  48. }
  49. Serial.println(F("\n"));
  50. return true;
  51. }
  52. bool GithubClient::download(const String& path, const String& fsPath) {
  53. String tmpFile = fsPath + ".download_tmp";
  54. File f = SPIFFS.open(tmpFile.c_str(), "w");
  55. printf("1.");
  56. if (!f) {
  57. Serial.print(F("ERROR - could not open file for downloading: "));
  58. Serial.println(fsPath);
  59. return false;
  60. }
  61. printf("2.");
  62. if (!download(path, f)) {
  63. f.close();
  64. return false;
  65. }
  66. printf("3.");
  67. f.flush();
  68. f.close();
  69. SPIFFS.remove(fsPath);
  70. SPIFFS.rename(tmpFile, fsPath);
  71. printf("Finished downloading file: %s\n", fsPath.c_str());
  72. return true;
  73. }
  74. String GithubClient::buildRepoPath(const String& username, const String& repo, const String& repoPath) {
  75. String path = String("/") + username + "/" + repo + "/master/" + repoPath;
  76. return path;
  77. }
  78. GithubClient GithubClient::rawDownloader() {
  79. return GithubClient(GITHUB_RAW_DOMAIN, GITHUB_RAW_FINGERPRINT);
  80. }
  81. GithubClient GithubClient::apiClient() {
  82. return GithubClient(GITHUB_API_DOMAIN, GITHUB_API_FINGERPRINT);
  83. }