LeechCraft  0.6.70-18450-gabe19ee3b0
Modular cross-platform feature rich live environment.
downloadhelpers.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * LeechCraft - modular cross-platform feature rich internet client.
3  * Copyright (C) 2006-2014 Georg Rudoy
4  *
5  * Distributed under the Boost Software License, Version 1.0.
6  * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
7  **********************************************************************/
8 
9 #include "downloadhelpers.h"
10 #include <QFile>
11 #include <QtDebug>
12 #include <util/sll/either.h>
13 #include <util/sll/visitor.h>
14 #include <util/sys/paths.h>
15 #include <util/xpc/util.h>
17 #include <util/threads/coro.h>
19 
20 namespace LC::Util
21 {
23  {
24  const auto& path = GetTemporaryName ();
25  auto e = MakeEntity (url,
26  path,
28  Internal |
31  e.Mime_ = std::move (params.Mime_);
32  e.Additional_ = std::move (params.Additional_);
33 
34  const auto res = iem.DelegateEntity (e);
35  if (!res)
36  {
37  qWarning () << "delegation failed for" << url;
38  co_return IDownload::Error
39  {
41  QObject::tr ("Unable to find a downloader plugin.")
42  };
43  }
44 
45  const auto result = co_await res.DownloadResult_;
46  const auto success [[maybe_unused]] = co_await WithHandler (result,
47  [&url] (const IDownload::Error& error)
48  {
49  qWarning () << "failed downloading" << url << static_cast<int> (error.Type_) << error.Message_;
50  });
51 
52  QFile file { path };
53  auto removeGuard = MakeScopeGuard ([&file] { file.remove (); });
54  if (!file.open (QIODevice::ReadOnly))
55  {
56  qWarning () << "unable to open downloaded file" << file.errorString ();
57  co_return IDownload::Error
58  {
60  QObject::tr ("Unable to open local file: %1.").arg (file.errorString ())
61  };
62  }
63 
64  co_return file.readAll ();
65  }
66 }
Proxy to core entity manager.
requires std::invocable< F, const L & > detail::EitherAwaiter< L, R, F > WithHandler(const Either< L, R > &either, F &&errorHandler)
Definition: either.h:82
Task< TempDownload_t > DownloadAsTemporary(IEntityManager &iem, QUrl url, DownloadParams params)
Entity MakeEntity(const QVariant &entity, const QString &location, TaskParameters tp, const QString &mime)
Definition: util.cpp:82
enum IDownload::Error::Type Type_
QString Message_
Definition: idownload.h:64
virtual DelegationResult DelegateEntity(LC::Entity entity, QObject *desired=nullptr)=0
Delegates the given entity and returns the delegation result.
detail::ScopeGuard< F > MakeScopeGuard(const F &f)
Returns an object performing passed function on scope exit.
Definition: util.h:155
QString GetTemporaryName(const QString &pattern)
Returns a temporary filename.
Definition: paths.cpp:143