Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / media_galleries / media_galleries_preferences.h
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_MEDIA_GALLERIES_MEDIA_GALLERIES_PREFERENCES_H_
6 #define CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_GALLERIES_PREFERENCES_H_
7
8 #include <map>
9 #include <set>
10 #include <string>
11
12 #include "base/basictypes.h"
13 #include "base/callback_forward.h"
14 #include "base/files/file_path.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/observer_list.h"
17 #include "base/strings/string16.h"
18 #include "base/time/time.h"
19 #include "components/browser_context_keyed_service/browser_context_keyed_service.h"
20 #include "components/storage_monitor/removable_storage_observer.h"
21
22 class Profile;
23
24 namespace base {
25 class DictionaryValue;
26 }
27
28 namespace extensions {
29 class Extension;
30 class ExtensionPrefs;
31 }
32
33 namespace user_prefs {
34 class PrefRegistrySyncable;
35 }
36
37 typedef uint64 MediaGalleryPrefId;
38 const MediaGalleryPrefId kInvalidMediaGalleryPrefId = 0;
39
40 struct MediaGalleryPermission {
41   MediaGalleryPrefId pref_id;
42   bool has_permission;
43 };
44
45 struct MediaGalleryPrefInfo {
46   enum Type {
47     kUserAdded,     // Explicitly added by the user.
48     kAutoDetected,  // Auto added to the list of galleries.
49     kBlackListed,   // Auto added but then removed by the user.
50     kScanResult,    // Discovered by a disk scan.
51     kRemovedScan,   // Discovered by a disk scan but then removed by the user.
52     kInvalidType,
53   };
54
55   MediaGalleryPrefInfo();
56   ~MediaGalleryPrefInfo();
57
58   // The absolute path of the gallery.
59   base::FilePath AbsolutePath() const;
60
61   // True if the gallery should not be displayed to the user
62   // i.e. kBlackListed || kRemovedScan.
63   bool IsBlackListedType() const;
64
65   // The ID that identifies this gallery in this Profile.
66   MediaGalleryPrefId pref_id;
67
68   // The user-visible name of this gallery.
69   base::string16 display_name;
70
71   // A string which uniquely and persistently identifies the device that the
72   // gallery lives on.
73   std::string device_id;
74
75   // The root of the gallery, relative to the root of the device.
76   base::FilePath path;
77
78   // The type of gallery.
79   Type type;
80
81   // The volume label of the volume/device on which the gallery
82   // resides. Empty if there is no such label or it is unknown.
83   base::string16 volume_label;
84
85   // Vendor name for the volume/device on which the gallery is located.
86   // Will be empty if unknown.
87   base::string16 vendor_name;
88
89   // Model name for the volume/device on which the gallery is located.
90   // Will be empty if unknown.
91   base::string16 model_name;
92
93   // The capacity in bytes of the volume/device on which the gallery is
94   // located. Will be zero if unknown.
95   uint64 total_size_in_bytes;
96
97   // If the gallery is on a removable device, the time that device was last
98   // attached. It is stored in preferences by the base::Time internal value,
99   // which is microseconds since the epoch.
100   base::Time last_attach_time;
101
102   // Set to true if the volume metadata fields (volume_label, vendor_name,
103   // model_name, total_size_in_bytes) were set. False if these fields were
104   // never written.
105   bool volume_metadata_valid;
106
107   // The following fields are populated with the audio, image, and video file
108   // counts from the last scan. For files where it is hard to determine the
109   // exact type, the file should be counted in all possible counts.
110   int audio_count;
111   int image_count;
112   int video_count;
113
114   // 0 if the display_name is set externally and always used for display.
115   // 1 if the display_name is only set externally when it is overriding
116   // the name constructed from volume metadata.
117   int prefs_version;
118
119   // Called by views to provide details for the gallery permission entries.
120   base::string16 GetGalleryDisplayName() const;
121   base::string16 GetGalleryTooltip() const;
122   base::string16 GetGalleryAdditionalDetails() const;
123
124   // Returns true if the gallery is currently a removable device gallery which
125   // is now attached, or a fixed storage gallery.
126   bool IsGalleryAvailable() const;
127 };
128
129 typedef std::map<MediaGalleryPrefId, MediaGalleryPrefInfo>
130     MediaGalleriesPrefInfoMap;
131 typedef std::set<MediaGalleryPrefId> MediaGalleryPrefIdSet;
132
133 // A class to manage the media gallery preferences.  There is one instance per
134 // user profile.
135 class MediaGalleriesPreferences : public BrowserContextKeyedService,
136                                   public RemovableStorageObserver {
137  public:
138   class GalleryChangeObserver {
139     public:
140      // |extension_id| specifies the extension affected by this change.
141      // |pref_id| refers to the gallery.
142      virtual void OnPermissionAdded(MediaGalleriesPreferences* pref,
143                                     const std::string& extension_id,
144                                     MediaGalleryPrefId pref_id) {}
145
146      virtual void OnPermissionRemoved(MediaGalleriesPreferences* pref,
147                                       const std::string& extension_id,
148                                       MediaGalleryPrefId pref_id) {}
149
150      virtual void OnGalleryAdded(MediaGalleriesPreferences* pref,
151                                  MediaGalleryPrefId pref_id) {}
152
153      virtual void OnGalleryRemoved(MediaGalleriesPreferences* pref,
154                                    MediaGalleryPrefId pref_id) {}
155
156      virtual void OnGalleryInfoUpdated(MediaGalleriesPreferences* pref,
157                                        MediaGalleryPrefId pref_id) {}
158     protected:
159      virtual ~GalleryChangeObserver();
160   };
161
162   explicit MediaGalleriesPreferences(Profile* profile);
163   virtual ~MediaGalleriesPreferences();
164
165   // Ensures that the preferences is initialized. The provided callback, if
166   // non-null, will be called when initialization is complete. If initialization
167   // has already completed, this callback will be invoked in the calling stack.
168   // Before the callback is run, other calls may not return the correct results.
169   // Should be invoked on the UI thread; callbacks will be run on the UI thread.
170   // This call also ensures that the StorageMonitor is initialized.
171   // Note for unit tests: This requires an active FILE thread and
172   // EnsureMediaDirectoriesExists instance to complete reliably.
173   void EnsureInitialized(base::Closure callback);
174
175   // Return true if the storage monitor has already been initialized.
176   bool IsInitialized() const;
177
178   Profile* profile();
179
180   void AddGalleryChangeObserver(GalleryChangeObserver* observer);
181   void RemoveGalleryChangeObserver(GalleryChangeObserver* observer);
182
183   // RemovableStorageObserver implementation.
184   virtual void OnRemovableStorageAttached(const StorageInfo& info) OVERRIDE;
185
186   // Lookup a media gallery and fill in information about it and return true if
187   // it exists. Return false if it does not, filling in default information.
188   bool LookUpGalleryByPath(const base::FilePath& path,
189                            MediaGalleryPrefInfo* gallery) const;
190
191   MediaGalleryPrefIdSet LookUpGalleriesByDeviceId(
192       const std::string& device_id) const;
193
194   // Returns the absolute file path of the gallery specified by the
195   // |gallery_id|. Returns an empty file path if the |gallery_id| is invalid.
196   // Set |include_unpermitted_galleries| to true to get the file path of the
197   // gallery to which this |extension| has no access permission.
198   base::FilePath LookUpGalleryPathForExtension(
199       MediaGalleryPrefId gallery_id,
200       const extensions::Extension* extension,
201       bool include_unpermitted_galleries);
202
203   // Teaches the registry about a new gallery. If the gallery is in a
204   // blacklisted state, it is unblacklisted. |type| should not be a blacklisted
205   // type. Returns the gallery's pref id.
206   MediaGalleryPrefId AddGallery(const std::string& device_id,
207                                 const base::FilePath& relative_path,
208                                 MediaGalleryPrefInfo::Type type,
209                                 const base::string16& volume_label,
210                                 const base::string16& vendor_name,
211                                 const base::string16& model_name,
212                                 uint64 total_size_in_bytes,
213                                 base::Time last_attach_time,
214                                 int audio_count,
215                                 int image_count,
216                                 int video_count);
217
218   // Teach the registry about a gallery simply from the path. If the gallery is
219   // in a blacklisted state, it is unblacklisted. |type| should not be a
220   // blacklisted type. Returns the gallery's pref id.
221   MediaGalleryPrefId AddGalleryByPath(const base::FilePath& path,
222                                       MediaGalleryPrefInfo::Type type);
223
224   // Logically removes the gallery identified by |id| from the store. For
225   // auto added or scan result galleries, this means moving them into a
226   // blacklisted state, otherwise they may come back when they are detected
227   // again.
228   void ForgetGalleryById(MediaGalleryPrefId id);
229
230   // Remove the gallery identified by |id| from the store entirely. If it is an
231   // auto added or scan result gallery, it could get added again when the
232   // location is noticed again.
233   void EraseGalleryById(MediaGalleryPrefId id);
234
235   // Returns true if some extension has permission for |id|, which may not be
236   // an auto detected type.
237   bool NonAutoGalleryHasPermission(MediaGalleryPrefId id) const;
238
239   MediaGalleryPrefIdSet GalleriesForExtension(
240       const extensions::Extension& extension) const;
241
242   // Returns true if the permission changed. Returns false if there was
243   // no change.
244   bool SetGalleryPermissionForExtension(const extensions::Extension& extension,
245                                         MediaGalleryPrefId pref_id,
246                                         bool has_permission);
247
248   const MediaGalleriesPrefInfoMap& known_galleries() const;
249
250   // These keep track of when we last successfully completed a media scan.
251   // This is used to provide cached results when appropriate.
252   base::Time GetLastScanCompletionTime() const;
253   void SetLastScanCompletionTime(const base::Time& time);
254
255   // BrowserContextKeyedService implementation:
256   virtual void Shutdown() OVERRIDE;
257
258   static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
259
260   // Returns true if the media gallery preferences system has ever been used
261   // for this profile. To be exact, it checks if a gallery has ever been added
262   // (including defaults).
263   static bool APIHasBeenUsed(Profile* profile);
264
265  private:
266   friend class MediaGalleriesPreferencesTest;
267   friend class MediaGalleriesPermissionsTest;
268
269   typedef std::map<std::string /*device id*/, MediaGalleryPrefIdSet>
270       DeviceIdPrefIdsMap;
271
272   // These must be called on the UI thread.
273   void OnInitializationCallbackReturned();
274   void FinishInitialization();
275
276   // Populates the default galleries. Call only on fresh profiles.
277   void AddDefaultGalleries();
278
279   // This is a hack - Some devices (iTunes, Picasa) are singletons in that only
280   // one instance of that type is supported at a time. As such, the device id
281   // should just be "itunes:" or "picasa:" but that would mean finding the
282   // location of the database file multiple times, which may be an async
283   // operation. Storing the location of the backing database in the device
284   // id allows that look up to be avoided. However, the cost is that if the
285   // database moves, the device id in preferences has to be updated.  This
286   // method searches for a gallery of the type passed in and updates its
287   // device id.  It returns true if the device id is up to date.
288   bool UpdateDeviceIDForSingletonType(const std::string& device_id);
289
290   void OnStorageMonitorInit(bool add_default_galleries);
291
292   // Handle an iPhoto, iTunes, or Picasa finder returning a device ID to us.
293   void OnFinderDeviceID(const std::string& device_id);
294
295   // Builds |known_galleries_| from the persistent store.
296   void InitFromPrefs();
297
298   MediaGalleryPrefId AddGalleryInternal(const std::string& device_id,
299                                         const base::string16& display_name,
300                                         const base::FilePath& relative_path,
301                                         MediaGalleryPrefInfo::Type type,
302                                         const base::string16& volume_label,
303                                         const base::string16& vendor_name,
304                                         const base::string16& model_name,
305                                         uint64 total_size_in_bytes,
306                                         base::Time last_attach_time,
307                                         bool volume_metadata_valid,
308                                         int audio_count,
309                                         int image_count,
310                                         int video_count,
311                                         int prefs_version);
312
313   void EraseOrBlacklistGalleryById(MediaGalleryPrefId id, bool erase);
314
315   // Sets permission for the media galleries identified by |gallery_id| for the
316   // extension in the given |prefs|. Returns true only if anything changed.
317   bool SetGalleryPermissionInPrefs(const std::string& extension_id,
318                                    MediaGalleryPrefId gallery_id,
319                                    bool has_access);
320
321   // Removes the entry for the media galleries permissions identified by
322   // |gallery_id| for the extension in the given |prefs|.
323   // Returns true only if anything changed.
324   bool UnsetGalleryPermissionInPrefs(const std::string& extension_id,
325                                      MediaGalleryPrefId gallery_id);
326
327   // Return all media gallery permissions for the extension in the given
328   // |prefs|.
329   std::vector<MediaGalleryPermission> GetGalleryPermissionsFromPrefs(
330       const std::string& extension_id) const;
331
332   // Remove all the media gallery permissions in |prefs| for the gallery
333   // specified by |gallery_id|.
334   void RemoveGalleryPermissionsFromPrefs(MediaGalleryPrefId gallery_id);
335
336   // Get the ExtensionPrefs to use; this will be either the ExtensionPrefs
337   // object associated with |profile_|, or extension_prefs_for_testing_, if
338   // SetExtensionPrefsForTesting() has been called.
339   extensions::ExtensionPrefs* GetExtensionPrefs() const;
340
341   // Set the ExtensionPrefs object to be returned by GetExtensionPrefs().
342   void SetExtensionPrefsForTesting(extensions::ExtensionPrefs* extension_prefs);
343
344   bool initialized_;
345   std::vector<base::Closure> on_initialize_callbacks_;
346   int pre_initialization_callbacks_waiting_;
347
348   // The profile that owns |this|.
349   Profile* profile_;
350
351   // The ExtensionPrefs used in a testing environment, where
352   // BrowserContextKeyedServices aren't used. This will be NULL unless it is
353   // set with SetExtensionPrefsForTesting().
354   extensions::ExtensionPrefs* extension_prefs_for_testing_;
355
356   // An in-memory cache of known galleries.
357   MediaGalleriesPrefInfoMap known_galleries_;
358
359   // A mapping from device id to the set of gallery pref ids on that device.
360   // All pref ids in |device_map_| are also in |known_galleries_|.
361   DeviceIdPrefIdsMap device_map_;
362
363   ObserverList<GalleryChangeObserver> gallery_change_observers_;
364
365   base::WeakPtrFactory<MediaGalleriesPreferences> weak_factory_;
366
367   DISALLOW_COPY_AND_ASSIGN(MediaGalleriesPreferences);
368 };
369
370 #endif  // CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_GALLERIES_PREFERENCES_H_