1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/feedback/feedback_report.h"
7 #include "base/file_util.h"
8 #include "base/files/file_enumerator.h"
9 #include "base/files/important_file_writer.h"
10 #include "base/guid.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/threading/sequenced_worker_pool.h"
13 #include "content/public/browser/browser_context.h"
14 #include "content/public/browser/browser_thread.h"
15 #include "net/base/directory_lister.h"
17 using content::BrowserThread;
21 const base::FilePath::CharType kFeedbackReportPath[] =
22 FILE_PATH_LITERAL("Feedback Reports");
23 const base::FilePath::CharType kFeedbackReportFilenameWildcard[] =
24 FILE_PATH_LITERAL("Feedback Report.*");
26 const char kFeedbackReportFilenamePrefix[] = "Feedback Report.";
28 base::FilePath GetFeedbackReportsPath(content::BrowserContext* context) {
30 return base::FilePath();
31 return context->GetPath().Append(kFeedbackReportPath);
34 void WriteReportOnBlockingPool(const base::FilePath reports_path,
35 const base::FilePath& file,
36 const std::string& data) {
37 DCHECK(reports_path.IsParent(file));
38 if (!base::DirectoryExists(reports_path)) {
39 base::File::Error error;
40 if (!base::CreateDirectoryAndGetError(reports_path, &error))
43 base::ImportantFileWriter::WriteFileAtomically(file, data);
50 FeedbackReport::FeedbackReport(content::BrowserContext* context,
51 const base::Time& upload_at,
52 const std::string& data)
53 : upload_at_(upload_at),
55 reports_path_ = GetFeedbackReportsPath(context);
56 if (reports_path_.empty())
58 file_ = reports_path_.AppendASCII(
59 kFeedbackReportFilenamePrefix + base::GenerateGUID());
61 // Uses a BLOCK_SHUTDOWN file task runner because we really don't want to
63 base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool();
64 reports_task_runner_ = pool->GetSequencedTaskRunnerWithShutdownBehavior(
65 pool->GetSequenceToken(),
66 base::SequencedWorkerPool::BLOCK_SHUTDOWN);
68 reports_task_runner_->PostTask(FROM_HERE, base::Bind(
69 &WriteReportOnBlockingPool, reports_path_, file_, data_));
72 FeedbackReport::~FeedbackReport() {}
74 void FeedbackReport::DeleteReportOnDisk() {
75 reports_task_runner_->PostTask(FROM_HERE, base::Bind(
76 base::IgnoreResult(&base::DeleteFile), file_, false));
80 void FeedbackReport::LoadReportsAndQueue(
81 const base::FilePath& user_dir, QueueCallback callback) {
85 base::FileEnumerator enumerator(user_dir.Append(kFeedbackReportPath),
87 base::FileEnumerator::FILES,
88 kFeedbackReportFilenameWildcard);
89 for (base::FilePath name = enumerator.Next();
91 name = enumerator.Next()) {
93 if (ReadFileToString(name, &data))
94 BrowserThread::PostTask(
95 BrowserThread::UI, FROM_HERE, base::Bind(callback, data));
96 base::DeleteFile(name, false);
100 } // namespace feedback