SongDownloader.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "api.h"
  2. #include "SongDownloader.h"
  3. #include "main.h"
  4. #include "../../..\Components\wac_network\wac_network_http_receiver_api.h"
  5. #include <strsafe.h>
  6. SongDownloader::SongDownloader(const wchar_t *filename, HANDLE done_event, void (*callback)(void *callbackContext, wchar_t *status), void *context)
  7. : done_event(done_event), callback(callback), context(context)
  8. {
  9. hFile = CreateFile(filename, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
  10. content_length=0;
  11. bytes_downloaded=0;
  12. }
  13. SongDownloader::~SongDownloader()
  14. {
  15. if (hFile != INVALID_HANDLE_VALUE)
  16. CloseHandle(hFile);
  17. }
  18. void SongDownloader::OnInit(DownloadToken token)
  19. {
  20. api_httpreceiver *jnet = WAC_API_DOWNLOADMANAGER->GetReceiver(token);
  21. if (jnet)
  22. {
  23. jnet->AddHeaderValue("X-Winamp-ID", winamp_id_str);
  24. jnet->AddHeaderValue("X-Winamp-Name", winamp_name);
  25. }
  26. }
  27. void SongDownloader::OnData(DownloadToken token, void *data, size_t datalen)
  28. {
  29. if (!content_length)
  30. {
  31. api_httpreceiver *jnet = WAC_API_DOWNLOADMANAGER->GetReceiver(token);
  32. if (jnet)
  33. {
  34. const char *header = jnet->getheader("content-length");
  35. if (header)
  36. content_length = _strtoui64(header, 0, 10);
  37. }
  38. }
  39. DWORD written = 0;
  40. WriteFile(hFile, data, (DWORD)datalen, &written, 0);
  41. bytes_downloaded+=written;
  42. if (content_length && callback)
  43. {
  44. wchar_t status[128] = {0};
  45. StringCbPrintf(status, sizeof(status), L"Transferring (%d%%)", (int)(100ULL * bytes_downloaded / content_length));
  46. callback(context,status);
  47. }
  48. }
  49. void SongDownloader::OnCancel(DownloadToken token)
  50. {
  51. wchar_t status[128] = {0};
  52. // TODO: lang pack
  53. StringCbCopy(status, sizeof(status), L"Cancelled");
  54. callback(context,status);
  55. SetEvent(done_event);
  56. this->Release();
  57. }
  58. void SongDownloader::OnError(DownloadToken token, int error)
  59. {
  60. wchar_t status[128] = {0};
  61. // TODO: lang pack
  62. StringCbCopy(status, sizeof(status), L"Failed");
  63. callback(context,status);
  64. SetEvent(done_event);
  65. this->Release();
  66. }
  67. void SongDownloader::OnFinish(DownloadToken token)
  68. {
  69. wchar_t status[128] = {0};
  70. // TODO: lang pack
  71. StringCbCopy(status, sizeof(status), L"Done");
  72. callback(context,status);
  73. SetEvent(done_event);
  74. this->Release();
  75. }