1 // Copyright 2013 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.
9 #include "base/bind_helpers.h"
10 #include "base/files/file_path.h"
11 #include "base/files/file_util.h"
12 #include "base/files/scoped_temp_dir.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_vector.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/message_loop/message_loop_proxy.h"
17 #include "base/run_loop.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/time/time.h"
20 #include "chrome/browser/media_galleries/fileapi/media_file_system_backend.h"
21 #include "chrome/browser/media_galleries/fileapi/media_path_filter.h"
22 #include "chrome/browser/media_galleries/fileapi/picasa_data_provider.h"
23 #include "chrome/browser/media_galleries/fileapi/picasa_file_util.h"
24 #include "chrome/browser/media_galleries/imported_media_gallery_registry.h"
25 #include "chrome/common/media_galleries/picasa_types.h"
26 #include "chrome/common/media_galleries/pmp_constants.h"
27 #include "content/public/browser/browser_thread.h"
28 #include "content/public/test/mock_special_storage_policy.h"
29 #include "content/public/test/test_browser_thread.h"
30 #include "content/public/test/test_file_system_options.h"
31 #include "storage/browser/blob/shareable_file_reference.h"
32 #include "storage/browser/fileapi/async_file_util.h"
33 #include "storage/browser/fileapi/external_mount_points.h"
34 #include "storage/browser/fileapi/file_system_context.h"
35 #include "storage/browser/fileapi/file_system_operation_context.h"
36 #include "storage/browser/fileapi/file_system_operation_runner.h"
37 #include "storage/browser/fileapi/isolated_context.h"
38 #include "testing/gtest/include/gtest/gtest.h"
40 using storage::FileSystemOperationContext
;
41 using storage::FileSystemOperation
;
42 using storage::FileSystemURL
;
48 base::Time::Exploded test_date_exploded
= { 2013, 4, 0, 16, 0, 0, 0, 0 };
50 bool WriteJPEGHeader(const base::FilePath
& path
) {
51 const char kJpegHeader
[] = "\xFF\xD8\xFF"; // Per HTML5 specification.
52 return base::WriteFile(path
, kJpegHeader
, arraysize(kJpegHeader
)) != -1;
57 TestFolder(const std::string
& name
, const base::Time
& timestamp
,
58 const std::string
& uid
, unsigned int image_files
,
59 unsigned int non_image_files
)
61 timestamp_(timestamp
),
63 image_files_(image_files
),
64 non_image_files_(non_image_files
),
65 folder_info_("", base::Time(), "", base::FilePath()) {
69 if (!folder_dir_
.CreateUniqueTempDir())
72 folder_info_
= AlbumInfo(name_
, timestamp_
, uid_
, folder_dir_
.path());
74 for (unsigned int i
= 0; i
< image_files_
; ++i
) {
75 std::string image_filename
= base::StringPrintf("img%05d.jpg", i
);
76 image_filenames_
.insert(image_filename
);
78 base::FilePath path
= folder_dir_
.path().AppendASCII(image_filename
);
80 if (!WriteJPEGHeader(path
))
84 for (unsigned int i
= 0; i
< non_image_files_
; ++i
) {
85 base::FilePath path
= folder_dir_
.path().AppendASCII(
86 base::StringPrintf("hello%05d.txt", i
));
87 if (base::WriteFile(path
, NULL
, 0) == -1)
94 double GetVariantTimestamp() const {
95 DCHECK(!folder_dir_
.path().empty());
96 base::Time variant_epoch
= base::Time::FromLocalExploded(
97 picasa::kPmpVariantTimeEpoch
);
99 int64 microseconds_since_epoch
=
100 (folder_info_
.timestamp
- variant_epoch
).InMicroseconds();
102 return static_cast<double>(microseconds_since_epoch
) /
103 base::Time::kMicrosecondsPerDay
;
106 const std::set
<std::string
>& image_filenames() const {
107 DCHECK(!folder_dir_
.path().empty());
108 return image_filenames_
;
111 const AlbumInfo
& folder_info() const {
112 DCHECK(!folder_dir_
.path().empty());
116 const base::Time
& timestamp() const {
121 const std::string name_
;
122 const base::Time timestamp_
;
123 const std::string uid_
;
124 unsigned int image_files_
;
125 unsigned int non_image_files_
;
127 std::set
<std::string
> image_filenames_
;
129 base::ScopedTempDir folder_dir_
;
130 AlbumInfo folder_info_
;
133 void ReadDirectoryTestHelperCallback(
134 base::RunLoop
* run_loop
,
135 FileSystemOperation::FileEntryList
* contents
,
136 bool* completed
, base::File::Error error
,
137 const FileSystemOperation::FileEntryList
& file_list
,
140 *completed
= !has_more
&& error
== base::File::FILE_OK
;
141 *contents
= file_list
;
145 void ReadDirectoryTestHelper(storage::FileSystemOperationRunner
* runner
,
146 const FileSystemURL
& url
,
147 FileSystemOperation::FileEntryList
* contents
,
151 base::RunLoop run_loop
;
152 runner
->ReadDirectory(
153 url
, base::Bind(&ReadDirectoryTestHelperCallback
, &run_loop
, contents
,
158 void SynchronouslyRunOnMediaTaskRunner(const base::Closure
& closure
) {
160 MediaFileSystemBackend::MediaTaskRunner()->PostTaskAndReply(
167 void CreateSnapshotFileTestHelperCallback(
168 base::RunLoop
* run_loop
,
169 base::File::Error
* error
,
170 base::FilePath
* platform_path_result
,
171 base::File::Error result
,
172 const base::File::Info
& file_info
,
173 const base::FilePath
& platform_path
,
174 const scoped_refptr
<storage::ShareableFileReference
>& file_ref
) {
177 DCHECK(platform_path_result
);
180 *platform_path_result
= platform_path
;
186 class TestPicasaFileUtil
: public PicasaFileUtil
{
188 TestPicasaFileUtil(MediaPathFilter
* media_path_filter
,
189 PicasaDataProvider
* data_provider
)
190 : PicasaFileUtil(media_path_filter
),
191 data_provider_(data_provider
) {
193 ~TestPicasaFileUtil() override
{}
196 PicasaDataProvider
* GetDataProvider() override
{ return data_provider_
; }
198 PicasaDataProvider
* data_provider_
;
201 class TestMediaFileSystemBackend
: public MediaFileSystemBackend
{
203 TestMediaFileSystemBackend(const base::FilePath
& profile_path
,
204 PicasaFileUtil
* picasa_file_util
)
205 : MediaFileSystemBackend(profile_path
,
206 MediaFileSystemBackend::MediaTaskRunner().get()),
207 test_file_util_(picasa_file_util
) {}
209 storage::AsyncFileUtil
* GetAsyncFileUtil(
210 storage::FileSystemType type
) override
{
211 if (type
!= storage::kFileSystemTypePicasa
)
214 return test_file_util_
.get();
218 scoped_ptr
<storage::AsyncFileUtil
> test_file_util_
;
221 class PicasaFileUtilTest
: public testing::Test
{
224 : io_thread_(content::BrowserThread::IO
, &message_loop_
) {
227 void SetUp() override
{
228 ASSERT_TRUE(profile_dir_
.CreateUniqueTempDir());
229 ImportedMediaGalleryRegistry::GetInstance()->Initialize();
231 scoped_refptr
<storage::SpecialStoragePolicy
> storage_policy
=
232 new content::MockSpecialStoragePolicy();
234 SynchronouslyRunOnMediaTaskRunner(base::Bind(
235 &PicasaFileUtilTest::SetUpOnMediaTaskRunner
, base::Unretained(this)));
237 media_path_filter_
.reset(new MediaPathFilter());
239 ScopedVector
<storage::FileSystemBackend
> additional_providers
;
240 additional_providers
.push_back(new TestMediaFileSystemBackend(
242 new TestPicasaFileUtil(media_path_filter_
.get(),
243 picasa_data_provider_
.get())));
245 file_system_context_
= new storage::FileSystemContext(
246 base::MessageLoopProxy::current().get(),
247 base::MessageLoopProxy::current().get(),
248 storage::ExternalMountPoints::CreateRefCounted().get(),
249 storage_policy
.get(),
251 additional_providers
.Pass(),
252 std::vector
<storage::URLRequestAutoMountHandler
>(),
254 content::CreateAllowFileAccessOptions());
257 void TearDown() override
{
258 SynchronouslyRunOnMediaTaskRunner(
259 base::Bind(&PicasaFileUtilTest::TearDownOnMediaTaskRunner
,
260 base::Unretained(this)));
264 void SetUpOnMediaTaskRunner() {
265 picasa_data_provider_
.reset(new PicasaDataProvider(base::FilePath()));
268 void TearDownOnMediaTaskRunner() {
269 picasa_data_provider_
.reset();
272 // |test_folders| must be in alphabetical order for easy verification
273 void SetupFolders(ScopedVector
<TestFolder
>* test_folders
,
274 const std::vector
<AlbumInfo
>& albums
,
275 const AlbumImagesMap
& albums_images
) {
276 std::vector
<AlbumInfo
> folders
;
277 for (ScopedVector
<TestFolder
>::iterator it
= test_folders
->begin();
278 it
!= test_folders
->end(); ++it
) {
279 TestFolder
* test_folder
= *it
;
280 ASSERT_TRUE(test_folder
->Init());
281 folders
.push_back(test_folder
->folder_info());
284 PicasaDataProvider::UniquifyNames(albums
,
285 &picasa_data_provider_
->album_map_
);
286 PicasaDataProvider::UniquifyNames(folders
,
287 &picasa_data_provider_
->folder_map_
);
288 picasa_data_provider_
->albums_images_
= albums_images
;
289 picasa_data_provider_
->state_
=
290 PicasaDataProvider::ALBUMS_IMAGES_FRESH_STATE
;
293 void VerifyFolderDirectoryList(const ScopedVector
<TestFolder
>& test_folders
) {
294 FileSystemOperation::FileEntryList contents
;
295 FileSystemURL url
= CreateURL(kPicasaDirFolders
);
296 bool completed
= false;
297 ReadDirectoryTestHelper(operation_runner(), url
, &contents
, &completed
);
299 ASSERT_TRUE(completed
);
300 ASSERT_EQ(test_folders
.size(), contents
.size());
302 for (size_t i
= 0; i
< contents
.size(); ++i
) {
303 EXPECT_TRUE(contents
[i
].is_directory
);
305 // Because the timestamp is written out as a floating point Microsoft
306 // variant time, we only expect it to be accurate to within a second.
307 base::TimeDelta delta
= test_folders
[i
]->folder_info().timestamp
-
308 contents
[i
].last_modified_time
;
309 EXPECT_LT(delta
, base::TimeDelta::FromSeconds(1));
311 FileSystemOperation::FileEntryList folder_contents
;
312 FileSystemURL folder_url
= CreateURL(
313 std::string(kPicasaDirFolders
) + "/" +
314 base::FilePath(contents
[i
].name
).AsUTF8Unsafe());
315 bool folder_read_completed
= false;
316 ReadDirectoryTestHelper(operation_runner(), folder_url
, &folder_contents
,
317 &folder_read_completed
);
319 EXPECT_TRUE(folder_read_completed
);
321 const std::set
<std::string
>& image_filenames
=
322 test_folders
[i
]->image_filenames();
324 EXPECT_EQ(image_filenames
.size(), folder_contents
.size());
326 for (FileSystemOperation::FileEntryList::const_iterator file_it
=
327 folder_contents
.begin(); file_it
!= folder_contents
.end();
329 EXPECT_EQ(1u, image_filenames
.count(
330 base::FilePath(file_it
->name
).AsUTF8Unsafe()));
335 std::string
DateToPathString(const base::Time
& time
) {
336 return PicasaDataProvider::DateToPathString(time
);
339 void TestNonexistentDirectory(const std::string
& path
) {
340 FileSystemOperation::FileEntryList contents
;
341 FileSystemURL url
= CreateURL(path
);
342 bool completed
= false;
343 ReadDirectoryTestHelper(operation_runner(), url
, &contents
, &completed
);
345 ASSERT_FALSE(completed
);
348 void TestEmptyDirectory(const std::string
& path
) {
349 FileSystemOperation::FileEntryList contents
;
350 FileSystemURL url
= CreateURL(path
);
351 bool completed
= false;
352 ReadDirectoryTestHelper(operation_runner(), url
, &contents
, &completed
);
354 ASSERT_TRUE(completed
);
355 EXPECT_EQ(0u, contents
.size());
358 FileSystemURL
CreateURL(const std::string
& path
) const {
359 base::FilePath virtual_path
=
360 ImportedMediaGalleryRegistry::GetInstance()->ImportedRoot();
361 virtual_path
= virtual_path
.AppendASCII("picasa");
362 virtual_path
= virtual_path
.AppendASCII(path
);
363 return file_system_context_
->CreateCrackedFileSystemURL(
364 GURL("http://www.example.com"),
365 storage::kFileSystemTypePicasa
,
369 storage::FileSystemOperationRunner
* operation_runner() const {
370 return file_system_context_
->operation_runner();
373 scoped_refptr
<storage::FileSystemContext
> file_system_context() const {
374 return file_system_context_
;
378 base::MessageLoop message_loop_
;
379 content::TestBrowserThread io_thread_
;
381 base::ScopedTempDir profile_dir_
;
383 scoped_refptr
<storage::FileSystemContext
> file_system_context_
;
384 scoped_ptr
<PicasaDataProvider
> picasa_data_provider_
;
385 scoped_ptr
<MediaPathFilter
> media_path_filter_
;
387 DISALLOW_COPY_AND_ASSIGN(PicasaFileUtilTest
);
390 TEST_F(PicasaFileUtilTest
, DateFormat
) {
391 base::Time::Exploded exploded_shortmonth
= { 2013, 4, 0, 16, 0, 0, 0, 0 };
392 base::Time shortmonth
= base::Time::FromLocalExploded(exploded_shortmonth
);
394 base::Time::Exploded exploded_shortday
= { 2013, 11, 0, 3, 0, 0, 0, 0 };
395 base::Time shortday
= base::Time::FromLocalExploded(exploded_shortday
);
397 EXPECT_EQ("2013-04-16", DateToPathString(shortmonth
));
398 EXPECT_EQ("2013-11-03", DateToPathString(shortday
));
401 TEST_F(PicasaFileUtilTest
, NameDeduplication
) {
402 ScopedVector
<TestFolder
> test_folders
;
403 std::vector
<std::string
> expected_names
;
405 base::Time test_date
= base::Time::FromLocalExploded(test_date_exploded
);
406 base::Time test_date_2
= test_date
- base::TimeDelta::FromDays(1);
408 std::string test_date_string
= DateToPathString(test_date
);
409 std::string test_date_2_string
= DateToPathString(test_date_2
);
411 test_folders
.push_back(
412 new TestFolder("diff_date", test_date_2
, "uuid3", 0, 0));
413 expected_names
.push_back("diff_date " + test_date_2_string
);
415 test_folders
.push_back(
416 new TestFolder("diff_date", test_date
, "uuid2", 0, 0));
417 expected_names
.push_back("diff_date " + test_date_string
);
419 test_folders
.push_back(
420 new TestFolder("duplicate", test_date
, "uuid4", 0, 0));
421 expected_names
.push_back("duplicate " + test_date_string
+ " (1)");
423 test_folders
.push_back(
424 new TestFolder("duplicate", test_date
, "uuid5", 0, 0));
425 expected_names
.push_back("duplicate " + test_date_string
+ " (2)");
427 test_folders
.push_back(
428 new TestFolder("unique_name", test_date
, "uuid1", 0, 0));
429 expected_names
.push_back("unique_name " + test_date_string
);
431 SetupFolders(&test_folders
, std::vector
<AlbumInfo
>(), AlbumImagesMap());
433 FileSystemOperation::FileEntryList contents
;
434 FileSystemURL url
= CreateURL(kPicasaDirFolders
);
435 bool completed
= false;
436 ReadDirectoryTestHelper(operation_runner(), url
, &contents
, &completed
);
438 ASSERT_TRUE(completed
);
439 ASSERT_EQ(expected_names
.size(), contents
.size());
440 for (size_t i
= 0; i
< contents
.size(); ++i
) {
441 EXPECT_EQ(expected_names
[i
],
442 base::FilePath(contents
[i
].name
).AsUTF8Unsafe());
443 EXPECT_EQ(test_folders
[i
]->timestamp(), contents
[i
].last_modified_time
);
444 EXPECT_TRUE(contents
[i
].is_directory
);
448 TEST_F(PicasaFileUtilTest
, RootFolders
) {
449 ScopedVector
<TestFolder
> empty_folders_list
;
450 SetupFolders(&empty_folders_list
, std::vector
<AlbumInfo
>(), AlbumImagesMap());
452 FileSystemOperation::FileEntryList contents
;
453 FileSystemURL url
= CreateURL("");
454 bool completed
= false;
455 ReadDirectoryTestHelper(operation_runner(), url
, &contents
, &completed
);
457 ASSERT_TRUE(completed
);
458 ASSERT_EQ(2u, contents
.size());
460 EXPECT_TRUE(contents
.front().is_directory
);
461 EXPECT_TRUE(contents
.back().is_directory
);
463 EXPECT_EQ(0, contents
.front().size
);
464 EXPECT_EQ(0, contents
.back().size
);
466 EXPECT_EQ(FILE_PATH_LITERAL("albums"), contents
.front().name
);
467 EXPECT_EQ(FILE_PATH_LITERAL("folders"), contents
.back().name
);
470 TEST_F(PicasaFileUtilTest
, NonexistentFolder
) {
471 ScopedVector
<TestFolder
> empty_folders_list
;
472 SetupFolders(&empty_folders_list
, std::vector
<AlbumInfo
>(), AlbumImagesMap());
474 TestNonexistentDirectory(std::string(kPicasaDirFolders
) + "/foo");
475 TestNonexistentDirectory(std::string(kPicasaDirFolders
) + "/foo/bar");
476 TestNonexistentDirectory(std::string(kPicasaDirFolders
) + "/foo/bar/baz");
479 TEST_F(PicasaFileUtilTest
, FolderContentsTrivial
) {
480 ScopedVector
<TestFolder
> test_folders
;
481 base::Time test_date
= base::Time::FromLocalExploded(test_date_exploded
);
483 test_folders
.push_back(
484 new TestFolder("folder-1-empty", test_date
, "uid-empty", 0, 0));
485 test_folders
.push_back(
486 new TestFolder("folder-2-images", test_date
, "uid-images", 5, 0));
487 test_folders
.push_back(
488 new TestFolder("folder-3-nonimages", test_date
, "uid-nonimages", 0, 5));
489 test_folders
.push_back(
490 new TestFolder("folder-4-both", test_date
, "uid-both", 5, 5));
492 SetupFolders(&test_folders
, std::vector
<AlbumInfo
>(), AlbumImagesMap());
493 VerifyFolderDirectoryList(test_folders
);
496 TEST_F(PicasaFileUtilTest
, FolderWithManyFiles
) {
497 ScopedVector
<TestFolder
> test_folders
;
498 base::Time test_date
= base::Time::FromLocalExploded(test_date_exploded
);
500 test_folders
.push_back(
501 new TestFolder("folder-many-files", test_date
, "uid-both", 50, 50));
503 SetupFolders(&test_folders
, std::vector
<AlbumInfo
>(), AlbumImagesMap());
504 VerifyFolderDirectoryList(test_folders
);
507 TEST_F(PicasaFileUtilTest
, ManyFolders
) {
508 ScopedVector
<TestFolder
> test_folders
;
509 base::Time test_date
= base::Time::FromLocalExploded(test_date_exploded
);
511 for (unsigned int i
= 0; i
< 50; ++i
) {
512 base::Time date
= test_date
- base::TimeDelta::FromDays(i
);
514 test_folders
.push_back(
515 new TestFolder(base::StringPrintf("folder-%05d", i
),
517 base::StringPrintf("uid%05d", i
), i
% 5, i
% 3));
520 SetupFolders(&test_folders
, std::vector
<AlbumInfo
>(), AlbumImagesMap());
521 VerifyFolderDirectoryList(test_folders
);
524 TEST_F(PicasaFileUtilTest
, AlbumExistence
) {
525 ScopedVector
<TestFolder
> test_folders
;
526 base::Time test_date
= base::Time::FromLocalExploded(test_date_exploded
);
528 std::vector
<AlbumInfo
> albums
;
530 info
.name
= "albumname";
531 info
.uid
= "albumuid";
532 info
.timestamp
= test_date
;
533 albums
.push_back(info
);
535 AlbumImagesMap albums_images
;
536 albums_images
[info
.uid
] = AlbumImages();
538 SetupFolders(&test_folders
, albums
, albums_images
);
540 TestEmptyDirectory(std::string(kPicasaDirAlbums
) + "/albumname 2013-04-16");
541 TestNonexistentDirectory(std::string(kPicasaDirAlbums
) +
542 "/albumname 2013-04-16/toodeep");
543 TestNonexistentDirectory(std::string(kPicasaDirAlbums
) + "/wrongname");
546 TEST_F(PicasaFileUtilTest
, AlbumContents
) {
547 ScopedVector
<TestFolder
> test_folders
;
548 base::Time test_date
= base::Time::FromLocalExploded(test_date_exploded
);
550 std::vector
<AlbumInfo
> albums
;
552 info
.name
= "albumname";
553 info
.uid
= "albumuid";
554 info
.timestamp
= test_date
;
555 albums
.push_back(info
);
557 base::ScopedTempDir temp_dir
;
558 ASSERT_TRUE(temp_dir
.CreateUniqueTempDir());
560 base::FilePath image_path
= temp_dir
.path().AppendASCII("img.jpg");
561 ASSERT_TRUE(WriteJPEGHeader(image_path
));
563 AlbumImagesMap albums_images
;
564 albums_images
[info
.uid
] = AlbumImages();
565 albums_images
[info
.uid
]["mapped_name.jpg"] = image_path
;
567 SetupFolders(&test_folders
, albums
, albums_images
);
569 FileSystemOperation::FileEntryList contents
;
571 CreateURL(std::string(kPicasaDirAlbums
) + "/albumname 2013-04-16");
572 bool completed
= false;
573 ReadDirectoryTestHelper(operation_runner(), url
, &contents
, &completed
);
575 ASSERT_TRUE(completed
);
576 EXPECT_EQ(1u, contents
.size());
577 EXPECT_EQ("mapped_name.jpg",
578 base::FilePath(contents
.begin()->name
).AsUTF8Unsafe());
579 EXPECT_FALSE(contents
.begin()->is_directory
);
581 // Create a snapshot file to verify the file path.
583 base::File::Error error
;
584 base::FilePath platform_path_result
;
585 storage::FileSystemOperationRunner::SnapshotFileCallback snapshot_callback
=
586 base::Bind(&CreateSnapshotFileTestHelperCallback
,
589 &platform_path_result
);
590 operation_runner()->CreateSnapshotFile(
591 CreateURL(std::string(kPicasaDirAlbums
) +
592 "/albumname 2013-04-16/mapped_name.jpg"),
595 EXPECT_EQ(base::File::FILE_OK
, error
);
596 EXPECT_EQ(image_path
, platform_path_result
);
599 } // namespace picasa