DownloadDialog.xaml.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. //
  2. // DownloadDialog.xaml.cpp
  3. // DownloadDialog 类的实现
  4. //
  5. #include "pch.h"
  6. #include <wrl.h>
  7. #include <shcore.h>
  8. #include "DownloadDialog.xaml.h"
  9. #include "AsyncHelper.h"
  10. #include "NativeBuffer.h"
  11. #include "StringHelper.h"
  12. #include "minizip/unzip.h"
  13. using namespace SDLPal;
  14. using namespace Platform;
  15. using namespace Platform::Collections;
  16. using namespace Windows::Foundation;
  17. using namespace Windows::Foundation::Collections;
  18. using namespace Windows::Storage;
  19. using namespace Windows::Storage::Compression;
  20. using namespace Windows::Storage::Streams;
  21. using namespace Windows::UI::Core;
  22. using namespace Windows::UI::Popups;
  23. using namespace Windows::UI::Xaml;
  24. using namespace Windows::UI::Xaml::Controls;
  25. using namespace Windows::UI::Xaml::Controls::Primitives;
  26. using namespace Windows::UI::Xaml::Data;
  27. using namespace Windows::UI::Xaml::Input;
  28. using namespace Windows::UI::Xaml::Media;
  29. using namespace Windows::UI::Xaml::Navigation;
  30. using namespace Windows::Web::Http;
  31. // https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“内容对话框”项模板
  32. static const uint32_t _buffer_size = 65536;
  33. static Platform::String^ const _url = "http://pal5q.baiyou100.com/pal5/download/98xjrq.html";
  34. static const wchar_t _postfix[] = L"/Pal98rqp.zip";
  35. struct zip_file
  36. {
  37. IStream* stream;
  38. HRESULT hr;
  39. ULONG cbBytes;
  40. zip_file(IStream* s) : stream(s), hr(S_OK), cbBytes(0) {}
  41. };
  42. SDLPal::DownloadDialog::DownloadDialog(Windows::ApplicationModel::Resources::ResourceLoader^ ldr, StorageFolder^ folder, IRandomAccessStream^ stream, double w, double h, bool from_url)
  43. : m_stream(stream), m_Closable(false), m_InitialPhase(true), m_totalBytes(0), m_resLdr(ldr), m_folder(folder), m_width(w), m_height(h)
  44. {
  45. InitializeComponent();
  46. this->IsSecondaryButtonEnabled = false;
  47. this->MaxWidth = w;
  48. this->MaxHeight = h;
  49. pbDownload->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  50. tbProgress->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  51. if (from_url)
  52. {
  53. wvDownloadPage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  54. }
  55. else
  56. {
  57. gridURL->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  58. }
  59. }
  60. Platform::String^ SDLPal::DownloadDialog::FormatProgress()
  61. {
  62. static auto format = [](wchar_t* buf, double v)->wchar_t* {
  63. if (v <= 1024.0)
  64. swprintf_s(buf, 32, L"%0.0f B", v);
  65. else if (v <= 1048576.0)
  66. swprintf_s(buf, 32, L"%0.2f KB", v / 1024.0);
  67. else if (v <= 1073741824.0)
  68. swprintf_s(buf, 32, L"%0.2f MB", v / 1048576.0);
  69. else
  70. swprintf_s(buf, 32, L"%0.2f GB", v / 1073741824.0);
  71. return buf;
  72. };
  73. wchar_t buf[64], buf1[32], buf2[32];
  74. swprintf_s(buf, L"%s / %s", format(buf1, pbDownload->Value), format(buf2, pbDownload->Maximum));
  75. return ref new Platform::String(buf);
  76. }
  77. void SDLPal::DownloadDialog::DoDownload(Platform::String^ url)
  78. {
  79. wvDownloadPage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  80. gridURL->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  81. pbDownload->Visibility = Windows::UI::Xaml::Visibility::Visible;
  82. tbProgress->Visibility = Windows::UI::Xaml::Visibility::Visible;
  83. this->MaxHeight -= wvDownloadPage->ActualHeight + gridURL->ActualHeight - 48;
  84. this->PrimaryButtonText = m_resLdr->GetString("ButtonStop");
  85. this->Title = m_title;
  86. this->UpdateLayout();
  87. concurrency::create_task([this, url]() {
  88. Exception^ ex = nullptr;
  89. auto client = ref new HttpClient();
  90. try
  91. {
  92. concurrency::create_task(client->GetAsync(ref new Uri(url), HttpCompletionOption::ResponseHeadersRead)).then(
  93. [this](HttpResponseMessage^ response)->IAsyncOperationWithProgress<IInputStream^, uint64_t>^ {
  94. response->EnsureSuccessStatusCode();
  95. bool determinate = response->Content->Headers->HasKey("Content-Length");
  96. if (determinate)
  97. {
  98. m_totalBytes = wcstoull(response->Content->Headers->Lookup("Content-Length")->Data(), nullptr, 10);
  99. }
  100. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, determinate]() {
  101. pbDownload->Maximum = (double)m_totalBytes;
  102. pbDownload->IsIndeterminate = !determinate;
  103. }));
  104. return response->Content->ReadAsInputStreamAsync();
  105. }).then([this, client](IInputStream^ input) {
  106. auto buffer = ref new Buffer(_buffer_size);
  107. uint64_t bytes = 0;
  108. HANDLE hEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS);
  109. for (bool looping = true; looping; )
  110. {
  111. concurrency::create_task(input->ReadAsync(buffer, _buffer_size, InputStreamOptions::None)).then(
  112. [this, &bytes, &looping](IBuffer^ result)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  113. looping = (result->Length == _buffer_size) && !m_Closable;
  114. bytes += result->Length;
  115. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  116. pbDownload->Value = (double)bytes;
  117. tbProgress->Text = FormatProgress();
  118. UpdateLayout();
  119. }));
  120. return m_stream->WriteAsync(result);
  121. }).then([this](uint32_t)->IAsyncOperation<bool>^ {
  122. return m_stream->FlushAsync();
  123. }).wait();
  124. }
  125. delete buffer;
  126. delete client;
  127. delete input;
  128. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  129. this->Title = m_resLdr->GetString("Extracting");
  130. pbDownload->Value = 0.0;
  131. UpdateLayout();
  132. }));
  133. m_stream->Seek(0);
  134. Microsoft::WRL::ComPtr<IStream> strm;
  135. HRESULT hr;
  136. if (FAILED(hr = CreateStreamOverRandomAccessStream(m_stream, IID_PPV_ARGS(&strm)))) throw ref new Platform::Exception(hr);
  137. zlib_filefunc_def funcs = {
  138. /* open */ [](voidpf opaque, const char* filename, int mode)->voidpf { return new zip_file((IStream*)opaque); },
  139. /* read */ [](voidpf opaque, voidpf stream, void* buf, uLong size)->uLong {
  140. auto zip = (zip_file*)stream;
  141. return SUCCEEDED(zip->hr = zip->stream->Read(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  142. },
  143. /* write */ [](voidpf opaque, voidpf stream, const void* buf, uLong size)->uLong {
  144. auto zip = (zip_file*)stream;
  145. return SUCCEEDED(zip->hr = zip->stream->Write(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  146. },
  147. /* tell */ [](voidpf opaque, voidpf stream)->long {
  148. auto zip = (zip_file*)stream;
  149. LARGE_INTEGER liPos = { 0 };
  150. ULARGE_INTEGER uliPos;
  151. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, STREAM_SEEK_CUR, &uliPos)) ? uliPos.LowPart : UNZ_ERRNO;
  152. },
  153. /* seek */ [](voidpf opaque, voidpf stream, uLong offset, int origin)->long {
  154. auto zip = (zip_file*)stream;
  155. LARGE_INTEGER liPos = { offset };
  156. ULARGE_INTEGER uliPos;
  157. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, origin, &uliPos)) ? 0 : UNZ_ERRNO;
  158. },
  159. /* close */ [](voidpf opaque, voidpf stream)->int { delete (zip_file*)stream; return 0; },
  160. /* error */ [](voidpf opaque, voidpf stream)->int { return reinterpret_cast<zip_file*>(stream)->hr; },
  161. strm.Get()
  162. };
  163. unz_global_info ugi;
  164. char szFilename[65536];
  165. uLong filenum = 0;
  166. bool success = true;
  167. auto uzf = unzOpen2("", &funcs);
  168. unzGetGlobalInfo(uzf, &ugi);
  169. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ugi]() { pbDownload->Maximum = ugi.number_entry; UpdateLayout(); }));
  170. for (auto ret = unzGoToFirstFile(uzf); ret == UNZ_OK; ret = unzGoToNextFile(uzf))
  171. {
  172. unz_file_info ufi;
  173. if (UNZ_OK == unzGetCurrentFileInfo(uzf, &ufi, szFilename, sizeof(szFilename), nullptr, 0, nullptr, 0) &&
  174. UNZ_OK == unzOpenCurrentFile(uzf))
  175. {
  176. std::auto_ptr<uint8_t> buf(new uint8_t[ufi.uncompressed_size]);
  177. auto len = unzReadCurrentFile(uzf, buf.get(), ufi.uncompressed_size);
  178. unzCloseCurrentFile(uzf);
  179. if (len != ufi.uncompressed_size)
  180. {
  181. success = false;
  182. break;
  183. }
  184. auto local = m_folder;
  185. uLong prev = 0;
  186. for (uLong i = 0; i < ufi.size_filename; i++)
  187. {
  188. if (szFilename[i] != '/') continue;
  189. try
  190. {
  191. concurrency::create_task(local->GetFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  192. }
  193. catch (Exception^ e)
  194. {
  195. concurrency::create_task(local->CreateFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  196. }
  197. prev = i + 1;
  198. }
  199. if (prev < ufi.size_filename)
  200. {
  201. IRandomAccessStream^ stm = nullptr;
  202. StorageFile^ file = nullptr;
  203. auto filename = ConvertString(szFilename + prev, ufi.size_filename - prev);
  204. concurrency::create_task(local->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([&](StorageFile^ f)->IAsyncOperation<IRandomAccessStream^>^ {
  205. return (file = f)->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
  206. }).then([&](IRandomAccessStream^ s)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  207. return (stm = s)->WriteAsync(NativeBuffer::GetIBuffer(buf.get(), ufi.uncompressed_size));
  208. }).then([&](uint32_t size)->IAsyncOperation<bool>^ {
  209. if (size < ufi.uncompressed_size) throw ref new Exception(E_FAIL);
  210. return stm->FlushAsync();
  211. }).wait();
  212. delete stm;
  213. delete file;
  214. }
  215. }
  216. else
  217. {
  218. success = false;
  219. break;
  220. }
  221. filenum++;
  222. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, filenum, &ugi]() {
  223. wchar_t buf[64];
  224. swprintf_s(buf, L"%lu/%lu", filenum, ugi.number_entry);
  225. pbDownload->Value = (double)filenum;
  226. tbProgress->Text = ref new Platform::String(buf);
  227. UpdateLayout();
  228. }));
  229. }
  230. unzClose(uzf);
  231. if (!success) throw ref new Exception(E_FAIL);
  232. }).wait();
  233. }
  234. catch (Exception^ e)
  235. {
  236. ex = e;
  237. }
  238. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ex]() {
  239. if (!m_Closable)
  240. {
  241. String^ string;
  242. if (ex)
  243. {
  244. string = String::Concat(m_resLdr->GetString("MBDownloadError"), ex->Message);
  245. Result = ContentDialogResult::Secondary;
  246. }
  247. else
  248. {
  249. string = m_resLdr->GetString("MBDownloadOK");
  250. Result = ContentDialogResult::None;
  251. }
  252. (ref new MessageDialog(string, m_resLdr->GetString("MBDownloadTitle")))->ShowAsync();
  253. }
  254. m_Closable = true;
  255. Hide();
  256. }));
  257. });
  258. }
  259. void SDLPal::DownloadDialog::OnPrimaryButtonClick(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogButtonClickEventArgs^ args)
  260. {
  261. (ref new MessageDialog(m_resLdr->GetString("MBDownloadCanceled"), m_resLdr->GetString("MBDownloadTitle")))->ShowAsync();
  262. Result = ContentDialogResult::Primary;
  263. m_Closable = true;
  264. }
  265. void SDLPal::DownloadDialog::OnClosing(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogClosingEventArgs^ args)
  266. {
  267. args->Cancel = !m_Closable;
  268. }
  269. void SDLPal::DownloadDialog::OnOpened(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogOpenedEventArgs^ args)
  270. {
  271. m_title = this->Title;
  272. if (wvDownloadPage->Visibility == Windows::UI::Xaml::Visibility::Visible)
  273. {
  274. wvDownloadPage->Width = m_width - 48;
  275. wvDownloadPage->Height = m_height - 128 - gridURL->ActualHeight;
  276. UpdateLayout();
  277. wvDownloadPage->Navigate(ref new Uri(_url));
  278. }
  279. else
  280. {
  281. this->Title = " ";
  282. }
  283. }
  284. void SDLPal::DownloadDialog::OnNavigateStart(Windows::UI::Xaml::Controls::WebView^ sender, Windows::UI::Xaml::Controls::WebViewNavigationStartingEventArgs^ args)
  285. {
  286. auto url = args->Uri->RawUri;
  287. args->Cancel = (Platform::String::CompareOrdinal(url, _url) != 0);
  288. if (url->Length() >= _countof(_postfix) - 1 && _wcsicmp(url->Data() + url->Length() - (_countof(_postfix) - 1), _postfix) == 0)
  289. {
  290. DoDownload(url);
  291. }
  292. }
  293. void SDLPal::DownloadDialog::OnDOMContentLoaded(Windows::UI::Xaml::Controls::WebView^ sender, Windows::UI::Xaml::Controls::WebViewDOMContentLoadedEventArgs^ args)
  294. {
  295. this->Title = sender->DocumentTitle;
  296. sender->InvokeScriptAsync(ref new String(L"eval"), ref new Vector<String^>(1, ref new String(LR"rs(
  297. var elems = document.getElementsByTagName('a');
  298. for (var i = 0; i < elems.length; i++)
  299. {
  300. if (elems[i].href.indexOf('#') === -1)
  301. {
  302. if (/\/Pal98rqp\.zip$/i.test(elems[i].href))
  303. {
  304. elems[i].target = '';
  305. elems[i].focus();
  306. var r = elems[i].getBoundingClientRect();
  307. var y = (r.top + r.bottom - window.innerHeight) / 2 + window.pageYOffset;
  308. var x = (r.left + r.right - window.innerWidth) / 2 + window.pageXOffset;
  309. window.scroll(x, y);
  310. }
  311. else
  312. {
  313. elems[i].target = '_blank';
  314. }
  315. }
  316. }
  317. )rs")));
  318. }
  319. void SDLPal::DownloadDialog::OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e)
  320. {
  321. if (wvDownloadPage->Visibility == Windows::UI::Xaml::Visibility::Visible)
  322. {
  323. wvDownloadPage->Width = e->NewSize.Width - 48;
  324. wvDownloadPage->Height = e->NewSize.Height - 128 - gridURL->ActualHeight;
  325. }
  326. }
  327. void SDLPal::DownloadDialog::OnClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
  328. {
  329. if (tbURL->Text->Length() > 0)
  330. {
  331. DoDownload(tbURL->Text);
  332. }
  333. }