electron/shell/browser/api/save_page_handler.cc

72 lines
2.3 KiB
C++
Raw Normal View History

2015-10-14 04:41:31 +00:00
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/save_page_handler.h"
2015-10-14 04:41:31 +00:00
#include <string>
#include <utility>
2015-10-14 04:41:31 +00:00
#include "base/callback.h"
#include "base/files/file_path.h"
#include "content/public/browser/web_contents.h"
#include "shell/browser/atom_browser_context.h"
2015-10-14 04:41:31 +00:00
namespace atom {
namespace api {
SavePageHandler::SavePageHandler(content::WebContents* web_contents,
util::Promise promise)
: web_contents_(web_contents), promise_(std::move(promise)) {}
2015-10-14 04:41:31 +00:00
2018-04-18 01:55:30 +00:00
SavePageHandler::~SavePageHandler() {}
2015-10-14 04:41:31 +00:00
void SavePageHandler::OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) {
2015-10-14 04:41:31 +00:00
// OnDownloadCreated is invoked during WebContents::SavePage, so the |item|
// here is the one stated by WebContents::SavePage.
item->AddObserver(this);
}
bool SavePageHandler::Handle(const base::FilePath& full_path,
const content::SavePageType& save_type) {
auto* download_manager = content::BrowserContext::GetDownloadManager(
2015-10-14 04:41:31 +00:00
web_contents_->GetBrowserContext());
download_manager->AddObserver(this);
// Chromium will create a 'foo_files' directory under the directory of saving
// page 'foo.html' for holding other resource files of 'foo.html'.
base::FilePath saved_main_directory_path = full_path.DirName().Append(
full_path.RemoveExtension().BaseName().value() +
FILE_PATH_LITERAL("_files"));
2018-04-18 01:55:30 +00:00
bool result =
web_contents_->SavePage(full_path, saved_main_directory_path, save_type);
2015-10-14 04:41:31 +00:00
download_manager->RemoveObserver(this);
// If initialization fails which means fail to create |DownloadItem|, we need
// to delete the |SavePageHandler| instance to avoid memory-leak.
if (!result) {
promise_.RejectWithErrorMessage("Failed to save the page");
2015-10-14 04:41:31 +00:00
delete this;
}
2015-10-14 04:41:31 +00:00
return result;
}
void SavePageHandler::OnDownloadUpdated(download::DownloadItem* item) {
2015-10-14 04:41:31 +00:00
if (item->IsDone()) {
if (item->GetState() == download::DownloadItem::COMPLETE)
promise_.Resolve();
else
promise_.RejectWithErrorMessage("Failed to save the page.");
2015-10-14 04:41:31 +00:00
Destroy(item);
}
}
void SavePageHandler::Destroy(download::DownloadItem* item) {
2015-10-14 04:41:31 +00:00
item->RemoveObserver(this);
delete this;
}
} // namespace api
} // namespace atom