DownloadDialog.xaml.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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)
  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. }
  52. Platform::String^ SDLPal::DownloadDialog::FormatProgress()
  53. {
  54. static auto format = [](wchar_t* buf, double v)->wchar_t* {
  55. if (v <= 1024.0)
  56. swprintf_s(buf, 32, L"%0.0f B", v);
  57. else if (v <= 1048576.0)
  58. swprintf_s(buf, 32, L"%0.2f KB", v / 1024.0);
  59. else if (v <= 1073741824.0)
  60. swprintf_s(buf, 32, L"%0.2f MB", v / 1048576.0);
  61. else
  62. swprintf_s(buf, 32, L"%0.2f GB", v / 1073741824.0);
  63. return buf;
  64. };
  65. wchar_t buf[64], buf1[32], buf2[32];
  66. swprintf_s(buf, L"%s / %s", format(buf1, pbDownload->Value), format(buf2, pbDownload->Maximum));
  67. return ref new Platform::String(buf);
  68. }
  69. void SDLPal::DownloadDialog::OnPrimaryButtonClick(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogButtonClickEventArgs^ args)
  70. {
  71. m_Closable = true;
  72. }
  73. void SDLPal::DownloadDialog::OnClosing(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogClosingEventArgs^ args)
  74. {
  75. args->Cancel = !m_Closable;
  76. }
  77. void SDLPal::DownloadDialog::OnOpened(Windows::UI::Xaml::Controls::ContentDialog^ sender, Windows::UI::Xaml::Controls::ContentDialogOpenedEventArgs^ args)
  78. {
  79. DownloadPage->Width = m_width - 48;
  80. DownloadPage->Height = m_height - 128;
  81. UpdateLayout();
  82. DownloadPage->Navigate(ref new Uri(_url));
  83. }
  84. void SDLPal::DownloadDialog::OnNavigateStart(Windows::UI::Xaml::Controls::WebView^ sender, Windows::UI::Xaml::Controls::WebViewNavigationStartingEventArgs^ args)
  85. {
  86. auto url = args->Uri->RawUri;
  87. args->Cancel = (Platform::String::CompareOrdinal(url, _url) != 0);
  88. if (url->Length() >= _countof(_postfix) - 1 && _wcsicmp(url->Data() + url->Length() - (_countof(_postfix) - 1), _postfix) == 0)
  89. {
  90. DownloadPage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  91. pbDownload->Visibility = Windows::UI::Xaml::Visibility::Visible;
  92. tbProgress->Visibility = Windows::UI::Xaml::Visibility::Visible;
  93. this->MaxHeight -= DownloadPage->ActualHeight - 48;
  94. this->PrimaryButtonText = m_resLdr->GetString("ButtonBack");
  95. this->Title = m_title;
  96. this->UpdateLayout();
  97. concurrency::create_task([this, url]() {
  98. Exception^ ex = nullptr;
  99. auto client = ref new HttpClient();
  100. try
  101. {
  102. concurrency::create_task(client->GetAsync(ref new Uri(url), HttpCompletionOption::ResponseHeadersRead)).then(
  103. [this](HttpResponseMessage^ response)->IAsyncOperationWithProgress<IInputStream^, uint64_t>^ {
  104. response->EnsureSuccessStatusCode();
  105. bool determinate = response->Content->Headers->HasKey("Content-Length");
  106. if (determinate)
  107. {
  108. m_totalBytes = wcstoull(response->Content->Headers->Lookup("Content-Length")->Data(), nullptr, 10);
  109. }
  110. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, determinate]() {
  111. pbDownload->Maximum = (double)m_totalBytes;
  112. pbDownload->IsIndeterminate = !determinate;
  113. }));
  114. return response->Content->ReadAsInputStreamAsync();
  115. }).then([this, client](IInputStream^ input) {
  116. auto buffer = ref new Buffer(_buffer_size);
  117. uint64_t bytes = 0;
  118. HANDLE hEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS);
  119. for (bool looping = true; looping; )
  120. {
  121. concurrency::create_task(input->ReadAsync(buffer, _buffer_size, InputStreamOptions::None)).then(
  122. [this, &bytes, &looping](IBuffer^ result)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  123. looping = (result->Length == _buffer_size) && !m_Closable;
  124. bytes += result->Length;
  125. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  126. pbDownload->Value = (double)bytes;
  127. tbProgress->Text = FormatProgress();
  128. UpdateLayout();
  129. }));
  130. return m_stream->WriteAsync(result);
  131. }).then([this](uint32_t)->IAsyncOperation<bool>^ {
  132. return m_stream->FlushAsync();
  133. }).wait();
  134. }
  135. delete buffer;
  136. delete client;
  137. delete input;
  138. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, bytes]() {
  139. this->Title = m_resLdr->GetString("Extracting");
  140. pbDownload->Value = 0.0;
  141. UpdateLayout();
  142. }));
  143. m_stream->Seek(0);
  144. Microsoft::WRL::ComPtr<IStream> strm;
  145. HRESULT hr;
  146. if (FAILED(hr = CreateStreamOverRandomAccessStream(m_stream, IID_PPV_ARGS(&strm)))) throw ref new Platform::Exception(hr);
  147. zlib_filefunc_def funcs = {
  148. /* open */ [](voidpf opaque, const char* filename, int mode)->voidpf { return new zip_file((IStream*)opaque); },
  149. /* read */ [](voidpf opaque, voidpf stream, void* buf, uLong size)->uLong {
  150. auto zip = (zip_file*)stream;
  151. return SUCCEEDED(zip->hr = zip->stream->Read(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  152. },
  153. /* write */ [](voidpf opaque, voidpf stream, const void* buf, uLong size)->uLong {
  154. auto zip = (zip_file*)stream;
  155. return SUCCEEDED(zip->hr = zip->stream->Write(buf, size, &zip->cbBytes)) ? zip->cbBytes : 0;
  156. },
  157. /* tell */ [](voidpf opaque, voidpf stream)->long {
  158. auto zip = (zip_file*)stream;
  159. LARGE_INTEGER liPos = { 0 };
  160. ULARGE_INTEGER uliPos;
  161. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, STREAM_SEEK_CUR, &uliPos)) ? uliPos.LowPart : UNZ_ERRNO;
  162. },
  163. /* seek */ [](voidpf opaque, voidpf stream, uLong offset, int origin)->long {
  164. auto zip = (zip_file*)stream;
  165. LARGE_INTEGER liPos = { offset };
  166. ULARGE_INTEGER uliPos;
  167. return SUCCEEDED(zip->hr = zip->stream->Seek(liPos, origin, &uliPos)) ? 0 : UNZ_ERRNO;
  168. },
  169. /* close */ [](voidpf opaque, voidpf stream)->int { delete (zip_file*)stream; return 0; },
  170. /* error */ [](voidpf opaque, voidpf stream)->int { return reinterpret_cast<zip_file*>(stream)->hr; },
  171. strm.Get()
  172. };
  173. unz_global_info ugi;
  174. char szFilename[65536];
  175. uLong filenum = 0;
  176. bool success = true;
  177. auto uzf = unzOpen2("", &funcs);
  178. unzGetGlobalInfo(uzf, &ugi);
  179. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ugi]() { pbDownload->Maximum = ugi.number_entry; UpdateLayout(); }));
  180. for (auto ret = unzGoToFirstFile(uzf); ret == UNZ_OK; ret = unzGoToNextFile(uzf))
  181. {
  182. unz_file_info ufi;
  183. if (UNZ_OK == unzGetCurrentFileInfo(uzf, &ufi, szFilename, sizeof(szFilename), nullptr, 0, nullptr, 0) &&
  184. UNZ_OK == unzOpenCurrentFile(uzf))
  185. {
  186. std::auto_ptr<uint8_t> buf(new uint8_t[ufi.uncompressed_size]);
  187. auto len = unzReadCurrentFile(uzf, buf.get(), ufi.uncompressed_size);
  188. unzCloseCurrentFile(uzf);
  189. if (len != ufi.uncompressed_size)
  190. {
  191. success = false;
  192. break;
  193. }
  194. auto local = m_folder;
  195. uLong prev = 0;
  196. for (uLong i = 0; i < ufi.size_filename; i++)
  197. {
  198. if (szFilename[i] != '/') continue;
  199. try
  200. {
  201. concurrency::create_task(local->GetFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  202. }
  203. catch (Exception^ e)
  204. {
  205. concurrency::create_task(local->CreateFolderAsync(ConvertString(szFilename + prev, i - prev))).then([&local](StorageFolder^ sub) { local = sub; }).wait();
  206. }
  207. prev = i + 1;
  208. }
  209. if (prev < ufi.size_filename)
  210. {
  211. IRandomAccessStream^ stm = nullptr;
  212. StorageFile^ file = nullptr;
  213. auto filename = ConvertString(szFilename + prev, ufi.size_filename - prev);
  214. concurrency::create_task(local->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([&](StorageFile^ f)->IAsyncOperation<IRandomAccessStream^>^ {
  215. return (file = f)->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
  216. }).then([&](IRandomAccessStream^ s)->IAsyncOperationWithProgress<uint32_t, uint32_t>^ {
  217. return (stm = s)->WriteAsync(NativeBuffer::GetIBuffer(buf.get(), ufi.uncompressed_size));
  218. }).then([&](uint32_t size)->IAsyncOperation<bool>^ {
  219. if (size < ufi.uncompressed_size) throw ref new Exception(E_FAIL);
  220. return stm->FlushAsync();
  221. }).wait();
  222. delete stm;
  223. delete file;
  224. }
  225. }
  226. else
  227. {
  228. success = false;
  229. break;
  230. }
  231. filenum++;
  232. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, filenum, &ugi]() {
  233. wchar_t buf[64];
  234. swprintf_s(buf, L"%lu/%lu", filenum, ugi.number_entry);
  235. pbDownload->Value = (double)filenum;
  236. tbProgress->Text = ref new Platform::String(buf);
  237. UpdateLayout();
  238. }));
  239. }
  240. unzClose(uzf);
  241. if (!success) throw ref new Exception(E_FAIL);
  242. }).wait();
  243. }
  244. catch (Exception^ e)
  245. {
  246. ex = e;
  247. }
  248. this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, ex]() {
  249. Platform::String^ string;
  250. if (m_Closable)
  251. string = m_resLdr->GetString("MBDownloadCanceled");
  252. else if (ex)
  253. string = String::Concat(m_resLdr->GetString("MBDownloadError"), ex->Message);
  254. else
  255. string = m_resLdr->GetString("MBDownloadOK");
  256. (ref new MessageDialog(string, m_resLdr->GetString("MBDownloadTitle")))->ShowAsync();
  257. m_Closable = true;
  258. Hide();
  259. }));
  260. });
  261. }
  262. }
  263. void SDLPal::DownloadDialog::OnDOMContentLoaded(Windows::UI::Xaml::Controls::WebView^ sender, Windows::UI::Xaml::Controls::WebViewDOMContentLoadedEventArgs^ args)
  264. {
  265. m_title = this->Title;
  266. this->Title = sender->DocumentTitle;
  267. sender->InvokeScriptAsync(ref new String(L"eval"), ref new Vector<String^>(1, ref new String(LR"rs(
  268. var elems = document.getElementsByTagName('a');
  269. for (var i = 0; i < elems.length; i++)
  270. {
  271. if (elems[i].href.indexOf('#') === -1)
  272. {
  273. if (/\/Pal98rqp\.zip$/i.test(elems[i].href))
  274. {
  275. elems[i].target = '';
  276. elems[i].focus();
  277. var r = elems[i].getBoundingClientRect();
  278. var y = (r.top + r.bottom - window.innerHeight) / 2 + window.scrollY;
  279. var x = (r.left + r.right - window.innerWidth) / 2 + window.scrollX;
  280. window.scroll(x, y);
  281. }
  282. else
  283. {
  284. elems[i].target = '_blank';
  285. }
  286. }
  287. }
  288. )rs")));
  289. }
  290. void SDLPal::DownloadDialog::OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e)
  291. {
  292. if (DownloadPage->Visibility == Windows::UI::Xaml::Visibility::Visible)
  293. {
  294. DownloadPage->Width = e->NewSize.Width - 48;
  295. DownloadPage->Height = e->NewSize.Height - 128;
  296. }
  297. }