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#include "base/auto_reset.h"
6#include "base/callback.h"
7#include "base/files/file_util.h"
8#include "base/files/scoped_temp_dir.h"
9#include "base/json/json_writer.h"
10#include "base/numerics/safe_conversions.h"
11#include "base/path_service.h"
12#include "base/strings/string_util.h"
13#include "base/strings/utf_string_conversions.h"
14#include "base/values.h"
15#include "chrome/browser/apps/app_browsertest_util.h"
16#include "chrome/browser/browser_process.h"
17#include "chrome/browser/extensions/api/media_galleries/media_galleries_api.h"
18#include "chrome/browser/media_galleries/media_file_system_registry.h"
19#include "chrome/browser/media_galleries/media_folder_finder.h"
20#include "chrome/browser/media_galleries/media_galleries_preferences.h"
21#include "chrome/browser/media_galleries/media_galleries_scan_result_controller.h"
22#include "chrome/browser/media_galleries/media_galleries_test_util.h"
23#include "chrome/browser/media_galleries/media_scan_manager.h"
24#include "chrome/common/chrome_paths.h"
25#include "components/storage_monitor/storage_info.h"
26#include "components/storage_monitor/storage_monitor.h"
27#include "content/public/browser/web_contents.h"
28#include "content/public/test/test_utils.h"
29#include "extensions/browser/extension_system.h"
30#include "extensions/common/extension.h"
31#include "extensions/test/result_catcher.h"
32#include "media/base/test_data_util.h"
33
34#if defined(OS_WIN) || defined(OS_MACOSX)
35#include "chrome/browser/media_galleries/fileapi/picasa_finder.h"
36#include "chrome/common/media_galleries/picasa_test_util.h"
37#include "chrome/common/media_galleries/picasa_types.h"
38#include "chrome/common/media_galleries/pmp_test_util.h"
39#endif
40
41#if defined(OS_MACOSX)
42#include "base/mac/foundation_util.h"
43#include "base/strings/sys_string_conversions.h"
44#include "chrome/browser/media_galleries/fileapi/iapps_finder_impl.h"
45#endif  // OS_MACOSX
46
47#if !defined(DISABLE_NACL)
48#include "base/command_line.h"
49#include "chrome/browser/ui/extensions/application_launch.h"
50#include "ppapi/shared_impl/ppapi_switches.h"
51#endif
52
53using extensions::PlatformAppBrowserTest;
54using storage_monitor::StorageInfo;
55using storage_monitor::StorageMonitor;
56
57namespace {
58
59// Dummy device properties.
60const char kDeviceId[] = "testDeviceId";
61const char kDeviceName[] = "foobar";
62#if defined(FILE_PATH_USES_DRIVE_LETTERS)
63base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("C:\\qux");
64#else
65base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");
66#endif
67
68class DoNothingMediaFolderFinder : public MediaFolderFinder {
69 public:
70  explicit DoNothingMediaFolderFinder(
71      const MediaFolderFinderResultsCallback& callback)
72      : MediaFolderFinder(callback) {
73  }
74  virtual ~DoNothingMediaFolderFinder() {}
75
76  static MediaFolderFinder* CreateDoNothingMediaFolderFinder(
77      const MediaFolderFinderResultsCallback& callback) {
78    return new DoNothingMediaFolderFinder(callback);
79  }
80
81  virtual void StartScan() OVERRIDE {}
82
83 private:
84};
85
86}  // namespace
87
88class TestMediaGalleriesAddScanResultsFunction
89    : public extensions::MediaGalleriesAddScanResultsFunction {
90 public:
91  static ExtensionFunction* Factory() {
92    return new TestMediaGalleriesAddScanResultsFunction;
93  }
94
95 protected:
96  virtual ~TestMediaGalleriesAddScanResultsFunction() {}
97
98  // Accepts the dialog as soon as it is created.
99  virtual MediaGalleriesScanResultController* MakeDialog(
100      content::WebContents* web_contents,
101      const extensions::Extension& extension,
102      const base::Closure& on_finish) OVERRIDE {
103    MediaGalleriesScanResultController* controller =
104        extensions::MediaGalleriesAddScanResultsFunction::MakeDialog(
105            web_contents, extension, on_finish);
106    controller->dialog_->AcceptDialogForTesting();
107    // The dialog is closing or closed so don't return it.
108    return NULL;
109  }
110};
111
112class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest {
113 protected:
114  MediaGalleriesPlatformAppBrowserTest() : test_jpg_size_(0) {}
115  virtual ~MediaGalleriesPlatformAppBrowserTest() {}
116
117  virtual void SetUpOnMainThread() OVERRIDE {
118    PlatformAppBrowserTest::SetUpOnMainThread();
119    ensure_media_directories_exists_.reset(new EnsureMediaDirectoriesExists);
120
121    int64 file_size;
122    ASSERT_TRUE(base::GetFileSize(GetCommonDataDir().AppendASCII("test.jpg"),
123                                  &file_size));
124    test_jpg_size_ = base::checked_cast<int>(file_size);
125  }
126
127  virtual void TearDownOnMainThread() OVERRIDE {
128    ensure_media_directories_exists_.reset();
129    PlatformAppBrowserTest::TearDownOnMainThread();
130  }
131
132  bool RunMediaGalleriesTest(const std::string& extension_name) {
133    base::ListValue empty_list_value;
134    return RunMediaGalleriesTestWithArg(extension_name, empty_list_value);
135  }
136
137  bool RunMediaGalleriesTestWithArg(const std::string& extension_name,
138                                    const base::ListValue& custom_arg_value) {
139    // Copy the test data for this test into a temporary directory. Then add
140    // a common_injected.js to the temporary copy and run it.
141    const char kTestDir[] = "api_test/media_galleries/";
142    base::FilePath from_dir =
143        test_data_dir_.AppendASCII(kTestDir + extension_name);
144    from_dir = from_dir.NormalizePathSeparators();
145
146    base::ScopedTempDir temp_dir;
147    if (!temp_dir.CreateUniqueTempDir())
148      return false;
149
150    if (!base::CopyDirectory(from_dir, temp_dir.path(), true))
151      return false;
152
153    base::FilePath common_js_path(
154        GetCommonDataDir().AppendASCII("common_injected.js"));
155    base::FilePath inject_js_path(
156        temp_dir.path().AppendASCII(extension_name)
157                       .AppendASCII("common_injected.js"));
158    if (!base::CopyFile(common_js_path, inject_js_path))
159      return false;
160
161    const char* custom_arg = NULL;
162    std::string json_string;
163    if (!custom_arg_value.empty()) {
164      base::JSONWriter::Write(&custom_arg_value, &json_string);
165      custom_arg = json_string.c_str();
166    }
167
168    base::AutoReset<base::FilePath> reset(&test_data_dir_, temp_dir.path());
169    bool result = RunPlatformAppTestWithArg(extension_name, custom_arg);
170    content::RunAllPendingInMessageLoop();  // avoid race on exit in registry.
171    return result;
172  }
173
174  void AttachFakeDevice() {
175    device_id_ = StorageInfo::MakeDeviceId(
176        StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);
177
178    StorageMonitor::GetInstance()->receiver()->ProcessAttach(
179        StorageInfo(device_id_, kDevicePath, base::ASCIIToUTF16(kDeviceName),
180                    base::string16(), base::string16(), 0));
181    content::RunAllPendingInMessageLoop();
182  }
183
184  void DetachFakeDevice() {
185    StorageMonitor::GetInstance()->receiver()->ProcessDetach(device_id_);
186    content::RunAllPendingInMessageLoop();
187  }
188
189  // Called if test only wants a single gallery it creates.
190  void RemoveAllGalleries() {
191    MediaGalleriesPreferences* preferences = GetAndInitializePreferences();
192
193    // Make a copy, as the iterator would be invalidated otherwise.
194    const MediaGalleriesPrefInfoMap galleries =
195        preferences->known_galleries();
196    for (MediaGalleriesPrefInfoMap::const_iterator it = galleries.begin();
197         it != galleries.end(); ++it) {
198      preferences->ForgetGalleryById(it->first);
199    }
200  }
201
202  // This function makes a single fake gallery. This is needed to test platforms
203  // with no default media galleries, such as CHROMEOS. This fake gallery is
204  // pre-populated with a test.jpg and test.txt.
205  void MakeSingleFakeGallery(MediaGalleryPrefId* pref_id) {
206    ASSERT_FALSE(fake_gallery_temp_dir_.IsValid());
207    ASSERT_TRUE(fake_gallery_temp_dir_.CreateUniqueTempDir());
208
209    MediaGalleriesPreferences* preferences = GetAndInitializePreferences();
210
211    MediaGalleryPrefInfo gallery_info;
212    ASSERT_FALSE(preferences->LookUpGalleryByPath(fake_gallery_temp_dir_.path(),
213                                                  &gallery_info));
214    MediaGalleryPrefId id = preferences->AddGallery(
215        gallery_info.device_id,
216        gallery_info.path,
217        MediaGalleryPrefInfo::kAutoDetected,
218        gallery_info.volume_label,
219        gallery_info.vendor_name,
220        gallery_info.model_name,
221        gallery_info.total_size_in_bytes,
222        gallery_info.last_attach_time,
223        0, 0, 0);
224    if (pref_id)
225      *pref_id = id;
226
227    content::RunAllPendingInMessageLoop();
228
229    // Valid file, should show up in JS as a FileEntry.
230    AddFileToSingleFakeGallery(GetCommonDataDir().AppendASCII("test.jpg"));
231
232    // Invalid file, should not show up as a FileEntry in JS at all.
233    AddFileToSingleFakeGallery(GetCommonDataDir().AppendASCII("test.txt"));
234  }
235
236  void AddFileToSingleFakeGallery(const base::FilePath& source_path) {
237    ASSERT_TRUE(fake_gallery_temp_dir_.IsValid());
238
239    ASSERT_TRUE(base::CopyFile(
240        source_path,
241        fake_gallery_temp_dir_.path().Append(source_path.BaseName())));
242  }
243
244#if defined(OS_WIN) || defined(OS_MACOSX)
245  void PopulatePicasaTestData(const base::FilePath& picasa_app_data_root) {
246    base::FilePath picasa_database_path =
247        picasa::MakePicasaDatabasePath(picasa_app_data_root);
248    base::FilePath picasa_temp_dir_path =
249        picasa_database_path.DirName().AppendASCII(picasa::kPicasaTempDirName);
250    ASSERT_TRUE(base::CreateDirectory(picasa_database_path));
251    ASSERT_TRUE(base::CreateDirectory(picasa_temp_dir_path));
252
253    // Create fake folder directories.
254    base::FilePath folders_root =
255        ensure_media_directories_exists_->GetFakePicasaFoldersRootPath();
256    base::FilePath fake_folder_1 = folders_root.AppendASCII("folder1");
257    base::FilePath fake_folder_2 = folders_root.AppendASCII("folder2");
258    ASSERT_TRUE(base::CreateDirectory(fake_folder_1));
259    ASSERT_TRUE(base::CreateDirectory(fake_folder_2));
260
261    // Write folder and album contents.
262    picasa::WriteTestAlbumTable(
263        picasa_database_path, fake_folder_1, fake_folder_2);
264    picasa::WriteTestAlbumsImagesIndex(fake_folder_1, fake_folder_2);
265
266    base::FilePath test_jpg_path = GetCommonDataDir().AppendASCII("test.jpg");
267    ASSERT_TRUE(base::CopyFile(
268        test_jpg_path, fake_folder_1.AppendASCII("InBoth.jpg")));
269    ASSERT_TRUE(base::CopyFile(
270        test_jpg_path, fake_folder_1.AppendASCII("InSecondAlbumOnly.jpg")));
271    ASSERT_TRUE(base::CopyFile(
272        test_jpg_path, fake_folder_2.AppendASCII("InFirstAlbumOnly.jpg")));
273  }
274#endif  // defined(OS_WIN) || defined(OS_MACOSX)
275
276#if defined(OS_MACOSX)
277  void PopulateIPhotoTestData(const base::FilePath& iphoto_data_root) {
278    std::string xml_contents = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
279    "<plist version=\"1.0\">"
280    "<dict>\n"
281
282    "    <key>List of Albums</key>"
283    "    <array>\n"
284
285    "    <dict>\n"
286    "      <key>AlbumId</key>"
287    "      <integer>1</integer>"
288    "      <key>AlbumName</key>"
289    "      <string>Album1</string>"
290    "      <key>KeyList</key>\n"
291    "      <array>"
292    "      <string>1</string>"
293    "      <string>2</string>"
294    "      </array>\n"
295    "    </dict>\n"
296
297    "    <dict>\n"
298    "      <key>AlbumId</key>"
299    "      <integer>2</integer>"
300    "      <key>AlbumName</key>"
301    "      <string>Album2</string>"
302    "      <key>KeyList</key>\n"
303    "      <array>"
304    "      <string>2</string>"
305    "      </array>\n"
306    "    </dict>\n"
307
308    "    </array>\n"
309
310    "   <key>Master Image List</key>\n"
311    "   <dict>\n"
312
313    "  <key>1</key>"
314    "  <dict>\n"
315    "    <key>MediaType</key>"
316    "    <string>Image</string>"
317    "    <key>Caption</key>"
318    "    <string>caption 1</string>"
319    "    <key>GUID</key>"
320    "    <string>1</string>"
321    "    <key>ModDateAsTimerInterval</key>"
322    "    <string>386221543.0000</string>"
323    "    <key>DateAsTimerInterval</key>"
324    "    <string>386221543.0000</string>"
325    "    <key>DateAsTimerIntervalGMT</key>"
326    "    <string>385123456.00</string>"
327    "    <key>ImagePath</key>"
328    "    <string>$path1</string>"
329    "    <key>ThumbPath</key>"
330    "    <string>/thumb/path</string>\n"
331    "  </dict>\n"
332
333    "  <key>2</key>\n"
334    "  <dict>\n"
335    "    <key>MediaType</key>"
336    "    <string>Image</string>"
337    "    <key>Caption</key>"
338    "    <string>caption 2</string>"
339    "    <key>GUID</key>"
340    "    <string>2</string>"
341    "    <key>ModDateAsTimerInterval</key>"
342    "    <string>386221543.0000</string>"
343    "    <key>DateAsTimerInterval</key>"
344    "    <string>386221543.0000</string>"
345    "    <key>DateAsTimerIntervalGMT</key>"
346    "    <string>385123456.00</string>"
347    "    <key>ImagePath</key>"
348    "    <string>$path2</string>"
349    "    <key>ThumbPath</key>"
350    "    <string>/thumb/path2</string>\n"
351    "  </dict>\n"
352
353    "   </dict>\n"  // Master Image List
354
355    "</dict>\n"
356    "</plist>";
357
358    base::FilePath test_jpg_path = GetCommonDataDir().AppendASCII("test.jpg");
359    ASSERT_TRUE(base::CreateDirectory(iphoto_data_root));
360    base::FilePath first_only_jpg =
361        iphoto_data_root.AppendASCII("InFirstAlbumOnly.jpg");
362    base::FilePath in_both_jpg = iphoto_data_root.AppendASCII("InBoth.jpg");
363    ASSERT_TRUE(base::CopyFile(test_jpg_path, first_only_jpg));
364    ASSERT_TRUE(base::CopyFile(test_jpg_path, in_both_jpg));
365    ReplaceFirstSubstringAfterOffset(
366        &xml_contents, 0, std::string("$path1"), first_only_jpg.value());
367    ReplaceFirstSubstringAfterOffset(
368        &xml_contents, 0, std::string("$path2"), in_both_jpg.value());
369
370    base::FilePath album_xml = iphoto_data_root.AppendASCII("AlbumData.xml");
371    ASSERT_NE(-1, base::WriteFile(album_xml,
372                                  xml_contents.c_str(), xml_contents.size()));
373  }
374#endif  // defined(OS_MACOSX)
375
376  base::FilePath GetCommonDataDir() const {
377    return test_data_dir_.AppendASCII("api_test")
378                         .AppendASCII("media_galleries")
379                         .AppendASCII("common");
380  }
381
382  base::FilePath GetWallpaperTestDataDir() const {
383    return test_data_dir_.AppendASCII("api_test")
384                         .AppendASCII("wallpaper");
385  }
386
387  int num_galleries() const {
388    return ensure_media_directories_exists_->num_galleries();
389  }
390
391  int test_jpg_size() const { return test_jpg_size_; }
392
393  EnsureMediaDirectoriesExists* ensure_media_directories_exists() const {
394    return ensure_media_directories_exists_.get();
395  }
396
397  void InstallDoNothingFolderFinder() {
398    MediaScanManager * scan_manager =
399        g_browser_process->media_file_system_registry()->media_scan_manager();
400    scan_manager->SetMediaFolderFinderFactory(base::Bind(
401        &DoNothingMediaFolderFinder::CreateDoNothingMediaFolderFinder));
402  }
403
404  void SetRootsForFolderFinder(const std::vector<base::FilePath>& roots) {
405    MediaScanManager* scan_manager =
406        g_browser_process->media_file_system_registry()->media_scan_manager();
407    scan_manager->SetMediaFolderFinderFactory(base::Bind(
408        &MediaGalleriesPlatformAppBrowserTest::CreateMediaFolderFinderWithRoots,
409        roots));
410  }
411
412 private:
413  static MediaFolderFinder* CreateMediaFolderFinderWithRoots(
414      const std::vector<base::FilePath>& roots,
415      const MediaFolderFinder::MediaFolderFinderResultsCallback& callback) {
416    MediaFolderFinder* finder = new MediaFolderFinder(callback);
417    finder->SetRootsForTesting(roots);
418    return finder;
419  }
420
421  MediaGalleriesPreferences* GetAndInitializePreferences() {
422    MediaGalleriesPreferences* preferences =
423        g_browser_process->media_file_system_registry()->GetPreferences(
424            browser()->profile());
425    base::RunLoop runloop;
426    preferences->EnsureInitialized(runloop.QuitClosure());
427    runloop.Run();
428    return preferences;
429  }
430
431  std::string device_id_;
432  base::ScopedTempDir fake_gallery_temp_dir_;
433  int test_jpg_size_;
434  scoped_ptr<EnsureMediaDirectoriesExists> ensure_media_directories_exists_;
435};
436
437#if !defined(DISABLE_NACL)
438class MediaGalleriesPlatformAppPpapiTest
439    : public MediaGalleriesPlatformAppBrowserTest {
440 protected:
441  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
442    MediaGalleriesPlatformAppBrowserTest::SetUpCommandLine(command_line);
443    command_line->AppendSwitch(switches::kEnablePepperTesting);
444  }
445
446  virtual void SetUpOnMainThread() OVERRIDE {
447    MediaGalleriesPlatformAppBrowserTest::SetUpOnMainThread();
448
449    ASSERT_TRUE(PathService::Get(chrome::DIR_GEN_TEST_DATA, &app_dir_));
450    app_dir_ = app_dir_.AppendASCII("ppapi")
451                       .AppendASCII("tests")
452                       .AppendASCII("extensions")
453                       .AppendASCII("media_galleries")
454                       .AppendASCII("newlib");
455  }
456
457  const base::FilePath& app_dir() const {
458    return app_dir_;
459  }
460
461 private:
462  base::FilePath app_dir_;
463};
464
465IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppPpapiTest, SendFilesystem) {
466  RemoveAllGalleries();
467  MakeSingleFakeGallery(NULL);
468
469  const extensions::Extension* extension = LoadExtension(app_dir());
470  ASSERT_TRUE(extension);
471
472  extensions::ResultCatcher catcher;
473  AppLaunchParams params(browser()->profile(),
474                         extension,
475                         extensions::LAUNCH_CONTAINER_NONE,
476                         NEW_WINDOW);
477  params.command_line = *CommandLine::ForCurrentProcess();
478  OpenApplication(params);
479
480  bool result = true;
481  if (!catcher.GetNextResult()) {
482    message_ = catcher.message();
483    result = false;
484  }
485  content::RunAllPendingInMessageLoop();  // avoid race on exit in registry.
486  ASSERT_TRUE(result) << message_;
487}
488
489#endif  // !defined(DISABLE_NACL)
490
491// Test is flaky, it fails on certain bots, namely WinXP Tests(1) and Linux
492// (dbg)(1)(32).  See crbug.com/354425.
493#if defined(OS_WIN) || defined(OS_LINUX)
494#define MAYBE_MediaGalleriesNoAccess DISABLED_MediaGalleriesNoAccess
495#else
496#define MAYBE_MediaGalleriesNoAccess MediaGalleriesNoAccess
497#endif
498IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
499                       MAYBE_MediaGalleriesNoAccess) {
500  MakeSingleFakeGallery(NULL);
501
502  base::ListValue custom_args;
503  custom_args.AppendInteger(num_galleries() + 1);
504
505  ASSERT_TRUE(RunMediaGalleriesTestWithArg("no_access", custom_args))
506      << message_;
507}
508
509IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, NoGalleriesRead) {
510  ASSERT_TRUE(RunMediaGalleriesTest("no_galleries")) << message_;
511}
512
513IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
514                       NoGalleriesCopyTo) {
515  ASSERT_TRUE(RunMediaGalleriesTest("no_galleries_copy_to")) << message_;
516}
517
518// Test is flaky. crbug.com/416128
519IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
520                       DISABLED_MediaGalleriesRead) {
521  RemoveAllGalleries();
522  MakeSingleFakeGallery(NULL);
523  base::ListValue custom_args;
524  custom_args.AppendInteger(test_jpg_size());
525
526  ASSERT_TRUE(RunMediaGalleriesTestWithArg("read_access", custom_args))
527      << message_;
528}
529
530// Test is flaky, it fails on certain bots, namely WinXP Tests(1) and Linux
531// (dbg)(1)(32).  See crbug.com/354425.
532#if defined(OS_WIN) || defined(OS_LINUX)
533#define MAYBE_MediaGalleriesCopyTo DISABLED_MediaGalleriesCopyTo
534#else
535#define MAYBE_MediaGalleriesCopyTo MediaGalleriesCopyTo
536#endif
537IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
538                       MAYBE_MediaGalleriesCopyTo) {
539  RemoveAllGalleries();
540  MakeSingleFakeGallery(NULL);
541  ASSERT_TRUE(RunMediaGalleriesTest("copy_to_access")) << message_;
542}
543
544IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
545                       MediaGalleriesDelete) {
546  MakeSingleFakeGallery(NULL);
547  base::ListValue custom_args;
548  custom_args.AppendInteger(num_galleries() + 1);
549  ASSERT_TRUE(RunMediaGalleriesTestWithArg("delete_access", custom_args))
550      << message_;
551}
552
553IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
554                       MediaGalleriesAccessAttached) {
555  AttachFakeDevice();
556
557  base::ListValue custom_args;
558  custom_args.AppendInteger(num_galleries() + 1);
559  custom_args.AppendString(kDeviceName);
560
561  ASSERT_TRUE(RunMediaGalleriesTestWithArg("access_attached", custom_args))
562      << message_;
563
564  DetachFakeDevice();
565}
566
567#if defined(OS_WIN)|| defined(OS_MACOSX)
568IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
569                       PicasaDefaultLocation) {
570#if defined(OS_WIN)
571  PopulatePicasaTestData(
572      ensure_media_directories_exists()->GetFakeLocalAppDataPath());
573#elif defined(OS_MACOSX)
574  PopulatePicasaTestData(
575      ensure_media_directories_exists()->GetFakeAppDataPath());
576#endif
577
578  base::ListValue custom_args;
579  custom_args.AppendInteger(test_jpg_size());
580  ASSERT_TRUE(RunMediaGalleriesTestWithArg("picasa", custom_args)) << message_;
581}
582
583IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
584                       PicasaCustomLocation) {
585  base::ScopedTempDir custom_picasa_app_data_root;
586  ASSERT_TRUE(custom_picasa_app_data_root.CreateUniqueTempDir());
587  ensure_media_directories_exists()->SetCustomPicasaAppDataPath(
588      custom_picasa_app_data_root.path());
589  PopulatePicasaTestData(custom_picasa_app_data_root.path());
590
591  base::ListValue custom_args;
592  custom_args.AppendInteger(test_jpg_size());
593  ASSERT_TRUE(RunMediaGalleriesTestWithArg("picasa", custom_args)) << message_;
594}
595#endif  // defined(OS_WIN) || defined(OS_MACOSX)
596
597#if defined(OS_MACOSX)
598IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
599                       IPhotoTest) {
600  PopulateIPhotoTestData(
601      ensure_media_directories_exists()->GetFakeIPhotoRootPath());
602
603  base::ListValue custom_args;
604  custom_args.AppendInteger(test_jpg_size());
605  ASSERT_TRUE(RunMediaGalleriesTestWithArg("iphoto", custom_args)) << message_;
606
607  iapps::SetMacPreferencesForTesting(NULL);
608}
609#endif  // defined(OS_MACOSX)
610
611IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, CancelScan) {
612  InstallDoNothingFolderFinder();
613  ASSERT_TRUE(RunMediaGalleriesTest("cancel_scan")) << message_;
614}
615
616IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, Scan) {
617  base::ScopedTempDir scan_root;
618  ASSERT_TRUE(scan_root.CreateUniqueTempDir());
619  std::vector<base::FilePath> roots;
620  roots.push_back(scan_root.path());
621  SetRootsForFolderFinder(roots);
622
623  // Override addScanResults so that the dialog is accepted as soon as it is
624  // created.
625  ASSERT_TRUE(extensions::ExtensionFunctionDispatcher::OverrideFunction(
626      "mediaGalleries.addScanResults",
627      &TestMediaGalleriesAddScanResultsFunction::Factory));
628
629  // Add some files and directories to the scan root for testing. Only the
630  // "f" directory should be found.
631  std::string dummy_data;
632  dummy_data.resize(1);
633  ASSERT_TRUE(base::CreateDirectory(scan_root.path().AppendASCII("a/b")));
634  ASSERT_EQ(static_cast<int>(dummy_data.size()),
635            base::WriteFile(scan_root.path().AppendASCII("a/b/c.jpg"),
636                            dummy_data.c_str(), dummy_data.size()));
637  ASSERT_TRUE(base::CreateDirectory(scan_root.path().AppendASCII("a/d")));
638  dummy_data.resize(201 * 1024);  // 200k is the min size for the folder finder.
639  ASSERT_EQ(static_cast<int>(dummy_data.size()),
640            base::WriteFile(scan_root.path().AppendASCII("a/d/e.txt"),
641                            dummy_data.c_str(), dummy_data.size()));
642  ASSERT_TRUE(base::CreateDirectory(scan_root.path().AppendASCII("f")));
643  ASSERT_EQ(static_cast<int>(dummy_data.size()),
644            base::WriteFile(scan_root.path().AppendASCII("f/g.jpg"),
645                            dummy_data.c_str(), dummy_data.size()));
646
647  ASSERT_TRUE(RunMediaGalleriesTest("scan")) << message_;
648}
649
650IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, ToURL) {
651  RemoveAllGalleries();
652  MediaGalleryPrefId pref_id;
653  MakeSingleFakeGallery(&pref_id);
654
655  base::ListValue custom_args;
656  custom_args.AppendInteger(base::checked_cast<int>(pref_id));
657  custom_args.AppendString(
658      browser()->profile()->GetPath().BaseName().MaybeAsASCII());
659
660  ASSERT_TRUE(RunMediaGalleriesTestWithArg("tourl", custom_args)) << message_;
661}
662
663IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, GetMetadata) {
664  RemoveAllGalleries();
665  MakeSingleFakeGallery(NULL);
666
667  AddFileToSingleFakeGallery(media::GetTestDataFilePath("90rotation.mp4"));
668  AddFileToSingleFakeGallery(media::GetTestDataFilePath("id3_png_test.mp3"));
669  AddFileToSingleFakeGallery(GetWallpaperTestDataDir().AppendASCII("test.jpg"));
670
671  base::ListValue custom_args;
672#if defined(USE_PROPRIETARY_CODECS)
673  custom_args.AppendBoolean(true);
674#else
675  custom_args.AppendBoolean(false);
676#endif
677  ASSERT_TRUE(RunMediaGalleriesTestWithArg("media_metadata", custom_args))
678      << message_;
679}
680