diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/MediaLibraryExt/entry/src/main/ets/MediaBackupExtensionAbility/MediaBackupExtensionAbility.ts b/frameworks/innerkitsimpl/medialibrary_data_extension/MediaLibraryExt/entry/src/main/ets/MediaBackupExtensionAbility/MediaBackupExtensionAbility.ts index 897c7726d64676f39aaba73b21a9cf6c063fa35d..a421aa335bfa6be6ad753d9f7b4fa7f057353cf8 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/MediaLibraryExt/entry/src/main/ets/MediaBackupExtensionAbility/MediaBackupExtensionAbility.ts +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/MediaLibraryExt/entry/src/main/ets/MediaBackupExtensionAbility/MediaBackupExtensionAbility.ts @@ -10,6 +10,7 @@ const backupClonePath = '/data/storage/el2/backup/restore/storage/cloud/files/'; const documentPath = '/storage/media/local/files/Documents'; const galleryAppName = 'com.huawei.photos'; const mediaAppName = 'com.android.providers.media.module'; +const cameraAppName = 'com.huawei.camera'; const UPDATE_RESTORE : number = 0; const CLONE_RESTORE : number = 1; @@ -24,10 +25,10 @@ export default class MediaBackupExtAbility extends BackupExtensionAbility { console.time(TAG + ' RESTORE'); let path:string; if (bundleVersion.name === '0.0.0.0' && bundleVersion.code === 0) { - await mediabackup.startRestore(UPDATE_RESTORE, galleryAppName, mediaAppName); + await mediabackup.startRestore(UPDATE_RESTORE, galleryAppName, mediaAppName, cameraAppName); path = backupPath; } else { - await mediabackup.startRestore(CLONE_RESTORE, galleryAppName, mediaAppName); + await mediabackup.startRestore(CLONE_RESTORE, galleryAppName, mediaAppName, cameraAppName); path = backupClonePath; } console.timeEnd(TAG + ' RESTORE'); diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/BUILD.gn b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/BUILD.gn index 075c0bfefe6f3984906dee8d36a2da771170e77f..be39365aecb38ad953ba00e8660b1d6591e5b21e 100644 --- a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/BUILD.gn +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/BUILD.gn @@ -33,8 +33,11 @@ ohos_unittest("medialibrary_backup_test") { ] sources = [ + "${MEDIALIB_SERVICES_PATH}/media_backup_extension/src/backup_database_utils.cpp", "${MEDIALIB_SERVICES_PATH}/media_backup_extension/src/base_restore.cpp", "${MEDIALIB_SERVICES_PATH}/media_backup_extension/src/update_restore.cpp", + "./src/external_source.cpp", + "./src/gallery_source.cpp", "./src/medialibrary_backup_test.cpp", ] diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/external_source.h b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/external_source.h new file mode 100644 index 0000000000000000000000000000000000000000..456e5513f5b27bc04eb4cd6d33dbd164bd43bb5d --- /dev/null +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/external_source.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef EXTERNAL_SROUCE_H +#define EXTERNAL_SROUCE_H + +#include + +#include "result_set_utils.h" +#include "rdb_helper.h" + +namespace OHOS { +namespace Media { +class ExternalOpenCall; + +class ExternalSource { +public: + void Init(const std::string &path); + +private: + std::shared_ptr galleryStorePtr_; +}; + +class ExternalOpenCall : public NativeRdb::RdbOpenCallback { +public: + int OnCreate(NativeRdb::RdbStore &rdbStore) override; + int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; + static const string CREATE_EXTERNAL_FILES; +}; +} // namespace Media +} // namespace OHOS +#endif // EXTERNAL_SROUCE_H diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/gallery_source.h b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/gallery_source.h new file mode 100644 index 0000000000000000000000000000000000000000..66728bd150a46622b865885257c1c64c51a2ad98 --- /dev/null +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/gallery_source.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GALLERY_SROUCE_H +#define GALLERY_SROUCE_H + +#include + +#include "result_set_utils.h" +#include "rdb_helper.h" + +namespace OHOS { +namespace Media { +class GalleryOpenCall; + +class GallerySource { +public: + void Init(const std::string &path); + std::shared_ptr galleryStorePtr_; +}; + +class GalleryOpenCall : public NativeRdb::RdbOpenCallback { +public: + int OnCreate(NativeRdb::RdbStore &rdbStore) override; + int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; + static const string CREATE_GALLERY_MEDIA; + static const string CREATE_GARBAGE_ALBUM; +}; +} // namespace Media +} // namespace OHOS +#endif // GALLERY_SROUCE_H diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/medialibrary_backup_test.h b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/medialibrary_backup_test.h index df5f134e724572884ec9ac209900df39169f85bb..504b4db5691c90fb540f490fd1cdd28e698e8f23 100644 --- a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/medialibrary_backup_test.h +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/medialibrary_backup_test.h @@ -17,9 +17,13 @@ #define MEDIALIBRARY_BACKUP_TEST_H #include "gtest/gtest.h" +#include "rdb_helper.h" +#include "result_set_utils.h" namespace OHOS { namespace Media { +class PhotosOpenCall; + class MediaLibraryBackupTest : public testing::Test { public: static void SetUpTestCase(void); @@ -27,6 +31,13 @@ public: void SetUp(); void TearDown(); }; + +class PhotosOpenCall : public NativeRdb::RdbOpenCallback { +public: + int OnCreate(NativeRdb::RdbStore &rdbStore) override; + int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; + static const std::string CREATE_PHOTOS; +}; } // namespace Media } // namespace OHOS #endif // MEDIALIBRARY_BACKUP_TEST_H diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/external_source.cpp b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/external_source.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b061ecb80a20d32f9902618241c1855161ad291 --- /dev/null +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/external_source.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "external_source.h" + +namespace OHOS { +namespace Media { +// create external files +const string ExternalOpenCall::CREATE_EXTERNAL_FILES = string("CREATE TABLE IF NOT EXISTS files ") + + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, _data TEXT COLLATE NOCASE, _display_name TEXT, is_favorite INTEGER, " + + "_size INTEGER, duration INTEGER, media_type INTEGER, date_modified INTEGER, height INTEGER, width INTEGER, " + + "title TEXT, orientation INTEGER, date_added INTEGER, bucket_id TEXT, is_pending INTEGER, " + + "owner_package_name TEXT);"; + +int ExternalOpenCall::OnCreate(NativeRdb::RdbStore &store) +{ + return store.ExecuteSql(CREATE_EXTERNAL_FILES); +} + +int ExternalOpenCall::OnUpgrade(NativeRdb::RdbStore &store, int oldVersion, int newVersion) +{ + return 0; +} + +void ExternalSource::Init(const string &dbPath) +{ + NativeRdb::RdbStoreConfig config(dbPath); + ExternalOpenCall helper; + int errCode = 0; + shared_ptr store = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); + galleryStorePtr_ = store; + store->ExecuteSql(string("INSERT INTO files VALUES(7, '/storage/emulated/0/DCIM/Camera/fake_camera.jpg', ") + + "'fake_camera.jpg', 0, 2808831, null, 1, 1546937461, 2976, 3968, 'fake_camera.jpg', 0, 1699781505, " + + "-1739773001, 0, 'camera')"); + store->ExecuteSql(string("INSERT INTO files VALUES(8, '/storage/emulated/0/CTRIP/avatar/not_sync_invalid.jpg', ") + + "'not_sync_invalid.jpg', 0, 27657543, null, 1, 1546937461, 2448, 3264, 'not_sync_invalid.jpg', 0, " + + "1699781529, 876554266, 0, 'camera')"); + store->ExecuteSql(string("INSERT INTO files VALUES(9, ") + + "'/storage/emulated/0/MicroMsg/WeiXin/not_sync_valid.jpg', 'not_sync_valid.jpg', 0, 3503265, null, 1, " + + "1546937461, 2976, 3968, 'not_sync_valid.jpg', 0, 1699781529, 876554266, 0, 'camera')"); +} +} // namespace Media +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/gallery_source.cpp b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/gallery_source.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a67e8d79d808e3e15f84d0eb4faff3aa124a85c8 --- /dev/null +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/gallery_source.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gallery_source.h" + +namespace OHOS { +namespace Media { +const string GalleryOpenCall::CREATE_GALLERY_MEDIA = string("CREATE TABLE IF NOT EXISTS gallery_media ") + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, local_media_id INTEGER, _data TEXT COLLATE NOCASE," + + " _display_name TEXT, description TEXT, is_hw_favorite INTEGER, _size INTEGER, recycledTime INTEGER," + + " duration INTEGER, media_type INTEGER, showDateToken INTEGER, date_modified INTEGER, height INTEGER, " + + " width INTEGER, title TEXT, orientation INTEGER, storage_id INTEGER, relative_bucket_id TEXT, " + + " bucket_id TEXT, recycleFlag INTEGER);"; + +const string GalleryOpenCall::CREATE_GARBAGE_ALBUM = string("CREATE TABLE IF NOT EXISTS garbage_album") + + "(app_name TEXT, cache_dir TEXT, nick_name TEXT, nick_dir TEXT, type INTEGER, relative_bucket_id TEXT);"; + +int GalleryOpenCall::OnCreate(NativeRdb::RdbStore &store) +{ + store.ExecuteSql(CREATE_GALLERY_MEDIA); + return store.ExecuteSql(CREATE_GARBAGE_ALBUM); +} + +int GalleryOpenCall::OnUpgrade(NativeRdb::RdbStore &store, int oldVersion, int newVersion) +{ + return 0; +} + +void GallerySource::Init(const string &dbPath) +{ + NativeRdb::RdbStoreConfig config(dbPath); + GalleryOpenCall helper; + int errCode = 0; + shared_ptr store = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); + galleryStorePtr_ = store; + store->ExecuteSql(string("INSERT INTO gallery_media VALUES(1, 1, ") + + "'/storage/emulated/0/tencent/MicroMsg/WeiXin/fake_wechat.jpg', 'fake_wechat.jpg', 'fake_wechat', " + + " null, 2419880, 0, 0, 1, 1432973383179, 1432973383, 2976, 3968, 'fake_wechat', 0, 65537, -1803300197, " + " -924335728, 0)"); + store->ExecuteSql(string("INSERT INTO gallery_media VALUES(2, 2, '/storage/emulated/0/Pictures/favorite.jpg', ") + + "'favorite.jpg', 'favorite', 1, 7440437, 0, 0, 1, 1495957457427, 15464937461, 3840, 5120, " + + "'favorite', 0, 65537, 218866788, -1617409521, 0)"); + store->ExecuteSql(string("INSERT INTO gallery_media VALUES(3, -4, ") + + "'/storage/emulated/0/Pictures/hiddenAlbum/bins/0/xxx','hidden.jpg', 'hidden', null, 2716337, 0, 0, 1, " + + "1495961420646, 1546937461, 2976, 3968, 'hidden', 0, 65537, 218866788, 1385117028, null)"); + store->ExecuteSql(string("INSERT INTO gallery_media VALUES(4, 4, ") + + "'/storage/emulated/0/Pictures/.Gallery2/recycle/bins/0/xx', 'trashed.jpg', 'trashed', null, 2454477, " + + "1698397634260, 0, 1, 1495959683996, 1546937461, 2976, 3968, 'trashed', 0, 65537, 218866788, -1739773001, 2)"); + store->ExecuteSql(string("INSERT INTO gallery_media VALUES(5, 5, ") + + "'/storage/emulated/0/Pictures/orientation.jpg', 'orientation.jpg', 'orientation', null, 2781577, 0, 0," + + " 1, 1495962070277, 1698397638, 2448, 3264, 'orientation', 270, 65537, 218866788, -1617409521, 0)"); + store->ExecuteSql(string("INSERT INTO gallery_media VALUES(6, 6, ") + + "'/storage/emulated/0/BaiduMap/cache/fake_garbage_baidu.jpg', 'fake_garbage_baidu.jpg', " + + "'fake_garbage_baidu', null, 2160867, 0, 0, 1, 1495954569032, 1546937461, 2976, 3968, " + + "'fake_garbage_baidu', 0, 65537, 1151084355, -1617409521, 0)"); + store->ExecuteSql(string("INSERT INTO garbage_album VALUES('baidu', '/BaiduMap/cache', ") + + "null, null, 1, 1151084355);"); + store->ExecuteSql(string("INSERT INTO garbage_album VALUES('ctrip', '/CTRIP/avatar', ") + + "null, null, 1, -1457303569);"); + store->ExecuteSql("INSERT INTO garbage_album VALUES(null, null, 'wechat', '/tencent/MicroMsg/WeiXin', 0, null);"); +} +} // namespace Media +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/medialibrary_backup_test.cpp b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/medialibrary_backup_test.cpp index 470f51099485e1e97e3431d5ad3c3c8609c3be8e..843f66e2c5907a47a754424b56f7c6e770078738 100644 --- a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/medialibrary_backup_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/medialibrary_backup_test.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,9 +14,12 @@ */ #include "medialibrary_backup_test.h" + +#include "backup_database_utils.h" +#include "external_source.h" +#include "gallery_source.h" #include "media_log.h" #include "update_restore.h" -#include "result_set_utils.h" using namespace std; using namespace OHOS; @@ -27,8 +30,9 @@ namespace OHOS { namespace Media { const std::string TEST_ORIGIN_PATH = "/data/test/backup/db"; const std::string TEST_UPDATE_FILE_DIR = "/data/test/backup/file"; -const std::string GALLERY_APP_NAME = "photos"; -const std::string MEDIA_APP_NAME = "mediaprovider"; +const std::string GALLERY_APP_NAME = "gallery"; +const std::string MEDIA_APP_NAME = "external"; +const std::string CAMERA_APP_NAME = "camera"; const std::string MEDIA_LIBRARY_APP_NAME = "medialibrary"; const int EXPECTED_NUM = 5; @@ -38,41 +42,6 @@ const std::string EXPECTED_USER_COMMENT = "fake_wechat"; const int64_t EXPECTED_DATE_ADDED = 1432973383; const int64_t EXPECTED_DATE_TAKEN = 1432973383; -class GalleryMediaOpenCall : public NativeRdb::RdbOpenCallback { -public: - int OnCreate(NativeRdb::RdbStore &rdbStore) override; - int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; - static const string CREATE_GALLERY_MEDIA; - static const string CREATE_GARBAGE_ALBUM; -}; - -const string GalleryMediaOpenCall::CREATE_GALLERY_MEDIA = string("CREATE TABLE IF NOT EXISTS gallery_media ") + - " (id INTEGER PRIMARY KEY AUTOINCREMENT, local_media_id INTEGER, _data TEXT COLLATE NOCASE," + - " _display_name TEXT, description TEXT, is_hw_favorite INTEGER, _size INTEGER, recycledTime INTEGER," + - " duration INTEGER, media_type INTEGER, showDateToken INTEGER, date_modified INTEGER, height INTEGER, " + - " width INTEGER, title TEXT, orientation INTEGER, storage_id INTEGER, relative_bucket_id TEXT);"; - -const string GalleryMediaOpenCall::CREATE_GARBAGE_ALBUM = string("CREATE TABLE IF NOT EXISTS garbage_album") + - "(app_name TEXT, cache_dir TEXT, nick_name TEXT, nick_dir TEXT, type INTEGER, relative_bucket_id TEXT);"; - -int GalleryMediaOpenCall::OnCreate(RdbStore &store) -{ - store.ExecuteSql(CREATE_GALLERY_MEDIA); - return store.ExecuteSql(CREATE_GARBAGE_ALBUM); -} - -int GalleryMediaOpenCall::OnUpgrade(RdbStore &store, int oldVersion, int newVersion) -{ - return 0; -} - -class PhotosOpenCall : public NativeRdb::RdbOpenCallback { -public: - int OnCreate(NativeRdb::RdbStore &rdbStore) override; - int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; - static const string CREATE_PHOTOS; -}; - const string PhotosOpenCall::CREATE_PHOTOS = string("CREATE TABLE IF NOT EXISTS Photos ") + " (file_id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT, title TEXT, display_name TEXT, size BIGINT," + " media_type INT, date_added BIGINT, date_taken BIGINT, duration INT, is_favorite INT default 0, " + @@ -89,55 +58,53 @@ int PhotosOpenCall::OnUpgrade(RdbStore &store, int oldVersion, int newVersion) return 0; } -shared_ptr galleryStorePtr = nullptr; shared_ptr photosStorePtr = nullptr; +std::unique_ptr restoreService = nullptr; -void InitGalleryDB() -{ - const string dbPath = TEST_ORIGIN_PATH + "/" + GALLERY_APP_NAME + "/ce/databases/gallery.db"; - NativeRdb::RdbStoreConfig config(dbPath); - GalleryMediaOpenCall helper; - int errCode = 0; - shared_ptr store = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); - galleryStorePtr = store; - store->ExecuteSql(string("INSERT INTO gallery_media VALUES(1, 1, ") + - "'/storage/emulated/0/tencent/MicroMsg/WeiXin/fake_wechat.jpg', 'fake_wechat.jpg', 'fake_wechat', " + - " null, 2419880, 0, 0, 1, 1432973383179, 1432973383, 2976, 3968, 'fake_wechat', 0, 65537, -1803300197)"); - store->ExecuteSql(string("INSERT INTO gallery_media VALUES(2, 2, '/storage/emulated/0/Pictures/favorite.jpg', ") + - "'favorite.jpg', 'favorite', 1, 7440437, 0, 0, 1, 1495957457427, 15464937461, 3840, 5120, " + - "'favorite', 0, 65537, 218866788)"); - store->ExecuteSql(string("INSERT INTO gallery_media VALUES(3, -4, ") + - "'/storage/emulated/0/Pictures/hiddenAlbum/bins/0/xxx','hidden.jpg', 'hidden', null, 2716337, 0, 0, 1, " + - "1495961420646, 1546937461, 2976, 3968, 'hidden', 0, 65537, 218866788)"); - store->ExecuteSql(string("INSERT INTO gallery_media VALUES(4, 4, ") + - "'/storage/emulated/0/Pictures/.Gallery2/recycle/bins/0/xx', 'trashed.jpg', 'trashed', null, 2454477, " + - "1698397634260, 0, 1, 1495959683996, 1546937461, 2976, 3968, 'trashed', 0, 65537, 218866788)"); - store->ExecuteSql(string("INSERT INTO gallery_media VALUES(5, 5, ") + - "'/storage/emulated/0/Pictures/orientation.jpg', 'orientation.jpg', 'orientation', null, 2781577, 0, 0," + - " 1, 1495962070277, 1698397638, 2448, 3264, 'orientation', 270, 65537, 218866788)"); - store->ExecuteSql(string("INSERT INTO gallery_media VALUES(6, 6, ") + - "'/storage/emulated/0/BaiduMap/cache/fake_garbage_baidu.jpg', 'fake_garbage_baidu.jpg', " + - "'fake_garbage_baidu', null, 2160867, 0, 0, 1, 1495954569032, 1546937461, 2976, 3968, " + - "'fake_garbage_baidu', 0, 65537, 1151084355)"); - store->ExecuteSql(string("INSERT INTO garbage_album VALUES('baidu', '/BaiduMap/cache', ") + - "null, null, 1, 1151084355);"); - store->ExecuteSql("INSERT INTO garbage_album VALUES(null, null, 'wechat', '/tencent/MicroMsg/WeiXin', 0, null);"); -} - -void InitMediaDB() +void Init(GallerySource &gallerySource, ExternalSource &externalSource) { + MEDIA_INFO_LOG("start init galleryDb"); + const string galleryDbPath = TEST_ORIGIN_PATH + "/" + GALLERY_APP_NAME + "/ce/databases/gallery.db"; + gallerySource.Init(galleryDbPath); + MEDIA_INFO_LOG("end init galleryDb"); + MEDIA_INFO_LOG("start init externalDb"); + const string externalDbPath = TEST_ORIGIN_PATH + "/" + MEDIA_APP_NAME + "/ce/databases/external.db"; + externalSource.Init(externalDbPath); + MEDIA_INFO_LOG("end init externalDb"); const string dbPath = TEST_ORIGIN_PATH + "/" + MEDIA_LIBRARY_APP_NAME + "/ce/databases/media_library.db"; NativeRdb::RdbStoreConfig config(dbPath); PhotosOpenCall helper; int errCode = 0; shared_ptr store = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); photosStorePtr = store; - std::unique_ptr restoreService = std::make_unique(GALLERY_APP_NAME, MEDIA_APP_NAME); + restoreService = std::make_unique(GALLERY_APP_NAME, MEDIA_APP_NAME, CAMERA_APP_NAME); restoreService->Init(TEST_ORIGIN_PATH, TEST_UPDATE_FILE_DIR, false); - std::vector fileInfos = restoreService -> QueryFileInfos(0); restoreService -> InitGarbageAlbum(); +} + +void RestoreFromGallery() +{ + std::vector fileInfos = restoreService -> QueryFileInfos(0); + for (size_t i = 0; i < fileInfos.size(); i++) { + const NativeRdb::ValuesBucket values = restoreService -> GetInsertValue(fileInfos[i], TEST_ORIGIN_PATH, + SourceType::GALLERY); + int64_t rowNum = 0; + if (photosStorePtr -> Insert(rowNum, "Photos", values) != E_OK) { + MEDIA_ERR_LOG("InsertSql failed, filePath = %{private}s", fileInfos[i].filePath.c_str()); + } + } +} + +void RestoreFromExternal(GallerySource &gallerySource, bool isCamera) +{ + MEDIA_INFO_LOG("start restore from %{public}s", (isCamera ? "camera" : "others")); + int32_t maxId = BackupDatabaseUtils::QueryInt(gallerySource.galleryStorePtr_, isCamera ? + QUERY_MAX_ID_CAMERA_SCREENSHOT : QUERY_MAX_ID_OTHERS, MAX_ID); + int32_t type = isCamera ? SourceType::EXTERNAL_CAMERA : SourceType::EXTERNAL_OTHERS; + std::vector fileInfos = restoreService -> QueryFileInfosFromExternal(0, maxId, isCamera); for (size_t i = 0; i < fileInfos.size(); i++) { - const NativeRdb::ValuesBucket values = restoreService -> GetInsertValue(fileInfos[i], TEST_ORIGIN_PATH); + const NativeRdb::ValuesBucket values = restoreService -> GetInsertValue(fileInfos[i], TEST_ORIGIN_PATH, + type); int64_t rowNum = 0; if (photosStorePtr -> Insert(rowNum, "Photos", values) != E_OK) { MEDIA_ERR_LOG("InsertSql failed, filePath = %{private}s", fileInfos[i].filePath.c_str()); @@ -148,8 +115,12 @@ void InitMediaDB() void MediaLibraryBackupTest::SetUpTestCase(void) { MEDIA_INFO_LOG("SetUpTestCase"); - InitGalleryDB(); - InitMediaDB(); + GallerySource gallerySource; + ExternalSource externalSource; + Init(gallerySource, externalSource); + RestoreFromGallery(); + RestoreFromExternal(gallerySource, true); + RestoreFromExternal(gallerySource, false); } void MediaLibraryBackupTest::TearDownTestCase(void) @@ -165,7 +136,8 @@ void MediaLibraryBackupTest::TearDown(void) {} HWTEST_F(MediaLibraryBackupTest, medialib_backup_test_init, TestSize.Level0) { MEDIA_INFO_LOG("medialib_backup_test_init start"); - std::unique_ptr restoreService = std::make_unique(GALLERY_APP_NAME, MEDIA_APP_NAME); + std::unique_ptr restoreService = std::make_unique(GALLERY_APP_NAME, MEDIA_APP_NAME, + CAMERA_APP_NAME); int32_t result = restoreService->Init(TEST_ORIGIN_PATH, TEST_UPDATE_FILE_DIR, false); EXPECT_EQ(result, 0); MEDIA_INFO_LOG("medialib_backup_test_init end"); @@ -174,7 +146,8 @@ HWTEST_F(MediaLibraryBackupTest, medialib_backup_test_init, TestSize.Level0) HWTEST_F(MediaLibraryBackupTest, medialib_backup_test_query_total_number, TestSize.Level0) { MEDIA_INFO_LOG("medialib_backup_test_query_total_number start"); - std::unique_ptr restoreService = std::make_unique(GALLERY_APP_NAME, MEDIA_APP_NAME); + std::unique_ptr restoreService = std::make_unique(GALLERY_APP_NAME, MEDIA_APP_NAME, + CAMERA_APP_NAME); restoreService->Init(TEST_ORIGIN_PATH, TEST_UPDATE_FILE_DIR, false); int32_t number = restoreService -> QueryTotalNumber(); MEDIA_INFO_LOG("medialib_backup_test_query_total_number %{public}d", number); @@ -277,5 +250,26 @@ HWTEST_F(MediaLibraryBackupTest, medialib_backup_test_valid_date_taken, TestSize EXPECT_EQ(dateTaken, EXPECTED_DATE_TAKEN); MEDIA_INFO_LOG("medialib_backup_test_valid_date_taken end"); } + +HWTEST_F(MediaLibraryBackupTest, medialib_backup_test_not_sync_valid, TestSize.Level0) +{ + MEDIA_INFO_LOG("medialib_backup_test_not_sync_valid start"); + std::string queryNotSyncValid = "SELECT file_id, date_taken from Photos where display_name ='not_sync_valid.jpg'"; + auto resultSet = photosStorePtr -> QuerySql(queryNotSyncValid); + ASSERT_FALSE(resultSet == nullptr); + ASSERT_TRUE(resultSet -> GoToNextRow() == NativeRdb::E_OK); + MEDIA_INFO_LOG("medialib_backup_test_not_sync_valid end"); +} + +HWTEST_F(MediaLibraryBackupTest, medialib_backup_test_not_sync_invalid, TestSize.Level0) +{ + MEDIA_INFO_LOG("medialib_backup_test_not_sync_invalid start"); + std::string queryNotSyncInvalid = + "SELECT file_id, date_taken from Photos where display_name ='not_sync_invalid.jpg'"; + auto resultSet = photosStorePtr -> QuerySql(queryNotSyncInvalid); + ASSERT_FALSE(resultSet == nullptr); + ASSERT_FALSE(resultSet -> GoToNextRow() == NativeRdb::E_OK); + MEDIA_INFO_LOG("medialib_backup_test_not_sync_invalid end"); +} } // namespace Media } // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/unittest/resources/ohos_test.xml b/frameworks/innerkitsimpl/test/unittest/resources/ohos_test.xml index 580a65c229f669e76dca93295e62c0fd90594a0a..4b0765780493a572d155fbb60ef44b5fd444dedc 100644 --- a/frameworks/innerkitsimpl/test/unittest/resources/ohos_test.xml +++ b/frameworks/innerkitsimpl/test/unittest/resources/ohos_test.xml @@ -95,8 +95,9 @@ \ No newline at end of file diff --git a/frameworks/services/media_backup_extension/BUILD.gn b/frameworks/services/media_backup_extension/BUILD.gn index 201781078c2d7d7ad064d7b9e746e3828255bc5c..0be0798dc1b83e5cffb384a036e6c7878cf85627 100644 --- a/frameworks/services/media_backup_extension/BUILD.gn +++ b/frameworks/services/media_backup_extension/BUILD.gn @@ -29,6 +29,7 @@ ohos_shared_library("mediabackup") { ] sources = [ + "./src/backup_database_utils.cpp", "./src/backup_restore_service.cpp", "./src/base_restore.cpp", "./src/clone_restore.cpp", diff --git a/frameworks/services/media_backup_extension/include/backup_defines.h b/frameworks/services/media_backup_extension/include/backup_const.h similarity index 45% rename from frameworks/services/media_backup_extension/include/backup_defines.h rename to frameworks/services/media_backup_extension/include/backup_const.h index cd82ad851f429d97a03493978e2fc045af321d38..c0bf7996328fe00e6723a0b193bda9d6b4430493 100644 --- a/frameworks/services/media_backup_extension/include/backup_defines.h +++ b/frameworks/services/media_backup_extension/include/backup_const.h @@ -50,6 +50,30 @@ const std::string GALLERY_HEIGHT = "height"; const std::string GALLERY_WIDTH = "width"; const std::string GALLERY_ORIENTATION = "orientation"; +// external column +const std::string IS_FAVORITE = "is_favorite"; +const std::string DATE_MODIFIED = "date_modified"; +const std::string DATE_ADDED = "date_added"; + +// custom column +const std::string COUNT = "count"; +const std::string MAX_ID = "max_id"; + +constexpr int32_t INDEX_TYPE = 0; +constexpr int32_t INDEX_CACHE_DIR = 1; +constexpr int32_t INDEX_NICK_DIR = 2; +constexpr int32_t INDEX_NICK_NAME = 3; + +constexpr int32_t NICK = 0; +constexpr int32_t CACHE = 1; + +enum SourceType { + GALLERY = 0, + EXTERNAL_CAMERA, + EXTERNAL_OTHERS, + PHOTOS, +}; + struct FileInfo { std::string filePath; std::string displayName; @@ -68,6 +92,47 @@ struct FileInfo { int64_t dateAdded {0}; int32_t orientation {0}; }; + +// sql for external +const std::string QUERY_FILE_COLUMN = "SELECT _id, " + GALLERY_FILE_DATA + ", " + GALLERY_DISPLAY_NAME + ", " + + IS_FAVORITE + ", " + GALLERY_FILE_SIZE + ", " + GALLERY_DURATION + ", " + GALLERY_MEDIA_TYPE + ", " + + DATE_MODIFIED + ", " + GALLERY_HEIGHT + ", " + GALLERY_WIDTH + ", " + GALLERY_TITLE + ", " + GALLERY_ORIENTATION + + ", " + DATE_ADDED + " FROM files WHERE "; + +const std::string IN_CAMERA = " bucket_id IN (-1739773001, 0, 1028075469, 0) AND \ + ((is_pending = 0) OR (media_type = 1 AND owner_package_name = '"; + +const std::string NOT_IN_CAMERA = " bucket_id NOT IN (-1739773001, 0, 1028075469, 0 ) AND is_pending = 0"; + +const std::string QUERY_NOT_SYNC = " _id < 1000000000 AND media_type IN (1, 3) "; + +const std::string COMPARE_ID = " _id > "; + +const std::string QUERY_COUNT_FROM_FILES = "SELECT count(1) AS count FROM files WHERE"; + +// sql for gallery +const std::string QUERY_GARBAGE_ALBUM = "SELECT type, cache_dir, nick_dir, nick_name FROM garbage_album"; + +const std::string QUERY_MAX_ID_CAMERA_SCREENSHOT = "SELECT max(local_media_id) AS max_id FROM gallery_media \ + WHERE local_media_id > 0 AND bucket_id IN (-1739773001, 0, 1028075469, 0) AND \ + (recycleFlag NOT IN (2, -1, 1, -2, -4) OR recycleFlag IS NULL) AND \ + (storage_id IN (0, 65537) or storage_id IS NULL)"; + +const std::string QUERY_MAX_ID_OTHERS = "SELECT max(local_media_id) AS max_id FROM gallery_media \ + WHERE local_media_id > 0 AND bucket_id NOT IN (-1739773001, 0, 1028075469, 0) AND \ + (recycleFlag NOT IN (2, -1, 1, -2, -4) OR recycleFlag IS NULL) AND \ + (storage_id IN (0, 65537) or storage_id IS NULL)"; + +const std::string QUERY_GALLERY_COUNT = "SELECT count(1) AS count FROM gallery_media \ + WHERE (local_media_id != -1) AND (storage_id IN (0, 65537)) AND relative_bucket_id NOT IN ( \ + SELECT DISTINCT relative_bucket_id FROM garbage_album WHERE type = 1)"; + +const std::string QUERY_ALL_PHOTOS = "SELECT " + GALLERY_LOCAL_MEDIA_ID + "," + GALLERY_FILE_DATA + "," + + GALLERY_DISPLAY_NAME + "," + GALLERY_DESCRIPTION + "," + GALLERY_IS_FAVORITE + "," + GALLERY_RECYCLED_TIME + + "," + GALLERY_FILE_SIZE + "," + GALLERY_DURATION + "," + GALLERY_MEDIA_TYPE + "," + GALLERY_SHOW_DATE_TOKEN + "," + + GALLERY_HEIGHT + "," + GALLERY_WIDTH + "," + GALLERY_TITLE + ", " + GALLERY_ORIENTATION + " FROM gallery_media \ + WHERE (local_media_id != -1) AND (storage_id IN (0, 65537)) AND relative_bucket_id NOT IN ( \ + SELECT DISTINCT relative_bucket_id FROM garbage_album WHERE type = 1) ORDER BY showDateToken ASC "; } // namespace Media } // namespace OHOS diff --git a/frameworks/services/media_backup_extension/include/backup_database_utils.h b/frameworks/services/media_backup_extension/include/backup_database_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0265fdbbaf13b22fa6bfa43416376041135e1109 --- /dev/null +++ b/frameworks/services/media_backup_extension/include/backup_database_utils.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BACKUP_DATABASE_UTILS_H +#define BACKUP_DATABASE_UTILS_H + +#include + +#include "rdb_helper.h" +#include "result_set.h" + +namespace OHOS { +namespace Media { +class BackupDatabaseUtils { +public: + static int32_t QueryInt(std::shared_ptr rdbStore, const std::string &sql, + const std::string &column); +}; +} // namespace Media +} // namespace OHOS + +#endif // BACKUP_DATABASE_UTILS_H \ No newline at end of file diff --git a/frameworks/services/media_backup_extension/include/backup_restore_service.h b/frameworks/services/media_backup_extension/include/backup_restore_service.h index 9de83f7cb2a3603fd0f512e6052172ceb0a4e194..fbc38e2f78d3884e289e70f9f4dc78c78b118edc 100644 --- a/frameworks/services/media_backup_extension/include/backup_restore_service.h +++ b/frameworks/services/media_backup_extension/include/backup_restore_service.h @@ -24,7 +24,8 @@ class BackupRestoreService { public: virtual ~BackupRestoreService() = default; static BackupRestoreService &GetInstance(void); - void StartRestore(int32_t sceneCode, const std::string &galleryAppName, const std::string &mediaAppName); + void StartRestore(int32_t sceneCode, const std::string &galleryAppName, const std::string &mediaAppName, + const std::string &cameraAppName); private: BackupRestoreService() = default; diff --git a/frameworks/services/media_backup_extension/include/base_restore.h b/frameworks/services/media_backup_extension/include/base_restore.h index aa0565bc9535579fd5f87c804ba594d3a9d39314..48046302aabb0fbb514ef5abd587a3880b1f38e9 100644 --- a/frameworks/services/media_backup_extension/include/base_restore.h +++ b/frameworks/services/media_backup_extension/include/base_restore.h @@ -16,7 +16,7 @@ #ifndef OHOS_MEDIA_BASE_RESTORE_H #define OHOS_MEDIA_BASE_RESTORE_H -#include "backup_defines.h" +#include "backup_const.h" #include "rdb_helper.h" #include "result_set.h" @@ -30,7 +30,8 @@ public: virtual int32_t Init(const std::string &orignPath, const std::string &updatePath, bool isUpdate) = 0; virtual int32_t QueryTotalNumber(void) = 0; virtual std::vector QueryFileInfos(int32_t offset) = 0; - virtual NativeRdb::ValuesBucket GetInsertValue(const FileInfo &fileInfo, const std::string &newPath) const; + virtual NativeRdb::ValuesBucket GetInsertValue(const FileInfo &fileInfo, const std::string &newPath, + int32_t sourceType) const; protected: int32_t Init(void); @@ -44,7 +45,7 @@ protected: int32_t MoveFile(const std::string &srcFile, const std::string &dstFile) const; std::shared_ptr QuerySql(const std::string &sql, const std::vector &selectionArgs = std::vector()) const; - void InsertPhoto(int32_t sceneCode, const std::vector &fileInfos) const; + void InsertPhoto(int32_t sceneCode, const std::vector &fileInfos, int32_t sourceType) const; bool ConvertPathToRealPath(const std::string &srcPath, const std::string &prefix, std::string &newPath, std::string &relativePath); bool IsSameFile(const FileInfo &fileInfo) const; diff --git a/frameworks/services/media_backup_extension/include/medialibrary_backup_napi.h b/frameworks/services/media_backup_extension/include/medialibrary_backup_napi.h index 0c15f2ccfdcf87b20a857023e0ffc7b00701e393..777655b774d6033ad191489297cfbc934247d14c 100644 --- a/frameworks/services/media_backup_extension/include/medialibrary_backup_napi.h +++ b/frameworks/services/media_backup_extension/include/medialibrary_backup_napi.h @@ -22,7 +22,6 @@ #include "napi/native_node_api.h" #include "napi_error.h" #include "napi_remote_object.h" -#include "backup_defines.h" namespace OHOS { namespace Media { diff --git a/frameworks/services/media_backup_extension/include/update_restore.h b/frameworks/services/media_backup_extension/include/update_restore.h index 0bbccdbb6741126e589675c953ae94307482c5d5..16b3c6b5bdb5c485776a4f29ca0966d3cd7850ab 100644 --- a/frameworks/services/media_backup_extension/include/update_restore.h +++ b/frameworks/services/media_backup_extension/include/update_restore.h @@ -22,27 +22,39 @@ namespace OHOS { namespace Media { class UpdateRestore : public BaseRestore { public: - UpdateRestore(const std::string &galleryAppName, const std::string &mediaAppName); + UpdateRestore(const std::string &galleryAppName, const std::string &mediaAppName, const std::string &cameraAppName); virtual ~UpdateRestore() = default; int32_t Init(const std::string &orignPath, const std::string &updatePath, bool isUpdate) override; int32_t QueryTotalNumber(void) override; std::vector QueryFileInfos(int32_t offset) override; int32_t InitGarbageAlbum(); - NativeRdb::ValuesBucket GetInsertValue(const FileInfo &fileInfo, const std::string &newPath) const override; + NativeRdb::ValuesBucket GetInsertValue(const FileInfo &fileInfo, const std::string &newPath, + int32_t sourceType) const override; + std::vector QueryFileInfosFromExternal(int32_t offset, int32_t maxId, bool isCamera); + int32_t QueryNotSyncTotalNumber(int32_t offset, bool isCamera); private: void RestorePhoto(void) override; void HandleRestData(void) override; bool ParseResultSet(const std::shared_ptr &resultSet, FileInfo &info) override; + int32_t InitOldDb(const std::string &dbName, const std::string &dbPath, const std::string &bundleName, + std::shared_ptr &rdbStore); + void RestoreFromGallery(); + void RestoreFromExternal(bool isCamera); + bool IsValidDir(const std::string &path); private: std::shared_ptr galleryRdb_; + std::shared_ptr externalRdb_; std::string filePath_; - std::string dbPath_; + std::string galleryDbPath_; + std::string externalDbPath_; std::string appDataPath_; std::string galleryAppName_; std::string mediaAppName_; - std::unordered_map garbageMap_; + std::string cameraAppName_; + std::set cacheSet_; + std::unordered_map nickMap_; }; } // namespace Media } // namespace OHOS diff --git a/frameworks/services/media_backup_extension/src/backup_database_utils.cpp b/frameworks/services/media_backup_extension/src/backup_database_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..20e649da652c8687c25f4a7bf395eb26f67fb84d --- /dev/null +++ b/frameworks/services/media_backup_extension/src/backup_database_utils.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "backup_database_utils.h" + +#include "backup_const.h" +#include "media_log.h" +#include "result_set_utils.h" + +namespace OHOS { +namespace Media { +int32_t BackupDatabaseUtils::QueryInt(std::shared_ptr rdbStore, const std::string &sql, + const std::string &column) +{ + if (rdbStore == nullptr) { + MEDIA_ERR_LOG("rdb_ is nullptr, Maybe init failed."); + return 0; + } + auto resultSet = rdbStore->QuerySql(sql); + if (resultSet == nullptr || resultSet->GoToFirstRow() != NativeRdb::E_OK) { + return 0; + } + int32_t result = GetInt32Val(column, resultSet); + return result; +} +} // namespace Media +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/services/media_backup_extension/src/backup_restore_service.cpp b/frameworks/services/media_backup_extension/src/backup_restore_service.cpp index cc0cede932bed76a7c29378bc900394abaf4fee1..d47dc4632cea4642f4c353fe12136a0579525d66 100644 --- a/frameworks/services/media_backup_extension/src/backup_restore_service.cpp +++ b/frameworks/services/media_backup_extension/src/backup_restore_service.cpp @@ -29,11 +29,11 @@ BackupRestoreService &BackupRestoreService::GetInstance(void) } void BackupRestoreService::StartRestore(int32_t sceneCode, const std::string &galleryAppName, - const std::string &mediaAppName) + const std::string &mediaAppName, const std::string &cameraAppName) { std::unique_ptr restoreService; if (sceneCode == 0) { - restoreService = std::make_unique(galleryAppName, mediaAppName); + restoreService = std::make_unique(galleryAppName, mediaAppName, cameraAppName); } else { restoreService = std::make_unique(); } diff --git a/frameworks/services/media_backup_extension/src/base_restore.cpp b/frameworks/services/media_backup_extension/src/base_restore.cpp index b1ff14cafcb1c6080248327233cf88d0f672f7cd..d93654f307722e1018f1317a023cad62887eaa7e 100644 --- a/frameworks/services/media_backup_extension/src/base_restore.cpp +++ b/frameworks/services/media_backup_extension/src/base_restore.cpp @@ -171,7 +171,7 @@ bool BaseRestore::IsSameFile(const FileInfo &fileInfo) const return true; } -void BaseRestore::InsertPhoto(int32_t sceneCode, const std::vector &fileInfos) const +void BaseRestore::InsertPhoto(int32_t sceneCode, const std::vector &fileInfos, int32_t sourceType) const { for (size_t i = 0; i < fileInfos.size(); i++) { if (!MediaFileUtils::IsFileExists(fileInfos[i].filePath)) { @@ -191,7 +191,7 @@ void BaseRestore::InsertPhoto(int32_t sceneCode, const std::vector &fi MEDIA_ERR_LOG("Create Asset Path failed, errCode=%{public}d", errCode); continue; } - NativeRdb::ValuesBucket values = GetInsertValue(fileInfos[i], cloudPath); + NativeRdb::ValuesBucket values = GetInsertValue(fileInfos[i], cloudPath, sourceType); if (mediaLibraryRdb_ == nullptr) { MEDIA_ERR_LOG("mediaLibraryRdb_ is null"); return; @@ -212,7 +212,8 @@ void BaseRestore::InsertPhoto(int32_t sceneCode, const std::vector &fi } } -NativeRdb::ValuesBucket BaseRestore::GetInsertValue(const FileInfo &fileInfo, const std::string &newPath) const +NativeRdb::ValuesBucket BaseRestore::GetInsertValue(const FileInfo &fileInfo, const std::string &newPath, + int32_t sourceType) const { NativeRdb::ValuesBucket values; values.PutString(MediaColumn::MEDIA_FILE_PATH, newPath); diff --git a/frameworks/services/media_backup_extension/src/clone_restore.cpp b/frameworks/services/media_backup_extension/src/clone_restore.cpp index ab584c347c515318a8265d2ffdee3d5baf201069..130e2bcf9a18fd1e6fbff164b86e53ef931332bf 100644 --- a/frameworks/services/media_backup_extension/src/clone_restore.cpp +++ b/frameworks/services/media_backup_extension/src/clone_restore.cpp @@ -65,7 +65,7 @@ void CloneRestore::RestorePhoto(void) MEDIA_INFO_LOG("QueryTotalNumber, totalNumber = %{public}d", totalNumber); for (int32_t offset = 0; offset < totalNumber; offset += QUERY_COUNT) { std::vector infos = QueryFileInfos(offset); - InsertPhoto(CLONE_RESTORE_ID, infos); + InsertPhoto(CLONE_RESTORE_ID, infos, SourceType::PHOTOS); } (void)NativeRdb::RdbHelper::DeleteRdbStore(dbPath_); } diff --git a/frameworks/services/media_backup_extension/src/medialibrary_backup_napi.cpp b/frameworks/services/media_backup_extension/src/medialibrary_backup_napi.cpp index 4ff8d0062bf6562461606309969934788a1ffeb2..a8f0976097fb15013151e39778ff196de3e9dd28 100644 --- a/frameworks/services/media_backup_extension/src/medialibrary_backup_napi.cpp +++ b/frameworks/services/media_backup_extension/src/medialibrary_backup_napi.cpp @@ -87,22 +87,23 @@ napi_value MediaLibraryBackupNapi::JSStartRestore(napi_env env, napi_callback_in return result; } - size_t argc = ARGS_THREE; - napi_value argv[ARGS_THREE] = {0}; + size_t argc = ARGS_FOUR; + napi_value argv[ARGS_FOUR] = {0}; napi_value thisVar = nullptr; GET_JS_ARGS(env, info, argc, argv, thisVar); - NAPI_ASSERT(env, (argc == ARGS_THREE), "requires 3 parameters"); + NAPI_ASSERT(env, (argc == ARGS_FOUR), "requires 4 parameters"); napi_get_undefined(env, &result); int32_t sceneCode = GetIntFromParams(env, argv, PARAM0); std::string galleryAppName = GetStringFromParams(env, argv, PARAM1); std::string mediaAppName = GetStringFromParams(env, argv, PARAM2); + std::string cameraAppName = GetStringFromParams(env, argv, PARAM3); NAPI_INFO_LOG("StartRestore, sceneCode = %{public}d", sceneCode); if (sceneCode < 0) { NAPI_INFO_LOG("Parameters error, sceneCode = %{public}d", sceneCode); return result; } - BackupRestoreService::GetInstance().StartRestore(sceneCode, galleryAppName, mediaAppName); + BackupRestoreService::GetInstance().StartRestore(sceneCode, galleryAppName, mediaAppName, cameraAppName); return result; } } // namespace Media diff --git a/frameworks/services/media_backup_extension/src/update_restore.cpp b/frameworks/services/media_backup_extension/src/update_restore.cpp index 02d7af99a5ca408a2473d82e504f6deb37781dc0..6aed28a695c53d6cd262723aeb279762252ab0fa 100644 --- a/frameworks/services/media_backup_extension/src/update_restore.cpp +++ b/frameworks/services/media_backup_extension/src/update_restore.cpp @@ -16,6 +16,8 @@ #define MLOG_TAG "MediaLibraryUpdateRestore" #include "update_restore.h" + +#include "backup_database_utils.h" #include "media_column.h" #include "media_file_utils.h" #include "media_log.h" @@ -26,52 +28,72 @@ namespace OHOS { namespace Media { -const std::string UPDATE_DB_NAME = "gallery.db"; +const std::string UPDATE_GALLERY_DB_NAME = "gallery.db"; +const std::string UPDATE_EXTERNAL_DB_NAME = "external.db"; const std::string CLONE_TAG = "cloneBackupData.json"; constexpr int32_t GALLERY_IMAGE_TYPE = 1; constexpr int32_t GALLERY_VIDEO_TYPE = 3; -UpdateRestore::UpdateRestore(const std::string &galleryAppName, const std::string &mediaAppName) +UpdateRestore::UpdateRestore(const std::string &galleryAppName, const std::string &mediaAppName, + const std::string &cameraAppName) { galleryAppName_ = galleryAppName; mediaAppName_ = mediaAppName; + cameraAppName_ = cameraAppName; } int32_t UpdateRestore::Init(const std::string &orignPath, const std::string &updatePath, bool isUpdate) { - dbPath_ = orignPath + "/" + galleryAppName_ + "/ce/databases/gallery.db"; appDataPath_ = orignPath; if (MediaFileUtils::IsFileExists(orignPath + "/" + CLONE_TAG)) { filePath_ = orignPath; } else { filePath_ = updatePath; } - if (!MediaFileUtils::IsFileExists(dbPath_)) { + + if (isUpdate && BaseRestore::Init() != E_OK) { + return E_FAIL; + } + galleryDbPath_ = orignPath + "/" + galleryAppName_ + "/ce/databases/gallery.db"; + if (!MediaFileUtils::IsFileExists(galleryDbPath_)) { + MEDIA_ERR_LOG("Gallery media db is not exist."); + } else { + int32_t galleryErr = InitOldDb(UPDATE_GALLERY_DB_NAME, galleryDbPath_, galleryAppName_, galleryRdb_); + if (galleryRdb_ == nullptr) { + MEDIA_ERR_LOG("gallyer data syncer init rdb fail, err = %{public}d", galleryErr); + return E_FAIL; + } + } + externalDbPath_ = orignPath + "/" + mediaAppName_ + "/ce/databases/external.db"; + if (!MediaFileUtils::IsFileExists(externalDbPath_)) { MEDIA_ERR_LOG("Gallery media db is not exist."); return E_FAIL; } - if (isUpdate && BaseRestore::Init() != E_OK) { + int32_t externalErr = InitOldDb(UPDATE_EXTERNAL_DB_NAME, externalDbPath_, mediaAppName_, externalRdb_); + if (externalRdb_ == nullptr) { + MEDIA_ERR_LOG("external data syncer init rdb fail, err = %{public}d", externalErr); return E_FAIL; } + MEDIA_INFO_LOG("Init db succ."); + return E_OK; +} - NativeRdb::RdbStoreConfig config(UPDATE_DB_NAME); - config.SetPath(dbPath_); - config.SetBundleName(galleryAppName_); +int32_t UpdateRestore::InitOldDb(const std::string &dbName, const std::string &dbPath, const std::string &bundleName, + std::shared_ptr &rdbStore) +{ + NativeRdb::RdbStoreConfig config(dbName); + config.SetPath(dbPath); + config.SetBundleName(bundleName); config.SetReadConSize(CONNECT_SIZE); config.SetSecurityLevel(NativeRdb::SecurityLevel::S3); - int32_t err; RdbCallback cb; - galleryRdb_ = NativeRdb::RdbHelper::GetRdbStore(config, MEDIA_RDB_VERSION, cb, err); - if (galleryRdb_ == nullptr) { - MEDIA_ERR_LOG("gallyer data syncer init rdb fail, err = %{public}d", err); - return E_FAIL; - } - MEDIA_INFO_LOG("Init db succ."); - return E_OK; + rdbStore = NativeRdb::RdbHelper::GetRdbStore(config, MEDIA_RDB_VERSION, cb, err); + return err; } + int32_t UpdateRestore::InitGarbageAlbum() { if (galleryRdb_ == nullptr) { @@ -80,7 +102,7 @@ int32_t UpdateRestore::InitGarbageAlbum() } const string querySql = "SELECT nick_dir, nick_name FROM garbage_album where type = 0"; - auto resultSet = galleryRdb_->QuerySql(querySql); + auto resultSet = galleryRdb_->QuerySql(QUERY_GARBAGE_ALBUM); if (resultSet == nullptr) { return E_HAS_DB_ERROR; } @@ -92,11 +114,19 @@ int32_t UpdateRestore::InitGarbageAlbum() } MEDIA_INFO_LOG("garbageCount: %{public}d", count); while (resultSet->GoToNextRow() == NativeRdb::E_OK) { - string nick_dir; - string nick_name; - resultSet->GetString(0, nick_dir); - resultSet->GetString(1, nick_name); - garbageMap_[nick_dir] = nick_name; + int32_t type; + resultSet -> GetInt(INDEX_TYPE, type); + if (type == NICK) { + string nickName; + string nickDir; + resultSet -> GetString(INDEX_NICK_DIR, nickDir); + resultSet -> GetString(INDEX_NICK_NAME, nickName); + nickMap_[nickDir] = nickName; + } else { + string cacheDir; + resultSet -> GetString(INDEX_CACHE_DIR, cacheDir); + cacheSet_.insert(cacheDir); + } } MEDIA_INFO_LOG("add map success!"); resultSet->Close(); @@ -104,15 +134,51 @@ int32_t UpdateRestore::InitGarbageAlbum() } void UpdateRestore::RestorePhoto(void) +{ + InitGarbageAlbum(); + RestoreFromGallery(); + RestoreFromExternal(true); + RestoreFromExternal(false); + (void)NativeRdb::RdbHelper::DeleteRdbStore(galleryDbPath_); + (void)NativeRdb::RdbHelper::DeleteRdbStore(externalDbPath_); +} + +void UpdateRestore::RestoreFromGallery() { int32_t totalNumber = QueryTotalNumber(); MEDIA_INFO_LOG("QueryTotalNumber, totalNumber = %{public}d", totalNumber); InitGarbageAlbum(); for (int32_t offset = 0; offset < totalNumber; offset += QUERY_COUNT) { std::vector infos = QueryFileInfos(offset); - InsertPhoto(UPDATE_RESTORE_ID, infos); + InsertPhoto(UPDATE_RESTORE_ID, infos, SourceType::GALLERY); + } +} + +void UpdateRestore::RestoreFromExternal(bool isCamera) +{ + MEDIA_INFO_LOG("start restore from %{public}s", (isCamera ? "camera" : "others")); + int32_t maxId = BackupDatabaseUtils::QueryInt(galleryRdb_, isCamera ? + QUERY_MAX_ID_CAMERA_SCREENSHOT : QUERY_MAX_ID_OTHERS, MAX_ID); + int32_t type = isCamera ? SourceType::EXTERNAL_CAMERA : SourceType::EXTERNAL_OTHERS; + int32_t totalNumber = QueryNotSyncTotalNumber(maxId, isCamera); + MEDIA_INFO_LOG("QueryTotalNumber, totalNumber = %{public}d", totalNumber); + for (int32_t offset = 0; offset < totalNumber; offset += QUERY_COUNT) { + std::vector infos = QueryFileInfosFromExternal(offset, maxId, isCamera); + InsertPhoto(UPDATE_RESTORE_ID, infos, type); } - (void)NativeRdb::RdbHelper::DeleteRdbStore(dbPath_); +} + +int32_t UpdateRestore::QueryNotSyncTotalNumber(int32_t maxId, bool isCamera) +{ + std::string queryCamera; + if (isCamera) { + queryCamera = IN_CAMERA + "'" + cameraAppName_ + "'))"; + } else { + queryCamera = NOT_IN_CAMERA; + } + std::string queryNotSyncByCount = QUERY_COUNT_FROM_FILES + queryCamera + " AND " + + COMPARE_ID + std::to_string(maxId) + " AND " + QUERY_NOT_SYNC; + return BackupDatabaseUtils::QueryInt(externalRdb_, queryNotSyncByCount, COUNT); } void UpdateRestore::HandleRestData(void) @@ -135,37 +201,51 @@ void UpdateRestore::HandleRestData(void) int32_t UpdateRestore::QueryTotalNumber(void) { + return BackupDatabaseUtils::QueryInt(galleryRdb_, QUERY_GALLERY_COUNT, COUNT); +} + +std::vector UpdateRestore::QueryFileInfos(int32_t offset) +{ + std::vector result; + result.reserve(QUERY_COUNT); if (galleryRdb_ == nullptr) { MEDIA_ERR_LOG("Pointer rdb_ is nullptr, Maybe init failed."); - return 0; + return result; + } + std::string queryAllPhotosByCount = QUERY_ALL_PHOTOS + "limit " + std::to_string(offset) + ", " + + std::to_string(QUERY_COUNT); + auto resultSet = galleryRdb_->QuerySql(queryAllPhotosByCount); + if (resultSet == nullptr) { + MEDIA_ERR_LOG("Query resultSql is null."); + return result; } - std::string querySql = "SELECT count(1) as count FROM gallery_media \ - WHERE (local_media_id != -1) AND (storage_id IN (0, 65537)) AND relative_bucket_id NOT IN ( \ - SELECT DISTINCT relative_bucket_id FROM garbage_album WHERE type = 1)"; - auto resultSet = galleryRdb_->QuerySql(querySql); - if (resultSet == nullptr || resultSet->GoToFirstRow() != NativeRdb::E_OK) { - return 0; + while (resultSet->GoToNextRow() == NativeRdb::E_OK) { + FileInfo tmpInfo; + if (ParseResultSet(resultSet, tmpInfo)) { + result.emplace_back(tmpInfo); + } } - int32_t result = GetInt32Val("count", resultSet); return result; } -std::vector UpdateRestore::QueryFileInfos(int32_t offset) +std::vector UpdateRestore::QueryFileInfosFromExternal(int32_t offset, int32_t maxId, bool isCamera) { std::vector result; result.reserve(QUERY_COUNT); - if (galleryRdb_ == nullptr) { + if (externalRdb_ == nullptr) { MEDIA_ERR_LOG("Pointer rdb_ is nullptr, Maybe init failed."); return result; } - std::string querySql = "SELECT " + GALLERY_LOCAL_MEDIA_ID + "," + GALLERY_FILE_DATA + "," + GALLERY_DISPLAY_NAME + - "," + GALLERY_DESCRIPTION + "," + GALLERY_IS_FAVORITE + "," + GALLERY_RECYCLED_TIME + "," + GALLERY_FILE_SIZE + - "," + GALLERY_DURATION + "," + GALLERY_MEDIA_TYPE + "," + GALLERY_SHOW_DATE_TOKEN + "," + GALLERY_HEIGHT + - "," + GALLERY_WIDTH + "," + GALLERY_TITLE + ", " + GALLERY_ORIENTATION + " FROM gallery_media \ - WHERE (local_media_id != -1) AND (storage_id IN (0, 65537)) AND relative_bucket_id NOT IN ( \ - SELECT DISTINCT relative_bucket_id FROM garbage_album WHERE type = 1 \ - ) ORDER BY showDateToken ASC limit " + std::to_string(offset) + ", " + std::to_string(QUERY_COUNT); - auto resultSet = galleryRdb_->QuerySql(querySql); + std::string queryCamera; + if (isCamera) { + queryCamera = IN_CAMERA + "'" + cameraAppName_ + "'))"; + } else { + queryCamera = NOT_IN_CAMERA; + } + std::string queryFilesByCount = QUERY_FILE_COLUMN + queryCamera + " AND " + + COMPARE_ID + std::to_string(maxId) + " AND " + QUERY_NOT_SYNC + " limit " + std::to_string(offset) + ", " + + std::to_string(QUERY_COUNT); + auto resultSet = externalRdb_->QuerySql(queryFilesByCount); if (resultSet == nullptr) { MEDIA_ERR_LOG("Query resultSql is null."); return result; @@ -173,12 +253,27 @@ std::vector UpdateRestore::QueryFileInfos(int32_t offset) while (resultSet->GoToNextRow() == NativeRdb::E_OK) { FileInfo tmpInfo; if (ParseResultSet(resultSet, tmpInfo)) { - result.emplace_back(tmpInfo); + std::string findPath = tmpInfo.relativePath; + bool isValid = IsValidDir(findPath); + if (isValid) { + result.emplace_back(tmpInfo); + } } } return result; } +bool UpdateRestore::IsValidDir(const string &path) +{ + bool isValid = true; + for (auto &cacheDir : cacheSet_) { + if (path.find(cacheDir) == 0) { + isValid = false; + break; + } + } + return isValid; +} bool UpdateRestore::ParseResultSet(const std::shared_ptr &resultSet, FileInfo &info) { // only parse image and video @@ -205,11 +300,13 @@ bool UpdateRestore::ParseResultSet(const std::shared_ptr & info.showDateToken = GetInt64Val(GALLERY_SHOW_DATE_TOKEN, resultSet) / MILLISECONDS; info.height = GetInt64Val(GALLERY_HEIGHT, resultSet); info.width = GetInt64Val(GALLERY_WIDTH, resultSet); + info.dateAdded = GetInt64Val(DATE_ADDED, resultSet); info.orientation = GetInt64Val(GALLERY_ORIENTATION, resultSet); return true; } -NativeRdb::ValuesBucket UpdateRestore::GetInsertValue(const FileInfo &fileInfo, const std::string &newPath) const +NativeRdb::ValuesBucket UpdateRestore::GetInsertValue(const FileInfo &fileInfo, const std::string &newPath, + int32_t sourceType) const { NativeRdb::ValuesBucket values; values.PutString(MediaColumn::MEDIA_FILE_PATH, newPath); @@ -217,7 +314,11 @@ NativeRdb::ValuesBucket UpdateRestore::GetInsertValue(const FileInfo &fileInfo, values.PutString(MediaColumn::MEDIA_NAME, fileInfo.displayName); values.PutLong(MediaColumn::MEDIA_SIZE, fileInfo.fileSize); values.PutInt(MediaColumn::MEDIA_TYPE, fileInfo.fileType); - values.PutLong(MediaColumn::MEDIA_DATE_ADDED, fileInfo.showDateToken); + if (sourceType == SourceType::EXTERNAL_CAMERA || sourceType == SourceType::EXTERNAL_OTHERS) { + values.PutLong(MediaColumn::MEDIA_DATE_ADDED, fileInfo.dateAdded); + } else { + values.PutLong(MediaColumn::MEDIA_DATE_ADDED, fileInfo.showDateToken); + } values.PutLong(MediaColumn::MEDIA_DURATION, fileInfo.duration); values.PutInt(MediaColumn::MEDIA_IS_FAV, fileInfo.isFavorite); values.PutLong(MediaColumn::MEDIA_DATE_TRASHED, fileInfo.recycledTime); @@ -229,9 +330,9 @@ NativeRdb::ValuesBucket UpdateRestore::GetInsertValue(const FileInfo &fileInfo, values.PutInt(PhotoColumn::PHOTO_ORIENTATION, fileInfo.orientation); std::string package_name = ""; std::string findPath = fileInfo.relativePath; - for (auto &garbageItem : garbageMap_) { - if (findPath.find(garbageItem.first) == 0) { - package_name = garbageItem.second; + for (auto &nickItem : nickMap_) { + if (findPath.find(nickItem.first) == 0) { + package_name = nickItem.second; break; } }