1// Copyright (c) 2012 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.
4
5#ifndef CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_MANAGER_EVENT_ROUTER_H_
6#define CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_MANAGER_EVENT_ROUTER_H_
7
8#include <map>
9#include <string>
10
11#include "base/basictypes.h"
12#include "base/compiler_specific.h"
13#include "base/files/file_path_watcher.h"
14#include "base/memory/scoped_ptr.h"
15#include "chrome/browser/chromeos/drive/drive_integration_service.h"
16#include "chrome/browser/chromeos/drive/file_system_observer.h"
17#include "chrome/browser/chromeos/drive/job_list.h"
18#include "chrome/browser/chromeos/drive/sync_client.h"
19#include "chrome/browser/chromeos/file_manager/file_watcher.h"
20#include "chrome/browser/chromeos/file_manager/fileapi_util.h"
21#include "chrome/browser/chromeos/file_manager/volume_manager.h"
22#include "chrome/browser/chromeos/file_manager/volume_manager_observer.h"
23#include "chrome/browser/drive/drive_service_interface.h"
24#include "chrome/common/extensions/api/file_manager_private.h"
25#include "chromeos/disks/disk_mount_manager.h"
26#include "chromeos/network/network_state_handler_observer.h"
27#include "components/keyed_service/core/keyed_service.h"
28#include "storage/browser/fileapi/file_system_operation.h"
29
30class PrefChangeRegistrar;
31class Profile;
32
33using file_manager::util::EntryDefinition;
34
35namespace base {
36class ListValue;
37}
38
39namespace chromeos {
40class NetworkState;
41}
42
43namespace drive {
44class FileChange;
45}
46
47namespace file_manager {
48class DeviceEventRouter;
49
50// Monitors changes in disk mounts, network connection state and preferences
51// affecting File Manager. Dispatches appropriate File Browser events.
52class EventRouter : public KeyedService,
53                    public chromeos::NetworkStateHandlerObserver,
54                    public drive::FileSystemObserver,
55                    public drive::JobListObserver,
56                    public drive::DriveServiceObserver,
57                    public VolumeManagerObserver,
58                    public content::NotificationObserver {
59 public:
60  explicit EventRouter(Profile* profile);
61  virtual ~EventRouter();
62
63  // KeyedService overrides.
64  virtual void Shutdown() OVERRIDE;
65
66  typedef base::Callback<void(bool success)> BoolCallback;
67
68  // Adds a file watch at |local_path|, associated with |virtual_path|, for
69  // an extension with |extension_id|.
70  //
71  // |callback| will be called with true on success, or false on failure.
72  // |callback| must not be null.
73  void AddFileWatch(const base::FilePath& local_path,
74                    const base::FilePath& virtual_path,
75                    const std::string& extension_id,
76                    const BoolCallback& callback);
77
78  // Removes a file watch at |local_path| for an extension with |extension_id|.
79  void RemoveFileWatch(const base::FilePath& local_path,
80                       const std::string& extension_id);
81
82  // Called when a copy task is completed.
83  void OnCopyCompleted(
84      int copy_id, const GURL& source_url, const GURL& destination_url,
85      base::File::Error error);
86
87  // Called when a copy task progress is updated.
88  void OnCopyProgress(int copy_id,
89                      storage::FileSystemOperation::CopyProgressType type,
90                      const GURL& source_url,
91                      const GURL& destination_url,
92                      int64 size);
93
94  // chromeos::NetworkStateHandlerObserver overrides.
95  virtual void DefaultNetworkChanged(
96      const chromeos::NetworkState* network) OVERRIDE;
97
98  // drive::JobListObserver overrides.
99  virtual void OnJobAdded(const drive::JobInfo& job_info) OVERRIDE;
100  virtual void OnJobUpdated(const drive::JobInfo& job_info) OVERRIDE;
101  virtual void OnJobDone(const drive::JobInfo& job_info,
102                         drive::FileError error) OVERRIDE;
103
104  // drive::DriveServiceObserver overrides.
105  virtual void OnRefreshTokenInvalid() OVERRIDE;
106
107  // drive::FileSystemObserver overrides.
108  virtual void OnDirectoryChanged(const base::FilePath& drive_path) OVERRIDE;
109  virtual void OnFileChanged(const drive::FileChange& changed_files) OVERRIDE;
110  virtual void OnDriveSyncError(drive::file_system::DriveSyncErrorType type,
111                                const base::FilePath& drive_path) OVERRIDE;
112
113  // VolumeManagerObserver overrides.
114  virtual void OnDiskAdded(
115      const chromeos::disks::DiskMountManager::Disk& disk,
116      bool mounting) OVERRIDE;
117  virtual void OnDiskRemoved(
118      const chromeos::disks::DiskMountManager::Disk& disk) OVERRIDE;
119  virtual void OnDeviceAdded(const std::string& device_path) OVERRIDE;
120  virtual void OnDeviceRemoved(const std::string& device_path) OVERRIDE;
121  virtual void OnVolumeMounted(chromeos::MountError error_code,
122                               const VolumeInfo& volume_info) OVERRIDE;
123  virtual void OnVolumeUnmounted(chromeos::MountError error_code,
124                                 const VolumeInfo& volume_info) OVERRIDE;
125  virtual void OnFormatStarted(
126      const std::string& device_path, bool success) OVERRIDE;
127  virtual void OnFormatCompleted(
128      const std::string& device_path, bool success) OVERRIDE;
129
130  // content::NotificationObserver overrides.
131  virtual void Observe(int type,
132                       const content::NotificationSource& source,
133                       const content::NotificationDetails& details) OVERRIDE;
134
135 private:
136  typedef std::map<base::FilePath, FileWatcher*> WatcherMap;
137
138  // Starts observing file system change events.
139  void ObserveEvents();
140
141  // Called when prefs related to file manager change.
142  void OnFileManagerPrefsChanged();
143
144  // Process file watch notifications.
145  void HandleFileWatchNotification(const drive::FileChange* list,
146                                   const base::FilePath& path,
147                                   bool got_error);
148
149  // Sends directory change event.
150  void DispatchDirectoryChangeEvent(
151      const base::FilePath& path,
152      const drive::FileChange* list,
153      bool got_error,
154      const std::vector<std::string>& extension_ids);
155
156  // Sends directory change event, after converting the file definition to entry
157  // definition.
158  void DispatchDirectoryChangeEventWithEntryDefinition(
159      const linked_ptr<drive::FileChange> list,
160      const std::string* extension_id,
161      bool watcher_error,
162      const EntryDefinition& entry_definition);
163
164  // Dispatches the mount completed event.
165  void DispatchMountCompletedEvent(
166      extensions::api::file_manager_private::MountCompletedEventType event_type,
167      chromeos::MountError error,
168      const VolumeInfo& volume_info);
169
170  // If needed, opens a file manager window for the removable device mounted at
171  // |mount_path|. Disk.mount_path() is empty, since it is being filled out
172  // after calling notifying observers by DiskMountManager.
173  void ShowRemovableDeviceInFileManager(VolumeType type,
174                                        const base::FilePath& mount_path);
175
176  // Manages the list of currently active Drive file transfer jobs.
177  struct DriveJobInfoWithStatus {
178    DriveJobInfoWithStatus();
179    DriveJobInfoWithStatus(const drive::JobInfo& info,
180                           const std::string& status);
181    drive::JobInfo job_info;
182    std::string status;
183  };
184
185  // Sends onFileTransferUpdate event right now if |immediate| is set. Otherwise
186  // it refrains from sending for a short while, and after that it sends the
187  // most recently scheduled event once.
188  // The delay is for waiting subsequent 'added' events to come after the first
189  // one when multiple tasks are added. This way, we can avoid frequent UI
190  // update caused by differences between singular and plural cases.
191  void ScheduleDriveFileTransferEvent(const drive::JobInfo& job_info,
192                                      const std::string& status,
193                                      bool immediate);
194
195  // Sends the most recently scheduled onFileTransferUpdated event to
196  // extensions.
197  // This is used for implementing ScheduledDriveFileTransferEvent().
198  void SendDriveFileTransferEvent();
199
200  std::map<drive::JobID, DriveJobInfoWithStatus> drive_jobs_;
201  scoped_ptr<DriveJobInfoWithStatus> drive_job_info_for_scheduled_event_;
202  base::Time last_copy_progress_event_;
203  base::Time next_send_file_transfer_event_;
204
205  WatcherMap file_watchers_;
206  scoped_ptr<PrefChangeRegistrar> pref_change_registrar_;
207  Profile* profile_;
208
209  content::NotificationRegistrar notification_registrar_;
210
211  scoped_ptr<DeviceEventRouter> device_event_router_;
212
213  // Note: This should remain the last member so it'll be destroyed and
214  // invalidate the weak pointers before any other members are destroyed.
215  base::WeakPtrFactory<EventRouter> weak_factory_;
216  DISALLOW_COPY_AND_ASSIGN(EventRouter);
217};
218
219}  // namespace file_manager
220
221#endif  // CHROME_BROWSER_CHROMEOS_EXTENSIONS_FILE_MANAGER_EVENT_ROUTER_H_
222