GithubDownloader.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include <GithubDownloader.h>
  2. #include <FS.h>
  3. Stream& GithubDownloader::streamFile(const String& path) {
  4. if (!client.connect(GITHUB_RAW_DOMAIN, 443)) {
  5. Serial.println("Failed to connect to github over HTTPS.");
  6. }
  7. if (!client.verify(GITHUB_SSL_FINGERPRINT, GITHUB_RAW_DOMAIN)) {
  8. Serial.println("Failed to verify github certificate");
  9. }
  10. client.print(String("GET ") + path + " HTTP/1.1\r\n" +
  11. "Host: " + GITHUB_RAW_DOMAIN + "\r\n" +
  12. "Connection: close\r\n\r\n");
  13. return client;
  14. }
  15. Stream& GithubDownloader::streamFile(const String& username, const String& repo, const String& path) {
  16. return streamFile(buildPath(username, repo, path));
  17. }
  18. bool GithubDownloader::downloadFile(const String& path, Stream& dest) {
  19. Stream& client = streamFile(path);
  20. if (client.available()) {
  21. if (!client.find("\r\n\r\n")) {
  22. Serial.println("Error seeking to body");
  23. return false;
  24. }
  25. } else {
  26. Serial.println("Failed to open stream to Github");
  27. return false;
  28. }
  29. while (client.available()) {
  30. size_t l = client.readBytes(buffer, GITHUB_DOWNLOADER_BUFFER_SIZE);
  31. size_t w = dest.write(buffer, l);
  32. dest.flush();
  33. if (w != l) {
  34. printf("Error writing to stream. Expected to write %d bytes, but only wrote %d\n", l, w);
  35. return false;
  36. }
  37. printf("Read %d bytes\n", w);
  38. yield();
  39. }
  40. return true;
  41. }
  42. bool GithubDownloader::downloadFile(const String& username, const String& repo, const String& repoPath, Stream& dest) {
  43. return downloadFile(buildPath(username, repo, repoPath), dest);
  44. }
  45. bool GithubDownloader::downloadFile(const String& username, const String& repo, const String& repoPath, const String& fsPath) {
  46. String tmpFile = fsPath + ".download_tmp";
  47. File f = SPIFFS.open(tmpFile.c_str(), "w");
  48. if (!f) {
  49. Serial.print("ERROR - could not open file for downloading: ");
  50. Serial.println(fsPath);
  51. return false;
  52. }
  53. if (!downloadFile(buildPath(username, repo, repoPath), f)) {
  54. f.close();
  55. return false;
  56. }
  57. f.flush();
  58. f.close();
  59. SPIFFS.remove(fsPath);
  60. SPIFFS.rename(tmpFile, fsPath);
  61. Serial.print("Finished downloading file: ");
  62. Serial.println(fsPath);
  63. Serial.println(f.size());
  64. return true;
  65. }
  66. String GithubDownloader::buildPath(const String& username, const String& repo, const String& repoPath) {
  67. String path = String("/") + username + "/" + repo + "/master/" + repoPath;
  68. return path;
  69. }