DownloadDialog.xaml.cpp 12 KB

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