summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/drive/search_metadata.cc
blob: ae4cd20e84ee50d4b3aec87e9675d893928c8171 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/drive/search_metadata.h"

#include <algorithm>
#include "base/bind.h"
#include "base/string_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"

using content::BrowserThread;

namespace drive {

namespace {

// Used to sort the search result per the last accessed/modified time. The
// recently accessed/modified files come first.
bool CompareByTimestamp(const MetadataSearchResult& a,
                        const MetadataSearchResult& b) {
  const PlatformFileInfoProto& a_file_info = a.entry_proto.file_info();
  const PlatformFileInfoProto& b_file_info = b.entry_proto.file_info();

  if (a_file_info.last_accessed() != b_file_info.last_accessed())
    return a_file_info.last_accessed() > b_file_info.last_accessed();

  // When the entries have the same last access time (which happens quite often
  // because Drive server doesn't set the field until an entry is viewed via
  // drive.google.com), we use last modified time as the tie breaker.
  return a_file_info.last_modified() > b_file_info.last_modified();
}

}  // namespace

// Helper class for searching the local resource metadata.
class SearchMetadataHelper {
 public:
  SearchMetadataHelper(DriveFileSystemInterface* file_system,
                       const std::string& query,
                       int at_most_num_matches,
                       const SearchMetadataCallback& callback)
    : file_system_(file_system),
      query_(query),
      at_most_num_matches_(at_most_num_matches),
      callback_(callback),
      results_(new MetadataSearchResultVector),
      num_pending_reads_(0),
      ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
  }

  // Starts searching the local resource metadata by reading the root
  // directory.
  void Start() {
    const FilePath root(kDriveRootDirectory);
    ++num_pending_reads_;
    file_system_->ReadDirectoryByPath(
        root,
        base::Bind(&SearchMetadataHelper::DidReadDirectoryByPath,
                   weak_ptr_factory_.GetWeakPtr(),
                   root));
  }


 private:
  // Called when a directory is read. Continues searching the local resource
  // metadata by recursively reading sub directories.
  void DidReadDirectoryByPath(const FilePath& parent_path,
                              DriveFileError error,
                              bool hide_hosted_documents,
                              scoped_ptr<DriveEntryProtoVector> entries) {
    if (error != DRIVE_FILE_OK) {
      callback_.Run(error, scoped_ptr<MetadataSearchResultVector>());
      // There could be some in-flight ReadDirectoryByPath() requests, but
      // deleting |this| is safe thanks to the weak pointer.
      delete this;
      return;
    }
    DCHECK(entries);

    --num_pending_reads_;
    for (size_t i = 0; i < entries->size(); ++i) {
      const DriveEntryProto& entry = entries->at(i);
      const FilePath current_path = parent_path.Append(
          FilePath::FromUTF8Unsafe(entry.base_name()));
      // Skip the hosted document if "hide hosted documents" setting is
      // enabled.
      if (hide_hosted_documents &&
          entry.file_specific_info().is_hosted_document())
        continue;

      // Add it to the search result if the base name of the file contains
      // the query.
      std::string highlighted;
      if (FindAndHighlight(entry.base_name(), query_, &highlighted)) {
        results_->push_back(
            MetadataSearchResult(current_path, entry, highlighted));
      }

      // Recursively reading the sub directory.
      if (entry.file_info().is_directory()) {
        ++num_pending_reads_;
        file_system_->ReadDirectoryByPath(
            current_path,
            base::Bind(&SearchMetadataHelper::DidReadDirectoryByPath,
                       weak_ptr_factory_.GetWeakPtr(),
                       current_path));
      }
    }

    if (num_pending_reads_ == 0) {
      // Search is complete. Send the result to the callback.
      std::sort(results_->begin(), results_->end(), &CompareByTimestamp);
      if (results_->size() > static_cast<size_t>(at_most_num_matches_)) {
        // Don't use resize() as it requres a default constructor.
        results_->erase(results_->begin() + at_most_num_matches_,
                        results_->end());
      }
      callback_.Run(DRIVE_FILE_OK, results_.Pass());
      delete this;
    }
  }

  DriveFileSystemInterface* file_system_;
  const std::string query_;
  const int at_most_num_matches_;
  const SearchMetadataCallback callback_;
  scoped_ptr<MetadataSearchResultVector> results_;
  int num_pending_reads_;

  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<SearchMetadataHelper> weak_ptr_factory_;
};

void SearchMetadata(DriveFileSystemInterface* file_system,
                    const std::string& query,
                    int at_most_num_matches,
                    const SearchMetadataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  // |helper| will delete itself when the search is done.
  SearchMetadataHelper* helper =
      new SearchMetadataHelper(file_system,
                               query,
                               at_most_num_matches,
                               callback);
  helper->Start();
}

bool FindAndHighlight(const std::string& text,
                      const std::string& query,
                      std::string* highlighted_text) {
  DCHECK(highlighted_text);
  highlighted_text->clear();

  if (query.empty())
    return false;

  // TODO(satorux): Should support non-ASCII characters.
  std::string lower_text = StringToLowerASCII(text);
  std::string lower_query = StringToLowerASCII(query);

  int num_matches = 0;
  std::string::size_type cursor = 0;

  while (cursor < text.size()) {
    std::string::size_type matched_position =
        lower_text.find(lower_query, cursor);
    if (matched_position == std::string::npos)
      break;
    ++num_matches;

    std::string skipped_piece =
        net::EscapeForHTML(text.substr(cursor, matched_position - cursor));
    std::string matched_piece =
        net::EscapeForHTML(text.substr(matched_position, query.size()));

    highlighted_text->append(skipped_piece);
    highlighted_text->append("<b>" + matched_piece + "</b>");

    cursor = matched_position + query.size();
  }
  if (num_matches == 0)
    return false;

  std::string remaining_piece = text.substr(cursor);
  highlighted_text->append(net::EscapeForHTML(remaining_piece));

  return true;
}

}  // namespace drive