From fcdf01d0d3ab2a50a5cb6878f0119b449153490b Mon Sep 17 00:00:00 2001 From: Wang Luyao Date: Sun, 27 Apr 2025 16:46:09 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AB=AF=E4=BA=91=E8=BF=81=E4=BB=93=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Wang Luyao Change-Id: I1af896348d9f1edb8c167d5b7a37d6f246f57a9d --- cloud_file/.clang-format | 162 + cloud_file/BUILD.gn | 56 + cloud_file/CODEOWNERS | 17 + cloud_file/LICENSE | 177 + cloud_file/README.md | 36 + cloud_file/README_zh.md | 82 + .../adapter/cloud_adapter_example/BUILD.gn | 73 + .../include/cloud_asset_read_session_impl.h | 32 + .../include/cloud_assets_downloader_impl.h | 28 + .../include/cloud_database_impl.h | 33 + .../include/cloud_file_kit_impl.h | 55 + .../include/cloud_sync_helper_impl.h | 32 + .../include/data_sync_manager_impl.h | 32 + .../src/cloud_asset_read_session_impl.cpp | 29 + .../src/cloud_assets_downloader_impl.cpp | 26 + .../src/cloud_database_impl.cpp | 36 + .../src/cloud_file_kit_impl.cpp | 110 + .../src/cloud_sync_helper_impl.cpp | 38 + .../src/data_sync_manager_impl.cpp | 29 + cloud_file/bundle.json | 170 + cloud_file/cfi_blocklist.txt | 41 + cloud_file/cloud_file.gni | 57 + .../include/cloud_daemon_manager_impl.h | 43 + .../include/cloud_daemon_service_proxy.h | 41 + .../src/cloud_daemon_manager.cpp | 24 + .../src/cloud_daemon_manager_impl.cpp | 56 + .../src/cloud_daemon_service_proxy.cpp | 107 + .../cloud_file_fault_event.cpp | 128 + .../cloud_report_cacher.cpp | 153 + .../gallery_download_file_stat.cpp | 305 ++ .../src/cloud_asset_read_session.cpp | 66 + .../src/cloud_assets_downloader.cpp | 40 + .../src/cloud_database.cpp | 46 + .../src/cloud_file_kit.cpp | 108 + .../src/cloud_sync_helper.cpp | 36 + .../src/data_sync/data_syncer_rdb_store.cpp | 246 + .../src/data_sync/sync_state_manager.cpp | 117 + .../src/data_sync/task_state_manager.cpp | 147 + .../src/data_sync_manager.cpp | 202 + .../src/sync_rule/battery_status.cpp | 98 + .../src/sync_rule/cloud_status.cpp | 104 + .../sync_rule/net_conn_callback_observer.cpp | 82 + .../src/sync_rule/network_set_manager.cpp | 346 ++ .../src/sync_rule/network_status.cpp | 164 + .../src/sync_rule/screen_status.cpp | 44 + .../src/sync_rule/system_load.cpp | 111 + .../include/cloud_download_callback_client.h | 34 + .../include/cloud_download_callback_stub.h | 40 + .../include/cloud_download_uri_manager.h | 46 + .../include/cloud_optimize_callback_client.h | 34 + .../include/cloud_optimize_callback_stub.h | 39 + .../include/cloud_sync_asset_manager_impl.h | 57 + .../include/cloud_sync_callback_client.h | 33 + .../include/cloud_sync_callback_stub.h | 39 + .../include/cloud_sync_manager_impl.h | 102 + .../include/download_asset_callback_client.h | 46 + .../include/download_asset_callback_stub.h | 39 + .../include/service_proxy.h | 45 + .../src/cloud_download_callback_client.cpp | 31 + .../src/cloud_download_callback_stub.cpp | 59 + .../src/cloud_download_uri_manager.cpp | 124 + .../src/cloud_optimize_callback_client.cpp | 31 + .../src/cloud_optimize_callback_stub.cpp | 56 + .../src/cloud_sync_asset_manager.cpp | 24 + .../src/cloud_sync_asset_manager_impl.cpp | 150 + .../src/cloud_sync_callback_client.cpp | 31 + .../src/cloud_sync_callback_stub.cpp | 55 + .../src/cloud_sync_common.cpp | 439 ++ .../src/cloud_sync_manager.cpp | 24 + .../src/cloud_sync_manager_impl.cpp | 736 +++ .../src/download_asset_callback_client.cpp | 67 + .../src/download_asset_callback_stub.cpp | 55 + .../cloudsync_kit_inner/src/service_proxy.cpp | 95 + .../include/cloud_sync_manager_impl_lite.h | 42 + .../include/cloud_sync_manager_lite.h | 36 + .../include/svc_death_recipient_lite.h | 40 + .../src/cloud_sync_manager_impl_lite.cpp | 58 + .../src/cloud_sync_manager_lite.cpp | 24 + .../src/cloud_sync_service_proxy_lite.cpp | 347 ++ .../native/cloud_daemon_kit_inner/BUILD.gn | 77 + .../cloud_daemon_manager.h | 31 + .../cloud_file_daemon_interface_code.h | 26 + .../cloud_daemon_kit_inner/i_cloud_daemon.h | 38 + .../svc_death_recipient.h | 41 + .../native/cloud_file_kit_inner/BUILD.gn | 190 + .../cloud_file_kit_inner/battery_status.h | 48 + .../cloud_file_fault_event.h | 194 + .../big_data_statistics/cloud_report_cacher.h | 65 + .../gallery_download_file_stat.h | 72 + .../cloud_asset_read_session.h | 47 + .../cloud_assets_downloader.h | 39 + .../cloud_file_kit_inner/cloud_database.h | 43 + .../cloud_file_kit_inner/cloud_file_kit.h | 62 + .../native/cloud_file_kit_inner/cloud_info.h | 51 + .../cloud_file_kit_inner/cloud_status.h | 42 + .../cloud_file_kit_inner/cloud_sync_helper.h | 36 + .../cloud_file_kit_inner/data_sync_const.h | 106 + .../cloud_file_kit_inner/data_sync_manager.h | 91 + .../data_syncer_rdb_col.h | 64 + .../data_syncer_rdb_store.h | 54 + .../net_conn_callback_observer.h | 47 + .../network_set_manager.h | 79 + .../cloud_file_kit_inner/network_status.h | 50 + .../cloud_file_kit_inner/screen_status.h | 41 + .../cloud_file_kit_inner/sync_state_manager.h | 72 + .../native/cloud_file_kit_inner/system_load.h | 61 + .../cloud_file_kit_inner/task_state_manager.h | 57 + .../native/cloudsync_kit_inner/BUILD.gn | 200 + .../cloud_download_callback.h | 32 + .../cloud_file_sync_service_interface_code.h | 62 + .../cloud_optimize_callback.h | 31 + .../cloud_sync_asset_manager.h | 90 + .../cloudsync_kit_inner/cloud_sync_callback.h | 72 + .../cloudsync_kit_inner/cloud_sync_common.h | 182 + .../cloud_sync_constants.h | 108 + .../cloudsync_kit_inner/cloud_sync_manager.h | 138 + .../download_asset_callback.h | 28 + .../i_cloud_download_callback.h | 34 + .../i_cloud_optimize_callback.h | 34 + .../i_cloud_sync_callback.h | 34 + .../i_download_asset_callback.h | 33 + .../cloudsync_kit_inner/svc_death_recipient.h | 41 + .../interfaces/kits/js/cloudfilesync/BUILD.gn | 74 + .../cloudfilesync/cloud_file_cache_napi.cpp | 443 ++ .../js/cloudfilesync/cloud_file_cache_napi.h | 75 + .../cloud_file_download_napi.cpp | 39 + .../cloudfilesync/cloud_file_download_napi.h | 30 + .../kits/js/cloudfilesync/cloud_file_napi.cpp | 343 ++ .../kits/js/cloudfilesync/cloud_file_napi.h | 75 + .../cloudfilesync/cloud_sync_n_exporter.cpp | 221 + .../js/cloudfilesync/cloud_sync_n_exporter.h | 31 + .../kits/js/cloudfilesync/cloud_sync_napi.cpp | 1191 +++++ .../kits/js/cloudfilesync/cloud_sync_napi.h | 202 + .../kits/js/cloudfilesync/file_sync_napi.cpp | 199 + .../kits/js/cloudfilesync/file_sync_napi.h | 36 + .../js/cloudfilesync/gallery_sync_napi.cpp | 39 + .../kits/js/cloudfilesync/gallery_sync_napi.h | 30 + .../kits/js/cloudsyncmanager/BUILD.gn | 61 + .../cloud_sync_manager_n_exporter.cpp | 406 ++ .../cloud_sync_manager_n_exporter.h | 29 + .../cloud_sync_manager_napi.cpp | 72 + .../cloud_sync_manager_napi.h | 30 + cloud_file/services/5204.json | 97 + cloud_file/services/5205.json | 12 + cloud_file/services/BUILD.gn | 51 + .../services/clouddisk_database/BUILD.gn | 102 + .../include/clouddisk_db_const.h | 71 + .../include/clouddisk_notify.h | 55 + .../include/clouddisk_notify_const.h | 78 + .../include/clouddisk_notify_utils.h | 54 + .../include/clouddisk_rdb_transaction.h | 69 + .../include/clouddisk_rdb_utils.h | 51 + .../include/clouddisk_rdbstore.h | 151 + .../include/clouddisk_sync_helper.h | 62 + .../include/clouddisk_type_const.h | 89 + .../clouddisk_database/include/file_column.h | 126 + .../src/clouddisk_notify.cpp | 499 ++ .../src/clouddisk_notify_utils.cpp | 178 + .../src/clouddisk_rdb_transaction.cpp | 155 + .../src/clouddisk_rdb_utils.cpp | 169 + .../src/clouddisk_rdbstore.cpp | 2428 +++++++++ .../src/clouddisk_sync_helper.cpp | 103 + .../clouddisk_database/src/file_column.cpp | 226 + cloud_file/services/cloudfiledaemon.cfg | 22 + cloud_file/services/cloudfiledaemon/BUILD.gn | 110 + .../include/cloud_disk/account_status.h | 39 + .../cloud_disk/account_status_listener.h | 45 + .../include/cloud_disk/cloud_disk_inode.h | 106 + .../include/cloud_disk/database_manager.h | 44 + .../include/cloud_disk/file_operations_base.h | 66 + .../cloud_disk/file_operations_cloud.h | 59 + .../cloud_disk/file_operations_helper.h | 53 + .../cloud_disk/file_operations_local.h | 34 + .../include/cloud_disk/fuse_operations.h | 61 + .../fuse_manager/cloud_daemon_statistic.h | 63 + .../include/fuse_manager/fuse_manager.h | 47 + .../include/ipc/cloud_daemon.h | 66 + .../include/ipc/cloud_daemon_stub.h | 44 + .../src/cloud_disk/account_status.cpp | 42 + .../cloud_disk/account_status_listener.cpp | 160 + .../src/cloud_disk/database_manager.cpp | 48 + .../src/cloud_disk/file_operations_base.cpp | 185 + .../src/cloud_disk/file_operations_cloud.cpp | 1933 ++++++++ .../src/cloud_disk/file_operations_helper.cpp | 259 + .../src/cloud_disk/file_operations_local.cpp | 209 + .../src/cloud_disk/fuse_operations.cpp | 396 ++ .../fuse_manager/cloud_daemon_statistic.cpp | 242 + .../src/fuse_manager/fuse_manager.cpp | 1758 +++++++ .../cloudfiledaemon/src/ipc/cloud_daemon.cpp | 233 + .../src/ipc/cloud_daemon_stub.cpp | 63 + cloud_file/services/cloudfileservice.cfg | 38 + cloud_file/services/cloudsyncservice.para | 22 + cloud_file/services/cloudsyncservice.para.dac | 22 + cloud_file/services/cloudsyncservice/BUILD.gn | 336 ++ .../cloudsyncservice/ICloudSyncService.idl | 67 + .../include/cycle_task/cycle_task.h | 67 + .../include/cycle_task/cycle_task_runner.h | 49 + .../cycle_task/tasks/database_backup_task.h | 33 + .../cycle_task/tasks/optimize_cache_task.h | 33 + .../cycle_task/tasks/optimize_storage_task.h | 33 + .../cycle_task/tasks/periodic_check_task.h | 35 + .../cycle_task/tasks/report_statistics_task.h | 33 + .../cycle_task/tasks/save_subscription_task.h | 32 + .../include/ipc/cloud_sync_service.h | 139 + .../ipc/download_asset_callback_manager.h | 38 + .../ipc/download_asset_callback_proxy.h | 36 + .../sync_rule/battery_status_listener.h | 51 + .../sync_rule/i_user_status_observer.h | 28 + .../sync_rule/package_status_listener.h | 53 + .../sync_rule/screen_status_listener.h | 51 + .../include/sync_rule/user_status_listener.h | 56 + .../include/transport/file_transfer_manager.h | 74 + .../include/transport/message_handler.h | 97 + .../transport/softbus/i_softbus_listener.h | 36 + .../transport/softbus/session_manager.h | 89 + .../transport/softbus/softbus_adapter.h | 84 + .../transport/softbus/softbus_session.h | 57 + .../src/cycle_task/cycle_task.cpp | 110 + .../src/cycle_task/cycle_task_runner.cpp | 148 + .../cycle_task/tasks/database_backup_task.cpp | 66 + .../cycle_task/tasks/optimize_cache_task.cpp | 41 + .../tasks/optimize_storage_task.cpp | 60 + .../cycle_task/tasks/periodic_check_task.cpp | 48 + .../tasks/report_statistics_task.cpp | 38 + .../tasks/save_subscription_task.cpp | 47 + .../src/ipc/cloud_sync_service.cpp | 1111 +++++ .../ipc/download_asset_callback_manager.cpp | 56 + .../src/ipc/download_asset_callback_proxy.cpp | 64 + .../src/sync_rule/battery_status_listener.cpp | 98 + .../src/sync_rule/package_status_listener.cpp | 129 + .../src/sync_rule/screen_status_listener.cpp | 81 + .../src/sync_rule/user_status_listener.cpp | 118 + .../src/transport/file_transfer_manager.cpp | 270 + .../src/transport/message_handler.cpp | 177 + .../src/transport/softbus/session_manager.cpp | 205 + .../src/transport/softbus/softbus_adapter.cpp | 395 ++ .../src/transport/softbus/softbus_session.cpp | 139 + cloud_file/test/fuzztest/BUILD.gn | 22 + .../clouddaemonmanager_fuzzer/BUILD.gn | 59 + .../clouddaemonmanager_fuzzer.cpp | 50 + .../clouddaemonmanager_fuzzer.h | 20 + .../clouddaemonmanager_fuzzer/corpus/init | 14 + .../clouddaemonmanager_fuzzer/project.xml | 25 + .../fuzztest/clouddaemonstub_fuzzer/BUILD.gn | 59 + .../clouddaemonstub_fuzzer.cpp | 93 + .../clouddaemonstub_fuzzer.h | 22 + .../clouddaemonstub_fuzzer/corpus/init | 14 + .../clouddaemonstub_fuzzer/project.xml | 25 + .../fuzztest/clouddisknotify_fuzzer/BUILD.gn | 62 + .../clouddisknotify_fuzzer.cpp | 99 + .../clouddisknotify_fuzzer.h | 22 + .../clouddisknotify_fuzzer/corpus/init | 14 + .../clouddisknotify_fuzzer/project.xml | 25 + .../clouddownloadcallbackstub_fuzzer/BUILD.gn | 61 + .../clouddownloadcallbackstub_fuzzer.cpp | 94 + .../clouddownloadcallbackstub_fuzzer.h | 22 + .../corpus/init | 14 + .../project.xml | 25 + .../cloudsyncassetmanager_fuzzer/BUILD.gn | 62 + .../cloudsyncassetmanager_fuzzer.cpp | 130 + .../cloudsyncassetmanager_fuzzer.h | 20 + .../cloudsyncassetmanager_fuzzer/corpus/init | 14 + .../cloudsyncassetmanager_fuzzer/project.xml | 25 + .../cloudsynccallbackstub_fuzzer/BUILD.gn | 61 + .../cloudsynccallbackstub_fuzzer.cpp | 84 + .../cloudsynccallbackstub_fuzzer.h | 22 + .../cloudsynccallbackstub_fuzzer/corpus/init | 14 + .../cloudsynccallbackstub_fuzzer/project.xml | 25 + .../fuzztest/cloudsyncmanager_fuzzer/BUILD.gn | 61 + .../cloudsyncmanager_fuzzer.cpp | 220 + .../cloudsyncmanager_fuzzer.h | 20 + .../cloudsyncmanager_fuzzer/corpus/init | 14 + .../cloudsyncmanager_fuzzer/project.xml | 25 + .../cloudsyncservicestub_fuzzer/BUILD.gn | 85 + .../cloudsyncservicestub_fuzzer.cpp | 721 +++ .../cloudsyncservicestub_fuzzer.h | 22 + .../cloudsyncservicestub_fuzzer/corpus/init | 14 + .../cloudsyncservicestub_fuzzer/project.xml | 25 + .../fuzztest/cycletaskrunner_fuzzer/BUILD.gn | 63 + .../cycletaskrunner_fuzzer/corpus/init | 14 + .../cycletaskrunner_fuzzer.cpp | 91 + .../cycletaskrunner_fuzzer.h | 20 + .../cycletaskrunner_fuzzer/project.xml | 25 + .../downloadassetcallbackstub_fuzzer/BUILD.gn | 59 + .../corpus/init | 14 + .../downloadassetcallbackstub_fuzzer.cpp | 80 + .../downloadassetcallbackstub_fuzzer.h | 22 + .../project.xml | 25 + .../downloadassetcbmgr_fuzzer/BUILD.gn | 55 + .../downloadassetcbmgr_fuzzer/corpus/init | 14 + .../downloadassetcbmgr_fuzzer.cpp | 64 + .../downloadassetcbmgr_fuzzer.h | 20 + .../downloadassetcbmgr_fuzzer/project.xml | 25 + .../test/fuzztest/ffrttimer_fuzzer/BUILD.gn | 53 + .../fuzztest/ffrttimer_fuzzer/corpus/init | 14 + .../ffrttimer_fuzzer/ffrttimer_fuzzer.cpp | 54 + .../ffrttimer_fuzzer/ffrttimer_fuzzer.h | 22 + .../fuzztest/ffrttimer_fuzzer/project.xml | 25 + .../fuzz_common/cloud_fuzzer_helper.h | 86 + cloud_file/test/mock/battersrvclient_mock.cpp | 26 + cloud_file/test/mock/battersrvclient_mock.h | 39 + .../mock/cloud_daemon_manager_impl_mock.cpp | 50 + .../test/mock/cloud_daemon_manager_mock.cpp | 29 + .../mock/cloud_download_uri_manager_hook.cpp | 44 + cloud_file/test/mock/cloud_file_kit_mock.cpp | 30 + .../test/mock/clouddisk_notify_mock.cpp | 54 + .../transport/softbus_adapter_mock.cpp | 130 + .../transport/softbus_adapter_mock.h | 48 + .../transport/softbus_session_mock.cpp | 73 + .../transport/softbus_session_mock.h | 52 + .../test/mock/device_manager_impl_mock.cpp | 346 ++ .../test/mock/device_manager_impl_mock.h | 68 + cloud_file/test/mock/device_manager_mock.cpp | 29 + .../mock/if_system_ability_manager_mock.h | 71 + .../ipc/cloud_sync_service_proxy_mock.cpp | 95 + .../cloud_sync_service_proxy_unnomal_mock.cpp | 34 + cloud_file/test/mock/message_parcel_mock.cpp | 144 + cloud_file/test/mock/message_parcel_mock.h | 84 + cloud_file/test/mock/net_conn_client_mock.cpp | 24 + cloud_file/test/mock/net_conn_client_mock.h | 44 + .../test/mock/preference_helper_mock.cpp | 78 + cloud_file/test/mock/socket_mock.cpp | 49 + cloud_file/test/mock/socket_mock.h | 46 + .../test/mock/softbus_bus_center_mock.cpp | 45 + .../system_ability_manager_client_mock.cpp | 31 + .../mock/system_ability_manager_client_mock.h | 40 + cloud_file/test/unittests/BUILD.gn | 30 + .../test/unittests/cloud_daemon/BUILD.gn | 139 + .../cloud_daemon_manager_impl_test.cpp | 123 + .../cloud_daemon_manager_test.cpp | 71 + .../cloud_daemon_service_proxy_test.cpp | 188 + .../include/cloud_daemon_service_mock.h | 48 + cloud_file/test/unittests/cloud_disk/BUILD.gn | 462 ++ .../account_status_listener_test.cpp | 177 + .../cloud_disk/database_manager_test.cpp | 117 + .../cloud_disk/file_operations_base_test.cpp | 675 +++ .../cloud_disk/file_operations_cloud_test.cpp | 2914 +++++++++++ .../file_operations_helper_test.cpp | 875 ++++ .../cloud_disk/file_operations_local_test.cpp | 427 ++ .../cloud_disk/fuse_operations_test.cpp | 1753 +++++++ .../unittests/cloud_disk/mock/assistant.h | 89 + .../mock/clouddisk_rdbstore_mock.cpp | 265 + .../mock/file_operations_helper_mock.cpp | 261 + .../mock/file_operations_local_mock.cpp | 111 + .../cloud_disk/mock/libfuse_mock.cpp | 89 + .../cloud_disk/mock/system_function_mock.cpp | 38 + .../unittests/cloud_file_kit_inner/BUILD.gn | 23 + .../big_data_statistics/BUILD.gn | 116 + .../cloud_file_fault_event_test.cpp | 107 + .../cloud_report_cacher_test.cpp | 101 + .../gallery_download_file_stat_test.cpp | 305 ++ .../cloud_file_kit_inner/cloud_kit/BUILD.gn | 53 + .../cloud_kit/cloud_file_kit_test.cpp | 78 + .../cloud_file_kit_inner/data_sync/BUILD.gn | 141 + .../data_sync/data_syncer_rdb_store_test.cpp | 339 ++ .../data_sync/sync_state_manager_test.cpp | 467 ++ .../data_sync/task_state_manager_test.cpp | 391 ++ .../unittests/clouddisk_database/BUILD.gn | 546 +++ .../clouddisk_notify_test.cpp | 933 ++++ .../clouddisk_notify_utils_test.cpp | 500 ++ .../clouddisk_rdb_transaction_test.cpp | 302 ++ .../clouddisk_rdb_utils_test.cpp | 540 ++ .../clouddisk_rdbstore_test.cpp | 4341 +++++++++++++++++ .../clouddisk_sync_helper_test.cpp | 151 + .../include/clouddisk_rdbstore_mock.h | 210 + .../include/clouddisk_resultset_mock.h | 68 + .../include/result_set_mock.h | 66 + .../mock/clouddisk_notify_utils_mock.cpp | 146 + .../mock/clouddisk_rdb_transaction_mock.cpp | 70 + .../mock/clouddisk_rdb_utils_mock.cpp | 103 + .../mock/meta_file_clouddisk_mock.cpp | 580 +++ .../clouddisk_database/mock/rdb_assistant.h | 234 + .../clouddisk_database/mock/rdb_mock.cpp | 36 + .../mock/transaction_mock.cpp | 44 + .../test/unittests/cloudsync_api/BUILD.gn | 19 + .../cloudsync_api/cloudsync_impl/BUILD.gn | 559 +++ .../cloud_download_callback_client_test.cpp | 110 + .../cloud_download_callback_stub_test.cpp | 215 + .../cloud_download_uri_manager_test.cpp | 241 + .../cloud_sync_asset_manager_impl_test.cpp | 170 + ...d_sync_asset_manager_impl_unnomal_test.cpp | 93 + .../cloud_sync_asset_manager_test.cpp | 74 + .../cloud_sync_callback_client_test.cpp | 99 + .../cloud_sync_callback_stub_test.cpp | 156 + .../cloudsync_impl/cloud_sync_common_test.cpp | 655 +++ .../cloud_sync_manager_impl_test.cpp | 850 ++++ .../cloud_sync_manager_impl_unnomal_test.cpp | 300 ++ .../cloud_sync_manager_test.cpp | 73 + .../cloud_sync_service_proxy_lite_test.cpp | 232 + .../cloud_sync_service_proxy_test.cpp | 1111 +++++ .../download_asset_callback_client_test.cpp | 149 + .../download_asset_callback_stub_test.cpp | 161 + .../cloudsync_impl/file_hook/parcel.cpp | 107 + .../include/asset_callback_mock.h | 47 + .../include/i_cloud_download_callback_mock.h | 48 + .../include/i_cloud_sync_service_mock.h | 228 + .../include/service_callback_mock.h | 47 + .../test/unittests/cloudsync_sa/BUILD.gn | 27 + .../cloudsync_sa/cycle_task/BUILD.gn | 95 + .../cloud_sync_service_cycle_task_test.cpp | 580 +++ .../unittests/cloudsync_sa/dentry/BUILD.gn | 119 + .../dentry/dentry_file_utils_test.cpp | 199 + .../dentry_meta_file_clouddisk_test.cpp | 624 +++ .../dentry/dentry_meta_file_test.cpp | 671 +++ .../dentry/mock/base_interface_lib_mock.cpp | 139 + .../dentry/mock/base_interface_lib_mock.h | 70 + .../test/unittests/cloudsync_sa/ipc/BUILD.gn | 260 + .../ipc/cloud_sync_service_stub_test.cpp | 2099 ++++++++ .../ipc/cloud_sync_service_test.cpp | 773 +++ .../download_asset_callback_manager_test.cpp | 118 + .../download_asset_callback_proxy_test.cpp | 108 + .../test/unittests/cloudsync_sa/log/BUILD.gn | 67 + .../cloudsync_sa/log/dfs_error_test.cpp | 74 + .../cloudsync_sa/log/utils_log_test.cpp | 76 + .../mock/abs_shared_result_set_mock.h | 66 + .../cloudsync_sa/mock/battery_status_mock.cpp | 56 + .../mock/cloud_file_utils_mock.cpp | 137 + .../cloudsync_sa/mock/cloud_file_utils_mock.h | 26 + .../mock/cloud_pref_impl_mock.cpp | 69 + .../cloudsync_sa/mock/cloud_status_mock.cpp | 40 + .../mock/data_ability_observer_interface.h | 53 + .../mock/data_ability_observer_stub.cpp | 111 + .../mock/data_ability_observer_stub.h | 77 + .../cloudsync_sa/mock/datashare_errno.h | 116 + .../cloudsync_sa/mock/datashare_helper.cpp | 62 + .../cloudsync_sa/mock/datashare_helper.h | 66 + .../cloudsync_sa/mock/datashare_result_set.h | 55 + .../mock/dfsu_access_token_helper_mock.cpp | 60 + .../mock/dfsu_access_token_helper_mock.h | 55 + .../mock/network_set_manager_mock.cpp | 104 + .../cloudsync_sa/mock/network_status_mock.cpp | 73 + .../unittests/cloudsync_sa/mock/parameter.h | 31 + .../cloudsync_sa/mock/parameters.cpp | 45 + .../unittests/cloudsync_sa/mock/parameters.h | 34 + .../cloudsync_sa/mock/rdb_store_mock.h | 178 + .../cloudsync_sa/mock/result_set_mock.h | 66 + .../mock/sync_state_manager_mock.cpp | 51 + .../unittests/cloudsync_sa/mock/task_mock.cpp | 131 + .../unittests/cloudsync_sa/sync_rule/BUILD.gn | 593 +++ .../battery_status_listener_test.cpp | 226 + .../sync_rule/battery_status_test.cpp | 236 + .../sync_rule/cloud_status_test.cpp | 214 + .../net_conn_callback_observer_test.cpp | 152 + .../sync_rule/network_set_manager_test.cpp | 272 ++ .../sync_rule/network_status_test.cpp | 443 ++ .../package_status_listener_test.cpp | 384 ++ .../sync_rule/screen_status_listener_test.cpp | 205 + .../sync_rule/system_load_test.cpp | 273 ++ .../sync_rule/user_status_listener_test.cpp | 250 + .../unittests/cloudsync_sa/system/BUILD.gn | 137 + .../system/dfsu_access_token_helper_test.cpp | 211 + .../system/dfsu_fd_guard_test.cpp | 146 + .../dfsu_mount_argument_descriptors_test.cpp | 302 ++ .../system/reimplement/accesstoken_kit.cpp | 117 + .../reimplement/accesstoken_kit_mock.cpp | 30 + .../system/reimplement/ipc_skeleton.cpp | 89 + .../system/reimplement/tokenInfo.h | 34 + .../unittests/cloudsync_sa/transport/BUILD.gn | 182 + .../transport/file_transfer_manager_test.cpp | 210 + .../transport/message_handler_test.cpp | 129 + .../softbus/session_manager_test.cpp | 319 ++ .../softbus/softbus_adapter_test.cpp | 487 ++ .../softbus/softbus_session_test.cpp | 273 ++ .../resource/cloud_disk_data_handler_test.txt | 15 + .../cloud_disk_data_handler_test1.txt | 15 + .../test/unittests/resource/ohos_test.xml | 23 + .../test/unittests/services_daemon/BUILD.gn | 309 ++ .../cloud_daemon_statistic_test.cpp | 153 + .../cloud_daemon_stub_test.cpp | 155 + .../services_daemon/cloud_daemon_test.cpp | 259 + .../services_daemon/fuse_manager_test.cpp | 346 ++ .../services_daemon/mock/fuse_assistant.h | 54 + .../services_daemon/mock/libfuse_mock.cpp | 39 + .../mock/system_function_mock.cpp | 78 + cloud_file/test/unittests/utils/BUILD.gn | 214 + .../cloud_disk/cloud_file_utils_test.cpp | 184 + .../utils/load/plugin_loader_test.cpp | 95 + .../utils/preference/cloud_pref_impl_test.cpp | 924 ++++ .../utils/system/utils_directory_test.cpp | 356 ++ .../unittests/utils/work/async_work_test.cpp | 83 + cloud_file/utils/BUILD.gn | 275 ++ .../utils/cloud_disk/src/cloud_file_utils.cpp | 351 ++ cloud_file/utils/dentry/include/file_utils.h | 35 + cloud_file/utils/dentry/include/meta_file.h | 250 + cloud_file/utils/dentry/src/file_utils.cpp | 83 + cloud_file/utils/dentry/src/meta_file.cpp | 743 +++ .../utils/dentry/src/meta_file_clouddisk.cpp | 843 ++++ cloud_file/utils/dfx/src/xcollie_helper.cpp | 43 + cloud_file/utils/ffrt/src/ffrt_timer.cpp | 81 + cloud_file/utils/inner_api/block_object.h | 66 + cloud_file/utils/inner_api/cloud_file_error.h | 21 + cloud_file/utils/inner_api/cloud_file_log.h | 21 + cloud_file/utils/inner_api/cloud_file_timer.h | 21 + cloud_file/utils/inner_api/cloud_file_utils.h | 88 + cloud_file/utils/inner_api/cloud_meta_file.h | 21 + cloud_file/utils/inner_api/cloud_pref_impl.h | 46 + cloud_file/utils/inner_api/fdsan.h | 97 + cloud_file/utils/inner_api/ffrt_timer.h | 45 + cloud_file/utils/inner_api/visibility.h | 26 + cloud_file/utils/inner_api/xcollie_helper.h | 29 + cloud_file/utils/load/include/plugin_loader.h | 33 + cloud_file/utils/load/src/plugin_loader.cpp | 81 + cloud_file/utils/log/include/dfs_error.h | 234 + cloud_file/utils/log/include/utils_log.h | 48 + cloud_file/utils/log/src/dfs_error.cpp | 27 + cloud_file/utils/log/src/utils_log.cpp | 50 + .../utils/preference/src/cloud_pref_impl.cpp | 170 + .../system/include/dfs_daemon_event_dfx.h | 93 + .../system/include/dfsu_access_token_helper.h | 41 + cloud_file/utils/system/include/dfsu_actor.h | 172 + cloud_file/utils/system/include/dfsu_cmd.h | 89 + .../utils/system/include/dfsu_exception.h | 68 + .../utils/system/include/dfsu_fd_guard.h | 49 + .../utils/system/include/dfsu_memory_guard.h | 28 + .../include/dfsu_mount_argument_descriptors.h | 53 + .../utils/system/include/dfsu_singleton.h | 79 + .../utils/system/include/dfsu_startable.h | 30 + cloud_file/utils/system/include/dfsu_thread.h | 139 + .../system/include/dfsu_thread_safe_queue.h | 102 + cloud_file/utils/system/include/dfsu_timer.h | 36 + cloud_file/utils/system/include/sys_utils.h | 41 + .../utils/system/include/utils_directory.h | 103 + .../system/src/dfsu_access_token_helper.cpp | 151 + cloud_file/utils/system/src/dfsu_fd_guard.cpp | 59 + .../utils/system/src/dfsu_memory_guard.cpp | 42 + .../src/dfsu_mount_argument_descriptors.cpp | 128 + cloud_file/utils/system/src/dfsu_timer.cpp | 66 + cloud_file/utils/system/src/sys_utils.cpp | 52 + .../utils/system/src/utils_directory.cpp | 377 ++ cloud_file/utils/work/include/async_work.h | 30 + cloud_file/utils/work/src/async_work.cpp | 42 + 531 files changed, 83830 insertions(+) create mode 100644 cloud_file/.clang-format create mode 100644 cloud_file/BUILD.gn create mode 100644 cloud_file/CODEOWNERS create mode 100644 cloud_file/LICENSE create mode 100644 cloud_file/README.md create mode 100644 cloud_file/README_zh.md create mode 100644 cloud_file/adapter/cloud_adapter_example/BUILD.gn create mode 100644 cloud_file/adapter/cloud_adapter_example/include/cloud_asset_read_session_impl.h create mode 100644 cloud_file/adapter/cloud_adapter_example/include/cloud_assets_downloader_impl.h create mode 100644 cloud_file/adapter/cloud_adapter_example/include/cloud_database_impl.h create mode 100644 cloud_file/adapter/cloud_adapter_example/include/cloud_file_kit_impl.h create mode 100644 cloud_file/adapter/cloud_adapter_example/include/cloud_sync_helper_impl.h create mode 100644 cloud_file/adapter/cloud_adapter_example/include/data_sync_manager_impl.h create mode 100644 cloud_file/adapter/cloud_adapter_example/src/cloud_asset_read_session_impl.cpp create mode 100644 cloud_file/adapter/cloud_adapter_example/src/cloud_assets_downloader_impl.cpp create mode 100644 cloud_file/adapter/cloud_adapter_example/src/cloud_database_impl.cpp create mode 100644 cloud_file/adapter/cloud_adapter_example/src/cloud_file_kit_impl.cpp create mode 100644 cloud_file/adapter/cloud_adapter_example/src/cloud_sync_helper_impl.cpp create mode 100644 cloud_file/adapter/cloud_adapter_example/src/data_sync_manager_impl.cpp create mode 100644 cloud_file/bundle.json create mode 100644 cloud_file/cfi_blocklist.txt create mode 100644 cloud_file/cloud_file.gni create mode 100644 cloud_file/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_manager_impl.h create mode 100644 cloud_file/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_service_proxy.h create mode 100644 cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager.cpp create mode 100644 cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager_impl.cpp create mode 100644 cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_file_fault_event.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_report_cacher.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_asset_read_session.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_assets_downloader.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_database.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_file_kit.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_sync_helper.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/data_syncer_rdb_store.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/task_state_manager.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync_manager.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/net_conn_callback_observer.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/screen_status.cpp create mode 100644 cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/system_load.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_client.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_stub.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_uri_manager.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_optimize_callback_client.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_optimize_callback_stub.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_asset_manager_impl.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_client.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_stub.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_manager_impl.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_client.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_stub.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/include/service_proxy.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_client.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_stub.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_client.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_stub.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager_impl.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_client.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_stub.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/cloud_sync_manager_impl_lite.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/cloud_sync_manager_lite.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/svc_death_recipient_lite.h create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp create mode 100644 cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_service_proxy_lite.cpp create mode 100644 cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/BUILD.gn create mode 100644 cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_daemon_manager.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/i_cloud_daemon.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/svc_death_recipient.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/BUILD.gn create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/battery_status.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/cloud_file_fault_event.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/cloud_report_cacher.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_asset_read_session.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_assets_downloader.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_database.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_file_kit.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_info.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_status.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_sync_helper.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_const.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_manager.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_syncer_rdb_col.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_syncer_rdb_store.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/net_conn_callback_observer.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/network_set_manager.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/network_status.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/screen_status.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/sync_state_manager.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/system_load.h create mode 100644 cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/task_state_manager.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/BUILD.gn create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_download_callback.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_optimize_callback.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_asset_manager.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_callback.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_constants.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_manager.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/download_asset_callback.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_download_callback.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_optimize_callback.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_callback.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_download_asset_callback.h create mode 100644 cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/svc_death_recipient.h create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/BUILD.gn create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_napi.h create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.h create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/file_sync_napi.h create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h create mode 100644 cloud_file/interfaces/kits/js/cloudsyncmanager/BUILD.gn create mode 100644 cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.h create mode 100644 cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.cpp create mode 100644 cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.h create mode 100644 cloud_file/services/5204.json create mode 100644 cloud_file/services/5205.json create mode 100644 cloud_file/services/BUILD.gn create mode 100644 cloud_file/services/clouddisk_database/BUILD.gn create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_db_const.h create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_notify.h create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_notify_const.h create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_notify_utils.h create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_rdb_transaction.h create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_rdb_utils.h create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_rdbstore.h create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_sync_helper.h create mode 100644 cloud_file/services/clouddisk_database/include/clouddisk_type_const.h create mode 100644 cloud_file/services/clouddisk_database/include/file_column.h create mode 100644 cloud_file/services/clouddisk_database/src/clouddisk_notify.cpp create mode 100644 cloud_file/services/clouddisk_database/src/clouddisk_notify_utils.cpp create mode 100644 cloud_file/services/clouddisk_database/src/clouddisk_rdb_transaction.cpp create mode 100644 cloud_file/services/clouddisk_database/src/clouddisk_rdb_utils.cpp create mode 100644 cloud_file/services/clouddisk_database/src/clouddisk_rdbstore.cpp create mode 100644 cloud_file/services/clouddisk_database/src/clouddisk_sync_helper.cpp create mode 100644 cloud_file/services/clouddisk_database/src/file_column.cpp create mode 100644 cloud_file/services/cloudfiledaemon.cfg create mode 100644 cloud_file/services/cloudfiledaemon/BUILD.gn create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/account_status.h create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/account_status_listener.h create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/cloud_disk_inode.h create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/database_manager.h create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_base.h create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_cloud.h create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_helper.h create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_local.h create mode 100644 cloud_file/services/cloudfiledaemon/include/cloud_disk/fuse_operations.h create mode 100644 cloud_file/services/cloudfiledaemon/include/fuse_manager/cloud_daemon_statistic.h create mode 100644 cloud_file/services/cloudfiledaemon/include/fuse_manager/fuse_manager.h create mode 100644 cloud_file/services/cloudfiledaemon/include/ipc/cloud_daemon.h create mode 100644 cloud_file/services/cloudfiledaemon/include/ipc/cloud_daemon_stub.h create mode 100644 cloud_file/services/cloudfiledaemon/src/cloud_disk/account_status.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/cloud_disk/database_manager.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp create mode 100644 cloud_file/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp create mode 100644 cloud_file/services/cloudfileservice.cfg create mode 100644 cloud_file/services/cloudsyncservice.para create mode 100644 cloud_file/services/cloudsyncservice.para.dac create mode 100644 cloud_file/services/cloudsyncservice/BUILD.gn create mode 100644 cloud_file/services/cloudsyncservice/ICloudSyncService.idl create mode 100644 cloud_file/services/cloudsyncservice/include/cycle_task/cycle_task.h create mode 100644 cloud_file/services/cloudsyncservice/include/cycle_task/cycle_task_runner.h create mode 100644 cloud_file/services/cloudsyncservice/include/cycle_task/tasks/database_backup_task.h create mode 100644 cloud_file/services/cloudsyncservice/include/cycle_task/tasks/optimize_cache_task.h create mode 100644 cloud_file/services/cloudsyncservice/include/cycle_task/tasks/optimize_storage_task.h create mode 100644 cloud_file/services/cloudsyncservice/include/cycle_task/tasks/periodic_check_task.h create mode 100644 cloud_file/services/cloudsyncservice/include/cycle_task/tasks/report_statistics_task.h create mode 100644 cloud_file/services/cloudsyncservice/include/cycle_task/tasks/save_subscription_task.h create mode 100644 cloud_file/services/cloudsyncservice/include/ipc/cloud_sync_service.h create mode 100644 cloud_file/services/cloudsyncservice/include/ipc/download_asset_callback_manager.h create mode 100644 cloud_file/services/cloudsyncservice/include/ipc/download_asset_callback_proxy.h create mode 100644 cloud_file/services/cloudsyncservice/include/sync_rule/battery_status_listener.h create mode 100644 cloud_file/services/cloudsyncservice/include/sync_rule/i_user_status_observer.h create mode 100644 cloud_file/services/cloudsyncservice/include/sync_rule/package_status_listener.h create mode 100644 cloud_file/services/cloudsyncservice/include/sync_rule/screen_status_listener.h create mode 100644 cloud_file/services/cloudsyncservice/include/sync_rule/user_status_listener.h create mode 100644 cloud_file/services/cloudsyncservice/include/transport/file_transfer_manager.h create mode 100644 cloud_file/services/cloudsyncservice/include/transport/message_handler.h create mode 100644 cloud_file/services/cloudsyncservice/include/transport/softbus/i_softbus_listener.h create mode 100644 cloud_file/services/cloudsyncservice/include/transport/softbus/session_manager.h create mode 100644 cloud_file/services/cloudsyncservice/include/transport/softbus/softbus_adapter.h create mode 100644 cloud_file/services/cloudsyncservice/include/transport/softbus/softbus_session.h create mode 100644 cloud_file/services/cloudsyncservice/src/cycle_task/cycle_task.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/cycle_task/cycle_task_runner.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/cycle_task/tasks/database_backup_task.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/cycle_task/tasks/save_subscription_task.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/ipc/cloud_sync_service.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/ipc/download_asset_callback_manager.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/ipc/download_asset_callback_proxy.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/sync_rule/package_status_listener.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/sync_rule/user_status_listener.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/transport/file_transfer_manager.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/transport/message_handler.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/transport/softbus/session_manager.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/transport/softbus/softbus_adapter.cpp create mode 100644 cloud_file/services/cloudsyncservice/src/transport/softbus/softbus_session.cpp create mode 100644 cloud_file/test/fuzztest/BUILD.gn create mode 100644 cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.h create mode 100644 cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/clouddaemonstub_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.h create mode 100644 cloud_file/test/fuzztest/clouddaemonstub_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/clouddaemonstub_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/clouddisknotify_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.h create mode 100644 cloud_file/test/fuzztest/clouddisknotify_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/clouddisknotify_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.h create mode 100644 cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.h create mode 100644 cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.h create mode 100644 cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.h create mode 100644 cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.h create mode 100644 cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/cycletaskrunner_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/cycletaskrunner_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.h create mode 100644 cloud_file/test/fuzztest/cycletaskrunner_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.h create mode 100644 cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.h create mode 100644 cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/ffrttimer_fuzzer/BUILD.gn create mode 100644 cloud_file/test/fuzztest/ffrttimer_fuzzer/corpus/init create mode 100644 cloud_file/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.cpp create mode 100644 cloud_file/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.h create mode 100644 cloud_file/test/fuzztest/ffrttimer_fuzzer/project.xml create mode 100644 cloud_file/test/fuzztest/fuzz_common/cloud_fuzzer_helper.h create mode 100644 cloud_file/test/mock/battersrvclient_mock.cpp create mode 100644 cloud_file/test/mock/battersrvclient_mock.h create mode 100644 cloud_file/test/mock/cloud_daemon_manager_impl_mock.cpp create mode 100644 cloud_file/test/mock/cloud_daemon_manager_mock.cpp create mode 100644 cloud_file/test/mock/cloud_download_uri_manager_hook.cpp create mode 100644 cloud_file/test/mock/cloud_file_kit_mock.cpp create mode 100644 cloud_file/test/mock/clouddisk_notify_mock.cpp create mode 100644 cloud_file/test/mock/cloudsyncservice/transport/softbus_adapter_mock.cpp create mode 100644 cloud_file/test/mock/cloudsyncservice/transport/softbus_adapter_mock.h create mode 100644 cloud_file/test/mock/cloudsyncservice/transport/softbus_session_mock.cpp create mode 100644 cloud_file/test/mock/cloudsyncservice/transport/softbus_session_mock.h create mode 100644 cloud_file/test/mock/device_manager_impl_mock.cpp create mode 100644 cloud_file/test/mock/device_manager_impl_mock.h create mode 100644 cloud_file/test/mock/device_manager_mock.cpp create mode 100644 cloud_file/test/mock/if_system_ability_manager_mock.h create mode 100644 cloud_file/test/mock/ipc/cloud_sync_service_proxy_mock.cpp create mode 100644 cloud_file/test/mock/ipc/cloud_sync_service_proxy_unnomal_mock.cpp create mode 100644 cloud_file/test/mock/message_parcel_mock.cpp create mode 100644 cloud_file/test/mock/message_parcel_mock.h create mode 100644 cloud_file/test/mock/net_conn_client_mock.cpp create mode 100644 cloud_file/test/mock/net_conn_client_mock.h create mode 100644 cloud_file/test/mock/preference_helper_mock.cpp create mode 100644 cloud_file/test/mock/socket_mock.cpp create mode 100644 cloud_file/test/mock/socket_mock.h create mode 100644 cloud_file/test/mock/softbus_bus_center_mock.cpp create mode 100644 cloud_file/test/mock/system_ability_manager_client_mock.cpp create mode 100644 cloud_file/test/mock/system_ability_manager_client_mock.h create mode 100644 cloud_file/test/unittests/BUILD.gn create mode 100644 cloud_file/test/unittests/cloud_daemon/BUILD.gn create mode 100644 cloud_file/test/unittests/cloud_daemon/cloud_daemon_manager_impl_test.cpp create mode 100644 cloud_file/test/unittests/cloud_daemon/cloud_daemon_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloud_daemon/cloud_daemon_service_proxy_test.cpp create mode 100644 cloud_file/test/unittests/cloud_daemon/include/cloud_daemon_service_mock.h create mode 100644 cloud_file/test/unittests/cloud_disk/BUILD.gn create mode 100644 cloud_file/test/unittests/cloud_disk/account_status_listener_test.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/database_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/file_operations_base_test.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/file_operations_cloud_test.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/file_operations_helper_test.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/file_operations_local_test.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/fuse_operations_test.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/mock/assistant.h create mode 100644 cloud_file/test/unittests/cloud_disk/mock/clouddisk_rdbstore_mock.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/mock/file_operations_helper_mock.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/mock/file_operations_local_mock.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/mock/libfuse_mock.cpp create mode 100644 cloud_file/test/unittests/cloud_disk/mock/system_function_mock.cpp create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/BUILD.gn create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/BUILD.gn create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/cloud_file_fault_event_test.cpp create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/cloud_report_cacher_test.cpp create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat_test.cpp create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/cloud_kit/BUILD.gn create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/cloud_kit/cloud_file_kit_test.cpp create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/data_sync/BUILD.gn create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/data_sync/data_syncer_rdb_store_test.cpp create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/data_sync/sync_state_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloud_file_kit_inner/data_sync/task_state_manager_test.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/BUILD.gn create mode 100644 cloud_file/test/unittests/clouddisk_database/clouddisk_notify_test.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/clouddisk_notify_utils_test.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/clouddisk_rdb_transaction_test.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/clouddisk_rdb_utils_test.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/clouddisk_rdbstore_test.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/clouddisk_sync_helper_test.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/include/clouddisk_rdbstore_mock.h create mode 100644 cloud_file/test/unittests/clouddisk_database/include/clouddisk_resultset_mock.h create mode 100644 cloud_file/test/unittests/clouddisk_database/include/result_set_mock.h create mode 100644 cloud_file/test/unittests/clouddisk_database/mock/clouddisk_notify_utils_mock.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/mock/clouddisk_rdb_transaction_mock.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/mock/clouddisk_rdb_utils_mock.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/mock/meta_file_clouddisk_mock.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/mock/rdb_assistant.h create mode 100644 cloud_file/test/unittests/clouddisk_database/mock/rdb_mock.cpp create mode 100644 cloud_file/test/unittests/clouddisk_database/mock/transaction_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_callback_client_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_callback_stub_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_uri_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_impl_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_impl_unnomal_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_callback_client_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_callback_stub_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_common_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_impl_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_impl_unnomal_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_service_proxy_lite_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_service_proxy_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/download_asset_callback_client_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/download_asset_callback_stub_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/file_hook/parcel.cpp create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/asset_callback_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/i_cloud_download_callback_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/i_cloud_sync_service_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/service_callback_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_sa/cycle_task/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_sa/cycle_task/cloud_sync_service_cycle_task_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/dentry/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_sa/dentry/dentry_file_utils_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/dentry/dentry_meta_file_clouddisk_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/dentry/dentry_meta_file_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/dentry/mock/base_interface_lib_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/dentry/mock/base_interface_lib_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/ipc/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_sa/ipc/cloud_sync_service_stub_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/ipc/cloud_sync_service_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/ipc/download_asset_callback_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/ipc/download_asset_callback_proxy_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/log/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_sa/log/dfs_error_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/log/utils_log_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/abs_shared_result_set_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/battery_status_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/cloud_pref_impl_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/cloud_status_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_interface.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/datashare_errno.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/datashare_helper.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/datashare_helper.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/datashare_result_set.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/network_set_manager_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/network_status_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/parameter.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/parameters.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/parameters.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/rdb_store_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/result_set_mock.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/sync_state_manager_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/mock/task_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/battery_status_listener_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/battery_status_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/cloud_status_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/net_conn_callback_observer_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/network_set_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/network_status_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/package_status_listener_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/screen_status_listener_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/system_load_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/sync_rule/user_status_listener_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/system/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_sa/system/dfsu_access_token_helper_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/system/dfsu_fd_guard_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/system/dfsu_mount_argument_descriptors_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/system/reimplement/accesstoken_kit.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/system/reimplement/accesstoken_kit_mock.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/system/reimplement/ipc_skeleton.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/system/reimplement/tokenInfo.h create mode 100644 cloud_file/test/unittests/cloudsync_sa/transport/BUILD.gn create mode 100644 cloud_file/test/unittests/cloudsync_sa/transport/file_transfer_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/transport/message_handler_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/transport/softbus/session_manager_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/transport/softbus/softbus_adapter_test.cpp create mode 100644 cloud_file/test/unittests/cloudsync_sa/transport/softbus/softbus_session_test.cpp create mode 100644 cloud_file/test/unittests/resource/cloud_disk_data_handler_test.txt create mode 100644 cloud_file/test/unittests/resource/cloud_disk_data_handler_test1.txt create mode 100644 cloud_file/test/unittests/resource/ohos_test.xml create mode 100644 cloud_file/test/unittests/services_daemon/BUILD.gn create mode 100644 cloud_file/test/unittests/services_daemon/cloud_daemon_statistic_test.cpp create mode 100644 cloud_file/test/unittests/services_daemon/cloud_daemon_stub_test.cpp create mode 100644 cloud_file/test/unittests/services_daemon/cloud_daemon_test.cpp create mode 100644 cloud_file/test/unittests/services_daemon/fuse_manager_test.cpp create mode 100644 cloud_file/test/unittests/services_daemon/mock/fuse_assistant.h create mode 100644 cloud_file/test/unittests/services_daemon/mock/libfuse_mock.cpp create mode 100644 cloud_file/test/unittests/services_daemon/mock/system_function_mock.cpp create mode 100644 cloud_file/test/unittests/utils/BUILD.gn create mode 100644 cloud_file/test/unittests/utils/cloud_disk/cloud_file_utils_test.cpp create mode 100644 cloud_file/test/unittests/utils/load/plugin_loader_test.cpp create mode 100644 cloud_file/test/unittests/utils/preference/cloud_pref_impl_test.cpp create mode 100644 cloud_file/test/unittests/utils/system/utils_directory_test.cpp create mode 100644 cloud_file/test/unittests/utils/work/async_work_test.cpp create mode 100755 cloud_file/utils/BUILD.gn create mode 100644 cloud_file/utils/cloud_disk/src/cloud_file_utils.cpp create mode 100644 cloud_file/utils/dentry/include/file_utils.h create mode 100644 cloud_file/utils/dentry/include/meta_file.h create mode 100644 cloud_file/utils/dentry/src/file_utils.cpp create mode 100644 cloud_file/utils/dentry/src/meta_file.cpp create mode 100644 cloud_file/utils/dentry/src/meta_file_clouddisk.cpp create mode 100644 cloud_file/utils/dfx/src/xcollie_helper.cpp create mode 100644 cloud_file/utils/ffrt/src/ffrt_timer.cpp create mode 100644 cloud_file/utils/inner_api/block_object.h create mode 100644 cloud_file/utils/inner_api/cloud_file_error.h create mode 100644 cloud_file/utils/inner_api/cloud_file_log.h create mode 100644 cloud_file/utils/inner_api/cloud_file_timer.h create mode 100644 cloud_file/utils/inner_api/cloud_file_utils.h create mode 100644 cloud_file/utils/inner_api/cloud_meta_file.h create mode 100644 cloud_file/utils/inner_api/cloud_pref_impl.h create mode 100644 cloud_file/utils/inner_api/fdsan.h create mode 100644 cloud_file/utils/inner_api/ffrt_timer.h create mode 100644 cloud_file/utils/inner_api/visibility.h create mode 100644 cloud_file/utils/inner_api/xcollie_helper.h create mode 100644 cloud_file/utils/load/include/plugin_loader.h create mode 100644 cloud_file/utils/load/src/plugin_loader.cpp create mode 100644 cloud_file/utils/log/include/dfs_error.h create mode 100644 cloud_file/utils/log/include/utils_log.h create mode 100644 cloud_file/utils/log/src/dfs_error.cpp create mode 100644 cloud_file/utils/log/src/utils_log.cpp create mode 100644 cloud_file/utils/preference/src/cloud_pref_impl.cpp create mode 100644 cloud_file/utils/system/include/dfs_daemon_event_dfx.h create mode 100644 cloud_file/utils/system/include/dfsu_access_token_helper.h create mode 100644 cloud_file/utils/system/include/dfsu_actor.h create mode 100644 cloud_file/utils/system/include/dfsu_cmd.h create mode 100644 cloud_file/utils/system/include/dfsu_exception.h create mode 100644 cloud_file/utils/system/include/dfsu_fd_guard.h create mode 100644 cloud_file/utils/system/include/dfsu_memory_guard.h create mode 100644 cloud_file/utils/system/include/dfsu_mount_argument_descriptors.h create mode 100644 cloud_file/utils/system/include/dfsu_singleton.h create mode 100644 cloud_file/utils/system/include/dfsu_startable.h create mode 100644 cloud_file/utils/system/include/dfsu_thread.h create mode 100644 cloud_file/utils/system/include/dfsu_thread_safe_queue.h create mode 100644 cloud_file/utils/system/include/dfsu_timer.h create mode 100644 cloud_file/utils/system/include/sys_utils.h create mode 100644 cloud_file/utils/system/include/utils_directory.h create mode 100644 cloud_file/utils/system/src/dfsu_access_token_helper.cpp create mode 100644 cloud_file/utils/system/src/dfsu_fd_guard.cpp create mode 100644 cloud_file/utils/system/src/dfsu_memory_guard.cpp create mode 100644 cloud_file/utils/system/src/dfsu_mount_argument_descriptors.cpp create mode 100644 cloud_file/utils/system/src/dfsu_timer.cpp create mode 100644 cloud_file/utils/system/src/sys_utils.cpp create mode 100644 cloud_file/utils/system/src/utils_directory.cpp create mode 100644 cloud_file/utils/work/include/async_work.h create mode 100644 cloud_file/utils/work/src/async_work.cpp diff --git a/cloud_file/.clang-format b/cloud_file/.clang-format new file mode 100644 index 0000000..5820ac6 --- /dev/null +++ b/cloud_file/.clang-format @@ -0,0 +1,162 @@ +Language: Cpp +# BasedOnStyle: LLVM +# 访问说明符(public、private等)的偏移 +AccessModifierOffset: -4 +# 开括号(开圆括号、开尖括号、开方括号)后的对齐 +AlignAfterOpenBracket: Align +# 连续赋值时,等号对齐 +AlignConsecutiveAssignments: false +# 连续赋值时,变量名对齐 +AlignConsecutiveDeclarations: false +# 左对齐逃脱换行(使用反斜杠换行)的反斜杠 +AlignEscapedNewlinesLeft: true +# 水平对齐二元和三元表达式的操作数 +AlignOperands: true +# 对齐连续的尾随的注释 +AlignTrailingComments: true +# 允许函数声明的所有参数在放在下一行 +AllowAllParametersOfDeclarationOnNextLine: false +# 允许短的块放在同一行 +AllowShortBlocksOnASingleLine: false +# 允许短的case标签放在同一行 +AllowShortCaseLabelsOnASingleLine: false +# 允许短的函数放在同一行: None, InlineOnly(定义在类中), Empty(空函数), Inline(定义在类中,空函数), All +AllowShortFunctionsOnASingleLine: Empty +# 允许短的if语句保持在同一行 +AllowShortIfStatementsOnASingleLine: false +# 允许短的循环保持在同一行 +AllowShortLoopsOnASingleLine: false +# 总是在定义返回类型后换行(deprecated) +AlwaysBreakAfterDefinitionReturnType: None +# 总是在返回类型后换行: None, All, TopLevel(顶级函数,不包括在类中的函数), +# AllDefinitions(所有的定义,不包括声明), TopLevelDefinitions(所有的顶级函数的定义) +AlwaysBreakAfterReturnType: None +# 总是在多行string字面量前换行 +AlwaysBreakBeforeMultilineStrings: true +# 总是在template声明后换行 +AlwaysBreakTemplateDeclarations: true +# +SpaceAfterTemplateKeyword: false +# false表示函数实参要么都在同一行,要么都各自一行 +BinPackArguments: true +# false表示所有形参要么都在同一行,要么都各自一行 +BinPackParameters: false +# 大括号换行,只有当BreakBeforeBraces设置为Custom时才有效 +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false +# 在二元运算符前换行: None(在操作符后换行), NonAssignment(在非赋值的操作符前换行), All(在操作符前换行) +BreakBeforeBinaryOperators: None +# 在大括号前换行: Attach(始终将大括号附加到周围的上下文), Linux(除函数、命名空间和类定义,与Attach类似), +# Mozilla(除枚举、函数、记录定义,与Attach类似), Stroustrup(除函数定义、catch、else,与Attach类似), +# Allman(总是在大括号前换行), GNU(总是在大括号前换行,并对于控制语句的大括号增加额外的缩进), WebKit(在函数前换行), Custom +# 注:这里认为语句块也属于函数 +BreakBeforeBraces: Custom +# 在三元运算符前换行 +BreakBeforeTernaryOperators: true +# 在构造函数的初始化列表的逗号前换行 +BreakConstructorInitializersBeforeComma: false +# 每行字符的限制,0表示没有限制 +ColumnLimit: 120 +# 描述具有特殊意义的注释的正则表达式,它不应该被分割为多行或以其它方式改变 +CommentPragmas: "^ IWYU pragma:" +# 构造函数的初始化列表要么都在同一行,要么都各自一行 +ConstructorInitializerAllOnOneLineOrOnePerLine: true +# 构造函数的初始化列表的缩进宽度 +ConstructorInitializerIndentWidth: 4 +# 延续的行的缩进宽度 +ContinuationIndentWidth: 4 +# 去除C++11的列表初始化的大括号{后和}前的空格 +Cpp11BracedListStyle: true +# 继承最常用的指针和引用的对齐方式 +DerivePointerAlignment: false +# 关闭格式化 +DisableFormat: false +# 自动检测函数的调用和定义是否被格式为每行一个参数(Experimental) +ExperimentalAutoDetectBinPacking: false +# 需要被解读为foreach循环而不是函数调用的宏 +ForEachMacros: [foreach, Q_FOREACH, BOOST_FOREACH] +# 对#include进行排序,匹配了某正则表达式的#include拥有对应的优先级,匹配不到的则默认优先级为INT_MAX(优先级越小排序越靠前), +# 可以定义负数优先级从而保证某些#include永远在最前面 +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + - Regex: '^(<|"(gtest|isl|json)/)' + Priority: 3 + - Regex: ".*" + Priority: 1 +# 缩进case标签 +IndentCaseLabels: true +# 缩进宽度 +IndentWidth: 4 +# 函数返回类型换行时,缩进函数声明或函数定义的函数名 +IndentWrappedFunctionNames: true +# 保留在块开始处的空行 +KeepEmptyLinesAtTheStartOfBlocks: true +# 开始一个块的宏的正则表达式 +MacroBlockBegin: "" +# 结束一个块的宏的正则表达式 +MacroBlockEnd: "" +# 连续空行的最大数量 +MaxEmptyLinesToKeep: 1 +# 命名空间的缩进: None, Inner(缩进嵌套的命名空间中的内容), All +NamespaceIndentation: None +# 使用ObjC块时缩进宽度 +ObjCBlockIndentWidth: 4 +# 在ObjC的@property后添加一个空格 +ObjCSpaceAfterProperty: false +# 在ObjC的protocol列表前添加一个空格 +ObjCSpaceBeforeProtocolList: true +# 在call(后对函数调用换行的penalty +PenaltyBreakBeforeFirstCallParameter: 19 +# 在一个注释中引入换行的penalty +PenaltyBreakComment: 300 +# 第一次在<<前换行的penalty +PenaltyBreakFirstLessLess: 120 +# 在一个字符串字面量中引入换行的penalty +PenaltyBreakString: 1000 +# 对于每个在行字符数限制之外的字符的penalty +PenaltyExcessCharacter: 1000000 +# 将函数的返回类型放到它自己的行的penalty +PenaltyReturnTypeOnItsOwnLine: 60 +# 指针和引用的对齐: Left, Right, Middle +PointerAlignment: Right +# 允许重新排版注释 +ReflowComments: true +# 允许排序#include +SortIncludes: true +# 在C风格类型转换后添加空格 +SpaceAfterCStyleCast: false +# 在赋值运算符之前添加空格 +SpaceBeforeAssignmentOperators: true +# 开圆括号之前添加一个空格: Never, ControlStatements, Always +SpaceBeforeParens: ControlStatements +# 在空的圆括号中添加空格 +SpaceInEmptyParentheses: false +# 在尾随的评论前添加的空格数(只适用于//) +SpacesBeforeTrailingComments: 1 +# 在尖括号的<后和>前添加空格 +SpacesInAngles: false +# 在容器(ObjC和JavaScript的数组和字典等)字面量中添加空格 +SpacesInContainerLiterals: true +# 在C风格类型转换的括号中添加空格 +SpacesInCStyleCastParentheses: false +# 在圆括号的(后和)前添加空格 +SpacesInParentheses: false +# 在方括号的[后和]前添加空格,lamda表达式和未指明大小的数组的声明不受影响 +SpacesInSquareBrackets: false +# 标准: Cpp03, Cpp11, Auto +Standard: Cpp11 +# tab宽度 +TabWidth: 4 +# 使用tab字符: Never, ForIndentation, ForContinuationAndIndentation, Always +UseTab: Never \ No newline at end of file diff --git a/cloud_file/BUILD.gn b/cloud_file/BUILD.gn new file mode 100644 index 0000000..b7ae224 --- /dev/null +++ b/cloud_file/BUILD.gn @@ -0,0 +1,56 @@ +# 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. +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +group("services_target") { + deps = [ + "${services_path}:cloudsyncservice.para", + "${services_path}:cloudsyncservice.para.dac", + "${services_path}:cloudfileservice_etc", + "${services_path}:distributedfile_sa_profile", + "${services_path}/clouddisk_database:clouddisk_database", + "${services_path}/cloudfiledaemon:cloudfiledaemon", + "${services_path}/cloudsyncservice:cloudsync_sa", + ] + + if (cloud_file_feature_enable_cloud_adapter) { + deps += [ "${services_path}:cloudfiledaemon_etc" ] + } +} + +group("cloudsync_kit_inner_target") { + deps = + [ "interfaces/inner_api/native/cloudsync_kit_inner:cloudsync_kit_inner" ] +} + +group("cloud_daemon_kit_inner_target") { + deps = [ + "interfaces/inner_api/native/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + ] +} + +group("cloud_file_kit_inner_target") { + deps = [ "interfaces/inner_api/native/cloud_file_kit_inner:cloudfile_kit" ] +} + +group("cloudsync_asset_kit_inner_target") { + deps = [ + "interfaces/inner_api/native/cloudsync_kit_inner:cloudsync_asset_kit_inner", + ] +} + +group("cloudsync_test_module") { + testonly = true + deps = [ "test/unittests:cloudsyncunittests" ] +} \ No newline at end of file diff --git a/cloud_file/CODEOWNERS b/cloud_file/CODEOWNERS new file mode 100644 index 0000000..27585f3 --- /dev/null +++ b/cloud_file/CODEOWNERS @@ -0,0 +1,17 @@ +# Copyright (c) 2023-2025 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. + +# any change to xxx_ipc_interface_code.h needs to be reviewed by @leonchan5 +[InterfaceCode] +interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h @leonchan5 +interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h @leonchan5 \ No newline at end of file diff --git a/cloud_file/LICENSE b/cloud_file/LICENSE new file mode 100644 index 0000000..4947287 --- /dev/null +++ b/cloud_file/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/cloud_file/README.md b/cloud_file/README.md new file mode 100644 index 0000000..375304f --- /dev/null +++ b/cloud_file/README.md @@ -0,0 +1,36 @@ +# storage_distributed_file_manager + +#### Description +{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} + +#### Software Architecture +Software architecture description + +#### Installation + +1. xxxx +2. xxxx +3. xxxx + +#### Instructions + +1. xxxx +2. xxxx +3. xxxx + +#### Contribution + +1. Fork the repository +2. Create Feat_xxx branch +3. Commit your code +4. Create Pull Request + + +#### Gitee Feature + +1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md +2. Gitee blog [blog.gitee.com](https://blog.gitee.com) +3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) +4. The most valuable open source project [GVP](https://gitee.com/gvp) +5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) +6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/cloud_file/README_zh.md b/cloud_file/README_zh.md new file mode 100644 index 0000000..cc84e19 --- /dev/null +++ b/cloud_file/README_zh.md @@ -0,0 +1,82 @@ +# 分布式文件服务 + +## **简介** + +分布式文件服务提供跨设备的、符合POSIX规范的文件访问能力。其在分布式软总线动态组网的基础上,为网络上各个设备结点提供一个统一的、逻辑的、树形的文件系统层次结构。 + +
**图1**. 分布式文件系统架构图
+![架构图](https://images.gitee.com/uploads/images/2022/0107/113135_1cef6c44_7809790.png "hmdfs架构图update20220107.png") + + +其包括如下几个核心模块: + +- distributed_file_daemon:分布式文件管理常驻用户态服务,负责接入设备组网、数据传输能力,并负责挂载hmdfs。 +- distributed_file_service:分布式文件访问能力服务,对应用提供分布式扩展能力。 +- hmdfs(Harmony Distributed File System):分布式文件系统核心模块,是一种面向移动分布式场景的、高性能的、基于内核实现的、堆叠式文件系统。 + +## **目录** + +```raw +/ +├── frameworks // 接口实现 +│ └── native // c/c++ 接口实现 +├── interfaces // 接口声明 +│ └── inner_API // 对内接口声明 +├── services // 服务实现 +│ └── distributed_file_daemon // daemon常驻服务实现 +| └── include // daemon常驻服务头文件,类声明 +| └── src // daemon常驻服务源文件 +| └── device // 设备上下线管理 +| └── ipc // daemon进程拉起退出流程以及ipc接口实现 +| └── mount_point // hmdfs挂载管理 +| └── network // 软总线和内核会话session交互相关 +| └── test // 测试代码 +| └── distributed_file_service // 对应用提供扩展能力的服务实现 +├── utils // 公共组件 +| ├── log // 日志组件 +| └── system // 平台相关组件 +``` + +## **约束** + +### 接口支持情况 + +分布式文件管理当前不支持或有限支持如下 VFS 系统调用: + +- symlink:不支持 +- mmap:仅支持读 +- rename:仅支持同目录操作 + +### 规格 + +- 最大目录层级 + + 与被堆叠文件系统,即data分区所用文件系统,如ext4,f2fs等保持一致。 +- 最大文件名长度 + + 取决于680B与被堆叠文件支持长度的最小值。f2fs和ext4均为255B。 +- 最大单文件大小 + + 取决于$2^{64}$B与被堆叠文件系统支持最大单文件大小的最小值。ext4单文件最大为16TB,f2fs单文件最大为3.94TB。 + +## **说明** + +### 使用说明 + +可以使用终端调试分布式文件管理能力。 +- 环境准备 + +1) 设备A和设备B连接同一局域网 +2) 设备A和设备B登录同一华为账号 +- 分布式文件系统能力使用 + +1) 经过以上环境准备后,即建立了设备间分布式文件互相访问的能力。 +2) 可以在应用内通过```context.distributedFileDir()```接口获取本应用沙箱内的分布式路径。 +3) 在此路径下可以像操作本地文件一样,操作远端设备的文件,比如可以进行创建、删除、读写文件和目录。 +4) 在一端设备上进行步骤3的文件操作后,在组网的所有分布式设备上都可以查看相应的修改。 + +## 相关仓 + +- [分布式软总线-SoftBus](https://gitee.com/openharmony/communication_dsoftbus) +- [分布式硬件-设备管理](https://gitee.com/openharmony/device_manager) +- [用户程序框架](https://gitee.com/openharmony/appexecfwk_standard) diff --git a/cloud_file/adapter/cloud_adapter_example/BUILD.gn b/cloud_file/adapter/cloud_adapter_example/BUILD.gn new file mode 100644 index 0000000..294e632 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/BUILD.gn @@ -0,0 +1,73 @@ +# 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +group("cloud_adapter_example_target") { + deps = [] + if (!cloud_file_feature_enable_cloud_adapter) { + deps += [ + "${cloud_file_path}/adapter/cloud_adapter_example:cloud_adapter", + ] + } +} + +config("public_config") { + include_dirs = + [ "${cloud_file_path}/adapter/cloud_adapter_example/include" ] +} + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("cloud_adapter") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "${cloud_file_path}/adapter/cloud_adapter_example/src/cloud_asset_read_session_impl.cpp", + "${cloud_file_path}/adapter/cloud_adapter_example/src/cloud_assets_downloader_impl.cpp", + "${cloud_file_path}/adapter/cloud_adapter_example/src/cloud_database_impl.cpp", + "${cloud_file_path}/adapter/cloud_adapter_example/src/cloud_file_kit_impl.cpp", + "${cloud_file_path}/adapter/cloud_adapter_example/src/cloud_sync_helper_impl.cpp", + "${cloud_file_path}/adapter/cloud_adapter_example/src/data_sync_manager_impl.cpp", + ] + + public_configs = [ ":public_config" ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + ] + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/adapter/cloud_adapter_example/include/cloud_asset_read_session_impl.h b/cloud_file/adapter/cloud_adapter_example/include/cloud_asset_read_session_impl.h new file mode 100644 index 0000000..b022fd9 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/include/cloud_asset_read_session_impl.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_ASSET_READ_SESSION_IMPL_H +#define OHOS_CLOUD_FILE_CLOUD_ASSET_READ_SESSION_IMPL_H + +#include "cloud_asset_read_session.h" + +namespace OHOS::FileManagement::CloudFile { +class CloudAssetReadSessionImpl : public CloudAssetReadSession { +public: + CloudAssetReadSessionImpl(const int32_t userId, + std::string recordType, + std::string recordId, + std::string assetKey, + std::string assetPath); +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_ASSET_READ_SESSION_IMPL_H \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/include/cloud_assets_downloader_impl.h b/cloud_file/adapter/cloud_adapter_example/include/cloud_assets_downloader_impl.h new file mode 100644 index 0000000..9093899 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/include/cloud_assets_downloader_impl.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_ASSETS_DOWNLOADER_IMPL_H +#define OHOS_CLOUD_FILE_CLOUD_ASSETS_DOWNLOADER_IMPL_H + +#include "cloud_assets_downloader.h" + +namespace OHOS::FileManagement::CloudFile { +class CloudAssetsDownloaderImpl final : public CloudAssetsDownloader { +public: + CloudAssetsDownloaderImpl(const int32_t userId, const std::string &bundleName); +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_ASSETS_DOWNLOADER_IMPL_H \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/include/cloud_database_impl.h b/cloud_file/adapter/cloud_adapter_example/include/cloud_database_impl.h new file mode 100644 index 0000000..0ae5803 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/include/cloud_database_impl.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_DATABASE_IMPL_H +#define OHOS_CLOUD_FILE_CLOUD_DATABASE_IMPL_H + +#include "cloud_database.h" + +namespace OHOS::FileManagement::CloudFile { +class CloudDatabaseImpl : public CloudDatabase { +public: + CloudDatabaseImpl(const int32_t userId, const std::string &bundleName); + std::shared_ptr NewAssetReadSession(const int32_t userId, + std::string recordType, + std::string recordId, + std::string assetKey, + std::string assetPath) override; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_DATABASE_IMPL_H \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/include/cloud_file_kit_impl.h b/cloud_file/adapter/cloud_adapter_example/include/cloud_file_kit_impl.h new file mode 100644 index 0000000..2086c7f --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/include/cloud_file_kit_impl.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_FILE_KIT_IMPL_H +#define OHOS_CLOUD_FILE_CLOUD_FILE_KIT_IMPL_H + +#include "cloud_file_kit.h" +#include + +namespace OHOS::FileManagement::CloudFile { +class CloudFileKitImpl final : public CloudFileKit { +public: + int32_t GetCloudUserInfo(const int32_t userId, CloudUserInfo &userInfo) override; + std::pair GetSpaceInfo(const int32_t userId, const std::string& bundleName) override; + int32_t GetAppSwitchStatus(const std::string &bundleName, const int32_t userId, bool &switchStatus) override; + int32_t ResolveNotificationEvent(const int32_t userId, + const std::string &extraData, + std::string &appBundleName, + std::string &prepareTraceId) override; + + std::shared_ptr GetDataSyncManager() override; + std::shared_ptr GetCloudAssetsDownloader(const int32_t userId, + const std::string &bundleName) override; + std::shared_ptr GetCloudDatabase(const int32_t userId, const std::string &bundleName) override; + std::shared_ptr GetCloudSyncHelper(const int32_t userId, const std::string &bundleName) override; + std::string GetPrepareTraceId(const int32_t userId) override; + +private: + std::mutex dataSyncManagerMutex_; + std::shared_ptr dataSyncManager_; + + std::mutex cloudAssetsDownloaderMutex_; + std::shared_ptr cloudAssetsDownloader_; + + std::mutex cloudSyncHelperMutex_; + std::shared_ptr cloudSyncHelper_; + + std::mutex cloudDatabaseMutex_; + std::shared_ptr cloudDatabase_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_FILE_KIT_IMPL_H \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/include/cloud_sync_helper_impl.h b/cloud_file/adapter/cloud_adapter_example/include/cloud_sync_helper_impl.h new file mode 100644 index 0000000..e002d41 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/include/cloud_sync_helper_impl.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_SYNC_HELPER_IMPL_H +#define OHOS_CLOUD_FILE_CLOUD_SYNC_HELPER_IMPL_H + +#include "cloud_sync_helper.h" +#include + +namespace OHOS::FileManagement::CloudFile { +class CloudSyncHelperImpl : public CloudSyncHelper { +public: + CloudSyncHelperImpl(const int32_t userId, const std::string &bundleName); + + int32_t SaveSubScription() override; + int32_t Init() override; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_SYNC_HELPER_IMPL_H \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/include/data_sync_manager_impl.h b/cloud_file/adapter/cloud_adapter_example/include/data_sync_manager_impl.h new file mode 100644 index 0000000..c1d101c --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/include/data_sync_manager_impl.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_DATA_SYNC_MANAGER_IMPL_H +#define OHOS_CLOUD_FILE_DATA_SYNC_MANAGER_IMPL_H + +#include "data_sync_manager.h" + +namespace OHOS::FileManagement::CloudFile { +class DataSyncManagerImpl : public DataSyncManager { +public: + virtual int32_t TriggerStartSync(const std::string &bundleName, + const int32_t userId, + bool forceFlag, + SyncTriggerType triggerType, + std::string prepareTraceId = ""); +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_DATA_SYNC_MANAGER_IMPL_H \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/src/cloud_asset_read_session_impl.cpp b/cloud_file/adapter/cloud_adapter_example/src/cloud_asset_read_session_impl.cpp new file mode 100644 index 0000000..73e6fed --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/src/cloud_asset_read_session_impl.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024 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 "cloud_asset_read_session_impl.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +CloudAssetReadSessionImpl::CloudAssetReadSessionImpl(const int32_t userId, + std::string recordType, + std::string recordId, + std::string assetKey, + std::string assetPath) + : CloudAssetReadSession(userId, recordType, recordId, assetKey, assetPath) +{ +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/src/cloud_assets_downloader_impl.cpp b/cloud_file/adapter/cloud_adapter_example/src/cloud_assets_downloader_impl.cpp new file mode 100644 index 0000000..373b9cb --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/src/cloud_assets_downloader_impl.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 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 "cloud_assets_downloader_impl.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +CloudAssetsDownloaderImpl::CloudAssetsDownloaderImpl(const int32_t userId, const string &bundleName) + : CloudAssetsDownloader(userId, bundleName) +{ +} + +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/src/cloud_database_impl.cpp b/cloud_file/adapter/cloud_adapter_example/src/cloud_database_impl.cpp new file mode 100644 index 0000000..e7db228 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/src/cloud_database_impl.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 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 "cloud_database_impl.h" + +#include "cloud_asset_read_session_impl.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +CloudDatabaseImpl::CloudDatabaseImpl(const int32_t userId, const string &bundleName) + : CloudDatabase(userId, bundleName) +{ +} + +std::shared_ptr CloudDatabaseImpl::NewAssetReadSession(const int32_t userId, + std::string recordType, + std::string recordId, + std::string assetKey, + std::string assetPath) +{ + return std::make_shared(userId, recordType, recordId, assetKey, assetPath); +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/src/cloud_file_kit_impl.cpp b/cloud_file/adapter/cloud_adapter_example/src/cloud_file_kit_impl.cpp new file mode 100644 index 0000000..542c091 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/src/cloud_file_kit_impl.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2024 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 "cloud_file_kit_impl.h" + +#include + +#include "cloud_database_impl.h" +#include "cloud_assets_downloader_impl.h" +#include "cloud_sync_helper_impl.h" +#include "data_sync_manager_impl.h" +#include "dfs_error.h" + + +namespace OHOS::FileManagement::CloudFile { + +__attribute__((used)) static bool g_isInit = + CloudFileKit::RegisterCloudInstance(new (std::nothrow) CloudFileKitImpl()); + +using namespace std; + +int32_t CloudFileKitImpl::GetCloudUserInfo(const int32_t userId, CloudUserInfo &userInfo) +{ + userInfo.enableCloud = true; + return E_OK; +} + +std::pair CloudFileKitImpl::GetSpaceInfo(const int32_t userId, const std::string &bundleName) +{ + return std::make_pair(0, 0); +} + +int32_t CloudFileKitImpl::GetAppSwitchStatus(const std::string &bundleName, + const int32_t userId, + bool &switchStatus) +{ + switchStatus = true; + return E_OK; +} + +int32_t CloudFileKitImpl::ResolveNotificationEvent(const int32_t userId, + const std::string &extraData, + std::string &appBundleName, + std::string &prepareTraceId) +{ + appBundleName = "com.ohos.photos"; + return E_OK; +} + +std::shared_ptr CloudFileKitImpl::GetDataSyncManager() +{ + std::lock_guard lck(dataSyncManagerMutex_); + if (dataSyncManager_ == nullptr) { + dataSyncManager_ = std::make_shared(); + } + return dataSyncManager_; +} + +std::shared_ptr CloudFileKitImpl::GetCloudAssetsDownloader(const int32_t userId, + const std::string &bundleName) +{ + std::lock_guard lck(cloudAssetsDownloaderMutex_); + if (cloudAssetsDownloader_ == nullptr) { + cloudAssetsDownloader_ = std::make_shared(userId, bundleName); + } + return cloudAssetsDownloader_; +} + +std::shared_ptr CloudFileKitImpl::GetCloudSyncHelper(const int32_t userId, + const std::string &bundleName) +{ + std::lock_guard lck(cloudSyncHelperMutex_); + if (cloudSyncHelper_ == nullptr) { + std::shared_ptr cloudSyncHelper = std::make_shared(userId, bundleName); + if (cloudSyncHelper->Init() == E_OK) { + cloudSyncHelper_ = cloudSyncHelper; + } + } + return cloudSyncHelper_; +} + +std::shared_ptr CloudFileKitImpl::GetCloudDatabase(const int32_t userId, const std::string &bundleName) +{ + std::lock_guard lck(cloudDatabaseMutex_); + if (cloudDatabase_ == nullptr) { + auto cloudDatabase = std::make_shared(userId, bundleName); + if (cloudDatabase->Init() == E_OK) { + cloudDatabase_ = cloudDatabase; + } + } + return cloudDatabase_; +} + +std::string CloudFileKitImpl::GetPrepareTraceId(const int32_t userId) +{ + return ""; +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/src/cloud_sync_helper_impl.cpp b/cloud_file/adapter/cloud_adapter_example/src/cloud_sync_helper_impl.cpp new file mode 100644 index 0000000..e65adc5 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/src/cloud_sync_helper_impl.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 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 "cloud_sync_helper_impl.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +CloudSyncHelperImpl::CloudSyncHelperImpl(const int32_t userId, const string &bundleName) + : CloudSyncHelper(userId, bundleName) +{ +} + +int32_t CloudSyncHelperImpl::Init() +{ + (void)userId_; + (void)bundleName_; + return E_OK; +} + +int32_t CloudSyncHelperImpl::SaveSubScription() +{ + return E_OK; +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/adapter/cloud_adapter_example/src/data_sync_manager_impl.cpp b/cloud_file/adapter/cloud_adapter_example/src/data_sync_manager_impl.cpp new file mode 100644 index 0000000..cbfb8d8 --- /dev/null +++ b/cloud_file/adapter/cloud_adapter_example/src/data_sync_manager_impl.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024 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 "data_sync_manager_impl.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +int32_t DataSyncManagerImpl::TriggerStartSync(const std::string &bundleName, + const int32_t userId, + bool forceFlag, + SyncTriggerType triggerType, + std::string prepareTraceId) +{ + return E_OK; +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/bundle.json b/cloud_file/bundle.json new file mode 100644 index 0000000..a0d305d --- /dev/null +++ b/cloud_file/bundle.json @@ -0,0 +1,170 @@ +{ + "name": "@ohos/cloud_file", + "version": "3.1", + "description": "The cloud_file module belongs to the filemanagement subsystem of OpenHarmony. It provides the ability of accessing distributed files.", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "kernel/linux/common_modules/cloud_file" + }, + "dirs": {}, + "scripts": {}, + "author": {}, + "repository": "", + "component": { + "name": "cloud_file", + "subsystem": "kernel", + "syscap": [ + "SystemCapability.FileManagement.DistributedFileService.CloudSync.Core", + "SystemCapability.FileManagement.DistributedFileService.CloudSyncManager" + ], + "features": [ + "cloud_file_feature_enable_cloud_adapter", + "cloud_file_feature_enable_dist_file_daemon" + ], + "adapted_system_type": [ + "small", + "standard" + ], + "rom": "2048KB", + "ram": "4096KB", + "deps": { + "components": [ + "ability_base", + "ability_runtime", + "access_token", + "app_file_service", + "battery_manager", + "c_utils", + "common_event_service", + "dataclassification", + "data_share", + "device_auth", + "device_manager", + "dsoftbus", + "eventhandler", + "e2fsprogs", + "ffrt", + "file_api", + "hicollie", + "hilog", + "hisysevent", + "hitrace", + "init", + "ipc", + "json", + "napi", + "preferences", + "media_library", + "netmanager_base", + "relational_store", + "safwk", + "storage_service", + "samgr", + "os_account", + "power_manager", + "resource_schedule_service", + "libfuse", + "zlib" + ] + }, + "build": { + "group_type": { + "base_group": [], + "fwk_group": [], + "service_group": [ + "//kernel/linux/common_modules/cloud_file:services_target", + "//kernel/linux/common_modules/cloud_file:cloudsync_kit_inner_target", + "//kernel/linux/common_modules/cloud_file:cloud_daemon_kit_inner_target", + "//kernel/linux/common_modules/cloud_file:cloud_file_kit_inner_target", + "//kernel/linux/common_modules/cloud_file:cloudsync_asset_kit_inner_target", + "//kernel/linux/common_modules/cloud_file/interfaces/kits/js/cloudsyncmanager:cloudsyncmanager", + "//kernel/linux/common_modules/cloud_file/interfaces/kits/js/cloudfilesync:cloudsync", + "//kernel/linux/common_modules/cloud_file/adapter/cloud_adapter_example:cloud_adapter_example_target" + ] + }, + "inner_kits": [ + { + "name": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner:cloudsync_kit_inner", + "header": { + "header_files": [ + "cloud_sync_callback.h", + "cloud_sync_manager.h", + "i_cloud_sync_callback.h", + "svc_death_recipient.h", + "cloud_sync_constants.h", + "cloud_sync_common.h" + ], + "header_base": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner" + } + }, + { + "name": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner:cloudsync_asset_kit_inner", + "header": { + "header_files": [ + "cloud_sync_asset_manager.h" + ], + "header_base": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner" + } + }, + { + "name": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + "header": { + "header_files": [ + "cloud_daemon_manager.h", + "i_cloud_daemon.h", + "svc_death_recipient.h" + ], + "header_base": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner" + } + }, + { + "name": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner:cloudfile_kit", + "header": { + "header_files": [], + "header_base": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner" + } + }, + { + "name": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner:cloudfile_kit_core", + "header": { + "header_files": [], + "header_base": "//kernel/linux/common_modules/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner" + } + }, + { + "name": "//kernel/linux/common_modules/cloud_file/services/clouddisk_database:clouddisk_database", + "header": { + "header_files": [], + "header_base": "//kernel/linux/common_modules/cloud_file/services/clouddisk_database/include" + } + }, + { + "name": "//kernel/linux/common_modules/cloud_file/utils:libdistributedfiledentry", + "header": { + "header_files": [], + "header_base": "//kernel/linux/common_modules/cloud_file/utils/inner_api" + } + }, + { + "name": "//kernel/linux/common_modules/cloud_file/utils:libdistributedfileutils", + "header": { + "header_files": [], + "header_base": "//kernel/linux/common_modules/cloud_file/utils/inner_api" + } + }, + { + "name": "//kernel/linux/common_modules/cloud_file/utils:libdistributedfileutils_lite", + "header": { + "header_files": [], + "header_base": "//kernel/linux/common_modules/cloud_file/utils/inner_api" + } + } + ], + "test": [ + "//kernel/linux/common_modules/cloud_file:cloudsync_test_module", + "//kernel/linux/common_modules/cloud_file/test/fuzztest:cloud_file_fuzztest" + ] + } + } +} \ No newline at end of file diff --git a/cloud_file/cfi_blocklist.txt b/cloud_file/cfi_blocklist.txt new file mode 100644 index 0000000..ee95fc9 --- /dev/null +++ b/cloud_file/cfi_blocklist.txt @@ -0,0 +1,41 @@ +# Copyright (C) 2022-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. + +[cfi] +type:*OHOS::Parcel* +type:*OHOS::RefBase* +type:*OHOS::MessageParcel* +type:*OHOS::IRemoteObject* +type:*OHOS::IRemoteBroker* +type:*OHOS::FileManagement::CloudFile::IRemoteProxy* +type:*OHOS::FileManagement::CloudFile::ICloudDaemon* +type:*OHOS::FileManagement::CloudSync::ICloudDownloadCallback* +type:*OHOS::FileManagement::CloudSync::ICloudSyncCallback* +type:*OHOS::FileManagement::CloudSync::ICloudSyncService* +type:*OHOS::Storage::DistributedFile::IDaemon* +type:*OHOS::ISystemAbilityManager* +type:*OHOS::ThreadPool* +type:*OHOS::Media::MediaFileUri* +type:*OHOS::IPCSkeleton* +type:*OHOS::Security::AccessToken::AccessTokenKit* +type:*OHOS::NativeRdb* +type:*OHOS::AAFwk::SystemAbilityManagerClient* +type:*OHOS::SystemAbility* +type:*OHOS::NativeRdb* +src:*cloud_download_callback_stub.cpp +src:*cloud_sync_callback_stub.cpp +src:*cloud_daemon_stub.cpp +src:*daemon_stub.cpp +src:*dfsu_access_token_helper.cpp +src:*third_party/googletest/googlemock/include/gmock/* +src:*third_party/googletest/googletest/include/gtest/* \ No newline at end of file diff --git a/cloud_file/cloud_file.gni b/cloud_file/cloud_file.gni new file mode 100644 index 0000000..a895b40 --- /dev/null +++ b/cloud_file/cloud_file.gni @@ -0,0 +1,57 @@ +# Copyright (c) 2021 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. + +ability_base_kits_path = "//foundation/ability/ability_base/interfaces/kits" +ability_runtime_kits_path = + "//foundation/ability/ability_runtime/frameworks/kits" + +cloud_file_path = "//kernel/linux/common_modules/cloud_file" + +utils_path = "${cloud_file_path}/utils" +services_path = "${cloud_file_path}/services" +innerkits_native_path = "${cloud_file_path}/interfaces/inner_api/native" +bas_hiviewdfx_hilog_path = "//base/hiviewdfx/hilog" +communication_ipc_path = "//foundation/communication" +image_framework_path = "//foundation/multimedia/image_framework" +clouddisk_database_path = "${services_path}/clouddisk_database" + +declare_args() { + if (defined(global_parts_info) && + defined(global_parts_info.powermgr_battery_manager)) { + cloudsync_service_power = true + } else { + cloudsync_service_power = false + } + cloud_file_feature_enable_cloud_adapter = false + cloud_file_feature_enable_dist_file_daemon = true + if (defined(global_parts_info) && + defined(global_parts_info.multimedia_media_library)) { + cloudsync_service_media_library = true + } else { + cloudsync_service_media_library = false + } + + if (defined(global_parts_info) && + defined(global_parts_info.resourceschedule_resource_schedule_service)) { + cloudsync_service_resource_schedule = true + } else { + cloudsync_service_resource_schedule = false + } + + if (defined(global_parts_info) && + defined(global_parts_info.hiviewdfx_hicollie)) { + cloudsync_service_hicollie_enable = true + } else { + cloudsync_service_hicollie_enable = false + } +} diff --git a/cloud_file/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_manager_impl.h b/cloud_file/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_manager_impl.h new file mode 100644 index 0000000..19f9b6d --- /dev/null +++ b/cloud_file/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_manager_impl.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 OHOS_STORAGE_CLOUD_DAEMON_MANAGER_IMPL_H +#define OHOS_STORAGE_CLOUD_DAEMON_MANAGER_IMPL_H + +#include +#include + +#include "cloud_daemon_manager.h" +#include "nocopyable.h" +#include "svc_death_recipient.h" + +namespace OHOS::FileManagement::CloudFile { +class CloudDaemonManagerImpl final : public CloudDaemonManager, public NoCopyable { +public: + static CloudDaemonManagerImpl &GetInstance(); + + int32_t StartFuse(int32_t userId, int32_t devFd, const string &path) override; + +private: + CloudDaemonManagerImpl() = default; + void SetDeathRecipient(const sptr &remoteObject); + + std::atomic_flag isFirstCall_{false}; + std::mutex recipientMutex_; + sptr deathRecipient_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_STORAGE_CLOUD_DAEMON_MANAGER_IMPL_H diff --git a/cloud_file/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_service_proxy.h b/cloud_file/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_service_proxy.h new file mode 100644 index 0000000..48de17d --- /dev/null +++ b/cloud_file/frameworks/native/cloud_daemon_kit_inner/include/cloud_daemon_service_proxy.h @@ -0,0 +1,41 @@ +/* + * 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 OHOS_STORAGE_CLOUD_DAEMON_SERVICE_PROXY_H +#define OHOS_STORAGE_CLOUD_DAEMON_SERVICE_PROXY_H + +#include "i_cloud_daemon.h" +#include "iremote_proxy.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +class CloudDaemonServiceProxy : public IRemoteProxy { +public: + explicit CloudDaemonServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} + ~CloudDaemonServiceProxy() override {} + + static sptr GetInstance(); + static void InvaildInstance(); + + int32_t StartFuse(int32_t userId, int32_t devFd, const string &path) override; + +private: + static inline std::mutex proxyMutex_; + static inline sptr serviceProxy_; + static inline BrokerDelegator delegator_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_STORAGE_CLOUD_DAEMON_SERVICE_PROXY_H diff --git a/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager.cpp b/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager.cpp new file mode 100644 index 0000000..d8f7800 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager.cpp @@ -0,0 +1,24 @@ +/* + * 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 "cloud_daemon_manager_impl.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +CloudDaemonManager &CloudDaemonManager::GetInstance() +{ + return CloudDaemonManagerImpl::GetInstance(); +} +} // namespace OHOS::FileManagement::CloudFile diff --git a/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager_impl.cpp b/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager_impl.cpp new file mode 100644 index 0000000..91e6d4f --- /dev/null +++ b/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager_impl.cpp @@ -0,0 +1,56 @@ +/* + * 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 "cloud_daemon_manager_impl.h" +#include "cloud_daemon_service_proxy.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +using namespace OHOS::FileManagement; +CloudDaemonManagerImpl &CloudDaemonManagerImpl::GetInstance() +{ + static CloudDaemonManagerImpl instance; + return instance; +} + +int32_t CloudDaemonManagerImpl::StartFuse(int32_t userId, int32_t devFd, const string &path) +{ + auto CloudDaemonServiceProxy = CloudDaemonServiceProxy::GetInstance(); + if (!CloudDaemonServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + if (!isFirstCall_.test_and_set()) { + SetDeathRecipient(CloudDaemonServiceProxy->AsObject()); + } + + return CloudDaemonServiceProxy->StartFuse(userId, devFd, path); +} + +void CloudDaemonManagerImpl::SetDeathRecipient(const sptr &remoteObject) +{ + auto deathCallback = [this](const wptr &obj) { + LOGE("service died. Died remote obj"); + CloudDaemonServiceProxy::InvaildInstance(); + isFirstCall_.clear(); + }; + std::lock_guard lock(recipientMutex_); + deathRecipient_ = sptr(new SvcDeathRecipient(deathCallback)); + remoteObject->AddDeathRecipient(deathRecipient_); +} +} // namespace OHOS::FileManagement::CloudFile diff --git a/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp b/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp new file mode 100644 index 0000000..9782fb6 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp @@ -0,0 +1,107 @@ +/* + * 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 "cloud_daemon_service_proxy.h" + +#include + +#include "cloud_file_daemon_interface_code.h" +#include "dfs_error.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +using namespace OHOS::FileManagement; + +int32_t CloudDaemonServiceProxy::StartFuse(int32_t userId, int32_t devFd, const string &path) +{ + LOGI("Start fuse"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + LOGE("Failed to write interface token"); + return E_BROKEN_IPC; + } + + if (!data.WriteInt32(userId)) { + LOGE("Failed to send user id"); + return E_INVAL_ARG; + } + + if (!data.WriteFileDescriptor(devFd)) { + LOGE("Failed to send the device file fd"); + return E_INVAL_ARG; + } + + if (!data.WriteString(path)) { + LOGE("Failed to send the device file path"); + return E_INVAL_ARG; + } + + auto remote = Remote(); + if (!remote) { + LOGE("remote is nullptr"); + return E_BROKEN_IPC; + } + int32_t ret = remote->SendRequest(static_cast(CloudFileDaemonInterfaceCode::CLOUD_DAEMON_CMD_START_FUSE), + data, reply, option); + if (ret != E_OK) { + stringstream ss; + ss << "Failed to send out the requeset, errno:" << ret; + LOGE("%{public}s", ss.str().c_str()); + return E_BROKEN_IPC; + } + LOGI("StartFuseInner Success"); + return reply.ReadInt32(); +} + +sptr CloudDaemonServiceProxy::GetInstance() +{ + LOGI("getinstance"); + unique_lock lock(proxyMutex_); + if (serviceProxy_ != nullptr) { + return serviceProxy_; + } + + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Samgr is nullptr"); + return nullptr; + } + + auto object = samgr->CheckSystemAbility(FILEMANAGEMENT_CLOUD_DAEMON_SERVICE_SA_ID); + if (object == nullptr) { + LOGE("CloudDaemon::Connect object == nullptr"); + return nullptr; + } + + serviceProxy_ = iface_cast(object); + if (serviceProxy_ == nullptr) { + LOGE("CloudDaemon::Connect service == nullptr"); + return nullptr; + } + return serviceProxy_; +} + +void CloudDaemonServiceProxy::InvaildInstance() +{ + LOGI("invalid instance"); + unique_lock lock(proxyMutex_); + serviceProxy_ = nullptr; +} +} // namespace OHOS::FileManagement::CloudFile diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_file_fault_event.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_file_fault_event.cpp new file mode 100644 index 0000000..7fd5255 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_file_fault_event.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2024 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 "cloud_file_fault_event.h" + +#include +#include +#include +#include +#include + +#include "cloud_file_log.h" +#include "dfs_error.h" +#include "cloud_report_cacher.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { + +CloudFaultReportStatus& CloudFaultReportStatus::GetInstance() +{ + static CloudFaultReportStatus instance_; + return instance_; +} + +bool CloudFaultReportStatus::IsAllowToReport(const FaultType &faultType) +{ + std::lock_guard timeMapLock(timeMapLock_); + if (lastTimeMap_.find(faultType) != lastTimeMap_.end()) { + struct timespec t; + clock_gettime(CLOCK_REALTIME, &t); + int64_t currentTime_ = t.tv_sec; + if (lastTimeMap_[faultType] == 0 || + (currentTime_ > lastTimeMap_[faultType] && + currentTime_ - lastTimeMap_[faultType] > MINIMUM_FAULT_REPORT_INTERVAL)) { + lastTimeMap_[faultType] = currentTime_; + return true; + } else { + return false; + } + } + return true; +} + +CloudFaultReportStatus::CloudFaultReportStatus() +{ + for (const auto &faultType : PERIODIC_REPORT_FAULT_TYPE) { + lastTimeMap_[faultType] = 0; + } +} + +int32_t CloudFileFaultEvent::CloudSyncFaultReport(const std::string &funcName, + const int lineNum, + const CloudSyncFaultInfo &event) +{ + if (CloudFaultReportStatus::GetInstance().IsAllowToReport(event.faultType_)) { + int32_t ret = CLOUD_SYNC_SYS_EVENT("CLOUD_FILE_SYNC_FAULT", + HiviewDFX::HiSysEvent::EventType::FAULT, + "bundle_name", event.bundleName_, + "fault_scenario", static_cast(event.faultScenario_), + "fault_type", static_cast(event.faultType_), + "fault_error_code", static_cast(abs(event.faultErrorCode_)), + "function_name", funcName + ":" + std::to_string(lineNum), + "message", event.message_); + if (ret != E_OK) { + LOGE("report CLOUD_FILE_SYNC_FAULT error %{public}d", ret); + } + } + LOGE("%{public}s", event.message_.c_str()); + return event.faultErrorCode_; +} + +int32_t CloudFileFaultEvent::CloudFileFaultReport(const std::string &funcName, + const int lineNum, + const CloudFileFaultInfo &event) +{ + if (CloudFaultReportStatus::GetInstance().IsAllowToReport(event.faultType_)) { + int32_t ret = CLOUD_SYNC_SYS_EVENT("CLOUD_FILE_ACCESS_FAULT", + HiviewDFX::HiSysEvent::EventType::FAULT, + "bundle_name", event.bundleName_, + "fault_operation", static_cast(event.faultOperation_), + "fault_type", static_cast(event.faultType_), + "fault_error_code", static_cast(abs(event.faultErrorCode_)), + "function_name", funcName + ":" + std::to_string(lineNum), + "message", event.message_); + if (ret != E_OK) { + LOGE("report CLOUD_FILE_ACCESS_FAULT error %{public}d", ret); + } + } + LOGE("%{public}s", event.message_.c_str()); + return event.faultErrorCode_; +} + +int32_t CloudFileFaultEvent::CloudSyncCacheReport(const std::string &funcName, + const int lineNum, + const CloudCacheFaultInfo &event) +{ + if (CloudFaultReportStatus::GetInstance().IsAllowToReport(event.faultType_)) { + struct timespec t; + clock_gettime(CLOCK_REALTIME, &t); + int64_t currentTime_ = t.tv_sec; + CloudReportCacher::GetInstance().PushEvent(event.bundleName_, { + "CLOUD_FILE_SYNC_FAULT", + currentTime_, + static_cast(event.faultType_), + static_cast(abs(event.faultErrorCode_)), + funcName + ":" + std::to_string(lineNum), + event.message_, + event.terminate_ + }); + } + LOGE("%{public}s", event.message_.c_str()); + return event.faultErrorCode_; +} +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_report_cacher.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_report_cacher.cpp new file mode 100644 index 0000000..ca09077 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_report_cacher.cpp @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2024 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 "cloud_report_cacher.h" +#include "hisysevent.h" +#include "nlohmann/json.hpp" +#include "cloud_file_log.h" +#include "cloud_file_fault_event.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using namespace std; + +constexpr int MAX_CACHE_SIZE = 20; +constexpr int REPORT_VERSION = 2; + +CloudReportCacher::CloudReportCacher() +{ +} + +CloudReportCacher &CloudReportCacher::GetInstance() +{ + static CloudReportCacher instance_; + return instance_; +} + +void CloudReportCacher::Init(const string &bundleName, const string &traceId, const uint32_t scenarioCode) +{ + LOGI("init : %{public}s %{public}s %{public}d", bundleName.c_str(), traceId.c_str(), scenarioCode); + if (bundleName.empty() || traceId.empty()) { + return; + } + shared_ptr reportInfo; + if (!GetReportInfo(bundleName, reportInfo)) { + return; + } + reportInfo->traceId_ = traceId; + reportInfo->scenarioCode_ = scenarioCode; +} + +void CloudReportCacher::SetScenarioCode(const string &bundleName, const uint32_t scenarioCode) +{ + LOGI("set scenario_code : %{public}s %{public}d", bundleName.c_str(), scenarioCode); + if (bundleName.empty() || scenarioCode <= 0) { + return; + } + shared_ptr reportInfo; + if (!GetReportInfo(bundleName, reportInfo)) { + return; + } + reportInfo->scenarioCode_ = scenarioCode; +} + +void CloudReportCacher::PushEvent(const string &bundleName, const CloudFaultInfo &event) +{ + shared_ptr reportInfo; + if (!GetReportInfo(bundleName, reportInfo)) { + return; + } + bool exceededLimit = false; + { + unique_lock lock(eventsMutex_); + reportInfo->events_.emplace_back(event); + exceededLimit = reportInfo->events_.size() > MAX_CACHE_SIZE; + } + if (exceededLimit) { + Report(bundleName, reportInfo->lastScheduleType_ + 1); + } +} + +void CloudReportCacher::Report(const string &bundleName, const int scheduleType) +{ + if (scheduleType <= 0) { + return; + } + LOGI("report schedule : %{public}s %{public}d", bundleName.c_str(), scheduleType); + shared_ptr reportInfo; + if (!GetReportInfo(bundleName, reportInfo)) { + return; + } + reportInfo->lastScheduleType_ = scheduleType; + unique_lock lock(eventsMutex_); + if (reportInfo->events_.empty()) { + return; + } + + nlohmann::json jsonArr = nlohmann::json::array(); + CloudFaultInfo terminateEvent = reportInfo->events_[reportInfo->events_.size() - 1]; + terminateEvent.faultType_ = static_cast(FaultType::WARNING); + for (auto it = reportInfo->events_.begin(); it != reportInfo->events_.end(); ++it) { + CloudFaultInfo& event = *it; + nlohmann::json jsonItem; + jsonItem["version"] = REPORT_VERSION; + jsonItem["trace_id"] = reportInfo->traceId_; + jsonItem["schedule"] = scheduleType; + jsonItem["fault_error_code"] = event.faultErrorCode_ ; + jsonItem["function_name"] = event.funcName_; + jsonItem["fault_time"] = event.faultTime_; + jsonItem["message"] = event.message_; + jsonArr.push_back(jsonItem); + if (event.terminate_) { + terminateEvent = event; + terminateEvent.faultType_ = static_cast(FaultType::CLOUD_SYNC_ERROR); + } + } + terminateEvent.message_ = jsonArr.dump(); + ReportFaultInfo(terminateEvent, bundleName, reportInfo->scenarioCode_); + reportInfo->events_.clear(); +} + +void CloudReportCacher::ReportFaultInfo(const CloudFaultInfo &event, const string &bundleName, + const uint32_t scenarioCode) +{ + HiSysEventWrite( + HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT, event.eventType_, + HiviewDFX::HiSysEvent::EventType::FAULT, + "bundle_name", bundleName, + "fault_scenario", scenarioCode, + "fault_type", event.faultType_, + "fault_error_code", event.faultErrorCode_, + "function_name", event.funcName_, + "message", event.message_); +} + +bool CloudReportCacher::GetReportInfo(const string &bundleName, shared_ptr &reportInfo) +{ + unique_lock lock(reportMutex_); + if (reportCache_.Find(bundleName, reportInfo)) { + return true; + } + reportInfo = make_shared(); + if (reportInfo == nullptr) { + LOGE("new report fail"); + return false; + } + reportCache_.EnsureInsert(bundleName, reportInfo); + return true; +} +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp new file mode 100644 index 0000000..5e18358 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2024 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_download_file_stat.h" + +#include +#include +#include +#include + +#include "dfs_error.h" +#include "hisysevent.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +#define TYPE_DOWNLOAD_FILE_IMAGE 1 +#define TYPE_DOWNLOAD_FILE_VIDEO 2 +#define DOWNLOAD_FILE_BYTE_SIZE 1e6 +#define DIR_MODE 0770 +#define FILE_MODE 0660 +#define CLOUD_SYNC_SYS_EVENT(eventName, type, ...) \ + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT, eventName, \ + type, ##__VA_ARGS__) \ + +const std::string DOWNLOAD_FILE_STAT_LOCAL_PATH = "/data/service/el1/public/cloudfile/cloud_data_statistic/"; +const std::string DOWNLOAD_FILE_STAT_NAME = "cloud_sync_download_file_stat"; +const std::vector DOWNLOAD_IMAGE_SIZE_RANGE_VECTOR = { 2, 4, 6, 8, 15 }; +const std::vector DOWNLOAD_VIDEO_SIZE_RANGE_VECTOR = { 20, 40, 80, 200, 400, 800 }; + +enum DownloadFileStatIndex { + DOWNLOAD_FILE_ERROR = 1, + DOWNLOAD_IMAGE_SIZE, + DOWNLOAD_IMAGE_SPEED, + DOWNLOAD_VIDEO_SIZE, + DOWNLOAD_VIDEO_SPEED, +}; + +static int32_t CreateDataStatisticFolder() +{ + std::string path = DOWNLOAD_FILE_STAT_LOCAL_PATH; + if (access(path.c_str(), F_OK) == 0) { + LOGI("cloud data statistic folder already exists"); + return E_OK; + } + int32_t ret = mkdir(path.c_str(), DIR_MODE); + if (ret != E_OK) { + LOGE("Create cloud data statistic folder fail errno = %{public}d", errno); + return E_PATH; + } + return E_OK; +} + +static int32_t CreateDownloadFileStatData() +{ + const std::string path = DOWNLOAD_FILE_STAT_LOCAL_PATH + DOWNLOAD_FILE_STAT_NAME; + if (access(path.c_str(), F_OK) == 0) { + LOGI("download file statistics data file already exists"); + return E_OK; + } + std::FILE *file = fopen(path.c_str(), "w"); + if (file == nullptr) { + LOGE("create file downloadstatistic report fail, ret = %{public}d", errno); + return errno; + } + if (fclose(file)) { + LOGE("close file downloadstatistic report fail, ret = %{public}d", errno); + } + return E_OK; +} + +GalleryDownloadFileStat::GalleryDownloadFileStat() +{ + auto ret = CreateDataStatisticFolder(); + if (ret !=E_OK) { + LOGE("create data statistic failed with error %{public}d", ret); + return; + } + ret = CreateDownloadFileStatData(); + if (ret != E_OK) { + LOGE("create download file stat failed with error %{public}d", ret); + return; + } +} + +static uint32_t GetRangeIndex(uint64_t value, const std::vector rangeVector) +{ + uint32_t index = 0; + for (; index < rangeVector.size(); index++) { + if (value <= rangeVector[index] * DOWNLOAD_FILE_BYTE_SIZE) { + break; + } + } + return index; +} + +void GalleryDownloadFileStat::UpdateDownloadSpeedStat(uint32_t mediaType, uint64_t size, uint64_t duration) +{ + double sizeMb = static_cast(size) / DOWNLOAD_FILE_BYTE_SIZE; + double time = static_cast(duration) / DOWNLOAD_FILE_BYTE_SIZE; + + double precision = 1e-10; + uint32_t indexSpeed = 15; + if (abs(time) > precision) { + double speed = sizeMb / time; + indexSpeed = static_cast(floor(speed)); + } + if (mediaType == TYPE_DOWNLOAD_FILE_IMAGE && indexSpeed < stat_.imageDownloadSpeed.size()) { + stat_.imageDownloadSpeed[indexSpeed]++; + } + if (mediaType == TYPE_DOWNLOAD_FILE_VIDEO && indexSpeed < stat_.videoDownloadSpeed.size()) { + stat_.videoDownloadSpeed[indexSpeed]++; + } +} + +void GalleryDownloadFileStat::UpdateDownloadSizeStat(uint32_t mediaType, uint64_t size, uint64_t duration) +{ + std::vector rangeVector; + if (mediaType == TYPE_DOWNLOAD_FILE_IMAGE) { + rangeVector = DOWNLOAD_IMAGE_SIZE_RANGE_VECTOR; + uint32_t index = GetRangeIndex(size, rangeVector); + if (index >= stat_.imageSize.size()) { + return; + } + stat_.imageSize[index]++; + } else { + rangeVector = DOWNLOAD_VIDEO_SIZE_RANGE_VECTOR; + uint32_t index = GetRangeIndex(size, rangeVector); + if (index >= stat_.videoSize.size()) { + return; + } + stat_.videoSize[index]++; + } +} + +void GalleryDownloadFileStat::UpdateDownloadStat(uint32_t mediaType, uint64_t size, uint64_t duration) +{ + UpdateDownloadSizeStat(mediaType, size, duration); + UpdateDownloadSpeedStat(mediaType, size, duration); +} + +static std::string VectorToString(const std::vector &vec) +{ + std::ostringstream oss; + for (size_t i = 0; i < vec.size(); ++i) { + oss << vec[i]; + if (i <= vec.size() -1) { + oss << " "; + } + } + return oss.str(); +} + +static std::vector StringToVector(std::string line) +{ + std::vector vec; + std::istringstream iss(line); + uint64_t num; + while (iss >> num) { + vec.push_back(num); + } + return vec; +} + +static inline void SumTwoVector(std::vector &dataOne, std::vector dataTwo) +{ + if (dataOne.size() != dataTwo.size()) { + return; + } + for (size_t i = 0; i < dataOne.size(); i++) { + dataOne[i] += dataTwo[i]; + } + return; +} + +static inline DownloadFileStatInfo SumTwoDownloadFileStat(DownloadFileStatInfo dataOne, DownloadFileStatInfo dataTwo) +{ + SumTwoVector(dataOne.downloadFileError, dataTwo.downloadFileError); + SumTwoVector(dataOne.imageSize, dataTwo.imageSize); + SumTwoVector(dataOne.imageDownloadSpeed, dataTwo.imageDownloadSpeed); + SumTwoVector(dataOne.videoSize, dataTwo.videoSize); + SumTwoVector(dataOne.videoDownloadSpeed, dataTwo.videoDownloadSpeed); + return dataOne; +} + +void GalleryDownloadFileStat::OutputToFile() +{ + DownloadFileStatInfo tmpInfo = ReadVecFromLocal(); + stat_ = SumTwoDownloadFileStat(stat_, tmpInfo); + + std::vector lines; + /* Keep code order below */ + lines.emplace_back(stat_.bundleName); + lines.emplace_back(VectorToString(stat_.downloadFileError)); + lines.emplace_back(VectorToString(stat_.imageSize)); + lines.emplace_back(VectorToString(stat_.imageDownloadSpeed)); + lines.emplace_back(VectorToString(stat_.videoSize)); + lines.emplace_back(VectorToString(stat_.videoDownloadSpeed)); + + std::ofstream localData(DOWNLOAD_FILE_STAT_LOCAL_PATH + DOWNLOAD_FILE_STAT_NAME, std::ios::trunc); + if (!localData.is_open()) { + LOGE("Open cloud data statistic local data fail %{public}d", errno); + return; + } + for (std::string line : lines) { + localData << line << std::endl; + } + localData.close(); + ClearDownloadFileStat(); + return; +} + +DownloadFileStatInfo GalleryDownloadFileStat::ReadVecFromLocal() +{ + std::vector vec; + DownloadFileStatInfo tmpStat; + std::ifstream localData(DOWNLOAD_FILE_STAT_LOCAL_PATH + DOWNLOAD_FILE_STAT_NAME); + if (localData) { + uint32_t rowCount = 0; + std::string line; + while (std::getline(localData, line)) { + if (rowCount != 0) { + vec = StringToVector(line); + } + if (rowCount == DOWNLOAD_FILE_ERROR) { + tmpStat.downloadFileError = vec; + } + if (rowCount == DOWNLOAD_IMAGE_SIZE) { + tmpStat.imageSize = vec; + } + if (rowCount == DOWNLOAD_IMAGE_SPEED) { + tmpStat.imageDownloadSpeed = vec; + } + if (rowCount == DOWNLOAD_VIDEO_SIZE) { + tmpStat.videoSize = vec; + } + if (rowCount == DOWNLOAD_VIDEO_SPEED) { + tmpStat.videoDownloadSpeed = vec; + } + rowCount += 1; + } + localData.close(); + } else { + LOGE("Open cloud data statistic local data fail %{public}d", errno); + } + return tmpStat; +} + +void GalleryDownloadFileStat::ClearDownloadFileStat() +{ + std::fill(stat_.downloadFileError.begin(), stat_.downloadFileError.end(), 0); + std::fill(stat_.imageSize.begin(), stat_.imageSize.end(), 0); + std::fill(stat_.imageDownloadSpeed.begin(), stat_.imageDownloadSpeed.end(), 0); + std::fill(stat_.videoSize.begin(), stat_.videoSize.end(), 0); + std::fill(stat_.videoDownloadSpeed.begin(), stat_.videoDownloadSpeed.end(), 0); +} + +void GalleryDownloadFileStat::Report() +{ + const std::string path = DOWNLOAD_FILE_STAT_LOCAL_PATH + DOWNLOAD_FILE_STAT_NAME; + if (access(path.c_str(), F_OK) == -1) { + LOGE("download file statistics data file not exists"); + return; + } + + /* read stat from dist */ + stat_ = ReadVecFromLocal(); + + int32_t ret = CLOUD_SYNC_SYS_EVENT("CLOUD_SYNC_DOWNLOAD_FILE_STAT", + HiviewDFX::HiSysEvent::EventType::STATISTIC, + "bundle_name", stat_.bundleName, + "download_file", stat_.downloadFileError, + "image_size", stat_.imageSize, + "image_download_speed", stat_.imageDownloadSpeed, + "video_size", stat_.videoSize, + "video_download_speed", stat_.videoDownloadSpeed); + if (ret != E_OK) { + LOGE("report CLOUD_SYNC_DOWNLOAD_FILE_STAT error %{public}d", ret); + } + ret = unlink(path.c_str()); + if (ret != 0) { + LOGE("fail to delete local statistic data, errno %{public}d", errno); + } +} + +GalleryDownloadFileStat &GalleryDownloadFileStat::GetInstance() +{ + static GalleryDownloadFileStat downloadStat_; + return downloadStat_; +} +} // CloudFile +} // FileManagement +} // OHOS \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_asset_read_session.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_asset_read_session.cpp new file mode 100644 index 0000000..8008d28 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_asset_read_session.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024 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 "cloud_asset_read_session.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +CloudAssetReadSession::CloudAssetReadSession(const int32_t userId, + std::string recordType, + std::string recordId, + std::string assetKey, + std::string assetPath) + : userId_(userId) +{ +} + +CloudError CloudAssetReadSession::InitSession() +{ + return CloudError::CK_NO_ERROR; +} + +int64_t CloudAssetReadSession::PRead(int64_t offset, int64_t size, char *buffer, CloudError &error) +{ + return E_OK; +} + +bool CloudAssetReadSession::Close(bool needRemain) +{ + return true; +} + +bool CloudAssetReadSession::HasCache(int64_t offset, int64_t readSize) +{ + return true; +} + +void CloudAssetReadSession::SentPrepareTraceId(std::string prepareTraceId) +{ + return; +} + +void CloudAssetReadSession::SetPrepareTraceId(std::string prepareTraceId) +{ + traceId_ = prepareTraceId; + SentPrepareTraceId(traceId_); +} + +std::string CloudAssetReadSession::GetPrepareTraceId() +{ + return traceId_; +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_assets_downloader.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_assets_downloader.cpp new file mode 100644 index 0000000..16dc5a4 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_assets_downloader.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 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 "cloud_assets_downloader.h" +#include "cloud_info.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +CloudAssetsDownloader::CloudAssetsDownloader(const int32_t userId, const string &bundleName) + : userId_(userId), bundleName_(bundleName) +{ +} + +int32_t CloudAssetsDownloader::DownloadAssets(DownloadAssetInfo &assetsToDownload) +{ + (void)userId_; + (void)bundleName_; + return E_OK; +} + +int32_t CloudAssetsDownloader::DownloadAssets(const std::vector &assetsToDownload, + std::vector &assetResultMap) +{ + return E_OK; +} + +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_database.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_database.cpp new file mode 100644 index 0000000..74fee1f --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_database.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 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 "cloud_database.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +CloudDatabase::CloudDatabase(const int32_t userId, const std::string &bundleName) + : userId_(userId), bundleName_(bundleName) +{ +} + +std::shared_ptr CloudDatabase::NewAssetReadSession(const int32_t userId, + std::string recordType, + std::string recordId, + std::string assetKey, + std::string assetPath) +{ + return std::make_shared(userId, recordType, recordId, assetKey, assetPath); +} + +int32_t CloudDatabase::Init() +{ + (void)userId_; + (void)bundleName_; + return E_OK; +} + +int32_t CloudDatabase::GenerateIds(int count, std::vector &ids) +{ + return E_OK; +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_file_kit.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_file_kit.cpp new file mode 100644 index 0000000..aad42e9 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_file_kit.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2024 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 "cloud_file_kit.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +CloudFileKit *CloudFileKit::GetInstance() +{ + return instance_; +} + +bool CloudFileKit::RegisterCloudInstance(CloudFileKit *instance) +{ + if (instance_ != nullptr) { + return false; + } + instance_ = instance; + return true; +} + +int32_t CloudFileKit::GetCloudUserInfo(const int32_t userId, CloudUserInfo &userInfo) +{ + userInfo.enableCloud = true; + return E_OK; +} + +std::pair CloudFileKit::GetSpaceInfo(const int32_t userId, const std::string &bundleName) +{ + return make_pair(0, 0); +} + +int32_t CloudFileKit::GetAppSwitchStatus(const std::string &bundleName, const int32_t userId, bool &switchStatus) +{ + switchStatus = true; + return E_OK; +} + +int32_t CloudFileKit::ResolveNotificationEvent(const int32_t userId, + const std::string &extraData, + std::string &appBundleName, + std::string &prepareTraceId) +{ + appBundleName = "com.ohos.photos"; + return E_OK; +} + +int32_t CloudFileKit::GetAppConfigParams(const int32_t userId, + const std::string &bundleName, + std::map ¶m) +{ + param["validDays"] = "30"; + param["dataAgingPolicy"] = "0"; + return E_OK; +} + +int32_t CloudFileKit::CleanCloudUserInfo(const int32_t userId) +{ + return E_OK; +} + +shared_ptr CloudFileKit::GetDataSyncManager() +{ + return std::make_shared(); +} + +int32_t CloudFileKit::OnUploadAsset(const int32_t userId, const std::string &request, std::string &result) +{ + return E_OK; +} + +std::shared_ptr CloudFileKit::GetCloudAssetsDownloader(const int32_t userId, + const std::string &bundleName) +{ + return make_shared(userId, bundleName); +} + +std::shared_ptr CloudFileKit::GetCloudDatabase(const int32_t userId, const std::string &bundleName) +{ + return make_shared(userId, bundleName); +} + +std::shared_ptr CloudFileKit::GetCloudSyncHelper(const int32_t userId, const std::string &bundleName) +{ + return make_shared(userId, bundleName); +} + +std::string CloudFileKit::GetPrepareTraceId(const int32_t userId) +{ + return ""; +} + +void CloudFileKit::Release(int32_t userId) {} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_sync_helper.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_sync_helper.cpp new file mode 100644 index 0000000..4feda86 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/cloud_sync_helper.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 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 "cloud_sync_helper.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +CloudSyncHelper::CloudSyncHelper(const int32_t userId, const string &bundleName) + : userId_(userId), bundleName_(bundleName) +{ +} + +int32_t CloudSyncHelper::Init() +{ + return E_OK; +} + +int32_t CloudSyncHelper::SaveSubScription() +{ + return E_OK; +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/data_syncer_rdb_store.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/data_syncer_rdb_store.cpp new file mode 100644 index 0000000..68827b0 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/data_syncer_rdb_store.cpp @@ -0,0 +1,246 @@ +/* + * 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 "data_syncer_rdb_store.h" + +#include "data_syncer_rdb_col.h" +#include "dfs_error.h" +#include "rdb_helper.h" +#include "rdb_sql_utils.h" +#include "rdb_store_config.h" +#include "result_set.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +DataSyncerRdbStore &DataSyncerRdbStore::GetInstance() +{ + static DataSyncerRdbStore instance; + return instance; +} + +int32_t DataSyncerRdbStore::RdbInit() +{ + LOGI("Init rdb store"); + int32_t errCode = 0; + string databasePath = NativeRdb::RdbSqlUtils::GetDefaultDatabasePath(EL1_CLOUDFILE_DIR, DATA_SYNCER_DB, errCode); + + if (errCode != E_OK) { + LOGE("Create Default Database Path is failed, errCode = %{public}d", errCode); + return E_RDB; + } + NativeRdb::RdbStoreConfig config{""}; + config.SetName(move(DATA_SYNCER_DB)); + config.SetPath(move(databasePath)); + errCode = E_OK; + DataSyncerRdbCallBack rdbDataCallBack; + rdb_ = NativeRdb::RdbHelper::GetRdbStore(config, CLOUD_DISK_RDB_VERSION, rdbDataCallBack, errCode); + if (rdb_ == nullptr) { + LOGE("GetRdbStore is failed, errCode = %{public}d", errCode); + return E_RDB; + } + + return E_OK; +} + +int32_t DataSyncerRdbStore::Insert(int32_t userId, const std::string &bundleName) +{ + LOGI("datasyncer insert userId %d, bundleName %s", userId, bundleName.c_str()); + string uniqueId = to_string(userId) + bundleName; + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE); + predicates.EqualTo(DATA_SYNCER_UNIQUE_ID, uniqueId); + std::shared_ptr resultSet = nullptr; + auto queryRet = Query(predicates, resultSet); + if (queryRet != E_OK) { + return queryRet; + } + if (resultSet->GoToNextRow() == E_OK) { + return E_OK; + } + NativeRdb::ValuesBucket values; + values.PutInt(USER_ID, userId); + values.PutString(BUNDLE_NAME, bundleName); + values.PutString(DATA_SYNCER_UNIQUE_ID, uniqueId); + int32_t ret = 0; + { + std::lock_guard lck(rdbMutex_); + int64_t rowId; + if (rdb_ == nullptr) { + if (RdbInit() != E_OK) { + LOGE("Data Syner init rdb failed"); + return E_RDB; + } + } + ret = rdb_->Insert(rowId, DATA_SYNCER_TABLE, values); + } + if (ret != E_OK) { + LOGE("fail to insert userId %d bundleName %s, ret %{public}d", userId, bundleName.c_str(), ret); + return E_RDB; + } + + return E_OK; +} + +static int64_t UTCTimeMilliSeconds() +{ + struct timespec t; + clock_gettime(CLOCK_REALTIME, &t); + return t.tv_sec * SECOND_TO_MILLISECOND + t.tv_nsec / MILLISECOND_TO_NANOSECOND; +} + +int32_t DataSyncerRdbStore::UpdateSyncState(int32_t userId, const string &bundleName, SyncState syncState) +{ + LOGI("update syncstate %{public}d", syncState); + int updateRows; + NativeRdb::ValuesBucket values; + values.PutInt(SYNC_STATE, static_cast(syncState)); + if (syncState == SyncState::SYNC_SUCCEED) { + values.PutLong(LAST_SYNC_TIME, UTCTimeMilliSeconds()); + } + string whereClause = USER_ID + " = ? AND " + BUNDLE_NAME + " = ?"; + vector whereArgs = { to_string(userId), bundleName }; + if (rdb_ == nullptr) { + if (RdbInit() != E_OK) { + LOGE("Data Syner init rdb failed"); + return E_RDB; + } + } + int32_t ret = rdb_->Update(updateRows, DATA_SYNCER_TABLE, values, whereClause, whereArgs); + if (ret != E_OK) { + LOGE("update sync state failed: %{public}d", ret); + return E_OK; + } + return E_OK; +} + +static int32_t GetLong(const string &key, int64_t &val, NativeRdb::ResultSet &resultSet) +{ + int32_t index; + int32_t err = resultSet.GetColumnIndex(key, index); + if (err != NativeRdb::E_OK) { + LOGE("result set get %{public}s column index err %{public}d", key.c_str(), err); + return E_RDB; + } + + err = resultSet.GetLong(index, val); + if (err != 0) { + LOGE("result set get int err %{public}d", err); + return E_RDB; + } + + return E_OK; +} + +int32_t DataSyncerRdbStore::GetLastSyncTime(int32_t userId, const string &bundleName, int64_t &time) +{ + LOGI("get sync time uid: %{public}d, name: %{public}s", userId, bundleName.c_str()); + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE); + predicates.EqualTo(USER_ID, userId)->EqualTo(BUNDLE_NAME, bundleName); + std::shared_ptr resultSet = nullptr; + + auto queryRet = Query(predicates, resultSet); + if (queryRet != E_OK) { + return queryRet; + } + if (resultSet->GoToNextRow() != E_OK) { + return E_INVAL_ARG; + } + int32_t ret = GetLong(LAST_SYNC_TIME, time, *resultSet); + if (ret != E_OK) { + LOGE("get last sync time failed"); + return ret; + } + return E_OK; +} + +int32_t DataSyncerRdbStore::QueryDataSyncer(int32_t userId, std::shared_ptr &resultSet) +{ + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE); + predicates.EqualTo(USER_ID, userId); + return Query(predicates, resultSet); +} + +int32_t DataSyncerRdbStore::QueryCloudSync(int32_t userId, + const std::string &bundleName, + std::shared_ptr &resultSet) +{ + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE); + predicates.EqualTo(USER_ID, userId); + predicates.EqualTo(BUNDLE_NAME, bundleName); + return Query(predicates, resultSet); +} + +int32_t DataSyncerRdbStore::Query(NativeRdb::AbsRdbPredicates predicates, + std::shared_ptr &resultSet) +{ + if (rdb_ == nullptr) { + if (RdbInit() != E_OK) { + LOGE("Data Syner init rdb failed"); + return E_RDB; + } + } + resultSet = rdb_->QueryByStep(predicates, {}); + if (resultSet == nullptr) { + LOGE("DataSyncerRdbStore query failed"); + return E_RDB; + } + return E_OK; +} + + +int32_t DataSyncerRdbCallBack::OnCreate(NativeRdb::RdbStore &store) +{ + vector executeSqlStrs = { + CREATE_DATA_SYNCER_TABLE, + CREATE_DATA_SYNCER_UNIQUE_INDEX, + }; + + for (const string& sqlStr : executeSqlStrs) { + if (store.ExecuteSql(sqlStr) != E_OK) { + LOGE("create table failed."); + return E_RDB; + } + } + return E_OK; +} + +static void VersionAddDataSyncerUniqueIndex(NativeRdb::RdbStore &store) +{ + const string addDataSyncerUniqueIdColumn = + "ALTER TABLE " + DATA_SYNCER_TABLE + " ADD COLUMN " + + DATA_SYNCER_UNIQUE_ID + " TEXT"; + const string initUniqueIdColumn = + "UPDATE " + DATA_SYNCER_TABLE + " SET " + + DATA_SYNCER_UNIQUE_ID + " = userId || bundleName"; + const string addDataSyncerUniqueIndex = CREATE_DATA_SYNCER_UNIQUE_INDEX; + const vector addUniqueIndex = { addDataSyncerUniqueIdColumn, initUniqueIdColumn, + addDataSyncerUniqueIndex}; + for (size_t i = 0; i < addUniqueIndex.size(); i++) { + if (store.ExecuteSql(addUniqueIndex[i]) != NativeRdb::E_OK) { + LOGE("upgrade fail idx:%{public}zu", i); + } + } +} + +int32_t DataSyncerRdbCallBack::OnUpgrade(NativeRdb::RdbStore &store, int32_t oldVersion, int32_t newVersion) +{ + LOGD("OnUpgrade old:%d, new:%d", oldVersion, newVersion); + if (oldVersion < VERSION_ADD_DATA_SYNCER_UNIQUE_INDEX) { + VersionAddDataSyncerUniqueIndex(store); + } + return E_OK; +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp new file mode 100644 index 0000000..c2cfb6f --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp @@ -0,0 +1,117 @@ +/* + * 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 "sync_state_manager.h" + +#include + +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +Action SyncStateManager::UpdateSyncState(SyncState newState) +{ + std::unique_lock lck(syncMutex_); + state_ = newState; + stopSyncFlag_ = false; + return nextAction_; +} + +bool SyncStateManager::CheckAndSetPending(bool forceFlag, SyncTriggerType triggerType) +{ + std::unique_lock lck(syncMutex_); + if (!CheckCleaningFlag() && + !CheckDisableCloudFlag() && + state_ != SyncState::SYNCING) { + state_ = SyncState::SYNCING; + nextAction_ = Action::STOP; + isForceSync_ = forceFlag; + return false; + } + + if (nextAction_ == Action::CHECK) { + return true; + } + if (forceFlag) { + nextAction_ = Action::FORCE_START; + } else if (triggerType == SyncTriggerType::TASK_TRIGGER) { + nextAction_ = Action::CHECK; + } else { + nextAction_ = Action::START; + } + return true; +} + +bool SyncStateManager::CheckCleaningFlag() +{ + return syncSignal.test(static_cast(SignalPos::CLEANING)); +} + +void SyncStateManager::SetCleaningFlag() +{ + std::unique_lock lck(syncMutex_); + syncSignal.set(static_cast(SignalPos::CLEANING)); + nextAction_ = Action::STOP; +} + +Action SyncStateManager::ClearCleaningFlag() +{ + std::unique_lock lck(syncMutex_); + syncSignal.reset(static_cast(SignalPos::CLEANING)); + return nextAction_; +} + +bool SyncStateManager::CheckDisableCloudFlag() +{ + return syncSignal.test(static_cast(SignalPos::DISABLE_CLOUD)); +} + +void SyncStateManager::SetDisableCloudFlag() +{ + std::unique_lock lck(syncMutex_); + syncSignal.set(static_cast(SignalPos::DISABLE_CLOUD)); + nextAction_ = Action::STOP; +} + +Action SyncStateManager::ClearDisableCloudFlag() +{ + std::unique_lock lck(syncMutex_); + syncSignal.reset(static_cast(SignalPos::DISABLE_CLOUD)); + return nextAction_; +} + +bool SyncStateManager::GetStopSyncFlag() +{ + return stopSyncFlag_; +} + +void SyncStateManager::SetStopSyncFlag() +{ + std::unique_lock lck(syncMutex_); + nextAction_ = Action::STOP; + stopSyncFlag_ = true; +} + +SyncState SyncStateManager::GetSyncState() const +{ + return state_; +} + +bool SyncStateManager::GetForceFlag() const +{ + return isForceSync_; +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/task_state_manager.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/task_state_manager.cpp new file mode 100644 index 0000000..84ea838 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync/task_state_manager.cpp @@ -0,0 +1,147 @@ +/* + * 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 "task_state_manager.h" + +#include "gallery_download_file_stat.h" +#include "iservice_registry.h" +#include "parameters.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +using namespace std; + +const int32_t DELAY_TIME = 90000; // ms +const int32_t SYSTEM_LOAD_DELAY_TIME = 600000; // ms + +TaskStateManager &TaskStateManager::GetInstance() +{ + static TaskStateManager instance; + return instance; +} + +TaskStateManager::TaskStateManager() : queue_("unloadTask") +{ +} + +void TaskStateManager::StartTask(string bundleName, TaskType task) +{ + CancelUnloadTask(); + std::lock_guard lock(taskMapsMutex_); + auto iterator = taskMaps_.find(bundleName); + if (iterator == taskMaps_.end()) { + taskMaps_[bundleName] = static_cast(task); + return; + } + auto taskState = iterator->second | static_cast(task); + taskMaps_[bundleName] = taskState; +} + +void TaskStateManager::CompleteTask(string bundleName, TaskType task) +{ + std::lock_guard lock(taskMapsMutex_); + auto iterator = taskMaps_.find(bundleName); + if (iterator == taskMaps_.end()) { + LOGE("task is not started"); + } else { + taskMaps_[bundleName] = iterator->second & ~static_cast(task); + if (taskMaps_[bundleName] == 0) { + taskMaps_.erase(bundleName); + } + } + if (taskMaps_.empty()) { + DelayUnloadTask(); + } +} + +void TaskStateManager::StartTask() +{ + std::lock_guard lock(taskMapsMutex_); + if (taskMaps_.empty()) { + DelayUnloadTask(); + } +} + +bool TaskStateManager::HasTask(const string bundleName, TaskType task) +{ + std::lock_guard lock(taskMapsMutex_); + auto iterator = taskMaps_.find(bundleName); + if (iterator != taskMaps_.end()) { + if (taskMaps_[bundleName] & static_cast(task)) { + return true; + } + } + return false; +} + + +void TaskStateManager::CancelUnloadTask() +{ + std::lock_guard lock(unloadTaskMutex_); + if (unloadTaskHandle_ == nullptr) { + return; + } + LOGD("cancel unload task"); + queue_.cancel(unloadTaskHandle_); + unloadTaskHandle_ = nullptr; +} + +void TaskStateManager::DelayUnloadTask() +{ + const std::string temperatureSysparamSync = "persist.kernel.cloudsync.temperature_abnormal_sync"; + const std::string temperatureSysparamThumb = "persist.kernel.cloudsync.temperature_abnormal_thumb"; + string systemLoadSync = system::GetParameter(temperatureSysparamSync, ""); + string systemLoadThumb = system::GetParameter(temperatureSysparamThumb, ""); + LOGI("delay unload task begin"); + auto delayTime = DELAY_TIME; + if (systemLoadSync == "true" || systemLoadThumb == "true") { + LOGE("temperatureSysparam is true, unload task in 10 minutes"); + delayTime = SYSTEM_LOAD_DELAY_TIME; + } + auto task = [this]() { + LOGI("do unload task"); + { + std::lock_guard lock(unloadTaskMutex_); + unloadTaskHandle_ = nullptr; + } + + /* for big data statistics */ + CloudFile::GalleryDownloadFileStat::GetInstance().OutputToFile(); + + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("get samgr failed"); + return; + } + system::SetParameter(CLOUD_FILE_SERVICE_SA_STATUS_FLAG, CLOUD_FILE_SERVICE_SA_END); + int32_t ret = samgrProxy->UnloadSystemAbility(FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID); + if (ret != ERR_OK) { + LOGE("remove system ability failed"); + return; + } + }; + + CancelUnloadTask(); + std::lock_guard lock(unloadTaskMutex_); + std::chrono::milliseconds ms(delayTime); + auto us = std::chrono::duration_cast(ms); + unloadTaskHandle_ = queue_.submit_h(task, ffrt::task_attr().delay(us.count())); +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync_manager.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync_manager.cpp new file mode 100644 index 0000000..b711e2a --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/data_sync_manager.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2024 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 "data_sync_manager.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +int32_t DataSyncManager::TriggerStartSync(const std::string &bundleName, + const int32_t userId, + bool forceFlag, + SyncTriggerType triggerType, + std::string prepareTraceId) +{ + return E_OK; +} + +int32_t DataSyncManager::TriggerStopSync(const std::string &bundleName, + const int32_t userId, + bool forceFlag, + SyncTriggerType triggerType) +{ + return E_OK; +} + +int32_t DataSyncManager::StopUploadTask(const std::string &bundleName, const int32_t userId) +{ + return E_OK; +} + +int32_t DataSyncManager::ChangeAppSwitch(const std::string &bundleName, const int32_t userId, bool status) +{ + return E_OK; +} + +int32_t DataSyncManager::TriggerRecoverySync(SyncTriggerType triggerType) +{ + return E_OK; +} + +int32_t DataSyncManager::ResetCursor(const std::string &bundleName, const int32_t &userId) +{ + return E_OK; +} + +void DataSyncManager::RegisterCloudSyncCallback(const std::string &bundleName, + const std::string &callerBundleName, + const int32_t userId, + const sptr &callback) +{ + return; +} + +void DataSyncManager::UnRegisterCloudSyncCallback(const std::string &bundleName, + const std::string &callerBundleName) +{ + return; +} + +int32_t DataSyncManager::IsSkipSync(const std::string &bundleName, const int32_t userId, bool forceFlag) +{ + return E_OK; +} + +int32_t DataSyncManager::StartDownloadFile(const BundleNameUserInfo &bundleNameUserInfo, + const std::vector &pathVec, + int64_t &downloadId, int32_t fieldkey, + const sptr &downloadCallback, + int32_t timeout) +{ + return E_OK; +} + +int32_t DataSyncManager::StopDownloadFile(const BundleNameUserInfo &bundleNameUserInfo, + const std::string &path, + bool needClean) +{ + return E_OK; +} + +int32_t DataSyncManager::StopFileCache(const BundleNameUserInfo &bundleNameUserInfo, + int64_t downloadId, + bool needClean, + int32_t timeout) +{ + return E_OK; +} + +int32_t DataSyncManager::RegisterDownloadFileCallback(const BundleNameUserInfo &bundleNameUserInfo, + const sptr &downloadCallback) +{ + return E_OK; +} + +int32_t DataSyncManager::UnregisterDownloadFileCallback(const BundleNameUserInfo &bundleNameUserInfo) +{ + return E_OK; +} + +int32_t DataSyncManager::CleanCloudFile(const int32_t userId, const std::string &bundleName, const int action) +{ + return E_OK; +} + +int32_t DataSyncManager::CleanRemainFile(const std::string &bundleName, const int32_t userId) +{ + return E_OK; +} + +int32_t DataSyncManager::OptimizeStorage(const std::string &bundleName, const int32_t userId, const int32_t agingDays) +{ + return E_OK; +} + +int32_t DataSyncManager::StartOptimizeStorage(const BundleNameUserInfo &bundleNameUserInfo, + const CloudSync::OptimizeSpaceOptions &optimizeOptions, + const sptr &optimizeCallback) +{ + return E_OK; +} + +int32_t DataSyncManager::StopOptimizeStorage(const BundleNameUserInfo &bundleNameUserInfo) +{ + return E_OK; +} + +int32_t DataSyncManager::OptimizeCache(const int32_t userId, const std::string &bundleName) +{ + return E_OK; +} + +int32_t DataSyncManager::DownloadThumb() +{ + return E_OK; +} + +int32_t DataSyncManager::TriggerDownloadThumb() +{ + return E_OK; +} + +int32_t DataSyncManager::CacheVideo() +{ + return E_OK; +} + +int32_t DataSyncManager::CleanVideoCache() +{ + return E_OK; +} + +int32_t DataSyncManager::CleanCache(const std::string &bundleName, const int32_t userId, const std::string &uri) +{ + return E_OK; +} + +int32_t DataSyncManager::BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId) +{ + return E_OK; +} + +int32_t DataSyncManager::DisableCloud(const int32_t userId) +{ + return E_OK; +} + +int32_t DataSyncManager::GetUserId(int32_t &userId) +{ + return E_OK; +} + +int32_t DataSyncManager::SaveSubscription(const std::string &bundleName, const int32_t userId) +{ + return E_OK; +} + +int32_t DataSyncManager::ReportEntry(const std::string &bundleName, const int32_t userId) +{ + return E_OK; +} + +int32_t DataSyncManager::BatchCleanFile(const std::vector &fileInfo, + std::vector &failCloudId) +{ + return E_OK; +} + +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp new file mode 100644 index 0000000..63d6873 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp @@ -0,0 +1,98 @@ +/* + * 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 "battery_status.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +constexpr int32_t PAUSE_CAPACITY_LIMIT = 15; +constexpr int32_t STOP_CAPACITY_LIMIT = 10; +constexpr int32_t DEFAULT_BATTERY_CAPCITY = 100; + +void BatteryStatus::SetChargingStatus(bool status) +{ + isCharging_ = status; +} + +void BatteryStatus::GetInitChargingStatus() +{ +#ifdef SUPPORT_POWER + auto &batterySrvClient = PowerMgr::BatterySrvClient::GetInstance(); + auto chargingStatus = batterySrvClient.GetChargingStatus(); + isCharging_ = (chargingStatus == PowerMgr::BatteryChargeState::CHARGE_STATE_ENABLE || + chargingStatus == PowerMgr::BatteryChargeState::CHARGE_STATE_FULL); +#endif +} + +int32_t BatteryStatus::GetCapacity() +{ + int32_t capacity = DEFAULT_BATTERY_CAPCITY; +#ifdef SUPPORT_POWER + auto &batterySrvClient = PowerMgr::BatterySrvClient::GetInstance(); + capacity = batterySrvClient.GetCapacity(); +#endif + return capacity; +} + +bool BatteryStatus::IsAllowUpload(bool forceFlag) +{ + if (isCharging_) { + return true; + } + + auto capacity = GetCapacity(); + if (capacity < STOP_CAPACITY_LIMIT) { + LOGE("power saving, stop upload"); + level_ = BatteryStatus::LEVEL_TOO_LOW; + return false; + } else if (capacity < PAUSE_CAPACITY_LIMIT) { + if (forceFlag) { + return true; + } else { + LOGE("power saving, pause upload"); + level_ = BatteryStatus::LEVEL_LOW; + return false; + } + } else { + level_ = BatteryStatus::LEVEL_NORMAL; + return true; + } +} + +bool BatteryStatus::IsBatteryCapcityOkay() +{ + if (isCharging_) { + return true; + } + + auto capacity = GetCapacity(); + if (capacity < STOP_CAPACITY_LIMIT) { + LOGE("battery capacity too low"); + level_ = BatteryStatus::LEVEL_TOO_LOW; + return false; + } + level_ = BatteryStatus::LEVEL_NORMAL; + return true; +} + +BatteryStatus::CapacityLevel BatteryStatus::GetCapacityLevel() +{ + return level_; +} + +bool BatteryStatus::IsCharging() +{ + return isCharging_; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp new file mode 100644 index 0000000..ac94009 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp @@ -0,0 +1,104 @@ +/* + * 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 "cloud_status.h" + +#include "cloud_file_kit.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +int32_t CloudStatus::GetCurrentCloudInfo(const std::string &bundleName, const int32_t userId) +{ + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + return E_NULLPTR; + } + + auto ret = instance->GetCloudUserInfo(userId, userInfo_); + if (ret != E_OK) { + return ret; + } + + bool switchStatus = false; + ret = instance->GetAppSwitchStatus(bundleName, userId, switchStatus); + if (ret != E_OK) { + return ret; + } + /* insert key-value */ + appSwitches_.insert(std::make_pair(bundleName, switchStatus)); + userId_ = userId; + return E_OK; +} + +std::pair CloudStatus::GetCurrentSpaceInfo(const int32_t userId, const std::string &bundleName) +{ + auto instance = CloudFile::CloudFileKit::GetInstance(); + return instance->GetSpaceInfo(userId, bundleName); +} + +bool CloudStatus::IsCloudStatusOkay(const std::string &bundleName, const int32_t userId) +{ + std::lock_guard lock(mutex_); + /* User switching */ + if (userId_ != userId) { + appSwitches_.erase(bundleName); + } + + /* Obtain cloud information only during first sync */ + auto iter = appSwitches_.find(bundleName); + if (iter == appSwitches_.end()) { + LOGI("appSwitches unknown, bundleName:%{private}s, userId:%{public}d", bundleName.c_str(), userId); + auto ret = GetCurrentCloudInfo(bundleName, userId); + if (ret) { + return false; + } + } + + LOGI("bundleName:%{private}s, cloudSatus:%{public}d, switcheStatus:%{public}d", bundleName.c_str(), + userInfo_.enableCloud, appSwitches_[bundleName]); + return appSwitches_[bundleName]; +} + +int32_t CloudStatus::ChangeAppSwitch(const std::string &bundleName, const int32_t userId, bool appSwitchStatus) +{ + std::lock_guard lock(mutex_); + if (appSwitchStatus == true) { + auto iter = appSwitches_.find(bundleName); + if (iter != appSwitches_.end()) { + LOGI("change app swtich, originStatus:%{public}d, currentStatus:%{public}d", appSwitches_[bundleName], + appSwitchStatus); + appSwitches_[bundleName] = appSwitchStatus; + } + } else { + /* Actively obtaining cloud information when next sync */ + appSwitches_.erase(bundleName); + } + + return E_OK; +} + +bool CloudStatus::IsAccountIdChanged(const std::string &accountId) +{ + std::lock_guard lock(mutex_); + if ((userInfo_.accountId != "") && (userInfo_.accountId != accountId)) { + /* accountId Changed, clear init flag */ + appSwitches_.clear(); + return true; + } + return false; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/net_conn_callback_observer.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/net_conn_callback_observer.cpp new file mode 100644 index 0000000..ebee299 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/net_conn_callback_observer.cpp @@ -0,0 +1,82 @@ +/* +* 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 "net_conn_callback_observer.h" +#include "dfs_error.h" +#include "network_status.h" +#include "utils_log.h" + +using namespace OHOS::NetManagerStandard; + +namespace OHOS::FileManagement::CloudSync { +NetConnCallbackObserver::NetConnCallbackObserver(std::shared_ptr dataSyncManager) +{ + dataSyncManager_ = dataSyncManager; +} + +int32_t NetConnCallbackObserver::NetAvailable(sptr &netHandle) +{ + LOGI("network is available"); + return E_OK; +} + +int32_t NetConnCallbackObserver::NetCapabilitiesChange(sptr &netHandle, + const sptr &netAllCap) +{ + NetworkStatus::NetConnStatus oldStatus = NetworkStatus::GetNetConnStatus(); + NetworkStatus::SetNetConnStatus(*netAllCap); + NetworkStatus::NetConnStatus newStatus = NetworkStatus::GetNetConnStatus(); + if (oldStatus == newStatus) { + LOGI("net status is not change, status is %{public}d", static_cast(newStatus)); + return E_OK; + } + if (newStatus == NetworkStatus::WIFI_CONNECT) { + LOGI("NetCapabilitiesChanged wifi connected"); + dataSyncManager_->TriggerRecoverySync(triggerType_); + dataSyncManager_->DownloadThumb(); + dataSyncManager_->CacheVideo(); + } else if (newStatus == NetworkStatus::CELLULAR_CONNECT) { + LOGI("NetCapabilitiesChanged cellular connected"); + dataSyncManager_->TriggerRecoverySync(triggerType_); + NetworkStatus::NetWorkChangeStopUploadTask(); + } else { + LOGI("NetCapabilitiesChanged newStatus:%{public}d", newStatus); + } + return E_OK; +} + +int32_t NetConnCallbackObserver::NetConnectionPropertiesChange(sptr &netHandle, + const sptr &info) +{ + return E_OK; +} + +int32_t NetConnCallbackObserver::NetLost(sptr &netHandle) +{ + LOGI("NetConnCallbackObserver::NetLost"); + NetworkStatus::SetNetConnStatus(NetworkStatus::NetConnStatus::NO_NETWORK); + return E_OK; +} + +int32_t NetConnCallbackObserver::NetUnavailable() +{ + return E_OK; +} + +int32_t NetConnCallbackObserver::NetBlockStatusChange(sptr &netHandle, bool blocked) +{ + return E_OK; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp new file mode 100644 index 0000000..4b4f502 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2024 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 "network_set_manager.h" + +#include + +#include "accesstoken_kit.h" +#include "cloud_file_kit.h" +#include "datashare_errno.h" +#include "datashare_result_set.h" +#include "dfs_error.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "parameters.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +const std::string QUERY_URI = "datashareproxy://"; +const std::string PHOTO_NET_CONT = "datashare://kernel/linux/common_modules/cloud_filecom.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; +const std::string SWITCH_STATUS_KEY = "useMobileNetworkData"; +const std::string CLOUDDRIVE_KEY = "persist.kernel.bundle_name.clouddrive"; +const std::string PHOTOS_BUNDLE_NAME = "com.ohos.photos"; +const std::string BUNDLE_NAME_KEY = "key"; +const std::string BUNDLE_NAME_VALUE = "value"; +auto driveBundleName = system::GetParameter(CLOUDDRIVE_KEY, ""); +auto photoQueryUri = PHOTO_NET_CONT + "&key=photo_network_connection_status"; +auto commonQueryUri = QUERY_URI + driveBundleName + "/cloud_sp?key=" + SWITCH_STATUS_KEY; +DataShare::CreateOptions commonOptions; + +int32_t NetworkSetManager::QueryCellularConnect(int32_t userId, const std::string &bundleName) +{ + LOGI("QueryCellularConnect bundleName: %{public}s", bundleName.c_str()); + DataShare::DataSharePredicates predicates; + predicates.EqualTo(BUNDLE_NAME_KEY, SWITCH_STATUS_KEY); + std::shared_ptr resultSet; + std::vector columns; + DataShare::CreateOptions options; + options.enabled_ = true; + auto clouddriveBundleName = system::GetParameter(CLOUDDRIVE_KEY, ""); + auto queryUri = QUERY_URI + clouddriveBundleName + "/cloud_sp?user=" + std::to_string(userId); + Uri uri(queryUri); + auto dataShareHelper = DataShare::DataShareHelper::Creator(QUERY_URI, options); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper = nullptr"); + return E_RDB; + } + resultSet = dataShareHelper->Query(uri, predicates, columns); + ReleaseDataShareHelper(dataShareHelper); + if (resultSet == nullptr) { + return E_RDB; + } + if (resultSet->GoToFirstRow() != E_OK) { + resultSet->Close(); + return E_RDB; + } + int32_t columnIndex = 0; + if (resultSet->GetColumnIndex(BUNDLE_NAME_VALUE, columnIndex) != E_OK) { + resultSet->Close(); + return E_RDB; + } + int64_t status = -1; + if (resultSet->GetLong(columnIndex, status) != E_OK) { + resultSet->Close(); + return E_RDB; + } + resultSet->Close(); + std::string queryKey = std::to_string(userId) + "/" + bundleName; + if (status == 1) { + cellularNetMap_.EnsureInsert(queryKey, true); + LOGI("QueryCellularConnect on"); + } else { + cellularNetMap_.EnsureInsert(queryKey, false); + LOGI("QueryCellularConnect off"); + } + return E_OK; +} + +int32_t NetworkSetManager::QueryNetConnect(int32_t userId, const std::string &bundleName) +{ + LOGI("QueryNetConnect bundleName: %{public}s", bundleName.c_str()); + DataShare::DataSharePredicates predicates; + predicates.EqualTo("KEYWORD", "photo_network_connection_status"); + std::vector columns = {"VALUE"}; + std::shared_ptr resultSet; + DataShare::CreateOptions options; + options.enabled_ = true; + auto queryUri = PHOTO_NET_CONT + "&key=photo_network_connection_status"; + auto dataShareHelper = DataShare::DataShareHelper::Creator(QUERY_URI, options); + Uri uri(queryUri); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper = nullptr"); + return E_RDB; + } + resultSet = dataShareHelper->Query(uri, predicates, columns); + ReleaseDataShareHelper(dataShareHelper); + if (resultSet == nullptr) { + return E_RDB; + } + if (resultSet->GoToFirstRow() != E_OK) { + resultSet->Close(); + return E_RDB; + } + int32_t columnIndex = 0; + if (resultSet->GetColumnIndex(BUNDLE_NAME_VALUE, columnIndex) != E_OK) { + resultSet->Close(); + return E_RDB; + } + std::string val; + if (resultSet->GetString(columnIndex, val) != E_OK) { + resultSet->Close(); + return E_RDB; + } + resultSet->Close(); + std::string queryKey = std::to_string(userId) + "/" + bundleName; + if (val == "on") { + netMap_.EnsureInsert(queryKey, true); + LOGI("QueryNetConnect on"); + } else { + netMap_.EnsureInsert(queryKey, false); + LOGI("QueryNetConnect off"); + } + return E_OK; +} + +void NetworkSetManager::GetCellularConnect(const std::string &bundleName, const int32_t userId) +{ + bool preCheckSwitch = false; + bool getConnect = cellularNetMap_.Find(std::to_string(userId) + "/" + bundleName, preCheckSwitch); + if (QueryCellularConnect(userId, bundleName) != E_OK) { + cellularNetMap_.EnsureInsert(std::to_string(userId) + "/" + + bundleName, GetConfigParams(bundleName, userId)); + } + + bool endCheckSwitch = false; + getConnect = cellularNetMap_.Find(std::to_string(userId) + "/" + bundleName, endCheckSwitch); + if (netStatus_ != WIFI_CONNECT && preCheckSwitch && !endCheckSwitch && dataSyncManager_ != nullptr) { + dataSyncManager_->StopUploadTask(bundleName, userId); + } +} + + +void NetworkSetManager::GetNetConnect(const std::string &bundleName, const int32_t userId) +{ + if (QueryNetConnect(userId, bundleName) != E_OK) { + netMap_.EnsureInsert(std::to_string(userId) + "/" + bundleName, true); + } +} + +bool NetworkSetManager::GetConfigParams(const std::string &bundleName, int32_t userId) +{ + auto driveKit = CloudFile::CloudFileKit::GetInstance(); + std::map param; + auto err = driveKit->GetAppConfigParams(userId, bundleName, param); + if (err != E_OK || param.empty()) { + LOGE("GetAppConfigParams failed"); + return false; + } + std::string networkDataStr = param["useMobileNetworkData"]; + bool isValid = std::all_of(networkDataStr.begin(), networkDataStr.end(), ::isdigit); + if (!isValid) { + LOGE("invalid param"); + return false; + } + int32_t networkData = std::stoi(networkDataStr); + if (networkData == 0) { + return false; + } + return true; +} + +void NetworkSetManager::UnregisterObserver(const std::string &bundleName, const int32_t userId, const int32_t type) +{ + LOGI("UnregisterObserver start"); + commonOptions.enabled_ = true; + auto dataShareHelper = DataShare::DataShareHelper::Creator(QUERY_URI, commonOptions); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper = nullptr"); + return; + } + sptr dataObserver(new (std::nothrow) MobileNetworkObserver(bundleName, + userId, type)); + if (type == CELLULARCONNECT) { + Uri observerUri(commonQueryUri); + dataShareHelper->UnregisterObserver(observerUri, dataObserver); + } else { + Uri observerUri(photoQueryUri); + dataShareHelper->UnregisterObserver(observerUri, dataObserver); + } + ReleaseDataShareHelper(dataShareHelper); + LOGI("UnregisterObserver type:%{public}d, finish", type); +} + +void NetworkSetManager::RegisterObserver(const std::string &bundleName, const int32_t userId, const int32_t type) +{ + commonOptions.enabled_ = true; + auto dataShareHelper = DataShare::DataShareHelper::Creator(QUERY_URI, commonOptions); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper = nullptr"); + return; + } + sptr dataObserver(new (std::nothrow) MobileNetworkObserver(bundleName, userId, type)); + if (type == CELLULARCONNECT) { + Uri observerUri(commonQueryUri); + dataShareHelper->RegisterObserver(observerUri, dataObserver); + } else { + Uri observerUri(photoQueryUri); + dataShareHelper->RegisterObserver(observerUri, dataObserver); + } + ReleaseDataShareHelper(dataShareHelper); + LOGI("RegisterObserver type:%{public}d, finish", type); +} + +void NetworkSetManager::ReleaseDataShareHelper(std::shared_ptr &helper) +{ + if (helper == nullptr) { + LOGI("helper is nullptr"); + return; + } + if (!helper->Release()) { + LOGI("Release data share helper failed"); + return; + } + LOGI("Release data share helper finish"); +} + +void MobileNetworkObserver::OnChange() +{ + LOGI("MobileNetworkObserver OnChange network status"); + if (observerCallback_ != nullptr) { + observerCallback_(); + } + if (type_ == NetworkSetManager::CELLULARCONNECT) { + NetworkSetManager::GetCellularConnect(bundleName_, userId_); + } else { + NetworkSetManager::GetNetConnect(bundleName_, userId_); + } +} + +bool NetworkSetManager::IsAllowCellularConnect(const std::string &bundleName, const int32_t userId) +{ + LOGI("IsAllowCellularConnect bundleName: %{public}s", bundleName.c_str()); + bool checkSwitch = false; + bool getCellularConnect = cellularNetMap_.Find(std::to_string(userId) + "/" + bundleName, checkSwitch); + if (getCellularConnect == false) { + GetCellularConnect(bundleName, userId); + return cellularNetMap_.ReadVal(std::to_string(userId) + "/" + bundleName); + } + return checkSwitch; +} + +bool NetworkSetManager::IsAllowNetConnect(const std::string &bundleName, const int32_t userId) +{ + LOGI("IsAllowNetConnect bundleName: %{public}s", bundleName.c_str()); + bool checkSwitch = true; + bool getNetConnect = netMap_.Find(std::to_string(userId) + "/" + bundleName, checkSwitch); + if (getNetConnect == false) { + GetNetConnect(bundleName, userId); + return netMap_.ReadVal(std::to_string(userId) + "/" + bundleName); + } + return checkSwitch; +} + +void NetworkSetManager::InitNetworkSetManager(const std::string &bundleName, const int32_t userId) +{ + LOGI("InitNetworkSetManager bundleName: %{public}s", bundleName.c_str()); + if (bundleName != PHOTOS_BUNDLE_NAME) { + LOGE("InitNetworkSetManager bundleName is illegals"); + return; + } + RegisterObserver(bundleName, userId, CELLULARCONNECT); + RegisterObserver(bundleName, userId, NETCONNECT); + GetCellularConnect(bundleName, userId); + GetNetConnect(bundleName, userId); +} + +void NetworkSetManager::InitDataSyncManager(std::shared_ptr dataSyncManager) +{ + dataSyncManager_ = dataSyncManager; +} + +static bool ConvertToInt(const std::string &str, int32_t &value) +{ + auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value); + return ec == std::errc{} && ptr == str.data() + str.size(); +} + +void NetworkSetManager::NetWorkChangeStopUploadTask() +{ + std::map cellularNetMap; + auto it = [&](std::string bundleName, bool swichStatus) { + cellularNetMap.insert(std::make_pair(bundleName, swichStatus)); + }; + cellularNetMap_.Iterate(it); + + for (auto pair = cellularNetMap.begin(); pair != cellularNetMap.end(); ++pair) { + const std::string &key = pair->first; + if (key.empty()) { + continue; + } + LOGI("bundleName: %{public}s", key.c_str()); + size_t pos = key.find(PHOTOS_BUNDLE_NAME); + if (pos == std::string::npos) { + continue; + } + auto swichStatus = pair->second; + if (swichStatus) { + continue; + } + + pos = key.find("/"); + if (pos == std::string::npos) { + continue; + } + + int32_t userId; + if (!ConvertToInt(key.substr(0, pos), userId)) { + continue; + } + + std::string bundleName = key.substr(pos + 1); + LOGI("bundleName: %{public}s, userId:%{public}d", key.c_str(), userId); + if (dataSyncManager_ != nullptr) { + dataSyncManager_->StopUploadTask(bundleName, userId); + } + } +} + +void NetworkSetManager::SetNetConnStatus(NetworkSetManager::NetConnStatus netStatus) +{ + netStatus_ = netStatus; + LOGI("netStatus type:%{public}d", netStatus); +} +} \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp new file mode 100644 index 0000000..6a1d14d --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp @@ -0,0 +1,164 @@ +/* + * 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 "network_status.h" + +#include +#include + +#include "net_conn_client.h" +#include "parameter.h" + +#include "dfs_error.h" +#include "network_set_manager.h" +#include "net_conn_callback_observer.h" +#include "utils_log.h" + +using namespace OHOS::NetManagerStandard; + +namespace OHOS::FileManagement::CloudSync { +static constexpr const int32_t MIN_VALID_NETID = 100; +static constexpr const int32_t WAIT_NET_SERVICE_TIME = 4; +static const char *NET_MANAGER_ON_STATUS = "2"; + +int32_t NetworkStatus::RegisterNetConnCallback(std::shared_ptr dataSyncManager) +{ + sptr observer(new (std::nothrow) NetConnCallbackObserver(dataSyncManager)); + if (observer == nullptr) { + LOGE("new operator error.observer is nullptr"); + return E_GET_NETWORK_MANAGER_FAILED; + } + int nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer); + if (nRet != NETMANAGER_SUCCESS) { + LOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet); + return E_GET_NETWORK_MANAGER_FAILED; + } + return E_OK; +} + +int32_t NetworkStatus::GetDefaultNet() +{ + NetHandle netHandle; + int ret = NetConnClient::GetInstance().GetDefaultNet(netHandle); + if (ret != NETMANAGER_SUCCESS) { + LOGE("GetDefaultNet failed, ret = %{public}d", ret); + return E_GET_NETWORK_MANAGER_FAILED; + } + if (netHandle.GetNetId() < MIN_VALID_NETID) { + SetNetConnStatus(NetConnStatus::NO_NETWORK); + return E_OK; + } + NetAllCapabilities netAllCap; + ret = NetConnClient::GetInstance().GetNetCapabilities(netHandle, netAllCap); + if (ret != NETMANAGER_SUCCESS) { + LOGE("GetNetCapbilities failed, ret = %{public}d", ret); + return E_GET_NETWORK_MANAGER_FAILED; + } + SetNetConnStatus(netAllCap); + return E_OK; +} + +void NetworkStatus::SetNetConnStatus(NetManagerStandard::NetAllCapabilities &netAllCap) +{ + if (netAllCap.netCaps_.count(NetCap::NET_CAPABILITY_INTERNET)) { + if (netAllCap.bearerTypes_.count(BEARER_ETHERNET)) { + SetNetConnStatus(NetConnStatus::ETHERNET_CONNECT); + } else if (netAllCap.bearerTypes_.count(BEARER_WIFI)) { + SetNetConnStatus(NetConnStatus::WIFI_CONNECT); + } else if (netAllCap.bearerTypes_.count(BEARER_CELLULAR)) { + SetNetConnStatus(NetConnStatus::CELLULAR_CONNECT); + } + } else { + SetNetConnStatus(NetConnStatus::NO_NETWORK); + } +} + +int32_t NetworkStatus::GetAndRegisterNetwork(std::shared_ptr dataSyncManager) +{ + int32_t res = GetDefaultNet(); + if (res != E_OK) { + return res; + } + + NetworkSetManager::InitDataSyncManager(dataSyncManager); + return RegisterNetConnCallback(dataSyncManager); +} + +void NetworkStatus::NetWorkChangeStopUploadTask() +{ + NetworkSetManager::NetWorkChangeStopUploadTask(); +} + +void NetworkStatus::InitNetwork(std::shared_ptr dataSyncManager) +{ + int status = WaitParameter("startup.service.ctl.netmanager", NET_MANAGER_ON_STATUS, WAIT_NET_SERVICE_TIME); + if (status != 0) { + LOGE(" wait SAMGR error, return value %{public}d.", status); + return; + } + constexpr int RETRY_MAX_TIMES = 2; + int retryCount = 0; + constexpr int RETRY_TIME_INTERVAL_MILLISECOND = 1 * 1000 * 1000; + do { + if (GetAndRegisterNetwork(dataSyncManager) == E_OK) { + break; + } + LOGE("wait and retry registering network callback"); + retryCount++; + usleep(RETRY_TIME_INTERVAL_MILLISECOND); + } while (retryCount < RETRY_MAX_TIMES); +} + +void NetworkStatus::SetNetConnStatus(NetworkStatus::NetConnStatus netStatus) +{ + netStatus_ = netStatus; + NetworkSetManager::SetNetConnStatus(static_cast(netStatus)); + return; +} + +NetworkStatus::NetConnStatus NetworkStatus::GetNetConnStatus() +{ + return netStatus_; +} + +bool NetworkStatus::CheckMobileNetwork(const std::string &bundleName, const int32_t userId) +{ + if (bundleName != "com.ohos.photos") { + return true; + } + if (NetworkSetManager::IsAllowCellularConnect(bundleName, userId)) { + LOGI("datashare status open, CheckMobileNetwork success"); + return true; + } + if (netStatus_ == WIFI_CONNECT) { + LOGI("datashare status close, networkdtatus:wifi"); + return true; + } + return false; +} + +bool NetworkStatus::CheckNetwork(const std::string &bundleName, const int32_t userId) +{ + if (bundleName != "com.ohos.photos") { + return true; + } + if (NetworkSetManager::IsAllowNetConnect(bundleName, userId)) { + LOGI("CheckNetwork on"); + return true; + } + LOGI("CheckNetwork off"); + return false; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/screen_status.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/screen_status.cpp new file mode 100644 index 0000000..4198fd6 --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/screen_status.cpp @@ -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. + */ + +#include "screen_status.h" + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "dfs_error.h" +#include "power_mgr_client.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +bool ScreenStatus::IsScreenOn() +{ + return screenState_ == ScreenState::SCREEN_ON; +} + +void ScreenStatus::InitScreenStatus() +{ + bool isScreenOn = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); + screenState_ = isScreenOn? ScreenState::SCREEN_ON : ScreenState::SCREEN_OFF; +} + +void ScreenStatus::SetScreenState(ScreenState screenState) +{ + screenState_ = screenState; +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/system_load.cpp b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/system_load.cpp new file mode 100644 index 0000000..80cba0e --- /dev/null +++ b/cloud_file/frameworks/native/cloud_file_kit_inner/src/sync_rule/system_load.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2024 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 "system_load.h" + +#include "battery_status.h" +#include "dfs_error.h" +#include "parameters.h" +#include "task_state_manager.h" +#include "utils_log.h" +#include "res_sched_client.h" + +namespace OHOS::FileManagement::CloudSync { + +void SystemLoadListener::SetDataSycner(std::shared_ptr dataSyncManager) +{ + dataSyncManager_ = dataSyncManager; +} + +void SystemLoadStatus::RegisterSystemloadCallback(std::shared_ptr dataSyncManager) +{ + sptr loadListener = new (std::nothrow) SystemLoadListener(); + if (loadListener == nullptr) { + return; + } + loadListener->SetDataSycner(dataSyncManager); + ResourceSchedule::ResSchedClient::GetInstance().RegisterSystemloadNotifier(loadListener); +} + +void SystemLoadListener::OnSystemloadLevel(int32_t level) +{ + SystemLoadStatus::Setload(level); + if (level >= SYSTEMLOADLEVEL_HOT) { + LOGI("OnSystemloadLevel over warm"); + } else if (dataSyncManager_) { + std::string systemLoadSync = system::GetParameter(TEMPERATURE_SYSPARAM_SYNC, ""); + std::string systemLoadThumb = system::GetParameter(TEMPERATURE_SYSPARAM_THUMB, ""); + LOGI("OnSystemloadLevel is normal, level:%{public}d", level); + if (systemLoadSync == "true") { + LOGI("SetParameter TEMPERATURE_SYSPARAM_SYNC false"); + system::SetParameter(TEMPERATURE_SYSPARAM_SYNC, "false"); + TaskStateManager::GetInstance().StartTask(); + dataSyncManager_->TriggerRecoverySync(SyncTriggerType::SYSTEM_LOAD_TRIGGER); + } + if (systemLoadThumb == "true") { + if (BatteryStatus::IsCharging() && level > SYSTEMLOADLEVEL_WARM) { + return; + } else if (!BatteryStatus::IsCharging() && level > SYSTEMLOADLEVEL_NORMAL) { + return; + } + LOGI("SetParameter TEMPERATURE_SYSPARAM_THUMB false"); + system::SetParameter(TEMPERATURE_SYSPARAM_THUMB, "false"); + TaskStateManager::GetInstance().StartTask(); + dataSyncManager_->DownloadThumb(); + } + } +} + +void SystemLoadStatus::GetSystemloadLevel() +{ + loadstatus_ = ResourceSchedule::ResSchedClient::GetInstance().GetSystemloadLevel(); + LOGI("GetSystemloadLevel finish, loadstatus:%{public}d", loadstatus_); +} + +void SystemLoadStatus::Setload(int32_t load) +{ + loadstatus_ = load; +} + +void SystemLoadStatus::InitSystemload(std::shared_ptr dataSyncManager) +{ + GetSystemloadLevel(); + RegisterSystemloadCallback(dataSyncManager); +} + +bool SystemLoadStatus::IsLoadStatusUnderNormal(STOPPED_TYPE process) +{ + if (loadstatus_ > SYSTEMLOADLEVEL_NORMAL && process == STOPPED_IN_SYNC) { + LOGI("SetParameter TEMPERATURE_SYSPARAM_SYNC true"); + system::SetParameter(TEMPERATURE_SYSPARAM_SYNC, "true"); + return false; + } + return true; +} + +bool SystemLoadStatus::IsLoadStatusUnderHot(STOPPED_TYPE process, int32_t level) +{ + if (loadstatus_ > level) { + if (process == STOPPED_IN_THUMB) { + LOGI("SetParameter TEMPERATURE_SYSPARAM_THUMB true"); + system::SetParameter(TEMPERATURE_SYSPARAM_THUMB, "true"); + } else if (process == STOPPED_IN_SYNC) { + LOGI("SetParameter TEMPERATURE_SYSPARAM_SYNC true"); + system::SetParameter(TEMPERATURE_SYSPARAM_SYNC, "true"); + } + return false; + } + return true; +} +} \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_client.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_client.h new file mode 100644 index 0000000..01dbbd3 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_client.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 OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_CLIENT_H +#define OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_CLIENT_H + +#include "cloud_download_callback_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudDownloadCallbackClient final : public CloudDownloadCallbackStub { +public: + explicit CloudDownloadCallbackClient(const std::shared_ptr &callback) + : callback_(callback) {} + + void OnDownloadProcess(const DownloadProgressObj& progress) override; + +private: + std::shared_ptr callback_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_CLIENT_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_stub.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_stub.h new file mode 100644 index 0000000..14d2ecb --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_callback_stub.h @@ -0,0 +1,40 @@ +/* +* 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 OHOS_FILEMGMT_CLOUD_DOWLOAD_CALLBACK_STUB_H +#define OHOS_FILEMGMT_CLOUD_DOWLOAD_CALLBACK_STUB_H + +#include + +#include "i_cloud_download_callback.h" +#include "iremote_stub.h" + +namespace OHOS::FileManagement::CloudSync { + +using ServiceInterface = std::function; +class CloudDownloadCallbackStub : public IRemoteStub { +public: + CloudDownloadCallbackStub(); + virtual ~CloudDownloadCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + std::map opToInterfaceMap_; + + int32_t HandleOnProcess(MessageParcel &data, MessageParcel &reply); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_STUB_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_uri_manager.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_uri_manager.h new file mode 100644 index 0000000..4144e9d --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_download_uri_manager.h @@ -0,0 +1,46 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_DOWNLOAD_URI_MANAGER_H +#define OHOS_FILEMGMT_CLOUD_DOWNLOAD_URI_MANAGER_H + +#include "nocopyable.h" + +#include +#include + +namespace OHOS::FileManagement::CloudSync { +class CloudDownloadUriManager : public NoCopyable { +public: + static CloudDownloadUriManager &GetInstance(); + + int32_t AddPathToUri(const std::string& path, const std::string& uri); + int32_t AddDownloadIdToPath(int64_t &downloadId, std::vector &pathVec); + std::string GetUri(const std::string& path); + void RemoveUri(const std::string& path); + void CheckDownloadIdPathMap(int64_t &downloadId); + void RemoveUri(const int64_t &downloadId); + void Reset(); + +private: + CloudDownloadUriManager() = default; + std::mutex pathUriMutex_; + std::mutex downloadIdPathMutex_; + std::map pathUriMap_; + std::map> downloadIdPathMap_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_DOWNLOAD_URI_MANAGER_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_optimize_callback_client.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_optimize_callback_client.h new file mode 100644 index 0000000..8438d29 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_optimize_callback_client.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 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 OHOS_FILEMGMT_CLOUD_OPTOMIZE_CALLBACK_CLIENT_H +#define OHOS_FILEMGMT_CLOUD_OPTOMIZE_CALLBACK_CLIENT_H + +#include "cloud_optimize_callback_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudOptimizeCallbackClient final : public CloudOptimizeCallbackStub { +public: + explicit CloudOptimizeCallbackClient(const std::shared_ptr &callback) + : callback_(callback) {} + + void OnOptimizeProcess(const OptimizeState state, const int32_t progress) override; + +private: + std::shared_ptr callback_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_OPTOMIZE_CALLBACK_CLIENT_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_optimize_callback_stub.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_optimize_callback_stub.h new file mode 100644 index 0000000..430bea0 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_optimize_callback_stub.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2025 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 OHOS_FILEMGMT_CLOUD_OPTOMIZE_CALLBACK_STUB_H +#define OHOS_FILEMGMT_CLOUD_OPTOMIZE_CALLBACK_STUB_H + +#include + +#include "i_cloud_optimize_callback.h" +#include "iremote_stub.h" + +namespace OHOS::FileManagement::CloudSync { + +using ServiceInterface = std::function; +class CloudOptimizeCallbackStub : public IRemoteStub { +public: + CloudOptimizeCallbackStub(); + virtual ~CloudOptimizeCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + std::map opToInterfaceMap_; + int32_t HandleOnProcess(MessageParcel &data, MessageParcel &reply); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_OPTOMIZE_CALLBACK_STUB_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_asset_manager_impl.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_asset_manager_impl.h new file mode 100644 index 0000000..ba872bb --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_asset_manager_impl.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 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 OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_IMPL_H +#define OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_IMPL_H + +#include +#include + +#include "cloud_sync_asset_manager.h" +#include "download_asset_callback_client.h" +#include "nocopyable.h" +#include "svc_death_recipient.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncAssetManagerImpl final : public CloudSyncAssetManager, public NoCopyable { +public: + static CloudSyncAssetManagerImpl &GetInstance(); + + int32_t UploadAsset(const int32_t userId, const std::string &request, std::string &result) override; + int32_t DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfo &assetInfo) override; + int32_t DeleteAsset(const int32_t userId, const std::string &uri) override; + int32_t DownloadFile(const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfo &assetInfo, + ResultCallback resultCallback) override; + int32_t DownloadFiles(const int32_t userId, + const std::string &bundleName, + const std::vector &assetInfo, + std::vector &assetResultMap) override; + +private: + CloudSyncAssetManagerImpl() = default; + void SetDeathRecipient(const sptr &remoteObject); + + sptr downloadAssetCallback_; + std::atomic_flag isCallbackRegistered_{false}; + std::atomic_flag isFirstCall_{false}; + sptr deathRecipient_; + std::mutex callbackInitMutex_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_IMPL_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_client.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_client.h new file mode 100644 index 0000000..05a3563 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_client.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2022 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 OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_CLIENT_H +#define OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_CLIENT_H + +#include "cloud_sync_callback_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncCallbackClient final : public CloudSyncCallbackStub { +public: + explicit CloudSyncCallbackClient(const std::shared_ptr &callback) : callback_(callback) {} + + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override; + +private: + std::shared_ptr callback_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_CLIENT_H \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_stub.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_stub.h new file mode 100644 index 0000000..e4d075d --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_callback_stub.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2022 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 OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_STUB_H +#define OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_STUB_H + +#include + +#include "i_cloud_sync_callback.h" +#include "iremote_stub.h" + +namespace OHOS::FileManagement::CloudSync { +using ServiceInterface = std::function; +class CloudSyncCallbackStub : public IRemoteStub { +public: + CloudSyncCallbackStub(); + virtual ~CloudSyncCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + std::map opToInterfaceMap_; + + int32_t HandleOnSyncStateChanged(MessageParcel &data, MessageParcel &reply); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_STUB_H \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_manager_impl.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_manager_impl.h new file mode 100644 index 0000000..c8514dd --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/cloud_sync_manager_impl.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2022 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 OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_H + +#include + +#include "nocopyable.h" + +#include "cloud_optimize_callback_client.h" +#include "cloud_sync_callback_client.h" +#include "cloud_sync_common.h" +#include "cloud_sync_manager.h" +#include "svc_death_recipient.h" +#include "system_ability_status_change_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncManagerImpl final : public CloudSyncManager, public NoCopyable { +public: + static CloudSyncManagerImpl &GetInstance(); + + int32_t RegisterCallback(const std::shared_ptr callback, + const std::string &bundleName = "") override; + int32_t RegisterFileSyncCallback(const std::shared_ptr callback, + const std::string &bundleName = "") override; + int32_t UnRegisterCallback(const std::string &bundleName = "") override; + int32_t UnRegisterFileSyncCallback(const std::string &bundleName = "") override; + int32_t StartSync(const std::string &bundleName = "") override; + int32_t StartFileSync(const std::string &bundleName = "") override; + int32_t StartSync(bool forceFlag, const std::shared_ptr callback) override; + int32_t TriggerSync(const std::string &bundleName, const int32_t &userId) override; + int32_t StopSync(const std::string &bundleName = "", bool forceFlag = false) override; + int32_t StopFileSync(const std::string &bundleName = "", bool forceFlag = false) override; + int32_t ResetCursor(const std::string &bundleName = "") override; + int32_t ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) override; + int32_t OptimizeStorage(const OptimizeSpaceOptions &optimizeOptions, + const std::shared_ptr optimizeCallback = nullptr) override; + int32_t StopOptimizeStorage() override; + int32_t Clean(const std::string &accountId, const CleanOptions &cleanOptions) override; + int32_t NotifyDataChange(const std::string &accoutId, const std::string &bundleName) override; + int32_t NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) override; + int32_t EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) override; + int32_t DisableCloud(const std::string &accoutId) override; + int32_t StartDownloadFile(const std::string &uri) override; + int32_t StartFileCache(const std::string &uri) override; + int32_t StartFileCache(const std::vector &uriVec, int64_t &downloadId, + int32_t fieldkey = FIELDKEY_CONTENT, + const std::shared_ptr downloadCallback = nullptr, + int32_t timeout = -1) override; + int32_t StopDownloadFile(const std::string &uri, bool needClean = false) override; + int32_t StopFileCache(int64_t downloadId, bool needClean = false, int32_t timeout = -1) override; + int32_t DownloadThumb() override; + int32_t RegisterDownloadFileCallback(const std::shared_ptr downloadCallback) override; + int32_t RegisterFileCacheCallback(const std::shared_ptr downloadCallback) override; + int32_t UnregisterDownloadFileCallback() override; + int32_t UnregisterFileCacheCallback() override; + int32_t GetSyncTime(int64_t &syncTime, const std::string &bundleName = "") override; + int32_t CleanCache(const std::string &uri) override; + void CleanGalleryDentryFile() override; + int32_t BatchCleanFile(const std::vector &fileInfo, std::vector &failCloudId) override; + int32_t BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId) override; + + class SystemAbilityStatusChange : public SystemAbilityStatusChangeStub { + public: + SystemAbilityStatusChange(const std::string &bundleName) : bundleName_(bundleName) {}; + void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId); + void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId); + private: + std::string bundleName_ = ""; + }; +private: + CloudSyncManagerImpl() = default; + void SetDeathRecipient(const sptr &remoteObject); + bool ResetProxyCallback(uint32_t retryCount, const std::string &bundleName); + + std::atomic_flag isFirstCall_{false}; + sptr deathRecipient_; + std::shared_ptr callback_; + std::shared_ptr downloadCallback_; + sptr listener_; + std::mutex subscribeMutex_; + std::mutex downloadMutex_; + std::mutex callbackMutex_; + void SubscribeListener(std::string bundleName = ""); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_client.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_client.h new file mode 100644 index 0000000..6fbd591 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_client.h @@ -0,0 +1,46 @@ +/* + * 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 OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_CLIENT_H +#define OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_CLIENT_H + +#include +#include +#include +#include + +#include "safe_map.h" + +#include "cloud_sync_asset_manager.h" +#include "download_asset_callback_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class DownloadAssetCallbackClient final : public DownloadAssetCallbackStub { +public: + DownloadAssetCallbackClient() = default; + ~DownloadAssetCallbackClient() = default; + void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) override; + void AddDownloadTaskCallback(const TaskId taskId, CloudSyncAssetManager::ResultCallback callback); + void RemoveDownloadTaskCallback(const TaskId taskId); + CloudSyncAssetManager::ResultCallback GetDownloadTaskCallback(const TaskId taskId); + TaskId GetTaskId(); + +private: + SafeMap callbackListMap_; + std::atomic taskId_{0}; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_CLIENT_H \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_stub.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_stub.h new file mode 100644 index 0000000..e46c108 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/download_asset_callback_stub.h @@ -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. + */ + +#ifndef OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_STUB_H +#define OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_STUB_H + +#include + +#include "i_download_asset_callback.h" +#include "iremote_stub.h" + +namespace OHOS::FileManagement::CloudSync { +using ServiceInterface = std::function; +class DownloadAssetCallbackStub : public IRemoteStub { +public: + DownloadAssetCallbackStub(); + virtual ~DownloadAssetCallbackStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + std::map opToInterfaceMap_; + + int32_t HandleOnFinished(MessageParcel &data, MessageParcel &reply); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_STUB_H \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/include/service_proxy.h b/cloud_file/frameworks/native/cloudsync_kit_inner/include/service_proxy.h new file mode 100644 index 0000000..c742b0e --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/include/service_proxy.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 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 OHOS_FILEMGMT_SERVICE_PROXY_H +#define OHOS_FILEMGMT_SERVICE_PROXY_H + +#include "icloud_sync_service.h" +#include "iremote_proxy.h" +#include "system_ability_load_callback_stub.h" + +namespace OHOS::FileManagement::CloudSync { +class ServiceProxy : public IRemoteProxy { +public: + static sptr GetInstance(); + static void InvaildInstance(); + + class ServiceProxyLoadCallback : public SystemAbilityLoadCallbackStub { + public: + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr &remoteObject) override; + void OnLoadSystemAbilityFail(int32_t systemAbilityId) override; + + std::condition_variable proxyConVar_; + std::atomic isLoadSuccess_{false}; + }; + +private: + static inline std::mutex proxyMutex_; + static inline std::mutex instanceMutex_; + static inline sptr serviceProxy_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_SERVICE_PROXY_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_client.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_client.cpp new file mode 100644 index 0000000..9f62fc0 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_client.cpp @@ -0,0 +1,31 @@ +/* + * 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 "cloud_download_callback_client.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +void CloudDownloadCallbackClient::OnDownloadProcess(const DownloadProgressObj& progress) +{ + if (!callback_) { + LOGE("callback_ is null, maybe not registered"); + return; + } + callback_->OnDownloadProcess(progress); +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_stub.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_stub.cpp new file mode 100644 index 0000000..f84f61e --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_stub.cpp @@ -0,0 +1,59 @@ +/* + * 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 "cloud_download_callback_stub.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +CloudDownloadCallbackStub::CloudDownloadCallbackStub() +{ + opToInterfaceMap_[SERVICE_CMD_ON_PROCESS] = [this](MessageParcel &data, MessageParcel &reply) { + return this->HandleOnProcess(data, reply); + }; +} + +int32_t CloudDownloadCallbackStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, + MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != GetDescriptor()) { + return E_SERVICE_DESCRIPTOR_IS_EMPTY; + } + auto interfaceIndex = opToInterfaceMap_.find(code); + if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { + LOGE("Cannot response request %d: unknown tranction", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + auto memberFunc = interfaceIndex->second; + return memberFunc(data, reply); +} + +int32_t CloudDownloadCallbackStub::HandleOnProcess(MessageParcel &data, MessageParcel &reply) +{ + sptr progress = data.ReadParcelable(); + if (!progress) { + LOGE("object of DownloadProgressObj is nullptr"); + return E_INVAL_ARG; + } + + OnDownloadProcess(*progress); + return E_OK; +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp new file mode 100644 index 0000000..38fd0aa --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp @@ -0,0 +1,124 @@ +/* + * 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 "cloud_download_uri_manager.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { + +CloudDownloadUriManager& CloudDownloadUriManager::GetInstance() +{ + static CloudDownloadUriManager mgr; + return mgr; +} + +int32_t CloudDownloadUriManager::AddPathToUri(const std::string& path, const std::string& uri) +{ + LOGI("download_file : add path [ %{public}s ] -> uri [ %{public}s ]", + GetAnonyString(path).c_str(), GetAnonyString(uri).c_str()); + std::lock_guard lock(pathUriMutex_); + if (pathUriMap_.find(path) == pathUriMap_.end()) { + pathUriMap_[path] = uri; + LOGI("download_file : add path [ %{public}s ] success, pathUriMap_ size is %{public}zu", + GetAnonyString(path).c_str(), pathUriMap_.size()); + return E_OK; + } + LOGE("file is already trigger downloading, pathUriMap_ size is %{public}zu", pathUriMap_.size()); + return E_STOP; +} + +int32_t CloudDownloadUriManager::AddDownloadIdToPath(int64_t &downloadId, std::vector &pathVec) +{ + std::lock_guard lock(downloadIdPathMutex_); + if (downloadIdPathMap_.find(downloadId) == downloadIdPathMap_.end()) { + downloadIdPathMap_[downloadId] = pathVec; + LOGI("download_file : AddDownloadIdToPath add downloadId %{public}lld, downloadIdPathMap_ size is %{public}zu", + static_cast(downloadId), downloadIdPathMap_.size()); + } + return E_OK; +} + +void CloudDownloadUriManager::RemoveUri(const std::string& path) +{ + std::lock_guard lock(pathUriMutex_); + if (pathUriMap_.find(path) != pathUriMap_.end()) { + LOGI("download_file : remove path [ %{public}s ] success, pathUriMap_ size is %{public}zu", + GetAnonyString(path).c_str(), pathUriMap_.size()); + pathUriMap_.erase(path); + } +} +void CloudDownloadUriManager::CheckDownloadIdPathMap(int64_t &downloadId) +{ + bool existUri = false; + std::lock_guard lock(downloadIdPathMutex_); + if (downloadIdPathMap_.find(downloadId) != downloadIdPathMap_.end()) { + std::vector pathVec = downloadIdPathMap_[downloadId]; + + std::lock_guard lock2(pathUriMutex_); + for (unsigned long i = 0; i < pathVec.size(); i++) { + if (pathUriMap_.find(pathVec[i]) != pathUriMap_.end()) { + existUri = true; + break; + } + } + if (!existUri) { + downloadIdPathMap_.erase(downloadId); + LOGI("download_file : remove downloadId [ %{public}lld ] success, downloadIdPathMap_ size is %{public}zu", + static_cast(downloadId), downloadIdPathMap_.size()); + } + } +} + +void CloudDownloadUriManager::RemoveUri(const int64_t &downloadId) +{ + std::lock_guard lock(downloadIdPathMutex_); + if (downloadIdPathMap_.find(downloadId) != downloadIdPathMap_.end()) { + std::vector pathVec = downloadIdPathMap_[downloadId]; + + std::lock_guard lock2(pathUriMutex_); + for (unsigned long i = 0; i < pathVec.size(); i++) { + if (pathUriMap_.find(pathVec[i]) != pathUriMap_.end()) { + pathUriMap_.erase(pathVec[i]); + LOGI("download_file : remove path [ %{public}s ] success, pathUriMap_ size is %{public}zu", + GetAnonyString(pathVec[i]).c_str(), pathUriMap_.size()); + } + } + downloadIdPathMap_.erase(downloadId); + LOGI("download_file : remove downloadId [ %{public}lld ] success, downloadIdPathMap_ size is %{public}zu", + static_cast(downloadId), downloadIdPathMap_.size()); + } +} + +std::string CloudDownloadUriManager::GetUri(const std::string& path) +{ + std::lock_guard lock(pathUriMutex_); + if (pathUriMap_.find(path) != pathUriMap_.end()) { + LOGI("download_file : get path [ %{public}s ] success, pathUriMap_ size is %{public}zu", + GetAnonyString(path).c_str(), pathUriMap_.size()); + return pathUriMap_[path]; + } + + LOGE("download_file : get path [ %{public}s ] fail, pathUriMap_ size is %{public}zu", + GetAnonyString(path).c_str(), pathUriMap_.size()); + return ""; +} + +void CloudDownloadUriManager::Reset() +{ + std::lock_guard lock(pathUriMutex_); + pathUriMap_.clear(); +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_client.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_client.cpp new file mode 100644 index 0000000..a8280d1 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_client.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 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 "cloud_optimize_callback_client.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +void CloudOptimizeCallbackClient::OnOptimizeProcess(const OptimizeState state, const int32_t progress) +{ + if (!callback_) { + LOGE("callback_ is null, maybe not registered"); + return; + } + callback_->OnOptimizeProcess(state, progress); +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_stub.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_stub.cpp new file mode 100644 index 0000000..28c51c7 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_stub.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2025 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 "cloud_optimize_callback_stub.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +CloudOptimizeCallbackStub::CloudOptimizeCallbackStub() +{ + opToInterfaceMap_[SERVICE_CMD_ON_PROCESS] = [this](MessageParcel &data, MessageParcel &reply) { + return this->HandleOnProcess(data, reply); + }; +} + +int32_t CloudOptimizeCallbackStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, + MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != GetDescriptor()) { + return E_SERVICE_DESCRIPTOR_IS_EMPTY; + } + auto interfaceIndex = opToInterfaceMap_.find(code); + if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { + LOGE("Cannot response request %d: unknown tranction", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + auto memberFunc = interfaceIndex->second; + return memberFunc(data, reply); +} + +int32_t CloudOptimizeCallbackStub::HandleOnProcess(MessageParcel &data, MessageParcel &reply) +{ + OptimizeState state = OptimizeState(data.ReadInt32()); + int32_t progress = data.ReadInt32(); + OnOptimizeProcess(state, progress); + LOGI("HandleOnProcess state:%{public}d: OptimizeSize%{public}d", state, progress); + return E_OK; +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager.cpp new file mode 100644 index 0000000..c7e13e3 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 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 "cloud_sync_asset_manager_impl.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +CloudSyncAssetManager &CloudSyncAssetManager::GetInstance() +{ + return CloudSyncAssetManagerImpl::GetInstance(); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager_impl.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager_impl.cpp new file mode 100644 index 0000000..7988d73 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager_impl.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2022 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 "cloud_sync_asset_manager_impl.h" + +#include + +#include "service_proxy.h" +#include "dfs_error.h" +#include "download_asset_callback_client.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +CloudSyncAssetManagerImpl &CloudSyncAssetManagerImpl::GetInstance() +{ + static CloudSyncAssetManagerImpl instance; + return instance; +} + +int32_t CloudSyncAssetManagerImpl::UploadAsset(const int32_t userId, + const std::string &request, + std::string &result) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + int32_t ret = CloudSyncServiceProxy->UploadAsset(userId, request, result); + LOGD("UploadAsset ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncAssetManagerImpl::DownloadFile(const int32_t userId, + const std::string &bundleName, + AssetInfo &assetInfo) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + AssetInfoObj assetInfoObj(assetInfo); + int32_t ret = CloudSyncServiceProxy->DownloadFile(userId, bundleName, assetInfoObj); + LOGI("DownloadFile ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncAssetManagerImpl::DownloadFiles(const int32_t userId, + const std::string &bundleName, + const std::vector &assetInfo, + std::vector &assetResultMap) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + std::vector assetInfoObj; + for (const auto &info : assetInfo) { + AssetInfoObj obj(info); + assetInfoObj.emplace_back(obj); + } + int32_t ret = CloudSyncServiceProxy->DownloadFiles(userId, bundleName, assetInfoObj, assetResultMap); + LOGI("DownloadFile ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncAssetManagerImpl::DownloadFile(const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfo &assetInfo, + ResultCallback resultCallback) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + { + std::lock_guard lock(callbackInitMutex_); + if (downloadAssetCallback_ == nullptr) { + downloadAssetCallback_ = sptr(new (std::nothrow) DownloadAssetCallbackClient()); + } + if (downloadAssetCallback_ == nullptr) { + LOGE("have no enough memory"); + return E_MEMORY; + } + } + + if (!isCallbackRegistered_.test_and_set()) { + LOGI("register callback"); + CloudSyncServiceProxy->RegisterDownloadAssetCallback(downloadAssetCallback_); + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + auto taskId = downloadAssetCallback_->GetTaskId(); + downloadAssetCallback_->AddDownloadTaskCallback(taskId, resultCallback); + AssetInfoObj assetInfoObj(assetInfo); + int32_t ret = CloudSyncServiceProxy->DownloadAsset(taskId, userId, bundleName, networkId, assetInfoObj); + LOGI("DownloadFile ret %{public}d, taskId:%{public}" PRIu64 "", ret, taskId); + return ret; +} + +int32_t CloudSyncAssetManagerImpl::DeleteAsset(const int32_t userId, const std::string &uri) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + int32_t ret = CloudSyncServiceProxy->DeleteAsset(userId, uri); + LOGI("DeleteAsset ret %{public}d", ret); + return ret; +} + +void CloudSyncAssetManagerImpl::SetDeathRecipient(const sptr &remoteObject) +{ + if (!isFirstCall_.test_and_set()) { + auto deathCallback = [this](const wptr &obj) { + LOGE("service died. Died remote obj"); + ServiceProxy::InvaildInstance(); + isCallbackRegistered_.clear(); + isFirstCall_.clear(); + }; + deathRecipient_ = sptr(new SvcDeathRecipient(deathCallback)); + remoteObject->AddDeathRecipient(deathRecipient_); + } +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_client.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_client.cpp new file mode 100644 index 0000000..a2ad853 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_client.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2022 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 "cloud_sync_callback_client.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +void CloudSyncCallbackClient::OnSyncStateChanged(CloudSyncState state, ErrorType error) +{ + if (!callback_) { + LOGE("callback_ is null, maybe not registered"); + return; + } + callback_->OnSyncStateChanged(state, error); +} + +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_stub.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_stub.cpp new file mode 100644 index 0000000..2cf4579 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_stub.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 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 "cloud_sync_callback_stub.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +CloudSyncCallbackStub::CloudSyncCallbackStub() +{ + opToInterfaceMap_[SERVICE_CMD_ON_SYNC_STATE_CHANGED] = [this](MessageParcel &data, MessageParcel &reply) { + return this->HandleOnSyncStateChanged(data, reply); + }; +} + +int32_t CloudSyncCallbackStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, + MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != GetDescriptor()) { + return E_SERVICE_DESCRIPTOR_IS_EMPTY; + } + auto interfaceIndex = opToInterfaceMap_.find(code); + if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { + LOGE("Cannot response request %d: unknown tranction", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + auto memberFunc = interfaceIndex->second; + return memberFunc(data, reply); +} + +int32_t CloudSyncCallbackStub::HandleOnSyncStateChanged(MessageParcel &data, MessageParcel &reply) +{ + CloudSyncState state = CloudSyncState(data.ReadInt32()); + ErrorType error = ErrorType(data.ReadInt32()); + OnSyncStateChanged(state, error); + LOGI("OnSyncStateChanged, error = %{public}d, state = %{public}d", error, state); + return E_OK; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp new file mode 100644 index 0000000..fa8325b --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp @@ -0,0 +1,439 @@ +/* + * 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 +#include "cloud_sync_common.h" + +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +namespace { +constexpr uint32_t MAX_MAP_SIZE = 1024; +} +bool SwitchDataObj::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteUint32(switchData.size())) { + LOGE("failed to write switch data size"); + return false; + } + for (const auto& it : switchData) { + if (!parcel.WriteString(it.first)) { + LOGE("failed to write key"); + return false; + } + if (!parcel.WriteBool(it.second)) { + LOGE("failed to write value"); + return false; + } + } + return true; +} + +bool DownloadProgressObj::MarshallingBatch(Parcel &parcel) const +{ + if (!parcel.WriteInt64(batchDownloadSize)) { + LOGE("failed to write batchDownloadSize"); + return false; + } + if (!parcel.WriteInt64(batchTotalSize)) { + LOGE("failed to write batchTotalSize"); + return false; + } + if (!parcel.WriteInt64(batchSuccNum)) { + LOGE("failed to write batchSuccNum"); + return false; + } + if (!parcel.WriteInt64(batchFailNum)) { + LOGE("failed to write batchFailNum"); + return false; + } + if (!parcel.WriteInt64(batchTotalNum)) { + LOGE("failed to write batchTotalNum"); + return false; + } + if (!parcel.WriteInt32(batchState)) { + LOGE("failed to write batchState"); + return false; + } + + return true; +} + +bool DownloadProgressObj::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(path)) { + LOGE("failed to write download path"); + return false; + } + if (!parcel.WriteInt32(state)) { + LOGE("failed to write download state"); + return false; + } + if (!parcel.WriteInt64(downloadedSize)) { + LOGE("failed to write downloadedSize"); + return false; + } + if (!parcel.WriteInt64(totalSize)) { + LOGE("failed to write totalSize"); + return false; + } + if (!parcel.WriteInt32(downloadErrorType)) { + LOGE("failed to write downloadErrorType"); + return false; + } + if (!parcel.WriteInt64(downloadId)) { + LOGE("failed to write downloadId"); + return false; + } + + if (!MarshallingBatch(parcel)) { + return false; + } + + return true; +} + +bool CleanOptions::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteUint32(appActionsData.size())) { + LOGE("failed to write appActions data size"); + return false; + } + for (const auto& it : appActionsData) { + if (!parcel.WriteString(it.first)) { + LOGE("failed to write key"); + return false; + } + if (!parcel.WriteInt32(it.second)) { + LOGE("failed to write value"); + return false; + } + } + return true; +} + +SwitchDataObj *SwitchDataObj::Unmarshalling(Parcel &parcel) +{ + SwitchDataObj *info = new (std::nothrow) SwitchDataObj(); + if ((info != nullptr) && (!info->ReadFromParcel(parcel))) { + LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +DownloadProgressObj *DownloadProgressObj::Unmarshalling(Parcel &parcel) +{ + DownloadProgressObj *info = new (std::nothrow) DownloadProgressObj(); + if ((info != nullptr) && (!info->ReadFromParcel(parcel))) { + LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +CleanOptions *CleanOptions::Unmarshalling(Parcel &parcel) +{ + CleanOptions *info = new (std::nothrow) CleanOptions(); + if ((info != nullptr) && (!info->ReadFromParcel(parcel))) { + LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +OptimizeSpaceOptions *OptimizeSpaceOptions::Unmarshalling(Parcel &parcel) +{ + OptimizeSpaceOptions *info = new (std::nothrow) OptimizeSpaceOptions(); + if ((info != nullptr) && (!info->ReadFromParcel(parcel))) { + LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +bool OptimizeSpaceOptions::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadInt64(totalSize)) { + LOGE("failed to read totalSize"); + return false; + } + if (!parcel.ReadInt32(agingDays)) { + LOGE("failed to read agingDays"); + return false; + } + return true; +} + +bool OptimizeSpaceOptions::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt64(totalSize)) { + LOGE("failed to write totalSize"); + return false; + } + if (!parcel.WriteInt32(agingDays)) { + LOGE("failed to write agingDays"); + return false; + } + + return true; +} + +bool SwitchDataObj::ReadFromParcel(Parcel &parcel) +{ + switchData.clear(); + uint32_t size = 0; + if (!parcel.ReadUint32(size)) { + LOGE("fail to read switch data size"); + return false; + } + if (size > MAX_MAP_SIZE) { + LOGE("switch data is oversize, the limit is %{public}d", MAX_MAP_SIZE); + return false; + } + for (uint32_t i = 0; i < size; ++i) { + std::string key; + if (!parcel.ReadString(key)) { + LOGE("fail to read switch data key"); + return false; + } + bool value = false; + if (!parcel.ReadBool(value)) { + LOGE("fail to read switch data value"); + return false; + } + switchData.emplace(key, value); + } + return true; +} + +bool CleanOptions::ReadFromParcel(Parcel &parcel) +{ + appActionsData.clear(); + uint32_t size = 0; + if (!parcel.ReadUint32(size)) { + LOGE("fail to read appActions data size"); + return false; + } + if (size > MAX_MAP_SIZE) { + LOGE("appActions data is oversize, the limit is %{public}d", MAX_MAP_SIZE); + return false; + } + for (uint32_t i = 0; i < size; ++i) { + std::string key; + if (!parcel.ReadString(key)) { + LOGE("fail to read appActions data key"); + return false; + } + int value = 0; + if (!parcel.ReadInt32(value)) { + LOGE("fail to read appActions data value"); + return false; + } + appActionsData.emplace(key, value); + } + return true; +} + +bool DownloadProgressObj::ReadBatchFromParcel(Parcel &parcel) +{ + if (!parcel.ReadInt64(batchDownloadSize)) { + LOGE("failed to read batchDownloadSize"); + return false; + } + if (!parcel.ReadInt64(batchTotalSize)) { + LOGE("failed to read batchTotalSize"); + return false; + } + if (!parcel.ReadInt64(batchSuccNum)) { + LOGE("failed to read batchSuccNum"); + return false; + } + if (!parcel.ReadInt64(batchFailNum)) { + LOGE("failed to read batchFailNum"); + return false; + } + if (!parcel.ReadInt64(batchTotalNum)) { + LOGE("failed to read batchTotalNum"); + return false; + } + int32_t tempBatchState = 0; + if (!parcel.ReadInt32(tempBatchState)) { + LOGE("failed to read download batchState"); + return false; + } + batchState = static_cast(tempBatchState); + + return true; +} + +bool DownloadProgressObj::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadString(path)) { + LOGE("failed to read download path"); + return false; + } + int32_t tempState = 0; + if (!parcel.ReadInt32(tempState)) { + LOGE("failed to read download state"); + return false; + } + state = static_cast(tempState); + if (!parcel.ReadInt64(downloadedSize)) { + LOGE("failed to read downloadedSize"); + return false; + } + if (!parcel.ReadInt64(totalSize)) { + LOGE("failed to read totalSize"); + return false; + } + if (!parcel.ReadInt32(downloadErrorType)) { + LOGE("failed to read downloadErrorType"); + return false; + } + if (!parcel.ReadInt64(downloadId)) { + LOGE("failed to read downloadId"); + return false; + } + + if (!ReadBatchFromParcel(parcel)) { + return false; + } + + return true; +} + +std::string DownloadProgressObj::to_string() +{ + std::stringstream ss; + std::string pathAnony = GetAnonyString(path); + ss << "DownloadProgressObj [path: " << pathAnony; + ss << " state: " << state; + ss << " downloaded: " << downloadedSize; + ss << " total: " << totalSize; + ss << " downloadErrorType: " << downloadErrorType; + + ss << " downloadId: " << downloadId; + ss << " batchState: " << batchState; + ss << " batchDownloadSize: " << batchDownloadSize; + ss << " batchTotalSize: " << batchTotalSize; + ss << " batchSuccNum: " << batchSuccNum; + ss << " batchFailNum: " << batchFailNum; + ss << " batchTotalNum: " << batchTotalNum << "]"; + return ss.str(); +} + +bool DentryFileInfoObj::ReadFromParcel(Parcel &parcel) +{ + parcel.ReadString(cloudId); + parcel.ReadInt64(size); + parcel.ReadInt64(modifiedTime); + parcel.ReadString(path); + parcel.ReadString(fileName); + parcel.ReadString(fileType); + return true; +} + +bool DentryFileInfoObj::Marshalling(Parcel &parcel) const +{ + parcel.WriteString(cloudId); + parcel.WriteInt64(size); + parcel.WriteInt64(modifiedTime); + parcel.WriteString(path); + parcel.WriteString(fileName); + parcel.WriteString(fileType); + return true; +} + +DentryFileInfoObj *DentryFileInfoObj::Unmarshalling(Parcel &parcel) +{ + DentryFileInfoObj *info = new (std::nothrow) DentryFileInfoObj(); + if ((info != nullptr) && (!info->ReadFromParcel(parcel))) { + LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +bool AssetInfoObj::ReadFromParcel(Parcel &parcel) +{ + parcel.ReadString(uri); + parcel.ReadString(recordType); + parcel.ReadString(recordId); + parcel.ReadString(fieldKey); + parcel.ReadString(assetName); + return true; +} + +bool AssetInfoObj::Marshalling(Parcel &parcel) const +{ + parcel.WriteString(uri); + parcel.WriteString(recordType); + parcel.WriteString(recordId); + parcel.WriteString(fieldKey); + parcel.WriteString(assetName); + return true; +} + +AssetInfoObj *AssetInfoObj::Unmarshalling(Parcel &parcel) +{ + AssetInfoObj *info = new (std::nothrow) AssetInfoObj(); + if ((info != nullptr) && (!info->ReadFromParcel(parcel))) { + LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +bool CleanFileInfoObj::ReadFromParcel(Parcel &parcel) +{ + parcel.ReadString(cloudId); + parcel.ReadInt64(size); + parcel.ReadInt64(modifiedTime); + parcel.ReadString(path); + parcel.ReadString(fileName); + parcel.ReadStringVector(&attachment); + return true; +} + +bool CleanFileInfoObj::Marshalling(Parcel &parcel) const +{ + parcel.WriteString(cloudId); + parcel.WriteInt64(size); + parcel.WriteInt64(modifiedTime); + parcel.WriteString(path); + parcel.WriteString(fileName); + parcel.WriteStringVector(attachment); + return true; +} + +CleanFileInfoObj *CleanFileInfoObj::Unmarshalling(Parcel &parcel) +{ + CleanFileInfoObj *info = new (std::nothrow) CleanFileInfoObj(); + if ((info != nullptr) && (!info->ReadFromParcel(parcel))) { + LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager.cpp new file mode 100644 index 0000000..8c29106 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2022 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 "cloud_sync_manager_impl.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +CloudSyncManager &CloudSyncManager::GetInstance() +{ + return CloudSyncManagerImpl::GetInstance(); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp new file mode 100644 index 0000000..a6794cc --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp @@ -0,0 +1,736 @@ +/* + * Copyright (c) 2022 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 "cloud_download_callback_client.h" +#include "cloud_sync_manager_impl.h" +#include "cloud_sync_callback_client.h" +#include "service_proxy.h" +#include "dfs_error.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "utils_directory.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +constexpr int32_t MIN_USER_ID = 100; +constexpr int32_t MAX_FILE_CACHE_NUM = 400; +constexpr int32_t MAX_DENTRY_FILE_SIZE = 500; +CloudSyncManagerImpl &CloudSyncManagerImpl::GetInstance() +{ + static CloudSyncManagerImpl instance; + return instance; +} + +int32_t CloudSyncManagerImpl::RegisterCallback(const std::shared_ptr callback, + const std::string &bundleName) +{ + if (!callback) { + LOGE("callback is null"); + return E_INVAL_ARG; + } + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + auto ret = CloudSyncServiceProxy->RegisterCallbackInner(sptr(new (std::nothrow) CloudSyncCallbackClient(callback)), + bundleName); + { + unique_lock lock(callbackMutex_); + callback_ = callback; + } + SubscribeListener(bundleName); + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + LOGI("RegisterCallback ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::RegisterFileSyncCallback(const std::shared_ptr callback, + const std::string &bundleName) +{ + if (!callback) { + LOGE("callback is null"); + return E_INVAL_ARG; + } + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + auto ret = CloudSyncServiceProxy->RegisterFileSyncCallbackInner( + sptr(new (std::nothrow) CloudSyncCallbackClient(callback)), bundleName); + { + unique_lock lock(callbackMutex_); + callback_ = callback; + } + SubscribeListener(bundleName); + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + LOGI("RegisterFileSyncCallback ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::UnRegisterCallback(const std::string &bundleName) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + auto ret = CloudSyncServiceProxy->UnRegisterCallbackInner(bundleName); + if (!ret) { + { + unique_lock lock(callbackMutex_); + callback_ = nullptr; + } + SubscribeListener(); + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + LOGI("UnRegisterCallback ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::UnRegisterFileSyncCallback(const std::string &bundleName) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + auto ret = CloudSyncServiceProxy->UnRegisterFileSyncCallbackInner(bundleName); + if (!ret) { + { + unique_lock lock(callbackMutex_); + callback_ = nullptr; + } + SubscribeListener(); + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + LOGI("UnRegisterFileSyncCallback ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::StartSync(const std::string &bundleName) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->StartSyncInner(true, bundleName); +} + +int32_t CloudSyncManagerImpl::StartFileSync(const std::string &bundleName) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->StartFileSyncInner(true, bundleName); +} + +int32_t CloudSyncManagerImpl::GetSyncTime(int64_t &syncTime, const std::string &bundleName) +{ + LOGI("GetSyncTime Start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->GetSyncTimeInner(syncTime, bundleName); +} + +int32_t CloudSyncManagerImpl::OptimizeStorage(const OptimizeSpaceOptions &optimizeOptions, + const std::shared_ptr optimizeCallback) +{ + LOGI("OptimizeStorage Start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + + bool isCallbackValid = false; + sptr opCallback = sptr(new (std::nothrow) CloudOptimizeCallbackClient(nullptr)); + if (optimizeCallback != nullptr) { + opCallback = sptr(new (std::nothrow) CloudOptimizeCallbackClient(optimizeCallback)); + isCallbackValid = true; + if (opCallback == nullptr) { + isCallbackValid = false; + LOGE("OptimizeStorage callback failed"); + } + } + + return CloudSyncServiceProxy->OptimizeStorage(optimizeOptions, isCallbackValid, opCallback); +} + +int32_t CloudSyncManagerImpl::StopOptimizeStorage() +{ + LOGI("StopOptimizeStorage Start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + + return CloudSyncServiceProxy->StopOptimizeStorage(); +} + +int32_t CloudSyncManagerImpl::StartSync(bool forceFlag, const std::shared_ptr callback) +{ + if (!callback) { + LOGE("callback is null"); + return E_INVAL_ARG; + } + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + if (!isFirstCall_.test()) { + LOGI("Register callback"); + auto ret = CloudSyncServiceProxy->RegisterCallbackInner( + sptr(new (std::nothrow) CloudSyncCallbackClient(callback)), ""); + if (ret) { + LOGE("Register callback failed"); + isFirstCall_.clear(); + return ret; + } + callback_ = callback; + SubscribeListener(); + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + } + + return CloudSyncServiceProxy->StartSyncInner(forceFlag, ""); +} + +int32_t CloudSyncManagerImpl::TriggerSync(const std::string &bundleName, const int32_t &userId) +{ + if (bundleName.empty() || userId < MIN_USER_ID) { + LOGE("Trigger Sync parameter is invalid"); + return E_INVAL_ARG; + } + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->TriggerSyncInner(bundleName, userId); +} + +int32_t CloudSyncManagerImpl::StopSync(const std::string &bundleName, bool forceFlag) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->StopSyncInner(bundleName, forceFlag); +} + +int32_t CloudSyncManagerImpl::StopFileSync(const std::string &bundleName, bool forceFlag) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->StopFileSyncInner(bundleName, forceFlag); +} + +int32_t CloudSyncManagerImpl::ResetCursor(const std::string &bundleName) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->ResetCursor(bundleName); +} + +int32_t CloudSyncManagerImpl::ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + + int32_t ret = CloudSyncServiceProxy->ChangeAppSwitch(accoutId, bundleName, status); + LOGI("ChangeAppSwitch ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::NotifyDataChange(const std::string &accoutId, const std::string &bundleName) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + + int32_t ret = CloudSyncServiceProxy->NotifyDataChange(accoutId, bundleName); + LOGI("NotifyDataChange ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::NotifyEventChange( + int32_t userId, const std::string &eventId, const std::string &extraData) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + + int32_t ret = CloudSyncServiceProxy->NotifyEventChange(userId, eventId, extraData); + LOGI("NotifyDataChange ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::StartDownloadFile(const std::string &uri) +{ + LOGI("StartDownloadFile start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + int32_t ret = CloudSyncServiceProxy->StartDownloadFile(uri); + LOGI("StartDownloadFile ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::BatchCleanFile(const std::vector &fileInfo, + std::vector &failCloudId) +{ + if (fileInfo.size() > CLEAN_FILE_MAX_SIZE) { + LOGE("BatchCleanFile size over max limit"); + return E_INVAL_ARG; + } + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + std::vector fileInfoObj; + for (const auto &info : fileInfo) { + CleanFileInfoObj obj(info); + fileInfoObj.emplace_back(obj); + } + + return CloudSyncServiceProxy->BatchCleanFile(fileInfoObj, failCloudId); +} + +int32_t CloudSyncManagerImpl::StartFileCache(const std::string &uri) +{ + LOGI("StartFileCache start"); + int64_t downloadId = 0; + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + std::vector uriVec; + uriVec.push_back(uri); + bool isCallbackValid = false; + int32_t timeout = -1; + sptr dlCallback = sptr(new (std::nothrow) CloudDownloadCallbackClient(nullptr)); + int32_t ret = CloudSyncServiceProxy->StartFileCache(uriVec, downloadId, FIELDKEY_CONTENT, isCallbackValid, + dlCallback, timeout); + LOGI("StartFileCache ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::StartFileCache(const std::vector &uriVec, + int64_t &downloadId, int32_t fieldkey, + const std::shared_ptr downloadCallback, + int32_t timeout) +{ + LOGI("StartFileCache batch start, uriVec size: %{public}zu, fieldKey: %{public}d, Callback is null: %{public}d", + uriVec.size(), fieldkey, (downloadCallback == nullptr)); + if (uriVec.empty()) { + LOGE("StartFileCache, uri list is empty"); + return E_INVAL_ARG; + } + if (uriVec.size() > MAX_FILE_CACHE_NUM) { + LOGE("StartFileCache, the size of uri list exceeded the maximum limit, size: %{public}zu", uriVec.size()); + return E_EXCEED_MAX_SIZE; + } + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + + bool isCallbackValid = false; + sptr dlCallback = sptr(new (std::nothrow) CloudDownloadCallbackClient(nullptr)); + if (downloadCallback != nullptr) { + dlCallback = sptr(new (std::nothrow) CloudDownloadCallbackClient(downloadCallback)); + isCallbackValid = true; + if (dlCallback == nullptr) { + LOGE("register download callback failed"); + isCallbackValid = false; + } + } + + int32_t ret = CloudSyncServiceProxy->StartFileCache(uriVec, downloadId, fieldkey, + isCallbackValid, dlCallback, timeout); + LOGI("StartFileCache batch ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::StopDownloadFile(const std::string &uri, bool needClean) +{ + LOGI("StopDownloadFile start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + int32_t ret = CloudSyncServiceProxy->StopDownloadFile(uri, needClean); + LOGI("StopDownloadFile ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::StopFileCache(int64_t downloadId, bool needClean, int32_t timeout) +{ + LOGI("StopFileCache start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + int32_t ret = CloudSyncServiceProxy->StopFileCache(downloadId, needClean, timeout); + LOGI("StopFileCache ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::DownloadThumb() +{ + LOGI("DownloadThumb start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + int32_t ret = CloudSyncServiceProxy->DownloadThumb(); + LOGI("DownloadThumb ret %{public}d", ret); + return ret; +} + +int32_t CloudSyncManagerImpl::RegisterDownloadFileCallback( + const std::shared_ptr downloadCallback) +{ + LOGI("RegisterDownloadFileCallback start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + { + unique_lock lock(downloadMutex_); + auto dlCallback = sptr(new (std::nothrow) CloudDownloadCallbackClient(downloadCallback)); + if (dlCallback == nullptr || + CloudSyncServiceProxy->RegisterDownloadFileCallback(dlCallback) != E_OK) { + LOGE("register download callback failed"); + } else { + downloadCallback_ = downloadCallback; + } + } + SubscribeListener(); + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return E_OK; +} + +int32_t CloudSyncManagerImpl::RegisterFileCacheCallback( + const std::shared_ptr downloadCallback) +{ + LOGI("RegisterFileCacheCallback start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + { + unique_lock lock(downloadMutex_); + auto dlCallback = sptr(new (std::nothrow) CloudDownloadCallbackClient(downloadCallback)); + if (dlCallback == nullptr || + CloudSyncServiceProxy->RegisterFileCacheCallback(dlCallback) != E_OK) { + LOGE("register download callback failed"); + } else { + downloadCallback_ = downloadCallback; + } + } + SubscribeListener(); + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return E_OK; +} + +int32_t CloudSyncManagerImpl::UnregisterDownloadFileCallback() +{ + LOGI("UnregisterDownloadFileCallback start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + int32_t ret = E_OK; + { + unique_lock lock(downloadMutex_); + ret = CloudSyncServiceProxy->UnregisterDownloadFileCallback(); + LOGI("UnregisterDownloadFileCallback ret %{public}d", ret); + if (ret == E_OK) { + downloadCallback_ = nullptr; + } + } + SubscribeListener(); + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return ret; +} + +int32_t CloudSyncManagerImpl::UnregisterFileCacheCallback() +{ + LOGI("UnregisterFileCacheCallback start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + int32_t ret = E_OK; + { + unique_lock lock(downloadMutex_); + ret = CloudSyncServiceProxy->UnregisterFileCacheCallback(); + LOGI("UnregisterFileCacheCallback ret %{public}d", ret); + if (ret == E_OK) { + downloadCallback_ = nullptr; + } + } + SubscribeListener(); + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return ret; +} + +void CloudSyncManagerImpl::SetDeathRecipient(const sptr &remoteObject) +{ + if (!isFirstCall_.test_and_set()) { + auto deathCallback = [this](const wptr &obj) { + LOGE("service died."); + ServiceProxy::InvaildInstance(); + if (callback_) { + callback_->OnDeathRecipient(); + } + isFirstCall_.clear(); + }; + deathRecipient_ = sptr(new SvcDeathRecipient(deathCallback)); + if (!remoteObject->AddDeathRecipient(deathRecipient_)) { + LOGE("add death recipient failed"); + isFirstCall_.clear(); + } + } +} + +int32_t CloudSyncManagerImpl::EnableCloud(const std::string &accoutId, + const SwitchDataObj &switchData) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + + return CloudSyncServiceProxy->EnableCloud(accoutId, switchData); +} + +int32_t CloudSyncManagerImpl::DisableCloud(const std::string &accoutId) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->DisableCloud(accoutId); +} + +int32_t CloudSyncManagerImpl::Clean(const std::string &accountId, const CleanOptions &cleanOptions) +{ + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + + return CloudSyncServiceProxy->Clean(accountId, cleanOptions); +} + +int32_t CloudSyncManagerImpl::CleanCache(const std::string &uri) +{ + LOGI("CleanCache Start"); + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->CleanCacheInner(uri); +} + +int32_t CloudSyncManagerImpl::BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId) +{ + if (fileInfo.size() > MAX_DENTRY_FILE_SIZE) { + LOGE("BatchDentryFileInsert parameter is invalid"); + return E_INVAL_ARG; + } + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + std::vector fileInfoObj; + for (const auto &info : fileInfo) { + DentryFileInfoObj obj(info); + fileInfoObj.emplace_back(obj); + } + + return CloudSyncServiceProxy->BatchDentryFileInsert(fileInfoObj, failCloudId); +} + +void CloudSyncManagerImpl::SubscribeListener(std::string bundleName) +{ + unique_lock lock(subscribeMutex_); + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Samgr is nullptr"); + return; + } + if (listener_ != nullptr) { + auto ret = samgr->UnSubscribeSystemAbility(FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, listener_); + LOGI("unsubscribed to systemAbility ret %{public}d", ret); + } + if (callback_ != nullptr || downloadCallback_ != nullptr) { + listener_ = new SystemAbilityStatusChange(bundleName); + auto ret = samgr->SubscribeSystemAbility(FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, listener_); + LOGI("subscribed to systemAbility ret %{public}d", ret); + } else { + listener_ = nullptr; + } +} + +bool CloudSyncManagerImpl::ResetProxyCallback(uint32_t retryCount, const string &bundleName) +{ + auto cloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (cloudSyncServiceProxy == nullptr) { + LOGE("proxy is null"); + return false; + } + bool hasCallback = false; + { + unique_lock downloadLock(downloadMutex_); + if (downloadCallback_ != nullptr) { + auto dlCallback = sptr(new (std::nothrow) CloudDownloadCallbackClient(downloadCallback_)); + if (dlCallback == nullptr || + cloudSyncServiceProxy->RegisterDownloadFileCallback(dlCallback) != E_OK) { + LOGW("register download callback failed, try time is %{public}d", retryCount); + } else { + hasCallback = true; + } + } + } + if (callback_ != nullptr) { + auto callback = sptr(new (std::nothrow) CloudSyncCallbackClient(callback_)); + if (callback == nullptr || + cloudSyncServiceProxy->RegisterCallbackInner(callback, bundleName) != E_OK) { + LOGW("register callback failed, try time is %{public}d", retryCount); + } else { + hasCallback = true; + } + } + if (hasCallback) { + CloudSyncManagerImpl::GetInstance().SetDeathRecipient(cloudSyncServiceProxy->AsObject()); + } + return true; +} + +void CloudSyncManagerImpl::SystemAbilityStatusChange::OnAddSystemAbility(int32_t systemAbilityId, + const std::string &deviceId) +{ + const uint32_t RETRY_TIMES = 3; + const uint32_t SLEEP_TIME = 20 * 1000; + uint32_t retryCount = 0; + LOGI("saId %{public}d loaded", systemAbilityId); + do { + usleep(SLEEP_TIME); + if (!CloudSyncManagerImpl::GetInstance().ResetProxyCallback(retryCount, bundleName_)) { + continue; + } + return; + } while (++retryCount < RETRY_TIMES); + LOGE("register callback failed, try too many times"); +} + +void CloudSyncManagerImpl::SystemAbilityStatusChange::OnRemoveSystemAbility(int32_t systemAbilityId, + const std::string &deviceId) +{ + return; +} + +void CloudSyncManagerImpl::CleanGalleryDentryFile() +{ + const std::string photoDir = "/storage/media/cloud/files/Photo"; + const std::string thumbsDir = "/storage/media/cloud/files/.thumbs/Photo"; + if (!OHOS::Storage::DistributedFile::Utils::ForceRemoveDirectoryDeepFirst(photoDir)) { + LOGW("remove photo dentry dir failed, errno: %{public}d", errno); + } + if (!OHOS::Storage::DistributedFile::Utils::ForceRemoveDirectoryDeepFirst(thumbsDir)) { + LOGW("remove thumbs dentry dir failed, errno: %{public}d", errno); + } +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp new file mode 100644 index 0000000..e4ebe14 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp @@ -0,0 +1,67 @@ +/* + * 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 "download_asset_callback_client.h" + +#include + +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +void DownloadAssetCallbackClient::OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) +{ + auto callback = GetDownloadTaskCallback(taskId); + if (callback) { + LOGD("callback"); + callback(uri, result); + } + RemoveDownloadTaskCallback(taskId); + LOGD("On Download finished, taskId:%{public}" PRIu64 ", uri:%{public}s, ret:%{public}d", + taskId, GetAnonyString(uri).c_str(), + result); +} + +void DownloadAssetCallbackClient::AddDownloadTaskCallback(TaskId taskId, CloudSyncAssetManager::ResultCallback callback) +{ + LOGD("taskId = %{public}" PRIu64 "", taskId); + callbackListMap_.EnsureInsert(taskId, std::move(callback)); +} + +void DownloadAssetCallbackClient::RemoveDownloadTaskCallback(TaskId taskId) +{ + CloudSyncAssetManager::ResultCallback callback; + if (callbackListMap_.Find(taskId, callback)) { + callbackListMap_.Erase(taskId); + return; + } + LOGE("not find task callback, taskId = %{public}" PRIu64 "", taskId); +} + +CloudSyncAssetManager::ResultCallback DownloadAssetCallbackClient::GetDownloadTaskCallback(TaskId taskId) +{ + CloudSyncAssetManager::ResultCallback callback; + if (callbackListMap_.Find(taskId, callback)) { + return callback; + } + LOGE("not find task callback, taskId = %{public}" PRIu64 "", taskId); + return std::function{}; // empty function +} + +DownloadAssetCallback::TaskId DownloadAssetCallbackClient::GetTaskId() +{ + return taskId_.fetch_add(1); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp new file mode 100644 index 0000000..6f6254b --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.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 "download_asset_callback_stub.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +DownloadAssetCallbackStub::DownloadAssetCallbackStub() +{ + opToInterfaceMap_[SERVICE_CMD_ON_DOWNLOAD_FINSHED] = [this](MessageParcel &data, MessageParcel &reply) { + return this->HandleOnFinished(data, reply); + }; +} + +int32_t DownloadAssetCallbackStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, + MessageParcel &reply, + MessageOption &option) +{ + if (data.ReadInterfaceToken() != GetDescriptor()) { + return E_SERVICE_DESCRIPTOR_IS_EMPTY; + } + auto interfaceIndex = opToInterfaceMap_.find(code); + if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { + LOGE("Cannot response request %d: unknown tranction", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + auto memberFunc = interfaceIndex->second; + return memberFunc(data, reply); +} + +int32_t DownloadAssetCallbackStub::HandleOnFinished(MessageParcel &data, MessageParcel &reply) +{ + TaskId taskId = data.ReadUint64(); + string uri = data.ReadString(); + int32_t result = data.ReadInt32(); + OnFinished(taskId, uri, result); + return E_OK; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp new file mode 100644 index 0000000..a960c2c --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2025 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 "service_proxy.h" + +#include + +#include "dfs_error.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +constexpr int LOAD_SA_TIMEOUT_MS = 2000; + +sptr ServiceProxy::GetInstance() +{ + LOGD("getinstance"); + unique_lock lock(instanceMutex_); + if (serviceProxy_ != nullptr) { + return serviceProxy_; + } + + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Samgr is nullptr"); + return nullptr; + } + sptr cloudSyncLoadCallback = new ServiceProxyLoadCallback(); + if (cloudSyncLoadCallback == nullptr) { + LOGE("cloudSyncLoadCallback is nullptr"); + return nullptr; + } + int32_t ret = samgr->LoadSystemAbility(FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, cloudSyncLoadCallback); + if (ret != E_OK) { + LOGE("Failed to Load systemAbility, systemAbilityId:%{public}d, ret code:%{public}d", + FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, ret); + return nullptr; + } + unique_lock proxyLock(proxyMutex_); + auto waitStatus = cloudSyncLoadCallback->proxyConVar_.wait_for( + proxyLock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS), + [cloudSyncLoadCallback]() { return cloudSyncLoadCallback->isLoadSuccess_.load(); }); + if (!waitStatus) { + LOGE("Load CloudSynd SA timeout"); + return nullptr; + } + return serviceProxy_; +} + +void ServiceProxy::InvaildInstance() +{ + LOGI("invalid instance"); + unique_lock lock(instanceMutex_); + serviceProxy_ = nullptr; +} + +void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilitySuccess( + int32_t systemAbilityId, + const sptr &remoteObject) +{ + LOGI("Load CloudSync SA success,systemAbilityId:%{public}d, remoteObj result:%{private}s", systemAbilityId, + (remoteObject == nullptr ? "false" : "true")); + unique_lock lock(proxyMutex_); + if (serviceProxy_ != nullptr) { + LOGE("CloudSync SA proxy has been loaded"); + } else { + serviceProxy_ = iface_cast(remoteObject); + } + isLoadSuccess_.store(true); + proxyConVar_.notify_one(); +} + +void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) +{ + LOGI("Load CloudSync SA failed,systemAbilityId:%{public}d", systemAbilityId); + unique_lock lock(proxyMutex_); + serviceProxy_ = nullptr; + isLoadSuccess_.store(false); + proxyConVar_.notify_one(); +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/cloud_sync_manager_impl_lite.h b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/cloud_sync_manager_impl_lite.h new file mode 100644 index 0000000..24b520e --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/cloud_sync_manager_impl_lite.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 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 OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_LITE_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_LITE_H + +#include + +#include "nocopyable.h" + +#include "cloud_sync_manager_lite.h" +#include "svc_death_recipient_lite.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncManagerImplLite final : public CloudSyncManagerLite, public NoCopyable { +public: + static CloudSyncManagerImplLite &GetInstance(); + + int32_t TriggerSync(const std::string &bundleName, const int32_t &userId) override; + +private: + CloudSyncManagerImplLite() = default; + void SetDeathRecipient(const sptr &remoteObject); + + std::atomic_flag isFirstCall_{false}; + sptr deathRecipient_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_IMPL_LITE_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/cloud_sync_manager_lite.h b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/cloud_sync_manager_lite.h new file mode 100644 index 0000000..21062f6 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/cloud_sync_manager_lite.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 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 OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_LITE_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_LITE_H + +#include + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncManagerLite { +public: + static CloudSyncManagerLite &GetInstance(); + /** + * @brief 触发同步 + * + * @param bundleName 应用包名 + * @param userId 用户ID + * @return int32_t 同步返回执行结果 + */ + virtual int32_t TriggerSync(const std::string &bundleName, const int32_t &userId) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_LITE_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/svc_death_recipient_lite.h b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/svc_death_recipient_lite.h new file mode 100644 index 0000000..78bc9a4 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/include/svc_death_recipient_lite.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 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 OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_LITE_H +#define OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_LITE_H + +#include + +#include "iremote_object.h" + +namespace OHOS::FileManagement::CloudSync { +class SvcDeathRecipientLite : public IRemoteObject::DeathRecipient { +public: + explicit SvcDeathRecipientLite( + std::function &)> functor) : functor_(functor) {}; + void OnRemoteDied(const wptr &object) override + { + if (object == nullptr) { return; } + object->RemoveDeathRecipient(this); + functor_(object); + } + +private: + std::function &)> functor_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_LITE_H diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp new file mode 100644 index 0000000..778e1d8 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2024 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 "cloud_sync_manager_impl_lite.h" +#include "service_proxy.h" +#include "dfs_error.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +constexpr int32_t MIN_USER_ID = 100; +CloudSyncManagerImplLite &CloudSyncManagerImplLite::GetInstance() +{ + static CloudSyncManagerImplLite instance; + return instance; +} + +int32_t CloudSyncManagerImplLite::TriggerSync(const std::string &bundleName, const int32_t &userId) +{ + if (bundleName.empty() || userId < MIN_USER_ID) { + LOGE("Trigger Sync parameter is invalid"); + return E_INVAL_ARG; + } + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + if (!CloudSyncServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + return CloudSyncServiceProxy->TriggerSyncInner(bundleName, userId); +} + +void CloudSyncManagerImplLite::SetDeathRecipient(const sptr &remoteObject) +{ + if (!isFirstCall_.test_and_set()) { + auto deathCallback = [this](const wptr &obj) { + LOGE("service dead"); + ServiceProxy::InvaildInstance(); + isFirstCall_.clear(); + }; + deathRecipient_ = sptr(new SvcDeathRecipientLite(deathCallback)); + remoteObject->AddDeathRecipient(deathRecipient_); + } +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp new file mode 100644 index 0000000..f001b87 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 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 "cloud_sync_manager_impl_lite.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +CloudSyncManagerLite &CloudSyncManagerLite::GetInstance() +{ + return CloudSyncManagerImplLite::GetInstance(); +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_service_proxy_lite.cpp b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_service_proxy_lite.cpp new file mode 100644 index 0000000..ac2fae1 --- /dev/null +++ b/cloud_file/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_service_proxy_lite.cpp @@ -0,0 +1,347 @@ +/* + * Copyright (c) 2024 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 "service_proxy.h" + +#include + +#include "cloud_file_sync_service_interface_code.h" +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { + +constexpr int LOAD_SA_TIMEOUT_MS = 4000; + +int32_t CloudSyncServiceProxy::TriggerSyncInner(const std::string &bundleName, const int32_t &userId) +{ + LOGI("Trigger Sync"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + LOGE("Failed to write interface token"); + return E_BROKEN_IPC; + } + + if (!data.WriteString(bundleName)) { + LOGE("Failed to send the bundle name"); + return E_INVAL_ARG; + } + + if (!data.WriteInt32(userId)) { + LOGE("Failed to send the user id"); + return E_INVAL_ARG; + } + + auto remote = Remote(); + if (!remote) { + LOGE("remote is nullptr"); + return E_BROKEN_IPC; + } + + int32_t ret = remote->SendRequest( + static_cast (CloudFileSyncServiceInterfaceCode::SERVICE_CMD_TRIGGER_SYNC), + data, reply, option); + if (ret != E_OK) { + LOGE("Failed to send out the request, errno: %{public}d", ret); + return E_BROKEN_IPC; + } + LOGI("TriggerSyncInner Success"); + return reply.ReadInt32(); +} + +sptr ServiceProxy::GetInstance() +{ + LOGI("GetInstance"); + std::unique_lock lock(instanceMutex_); + if (serviceProxy_ != nullptr) { + return serviceProxy_; + } + + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Samgr is nullptr"); + return nullptr; + } + sptr cloudSyncLoadCallback = new ServiceProxyLoadCallback(); + if (cloudSyncLoadCallback == nullptr) { + LOGE("cloudSyncLoadCallback is nullptr"); + return nullptr; + } + int32_t ret = samgr->LoadSystemAbility(FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, cloudSyncLoadCallback); + if (ret != E_OK) { + LOGE("Failed to load System Ability, systemAbilityId: %{public}d, ret code: %{public}d", + FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, ret); + return nullptr; + } + std::unique_lock proxyLock(proxyMutex_); + auto waitStatus = cloudSyncLoadCallback->proxyConVar_.wait_for( + proxyLock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS), + [cloudSyncLoadCallback]() { return cloudSyncLoadCallback->isLoadSuccess_.load(); }); + if (!waitStatus) { + LOGE("Load CloudSync SA timeout"); + return nullptr; + } + return serviceProxy_; +} + +void ServiceProxy::InvaildInstance() +{ + LOGI("Invalid Instance"); + std::unique_lock lock(instanceMutex_); + serviceProxy_ = nullptr; +} + +void CloudSyncServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilitySuccess( + int32_t systemAbilityId, + const sptr &remoteObject) +{ + LOGI("Load CloudSync SA success, systemAbilityId: %{public}d, remote Obj result: %{private}s", + systemAbilityId, (remoteObject == nullptr ? "false" : "true")); + std::unique_lock lock(proxyMutex_); + if (serviceProxy_ != nullptr) { + LOGE("CloudSync SA proxy has been loaded"); + } else { + serviceProxy_ = iface_cast(remoteObject); + } + isLoadSuccess_.store(true); + proxyConVar_.notify_one(); +} + +void CloudSyncServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilityFail( + int32_t systemAbilityId) +{ + LOGI("Load CloudSync SA failed, systemAbilityId: %{public}d", systemAbilityId); + std::unique_lock lock(proxyMutex_); + serviceProxy_ = nullptr; + isLoadSuccess_.store(false); + proxyConVar_.notify_one(); +} + +int32_t CloudSyncServiceProxy::UnRegisterCallbackInner(const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::UnRegisterFileSyncCallbackInner(const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::RegisterCallbackInner(const sptr &remoteObject, + const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::RegisterFileSyncCallbackInner(const sptr &remoteObject, + const std::string &bundleName) +{ +return E_OK; +} + +int32_t CloudSyncServiceProxy::StartSyncInner(bool forceFlag, const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StartFileSyncInner(bool forceFlag, const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::GetSyncTimeInner(int64_t &syncTime, const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::CleanCacheInner(const std::string &uri) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StopSyncInner(const std::string &bundleName, bool forceFlag) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StopFileSyncInner(const std::string &bundleName, bool forceFlag) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::ResetCursor(const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::ChangeAppSwitch(const std::string &accoutId, + const std::string &bundleName, + bool status) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::OptimizeStorage(const OptimizeSpaceOptions &optimizeOptions, bool isCallbackValid, + const sptr &optimizeCallback) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StopOptimizeStorage() +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::Clean(const std::string &accountId, const CleanOptions &cleanOptions) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::DisableCloud(const std::string &accoutId) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::NotifyDataChange(const std::string &accoutId, const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::NotifyEventChange( + int32_t userId, const std::string &eventId, const std::string &extraData) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StartDownloadFile(const std::string &uri) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StartFileCacheWriteParcel(MessageParcel &data, + const std::vector &pathVec, + int32_t &fieldkey, + bool isCallbackValid, + const sptr &downloadCallback, + int32_t timeout) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StartFileCache(const std::vector &uriVec, + int64_t &downloadId, int32_t fieldkey, + bool isCallbackValid, + const sptr &downloadCallback, + int32_t timeout) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StopDownloadFile(const std::string &uri, bool needClean) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StopFileCache(int64_t downloadId, bool needClean, int32_t timeout) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::DownloadThumb() +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::RegisterDownloadFileCallback(const sptr &downloadCallback) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::RegisterFileCacheCallback(const sptr &downloadCallback) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::UnregisterDownloadFileCallback() +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::UnregisterFileCacheCallback() +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::UploadAsset(const int32_t userId, const std::string &request, std::string &result) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::DownloadFile(const int32_t userId, + const std::string &bundleName, + AssetInfoObj &assetInfoObj) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::DownloadFiles(const int32_t userId, + const std::string &bundleName, + const std::vector &assetInfoObj, + std::vector &assetResultMap) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::BatchCleanFile(const std::vector &fileInfo, + std::vector &failCloudId) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::DownloadAsset(const uint64_t taskId, + const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfoObj &assetInfoObj) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::RegisterDownloadAssetCallback(const sptr &remoteObject) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::DeleteAsset(const int32_t userId, const std::string &uri) +{ + return E_OK; +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/BUILD.gn b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/BUILD.gn new file mode 100644 index 0000000..b58de40 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/BUILD.gn @@ -0,0 +1,77 @@ +# 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +config("public_config") { + include_dirs = [ "." ] +} + +config("private_config") { + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/include", + "${cloud_file_path}/utils/log/include", + ] +} + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("cloud_daemon_kit_inner") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager.cpp", + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager_impl.cpp", + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp", + "${cloud_file_path}/utils/log/src/utils_log.cpp", + ] + + defines = [ + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + configs += [ ":private_config" ] + public_configs = [ ":public_config" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_daemon_manager.h b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_daemon_manager.h new file mode 100644 index 0000000..01b6e37 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_daemon_manager.h @@ -0,0 +1,31 @@ +/* + * 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 OHOS_STORAGE_CLOUD_DAEMON_MANAGER_H +#define OHOS_STORAGE_CLOUD_DAEMON_MANAGER_H + +#include + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +class CloudDaemonManager { +public: + static CloudDaemonManager &GetInstance(); + + virtual int32_t StartFuse(int32_t userId, int32_t devFd, const string &path) = 0; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_STORAGE_CLOUD_DAEMON_MANAGER_H diff --git a/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h new file mode 100644 index 0000000..894d3d5 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/cloud_file_daemon_interface_code.h @@ -0,0 +1,26 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_FILE_DAEMON_INTERFACE_CODE_H +#define OHOS_FILEMGMT_CLOUD_FILE_DAEMON_INTERFACE_CODE_H + +/* SAID:5205 */ +namespace OHOS::FileManagement::CloudFile { +enum class CloudFileDaemonInterfaceCode { + CLOUD_DAEMON_CMD_START_FUSE = 0, +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_FILEMGMT_CLOUD_FILE_DAEMON_INTERFACE_CODE_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/i_cloud_daemon.h b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/i_cloud_daemon.h new file mode 100644 index 0000000..28a8c9a --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/i_cloud_daemon.h @@ -0,0 +1,38 @@ +/* + * 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 I_CLOUD_DAEMON_H +#define I_CLOUD_DAEMON_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +class ICloudDaemon : public IRemoteBroker { +public: + enum { + CLOUD_DAEMON_SUCCESS = 0, + CLOUD_DAEMON_DESCRIPTOR_IS_EMPTY, + }; + virtual int32_t StartFuse(int32_t userId, int32_t deviceFd, const std::string &path) = 0; + + static inline const std::string SERVICE_NAME { "ohos.filemanagement.distributedfile.clouddaemon" }; + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.filemanagement.distributedfile.clouddaemon") +}; +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS +#endif // I_CLOUD_DAEMON_H diff --git a/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/svc_death_recipient.h b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/svc_death_recipient.h new file mode 100644 index 0000000..5ecb8af --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_daemon_kit_inner/svc_death_recipient.h @@ -0,0 +1,41 @@ +/* + * 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 OHOS_STORAGE_SVC_DEATH_RECIPIENT_H +#define OHOS_STORAGE_SVC_DEATH_RECIPIENT_H + +#include + +#include "iremote_object.h" + +namespace OHOS::FileManagement::CloudFile { +class SvcDeathRecipient : public IRemoteObject::DeathRecipient { +public: + explicit SvcDeathRecipient(std::function &)> functor) : functor_(functor){}; + void OnRemoteDied(const wptr &object) override + { + if (object == nullptr) { + return; + } + object->RemoveDeathRecipient(this); + functor_(object); + } + +private: + std::function &)> functor_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_STORAGE_SVC_DEATH_RECIPIENT_H diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/BUILD.gn b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/BUILD.gn new file mode 100644 index 0000000..459149a --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/BUILD.gn @@ -0,0 +1,190 @@ +# Copyright (C) 2024 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +config("public_config") { + include_dirs = [ + ".", + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${innerkits_native_path}/cloudsync_kit_inner", + ] +} + +config("private_config") { + include_dirs = [] +} + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("cloudfile_kit") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + + big_data_statistics = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_file_fault_event.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_report_cacher.cpp", + ] + + data_sync = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync/data_syncer_rdb_store.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync/task_state_manager.cpp", + ] + + sync_rule = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/net_conn_callback_observer.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/screen_status.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/system_load.cpp", + ] + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_asset_read_session.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_assets_downloader.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_database.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_file_kit.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_sync_helper.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync_manager.cpp", + ] + + sources += big_data_statistics + sources += data_sync + sources += sync_rule + + defines = [ + "LOG_DOMAIN=0xD004311", + "LOG_TAG=\"CLOUD_FILE_KIT\"", + ] + + configs += [ ":private_config" ] + public_configs = [ ":public_config" ] + + external_deps = [ + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_single", + "json:nlohmann_json_static", + "netmanager_base:net_conn_manager_if", + "power_manager:powermgr_client", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_power) { + external_deps += [ "battery_manager:batterysrv_client" ] + + defines += [ "SUPPORT_POWER" ] + } + + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + + deps = [ "${utils_path}:libdistributedfileutils" ] + + use_exceptions = true + innerapi_tags = [ "platformsdk" ] + part_name = "cloud_file" + subsystem_name = "kernel" +} + +config("cloudfile_kit_lite_public_config") { + include_dirs = [ + ".", + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${innerkits_native_path}/cloudsync_kit_inner", + ] +} + +ohos_shared_library("cloudfile_kit_core") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + + big_data_statistics = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_file_fault_event.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_report_cacher.cpp", + ] + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_asset_read_session.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_assets_downloader.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_database.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_file_kit.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_sync_helper.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync_manager.cpp", + ] + + sources += big_data_statistics + + defines = [ + "LOG_DOMAIN=0xD004311", + "LOG_TAG=\"CLOUD_FILE_KIT\"", + ] + + public_configs = [ ":cloudfile_kit_lite_public_config" ] + + external_deps = [ + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "json:nlohmann_json_static", + ] + + deps = [ "${utils_path}:libdistributedfileutils_lite" ] + + use_exceptions = true + innerapi_tags = [ "platformsdk" ] + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/battery_status.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/battery_status.h new file mode 100644 index 0000000..007502f --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/battery_status.h @@ -0,0 +1,48 @@ +/* + * 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 OHOS_FILEMGMT_BATTERY_STATUS_H +#define OHOS_FILEMGMT_BATTERY_STATUS_H + +#include +#include + +#ifdef SUPPORT_POWER +#include "battery_info.h" +#include "battery_srv_client.h" +#endif + +namespace OHOS::FileManagement::CloudSync { +class BatteryStatus { +public: + enum CapacityLevel { + LEVEL_NORMAL, + LEVEL_LOW, + LEVEL_TOO_LOW, + }; + static bool IsAllowUpload(bool forceFlag); + static bool IsBatteryCapcityOkay(); + static CapacityLevel GetCapacityLevel(); + static void GetInitChargingStatus(); + static void SetChargingStatus(bool status); + static bool IsCharging(); + static int32_t GetCapacity(); +private: + static inline CapacityLevel level_{LEVEL_NORMAL}; + static inline std::atomic_bool isCharging_{false}; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_BATTERY_STATUS_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/cloud_file_fault_event.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/cloud_file_fault_event.h new file mode 100644 index 0000000..c9b8c08 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/cloud_file_fault_event.h @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_SYNC_SERVICE_CLOUD_FILE_FAULT_EVENT_H +#define OHOS_CLOUD_SYNC_SERVICE_CLOUD_FILE_FAULT_EVENT_H + +#include "hisysevent.h" +#include + +#define CLOUD_SYNC_FAULT_REPORT(...) \ + CloudFile::CloudFileFaultEvent::CloudSyncFaultReport(__FUNCTION__, __LINE__, ##__VA_ARGS__) +#define CLOUD_FILE_FAULT_REPORT(...) \ + CloudFile::CloudFileFaultEvent::CloudFileFaultReport(__FUNCTION__, __LINE__, ##__VA_ARGS__) +#define CLOUD_SYNC_CACHE_REPORT(...) \ + CloudFile::CloudFileFaultEvent::CloudSyncCacheReport(__FUNCTION__, __LINE__, ##__VA_ARGS__) + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { + +#ifndef CLOUD_SYNC_SYS_EVENT +#define CLOUD_SYNC_SYS_EVENT(eventName, type, ...) \ + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT, eventName, type, \ + ##__VA_ARGS__) +#endif + +#define MINIMUM_FAULT_REPORT_INTERVAL 3600 + +enum class FaultScenarioCode { + CLOUD_INIT = 000, + CLOUD_FULL_SYNC = 100, + CLOUD_INC_SYNC = 200, + CLOUD_CHECK_SYNC = 300, + CLOUD_SWITCH_CLOSE = 400, + CLOUD_LOAD_VIDEO_CACHE = 500, + CLOUD_DOWNLOAD_FILE = 600, + CLOUD_DOWNLOAD_THUM = 700, + CLOUD_OPTIMMIZE_STORAGE = 800, + CLOUD_PROCESS_EXIT_START = 900, + CLOUD_ACCOUNT_EXIT = 1000 +}; + +enum class FaultOperation { + LOOKUP = 100, + FORGET = 200, + GETATTR = 300, + OPEN = 400, + READ = 500, + READDIR = 600, + RELEASE = 700, + FORGETMULTI = 800, + IOCTL = 900, + UNLINK = 1000, + SETATTR = 1100, + SETEXTATTR = 1200, + MKNOD = 1300, + MKDIR = 1400, + GETEXTATTR = 1500, + CREATE = 1600, + WRITE = 1700, + RENAME = 1800, + RMDIR = 1900, + SESSION = 2000, + DOWNLOAD = 2100 +}; + +enum class FaultType { + /* file fault type */ + FILE = 10000000, + DENTRY_FILE = 10000001, + INODE_FILE = 10000002, + + /* driverkit fault type */ + DRIVERKIT = 20000000, + DRIVERKIT_NETWORK = 20000001, + DRIVERKIT_SERVER = 20000002, + DRIVERKIT_LOCAL = 20000003, + DRIVERKIT_DATABASE = 20000004, + DRIVERKIT_READSESSION = 20000005, + + /* timeout fault type */ + TIMEOUT = 30000000, + OPEN_CLOUD_FILE_TIMEOUT = 30000001, + CLOUD_READ_FILE_TIMEOUT = 30000002, + CLOUD_FILE_LOOKUP_TIMEOUT = 30000003, + CLOUD_FILE_FORGET_TIMEOUT = 30000004, + + /* temperature fault type */ + TEMPERATURE = 40000000, + + /* database fault type */ + DATABASE = 50000000, + QUERY_DATABASE = 50000001, + INSERT_DATABASE = 50000002, + DELETE_DATABASE = 50000003, + MODIFY_DATABASE = 50000004, + + /* consistency fault type */ + CONSISTENCY = 60000000, + FILE_CONSISTENCY = 60000001, + META_CONSISTENCY = 60000002, + + /* process fault type */ + PROCESS = 70000000, + + /* cloud sync error */ + CLOUD_SYNC_ERROR = 80000000, + + /* inner error */ + INNER_ERROR = 90000000, + + /* warning */ + WARNING = 100000000 +}; + +struct CloudSyncFaultInfo { + std::string bundleName_; + FaultScenarioCode faultScenario_; + FaultType faultType_; + int32_t faultErrorCode_; + std::string message_; +}; + +struct CloudFileFaultInfo { + std::string bundleName_; + FaultOperation faultOperation_; + FaultType faultType_; + int32_t faultErrorCode_; + std::string message_; +}; + +struct CloudCacheFaultInfo { + std::string bundleName_; + FaultType faultType_; + int32_t faultErrorCode_; + std::string message_; + bool terminate_ = false; +}; + +const std::vector PERIODIC_REPORT_FAULT_TYPE = { FaultType::WARNING, + FaultType::TIMEOUT, + FaultType::OPEN_CLOUD_FILE_TIMEOUT, + FaultType::CLOUD_READ_FILE_TIMEOUT, + FaultType::CLOUD_FILE_LOOKUP_TIMEOUT, + FaultType::CLOUD_FILE_FORGET_TIMEOUT }; + +class CloudFaultReportStatus { +public: + static CloudFaultReportStatus &GetInstance(); + + bool IsAllowToReport(const FaultType &faultType); + +private: + CloudFaultReportStatus(); + + CloudFaultReportStatus(const CloudFaultReportStatus&) = delete; + + CloudFaultReportStatus& operator=(const CloudFaultReportStatus&) = delete; + + std::mutex timeMapLock_; + std::unordered_map lastTimeMap_; +} ; + +class CloudFileFaultEvent { +public: + static int32_t CloudSyncFaultReport(const std::string &funcName, + const int lineNum, + const CloudSyncFaultInfo &event); + + static int32_t CloudFileFaultReport(const std::string &funcName, + const int lineNum, + const CloudFileFaultInfo &event); + + static int32_t CloudSyncCacheReport(const std::string &funcName, + const int lineNum, + const CloudCacheFaultInfo &event); +}; + +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS + +#endif // OHOS_CLOUD_SYNC_SERVICE_CLOUD_FILE_FAULT_EVENT_H diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/cloud_report_cacher.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/cloud_report_cacher.h new file mode 100644 index 0000000..00acec0 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/cloud_report_cacher.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_SYNC_SERVICE_CLOUD_REPORT_CACHE_H +#define OHOS_CLOUD_SYNC_SERVICE_CLOUD_REPORT_CACHE_H + +#include "safe_map.h" +#include +#include + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using namespace std; + +struct CloudFaultInfo { + string eventType_; + int64_t faultTime_; + uint32_t faultType_; + uint32_t faultErrorCode_; + string funcName_; + string message_; + bool terminate_ = false; +}; + +struct ReportInfo { + vector events_; + string traceId_; + uint32_t scenarioCode_; + int lastScheduleType_; +}; + +class CloudReportCacher { +public: + static CloudReportCacher &GetInstance(); + void Init(const string &bundleNmae, const string &traceId, const uint32_t scenarioCode); + void SetScenarioCode(const string &bundleName, const uint32_t scenarioCode); + void PushEvent(const string &bundleName, const CloudFaultInfo &event); + void Report(const string &bundleName, const int32_t scheduleType); + void ReportFaultInfo(const CloudFaultInfo &event, const string &bundleName, const uint32_t scenarioCode); +private: + CloudReportCacher(); + ~CloudReportCacher() = default; + bool GetReportInfo(const string &bundleName, shared_ptr &reportInfo); + + SafeMap> reportCache_; + mutex eventsMutex_; + mutex reportMutex_; +}; +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS + +#endif // OHOS_CLOUD_SYNC_SERVICE_CLOUD_REPORT_CACHE_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat.h new file mode 100644 index 0000000..90f260f --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_SERVICE_GALLERY_DOWNLOAD_FILE_STAT_H +#define OHOS_CLOUD_FILE_SERVICE_GALLERY_DOWNLOAD_FILE_STAT_H +#include +#include + +#include "nocopyable.h" +#include "hisysevent.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +#define GALLERY_DOWNLOAD_ERROR_STAT_LEN 10 +#define GALLERY_DOWNLOAD_IMAGE_SIZE_LEN 6 +#define GALLERY_DOWNLOAD_IMAGE_SPEED_LEN 16 +#define GALLERY_DOWNLOAD_VIDEO_SIZE_LEN 7 +#define GALLERY_DOWNLOAD_VIDEO_SPEED_LEN 16 +struct DownloadFileStatInfo { +public: + DownloadFileStatInfo() : downloadFileError(GALLERY_DOWNLOAD_ERROR_STAT_LEN), + imageSize(GALLERY_DOWNLOAD_IMAGE_SIZE_LEN), + imageDownloadSpeed(GALLERY_DOWNLOAD_IMAGE_SPEED_LEN), + videoSize(GALLERY_DOWNLOAD_VIDEO_SIZE_LEN), + videoDownloadSpeed(GALLERY_DOWNLOAD_VIDEO_SPEED_LEN) + { + } + ~DownloadFileStatInfo() = default; + + std::string bundleName; + std::vector downloadFileError; + std::vector imageSize; + std::vector imageDownloadSpeed; + std::vector videoSize; + std::vector videoDownloadSpeed; +}; + +class GalleryDownloadFileStat : public NoCopyable { +public: + static GalleryDownloadFileStat &GetInstance(); + GalleryDownloadFileStat(const GalleryDownloadFileStat&) = delete; + GalleryDownloadFileStat& operator=(const GalleryDownloadFileStat&) = delete; + + void UpdateDownloadStat(uint32_t mediaType, uint64_t size, uint64_t duration); + void OutputToFile(); + void Report(); +private: + GalleryDownloadFileStat(); + ~GalleryDownloadFileStat() = default; + void ClearDownloadFileStat(); + void UpdateDownloadSpeedStat(uint32_t mediaType, uint64_t size, uint64_t duration); + void UpdateDownloadSizeStat(uint32_t mediaType, uint64_t size, uint64_t duration); + DownloadFileStatInfo ReadVecFromLocal(); + + DownloadFileStatInfo stat_; +}; +} // CloudFile +} // FileManagement +} // OHOS +#endif // OHOS_CLOUD_FILE_SERVICE_GALLERY_DOWNLOAD_FILE_STAT_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_asset_read_session.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_asset_read_session.h new file mode 100644 index 0000000..dc6e13b --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_asset_read_session.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_ASSET_READ_SESSION_H +#define OHOS_CLOUD_FILE_CLOUD_ASSET_READ_SESSION_H + +#include +#include + +#include "cloud_info.h" + +namespace OHOS::FileManagement::CloudFile { +class CloudAssetReadSession { +public: + CloudAssetReadSession(const int32_t userId, std::string recordType, + std::string recordId, std::string assetKey, std::string assetPath); + virtual ~CloudAssetReadSession() = default; + + virtual CloudError InitSession(); + virtual int64_t PRead(int64_t offset, int64_t size, char *buffer, CloudError &error); + virtual bool Close(bool needRemain = false); + virtual bool HasCache(int64_t offset, int64_t readSize); + virtual void SentPrepareTraceId(std::string prepareTraceId); + void SetPrepareTraceId(std::string prepareTraceId); + std::string GetPrepareTraceId(); + +private: + std::string traceId_; + +protected: + int32_t userId_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_ASSET_READ_SESSION_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_assets_downloader.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_assets_downloader.h new file mode 100644 index 0000000..8d3f904 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_assets_downloader.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_ASSETS_DOWNLOADER_H +#define OHOS_CLOUD_FILE_CLOUD_ASSETS_DOWNLOADER_H + +#include +#include + +#include "cloud_info.h" + +namespace OHOS::FileManagement::CloudFile { +class CloudAssetsDownloader { +public: + CloudAssetsDownloader(const int32_t userId, const std::string &bundleName); + virtual ~CloudAssetsDownloader() = default; + virtual int32_t DownloadAssets(DownloadAssetInfo &assetsToDownload); + virtual int32_t DownloadAssets(const std::vector &assetsToDownload, + std::vector &assetResultMap); + +protected: + int32_t userId_; + std::string bundleName_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_ASSETS_DOWNLOADER_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_database.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_database.h new file mode 100644 index 0000000..3bd0b38 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_database.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_DATABASE_H +#define OHOS_CLOUD_FILE_CLOUD_DATABASE_H + +#include +#include +#include + +#include "cloud_asset_read_session.h" +namespace OHOS::FileManagement::CloudFile { +class CloudDatabase { +public: + CloudDatabase(const int32_t userId, const std::string &bundleName); + virtual ~CloudDatabase() = default; + virtual std::shared_ptr NewAssetReadSession(const int32_t userId, + std::string recordType, + std::string recordId, + std::string assetKey, + std::string assetPath); + virtual int32_t Init(); + virtual int32_t GenerateIds(int count, std::vector &ids); + +protected: + int32_t userId_; + std::string bundleName_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_DATABASE_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_file_kit.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_file_kit.h new file mode 100644 index 0000000..50b959e --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_file_kit.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_FILE_KIT_H +#define OHOS_CLOUD_FILE_CLOUD_FILE_KIT_H + +#include + +#include "cloud_assets_downloader.h" +#include "cloud_database.h" +#include "cloud_info.h" +#include "cloud_sync_helper.h" +#include "data_sync_manager.h" +#include "visibility.h" + + +namespace OHOS::FileManagement::CloudFile { +class API_EXPORT CloudFileKit { +public: + API_EXPORT static CloudFileKit *GetInstance(); + API_EXPORT static bool RegisterCloudInstance(CloudFileKit *instance); + + virtual ~CloudFileKit() = default; + virtual int32_t GetCloudUserInfo(const int32_t userId, CloudUserInfo &userInfo); + virtual std::pair GetSpaceInfo(const int32_t userId, const std::string &bundleName); + virtual int32_t GetAppSwitchStatus(const std::string &bundleName, const int32_t userId, bool &switchStatus); + virtual int32_t ResolveNotificationEvent(const int32_t userId, + const std::string &extraData, + std::string &appBundleName, + std::string &prepareTraceId); + virtual int32_t GetAppConfigParams(const int32_t userId, + const std::string &bundleName, + std::map ¶m); + virtual int32_t CleanCloudUserInfo(const int32_t userId); + virtual int32_t OnUploadAsset(const int32_t userId, const std::string &request, std::string &result); + + virtual std::shared_ptr GetDataSyncManager(); + virtual std::shared_ptr GetCloudDatabase(const int32_t userId, const std::string &bundleName); + virtual std::shared_ptr GetCloudAssetsDownloader(const int32_t userId, + const std::string &bundleName); + virtual std::shared_ptr GetCloudSyncHelper(const int32_t userId, const std::string &bundleName); + virtual std::string GetPrepareTraceId(const int32_t userId); + virtual void Release(int32_t userId); + +private: + static inline CloudFileKit *instance_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_FILE_KIT_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_info.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_info.h new file mode 100644 index 0000000..c8fdd3c --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_info.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_INFO_H +#define OHOS_CLOUD_FILE_CLOUD_INFO_H + +#include + +namespace OHOS::FileManagement::CloudFile { +struct CloudUserInfo { + std::string accountId; + bool enableCloud{false}; + uint64_t totalSpace{0}; + uint64_t remainSpace{0}; +}; + +struct Asset { + std::string uri; + std::string assetName; +}; + +struct DownloadAssetInfo { + std::string recordType; + std::string recordId; + std::string fieldKey; + Asset asset; + std::string downLoadPath; +}; + +enum class CloudError : int32_t { + CK_NO_ERROR, + CK_NETWORK_ERROR, + CK_SERVER_ERROR, + CK_LOCAL_ERROR, + CK_UNKNOWN_ERROR, +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_INFO_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_status.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_status.h new file mode 100644 index 0000000..3c631f9 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_status.h @@ -0,0 +1,42 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_STATUS_H +#define OHOS_FILEMGMT_CLOUD_STATUS_H + +#include +#include +#include + +#include "cloud_info.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudStatus { +public: + static int32_t GetCurrentCloudInfo(const std::string &bundleName, const int32_t userId); + static std::pair GetCurrentSpaceInfo(const int32_t userId, const std::string &bundleName); + static bool IsCloudStatusOkay(const std::string &bundleName, const int32_t userId); + static int32_t ChangeAppSwitch(const std::string &bundleName, const int32_t userId, bool appSwitchStatus); + static bool IsAccountIdChanged(const std::string &accountId); + +private: + static inline CloudFile::CloudUserInfo userInfo_; + static inline std::map appSwitches_; + static inline int32_t userId_{-1}; + static inline std::mutex mutex_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_STATUS_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_sync_helper.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_sync_helper.h new file mode 100644 index 0000000..2b7eb79 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/cloud_sync_helper.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_SYNC_HELPER_H +#define OHOS_CLOUD_FILE_CLOUD_SYNC_HELPER_H + +#include + +namespace OHOS::FileManagement::CloudFile { +class CloudSyncHelper { +public: + CloudSyncHelper(const int32_t useId, const std::string &bundleName); + virtual ~CloudSyncHelper() = default; + + virtual int32_t Init(); + virtual int32_t SaveSubScription(); + +protected: + int32_t userId_; + std::string bundleName_; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_CLOUD_SYNC_HELPER_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_const.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_const.h new file mode 100644 index 0000000..8e6726e --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_const.h @@ -0,0 +1,106 @@ +/* + * 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 OHOS_CLOUD_SYNC_SERVICE_DATA_SYNC_CONST_H +#define OHOS_CLOUD_SYNC_SERVICE_DATA_SYNC_CONST_H + +#include +#include +namespace OHOS::FileManagement::CloudSync { + +enum CleanAction { + RETAIN_DATA = 0, + CLEAR_DATA +}; + +enum AlbumSource { + ALBUM_FROM_LOCAL = 1, + ALBUM_FROM_CLOUD = 2 +}; + +enum class SyncTriggerType : int32_t { + APP_TRIGGER, + CLOUD_TRIGGER, + PENDING_TRIGGER, + BATTERY_OK_TRIGGER, + NETWORK_AVAIL_TRIGGER, + TASK_TRIGGER, + SYSTEM_LOAD_TRIGGER, +}; + +enum class ThumbState : int32_t { + DOWNLOADED, + LCD_TO_DOWNLOAD, + THM_TO_DOWNLOAD, + TO_DOWNLOAD, +}; + +struct LocalInfo { + std::string parentCloudId; + std::string fileName; + int64_t mdirtyTime; + int64_t fdirtyTime; + int64_t recycledTime; + int64_t rowId; + int32_t thm_flag; + int32_t lcd_flag; +}; + +struct BundleNameUserInfo { + std::string bundleName; + int32_t userId; + int32_t pid; +}; + +const int32_t POSITION_LOCAL = 1; +const int32_t POSITION_CLOUD = 2; +const int32_t POSITION_BOTH = 3; + +const int32_t DOWNLOADED_THM = 0; +const int32_t TO_DOWNLOAD_THM = 1; +const int32_t NO_THM_TO_DOWNLOAD = 2; +const int32_t THM_DENTRY_INSERTED = 3; + +const int32_t FILE = 0; +const int32_t DIRECTORY = 1; + +const int32_t MILLISECOND_TO_SECOND = 1000; +const int32_t SECOND_TO_MILLISECOND = 1000; +const int64_t MILLISECOND_TO_NANOSECOND = 1e6; + +const int32_t NOT_IN_TRASH = 0; +const int32_t NOT_IN_PENDING = 0; +const int32_t NOT_HIDDEN = 0; +const int32_t NOT_TEMP_FILE = 0; +const int32_t IS_BURST_COVER = 1; + +const std::string GALLERY_BUNDLE_NAME = "com.ohos.photos"; +const std::string MEDIALIBRARY_BUNDLE_NAME = "com.ohos.medialibrary.medialibrarydata"; + +static const std::string CLOUDSYNC_STATUS_KEY = "persist.kernel.cloudsync.status"; +static const std::string CLOUDSYNC_STATUS_LOGOUT = "0"; +static const std::string CLOUDSYNC_STATUS_START = "1"; +static const std::string CLOUDSYNC_STATUS_INC_SYNC = "2"; +static const std::string CLOUDSYNC_STATUS_FULL_SYNC = "3"; +static const std::string CLOUDSYNC_STATUS_FINISH = "4"; +static const std::string CLOUDSYNC_STATUS_SWITCHOFF = "5"; + +static inline uint64_t GetCurrentTimeStamp() +{ + struct timespec t; + clock_gettime(CLOCK_REALTIME, &t); + return t.tv_sec * MILLISECOND_TO_NANOSECOND + t.tv_nsec / SECOND_TO_MILLISECOND; +} +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_CLOUD_SYNC_SERVICE_DATA_SYNC_CONST_H diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_manager.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_manager.h new file mode 100644 index 0000000..d4ecda9 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_manager.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_DATA_SYNC_MANAGER_H +#define OHOS_CLOUD_FILE_DATA_SYNC_MANAGER_H + +#include +#include + +#include "data_sync_const.h" +#include "i_cloud_download_callback.h" +#include "i_cloud_optimize_callback.h" +#include "i_cloud_sync_callback.h" + +namespace OHOS::FileManagement::CloudFile { +class DataSyncManager { +public: + using BundleNameUserInfo = CloudSync::BundleNameUserInfo; + using SyncTriggerType = CloudSync::SyncTriggerType; + DataSyncManager() = default; + virtual ~DataSyncManager() = default; + + virtual int32_t TriggerStartSync(const std::string &bundleName, + const int32_t userId, + bool forceFlag, + SyncTriggerType triggerType, + std::string prepareTraceId = ""); + virtual int32_t TriggerStopSync(const std::string &bundleName, const int32_t userId, + bool forceFlag, SyncTriggerType triggerType); + virtual int32_t TriggerRecoverySync(SyncTriggerType triggerType); + virtual int32_t StopUploadTask(const std::string &bundleName, const int32_t userId); + virtual int32_t ResetCursor(const std::string &bundleName, const int32_t &userId); + virtual void RegisterCloudSyncCallback(const std::string &bundleName, + const std::string &callerBundleName, + const int32_t userId, + const sptr &callback); + virtual void UnRegisterCloudSyncCallback(const std::string &bundleName, const std::string &callerBundleName); + virtual int32_t IsSkipSync(const std::string &bundleName, const int32_t userId, bool forceFlag); + virtual int32_t StartDownloadFile(const BundleNameUserInfo &bundleNameUserInfo, + const std::vector &pathVec, + int64_t &downloadId, + int32_t fieldkey, + const sptr &downloadCallback, + int32_t timeout = -1); + virtual int32_t StopDownloadFile(const BundleNameUserInfo &bundleNameUserInfo, + const std::string &path, + bool needClean = false); + virtual int32_t StopFileCache(const BundleNameUserInfo &bundleNameUserInfo, + int64_t downloadId, + bool needClean, + int32_t timeout = -1); + virtual int32_t RegisterDownloadFileCallback(const BundleNameUserInfo &bundleNameUserInfo, + const sptr &downloadCallback); + virtual int32_t UnregisterDownloadFileCallback(const BundleNameUserInfo &bundleNameUserInfo); + virtual int32_t CleanCloudFile(const int32_t userId, const std::string &bundleName, const int action); + virtual int32_t CleanRemainFile(const std::string &bundleName, const int32_t userId); + virtual int32_t OptimizeStorage(const std::string &bundleName, const int32_t userId, const int32_t agingDays); + virtual int32_t StartOptimizeStorage(const BundleNameUserInfo &bundleNameUserInfo, + const CloudSync::OptimizeSpaceOptions &optimizeOptions, + const sptr &optimizeCallback); + virtual int32_t StopOptimizeStorage(const BundleNameUserInfo &bundleNameUserInfo); + virtual int32_t OptimizeCache(const int32_t userId, const std::string &bundleName); + virtual int32_t BatchCleanFile(const std::vector &fileInfo, + std::vector &failCloudId); + virtual int32_t DownloadThumb(); + virtual int32_t TriggerDownloadThumb(); + virtual int32_t CacheVideo(); + virtual int32_t CleanVideoCache(); + virtual int32_t CleanCache(const std::string &bundleName, const int32_t userId, const std::string &uri); + virtual int32_t BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId); + virtual int32_t DisableCloud(const int32_t userId); + virtual int32_t GetUserId(int32_t &userId); + virtual int32_t SaveSubscription(const std::string &bundleName, const int32_t userId); + virtual int32_t ReportEntry(const std::string &bundleName, const int32_t userId); + virtual int32_t ChangeAppSwitch(const std::string &bundleName, const int32_t userId, bool status); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_CLOUD_FILE_DATA_SYNC_MANAGER_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_syncer_rdb_col.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_syncer_rdb_col.h new file mode 100644 index 0000000..a6e61da --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_syncer_rdb_col.h @@ -0,0 +1,64 @@ +/* + * 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 OHOS_CLOUD_SYNC_DATA_SYNCER_RDB_COL_H +#define OHOS_CLOUD_SYNC_DATA_SYNCER_RDB_COL_H + +#include +#include + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +/* basic */ +const std::string DATA_SYNCER_ID = "dataSyncerId"; +const std::string USER_ID = "userId"; +const std::string BUNDLE_NAME = "bundleName"; +const std::string SYNC_STATE = "syncState"; +const std::string LAST_SYNC_TIME = "lastSyncTime"; +const std::string DATA_SYNCER_UNIQUE_ID = "dataSyncerUniqueId"; + +const std::string DATA_SYNCER_TABLE = "DataSyncers"; + +const std::string DATA_SYNCER_UNIQUE_INDEX = "DataSyncersUniqueIndex"; + +const std::string CREATE_DATA_SYNCER_TABLE = "CREATE TABLE IF NOT EXISTS " + + DATA_SYNCER_TABLE + " (" + + DATA_SYNCER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + USER_ID + " INT, " + + BUNDLE_NAME + " TEXT, " + + SYNC_STATE + " INT DEFAULT 0, " + + LAST_SYNC_TIME + " BIGINT DEFAULT 0, " + + DATA_SYNCER_UNIQUE_ID + " TEXT)"; + +const std::string CREATE_DATA_SYNCER_UNIQUE_INDEX = + "CREATE UNIQUE INDEX IF NOT EXISTS " + DATA_SYNCER_UNIQUE_INDEX + + " ON " + DATA_SYNCER_TABLE + " (" + DATA_SYNCER_UNIQUE_ID + ")"; + +const std::set DATA_SYNCER_COL = { + DATA_SYNCER_ID, USER_ID, BUNDLE_NAME, SYNC_STATE, LAST_SYNC_TIME, DATA_SYNCER_UNIQUE_ID +}; + +const std::string EL1_CLOUDFILE_DIR = "/data/service/el1/public/cloudfile"; +const std::string DATA_SYNCER_DB = "DataSyncers.db"; + +const int32_t CLOUD_DISK_RDB_VERSION = 2; +enum { + VERSION_ADD_DATA_SYNCER_UNIQUE_INDEX = 2, +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_DATA_SYNCER_RDB_COL_H diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_syncer_rdb_store.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_syncer_rdb_store.h new file mode 100644 index 0000000..65d00f6 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/data_syncer_rdb_store.h @@ -0,0 +1,54 @@ +/* + * 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 OHOS_FILEMGMT_DATA_SYNCER_RDB_STORE_H +#define OHOS_FILEMGMT_DATA_SYNCER_RDB_STORE_H + +#include "rdb_open_callback.h" +#include "rdb_store.h" +#include "sync_state_manager.h" + +namespace OHOS::FileManagement::CloudSync { +class DataSyncerRdbStore { +public: + static DataSyncerRdbStore &GetInstance(); + ~DataSyncerRdbStore() = default; + + int32_t Insert(int32_t userId, const std::string &bundleName); + int32_t UpdateSyncState(int32_t userId, const std::string &bundleName, SyncState syncState); + int32_t GetLastSyncTime(int32_t userId, const std::string &bundleName, int64_t &time); + int32_t QueryDataSyncer(int32_t userId, std::shared_ptr &resultSet); + int32_t QueryCloudSync(int32_t userId, + const std::string &bundleName, + std::shared_ptr &resultSet); +private: + int32_t Query(NativeRdb::AbsRdbPredicates predicates, std::shared_ptr &resultSet); + int32_t RdbInit(); + DataSyncerRdbStore() + { + RdbInit(); + } + std::shared_ptr rdb_; + std::mutex rdbMutex_; +}; + +class DataSyncerRdbCallBack : public NativeRdb::RdbOpenCallback { +public: + int32_t OnCreate(NativeRdb::RdbStore &rdbStore) override; + int32_t OnUpgrade(NativeRdb::RdbStore &rdbStore, int32_t oldVersion, int32_t newVersion) override; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DATA_SYNCER_RDB_STORE_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/net_conn_callback_observer.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/net_conn_callback_observer.h new file mode 100644 index 0000000..9dc0083 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/net_conn_callback_observer.h @@ -0,0 +1,47 @@ +/* +* 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 OHOS_FILEMGMT_CLOUD_SYNC_NET_CONN_CALLBACK_OBSERVER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_NET_CONN_CALLBACK_OBSERVER_H + +#include "net_all_capabilities.h" +#include "net_conn_callback_stub.h" +#include "data_sync_manager.h" + +namespace OHOS::FileManagement::CloudSync { +class NetConnCallbackObserver : public NetManagerStandard::NetConnCallbackStub { +public: + NetConnCallbackObserver(std::shared_ptr dataSyncManager); + int32_t NetAvailable(sptr &netHandle) override; + + int32_t NetCapabilitiesChange(sptr &netHandle, + const sptr &netAllCap) override; + + int32_t NetConnectionPropertiesChange(sptr &netHandle, + const sptr &info) override; + + int32_t NetLost(sptr &netHandle) override; + + int32_t NetUnavailable() override; + + int32_t NetBlockStatusChange(sptr &netHandle, bool blocked) override; + +private: + std::shared_ptr dataSyncManager_; + SyncTriggerType triggerType_{SyncTriggerType::NETWORK_AVAIL_TRIGGER}; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_NET_CONN_CALLBACK_OBSERVER_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/network_set_manager.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/network_set_manager.h new file mode 100644 index 0000000..54270bd --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/network_set_manager.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2024 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 OHOS_FILEMGMT_CLOUD_SYNC_DATA_SHARE_H +#define OHOS_FILEMGMT_CLOUD_SYNC_DATA_SHARE_H + +#include +#include +#include +#include + +#include "datashare_helper.h" +#include "data_ability_observer_stub.h" +#include "data_sync_manager.h" +#include "safe_map.h" + +namespace OHOS::FileManagement::CloudSync { +class MobileNetworkObserver : public AAFwk::DataAbilityObserverStub { +public: + MobileNetworkObserver(const std::string &bundleName, const int32_t userId, const int32_t type) + : bundleName_(bundleName), userId_(userId), type_(type) {} + ~MobileNetworkObserver() {} + void OnChange() override; + using ObserverCallback = std::function; +private: + std::string bundleName_; + int32_t userId_ = -1; + int32_t type_ = -1; + ObserverCallback observerCallback_ = nullptr; +}; + +class NetworkSetManager { +public: + enum PhotoType { + CELLULARCONNECT, + NETCONNECT, + }; + enum NetConnStatus { + NO_NETWORK, + ETHERNET_CONNECT, + WIFI_CONNECT, + CELLULAR_CONNECT, + NETWORK_AVAIL, + }; + static void InitNetworkSetManager(const std::string &bundleName, const int32_t userId); + static int32_t QueryCellularConnect(int32_t userId, const std::string &bundleName); + static int32_t QueryNetConnect(int32_t userId, const std::string &bundleName); + static void RegisterObserver(const std::string &bundleName, const int32_t userId, const int32_t type); + static void UnregisterObserver(const std::string &bundleName, const int32_t userId, const int32_t type); + static void GetCellularConnect(const std::string &bundleName, const int32_t userId); + static void GetNetConnect(const std::string &bundleName, const int32_t userId); + static void ReleaseDataShareHelper(std::shared_ptr &helper); + static bool IsAllowCellularConnect(const std::string &bundleName, const int32_t userId); + static bool IsAllowNetConnect(const std::string &bundleName, const int32_t userId); + static bool GetConfigParams(const std::string &bundleName, const int32_t userId); + static void InitDataSyncManager(std::shared_ptr dataSyncManager); + static void NetWorkChangeStopUploadTask(); + static void SetNetConnStatus(NetConnStatus netStatus); + static inline SafeMap cellularNetMap_; + static inline SafeMap netMap_; +private: + static inline std::shared_ptr dataSyncManager_; + static inline NetConnStatus netStatus_{NO_NETWORK}; +}; +} // OHOS + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_DATA_SHARE_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/network_status.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/network_status.h new file mode 100644 index 0000000..684eb03 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/network_status.h @@ -0,0 +1,50 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_SYNC_NETWORK_STATUS_H +#define OHOS_FILEMGMT_CLOUD_SYNC_NETWORK_STATUS_H +#include +#include "iremote_object.h" +#include "net_all_capabilities.h" +#include "data_sync_manager.h" + +namespace OHOS::FileManagement::CloudSync { +class NetworkStatus { +public: + enum NetConnStatus { + NO_NETWORK, + ETHERNET_CONNECT, + WIFI_CONNECT, + CELLULAR_CONNECT, + NETWORK_AVAIL, + }; + static int32_t RegisterNetConnCallback(std::shared_ptr dataSyncManager); + static int32_t GetDefaultNet(); + static int32_t GetAndRegisterNetwork(std::shared_ptr dataSyncManager); + static void InitNetwork(std::shared_ptr dataSyncManager); + static void SetNetConnStatus(NetManagerStandard::NetAllCapabilities &netAllCap); + static void SetNetConnStatus(NetConnStatus netStatus); + static NetConnStatus GetNetConnStatus(); + static void OnNetworkAvail(); + static bool CheckMobileNetwork(const std::string &bundleName, const int32_t userId); + static bool CheckNetwork(const std::string &bundleName, const int32_t userId); + static void NetWorkChangeStopUploadTask(); + +private: + static inline NetConnStatus netStatus_{NO_NETWORK}; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_NETWORK_STATUS_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/screen_status.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/screen_status.h new file mode 100644 index 0000000..1cb3225 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/screen_status.h @@ -0,0 +1,41 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_SYNC_SCREEN_STATUS_H +#define OHOS_FILEMGMT_CLOUD_SYNC_SCREEN_STATUS_H + +#include "common_event_subscriber.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +class ScreenStatus { +public: + enum ScreenState { + SCREEN_ON, + SCREEN_OFF, + }; + static bool IsScreenOn(); + static void InitScreenStatus(); + static void SetScreenState(ScreenState screenState); + +private: + static inline ScreenState screenState_{ScreenState::SCREEN_ON}; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_SCREEN_STATUS_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/sync_state_manager.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/sync_state_manager.h new file mode 100644 index 0000000..bf4ea5d --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/sync_state_manager.h @@ -0,0 +1,72 @@ +/* + * 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 OHOS_FILEMGMT_SYNC_STATE_MANAGER_H +#define OHOS_FILEMGMT_SYNC_STATE_MANAGER_H + +#include +#include +#include + +#include "data_sync_const.h" +namespace OHOS::FileManagement::CloudSync { +enum class SyncState : int32_t { + INIT = 0, + SYNCING, + SYNC_FAILED, + SYNC_SUCCEED, +}; + +enum class SignalPos: int32_t { + CLEANING = 0, + DISABLE_CLOUD, + END, +}; + +enum class Action : int32_t { + STOP = 0, + START, + FORCE_START, + CHECK, +}; + +class SyncStateManager { +public: + Action UpdateSyncState(SyncState newState); + bool CheckAndSetPending(bool forceFlag, SyncTriggerType triggerType); + void SetCleaningFlag(); + Action ClearCleaningFlag(); + bool CheckCleaningFlag(); + bool GetStopSyncFlag(); + void SetStopSyncFlag(); + void SetDisableCloudFlag(); + Action ClearDisableCloudFlag(); + bool CheckDisableCloudFlag(); + SyncState GetSyncState() const; + bool GetForceFlag() const; + +private: + mutable std::shared_mutex syncMutex_; + SyncState state_{SyncState::INIT}; + Action nextAction_{Action::STOP}; + //pos0: is_cleaning, pos1: is_disable_cloud + std::bitset(SignalPos::END)> syncSignal; + std::atomic_bool isForceSync_{false}; + std::atomic_bool stopSyncFlag_{false}; +}; + +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_SYNC_STATE_MANAGER_H diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/system_load.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/system_load.h new file mode 100644 index 0000000..45fbb4a --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/system_load.h @@ -0,0 +1,61 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_SYNC_SYSTEM_LOAD_H +#define OHOS_FILEMGMT_CLOUD_SYNC_SYSTEM_LOAD_H + +#include "data_sync_manager.h" +#include +#include "res_sched_systemload_notifier_client.h" +#include "res_type.h" +#include "sync_state_manager.h" + +namespace OHOS::FileManagement::CloudSync { +constexpr int32_t SYSTEMLOADLEVEL_HOT = ResourceSchedule::ResType::SystemloadLevel::HIGH; +constexpr int32_t SYSTEMLOADLEVEL_WARM = ResourceSchedule::ResType::SystemloadLevel::MEDIUM; +constexpr int32_t SYSTEMLOADLEVEL_NORMAL = ResourceSchedule::ResType::SystemloadLevel::NORMAL; +const std::string TEMPERATURE_SYSPARAM_SYNC = "persist.kernel.cloudsync.temperature_abnormal_sync"; +const std::string TEMPERATURE_SYSPARAM_THUMB = "persist.kernel.cloudsync.temperature_abnormal_thumb"; + +enum STOPPED_TYPE { + STOPPED_IN_SYNC = 0, + STOPPED_IN_THUMB = 1, + STOPPED_IN_OTHER = 2, +}; + +class SystemLoadStatus { +public: + SystemLoadStatus() = default; + virtual ~SystemLoadStatus() = default; + static void RegisterSystemloadCallback(std::shared_ptr dataSyncManager); + static void GetSystemloadLevel(); + static bool IsLoadStatusUnderHot(STOPPED_TYPE process = STOPPED_IN_OTHER, int32_t level = SYSTEMLOADLEVEL_HOT); + static bool IsLoadStatusUnderNormal(STOPPED_TYPE process); + static void InitSystemload(std::shared_ptr dataSyncManager); + static void Setload(int32_t load); + static inline int32_t loadstatus_ = 0; +}; + +class SystemLoadListener : public ResourceSchedule::ResSchedSystemloadNotifierClient { +public: + SystemLoadListener() = default; + void OnSystemloadLevel(int32_t level) override; + void SetDataSycner(std::shared_ptr dataSyncManager); +private: + std::shared_ptr dataSyncManager_ = nullptr; +}; +} // OHOS + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_SYSTEM_LOAD_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/task_state_manager.h b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/task_state_manager.h new file mode 100644 index 0000000..db648ce --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloud_file_kit_inner/task_state_manager.h @@ -0,0 +1,57 @@ +/* + * 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 OHOS_FILEMGMT_TASK_STATE_MANAGER_H +#define OHOS_FILEMGMT_TASK_STATE_MANAGER_H + +#include +#include "ffrt_inner.h" + +namespace OHOS::FileManagement::CloudSync { +static const std::string CLOUD_FILE_SERVICE_SA_STATUS_FLAG = "persist.kernel.medialibrarydata.stopflag"; +static const std::string CLOUD_FILE_SERVICE_SA_START = "0"; +static const std::string CLOUD_FILE_SERVICE_SA_END = "1"; +enum class TaskType : uint64_t { + SYNC_TASK = 1, + DOWNLOAD_TASK = 1 << 1, + CLEAN_TASK = 1 << 2, + UPLOAD_ASSET_TASK = 1 << 3, + DOWNLOAD_ASSET_TASK = 1 << 4, + DOWNLOAD_REMOTE_ASSET_TASK = 1 << 5, + DOWNLOAD_THUMB_TASK = 1 << 6, + DISABLE_CLOUD_TASK = 1 << 7, + CACHE_VIDEO_TASK = 1 << 8, +}; +class TaskStateManager : public NoCopyable { +public: + static TaskStateManager &GetInstance(); + ~TaskStateManager() = default; + void StartTask(std::string bundleName, TaskType task); + void CompleteTask(std::string bundleName, TaskType task); + bool HasTask(std::string bundleName, TaskType task); + void StartTask(); +private: + TaskStateManager(); + void DelayUnloadTask(); + void CancelUnloadTask(); + + std::mutex taskMapsMutex_; + std::unordered_map taskMaps_; + ffrt::queue queue_; + ffrt::task_handle unloadTaskHandle_; + ffrt::mutex unloadTaskMutex_; +}; +} +#endif // OHOS_FILEMGMT_TASK_STATE_MANAGER_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/BUILD.gn b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/BUILD.gn new file mode 100644 index 0000000..a4c584b --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/BUILD.gn @@ -0,0 +1,200 @@ +# Copyright (C) 2022 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +config("public_config") { + include_dirs = [ "." ] +} + +config("private_config") { + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/utils/log/include", + ] +} + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("cloudsync_kit_inner") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_stub.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_stub.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_stub.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp", + "${cloud_file_path}/utils/log/src/utils_log.cpp", + ] + + defines = [ + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUDSYNC_API\"", + ] + + configs += [ ":private_config" ] + public_configs = [ + ":public_config", + "${services_path}/cloudsyncservice:cloud_sync_service_public_config", + ] + + external_deps = [ + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloud_sync_service_proxy", + "${utils_path}:libdistributedfiledentry", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_shared_library("cloudsync_asset_kit_inner") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager_impl.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp", + ] + + defines = [ + "LOG_DOMAIN=0xD004309", + "LOG_TAG=\"CLOUD_ASSET_API\"", + ] + + configs += [ ":private_config" ] + public_configs = [ + ":public_config", + "${services_path}/cloudsyncservice:cloud_sync_service_public_config", + ] + + external_deps = [ + "ability_base:zuri", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloud_sync_service_proxy", + "${utils_path}:libdistributedfileutils_lite", + ] + + use_exceptions = true + innerapi_tags = [ "platformsdk" ] + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_shared_library("cloudsync_kit_inner_lite") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + cfi_vcall_icall_only = true + } + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp", + ] + + defines = [ + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CloudFileDaemon\"", + ] + + configs += [ ":private_config" ] + public_configs = [ + ":public_config", + "${services_path}/cloudsyncservice:cloud_sync_service_public_config", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloud_sync_service_proxy", + "${utils_path}:libdistributedfileutils_lite", + ] + + use_exceptions = true + innerapi_tags = [ "platformsdk" ] + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_download_callback.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_download_callback.h new file mode 100644 index 0000000..9e4179c --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_download_callback.h @@ -0,0 +1,32 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_H +#define OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_H + +#include + +#include "cloud_sync_common.h" + +namespace OHOS::FileManagement::CloudSync { + +class CloudDownloadCallback { +public: + virtual ~CloudDownloadCallback() = default; + virtual void OnDownloadProcess(const DownloadProgressObj& progress) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_DOWNLOAD_CALLBACK_H diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h new file mode 100644 index 0000000..2fd5611 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_file_sync_service_interface_code.h @@ -0,0 +1,62 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_FILE_SYNC_SERVICE_INTERFACE_CODE_H +#define OHOS_FILEMGMT_CLOUD_FILE_SYNC_SERVICE_INTERFACE_CODE_H + +/* SAID:5204 */ +namespace OHOS::FileManagement::CloudSync { +enum class CloudFileSyncServiceInterfaceCode { + SERVICE_CMD_UNREGISTER_CALLBACK, + SERVICE_CMD_UNREGISTER_FILE_SYNC_CALLBACK, + SERVICE_CMD_REGISTER_CALLBACK, + SERVICE_CMD_REGISTER_FILE_SYNC_CALLBACK, + SERVICE_CMD_START_SYNC, + SERVICE_CMD_START_FILE_SYNC, + SERVICE_CMD_TRIGGER_SYNC, + SERVICE_CMD_STOP_SYNC, + SERVICE_CMD_STOP_FILE_SYNC, + SERVICE_CMD_CHANGE_APP_SWITCH, + SERVICE_CMD_NOTIFY_DATA_CHANGE, + SERVICE_CMD_NOTIFY_EVENT_CHANGE, + SERVICE_CMD_ENABLE_CLOUD, + SERVICE_CMD_DISABLE_CLOUD, + SERVICE_CMD_CLEAN, + SERVICE_CMD_START_DOWNLOAD_FILE, + SERVICE_CMD_STOP_DOWNLOAD_FILE, + SERVICE_CMD_REGISTER_DOWNLOAD_FILE_CALLBACK, + SERVICE_CMD_REGISTER_FILE_CACHE_CALLBACK, + SERVICE_CMD_UNREGISTER_DOWNLOAD_FILE_CALLBACK, + SERVICE_CMD_UNREGISTER_FILE_CACHE_CALLBACK, + SERVICE_CMD_UPLOAD_ASSET, + SERVICE_CMD_DOWNLOAD_FILE, + SERVICE_CMD_DOWNLOAD_FILES, + SERVICE_CMD_DELETE_ASSET, + SERVICE_CMD_GET_SYNC_TIME, + SERVICE_CMD_CLEAN_CACHE, + SERVICE_CMD_START_FILE_CACHE, + SERVICE_CMD_DOWNLOAD_ASSET, + SERVICE_CMD_REGISTER_DOWNLOAD_ASSET_CALLBACK, + SERVICE_CMD_RESET_CURSOR, + SERVICE_CMD_STOP_FILE_CACHE, + SERVICE_CMD_DOWNLOAD_THUMB, + SERVICE_CMD_BATCH_CLEAN_FILE, + SERVICE_CMD_DENTRY_FILE_INSERT, + SERVICE_CMD_OPTIMIZE_STORAGE, + SERVICE_CMD_STOP_OPTIMIZE_STORAGE +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_FILE_SYNC_SERVICE_INTERFACE_CODE_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_optimize_callback.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_optimize_callback.h new file mode 100644 index 0000000..2cd1235 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_optimize_callback.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 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 OHOS_FILEMGMT_CLOUD_OPTIMIZE_CALLBACK_H +#define OHOS_FILEMGMT_CLOUD_OPTIMIZE_CALLBACK_H + +#include +#include "cloud_sync_constants.h" + +namespace OHOS::FileManagement::CloudSync { + +class CloudOptimizeCallback { +public: + virtual ~CloudOptimizeCallback() = default; + virtual void OnOptimizeProcess(const OptimizeState state, const int32_t progress) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_OPTIMIZE_CALLBACK_H diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_asset_manager.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_asset_manager.h new file mode 100644 index 0000000..f4c6477 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_asset_manager.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2022 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 OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_H + +#include +#include + +namespace OHOS::FileManagement::CloudSync { +struct AssetInfo { + std::string uri; + std::string recordType; + std::string recordId; + std::string fieldKey; + std::string assetName; +}; + +class CloudSyncAssetManager { +public: + using ResultCallback = std::function; + static CloudSyncAssetManager &GetInstance(); + /** + * @brief 接口触发文件上传 + * + * @param userId 用户Id + * @param request 请求 + * @param result 结果 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t UploadAsset(const int32_t userId, const std::string &request, std::string &result) = 0; + /** + * @brief 接口触发文件下载 + * + * @param userId 用户Id + * @param bundleName 应用包名 + * @param assetInfo 下载文件信息 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfo &assetInfo) = 0; + /** + * @brief 接口触发文件下载 + * + * @param userId 用户Id + * @param bundleName 应用包名 + * @param assetInfo 下载文件信息 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t DownloadFile(const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfo &assetInfo, + ResultCallback resultCallback) = 0; + /** + * @brief 接口触发批量文件下载 + * + * @param userId 用户Id + * @param bundleName 应用包名 + * @param assetInfo 下载批量文件信息 + * @param assetResultMap 同步返回执行结果 + * @return int32_t 同步返回执行总结果 + */ + virtual int32_t DownloadFiles(const int32_t userId, + const std::string &bundleName, + const std::vector &assetInfo, + std::vector &assetResultMap) = 0; + /** + * @brief 接口触发附件删除 + * + * @param userId 用户Id + * @param uri 用户uri + * @return int32_t 同步返回执行结果 + */ + virtual int32_t DeleteAsset(const int32_t userId, const std::string &uri) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_ASSET_MANAGER_H diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_callback.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_callback.h new file mode 100644 index 0000000..10cc38e --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_callback.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 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 OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_H +#define OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_H + +#include + +#include "cloud_sync_constants.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncCallback { +public: + virtual ~CloudSyncCallback() = default; + /** + * @brief 同步状态变更通知回调 + * + * @param type 0:upload 1:download 2:all + * @param state 同步状态 + * SYNC_STATE_DEFAULT 同步完成 + * SYNC_STATE_SYNCING 同步中 + * SYNC_STATE_FAILED 同步失败 + * SYNC_STATE_PAUSED_NO_NETWORK 未连接网络 + * SYNC_STATE_PAUSED_FOR_WIFI 未连接wifi + * SYNC_STATE_PAUSED_FOR_BATTERY 低电量 + * SYNC_STATE_BATTERY_TOO_LOW 电量过低 + * SYNC_STATE_PAUSED_FOR_SPACE_TOO_LOW 云空间满 + */ + virtual void OnSyncStateChanged(SyncType type, SyncPromptState state) {}; + /** + * @brief 同步状态变更通知回调 + * + * @param state 同步状态类型 + * UPLOADING 正在上传 + * UPLOAD_FAILED 同步上传失败 + * DOWNLOADING 正在下载 + * DOWNLOAD_FAILED 同步下载失败 + * COMPLETED 同步完成 + * STOPPED 同步停止 + * @param error 同步错误类型 + * NO_ERROR 无错误 + * NETWORK_UNAVAILABLE 网络不可用 + * WIFI_UNAVAILABLE wifi不可用 + * BATTERY_LEVEL_LOW 低电量 + * BATTERY_LEVEL_WARNING 电量警告 + * CLOUD_STORAGE_FULL 云空间满 + * LOCAL_STORAGE_FULL 本地空间满 + * DEVICE_TEMPERATURE_TOO_HIGH 设备温度过高 + * BUSINESS_MODE_CHANGED 商业模式变更 + */ + virtual void OnSyncStateChanged(CloudSyncState state, ErrorType error) {}; + /** + * @brief 死亡回调通知同步状态逻辑 + * + */ + virtual void OnDeathRecipient() {}; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_CALLBACK_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h new file mode 100644 index 0000000..6c25d65 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h @@ -0,0 +1,182 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_SYNC_COMMON_H +#define OHOS_FILEMGMT_CLOUD_SYNC_COMMON_H + +#include +#include + +#include "parcel.h" +#include "cloud_sync_asset_manager.h" + +namespace OHOS::FileManagement::CloudSync { +#define FIELD_KEY_MAX_SIZE 4 +constexpr int32_t CLEAN_FILE_MAX_SIZE = 200; +enum FieldKey { + FIELDKEY_CONTENT = 1 << 0, + FIELDKEY_THUMB = 1 << 1, + FIELDKEY_LCD = 1 << 2, +}; + +struct DownloadProgressObj : public Parcelable { + enum Status : int32_t { + RUNNING = 0, + COMPLETED = 1, + FAILED = 2, + STOPPED = 3, + }; + enum DownloadErrorType : int32_t { + NO_ERROR = 0, + UNKNOWN_ERROR = 1, + NETWORK_UNAVAILABLE = 2, + LOCAL_STORAGE_FULL = 3, + CONTENT_NOT_FOUND = 4, + FREQUENT_USER_REQUESTS = 5, + }; + uint32_t refCount; + std::string path; + int64_t downloadId; + Status state; + int32_t downloadErrorType; + int64_t downloadedSize; + int64_t totalSize; + + // member for batch download(same downloadId) + int64_t batchDownloadSize; + int64_t batchTotalSize; + int64_t batchSuccNum; + int64_t batchFailNum; + int64_t batchTotalNum; + Status batchState; + + bool ReadBatchFromParcel(Parcel &parcel); + bool ReadFromParcel(Parcel &parcel); + bool MarshallingBatch(Parcel &parcel) const; + bool Marshalling(Parcel &parcel) const override; + static DownloadProgressObj *Unmarshalling(Parcel &parcel); + std::string to_string(); +}; + +struct SwitchDataObj : public Parcelable { + std::map switchData; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static SwitchDataObj *Unmarshalling(Parcel &parcel); +}; + +struct CleanOptions : public Parcelable { + std::map appActionsData; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static CleanOptions *Unmarshalling(Parcel &parcel); +}; + +struct OptimizeSpaceOptions : public Parcelable { + int64_t totalSize; + int32_t agingDays; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static OptimizeSpaceOptions *Unmarshalling(Parcel &parcel); +}; + + +struct DentryFileInfo { + std::string cloudId; + int64_t size; + int64_t modifiedTime; + std::string path; + std::string fileName; + std::string fileType; +}; + +struct DentryFileInfoObj : public Parcelable { + std::string cloudId; + int64_t size; + int64_t modifiedTime; + std::string path; + std::string fileName; + std::string fileType; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static DentryFileInfoObj *Unmarshalling(Parcel &parcel); + + DentryFileInfoObj() = default; + DentryFileInfoObj(const DentryFileInfo &FileInfo) + : cloudId(FileInfo.cloudId), + size(FileInfo.size), + modifiedTime(FileInfo.modifiedTime), + path(FileInfo.path), + fileName(FileInfo.fileName), + fileType(FileInfo.fileType) + { + } +}; + +struct AssetInfoObj : public Parcelable { + std::string uri; + std::string recordType; + std::string recordId; + std::string fieldKey; + std::string assetName; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static AssetInfoObj *Unmarshalling(Parcel &parcel); + + AssetInfoObj() = default; + AssetInfoObj(const AssetInfo &assetInfo) + : uri(assetInfo.uri), + recordType(assetInfo.recordType), + recordId(assetInfo.recordId), + fieldKey(assetInfo.fieldKey), + assetName(assetInfo.assetName) + { + } +}; + +struct CleanFileInfo { + std::string cloudId; + int64_t size; + int64_t modifiedTime; + std::string path; + std::string fileName; + std::vector attachment; +}; + +struct CleanFileInfoObj : public Parcelable { + std::string cloudId; + int64_t size; + int64_t modifiedTime; + std::string path; + std::string fileName; + std::vector attachment; + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static CleanFileInfoObj *Unmarshalling(Parcel &parcel); + + CleanFileInfoObj() = default; + CleanFileInfoObj(const CleanFileInfo &FileInfo) + : cloudId(FileInfo.cloudId), + size(FileInfo.size), + modifiedTime(FileInfo.modifiedTime), + path(FileInfo.path), + fileName(FileInfo.fileName), + attachment(FileInfo.attachment) + { + } +}; + +} // namespace OHOS::FileManagement::CloudSync +#endif diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_constants.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_constants.h new file mode 100644 index 0000000..e281810 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_constants.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2024 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 OHOS_FILEMGMT_CLOUD_SYNC_CONSTANTS_H +#define OHOS_FILEMGMT_CLOUD_SYNC_CONSTANTS_H + +#include + +namespace OHOS::FileManagement::CloudSync { +enum class SyncType : int32_t { + UPLOAD = 0, + DOWNLOAD, + ALL, +}; + +enum class SyncPromptState : int32_t { + SYNC_STATE_DEFAULT = 0, + SYNC_STATE_SYNCING, + SYNC_STATE_FAILED, + SYNC_STATE_PAUSED_NO_NETWORK, + SYNC_STATE_PAUSED_FOR_WIFI, + SYNC_STATE_PAUSED_FOR_BATTERY, + SYNC_STATE_BATTERY_TOO_LOW, + SYNC_STATE_PAUSED_FOR_SPACE_TOO_LOW, +}; + +enum CloudSyncState { + UPLOADING = 0, + UPLOAD_FAILED, + DOWNLOADING, + DOWNLOAD_FAILED, + COMPLETED, + STOPPED, +}; + +enum OptimizeState { + OPTIMIZE_RUNNING = 0, + OPTIMIZE_COMPLETED = 1, + OPTIMIZE_FAILED = 2, + OPTIMIZE_STOPPED = 3, +}; + +enum ErrorType { + NO_ERROR = 0, + NETWORK_UNAVAILABLE, + WIFI_UNAVAILABLE, + BATTERY_LEVEL_LOW, + BATTERY_LEVEL_WARNING, + CLOUD_STORAGE_FULL, + LOCAL_STORAGE_FULL, + DEVICE_TEMPERATURE_TOO_HIGH, + BUSINESS_MODE_CHANGED, + PERMISSION_NOT_ALLOW, +}; + +enum State { + CLOUD_FILE_DOWNLOAD_RUNNING = 0, + CLOUD_FILE_DOWNLOAD_COMPLETED, + CLOUD_FILE_DOWNLOAD_FAILED, + CLOUD_FILE_DOWNLOAD_STOPPED, +}; + +enum FileSyncState { + FILESYNCSTATE_UPLOADING = 0, + FILESYNCSTATE_DOWNLOADING, + FILESYNCSTATE_COMPLETED, + FILESYNCSTATE_STOPPED, + FILESYNCSTATE_TO_BE_UPLOADED, + FILESYNCSTATE_UPLOAD_SUCCESS, + FILESYNCSTATE_UPLOAD_FAILURE, +}; + +enum FileSync { + FILESYNC_TO_BE_UPLOADED = 0, + FILESYNC_UPLOADING, + FILESYNC_UPLOAD_FAILURE, + FILESYNC_UPLOAD_SUCCESS, +}; + +static inline std::unordered_map statusMap { + {FileSync::FILESYNC_TO_BE_UPLOADED, FileSyncState::FILESYNCSTATE_TO_BE_UPLOADED}, + {FileSync::FILESYNC_UPLOADING, FileSyncState::FILESYNCSTATE_UPLOADING}, + {FileSync::FILESYNC_UPLOAD_SUCCESS, FileSyncState::FILESYNCSTATE_UPLOAD_SUCCESS}, + {FileSync::FILESYNC_UPLOAD_FAILURE, FileSyncState::FILESYNCSTATE_UPLOAD_FAILURE}, +}; + +enum NotifyType { + NOTIFY_ADDED = 0, + NOTIFY_MODIFIED, + NOTIFY_DELETED, + NOTIFY_RENAMED, + NOTIFY_NONE, +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_CONSTANTS_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_manager.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_manager.h new file mode 100644 index 0000000..893f2ab --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_manager.h @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2022 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 OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_H + +#include + +#include "cloud_download_callback.h" +#include "cloud_optimize_callback.h" +#include "cloud_sync_callback.h" +#include "cloud_sync_common.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncManager { +public: + static CloudSyncManager &GetInstance(); + /** + * @brief 注册 + * + * @param callback 注册同步回调 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t RegisterCallback(const std::shared_ptr callback, + const std::string &bundleName = "") = 0; + virtual int32_t RegisterFileSyncCallback(const std::shared_ptr callback, + const std::string &bundleName = "") = 0; + /** + * @brief 注册 + * + * @param callback 卸载同步回调 + * @return int32_t 返回执行结果 + */ + virtual int32_t UnRegisterCallback(const std::string &bundleName = "") = 0; + virtual int32_t UnRegisterFileSyncCallback(const std::string &bundleName = "") = 0; + /** + * @brief 启动同步 + * + * @return int32_t 同步返回执行结果 + */ + virtual int32_t StartSync(const std::string &bundleName = "") = 0; + virtual int32_t StartFileSync(const std::string &bundleName = "") = 0; + /** + * @brief 启动同步 + * + * @param forceFlag 是否强制继续同步,当前仅支持低电量下暂停后继续上传 + * @param callback 注册同步回调 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t StartSync(bool forceFlag, const std::shared_ptr callback) = 0; + /** + * @brief 触发同步 + * + * @param bundleName 应用包名 + * @param userId 用户ID + * @return int32_t 同步返回执行结果 + */ + virtual int32_t TriggerSync(const std::string &bundleName, const int32_t &userId) = 0; + /** + * @brief 停止同步 + * + * @return int32_t 同步返回执行结果 + */ + virtual int32_t StopSync(const std::string &bundleName = "", bool forceFlag = false) = 0; + virtual int32_t StopFileSync(const std::string &bundleName = "", bool forceFlag = false) = 0; + /** + * @brief 清理水位 + * + * @return int32_t 同步返回执行结果 + */ + virtual int32_t ResetCursor(const std::string &bundleName = "") = 0; + /** + * @brief 切换应用云同步开关 + * + * @param accoutId 账号ID + * @param bundleName 应用包名 + * @param status 应用开关状态 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) = 0; + /** + * @brief 云数据变化触发同步 + * + * @param accoutId 账号ID + * @param bundleName 应用包名 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t NotifyDataChange(const std::string &accoutId, const std::string &bundleName) = 0; + virtual int32_t NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) = 0; + virtual int32_t EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) = 0; + virtual int32_t DisableCloud(const std::string &accoutId) = 0; + /** + * @brief 云账号退出选择保留或清除云数据 + * + * @param accoutId 账号ID + * @param cleanOptions 说明云文件如何处理的方式 + * @return int32_t 同步返回执行结果 + */ + virtual int32_t Clean(const std::string &accountId, const CleanOptions &cleanOptions) = 0; + virtual int32_t OptimizeStorage(const OptimizeSpaceOptions &optimizeOptions, + const std::shared_ptr optimizeCallback = nullptr) = 0; + virtual int32_t StopOptimizeStorage() = 0; + virtual int32_t StartDownloadFile(const std::string &path) = 0; + virtual int32_t StartFileCache(const std::string &path) = 0; + virtual int32_t StartFileCache(const std::vector &pathVec, int64_t &downloadId, + int32_t fieldkey = FIELDKEY_CONTENT, + const std::shared_ptr downloadCallback = nullptr, + int32_t timeout = -1) = 0; + virtual int32_t StopDownloadFile(const std::string &path, bool needClean = false) = 0; + virtual int32_t StopFileCache(int64_t downloadId, bool needClean = false, int32_t timeout = -1) = 0; + virtual int32_t DownloadThumb() = 0; + virtual int32_t RegisterDownloadFileCallback(const std::shared_ptr downloadCallback) = 0; + virtual int32_t RegisterFileCacheCallback(const std::shared_ptr downloadCallback) = 0; + virtual int32_t UnregisterDownloadFileCallback() = 0; + virtual int32_t UnregisterFileCacheCallback() = 0; + virtual int32_t GetSyncTime(int64_t &syncTime, const std::string &bundleName = "") = 0; + virtual int32_t CleanCache(const std::string &uri) = 0; + virtual void CleanGalleryDentryFile() = 0; + virtual int32_t BatchCleanFile(const std::vector &fileInfo, + std::vector &failCloudId) = 0; + virtual int32_t BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_H diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/download_asset_callback.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/download_asset_callback.h new file mode 100644 index 0000000..9833088 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/download_asset_callback.h @@ -0,0 +1,28 @@ +/* + * 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 OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_H +#define OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_H + +namespace OHOS::FileManagement::CloudSync { +class DownloadAssetCallback { +public: + using TaskId = uint64_t; + virtual ~DownloadAssetCallback() = default; + virtual void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_download_callback.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_download_callback.h new file mode 100644 index 0000000..c439270 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_download_callback.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 OHOS_FILEMGMT_I_CLOUD_DOWNLOAD_CALLBACK_H +#define OHOS_FILEMGMT_I_CLOUD_DOWNLOAD_CALLBACK_H + +#include "iremote_broker.h" + +#include "cloud_download_callback.h" + +namespace OHOS::FileManagement::CloudSync { +class ICloudDownloadCallback : public CloudDownloadCallback, public IRemoteBroker { +public: + enum { + SERVICE_CMD_ON_PROCESS = 0, + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Dfs.ICloudDownloadCallback") +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_CLOUD_DOWNLOAD_CALLBACK_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_optimize_callback.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_optimize_callback.h new file mode 100644 index 0000000..e00c8f7 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_optimize_callback.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 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 OHOS_FILEMGMT_I_CLOUD_OPTOMIZE_CALLBACK_H +#define OHOS_FILEMGMT_I_CLOUD_OPTOMIZE_CALLBACK_H + +#include "iremote_broker.h" + +#include "cloud_optimize_callback.h" + +namespace OHOS::FileManagement::CloudSync { +class ICloudOptimizeCallback : public CloudOptimizeCallback, public IRemoteBroker { +public: + enum { + SERVICE_CMD_ON_PROCESS = 0, + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Dfs.ICloudOptimizeCallback") +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_CLOUD_OPTOMIZE_CALLBACK_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_callback.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_callback.h new file mode 100644 index 0000000..27078e3 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_cloud_sync_callback.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 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 OHOS_FILEMGMT_I_CLOUD_SYNC_CALLBACK_H +#define OHOS_FILEMGMT_I_CLOUD_SYNC_CALLBACK_H + +#include "iremote_broker.h" + +#include "cloud_sync_callback.h" + +namespace OHOS::FileManagement::CloudSync { +class ICloudSyncCallback : public CloudSyncCallback, public IRemoteBroker { +public: + enum { + SERVICE_CMD_ON_SYNC_STATE_CHANGED = 0, + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Dfs.ICloudSyncCallback") +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_CLOUD_SYNC_CALLBACK_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_download_asset_callback.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_download_asset_callback.h new file mode 100644 index 0000000..a61c5f4 --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/i_download_asset_callback.h @@ -0,0 +1,33 @@ +/* + * 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 OHOS_FILEMGMT_I_DOWNLOAD_ASSET_CALLBACK_H +#define OHOS_FILEMGMT_I_DOWNLOAD_ASSET_CALLBACK_H + +#include "iremote_broker.h" +#include "download_asset_callback.h" + +namespace OHOS::FileManagement::CloudSync { +class IDownloadAssetCallback : public DownloadAssetCallback, public IRemoteBroker { +public: + enum { + SERVICE_CMD_ON_DOWNLOAD_FINSHED = 0, + }; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Dfs.IDownloadAssetCallback") +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_DOWNLOAD_ASSET_CALLBACK_H \ No newline at end of file diff --git a/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/svc_death_recipient.h b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/svc_death_recipient.h new file mode 100644 index 0000000..d70ce7f --- /dev/null +++ b/cloud_file/interfaces/inner_api/native/cloudsync_kit_inner/svc_death_recipient.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 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 OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_H +#define OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_H + +#include + +#include "iremote_object.h" + +namespace OHOS::FileManagement::CloudSync { +class SvcDeathRecipient : public IRemoteObject::DeathRecipient { +public: + explicit SvcDeathRecipient(std::function &)> functor) : functor_(functor){}; + void OnRemoteDied(const wptr &object) override + { + if (object == nullptr) { + return; + } + object->RemoveDeathRecipient(this); + functor_(object); + } + +private: + std::function &)> functor_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_SVC_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/BUILD.gn b/cloud_file/interfaces/kits/js/cloudfilesync/BUILD.gn new file mode 100644 index 0000000..fe3585a --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/BUILD.gn @@ -0,0 +1,74 @@ +# Copyright (c) 2024 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("cloudsync") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "cloud_file_cache_napi.cpp", + "cloud_file_download_napi.cpp", + "cloud_file_napi.cpp", + "cloud_sync_n_exporter.cpp", + "cloud_sync_napi.cpp", + "file_sync_napi.cpp", + "gallery_sync_napi.cpp", + ] + deps = [ + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "hilog:libhilog", + "ipc:ipc_single", + "napi:ace_napi", + ] + + defines = [ + "LOG_DOMAIN=0xD004309", + "LOG_TAG=\"CLOUD_FILE_SYNC\"", + ] + + relative_install_dir = "module/file" + + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp new file mode 100644 index 0000000..932caa5 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp @@ -0,0 +1,443 @@ +/* + * 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 "cloud_file_cache_napi.h" + +#include +#include + +#include "async_work.h" +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +bool RegisterManager::HasEvent(const string &eventType) +{ + unique_lock registerMutex_; + bool hasEvent = false; + for (auto &iter : registerInfo_) { + if (iter->eventType == eventType) { + hasEvent = true; + break; + } + } + return hasEvent; +} + +bool RegisterManager::AddRegisterInfo(shared_ptr info) +{ + if (HasEvent(info->eventType)) { + return false; + } + { + unique_lock registerMutex_; + registerInfo_.insert(info); + } + return true; +} + +bool RegisterManager::RemoveRegisterInfo(const string &eventType) +{ + unique_lock registerMutex_; + bool isFound = false; + for (auto iter = registerInfo_.begin(); iter != registerInfo_.end();) { + if ((*iter)->eventType == eventType) { + isFound = true; + iter = registerInfo_.erase(iter); + } else { + iter++; + } + } + return isFound; +} + +napi_value CloudFileCacheNapi::Constructor(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + LOGE("Start Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto fileCacheEntity = make_unique(); + if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(fileCacheEntity))) { + LOGE("Failed to set file cache entity."); + NError(E_UNKNOWN_ERR).ThrowErr(env); + return nullptr; + } + return funcArg.GetThisVar(); +} + +bool CloudFileCacheNapi::ToExport(std::vector props) +{ + std::string className = GetClassName(); + auto [succ, classValue] = NClass::DefineClass(exports_.env_, className, Constructor, std::move(props)); + if (!succ) { + NError(E_UNKNOWN_ERR).ThrowErr(exports_.env_); + LOGE("Failed to define GallerySync class"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + NError(E_UNKNOWN_ERR).ThrowErr(exports_.env_); + LOGE("Failed to save GallerySync class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +napi_value CloudFileCacheNapi::CleanCloudFileCache(napi_env env, napi_callback_info info) +{ + LOGI("CleanCache start"); + NFuncArg funcArg(env, info); + + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto [succ, uri, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + LOGE("Get uri error"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + int32_t ret = CloudSyncManager::GetInstance().CleanCache(uri.get()); + if (ret != E_OK) { + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +bool CloudFileCacheNapi::Export() +{ + std::vector props = { + NVal::DeclareNapiFunction("on", CloudFileCacheNapi::On), + NVal::DeclareNapiFunction("off", CloudFileCacheNapi::Off), + NVal::DeclareNapiFunction("start", CloudFileCacheNapi::StartFileCache), + NVal::DeclareNapiFunction("startBatch", CloudFileCacheNapi::StartBatchFileCache), + NVal::DeclareNapiFunction("stop", CloudFileCacheNapi::StopFileCache), + NVal::DeclareNapiFunction("stopBatch", CloudFileCacheNapi::StopBatchFileCache), + NVal::DeclareNapiFunction("cleanCache", CloudFileCacheNapi::CleanCloudFileCache), + }; + + return ToExport(props); +} + +napi_value CloudFileCacheNapi::StartFileCache(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Start Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succUri, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succUri) { + LOGE("Start get uri parameter failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto cbExec = [uri = string(uri.get())]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StartFileCache(uri); + if (ret != E_OK) { + LOGE("Start Download failed! ret = %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + LOGI("Start Download Success!"); + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + string procedureName = "cloudFileCache"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} + +napi_value CloudFileCacheNapi::StopFileCache(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { + LOGE("Stop Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succ, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + LOGE("Stop get uri parameter failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + bool needClean = false; + size_t maxArgSize = static_cast(NARG_CNT::TWO); + if (funcArg.GetArgc() >= NARG_CNT::TWO) { + NVal option(env, funcArg[NARG_POS::SECOND]); + if (!option.TypeIs(napi_function)) { + tie(succ, needClean) = option.ToBool(); + if (!succ) { + LOGE("Failed to get clean flag!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + maxArgSize = static_cast(NARG_CNT::THREE); + } + } + auto cbExec = [uri = string(uri.get()), env = env, needClean]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StopDownloadFile(uri, needClean); + if (ret != E_OK) { + LOGE("Stop Download failed! ret = %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + string procedureName = "cloudFileCache"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, maxArgSize); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} + +struct FileCacheArg { + vector uriList; + int64_t downloadId; +}; + +napi_value CloudFileCacheNapi::StartBatchFileCache(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Start Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto fileUris = std::make_shared(); + auto [resGetUris, uriArray, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToStringArray(); + if (!resGetUris) { + LOGE("Start get uri array parameter failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + fileUris->uriList = uriArray; + auto cbExec = [fileUris]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StartFileCache(fileUris->uriList, fileUris->downloadId); + if (ret != E_OK) { + LOGE("Batch start file cache failed! ret = %{public}d", ret); + ret = (ret == E_CLOUD_SDK) ? E_UNKNOWN_ERR : ret; + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [fileUris](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateInt64(env, fileUris->downloadId); + }; + + string procedureName = "cloudFileCache"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} + +napi_value CloudFileCacheNapi::StopBatchFileCache(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { + LOGE("Start Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto [succ, downloadId] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt64(); + if (!succ || downloadId <= 0) { + LOGE("Start get download ID parameter failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + bool needClean = false; + size_t maxArgSize = static_cast(NARG_CNT::TWO); + if (funcArg.GetArgc() >= NARG_CNT::TWO) { + NVal option(env, funcArg[NARG_POS::SECOND]); + if (!option.TypeIs(napi_function)) { + tie(succ, needClean) = option.ToBool(); + if (!succ) { + LOGE("Failed to get clean flag!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + maxArgSize = static_cast(NARG_CNT::THREE); + } + } + + auto cbExec = [downloadId = downloadId, needClean]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StopFileCache(downloadId, needClean); + if (ret != E_OK) { + LOGE("Batch stop file cache failed! ret = %{public}d", ret); + ret = (ret == E_CLOUD_SDK) ? E_UNKNOWN_ERR : ret; + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + string procedureName = "cloudFileCache"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, maxArgSize); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} + +napi_value CloudFileCacheNapi::On(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { + LOGE("Batch-On Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succProgress, progress, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + string eventType(progress.get()); + if (!succProgress || (eventType != PROGRESS && eventType != MULTI_PROGRESS)) { + LOGE("Batch-On get progress failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (!NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Batch-On argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto fileCacheEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!fileCacheEntity) { + LOGE("Failed to get file cache entity."); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto arg = make_shared(); + arg->eventType = eventType; + if (eventType == PROGRESS) { + arg->callback = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); + } else { + arg->callback = + make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_, true); + } + + if (!fileCacheEntity->registerMgr.AddRegisterInfo(arg)) { + LOGE("Batch-On register callback fail, callback already exist"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + int32_t ret = CloudSyncManager::GetInstance().RegisterFileCacheCallback(arg->callback); + if (ret != E_OK) { + LOGE("Failed to register callback, error: %{public}d", ret); + (void)fileCacheEntity->registerMgr.RemoveRegisterInfo(eventType); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudFileCacheNapi::Off(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Off Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succProgress, progress, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + string eventType(progress.get()); + if (!succProgress || (eventType != PROGRESS && eventType != MULTI_PROGRESS)) { + LOGE("Batch-Off get progress failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (funcArg.GetArgc() == (uint)NARG_CNT::TWO && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Batch-Off argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto fileCacheEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!fileCacheEntity) { + LOGE("Failed to get file cache entity."); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (!fileCacheEntity->registerMgr.HasEvent(eventType)) { + LOGE("Batch-Off no callback is registered for this event type: %{public}s.", eventType.c_str()); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + int32_t ret = CloudSyncManager::GetInstance().UnregisterFileCacheCallback(); + if (ret != E_OK) { + LOGE("Failed to unregister callback, error: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + + if (!fileCacheEntity->registerMgr.RemoveRegisterInfo(eventType)) { + LOGE("Batch-Off no callback is registered for this event type: %{public}s.", eventType.c_str()); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +string CloudFileCacheNapi::GetClassName() +{ + return className_; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h new file mode 100644 index 0000000..06661dc --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.h @@ -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. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_FILE_CACHE_NAPI_H +#define OHOS_FILEMGMT_CLOUD_FILE_CACHE_NAPI_H + +#include +#include +#include "cloud_file_napi.h" + +namespace OHOS::FileManagement::CloudSync { +const std::string PROGRESS = "progress"; +const std::string MULTI_PROGRESS = "multiProgress"; +class CloudFileCacheNapi final : public LibN::NExporter { +public: + CloudFileCacheNapi(napi_env env, napi_value exports) : NExporter(env, exports) {} + ~CloudFileCacheNapi() = default; + + bool Export() override; + bool ToExport(std::vector props); + std::string GetClassName() override; + static napi_value Constructor(napi_env env, napi_callback_info info); + static napi_value StartFileCache(napi_env env, napi_callback_info info); + static napi_value StartBatchFileCache(napi_env env, napi_callback_info info); + static napi_value StopFileCache(napi_env env, napi_callback_info info); + static napi_value StopBatchFileCache(napi_env env, napi_callback_info info); + static napi_value On(napi_env env, napi_callback_info info); + static napi_value Off(napi_env env, napi_callback_info info); + static napi_value CleanCloudFileCache(napi_env env, napi_callback_info info); + +private: + inline static std::string className_ = "CloudFileCache"; +}; +struct RegisterInfoArg { + std::string eventType; + std::shared_ptr callback; + ~RegisterInfoArg() + { + if (callback != nullptr) { + callback->DeleteReference(); + callback = nullptr; + } + } +}; + +class RegisterManager { +public: + RegisterManager() = default; + ~RegisterManager() = default; + bool AddRegisterInfo(std::shared_ptr info); + bool RemoveRegisterInfo(const std::string &eventType); + bool HasEvent(const std::string &eventType); + +private: + std::mutex registerMutex_; + std::unordered_set> registerInfo_; +}; + +struct FileCacheEntity { + RegisterManager registerMgr; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.cpp new file mode 100644 index 0000000..be31b23 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.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 "cloud_file_download_napi.h" + +#include + +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "async_work.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +bool CloudFileDownloadNapi::Export() +{ + SetClassName("Download"); + bool success = CloudFileNapi::Export(); + if (!success) { + return false; + } + return true; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h new file mode 100644 index 0000000..ea22a00 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_download_napi.h @@ -0,0 +1,30 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H +#define OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H + +#include "cloud_file_napi.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudFileDownloadNapi final : public CloudFileNapi { +public: + CloudFileDownloadNapi(napi_env env, napi_value exports) : CloudFileNapi(env, exports) {} + ~CloudFileDownloadNapi() = default; + + bool Export() override; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp new file mode 100644 index 0000000..fd69882 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_napi.cpp @@ -0,0 +1,343 @@ +/* + * 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 "cloud_file_download_napi.h" + +#include + +#include "async_work.h" +#include "cloud_file_napi.h" +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; +const int32_t ARGS_ONE = 1; + +napi_value CloudFileNapi::Constructor(napi_env env, napi_callback_info info) +{ + LOGI("CloudFileNapi::Constructor begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + LOGE("Start Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + isDownloadCallbackRegistered_ = false; + LOGI("CloudFileNapi::Constructor end"); + return funcArg.GetThisVar(); +} + +napi_value CloudFileNapi::Start(napi_env env, napi_callback_info info) +{ + LOGI("Start begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Start Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succUri, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succUri) { + LOGE("Start get uri parameter failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto cbExec = [uri = string(uri.get()), env = env]() -> NError { + lock_guard lock(mtx_); + if (callback_ != nullptr && !isDownloadCallbackRegistered_) { + int32_t ret = CloudSyncManager::GetInstance().RegisterDownloadFileCallback(callback_); + if (ret != E_OK) { + LOGE("RegisterDownloadFileCallback error, ret: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + isDownloadCallbackRegistered_ = true; + } + + int32_t ret = CloudSyncManager::GetInstance().StartDownloadFile(uri); + if (ret != E_OK) { + LOGE("Start Download failed! ret = %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + LOGI("Start Download Success!"); + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + string procedureName = "cloudFileDownload"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} + +CloudDownloadCallbackImpl::CloudDownloadCallbackImpl(napi_env env, napi_value fun, bool isBatch) : env_(env) +{ + if (fun != nullptr) { + napi_create_reference(env_, fun, 1, &cbOnRef_); + } + isBatch_ = isBatch; +} + +void CloudDownloadCallbackImpl::OnComplete(UvChangeMsg *msg) +{ + auto downloadcCallback = msg->CloudDownloadCallback_.lock(); + if (downloadcCallback == nullptr || downloadcCallback->cbOnRef_ == nullptr) { + LOGE("downloadcCallback->cbOnRef_ is nullptr"); + return; + } + auto env = downloadcCallback->env_; + auto ref = downloadcCallback->cbOnRef_; + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env, &scope); + napi_value jsCallback = nullptr; + napi_status status = napi_get_reference_value(env, ref, &jsCallback); + if (status != napi_ok) { + LOGE("Create reference failed, status: %{public}d", status); + napi_close_handle_scope(env, scope); + return; + } + NVal obj = NVal::CreateObject(env); + if (!msg->isBatch_) { + obj.AddProp("state", NVal::CreateInt32(env, (int32_t)msg->downloadProgress_.state).val_); + obj.AddProp("processed", NVal::CreateInt64(env, msg->downloadProgress_.downloadedSize).val_); + obj.AddProp("size", NVal::CreateInt64(env, msg->downloadProgress_.totalSize).val_); + obj.AddProp("uri", NVal::CreateUTF8String(env, msg->downloadProgress_.path).val_); + } else { + LOGI("Batch download callback items"); + obj.AddProp("state", NVal::CreateInt32(env, (int32_t)msg->downloadProgress_.batchState).val_); + obj.AddProp("downloadedSize", NVal::CreateInt64(env, msg->downloadProgress_.batchDownloadSize).val_); + obj.AddProp("totalSize", NVal::CreateInt64(env, msg->downloadProgress_.batchTotalSize).val_); + obj.AddProp("successfulNum", NVal::CreateInt64(env, msg->downloadProgress_.batchSuccNum).val_); + obj.AddProp("failedNum", NVal::CreateInt64(env, msg->downloadProgress_.batchFailNum).val_); + obj.AddProp("totalNum", NVal::CreateInt64(env, msg->downloadProgress_.batchTotalNum).val_); + } + obj.AddProp("taskId", NVal::CreateInt64(env, msg->downloadProgress_.downloadId).val_); + obj.AddProp("error", NVal::CreateInt32(env, (int32_t)msg->downloadProgress_.downloadErrorType).val_); + + LOGI("OnComplete callback start for taskId: %{public}lld", + static_cast(msg->downloadProgress_.downloadId)); + napi_value retVal = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + status = napi_call_function(env, global, jsCallback, ARGS_ONE, &(obj.val_), &retVal); + if (status != napi_ok) { + LOGE("napi call function failed, status: %{public}d", status); + } + napi_close_handle_scope(env, scope); +} + +void CloudDownloadCallbackImpl::OnDownloadProcess(const DownloadProgressObj &progress) +{ + UvChangeMsg *msg = new (std::nothrow) UvChangeMsg(shared_from_this(), progress, isBatch_); + if (msg == nullptr) { + LOGE("Failed to create uv message object"); + return; + } + auto task = [msg]() { + if (msg->CloudDownloadCallback_.expired()) { + LOGE("CloudDownloadCallback_ is expired"); + delete msg; + return; + } + msg->CloudDownloadCallback_.lock()->OnComplete(msg); + delete msg; + }; + napi_status ret = napi_send_event(env_, task, napi_event_priority::napi_eprio_immediate); + if (ret != napi_ok) { + LOGE("Failed to execute libuv work queue, ret: %{public}d", ret); + delete msg; + return; + } +} + +void CloudDownloadCallbackImpl::DeleteReference() +{ + if (cbOnRef_ != nullptr) { + napi_delete_reference(env_, cbOnRef_); + cbOnRef_ = nullptr; + return; + } +} + +napi_value CloudFileNapi::On(napi_env env, napi_callback_info info) +{ + LOGI("On begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { + LOGE("On Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succProgress, progress, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succProgress || std::string(progress.get()) != "progress") { + LOGE("On get progress failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (!NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (callback_ != nullptr) { + LOGI("callback already exist"); + return NVal::CreateUndefined(env).val_; + } + + callback_ = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); + + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudFileNapi::Off(napi_env env, napi_callback_info info) +{ + LOGI("Off begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Off Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succProgress, progress, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succProgress || std::string(progress.get()) != "progress") { + LOGE("Off get progress failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + if (funcArg.GetArgc() == (uint)NARG_CNT::TWO && !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + /* callback_ may be nullptr */ + int32_t ret = CloudSyncManager::GetInstance().UnregisterDownloadFileCallback(); + if (ret != E_OK) { + LOGE("UnregisterDownloadFileCallback error, ret: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + if (callback_ != nullptr) { + /* napi delete reference */ + callback_->DeleteReference(); + callback_ = nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudFileNapi::Stop(napi_env env, napi_callback_info info) +{ + LOGI("Stop begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) { + LOGE("Stop Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succUri, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String(); + if (!succUri) { + LOGE("Stop get uri parameter failed!"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + bool needClean = false; + size_t maxArgSize = static_cast(NARG_CNT::TWO); + if (funcArg.GetArgc() >= NARG_CNT::TWO) { + NVal ui(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); + if (ui.TypeIs(napi_boolean)) { + bool needCleanIgnore; + std::tie(needCleanIgnore, needClean) = NVal(env, funcArg[NARG_POS::SECOND]).ToBool(); + maxArgSize = static_cast(NARG_CNT::THREE); + } + } + if (funcArg.GetArgc() == NARG_CNT::THREE) { + maxArgSize = static_cast(NARG_CNT::THREE); + } + auto cbExec = [uri = string(uri.get()), env = env, needClean]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StopDownloadFile(uri, needClean); + if (ret != E_OK) { + LOGE("Stop Download failed! ret = %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + LOGI("Stop Download Success!"); + return NError(ERRNO_NOERR); + }; + + auto cbCompl = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + string procedureName = "cloudFileDownload"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, maxArgSize); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbCompl).val_; +} + +bool CloudFileNapi::ToExport(std::vector props) +{ + std::string className = GetClassName(); + auto [succ, classValue] = + NClass::DefineClass(exports_.env_, className, Constructor, std::move(props)); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to define GallerySync class"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to save GallerySync class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +bool CloudFileNapi::Export() +{ + vector props = { + NVal::DeclareNapiFunction("start", CloudFileNapi::Start), + NVal::DeclareNapiFunction("on", CloudFileNapi::On), + NVal::DeclareNapiFunction("off", CloudFileNapi::Off), + NVal::DeclareNapiFunction("stop", CloudFileNapi::Stop), + }; + return ToExport(props); +} + +void CloudFileNapi::SetClassName(std::string classname) +{ + className_ = classname; +} + +string CloudFileNapi::GetClassName() +{ + return className_; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_napi.h b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_napi.h new file mode 100644 index 0000000..3eb1e22 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_file_napi.h @@ -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. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_FILE_NAPI_H +#define OHOS_FILEMGMT_CLOUD_FILE_NAPI_H + +#include "cloud_download_callback.h" +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudDownloadCallbackImpl; +class CloudFileNapi : public LibN::NExporter { +public: + CloudFileNapi(napi_env env, napi_value exports) : NExporter(env, exports) {} + ~CloudFileNapi() = default; + + bool Export() override; + bool ToExport(std::vector props); + virtual void SetClassName(std::string classname); + std::string GetClassName() override; + static napi_value Constructor(napi_env env, napi_callback_info info); + static napi_value Start(napi_env env, napi_callback_info info); + static napi_value On(napi_env env, napi_callback_info info); + static napi_value Off(napi_env env, napi_callback_info info); + static napi_value Stop(napi_env env, napi_callback_info info); + +private: + inline static std::mutex mtx_; + inline static bool isDownloadCallbackRegistered_; + static inline std::shared_ptr callback_; + inline static std::string className_ = "CloudFileNapi"; +}; + +class CloudDownloadCallbackImpl : public CloudDownloadCallback, + public std::enable_shared_from_this { +public: + CloudDownloadCallbackImpl(napi_env env, napi_value fun, bool isBatch = false); + ~CloudDownloadCallbackImpl() = default; + void OnDownloadProcess(const DownloadProgressObj &progress) override; + void DeleteReference(); + + class UvChangeMsg { + public: + UvChangeMsg(std::shared_ptr CloudDownloadCallbackIn, + DownloadProgressObj downloadProgress, + bool isBatch) + : CloudDownloadCallback_(CloudDownloadCallbackIn), downloadProgress_(downloadProgress), isBatch_(isBatch) + { + } + ~UvChangeMsg() {} + std::weak_ptr CloudDownloadCallback_; + DownloadProgressObj downloadProgress_; + bool isBatch_; + }; + +private: + static void OnComplete(UvChangeMsg *msg); + napi_env env_; + napi_ref cbOnRef_ = nullptr; + bool isBatch_; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_FILE_NAPI_H \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp new file mode 100644 index 0000000..5ae5d27 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.cpp @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2023-2024 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 "cloud_sync_n_exporter.h" + +#include "cloud_file_cache_napi.h" +#include "cloud_file_download_napi.h" +#include "cloud_file_napi.h" +#include "cloud_sync_napi.h" +#include "file_sync_napi.h" +#include "gallery_sync_napi.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +static void InitState(napi_env env, napi_value exports) +{ + char propertyName[] = "State"; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("RUNNING", + NVal::CreateInt32(env, (int32_t)State::CLOUD_FILE_DOWNLOAD_RUNNING).val_), + DECLARE_NAPI_STATIC_PROPERTY("COMPLETED", + NVal::CreateInt32(env, (int32_t)State::CLOUD_FILE_DOWNLOAD_COMPLETED).val_), + DECLARE_NAPI_STATIC_PROPERTY("FAILED", + NVal::CreateInt32(env, (int32_t)State::CLOUD_FILE_DOWNLOAD_FAILED).val_), + DECLARE_NAPI_STATIC_PROPERTY("STOPPED", + NVal::CreateInt32(env, (int32_t)State::CLOUD_FILE_DOWNLOAD_STOPPED).val_), + }; + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +/*********************************************** + * Module export and register + ***********************************************/ +napi_value CloudSyncExport(napi_env env, napi_value exports) +{ + InitCloudSyncState(env, exports); + InitErrorType(env, exports); + InitDownloadErrorType(env, exports); + InitState(env, exports); + InitFileSyncState(env, exports); + InitCloudSyncApi(env, exports); + InitNotifyType(env, exports); + InitCloudSyncFuncs(env, exports); + InitOptimizeState(env, exports); + + std::vector> products; + products.emplace_back(std::make_unique(env, exports)); + products.emplace_back(std::make_unique(env, exports)); + products.emplace_back(std::make_unique(env, exports)); + products.emplace_back(std::make_unique(env, exports)); + for (auto &&product : products) { + if (!product->Export()) { + LOGE("INNER BUG. Failed to export class %{public}s for module cloudSyncDownload ", + product->GetClassName().c_str()); + return nullptr; + } else { + LOGI("Class %{public}s for module cloudSyncDownload has been exported", product->GetClassName().c_str()); + } + } + return exports; +} + +void InitCloudSyncState(napi_env env, napi_value exports) +{ + char propertyName[] = "SyncState"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("UPLOADING", NVal::CreateInt32(env, UPLOADING).val_), + DECLARE_NAPI_STATIC_PROPERTY("UPLOAD_FAILED", NVal::CreateInt32(env, UPLOAD_FAILED).val_), + DECLARE_NAPI_STATIC_PROPERTY("DOWNLOADING", NVal::CreateInt32(env, DOWNLOADING).val_), + DECLARE_NAPI_STATIC_PROPERTY("DOWNLOAD_FAILED", NVal::CreateInt32(env, DOWNLOAD_FAILED).val_), + DECLARE_NAPI_STATIC_PROPERTY("COMPLETED", NVal::CreateInt32(env, COMPLETED).val_), + DECLARE_NAPI_STATIC_PROPERTY("STOPPED", NVal::CreateInt32(env, STOPPED).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitOptimizeState(napi_env env, napi_value exports) +{ + char propertyName[] = "OptimizeState"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("RUNNING", NVal::CreateInt32(env, OPTIMIZE_RUNNING).val_), + DECLARE_NAPI_STATIC_PROPERTY("COMPLETED", NVal::CreateInt32(env, OPTIMIZE_COMPLETED).val_), + DECLARE_NAPI_STATIC_PROPERTY("FAILED", NVal::CreateInt32(env, OPTIMIZE_FAILED).val_), + DECLARE_NAPI_STATIC_PROPERTY("STOPPED", NVal::CreateInt32(env, OPTIMIZE_STOPPED).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitFileSyncState(napi_env env, napi_value exports) +{ + char propertyName[] = "FileSyncState"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("UPLOADING", NVal::CreateInt32(env, FILESYNCSTATE_UPLOADING).val_), + DECLARE_NAPI_STATIC_PROPERTY("DOWNLOADING", NVal::CreateInt32(env, FILESYNCSTATE_DOWNLOADING).val_), + DECLARE_NAPI_STATIC_PROPERTY("COMPLETED", NVal::CreateInt32(env, FILESYNCSTATE_COMPLETED).val_), + DECLARE_NAPI_STATIC_PROPERTY("STOPPED", NVal::CreateInt32(env, FILESYNCSTATE_STOPPED).val_), + DECLARE_NAPI_STATIC_PROPERTY("TO_BE_UPLOADED", NVal::CreateInt32(env, FILESYNCSTATE_TO_BE_UPLOADED).val_), + DECLARE_NAPI_STATIC_PROPERTY("UPLOAD_FAILURE", NVal::CreateInt32(env, FILESYNCSTATE_UPLOAD_FAILURE).val_), + DECLARE_NAPI_STATIC_PROPERTY("UPLOAD_SUCCESS", NVal::CreateInt32(env, FILESYNCSTATE_UPLOAD_SUCCESS).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitErrorType(napi_env env, napi_value exports) +{ + char propertyName[] = "ErrorType"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("NO_ERROR", NVal::CreateInt32(env, NO_ERROR).val_), + DECLARE_NAPI_STATIC_PROPERTY("NETWORK_UNAVAILABLE", NVal::CreateInt32(env, NETWORK_UNAVAILABLE).val_), + DECLARE_NAPI_STATIC_PROPERTY("WIFI_UNAVAILABLE", NVal::CreateInt32(env, WIFI_UNAVAILABLE).val_), + DECLARE_NAPI_STATIC_PROPERTY("BATTERY_LEVEL_LOW", NVal::CreateInt32(env, BATTERY_LEVEL_LOW).val_), + DECLARE_NAPI_STATIC_PROPERTY("BATTERY_LEVEL_WARNING", NVal::CreateInt32(env, BATTERY_LEVEL_WARNING).val_), + DECLARE_NAPI_STATIC_PROPERTY("CLOUD_STORAGE_FULL", NVal::CreateInt32(env, CLOUD_STORAGE_FULL).val_), + DECLARE_NAPI_STATIC_PROPERTY("LOCAL_STORAGE_FULL", NVal::CreateInt32(env, LOCAL_STORAGE_FULL).val_), + DECLARE_NAPI_STATIC_PROPERTY("DEVICE_TEMPERATURE_TOO_HIGH", + NVal::CreateInt32(env, DEVICE_TEMPERATURE_TOO_HIGH).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitDownloadErrorType(napi_env env, napi_value exports) +{ + char propertyName[] = "DownloadErrorType"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("NO_ERROR", NVal::CreateInt32(env, NO_ERROR).val_), + DECLARE_NAPI_STATIC_PROPERTY("UNKNOWN_ERROR", + NVal::CreateInt32(env, DownloadProgressObj::UNKNOWN_ERROR).val_), + DECLARE_NAPI_STATIC_PROPERTY("NETWORK_UNAVAILABLE", + NVal::CreateInt32(env, DownloadProgressObj::NETWORK_UNAVAILABLE).val_), + DECLARE_NAPI_STATIC_PROPERTY("LOCAL_STORAGE_FULL", + NVal::CreateInt32(env, DownloadProgressObj::LOCAL_STORAGE_FULL).val_), + DECLARE_NAPI_STATIC_PROPERTY("CONTENT_NOT_FOUND", + NVal::CreateInt32(env, DownloadProgressObj::CONTENT_NOT_FOUND).val_), + DECLARE_NAPI_STATIC_PROPERTY("FREQUENT_USER_REQUESTS", + NVal::CreateInt32(env, DownloadProgressObj::FREQUENT_USER_REQUESTS).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitCloudSyncApi(napi_env env, napi_value exports) +{ + static napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("getFileSyncState", CloudSyncNapi::GetFileSyncState), + DECLARE_NAPI_FUNCTION("optimizeStorage", CloudSyncNapi::OptimizeStorage), + DECLARE_NAPI_FUNCTION("startOptimizeSpace", CloudSyncNapi::StartOptimizeStorage), + DECLARE_NAPI_FUNCTION("stopOptimizeSpace", CloudSyncNapi::StopOptimizeStorage), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +void InitNotifyType(napi_env env, napi_value exports) +{ + const char propertyName[] = "NotifyType"; + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_ADDED", NVal::CreateInt32(env, NotifyType::NOTIFY_ADDED).val_), + DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_MODIFIED", NVal::CreateInt32(env, NotifyType::NOTIFY_MODIFIED).val_), + DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_DELETED", NVal::CreateInt32(env, NotifyType::NOTIFY_DELETED).val_), + DECLARE_NAPI_STATIC_PROPERTY("NOTIFY_RENAMED", NVal::CreateInt32(env, NotifyType::NOTIFY_RENAMED).val_), + }; + napi_value obj = nullptr; + napi_create_object(env, &obj); + napi_define_properties(env, obj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, obj); +} + +void InitCloudSyncFuncs(napi_env env, napi_value exports) +{ + static napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("registerChange", CloudSyncNapi::RegisterChange), + DECLARE_NAPI_FUNCTION("unregisterChange", CloudSyncNapi::UnregisterChange), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = CloudSyncExport, + .nm_modname = "file.cloudSync", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.h b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.h new file mode 100644 index 0000000..013a64a --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_n_exporter.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023-2024 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 OHOS_FILEMGMT_CLOUD_SYNC_N_EXPORTER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_N_EXPORTER_H + +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::CloudSync { +void InitCloudSyncState(napi_env env, napi_value exports); +void InitFileSyncState(napi_env env, napi_value exports); +void InitErrorType(napi_env env, napi_value exports); +void InitCloudSyncApi(napi_env env, napi_value exports); +void InitDownloadErrorType(napi_env env, napi_value exports); +void InitNotifyType(napi_env env, napi_value exports); +void InitCloudSyncFuncs(napi_env env, napi_value exports); +void InitOptimizeState(napi_env env, napi_value exports); +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_SYNC_N_EXPORTER_H \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp new file mode 100644 index 0000000..9ab89d6 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp @@ -0,0 +1,1191 @@ +/* + * Copyright (c) 2023-2024 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 "cloud_sync_napi.h" + +#include +#include + +#include "async_work.h" +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "dfsu_access_token_helper.h" +#include "securec.h" +#include "uri.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; +const int32_t PARAM0 = 0; +static const unsigned int READ_SIZE = 1024; +const string FILE_SCHEME = "file"; +thread_local unique_ptr g_listObj = nullptr; +mutex CloudSyncNapi::sOnOffMutex_; +static mutex obsMutex_; +const int32_t AGING_DAYS = 30; +const int32_t GET_FILE_SYNC_MAX = 100; +CloudSyncState CloudSyncCallbackImpl::preState_ = CloudSyncState::COMPLETED; +ErrorType CloudSyncCallbackImpl::preError_ = ErrorType::NO_ERROR; + +class ObserverImpl : public AAFwk::DataAbilityObserverStub { +public: + explicit ObserverImpl(const shared_ptr cloudNotifyObserver) + : cloudNotifyObserver_(cloudNotifyObserver){}; + void OnChange(); + void OnChangeExt(const AAFwk::ChangeInfo &info); + static sptr GetObserver(const Uri &uri, const shared_ptr &observer); + static bool FindObserver(const Uri &uri, const shared_ptr &observer); + static bool DeleteObserver(const Uri &uri, const shared_ptr &observer); + +private: + struct ObserverParam { + sptr obs_; + list uris_; + }; + shared_ptr cloudNotifyObserver_; + static ConcurrentMap observers_; +}; + +ConcurrentMap ObserverImpl::observers_; + +void ObserverImpl::OnChange() {} + +void ObserverImpl::OnChangeExt(const AAFwk::ChangeInfo &info) +{ + if (cloudNotifyObserver_ == nullptr) { + LOGE("cloudNotifyObserver_ is null!"); + return; + } + cloudNotifyObserver_->OnchangeExt(info); +} + +sptr ObserverImpl::GetObserver(const Uri &uri, const shared_ptr &observer) +{ + lock_guard lock(obsMutex_); + sptr result = nullptr; + observers_.Compute(observer.get(), [&result, &uri, &observer](const auto &key, auto &value) { + if (value.obs_ == nullptr) { + value.obs_ = new (nothrow) ObserverImpl(observer); + value.uris_.push_back(uri); + } else { + auto it = find(value.uris_.begin(), value.uris_.end(), uri); + if (it == value.uris_.end()) { + value.uris_.push_back(uri); + } + } + + result = value.obs_; + return result != nullptr; + }); + + return result; +} + +bool ObserverImpl::FindObserver(const Uri &uri, const shared_ptr &observer) +{ + lock_guard lock(obsMutex_); + auto result = observers_.Find(observer.get()); + if (result.first) { + auto it = std::find(result.second.uris_.begin(), result.second.uris_.end(), uri); + if (it == result.second.uris_.end()) { + return false; + } + } + return result.first; +} + +bool ObserverImpl::DeleteObserver(const Uri &uri, const shared_ptr &observer) +{ + lock_guard lock(obsMutex_); + return observers_.ComputeIfPresent(observer.get(), [&uri](auto &key, auto &value) { + value.uris_.remove_if([&uri](const auto &value) { return uri == value; }); + return !value.uris_.empty(); + }); +} + +CloudSyncCallbackImpl::CloudSyncCallbackImpl(napi_env env, napi_value fun) : env_(env) +{ + if (fun != nullptr) { + napi_create_reference(env_, fun, 1, &cbOnRef_); + } +} + +void CloudSyncCallbackImpl::OnComplete(UvChangeMsg *msg) +{ + auto cloudSyncCallback = msg->cloudSyncCallback_.lock(); + if (cloudSyncCallback == nullptr || cloudSyncCallback->cbOnRef_ == nullptr) { + LOGE("cloudSyncCallback->cbOnRef_ is nullptr"); + return; + } + auto env = cloudSyncCallback->env_; + auto ref = cloudSyncCallback->cbOnRef_; + napi_handle_scope scope = nullptr; + napi_open_handle_scope(env, &scope); + napi_value jsCallback = nullptr; + napi_status status = napi_get_reference_value(env, ref, &jsCallback); + if (status != napi_ok) { + LOGE("Create reference failed, status: %{public}d", status); + napi_close_handle_scope(env, scope); + return; + } + NVal obj = NVal::CreateObject(env); + obj.AddProp("state", NVal::CreateInt32(env, (int32_t)msg->state_).val_); + obj.AddProp("error", NVal::CreateInt32(env, (int32_t)msg->error_).val_); + napi_value retVal = nullptr; + napi_value global = nullptr; + napi_get_global(env, &global); + status = napi_call_function(env, global, jsCallback, ARGS_ONE, &(obj.val_), &retVal); + if (status != napi_ok) { + LOGE("napi call function failed, status: %{public}d", status); + } + napi_close_handle_scope(env, scope); +} +void CloudSyncCallbackImpl::OnDeathRecipient() +{ + auto isInDownOrUpload = (preState_ == CloudSyncState::UPLOADING) || (preState_ == CloudSyncState::DOWNLOADING); + if (isInDownOrUpload && (preError_ == ErrorType::NO_ERROR)) { + OnSyncStateChanged(CloudSyncState::STOPPED, ErrorType::NO_ERROR); + } +} + +void CloudSyncCallbackImpl::OnSyncStateChanged(CloudSyncState state, ErrorType error) +{ + LOGI("notify - state: %{public}d, error: %{public}d", state, error); + UvChangeMsg *msg = new (std::nothrow) UvChangeMsg(shared_from_this(), state, error); + if (msg == nullptr) { + LOGE("Failed to create uv message object"); + return; + } + + auto task = [msg]() { + if (msg->cloudSyncCallback_.expired()) { + LOGE("cloudSyncCallback_ is expired"); + delete msg; + return; + } + msg->cloudSyncCallback_.lock()->OnComplete(msg); + delete msg; + }; + preState_ = state; + preError_ = error; + napi_status ret = napi_send_event(env_, task, napi_event_priority::napi_eprio_immediate); + if (ret != napi_ok) { + LOGE("Failed to execute libuv work queue, ret: %{public}d", ret); + delete msg; + return; + } +} + +void CloudSyncCallbackImpl::DeleteReference() +{ + if (cbOnRef_ != nullptr) { + napi_delete_reference(env_, cbOnRef_); + cbOnRef_ = nullptr; + } +} + +void CloudSyncCallbackImpl::OnSyncStateChanged(SyncType type, SyncPromptState state) +{ + return; +} + +void CloudOptimizeCallbackImpl::OnOptimizeProcess(const OptimizeState state, const int32_t progress) +{ + napi_env env = env_; + auto task = [this, env, state, progress] () { + if (!cbOnRef_) { + LOGE("cbOnRef_ is nullptr"); + return; + } + + napi_handle_scope scope = nullptr; + napi_status status = napi_open_handle_scope(env, &scope); + if (status != napi_ok) { + LOGE("Create reference failed, status: %{public}d", status); + return; + } + + napi_value jsCallback = cbOnRef_.Deref(env).val_; + NVal obj = NVal::CreateObject(env); + obj.AddProp("state", NVal::CreateInt32(env, (int32_t)state).val_); + obj.AddProp("progress", NVal::CreateInt32(env, (int32_t)progress).val_); + napi_value retVal = nullptr; + status = napi_call_function(env_, nullptr, jsCallback, ARGS_ONE, &(obj.val_), &retVal); + if (status != napi_ok) { + LOGE("napi call function failed, status: %{public}d", status); + } + napi_close_handle_scope(env, scope); + }; + auto ret = napi_send_event(env, task, napi_eprio_immediate); + if (ret != 0) { + LOGE("failed to send event, ret: %{public}d", ret); + } +} + +string CloudSyncNapi::GetBundleName(const napi_env &env, const NFuncArg &funcArg) +{ + string bundleName; + auto bundleEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (bundleEntity) { + bundleName = bundleEntity->bundleName_; + } + return bundleName; +} + +napi_value CloudSyncNapi::Constructor(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + if (funcArg.GetArgc() == NARG_CNT::ZERO) { + LOGD("init without bundleName"); + return funcArg.GetThisVar(); + } + if (funcArg.GetArgc() == NARG_CNT::ONE) { + auto [succ, bundleName, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ || bundleName.get() == string("")) { + LOGE("Failed to get bundle name"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto bundleEntity = make_unique(bundleName.get()); + if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(bundleEntity))) { + LOGE("Failed to set file entity"); + NError(EIO).ThrowErr(env); + return nullptr; + } + LOGI("init with bundleName"); + return funcArg.GetThisVar(); + } + return nullptr; +} + +bool CloudSyncNapi::InitArgsOnCallback(const napi_env &env, NFuncArg &funcArg) +{ + if (!funcArg.InitArgs(NARG_CNT::TWO)) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + LOGE("OnCallback Number of arguments unmatched"); + return false; + } + + auto [succ, type, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!(succ && (type.get() == std::string("progress")))) { + NError(E_PARAMS).ThrowErr(env); + return false; + } + + if (!NVal(env, funcArg[(int)NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return false; + } + + if (callback_ != nullptr) { + LOGI("callback already exist"); + return false; + } + return true; +} + +napi_value CloudSyncNapi::OnCallback(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!InitArgsOnCallback(env, funcArg)) { + return nullptr; + } + + string bundleName = GetBundleName(env, funcArg); + callback_ = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); + int32_t ret = CloudSyncManager::GetInstance().RegisterCallback(callback_, bundleName); + if (ret != E_OK) { + LOGE("OnCallback Register error, result: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +bool CloudSyncNapi::InitArgsOffCallback(const napi_env &env, NFuncArg &funcArg) +{ + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + LOGE("OffCallback Number of arguments unmatched"); + return false; + } + + auto [succ, type, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!(succ && (type.get() == std::string("progress")))) { + NError(E_PARAMS).ThrowErr(env); + return false; + } + + if (funcArg.GetArgc() == (uint)NARG_CNT::TWO && !NVal(env, funcArg[(int)NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + return false; + } + return true; +} + +napi_value CloudSyncNapi::OffCallback(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!InitArgsOffCallback(env, funcArg)) { + return nullptr; + } + + string bundleName = GetBundleName(env, funcArg); + int32_t ret = CloudSyncManager::GetInstance().UnRegisterCallback(bundleName); + if (ret != E_OK) { + LOGE("OffCallback UnRegister error, result: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + if (callback_ != nullptr) { + /* napi delete reference */ + callback_->DeleteReference(); + callback_ = nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudSyncNapi::Start(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + } + + string bundleName = GetBundleName(env, funcArg); + auto cbExec = [bundleName]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StartSync(bundleName); + if (ret != E_OK) { + LOGE("Start Sync error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "Start"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value CloudSyncNapi::Stop(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string bundleName = GetBundleName(env, funcArg); + auto cbExec = [bundleName]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StopSync(bundleName); + if (ret != E_OK) { + LOGE("Stop Sync error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "Stop"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +bool CloudSyncNapi::CheckRef(napi_env env, napi_ref ref, ChangeListenerNapi &listObj, const string &uri) +{ + napi_value offCallback = nullptr; + napi_status status = napi_get_reference_value(env, ref, &offCallback); + if (status != napi_ok) { + LOGE("Create reference fail, status: %{public}d", status); + return false; + } + bool isSame = false; + shared_ptr obs; + string obsUri; + { + lock_guard lock(sOnOffMutex_); + for (auto it = listObj.observers_.begin(); it < listObj.observers_.end(); it++) { + napi_value onCallback = nullptr; + status = napi_get_reference_value(env, (*it)->ref_, &onCallback); + if (status != napi_ok) { + LOGE("Create reference fail, status: %{public}d", status); + return false; + } + napi_strict_equals(env, offCallback, onCallback, &isSame); + if (isSame) { + obsUri = (*it)->uri_; + if (uri.compare(obsUri) != 0) { + return true; + } + return false; + } + } + } + return true; +} + +static bool CheckIsValidUri(Uri uri) +{ + string scheme = uri.GetScheme(); + if (scheme != FILE_SCHEME) { + return false; + } + string sandboxPath = uri.GetPath(); + char realPath[PATH_MAX + 1]{'\0'}; + if (realpath(sandboxPath.c_str(), realPath) == nullptr) { + LOGE("realpath failed with %{public}d", errno); + return false; + } + if (strncmp(realPath, sandboxPath.c_str(), sandboxPath.size()) != 0) { + LOGE("sandboxPath is not equal to realPath"); + return false; + } + if (sandboxPath.find("/data/storage/el2/cloud") != 0) { + LOGE("not surported uri"); + return false; + } + return true; +} + +static int32_t GetRegisterParams(napi_env env, napi_callback_info info, RegisterParams ®isterParams) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::THREE)) { + LOGE("Arguments number mismatch"); + return E_PARAMS; + } + + auto [succUri, uri, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succUri) { + LOGE("get arg uri fail"); + return E_PARAMS; + } + registerParams.uri = string(uri.get()); + if (!CheckIsValidUri(Uri(registerParams.uri))) { + LOGE("RegisterChange uri parameter format error!"); + return E_PARAMS; + } + + auto [succRecursion, recursion] = NVal(env, funcArg[(int)NARG_POS::SECOND]).ToBool(); + if (!succRecursion) { + LOGE("get arg recursion fail"); + return E_PARAMS; + } + registerParams.recursion = recursion; + + if (!NVal(env, funcArg[(int)NARG_POS::THIRD]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + return E_PARAMS; + } + napi_status status = + napi_create_reference(env, NVal(env, funcArg[(int)NARG_POS::THIRD]).val_, 1, ®isterParams.cbOnRef); + if (status != napi_ok) { + LOGE("Create reference fail, status: %{public}d", status); + return E_PARAMS; + } + + return ERR_OK; +} + +int32_t CloudSyncNapi::RegisterToObs(napi_env env, const RegisterParams ®isterParams) +{ + auto observer = make_shared(*g_listObj, registerParams.uri, registerParams.cbOnRef); + Uri uri(registerParams.uri); + auto obsMgrClient = AAFwk::DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + LOGE("get DataObsMgrClient failed"); + return E_SA_LOAD_FAILED; + } + sptr obs = ObserverImpl::GetObserver(uri, observer); + if (obs == nullptr) { + LOGE("new ObserverImpl failed"); + return E_INVAL_ARG; + } + ErrCode ret = obsMgrClient->RegisterObserverExt(uri, obs, registerParams.recursion); + if (ret != E_OK) { + LOGE("ObsMgr register fail"); + ObserverImpl::DeleteObserver(uri, observer); + return E_INVAL_ARG; + } + lock_guard lock(CloudSyncNapi::sOnOffMutex_); + g_listObj->observers_.push_back(observer); + return E_OK; +} + +napi_value CloudSyncNapi::RegisterChange(napi_env env, napi_callback_info info) +{ + if (g_listObj == nullptr) { + g_listObj = make_unique(env); + } + + RegisterParams registerParams; + int32_t ret = GetRegisterParams(env, info, registerParams); + if (ret != ERR_OK) { + LOGE("Get Params fail"); + NError(ret).ThrowErr(env); + return nullptr; + } + + if (CheckRef(env, registerParams.cbOnRef, *g_listObj, registerParams.uri)) { + ret = RegisterToObs(env, registerParams); + if (ret != E_OK) { + LOGE("Get Params fail"); + NError(ret).ThrowErr(env); + return nullptr; + } + } else { + LOGE("Check Ref fail"); + NError(E_PARAMS).ThrowErr(env); + napi_delete_reference(env, registerParams.cbOnRef); + return nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudSyncNapi::UnregisterFromObs(napi_env env, const string &uri) +{ + auto obsMgrClient = AAFwk::DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + LOGE("get DataObsMgrClient failed"); + NError(E_SA_LOAD_FAILED).ThrowErr(env); + return nullptr; + } + std::vector> offObservers; + { + lock_guard lock(sOnOffMutex_); + for (auto iter = g_listObj->observers_.begin(); iter != g_listObj->observers_.end();) { + if (uri == (*iter)->uri_) { + offObservers.push_back(*iter); + vector>::iterator tmp = iter; + iter = g_listObj->observers_.erase(tmp); + } else { + iter++; + } + } + } + for (auto observer : offObservers) { + if (!ObserverImpl::FindObserver(Uri(uri), observer)) { + LOGE("observer not exist"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + sptr obs = ObserverImpl::GetObserver(Uri(uri), observer); + if (obs == nullptr) { + LOGE("new observerimpl failed"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + ErrCode ret = obsMgrClient->UnregisterObserverExt(Uri(uri), obs); + if (ret != ERR_OK) { + LOGE("call obs unregister fail"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + ObserverImpl::DeleteObserver(Uri(uri), observer); + } + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudSyncNapi::UnregisterChange(napi_env env, napi_callback_info info) +{ + if (g_listObj == nullptr || g_listObj->observers_.empty()) { + LOGI("no obs to unregister"); + return nullptr; + } + + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + LOGE("params number mismatch"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succUri, uri, ignore] = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succUri || !CheckIsValidUri(Uri(uri.get()))) { + LOGE("get uri fail"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + return UnregisterFromObs(env, uri.get()); +} + +void CloudSyncNapi::SetClassName(const std::string classname) +{ + className_ = classname; +} + +std::string CloudSyncNapi::GetClassName() +{ + return className_; +} + +bool CloudSyncNapi::ToExport(std::vector props) +{ + std::string className = GetClassName(); + auto [succ, classValue] = + NClass::DefineClass(exports_.env_, className, Constructor, std::move(props)); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to define CloudSyncNapi class"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to save CloudSyncNapi class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +bool CloudSyncNapi::Export() +{ + std::vector props = { + NVal::DeclareNapiFunction("on", OnCallback), + NVal::DeclareNapiFunction("off", OffCallback), + NVal::DeclareNapiFunction("start", Start), + NVal::DeclareNapiFunction("stop", Stop), + NVal::DeclareNapiFunction("getFileSyncState", GetFileSyncState), + NVal::DeclareNapiFunction("optimizeStorage", OptimizeStorage), + NVal::DeclareNapiFunction("startOptimizeSpace", StartOptimizeStorage), + NVal::DeclareNapiFunction("stopOptimizeSpace", StopOptimizeStorage), + }; + std::string className = GetClassName(); + auto [succ, classValue] = + NClass::DefineClass(exports_.env_, className, CloudSyncNapi::Constructor, std::move(props)); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to define GallerySync class"); + return false; + } + + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + NError(E_GETRESULT).ThrowErr(exports_.env_); + LOGE("Failed to save GallerySync class"); + return false; + } + + return exports_.AddProp(className, classValue); +} + +int32_t CloudSyncNapi::HandOptimizeStorageParams(napi_env env, napi_callback_info info, NFuncArg &funcArg, + OptimizeSpaceOptions &optimizeOptions) +{ + bool succ = false; + auto argv = NVal(env, funcArg[NARG_POS::FIRST]); + if (!argv.HasProp("totalSize") || !argv.HasProp("agingDays")) { + return ERR_BAD_VALUE; + } + + int64_t totalSize = 0; + int32_t agingDays = 0; + tie(succ, totalSize) = argv.GetProp("totalSize").ToInt64(); + if (!succ) { + return ERR_BAD_VALUE; + } + tie(succ, agingDays) = argv.GetProp("agingDays").ToInt32(); + if (!succ) { + return ERR_BAD_VALUE; + } + + if (!NVal(env, funcArg[(int)NARG_POS::SECOND]).TypeIs(napi_function)) { + LOGE("Argument type mismatch"); + return ERR_BAD_VALUE; + } + + LOGI("totalSize:%{public}lld, agingDays:%{public}d", static_cast(totalSize), agingDays); + optimizeOptions.totalSize = totalSize; + optimizeOptions.agingDays = agingDays; + return ERR_OK; +} + +napi_value CloudSyncNapi::StartOptimizeStorage(napi_env env, napi_callback_info info) +{ + LOGI("StartOptimizeStorage enter"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::TWO)) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + LOGE("Number of arguments unmatched"); + return nullptr; + } + OptimizeSpaceOptions optimizeOptions {}; + int32_t res = HandOptimizeStorageParams(env, info, funcArg, optimizeOptions); + if (res != ERR_OK) { + LOGE("hand paeams failed"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto callback = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND])); + auto cbExec = [optimizeOptions, callback]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().OptimizeStorage(optimizeOptions, callback); + if (ret != E_OK) { + LOGE("StartOptimizeStorage error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "StartOptimizeStorage"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value CloudSyncNapi::StopOptimizeStorage(napi_env env, napi_callback_info info) +{ + LOGI("StopOptimizeStorage enter"); + int32_t ret = CloudSyncManager::GetInstance().StopOptimizeStorage(); + if (ret != E_OK) { + LOGE("StopOptimizeStorage error, result: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value CloudSyncNapi::OptimizeStorage(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + } + + OptimizeSpaceOptions optimizeOptions {}; + optimizeOptions.totalSize = 0; + optimizeOptions.agingDays = AGING_DAYS; + + auto cbExec = [optimizeOptions]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().OptimizeStorage(optimizeOptions); + if (ret != E_OK) { + LOGE("OptimizeStorage error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "OptimizeStorage"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +static bool IsGetSingleFileStatus(const napi_env &env, const NFuncArg &funcArg) +{ + if (!NVal(env, funcArg[(int)NARG_POS::FIRST]).TypeIs(napi_string)) { + return false; + } + return true; +} + +tuple CloudSyncNapi::GetSingleFileSyncState(const string &path) +{ + Uri uri(path); + char resolvedPath[PATH_MAX] = {'\0'}; + if (realpath(uri.GetPath().c_str(), resolvedPath) == nullptr) { + LOGE("get realPath failed"); + return { LibN::USER_FILE_MANAGER_SYS_CAP_TAG + E_URIM, -1 }; + } + std::string sandBoxPath(resolvedPath); + std::string xattrKey = "user.cloud.filestatus"; + auto xattrValueSize = getxattr(sandBoxPath.c_str(), xattrKey.c_str(), nullptr, 0); + if (xattrValueSize < 0) { + return { E_UNKNOWN_ERR, -1 }; + } + std::unique_ptr xattrValue = std::make_unique((long)xattrValueSize + 1); + if (xattrValue == nullptr) { + return { E_UNKNOWN_ERR, -1 }; + } + xattrValueSize = getxattr(sandBoxPath.c_str(), xattrKey.c_str(), xattrValue.get(), xattrValueSize); + if (xattrValueSize <= 0) { + return { E_UNKNOWN_ERR, -1 }; + } + std::string xattrValueStr(xattrValue.get(), xattrValueSize); + bool isValid = std::all_of(xattrValueStr.begin(), xattrValueStr.end(), ::isdigit); + if (!isValid) { + LOGE("invalid xattrValue"); + return { E_PARAMS, -1}; + } + int32_t fileStatus = std::stoi(xattrValue.get()); + int32_t val; + if (fileStatus == FileSync::FILESYNC_TO_BE_UPLOADED || fileStatus == FileSync::FILESYNC_UPLOADING || + fileStatus == FileSync::FILESYNC_UPLOAD_FAILURE || fileStatus == FileSync::FILESYNC_UPLOAD_SUCCESS) { + val = statusMap[fileStatus]; + } else { + val = FileSyncState::FILESYNCSTATE_COMPLETED; + } + return { E_OK, val }; +} + +tuple CloudSyncNapi::GetFileSyncStateForBatch(const string &path) +{ + Uri uri(path); + char resolvedPath[PATH_MAX] = {'\0'}; + if (realpath(uri.GetPath().c_str(), resolvedPath) == nullptr) { + LOGE("get realPath failed"); + return { LibN::USER_FILE_MANAGER_SYS_CAP_TAG + E_URIM, -1 }; + } + std::string sandBoxPath(resolvedPath); + std::string xattrKey = "user.cloud.filestatus"; + auto xattrValueSize = getxattr(sandBoxPath.c_str(), xattrKey.c_str(), nullptr, 0); + if (xattrValueSize < 0) { + return { LibN::STORAGE_SERVICE_SYS_CAP_TAG + LibN::E_IPCSS, -1 }; + } + std::unique_ptr xattrValue = std::make_unique((long)xattrValueSize + 1); + if (xattrValue == nullptr) { + return { LibN::STORAGE_SERVICE_SYS_CAP_TAG + LibN::E_IPCSS, -1 }; + } + xattrValueSize = getxattr(sandBoxPath.c_str(), xattrKey.c_str(), xattrValue.get(), xattrValueSize); + if (xattrValueSize <= 0) { + return { LibN::STORAGE_SERVICE_SYS_CAP_TAG + LibN::E_IPCSS, -1 }; + } + std::string xattrValueStr(xattrValue.get(), xattrValueSize); + bool isValid = std::all_of(xattrValueStr.begin(), xattrValueStr.end(), ::isdigit); + if (!isValid) { + LOGE("invalid xattrValue"); + return { E_PARAMS, -1}; + } + int32_t fileStatus = std::stoi(xattrValue.get()); + int32_t val; + if (fileStatus == FileSync::FILESYNC_TO_BE_UPLOADED || fileStatus == FileSync::FILESYNC_UPLOADING || + fileStatus == FileSync::FILESYNC_UPLOAD_FAILURE || fileStatus == FileSync::FILESYNC_UPLOAD_SUCCESS) { + val = statusMap[fileStatus]; + } else { + val = FileSyncState::FILESYNCSTATE_COMPLETED; + } + return { E_OK, val }; +} + +static NVal AsyncComplete(const napi_env &env, std::shared_ptr ctx) +{ + napi_value results = nullptr; + napi_status status = napi_create_array(env, &results); + if (status != napi_ok) { + LOGE("Failed to create array"); + return { env, NError(LibN::STORAGE_SERVICE_SYS_CAP_TAG + LibN::E_IPCSS).GetNapiErr(env) }; + } + int32_t index = 0; + for (auto result : ctx->resultList) { + status = napi_set_element(env, results, index, NVal::CreateInt32(env, result).val_); + if (status != napi_ok) { + LOGE("Failed to set element on data"); + return { env, NError(LibN::STORAGE_SERVICE_SYS_CAP_TAG + LibN::E_IPCSS).GetNapiErr(env) }; + } + index++; + } + return { env, results }; +} + +napi_value CloudSyncNapi::GetBatchFileSyncState(const napi_env &env, const NFuncArg &funcArg) +{ + NVal arrayVal(env, funcArg[static_cast(NARG_POS::FIRST)]); + if (!arrayVal.TypeIs(napi_object)) { + LOGE("Invalid argments"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + auto [succ, uris, ignore] = arrayVal.ToStringArray(); + auto ctx = std::make_shared(); + ctx->uriList.swap(uris); + if (ctx->uriList.size() > GET_FILE_SYNC_MAX) { + LOGE("The parameter is too long"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto cbExec = [env, ctx]() ->NError { + int32_t result = 0; + int32_t fileStatus = 0; + for (auto &path : ctx->uriList) { + tie(result, fileStatus) = GetFileSyncStateForBatch(path); + if (result != E_OK) { + return NError(result); + } + ctx->resultList.push_back(fileStatus); + } + return NError(NO_ERROR); + }; + + auto cbComplete = [ctx](napi_env env, NError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return AsyncComplete(env, ctx); + }; + + std::string procedureName = "GetFileSyncState"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value CloudSyncNapi::GetFileSyncState(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + int32_t result = 0; + int32_t fileStatus = 0; + + if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { + LOGE("Number of arguments unmatched"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + if (IsGetSingleFileStatus(env, funcArg)) { + std::unique_ptr path; + bool succ = false; + tie(succ, path, std::ignore) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToUTF8String(); + if (!succ) { + LOGE("Invalid path"); + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + tie(result, fileStatus) = GetSingleFileSyncState(string(path.get())); + if (result != E_OK) { + NError(result).ThrowErr(env); + return nullptr; + } + return NVal::CreateInt32(env, fileStatus).val_; + } + return GetBatchFileSyncState(env, funcArg); +} + +void ChangeListenerNapi::OnChange(CloudChangeListener &listener, const napi_ref cbRef) +{ + UvChangeMsg *msg = new (std::nothrow) UvChangeMsg(env_, cbRef, listener.changeInfo, listener.strUri); + if (msg == nullptr) { + LOGE("Failed to create uv message object"); + return; + } + + if (!listener.changeInfo.uris_.empty()) { + if (static_cast(listener.changeInfo.changeType_) == NotifyType::NOTIFY_NONE) { + LOGE("changeInfo.changeType_ is other"); + delete msg; + return; + } + if (msg->changeInfo_.size_ > 0) { + msg->data_ = (uint8_t *)malloc(msg->changeInfo_.size_); + if (msg->data_ == nullptr) { + LOGE("new msg->data failed"); + delete msg; + return; + } + int copyRet = memcpy_s(msg->data_, msg->changeInfo_.size_, + msg->changeInfo_.data_, msg->changeInfo_.size_); + if (copyRet != 0) { + LOGE("Parcel data copy failed, err = %{public}d", copyRet); + free(msg->data_); + delete msg; + return; + } + } + } + auto ret = SendEvent(msg); + if (ret != napi_ok) { + LOGE("Failed to execute libuv work queue, ret: %{public}d", ret); + free(msg->data_); + delete msg; + return; + } +} + +int32_t ChangeListenerNapi::SendEvent(UvChangeMsg *msg) +{ + auto task = [msg]() { + // js thread + napi_env env = msg->env_; + napi_handle_scope scope = nullptr; + if (napi_open_handle_scope(env, &scope) != napi_ok) { + LOGE("Failed to open handle scope"); + return; + } + do { + napi_value jsCallback = nullptr; + napi_status status = napi_get_reference_value(env, msg->ref_, &jsCallback); + if (status != napi_ok) { + LOGE("Create reference fail, status: %{public}d", status); + break; + } + + napi_value retVal = nullptr; + napi_value result[ARGS_ONE]; + result[PARAM0] = ChangeListenerNapi::SolveOnChange(env, msg); + if (result[PARAM0] == nullptr) { + break; + } + + status = napi_call_function(env, nullptr, jsCallback, ARGS_ONE, result, &retVal); + if (status != napi_ok) { + LOGE("CallJs napi_call_function fail, status: %{public}d", status); + } + } while (0); + napi_close_handle_scope(env, scope); + free(msg->data_); + delete msg; + }; + return napi_send_event(env_, task, napi_event_priority::napi_eprio_immediate); +} + +static napi_status SetValueArray(const napi_env &env, const char *fieldStr, const std::list listValue, + napi_value &result) +{ + napi_value value = nullptr; + napi_status status = napi_create_array_with_length(env, listValue.size(), &value); + if (status != napi_ok) { + LOGE("Create array error! field: %{public}s", fieldStr); + return status; + } + int elementIndex = 0; + for (auto uri : listValue) { + napi_value uriRet = nullptr; + napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &uriRet); + status = napi_set_element(env, value, elementIndex++, uriRet); + if (status != napi_ok) { + LOGE("Set lite item failed, error: %d", status); + } + } + status = napi_set_named_property(env, result, fieldStr, value); + if (status != napi_ok) { + LOGE("Set array named property error! field: %{public}s", fieldStr); + } + + return status; +} + +static napi_status SetValueInt32(const napi_env &env, const char *fieldStr, const int intValue, napi_value &result) +{ + napi_value value; + napi_status status = napi_create_int32(env, intValue, &value); + if (status != napi_ok) { + LOGE("Set value create int32 error! field: %{public}s", fieldStr); + return status; + } + status = napi_set_named_property(env, result, fieldStr, value); + if (status != napi_ok) { + LOGE("Set int32 named property error! field: %{public}s", fieldStr); + } + return status; +} + +static napi_status SetIsDir(const napi_env &env, const shared_ptr parcel, napi_value &result) +{ + uint32_t len = 0; + napi_status status = napi_invalid_arg; + if (!parcel->ReadUint32(len)) { + LOGE("Failed to read sub uri list length"); + return status; + } + napi_value isDirArray = nullptr; + napi_create_array_with_length(env, len, &isDirArray); + int elementIndex = 0; + if (len > READ_SIZE) { + return napi_invalid_arg; + } + for (uint32_t i = 0; i < len; i++) { + bool isDir = parcel->ReadBool(); + napi_value isDirRet = nullptr; + napi_get_boolean(env, isDir, &isDirRet); + napi_set_element(env, isDirArray, elementIndex++, isDirRet); + } + status = napi_set_named_property(env, result, "isDirectory", isDirArray); + if (status != napi_ok) { + LOGE("Set subUri named property error!"); + } + return status; +} + +napi_value ChangeListenerNapi::SolveOnChange(napi_env env, UvChangeMsg *msg) +{ + static napi_value result; + if (msg->changeInfo_.uris_.empty()) { + napi_get_undefined(env, &result); + return result; + } + napi_create_object(env, &result); + SetValueArray(env, "uris", msg->changeInfo_.uris_, result); + if (msg->data_ != nullptr && msg->changeInfo_.size_ > 0) { + uint8_t *parcelData = (uint8_t *)malloc(msg->changeInfo_.size_); + if (parcelData == nullptr) { + LOGE("new parcelData failed"); + return nullptr; + } + int copyRet = memcpy_s(parcelData, msg->changeInfo_.size_, msg->data_, msg->changeInfo_.size_); + if (copyRet != 0) { + LOGE("Parcel data copy failed, err = %{public}d", copyRet); + free(parcelData); + return nullptr; + } + shared_ptr parcel = make_shared(); + if (parcel->ParseFrom(reinterpret_cast(parcelData), msg->changeInfo_.size_)) { + napi_status status = SetIsDir(env, parcel, result); + if (status != napi_ok) { + LOGE("Set subArray named property error! field: subUris"); + return nullptr; + } + } else { + free(parcelData); + } + } + SetValueInt32(env, "type", (int)msg->changeInfo_.changeType_, result); + return result; +} + +void CloudNotifyObserver::OnChange() {} + +void CloudNotifyObserver::OnchangeExt(const AAFwk::ChangeInfo &changeInfo) +{ + CloudChangeListener listener; + listener.changeInfo = changeInfo; + listener.strUri = uri_; + listObj_.OnChange(listener, ref_); +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h new file mode 100644 index 0000000..d92b616 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/cloud_sync_napi.h @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2023-2024 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 OHOS_FILEMGMT_CLOUD_SYNC_NAPI_H +#define OHOS_FILEMGMT_CLOUD_SYNC_NAPI_H + +#include "cloud_sync_callback.h" +#include "cloud_optimize_callback.h" +#include "cloud_sync_common.h" +#include "data_ability_observer_interface.h" +#include "data_ability_observer_stub.h" +#include "dataobs_mgr_client.h" +#include "filemgmt_libn.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +const int32_t ARGS_ONE = 1; + +struct BundleEntity { + std::string bundleName_; + explicit BundleEntity(const std::string bundleName): bundleName_(bundleName){}; +}; + +struct CloudChangeListener { + NotifyType notifyType; + AAFwk::ChangeInfo changeInfo; + std::string strUri; +}; + +struct RegisterParams { + std::string uri; + bool recursion; + napi_ref cbOnRef; +}; + +struct BatchContext { + std::vector uriList; + std::vector resultList; +}; + +class CloudSyncCallbackImpl; +class ChangeListenerNapi; +class CloudNotifyObserver; +class CloudSyncNapi : public LibN::NExporter { +public: + void SetClassName(const std::string classname); + std::string GetClassName() override; + bool Export() override; + bool ToExport(std::vector props); + static napi_value Constructor(napi_env env, napi_callback_info info); + + static napi_value Start(napi_env env, napi_callback_info info); + static napi_value Stop(napi_env env, napi_callback_info info); + static napi_value OnCallback(napi_env env, napi_callback_info info); + static napi_value OffCallback(napi_env env, napi_callback_info info); + static std::tuple GetSingleFileSyncState(const std::string &path); + static std::tuple GetFileSyncStateForBatch(const std::string &path); + static napi_value GetBatchFileSyncState(const napi_env &env, const LibN::NFuncArg &funcArg); + static napi_value GetFileSyncState(napi_env env, napi_callback_info info); + static napi_value RegisterChange(napi_env env, napi_callback_info info); + static napi_value UnregisterChange(napi_env env, napi_callback_info info); + static napi_value OptimizeStorage(napi_env env, napi_callback_info info); + static napi_value StartOptimizeStorage(napi_env env, napi_callback_info info); + static napi_value StopOptimizeStorage(napi_env env, napi_callback_info info); + + static std::string GetBundleName(const napi_env &env, const LibN::NFuncArg &funcArg); + static bool InitArgsOnCallback(const napi_env &env, LibN::NFuncArg &funcArg); + static bool InitArgsOffCallback(const napi_env &env, LibN::NFuncArg &funcArg); + CloudSyncNapi(napi_env env, napi_value exports) : NExporter(env, exports) {}; + ~CloudSyncNapi() = default; + +protected: + static inline std::shared_ptr callback_; + +private: + static bool CheckRef(napi_env env, napi_ref ref, ChangeListenerNapi &listObj, const std::string &uri); + static int32_t RegisterToObs(napi_env env, const RegisterParams ®isterParams); + static napi_value UnregisterFromObs(napi_env env, const std::string &uri); + static int32_t HandOptimizeStorageParams(napi_env env, napi_callback_info info, LibN::NFuncArg &funcArg, + OptimizeSpaceOptions &optimizeOptions); + std::string className_; + static std::mutex sOnOffMutex_; +}; + +class CloudSyncCallbackImpl : public CloudSyncCallback, public std::enable_shared_from_this { +public: + CloudSyncCallbackImpl(napi_env env, napi_value fun); + ~CloudSyncCallbackImpl() = default; + void OnSyncStateChanged(SyncType type, SyncPromptState state) override; + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override; + void OnDeathRecipient() override; + void DeleteReference(); + + class UvChangeMsg { + public: + UvChangeMsg(std::shared_ptr cloudSyncCallbackIn, CloudSyncState state, ErrorType error) + : cloudSyncCallback_(cloudSyncCallbackIn), state_(state), error_(error) + { + } + ~UvChangeMsg() {} + std::weak_ptr cloudSyncCallback_; + CloudSyncState state_; + ErrorType error_; + }; + +private: + static void OnComplete(UvChangeMsg *msg); + napi_env env_; + napi_ref cbOnRef_ = nullptr; + static CloudSyncState preState_; + static ErrorType preError_; +}; + +class ChangeListenerNapi { +public: + class UvChangeMsg { + public: + UvChangeMsg(napi_env env, napi_ref ref, AAFwk::ChangeInfo &changeInfo, std::string strUri) + : env_(env), ref_(ref), changeInfo_(changeInfo), strUri_(std::move(strUri)) + { + data_ = nullptr; + } + ~UvChangeMsg() {} + napi_env env_; + napi_ref ref_; + AAFwk::ChangeInfo changeInfo_; + uint8_t *data_; + std::string strUri_; + }; + + explicit ChangeListenerNapi(napi_env env) : env_(env) {} + + ChangeListenerNapi(const ChangeListenerNapi &listener) + { + this->env_ = listener.env_; + this->cbOnRef_ = listener.cbOnRef_; + this->cbOffRef_ = listener.cbOffRef_; + this->observers_ = listener.observers_; + } + + ChangeListenerNapi &operator=(const ChangeListenerNapi &listener) + { + this->env_ = listener.env_; + this->cbOnRef_ = listener.cbOnRef_; + this->cbOffRef_ = listener.cbOffRef_; + this->observers_ = listener.observers_; + return *this; + } + + ~ChangeListenerNapi(){}; + void OnChange(CloudChangeListener &listener, const napi_ref cbRef); + int32_t SendEvent(UvChangeMsg *msg); + static napi_value SolveOnChange(napi_env env, UvChangeMsg *msg); + napi_ref cbOnRef_ = nullptr; + napi_ref cbOffRef_ = nullptr; + std::vector> observers_; + +private: + napi_env env_ = nullptr; +}; + +class CloudNotifyObserver { +public: + CloudNotifyObserver(const ChangeListenerNapi &listObj, std::string uri, napi_ref ref) + : listObj_(listObj), uri_(uri), ref_(ref) + { + } + ~CloudNotifyObserver() = default; + + void OnChange(); + void OnchangeExt(const AAFwk::ChangeInfo &changeInfo); + + ChangeListenerNapi listObj_; + std::string uri_; + napi_ref ref_; +}; + +class CloudOptimizeCallbackImpl : public CloudOptimizeCallback, + public std::enable_shared_from_this { +public: + CloudOptimizeCallbackImpl(napi_env env, LibN::NVal callbcakVal) : env_(env), cbOnRef_(callbcakVal) {} + ~CloudOptimizeCallbackImpl() = default; + void OnOptimizeProcess(const OptimizeState state, const int32_t progress) override; + +private: + napi_env env_ = nullptr;; + LibN::NRef cbOnRef_; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_SYNC_NAPI_H diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp b/cloud_file/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp new file mode 100644 index 0000000..8405a74 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/file_sync_napi.cpp @@ -0,0 +1,199 @@ +/* + * 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 "file_sync_napi.h" + +#include +#include + +#include "async_work.h" +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +struct SyncTimeArg { + int64_t time = 0; +}; + +napi_value FileSyncNapi::GetLastSyncTime(napi_env env, napi_callback_info info) +{ + LOGI("GetLastSyncTime Start"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto arg = make_shared(); + if (arg == nullptr) { + HILOGE("Failed to request heap memory."); + NError(ENOMEM).ThrowErr(env); + return nullptr; + } + + string bundleName = GetBundleName(env, funcArg); + auto cbExec = [arg, bundleName]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().GetSyncTime(arg->time, bundleName); + if (ret != E_OK) { + LOGE("GetLastSyncTime error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [cbArg = arg](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateInt64(env, cbArg->time); + }; + + const std::string procedureName = "getLastSyncTime"; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() == NARG_CNT::ONE) { + if (!NVal(env, funcArg[NARG_POS::FIRST]).TypeIs(napi_number)) { + NVal cb(env, funcArg[NARG_POS::FIRST]); + return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; + } + LOGE("Get napi_number Error"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value FileSyncNapi::OnCallback(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!FileSyncNapi::InitArgsOnCallback(env, funcArg)) { + return nullptr; + } + + string bundleName = GetBundleName(env, funcArg); + callback_ = make_shared(env, NVal(env, funcArg[(int)NARG_POS::SECOND]).val_); + int32_t ret = CloudSyncManager::GetInstance().RegisterFileSyncCallback(callback_, bundleName); + if (ret != E_OK) { + LOGE("OnCallback Register error, result: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + + return NVal::CreateUndefined(env).val_; +} + +napi_value FileSyncNapi::OffCallback(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!FileSyncNapi::InitArgsOffCallback(env, funcArg)) { + return nullptr; + } + + string bundleName = GetBundleName(env, funcArg); + int32_t ret = CloudSyncManager::GetInstance().UnRegisterFileSyncCallback(bundleName); + if (ret != E_OK) { + LOGE("OffCallback UnRegister error, result: %{public}d", ret); + NError(Convert2JsErrNum(ret)).ThrowErr(env); + return nullptr; + } + if (callback_ != nullptr) { + /* napi delete reference */ + callback_->DeleteReference(); + callback_ = nullptr; + } + return NVal::CreateUndefined(env).val_; +} + +napi_value FileSyncNapi::Start(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + } + + string bundleName = GetBundleName(env, funcArg); + auto cbExec = [bundleName]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StartFileSync(bundleName); + if (ret != E_OK) { + LOGE("Start Sync error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "Start"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value FileSyncNapi::Stop(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string bundleName = GetBundleName(env, funcArg); + auto cbExec = [bundleName]() -> NError { + int32_t ret = CloudSyncManager::GetInstance().StopFileSync(bundleName); + if (ret != E_OK) { + LOGE("Stop Sync error, result: %{public}d", ret); + return NError(Convert2JsErrNum(ret)); + } + return NError(ERRNO_NOERR); + }; + + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + return NVal::CreateUndefined(env); + }; + + std::string procedureName = "Stop"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +struct SyncStateArg { + vector stateList {}; +}; + +bool FileSyncNapi::Export() +{ + std::vector props = { + NVal::DeclareNapiFunction("on", FileSyncNapi::OnCallback), + NVal::DeclareNapiFunction("off", FileSyncNapi::OffCallback), + NVal::DeclareNapiFunction("start", FileSyncNapi::Start), + NVal::DeclareNapiFunction("stop", FileSyncNapi::Stop), + NVal::DeclareNapiFunction("getLastSyncTime", FileSyncNapi::GetLastSyncTime), + }; + + SetClassName("FileSync"); + return ToExport(props); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/file_sync_napi.h b/cloud_file/interfaces/kits/js/cloudfilesync/file_sync_napi.h new file mode 100644 index 0000000..5d2612c --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/file_sync_napi.h @@ -0,0 +1,36 @@ +/* + * 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 OHOS_FILEMGMT_FILE_SYNC_NAPI_H +#define OHOS_FILEMGMT_FILE_SYNC_NAPI_H + +#include "gallery_sync_napi.h" +#include "cloud_sync_napi.h" + +namespace OHOS::FileManagement::CloudSync { +class FileSyncNapi final : public CloudSyncNapi { +public: + bool Export() override; + static napi_value GetLastSyncTime(napi_env env, napi_callback_info info); + FileSyncNapi(napi_env env, napi_value exports) : CloudSyncNapi(env, exports) {}; + ~FileSyncNapi() = default; + + static napi_value Start(napi_env env, napi_callback_info info); + static napi_value Stop(napi_env env, napi_callback_info info); + static napi_value OnCallback(napi_env env, napi_callback_info info); + static napi_value OffCallback(napi_env env, napi_callback_info info); +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_FILE_SYNC_NAPI_H diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp b/cloud_file/interfaces/kits/js/cloudfilesync/gallery_sync_napi.cpp new file mode 100644 index 0000000..17b0456 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/gallery_sync_napi.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 "gallery_sync_napi.h" + +#include + +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "async_work.h" +#include "uv.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +bool GallerySyncNapi::Export() +{ + SetClassName("GallerySync"); + bool success = CloudSyncNapi::Export(); + if (!success) { + return false; + } + return true; +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h b/cloud_file/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h new file mode 100644 index 0000000..0ce0dc8 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudfilesync/gallery_sync_napi.h @@ -0,0 +1,30 @@ +/* + * 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 OHOS_FILEMGMT_GALLERY_SYNC_NAPI_H +#define OHOS_FILEMGMT_GALLERY_SYNC_NAPI_H + +#include "cloud_sync_napi.h" + +namespace OHOS::FileManagement::CloudSync { +class GallerySyncNapi final : public CloudSyncNapi { +public: + bool Export() override; + GallerySyncNapi(napi_env env, napi_value exports) : CloudSyncNapi(env, exports) {} + ~GallerySyncNapi() = default; +}; + +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_GALLERY_SYNC_NAPI_H diff --git a/cloud_file/interfaces/kits/js/cloudsyncmanager/BUILD.gn b/cloud_file/interfaces/kits/js/cloudsyncmanager/BUILD.gn new file mode 100644 index 0000000..1e66fe2 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudsyncmanager/BUILD.gn @@ -0,0 +1,61 @@ +# 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("cloudsyncmanager") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "cloud_sync_manager_n_exporter.cpp", + "cloud_sync_manager_napi.cpp", + ] + deps = [ + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "c_utils:utils", + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "hilog:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module/file" + + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.cpp b/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.cpp new file mode 100644 index 0000000..3f411c8 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.cpp @@ -0,0 +1,406 @@ +/* + * 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 "cloud_sync_manager_n_exporter.h" + +#include + +#include + +#include "cloud_sync_common.h" +#include "cloud_sync_manager.h" +#include "dfs_error.h" +#include "utils_log.h" +#include "async_work.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +using namespace std; + +napi_value ChangeAppCloudSwitch(napi_env env, napi_callback_info info) +{ + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::THREE), static_cast(NARG_CNT::FOUR))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr accoutId; + std::unique_ptr bundleName; + bool status; + + tie(succ, accoutId, std::ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + tie(succ, bundleName, std::ignore) = NVal(env, funcArg[(int)NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + tie(succ, status) = NVal(env, funcArg[(int)NARG_POS::THIRD]).ToBool(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string accoutIdStr(accoutId.get()); + string bundleNameStr(bundleName.get()); + + auto cbExec = [accoutIdStr, bundleNameStr, status]() -> NError { + int32_t result = CloudSyncManager::GetInstance().ChangeAppSwitch(accoutIdStr, bundleNameStr, status); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + return NError(ERRNO_NOERR); + }; + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + std::string procedureName = "ChangeAppCloudSwitch"; + NVal thisVar(env, funcArg.GetThisVar()); + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::FOUR)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value NotifyDataChangeInner(napi_env env, NFuncArg &funcArg) +{ + LOGI("NotifyDataChangeInner entrance"); + bool succ = false; + std::unique_ptr accoutId; + std::unique_ptr bundleName; + + tie(succ, accoutId, std::ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + tie(succ, bundleName, std::ignore) = NVal(env, funcArg[(int)NARG_POS::SECOND]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string accoutIdStr(accoutId.get()); + string bundleNameStr(bundleName.get()); + + auto cbExec = [accoutIdStr, bundleNameStr]() -> NError { + int32_t result = CloudSyncManager::GetInstance().NotifyDataChange(accoutIdStr, bundleNameStr); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + return NError(ERRNO_NOERR); + }; + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + std::string procedureName = "NotifyDataChange"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +static bool IsNotifyEventChange(napi_env env, NFuncArg &funcArg) +{ + auto options = NVal(env, funcArg[NARG_POS::SECOND]); + if (options.TypeIs(napi_object)) { + return true; + } + return false; +} + +napi_value NotifyEventChange(napi_env env, NFuncArg &funcArg) +{ + LOGI("NotifyEventChange entrance"); + bool succ = false; + int32_t userId; + tie(succ, userId) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToInt32(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + auto argv = NVal(env, funcArg[NARG_POS::SECOND]); + if (!argv.HasProp("eventId") || !argv.HasProp("extraData")) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + std::unique_ptr eventId; + std::unique_ptr extraData; + + tie(succ, eventId, std::ignore) = argv.GetProp("eventId").ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + tie(succ, extraData, std::ignore) = argv.GetProp("extraData").ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string eventIdStr(eventId.get()); + string extraDataStr(extraData.get()); + + auto cbExec = [userId, eventIdStr, extraDataStr]() -> NError { + int32_t result = CloudSyncManager::GetInstance().NotifyEventChange(userId, eventIdStr, extraDataStr); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + return NError(ERRNO_NOERR); + }; + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + std::string procedureName = "NotifyEventChange"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +napi_value NotifyDataChange(napi_env env, napi_callback_info info) +{ + LOGI("NotifyDataChange entrance"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + if (IsNotifyEventChange(env, funcArg)) { + return NotifyEventChange(env, funcArg); + } + return NotifyDataChangeInner(env, funcArg); +} + +napi_value DisableCloud(napi_env env, napi_callback_info info) +{ + LOGI("DisableCloud"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::ONE), static_cast(NARG_CNT::TWO))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr accoutId; + + tie(succ, accoutId, std::ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string accoutIdStr(accoutId.get()); + + auto cbExec = [accoutIdStr]() -> NError { + int32_t result = CloudSyncManager::GetInstance().DisableCloud(accoutIdStr); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + return NError(ERRNO_NOERR); + }; + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + std::string procedureName = "DisableCloud"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::TWO)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + + +bool ParseSwitches(napi_env env, napi_value object, SwitchDataObj &data) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, object, &valueType); + if (valueType != napi_object) { + LOGE("ParseSwitches failed, not napi object"); + return false; + } + napi_value bundleNameArr = nullptr; + napi_get_property_names(env, object, &bundleNameArr); + uint32_t bundleNameNum = 0; + napi_get_array_length(env, bundleNameArr, &bundleNameNum); + for (uint32_t i = 0; i < bundleNameNum; ++i) { + napi_value item = nullptr; + napi_get_element(env, bundleNameArr, i, &item); + std::unique_ptr bundleId; + bool succ = false; + tie(succ, bundleId, std::ignore) = NVal(env, item).ToUTF8String(); + if (!succ) { + LOGE("fail to get string"); + return false; + } + + napi_value val = nullptr; + napi_get_named_property(env, object, bundleId.get(), &val); + bool switchVal = false; + tie(succ, switchVal) = NVal(env, val).ToBool(); + if (!succ) { + LOGE("fail to get switchVal"); + return false; + } + data.switchData.emplace(bundleId.get(), switchVal); + } + return true; +} + +napi_value EnableCloud(napi_env env, napi_callback_info info) +{ + LOGI("EnableCloud"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + + bool succ = false; + std::unique_ptr accoutId; + + tie(succ, accoutId, std::ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + SwitchDataObj switchData; + if (!ParseSwitches(env, funcArg[(int)NARG_POS::SECOND], switchData)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + string accoutIdStr(accoutId.get()); + + auto cbExec = [accoutIdStr, switchData]() -> NError { + int32_t result = CloudSyncManager::GetInstance().EnableCloud(accoutIdStr, switchData); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + return NError(ERRNO_NOERR); + }; + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + std::string procedureName = "EnableCloud"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +bool ParseAppActions(napi_env env, napi_value object, CleanOptions &cleanOptions) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, object, &valueType); + if (valueType != napi_object) { + LOGE("ParseAppActions failed, not napi object"); + return false; + } + napi_value bundleNameArr = nullptr; + napi_get_property_names(env, object, &bundleNameArr); + uint32_t bundleNameNum = 0; + napi_get_array_length(env, bundleNameArr, &bundleNameNum); + for (uint32_t i = 0; i < bundleNameNum; ++i) { + napi_value item = nullptr; + napi_get_element(env, bundleNameArr, i, &item); + std::unique_ptr bundleNameStr = nullptr; + bool resGetKey = false; + tie(resGetKey, bundleNameStr, ignore) = NVal(env, item).ToUTF8String(); + if (!resGetKey) { + LOGE("Fail to get string"); + return false; + } + napi_value actionObj = nullptr; + napi_get_named_property(env, object, bundleNameStr.get(), &actionObj); + int appActionsVal = 0; + bool resGetValue = false; + tie(resGetValue, appActionsVal) = NVal(env, actionObj).ToInt32(); + if (!resGetValue) { + LOGE("Fail to get appActionsVal"); + return false; + } + cleanOptions.appActionsData.emplace(string(bundleNameStr.get()).c_str(), appActionsVal); + } + return true; +} +napi_value Clean(napi_env env, napi_callback_info info) +{ + LOGI("Clean"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { + NError(E_PARAMS).ThrowErr(env, "Number of arguments unmatched"); + return nullptr; + } + std::unique_ptr accoutId = nullptr; + bool succ = false; + tie(succ, accoutId, ignore) = NVal(env, funcArg[(int)NARG_POS::FIRST]).ToUTF8String(); + if (!succ) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + CleanOptions cleanOptions {}; + if (!ParseAppActions(env, funcArg[(int)NARG_POS::SECOND], cleanOptions)) { + NError(E_PARAMS).ThrowErr(env); + return nullptr; + } + + std::string accoutIdStr(accoutId.get()); + auto cbExec = [accoutIdStr, cleanOptions]() -> NError { + int32_t result = CloudSyncManager::GetInstance().Clean(accoutIdStr, cleanOptions); + if (result == E_PERMISSION_DENIED || result == E_PERMISSION_SYSTEM) { + return result == E_PERMISSION_DENIED? NError(Convert2JsErrNum(E_PERMISSION_DENIED)) : + NError(Convert2JsErrNum(E_PERMISSION_SYSTEM)); + } + return NError(ERRNO_NOERR); + }; + auto cbComplete = [](napi_env env, NError err) -> NVal { + if (err) { + return { env, err.GetNapiErr(env) }; + } + return { NVal::CreateUndefined(env) }; + }; + + std::string procedureName = "Clean"; + auto asyncWork = GetPromiseOrCallBackWork(env, funcArg, static_cast(NARG_CNT::THREE)); + return asyncWork == nullptr ? nullptr : asyncWork->Schedule(procedureName, cbExec, cbComplete).val_; +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.h b/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.h new file mode 100644 index 0000000..3e60af8 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_n_exporter.h @@ -0,0 +1,29 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_N_EXPORTER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_N_EXPORTER_H + +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::CloudSync { +napi_value ChangeAppCloudSwitch(napi_env env, napi_callback_info info); +napi_value Clean(napi_env env, napi_callback_info info); +napi_value NotifyDataChange(napi_env env, napi_callback_info info); +napi_value NotifyEventChange(napi_env env, napi_callback_info info); +napi_value EnableCloud(napi_env env, napi_callback_info info); +napi_value DisableCloud(napi_env env, napi_callback_info info); +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_NAPI_H diff --git a/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.cpp b/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.cpp new file mode 100644 index 0000000..c0b3325 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.cpp @@ -0,0 +1,72 @@ +/* + * 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 "cloud_sync_manager_napi.h" +#include "cloud_sync_manager_n_exporter.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace FileManagement::LibN; +/*********************************************** + * Module export and register + ***********************************************/ + +static napi_value Init(napi_env env, napi_value exports) +{ + CloudSyncManagerExport(env, exports); + InitENumACtions(env, exports); + + return exports; +} + +void CloudSyncManagerExport(napi_env env, napi_value exports) +{ + static napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("changeAppCloudSwitch", ChangeAppCloudSwitch), + DECLARE_NAPI_FUNCTION("clean", Clean), + DECLARE_NAPI_FUNCTION("notifyDataChange", NotifyDataChange), + DECLARE_NAPI_FUNCTION("enableCloud", EnableCloud), + DECLARE_NAPI_FUNCTION("disableCloud", DisableCloud), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +void InitENumACtions(napi_env env, napi_value exports) +{ + char propertyName[] = "Action"; + napi_value actionObj = nullptr; + napi_create_object(env, &actionObj); + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("RETAIN_DATA", NVal::CreateInt32(env, (int32_t)Action::RETAIN_DATA).val_), + DECLARE_NAPI_STATIC_PROPERTY("CLEAR_DATA", NVal::CreateInt32(env, (int32_t)Action::CLEAR_DATA).val_), + }; + napi_define_properties(env, actionObj, sizeof(desc) / sizeof(desc[0]), desc); + napi_set_named_property(env, exports, propertyName, actionObj); +} + +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "file.cloudSyncManager", + .nm_priv = ((void *)0), + .reserved = {0} +}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.h b/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.h new file mode 100644 index 0000000..8484d12 --- /dev/null +++ b/cloud_file/interfaces/kits/js/cloudsyncmanager/cloud_sync_manager_napi.h @@ -0,0 +1,30 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_NAPI_H +#define OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_NAPI_H + +#include "filemgmt_libn.h" + +enum Action { + RETAIN_DATA = 0, + CLEAR_DATA +}; + +namespace OHOS::FileManagement::CloudSync { +void CloudSyncManagerExport(napi_env env, napi_value exports); +void InitENumACtions(napi_env env, napi_value exports); +} // namespace OHOS::FileManagement::CloudSync +#endif // OHOS_FILEMGMT_CLOUD_SYNC_MANAGER_NAPI_H \ No newline at end of file diff --git a/cloud_file/services/5204.json b/cloud_file/services/5204.json new file mode 100644 index 0000000..08be0c8 --- /dev/null +++ b/cloud_file/services/5204.json @@ -0,0 +1,97 @@ +{ + "process": "cloudfileservice", + "systemability": [ + { + "name": 5204, + "libpath": "libcloudsync_sa.z.so", + "run-on-create": false, + "distributed": true, + "dump-level": 1, + "start-on-demand": { + "timedevent": [ + { + "name": "loopevent", + "value": "21600" + } + ], + "commonevent": [ + { + "name": "usual.event.wifi.CONN_STATE", + "value": "4", + "conditions": [ + { + "eventId": "param", + "name": "persist.kernel.cloudsync.network_unavailable", + "value": "true" + } + ] + }, + { + "name": "usual.event.SCREEN_OFF", + "conditions": [ + { + "eventId": "commonevent", + "name": "usual.event.wifi.CONN_STATE", + "value": "4" + }, + { + "eventId": "commonevent", + "name": "usual.event.POWER_CONNECTED" + } + ] + }, + { + "name": "usual.event.SCREEN_OFF", + "conditions": [ + { + "eventId": "commonevent", + "name": "persist.kernel.cloudsync.screen_off_enable_download", + "value": "true" + } + ] + }, + { + "name": "usual.event.wifi.CONN_STATE", + "value": "4", + "conditions": [ + { + "eventId": "commonevent", + "name": "usual.event.SCREEN_OFF" + }, + { + "eventId": "commonevent", + "name": "usual.event.POWER_CONNECTED" + } + ] + }, + { + "name": "usual.event.POWER_CONNECTED", + "conditions": [ + { + "eventId": "commonevent", + "name": "usual.event.wifi.CONN_STATE", + "value": "4" + } + ] + }, + { + "name": "usual.event.BATTERY_OKAY", + "conditions": [ + { + "eventId": "param", + "name": "persist.kernel.cloudsync.battery_level_low", + "value": "true" + } + ] + }, + { + "name": "usual.event.USER_UNLOCKED" + }, + { + "name": "usual.event.PACKAGE_REMOVED" + } + ] + } + } + ] +} diff --git a/cloud_file/services/5205.json b/cloud_file/services/5205.json new file mode 100644 index 0000000..e3f4b52 --- /dev/null +++ b/cloud_file/services/5205.json @@ -0,0 +1,12 @@ +{ + "process": "cloudfiledaemon", + "systemability": [ + { + "name": 5205, + "libpath": "libcloudfiledaemon.z.so", + "run-on-create": true, + "distributed": false, + "dump-level": 1 + } + ] +} \ No newline at end of file diff --git a/cloud_file/services/BUILD.gn b/cloud_file/services/BUILD.gn new file mode 100644 index 0000000..4494da7 --- /dev/null +++ b/cloud_file/services/BUILD.gn @@ -0,0 +1,51 @@ +# Copyright (C) 2021-2025 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. +import("//build/ohos.gni") +import("//build/ohos/sa_profile/sa_profile.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_sa_profile("distributedfile_sa_profile") { + sources = [ "5204.json" ] + if (cloud_file_feature_enable_cloud_adapter) { + sources += [ "5205.json" ] + } + part_name = "cloud_file" +} + +ohos_prebuilt_etc("cloudfileservice_etc") { + source = "cloudfileservice.cfg" + relative_install_dir = "init" + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_prebuilt_etc("cloudfiledaemon_etc") { + source = "cloudfiledaemon.cfg" + relative_install_dir = "init" + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_prebuilt_etc("cloudsyncservice.para") { + source = "cloudsyncservice.para" + part_name = "cloud_file" + module_install_dir = "etc/param" + subsystem_name = "kernel" +} + +ohos_prebuilt_etc("cloudsyncservice.para.dac") { + source = "cloudsyncservice.para.dac" + part_name = "cloud_file" + module_install_dir = "etc/param" + subsystem_name = "kernel" +} diff --git a/cloud_file/services/clouddisk_database/BUILD.gn b/cloud_file/services/clouddisk_database/BUILD.gn new file mode 100644 index 0000000..e90e46f --- /dev/null +++ b/cloud_file/services/clouddisk_database/BUILD.gn @@ -0,0 +1,102 @@ +# Copyright (c) 2024 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +config("clouddisk_database_config") { + visibility = [ ":*" ] +} + +config("clouddisk_database_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner", + "${services_path}/cloudfiledaemon/include/cloud_disk", + ] +} + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("clouddisk_database") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + + sources = [ + "src/clouddisk_notify.cpp", + "src/clouddisk_notify_utils.cpp", + "src/clouddisk_rdb_transaction.cpp", + "src/clouddisk_rdb_utils.cpp", + "src/clouddisk_rdbstore.cpp", + "src/clouddisk_sync_helper.cpp", + "src/file_column.cpp", + ] + + configs += [ ":clouddisk_database_config" ] + public_configs = [ ":clouddisk_database_public_config" ] + + cflags = [ + "-Wall", + "-Werror", + "-Wno-unused-but-set-variable", + ] + + defines = [ + "LOG_DOMAIN=0xD00430B", + "LOG_TAG=\"CLOUDDISK_DATABASE\"", + ] + + deps = [ + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner_lite", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_single", + "json:nlohmann_json_static", + "libfuse:libfuse", + "preferences:native_preferences", + "relational_store:native_rdb", + ] + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_db_const.h b/cloud_file/services/clouddisk_database/include/clouddisk_db_const.h new file mode 100644 index 0000000..78bec97 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_db_const.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_DISK_SERVICE_DB_CONST_H +#define OHOS_CLOUD_DISK_SERVICE_DB_CONST_H + +#include +#include "clouddisk_type_const.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +//rdb +const std::string CLOUD_DISK_DATABASE_NAME = "clouddisk.db"; +//rdb version +const int32_t CLOUD_DISK_RDB_VERSION = 16; +enum { + VERSION_ADD_PARENT_CLOUD_ID_INDEX = 2, + VERSION_FIX_FILE_TRIGGER = 3, + VERSION_FIX_CREATE_AND_LOCAL_TRIGGER = 4, + VERSION_ADD_STATUS_ERROR_FAVORITE = 5, + VERSION_ADD_FILE_STATUS = 6, + VERSION_SET_FILE_STATUS_DEFAULT = 7, + VERSION_ADD_CHECK_FLAG = 8, + VERSION_ADD_ROOT_DIRECTORY = 9, + VERSION_FIX_SYNC_METATIME_TRIGGER = 10, + VERSION_FIX_RETRY_TRIGGER = 11, + VERSION_REMOVE_CLOUD_SYNC_FUNC_TRIGGER = 12, + VERSION_ADD_ATTRIBUTE = 13, + VERSION_ADD_THM_FLAG = 14, + VERSION_ADD_SRC_CLOUD_ID = 15, + VERSION_ADD_THM_SIZE = 16, +}; +// drive kit +const std::string DK_FILE_NAME = "fileName"; +const std::string DK_PARENT_CLOUD_ID = "parentFolder"; +const std::string DK_IS_DIRECTORY = "type"; + +struct NotifyData { + std::string uri; + bool isDir = false; + NotifyType type = NotifyType::NOTIFY_NONE; + bool isLocalOperation = false; + std::string extraUri = ""; +}; + +struct CacheNode { + std::string cloudId; + std::string parentCloudId; + std::string fileName; + std::string isDir; + bool isRecycled = false; +}; + +} // namespace CloudDisk +} // namespace FileManagement +} // namaspace OHOS + +#endif // OHOS_CLOUD_DISK_SERVICE_DB_CONST_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_notify.h b/cloud_file/services/clouddisk_database/include/clouddisk_notify.h new file mode 100644 index 0000000..537caf2 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_notify.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_DISK_SERVICE_NOTIFY_H +#define OHOS_CLOUD_DISK_SERVICE_NOTIFY_H + +#include +#include + +#include "clouddisk_notify_const.h" +#include "dataobs_mgr_client.h" +#include "nocopyable.h" + +namespace OHOS::FileManagement::CloudDisk { +using namespace std; +using ChangeInfo = OHOS::AAFwk::ChangeInfo; + +struct CacheNotifyInfo { + NotifyType notifyType; + mutable list uriList; + mutable list isDirList; +}; + +class CloudDiskNotify final : public NoCopyable { +public: + static CloudDiskNotify &GetInstance(); + void TryNotify(const NotifyParamDisk ¶mDisk, const ParamDiskOthers ¶mOthers = {}); + void TryNotifyService(const NotifyParamService ¶mService, const ParamServiceOther ¶mOthers = {}); + int32_t GetDeleteNotifyData(const vector &deleteIds, + vector ¬ifyDataList, + const ParamServiceOther ¶mOthers); + void AddNotify(const NotifyData ¬ifyData); + void NotifyChangeOuter(); + +private: + CloudDiskNotify() = default; + ~CloudDiskNotify() = default; + list nfList_; + mutex mutex_; +}; +} // namespace OHOS::FileManagement::CloudDisk + +#endif // OHOS_CLOUD_DISK_SERVICE_NOTIFY_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_notify_const.h b/cloud_file/services/clouddisk_database/include/clouddisk_notify_const.h new file mode 100644 index 0000000..f12e48e --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_notify_const.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_DISK_SERVICE_NOTIFY_CONST_H +#define OHOS_CLOUD_DISK_SERVICE_NOTIFY_CONST_H + +#include "clouddisk_db_const.h" +#include "cloud_disk_inode.h" +#include "values_bucket.h" +#include + +namespace OHOS::FileManagement::CloudDisk { + +const std::string TYPE_DIR_STR = "directory"; + +enum class NotifyOpsType : uint32_t { + DAEMON_SETXATTR = 0, + DAEMON_SETATTR, + DAEMON_RESTORE, + DAEMON_RECYCLE, + DAEMON_MKDIR, + DAEMON_RMDIR, + DAEMON_UNLINK, + DAEMON_RENAME, + DAEMON_WRITE, + SERVICE_INSERT, + SERVICE_UPDATE, + SERVICE_UPDATE_RECYCLE, + SERVICE_DELETE, + SERVICE_DELETE_BATCH, + OPS_NONE, +}; + +using FindCloudDiskInodeFunc = std::function(CloudDiskFuseData*, int64_t)>; +struct NotifyParamDisk { + CloudDiskFuseData *data = nullptr; + FindCloudDiskInodeFunc func; + NotifyOpsType opsType = NotifyOpsType::OPS_NONE; + std::shared_ptr inoPtr = nullptr; + fuse_ino_t ino = 0; + std::string name = ""; + fuse_ino_t newIno = 0; + std::string newName = ""; +}; + +struct ParamDiskOthers { + int32_t dirtyType = static_cast(DirtyType::TYPE_NO_NEED_UPLOAD); + bool isDir = false; + int fileDirty = CLOUD_DISK_FILE_UNKNOWN; +}; + +struct NotifyParamService { + NotifyOpsType opsType = NotifyOpsType::OPS_NONE; + std::string cloudId = ""; + NotifyType notifyType = NotifyType::NOTIFY_NONE; + CacheNode node; +}; + +struct ParamServiceOther { + int32_t userId = 0; + std::string bundleName; + std::vector notifyDataList = {}; +}; + +} // namespace OHOS::FileManagement::CloudDisk +#endif // OHOS_CLOUD_DISK_SERVICE_NOTIFY_CONST_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_notify_utils.h b/cloud_file/services/clouddisk_database/include/clouddisk_notify_utils.h new file mode 100644 index 0000000..61ff401 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_notify_utils.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_DISK_SERVICE_NOTIFY_UTILS_H +#define OHOS_CLOUD_DISK_SERVICE_NOTIFY_UTILS_H + +#include +#include + +#include "clouddisk_db_const.h" +#include "clouddisk_notify_const.h" + +namespace OHOS::FileManagement::CloudDisk { +using namespace std; +class CloudDiskNotifyUtils final { +public: + using FindCloudDiskInodeFunc = std::function(CloudDiskFuseData*, int64_t)>; + /* cloud disk */ + static int32_t GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, const fuse_ino_t &ino, + NotifyData ¬ifyData); + static int32_t GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, const fuse_ino_t &parent, + const string &name, + NotifyData ¬ifyData); + static int32_t GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + shared_ptr inoPtr, NotifyData ¬ifyData); + static int32_t GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + shared_ptr inoPtr, const string &name, NotifyData ¬ifyData); + /* cloud disk syncer */ + static int32_t GetCacheNode(const string &cloudId, CacheNode &cacheNode); + static void PutCacheNode(const string &cloudId, const CacheNode &cacheNode); + static int32_t + GetUriFromCache(const string &bundleName, const string &rootId, const CacheNode &cacheNode, string &uri); +private: + static const int32_t maxCacheCnt_ = 50; + static list> cacheList_; + static unordered_map>::iterator> cacheMap_; + static mutex cacheMutex_; + static string rootId_; +}; +} // namespace OHOS::FileManagement::CloudDisk + +#endif // OHOS_CLOUD_DISK_SERVICE_NOTIFY_UTILS_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_rdb_transaction.h b/cloud_file/services/clouddisk_database/include/clouddisk_rdb_transaction.h new file mode 100644 index 0000000..252d849 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_rdb_transaction.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUDISK_RDB_TRANSACTION_H +#define OHOS_CLOUDISK_RDB_TRANSACTION_H + +#include +#include +#include +#include + +#include "rdb_store.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +enum TRANS_DB_IDX { + PHOTO_RDB_IDX = 0, + CLOUDDISK_RDB_IDX = 1, +}; +static constexpr uint32_t RDB_NUM = 2; +/** + * This class is used for database transaction creation, commit, and rollback + * The usage of class is as follows: + * 1. initialize TransactionOperations object with a rdb instance + * (for example: TranscationOperations opt(rdb)) + * 2. After init opt, you need call Start() function to start transaction + * int32_t err = opt.Start(); + * if err != E_OK, transaction init failed + * 3. If you need to commit transaction, then use + * int32_t err = opt.Finish(); + * if err != E_OK, transaction commit failed and auto rollback + * 4. If TransactionOperations is destructed without successfully finish, it will be auto rollback + */ +class TransactionOperations { +public: + TransactionOperations(const std::shared_ptr &rdbStore); + ~TransactionOperations(); + std::pair> Start( + NativeRdb::Transaction::TransactionType type = NativeRdb::Transaction::EXCLUSIVE); + void Finish(); + +private: + int32_t BeginTransaction(NativeRdb::Transaction::TransactionType type); + int32_t TransactionCommit(); + int32_t TransactionRollback(); + + std::shared_ptr rdbStore_; + std::shared_ptr transaction_; + + bool isStart = false; + bool isFinish = false; +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUDDISK_RDB_TRANSACTION_H diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_rdb_utils.h b/cloud_file/services/clouddisk_database/include/clouddisk_rdb_utils.h new file mode 100644 index 0000000..9d00135 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_rdb_utils.h @@ -0,0 +1,51 @@ +/* + * 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 OHOS_CLOUD_DISK_SERVICE_RDB_UTILS_H +#define OHOS_CLOUD_DISK_SERVICE_RDB_UTILS_H + +#include + +#include "cloud_file_utils.h" +#include "clouddisk_db_const.h" +#include "rdb_store.h" + +namespace OHOS::FileManagement::CloudDisk { +class CloudDiskRdbUtils final { +public: + CloudDiskRdbUtils() = delete; + ~CloudDiskRdbUtils() = delete; + static int32_t GetInt(const std::string &key, int32_t &val, + const std::shared_ptr resultSet); + static int32_t GetLong(const std::string &key, int64_t &val, + const std::shared_ptr resultSet); + static int32_t GetString(const std::string &key, std::string &val, + const std::shared_ptr resultSet); + static int32_t ResultSetToFileInfo(const std::shared_ptr resultSet, CloudDiskFileInfo &info); + static int32_t ResultSetToFileInfos(const std::shared_ptr resultSet, + std::vector &infos); + static size_t FuseDentryAlignSize(const char *name); +}; + +#define RETURN_ON_ERR(ret) \ + do { \ + int32_t res = ret; \ + if ((res) != E_OK) { \ + return res; \ + } \ + } while (0) +} // namespace OHOS::FileManagement::CloudDisk + +#endif // OHOS_CLOUD_DISK_SERVICE_RDB_UTILS_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_rdbstore.h b/cloud_file/services/clouddisk_database/include/clouddisk_rdbstore.h new file mode 100644 index 0000000..2c8d1a4 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_rdbstore.h @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_DISK_SERVICE_RDBSTORE_H +#define OHOS_CLOUD_DISK_SERVICE_RDBSTORE_H + +#include "rdb_errno.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" +#include "rdb_store.h" +#include "rdb_store_config.h" + +#include "cloud_file_utils.h" +#include "clouddisk_db_const.h" +#include "file_column.h" +#include "meta_file.h" +#include "transaction.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { + +class CloudDiskRdbStore final { +public: + CloudDiskRdbStore(const std::string &bundleName, const int32_t &userId); + ~CloudDiskRdbStore(); + + int32_t RdbInit(); + std::shared_ptr GetRaw(); + + int32_t LookUp(const std::string &parentCloudId, const std::string &fileName, CloudDiskFileInfo &info); + int32_t GetAttr(const std::string &cloudId, CloudDiskFileInfo &info); + int32_t SetAttr(const std::string &fileName, const std::string &parentCloudId, const std::string &cloudId, + const unsigned long long &size); + int32_t ReadDir(const std::string &cloudId, std::vector &infos); + int32_t MkDir(const std::string &cloudId, const std::string &parentCloudId, + const std::string &directoryName, bool noNeedUpload); + int32_t Create(const std::string &cloudId, const std::string &parentCloudId, + const std::string &fileName, bool noNeedUpload); + int32_t Write(const std::string &fileName, const std::string &parentCloudId, const std::string &cloudId); + int32_t GetXAttr(const std::string &cloudId, const std::string &key, std::string &value, + const CacheNode &node = {}, const std::string &extAttrKey = ""); + int32_t SetXAttr(const std::string &cloudId, const std::string &key, const std::string &value, + const std::string &name = "", const std::string &parentCloudId = ""); + int32_t Rename(const std::string &oldParentCloudId, const std::string &oldFileName, + const std::string &newParentCloudId, const std::string &newFileName); + int32_t Unlink(const std::string &cloudId, const int32_t &noUpload); + int32_t RecycleSetXattr(const std::string &name, const std::string &parentCloudId, + const std::string &cloudId, const std::string &value); + int32_t LocationSetXattr(const std::string &name, const std::string &parentCloudId, + const std::string &cloudId, const std::string &value); + int32_t HasTHMSetXattr(const std::string &name, const std::string &key, + const std::string &cloudId, const std::string &value); + int32_t FavoriteSetXattr(const std::string &cloudId, const std::string &value); + int32_t LocationGetXattr(const std::string &name, const std::string &key, std::string &value, + const std::string &parentCloudId); + int32_t FavoriteGetXattr(const std::string &cloudId, const std::string &key, std::string &value); + int32_t FileStatusGetXattr(const std::string &cloudId, const std::string &key, std::string &value); + int32_t TimeRecycledGetXattr(const std::string &cloudId, const std::string &key, std::string &value); + int32_t GetHasChild(const std::string &cloudId, bool &hasChild); + int32_t GetRowId(const std::string &cloudId, int64_t &rowId); + int32_t GetParentCloudId(const std::string &cloudId, std::string &parentCloudId); + int32_t ExtAttributeSetXattr(const std::string &cloudId, const std::string &value, const std::string &key); + int32_t GetExtAttr(const std::string &cloudId, std::string &value, int32_t &position); + int32_t GetExtAttrValue(const std::string &cloudId, const std::string &key, std::string &value); + int32_t GetRecycleInfo(std::shared_ptr transaction, + const std::string &cloudId, int64_t &rowId, int32_t &position, std::string &attr); + int32_t GetSourcePath(const std::string &attr, const std::string &parentCloudId, std::string &sourcePath); + int32_t SourcePathSetValue(const std::string &cloudId, const std::string &attr, NativeRdb::ValuesBucket &setXattr); + int32_t HandleRecycleXattr(const std::string &name, const std::string &parentCloudId, const std::string &cloudId); + int32_t HandleRestoreXattr(const std::string &name, const std::string &parentCloudId, const std::string &cloudId); + + /* clouddisk syncer */ + int32_t GetDirtyType(const std::string &cloudId, int32_t &fileStatus); + int32_t GetCurNode(const std::string &cloudId, CacheNode &curNode); + int32_t GetParentNode(const std::string &parentCloudId, std::string &nextCloudId, std::string &fileName); + int32_t GetUriFromDB(const std::string &parentCloudId, std::string &uri); + int32_t GetNotifyUri(const CacheNode &cacheNode, std::string &uri); + int32_t GetNotifyData(const CacheNode &cacheNode, NotifyData ¬ifyData); + int32_t CheckRootIdValid(); + int32_t InsertCopyData(std::string srcCloudId, std::string destCloudId, std::string destParentCloudId, + std::shared_ptr resultSet); + int32_t CopyFile(std::string srcCloudId, std::string destCloudId, std::string bundleName, + const int userId, std::string destPath); + int32_t CreateDentryFile(MetaBase metaBase, std::string destParentCloudId); + int32_t GetSrcCloudId(const std::string &cloudId, std::string &srcCloudId); + int32_t UpdateTHMStatus(MetaBase &metabase, int32_t status); + + void DatabaseRestore(); + + static const int32_t BATCH_LIMIT_SIZE = 500; + +private: + void Stop(); + int32_t UnlinkSynced(const std::string &cloudId); + int32_t UnlinkLocal(const std::string &cloudId); + int32_t ReBuildDatabase(const std::string &databasePath); + int32_t CheckIsConflict(const std::string &name, const std::string &parentCloudId, std::string &newName); + int32_t RestoreUpdateRdb(const std::string &cloudId, const struct RestoreInfo &restoreInfo, + const NativeRdb::ValuesBucket &setXattr); + + std::shared_ptr rdbStore_; + NativeRdb::RdbStoreConfig config_{""}; + const int32_t CONNECT_SIZE = 8; + std::string bundleName_; + int32_t userId_{0}; + std::string tableName_ = FileColumn::FILES_TABLE; + std::mutex rdbMutex_; + std::mutex backupMutex_; + std::string rootId_; + static std::map illegalCharacter; +}; + +class CloudDiskDataCallBack : public NativeRdb::RdbOpenCallback { +public: + int32_t OnCreate(NativeRdb::RdbStore &rdbStore) override; + int32_t OnUpgrade(NativeRdb::RdbStore &rdbStore, int32_t oldVersion, int32_t newVersion) override; +}; + +#define RDBPTR_IS_NULLPTR(rdbStore_) \ + do { \ + if ((rdbStore_) == nullptr) { \ + LOGE("rdbStore_ is nullptr"); \ + return E_RDB; \ + } \ + } while (0) + +#define CLOUDID_IS_NULL(cloudId) \ + do { \ + if ((cloudId).empty()) { \ + LOGE("cloudId is null"); \ + return E_INVAL_ARG; \ + } \ + } while (0) +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS + +#endif // OHOS_CLOUD_DISK_SERVICE_RDBSTORE_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_sync_helper.h b/cloud_file/services/clouddisk_database/include/clouddisk_sync_helper.h new file mode 100644 index 0000000..f4d1ca7 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_sync_helper.h @@ -0,0 +1,62 @@ +/* + * 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 OHOS_CLOUD_DISK_SERVICE_SYNC_HELPER_H +#define OHOS_CLOUD_DISK_SERVICE_SYNC_HELPER_H + +#include + +#include +#include +#include + +#include "cloud_sync_manager_lite.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +constexpr int32_t SYNC_INTERVAL = 5000; +constexpr int32_t ARGS_SIZE = 2; +enum TRIGGER_SYNC_ARGS : int32_t { + ARG_USER_ID = 0, + ARG_BUNDLE_NAME +}; +class CloudDiskSyncHelper final { +public: + using TriggerSyncCallback = std::function; + static CloudDiskSyncHelper& GetInstance(); + CloudDiskSyncHelper(const CloudDiskSyncHelper&) = delete; + CloudDiskSyncHelper& operator=(const CloudDiskSyncHelper&) = delete; + void RegisterTriggerSync(const std::string &bundleName, const int32_t &userId); + +private: + CloudDiskSyncHelper(); + ~CloudDiskSyncHelper(); + void UnregisterRepeatingTriggerSync(const std::string &bundleName, const int32_t &userId); + void OnTriggerSyncCallback(const std::string &bundleName, const int32_t &userId); + + struct TriggerInfo { + uint32_t timerId{0}; + TriggerSyncCallback callback; + }; + std::unique_ptr timer_; + std::mutex triggerMapMutex_; + std::unordered_map> triggerInfoMap_; +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS + +#endif // OHOS_CLOUD_DISK_SERVICE_SYNC_HELPER_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/include/clouddisk_type_const.h b/cloud_file/services/clouddisk_database/include/clouddisk_type_const.h new file mode 100644 index 0000000..be85981 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/clouddisk_type_const.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_DISK_SERVICE_TYPE_CONST_H +#define OHOS_CLOUD_DISK_SERVICE_TYPE_CONST_H + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +enum class DirtyType : int32_t { + TYPE_SYNCED, + TYPE_NEW, + TYPE_MDIRTY, + TYPE_FDIRTY, + TYPE_DELETED, + TYPE_RETRY, + TYPE_NO_NEED_UPLOAD, + TYPE_COPY +}; + +enum class FileType : int32_t { + FILE_TYPE_APPLICATION = 1, + FILE_TYPE_AUDIO, + FILE_TYPE_IMAGE, + FILE_TYPE_VIDEO, + FILE_TYPE_TEXT +}; + +enum class OperationType : int64_t { + UNKNOWN_TYPE = 0, + NEW, + UPDATE, + COPY, + SAVE, + DELETE, + RESTORE, + MOVE, + RENAME, + OPEN +}; + +enum FileStatus { + TO_BE_UPLOADED = 0, + UPLOADING = 1, + UPLOAD_FAILURE = 2, + UPLOAD_SUCCESS = 3, + UNKNOW = 4 +}; + +enum class NotifyType : uint32_t { + NOTIFY_ADDED = 0, + NOTIFY_MODIFIED, + NOTIFY_DELETED, + NOTIFY_RENAMED, + NOTIFY_FILE_CHANGED, + NOTIFY_NONE, +}; + +enum class TrashOptType : int32_t { + RESTORE = 0, + RECYCLE, +}; + +constexpr int64_t SECOND_TO_MILLISECOND = 1e3; +constexpr int64_t MILLISECOND_TO_NANOSECOND = 1e6; +constexpr int32_t LOCAL = 1; +constexpr int32_t CLOUD = 2; +constexpr int32_t LOCAL_AND_CLOUD = 3; +constexpr int32_t FILE = 0; +constexpr int32_t DIRECTORY = 1; +constexpr int32_t MOVE_FILE_TIME_DAEMON = 1; +constexpr int32_t MOVE_FILE_TIME_SERVICE = 3; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS + +#endif // OHOS_CLOUD_DISK_SERVICE_TYPE_CONST_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/include/file_column.h b/cloud_file/services/clouddisk_database/include/file_column.h new file mode 100644 index 0000000..f4340a5 --- /dev/null +++ b/cloud_file/services/clouddisk_database/include/file_column.h @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2023-2024 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 OHOS_CLOUD_DISK_SERVICE_FILE_COLUMN_H +#define OHOS_CLOUD_DISK_SERVICE_FILE_COLUMN_H + +#include + +#include "clouddisk_db_const.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class FileColumn { +public: + // Local And Cloud + static const std::string CLOUD_ID; + static const std::string IS_DIRECTORY; + static const std::string FILE_NAME; + static const std::string PARENT_CLOUD_ID; + static const std::string FILE_SIZE; + static const std::string FILE_SHA256; + static const std::string FILE_TIME_ADDED; + static const std::string FILE_TIME_EDITED; + static const std::string FILE_TIME_RECYCLED; + static const std::string META_TIME_EDITED; + static const std::string DIRECTLY_RECYCLED; + static const std::string VERSION; + static const std::string OPERATE_TYPE; + static const std::string FILE_STATUS; + static const std::string ROW_ID; + static const std::string CHECK_FLAG; + static const std::string ROOT_DIRECTORY; + static const std::string ATTRIBUTE; + + // Only Local + static const std::string FILE_TIME_VISIT; + static const std::string SYNC_STATUS; + static const std::string POSITION; + static const std::string DIRTY_TYPE; + static const std::string THM_FLAG; + static const std::string LCD_FLAG; + static const std::string MIME_TYPE; + static const std::string FILE_TYPE; + static const std::string FILE_CATEGORY; + static const std::string IS_FAVORITE; + static const std::string NO_NEED_UPLOAD; + static const std::string SRC_CLOUD_ID; + static const std::string THM_SIZE; + static const std::string LCD_SIZE; + + // table name + static const std::string FILES_TABLE; + + // parentCloudId index + static const std::string PARENT_CLOUD_ID_INDEX; + + // create FileTable sql + static const std::string CREATE_FILE_TABLE; + + // create parentCloudId index + static const std::string CREATE_PARENT_CLOUD_ID_INDEX; + + //create IsFavorite + static const std::string ADD_IS_FAVORITE; + + //create FileStatus + static const std::string ADD_FILE_STATUS; + + //set FileStatus + static const std::string SET_FILE_STATUS_DEFAULT; + + //set CheckFlag + static const std::string ADD_CHECK_FLAG; + + // set attribute + static const std::string ADD_ATTRIBUTE; + + static const std::string ADD_THM_FLAG; + + static const std::string ADD_LCD_FLAG; + + static const std::string ADD_UPLOAD_FLAG; + + static const std::string ADD_THM_SIZE; + + static const std::string ADD_LCD_SIZE; + + // Add copy field + static const std::string ADD_SRC_CLOUD_ID; + + // Query FILES_TABLE for FileSystem + static const std::vector FILE_SYSTEM_QUERY_COLUMNS; + + // Query FILES_TABLE for Disk Push + static const std::vector DISK_CLOUD_SYNC_COLUMNS; + + static const std::vector LOCAL_COLUMNS; + + // Query pull info columns + static const std::vector PULL_QUERY_COLUMNS; + + // Query local info columns + static const std::vector DISK_ON_UPLOAD_COLUMNS; + + static const std::vector EXT_ATTR_QUERY_COLUMNS; + + // Query FILES_TABLE for CopyFile + static const std::vector DISK_CLOUD_FOR_COPY; +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_DISK_SERVICE_FILE_COLUMN_H \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/src/clouddisk_notify.cpp b/cloud_file/services/clouddisk_database/src/clouddisk_notify.cpp new file mode 100644 index 0000000..21abf17 --- /dev/null +++ b/cloud_file/services/clouddisk_database/src/clouddisk_notify.cpp @@ -0,0 +1,499 @@ +/* + * Copyright (c) 2024 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 "clouddisk_notify.h" +#include "clouddisk_notify_utils.h" +#include "clouddisk_rdbstore.h" +#include "dfs_error.h" +#include "ffrt_inner.h" +#include "file_column.h" +#include "securec.h" +#include "uri.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudDisk { +const string BUNDLENAME_FLAG = ""; +const string CLOUDDISK_URI_PREFIX = "file:///data/storage/el2/cloud"; +const string BACKFLASH = "/"; +const string RECYCLE_BIN = ".trash"; +constexpr uint32_t MAX_NOTIFY_LIST_SIZE = 32; +constexpr size_t MNOTIFY_TIME_INTERVAL = 500; +static pair> cacheRdbStore("", nullptr); +std::mutex cacheRdbMutex; + +CloudDiskNotify &CloudDiskNotify::GetInstance() +{ + static CloudDiskNotify instance_; + return instance_; +} + +static shared_ptr GetRdbStore(const string &bundleName, int32_t userId) +{ + std::lock_guard lock(cacheRdbMutex); + string storeKey = bundleName + to_string(userId); + if (cacheRdbStore.first == storeKey) { + return cacheRdbStore.second; + } + cacheRdbStore.first = storeKey; + cacheRdbStore.second = make_shared(bundleName, userId); + return cacheRdbStore.second; +} + +static int32_t GetTrashNotifyData(const NotifyParamDisk ¶mDisk, NotifyData ¬ifyData) +{ + if (paramDisk.inoPtr == nullptr) { + return E_INVAL_ARG; + } + string realPrefix = CLOUDDISK_URI_PREFIX; + realPrefix.replace(CLOUDDISK_URI_PREFIX.find(BUNDLENAME_FLAG), BUNDLENAME_FLAG.length(), + paramDisk.inoPtr->bundleName); + notifyData.uri = realPrefix + BACKFLASH + RECYCLE_BIN + BACKFLASH + paramDisk.inoPtr->fileName; + return E_OK; +} + +static int32_t GetTrashNotifyData(const CacheNode &cacheNode, const ParamServiceOther ¶mOthers, + NotifyData ¬ifyData) +{ + string realPrefix = CLOUDDISK_URI_PREFIX; + realPrefix.replace(CLOUDDISK_URI_PREFIX.find(BUNDLENAME_FLAG), BUNDLENAME_FLAG.length(), paramOthers.bundleName); + notifyData.uri = realPrefix + BACKFLASH + RECYCLE_BIN + BACKFLASH + cacheNode.fileName; + return E_OK; +} + +static int32_t TrashUriAddRowId(shared_ptr rdbStore, const string &cloudId, string &uri) +{ + int64_t rowId = 0; + int32_t ret = rdbStore->GetRowId(cloudId, rowId); + if (ret != E_OK) { + LOGE("Get rowId fail, ret: %{public}d", ret); + return ret; + } + uri = uri + "_" + std::to_string(rowId); + return E_OK; +} + +static int32_t GetDataInner(const NotifyParamDisk ¶mDisk, NotifyData ¬ifyData) +{ + int32_t ret; + if (paramDisk.inoPtr != nullptr) { + ret = CloudDiskNotifyUtils::GetNotifyData(paramDisk.data, paramDisk.func, + paramDisk.inoPtr, notifyData); + } else { + ret = CloudDiskNotifyUtils::GetNotifyData(paramDisk.data, paramDisk.func, + paramDisk.ino, notifyData); + } + return ret; +} + +static int32_t GetDataInnerWithName(const NotifyParamDisk ¶mDisk, NotifyData ¬ifyData) +{ + if (paramDisk.name.empty()) { + return E_INVAL_ARG; + } + int32_t ret; + if (paramDisk.inoPtr != nullptr) { + ret = CloudDiskNotifyUtils::GetNotifyData(paramDisk.data, paramDisk.func, + paramDisk.inoPtr, paramDisk.name, notifyData); + } else { + ret = CloudDiskNotifyUtils::GetNotifyData(paramDisk.data, paramDisk.func, + paramDisk.ino, paramDisk.name, notifyData); + } + return ret; +} + +static void HandleSetAttr(const NotifyParamDisk ¶mDisk) +{ + NotifyData notifyData; + if (GetDataInner(paramDisk, notifyData) != E_OK) { + return; + } + notifyData.type = NotifyType::NOTIFY_MODIFIED; + notifyData.isLocalOperation = true; + CloudDiskNotify::GetInstance().AddNotify(notifyData); +} + +static void HandleRecycleRestore(const NotifyParamDisk ¶mDisk) +{ + NotifyData trashNotifyData; + if (GetTrashNotifyData(paramDisk, trashNotifyData) != E_OK) { + LOGE("Get trash notify data fail"); + return; + } + shared_ptr rdbStore = GetRdbStore(paramDisk.inoPtr->bundleName, paramDisk.data->userId); + if (rdbStore == nullptr) { + LOGE("Get rdb store fail, bundleName: %{public}s", paramDisk.inoPtr->bundleName.c_str()); + return; + } + if (TrashUriAddRowId(rdbStore, paramDisk.inoPtr->cloudId, trashNotifyData.uri) != E_OK) { + return; + } + + NotifyData originNotifyData; + if (GetDataInner(paramDisk, originNotifyData) != E_OK) { + LOGE("Get origin notify data fail"); + return; + } + + NotifyData notifyData; + notifyData.type = NotifyType::NOTIFY_RENAMED; + notifyData.isDir = originNotifyData.isDir; + + if (paramDisk.opsType == NotifyOpsType::DAEMON_RECYCLE) { + notifyData.uri = trashNotifyData.uri; + notifyData.extraUri = originNotifyData.uri; + } + if (paramDisk.opsType == NotifyOpsType::DAEMON_RESTORE) { + notifyData.uri = originNotifyData.uri; + notifyData.extraUri = trashNotifyData.uri; + } + notifyData.isLocalOperation = true; + CloudDiskNotify::GetInstance().AddNotify(notifyData); +} + +static void HandleWrite(const NotifyParamDisk ¶mDisk, const ParamDiskOthers ¶mOthers) +{ + NotifyData notifyData; + if (GetDataInner(paramDisk, notifyData) != E_OK) { + return; + } + + if (paramOthers.dirtyType == static_cast(DirtyType::TYPE_NO_NEED_UPLOAD)) { + notifyData.type = NotifyType::NOTIFY_ADDED; + } + if (paramOthers.fileDirty == CLOUD_DISK_FILE_WRITE) { + notifyData.type = NotifyType::NOTIFY_FILE_CHANGED; + } + notifyData.isLocalOperation = true; + CloudDiskNotify::GetInstance().AddNotify(notifyData); +} + +static void HandleMkdir(const NotifyParamDisk ¶mDisk) +{ + NotifyData notifyData; + if (GetDataInnerWithName(paramDisk, notifyData) != E_OK) { + return; + } + notifyData.type = NotifyType::NOTIFY_ADDED; + notifyData.isDir = true; + notifyData.isLocalOperation = true; + CloudDiskNotify::GetInstance().AddNotify(notifyData); +} + +static void HandleUnlink(const NotifyParamDisk ¶mDisk) +{ + NotifyData notifyData; + if (GetDataInnerWithName(paramDisk, notifyData) != E_OK) { + return; + } + notifyData.type = NotifyType::NOTIFY_DELETED; + notifyData.isDir = paramDisk.opsType == NotifyOpsType::DAEMON_RMDIR; + notifyData.isLocalOperation = true; + CloudDiskNotify::GetInstance().AddNotify(notifyData); +} + +static void HandleRename(const NotifyParamDisk ¶mDisk, const ParamDiskOthers ¶mOthers) +{ + NotifyData oldNotifyData; + NotifyData newNotifyData; + int32_t ret = CloudDiskNotifyUtils::GetNotifyData(paramDisk.data, paramDisk.func, paramDisk.ino, + paramDisk.name, oldNotifyData); + if (ret != E_OK) { + LOGE("get notify data fail, name: %{public}s", GetAnonyString(paramDisk.name).c_str()); + return; + } + ret = CloudDiskNotifyUtils::GetNotifyData(paramDisk.data, paramDisk.func, paramDisk.newIno, + paramDisk.newName, newNotifyData); + if (ret != E_OK) { + LOGE("get new notify data fail, name: %{public}s", GetAnonyString(paramDisk.newName).c_str()); + return; + } + NotifyData notifyData; + notifyData.uri = newNotifyData.uri; + notifyData.extraUri = oldNotifyData.uri; + notifyData.isDir = paramOthers.isDir; + notifyData.type = NotifyType::NOTIFY_RENAMED; + notifyData.isLocalOperation = true; + CloudDiskNotify::GetInstance().AddNotify(notifyData); +} + +void CloudDiskNotify::TryNotify(const NotifyParamDisk ¶mDisk, const ParamDiskOthers ¶mOthers) +{ + switch (paramDisk.opsType) { + case NotifyOpsType::DAEMON_SETATTR: + case NotifyOpsType::DAEMON_SETXATTR: + HandleSetAttr(paramDisk); + break; + case NotifyOpsType::DAEMON_RECYCLE: + case NotifyOpsType::DAEMON_RESTORE: + HandleRecycleRestore(paramDisk); + break; + case NotifyOpsType::DAEMON_MKDIR: + HandleMkdir(paramDisk); + break; + case NotifyOpsType::DAEMON_RMDIR: + case NotifyOpsType::DAEMON_UNLINK: + HandleUnlink(paramDisk); + break; + case NotifyOpsType::DAEMON_RENAME: + HandleRename(paramDisk, paramOthers); + break; + case NotifyOpsType::DAEMON_WRITE: + HandleWrite(paramDisk, paramOthers); + break; + default: + LOGE("bad ops, opsType: %{public}d", paramDisk.opsType); + break; + } +} + +static void HandleInsert(const NotifyParamService ¶mService, const ParamServiceOther ¶mOthers) +{ + shared_ptr rdbStore = GetRdbStore(paramOthers.bundleName, paramOthers.userId); + if (rdbStore == nullptr) { + LOGE("Get rdb store fail, bundleName: %{public}s", paramOthers.bundleName.c_str()); + return; + } + NotifyData notifyData; + int32_t ret; + if (paramService.node.isRecycled) { + ret = GetTrashNotifyData(paramService.node, paramOthers, notifyData); + if (TrashUriAddRowId(rdbStore, paramService.cloudId, notifyData.uri) != E_OK) { + return; + } + notifyData.isDir = paramService.node.isDir == TYPE_DIR_STR; + } else { + ret = rdbStore->GetNotifyData(paramService.node, notifyData); + } + if (ret == E_OK) { + notifyData.type = NotifyType::NOTIFY_ADDED; + CloudDiskNotify::GetInstance().AddNotify(notifyData); + } +} + +static void HandleUpdate(const NotifyParamService ¶mService, const ParamServiceOther ¶mOthers) +{ + shared_ptr rdbStore = GetRdbStore(paramOthers.bundleName, paramOthers.userId); + if (rdbStore == nullptr) { + LOGE("Get rdb store fail, bundleName: %{public}s", paramOthers.bundleName.c_str()); + return; + } + NotifyData inNotifyData; + NotifyData notifyData; + CacheNode curNode{paramService.cloudId}; + if (rdbStore->GetCurNode(paramService.cloudId, curNode) == E_OK && + rdbStore->GetNotifyUri(curNode, notifyData.uri) == E_OK) { + notifyData.type = NotifyType::NOTIFY_MODIFIED; + notifyData.isDir = curNode.isDir == TYPE_DIR_STR; + if (paramService.notifyType == NotifyType::NOTIFY_NONE && + rdbStore->GetNotifyData(paramService.node, inNotifyData) == E_OK) { + if (inNotifyData.uri != notifyData.uri) { + notifyData.type = NotifyType::NOTIFY_DELETED; + inNotifyData.type = NotifyType::NOTIFY_RENAMED; + } + } + } + CloudDiskNotify::GetInstance().AddNotify(notifyData); + CloudDiskNotify::GetInstance().AddNotify(inNotifyData); +} + +static void HandleUpdateRecycle(const NotifyParamService ¶mService, const ParamServiceOther ¶mOthers) +{ + shared_ptr rdbStore = GetRdbStore(paramOthers.bundleName, paramOthers.userId); + if (rdbStore == nullptr) { + LOGE("Get rdb store fail, bundleName: %{public}s", paramOthers.bundleName.c_str()); + return; + } + NotifyData trashNotifyData; + GetTrashNotifyData(paramService.node, paramOthers, trashNotifyData); + if (TrashUriAddRowId(rdbStore, paramService.cloudId, trashNotifyData.uri) != E_OK) { + return; + } + + NotifyData originNotifyData; + if (rdbStore->GetNotifyData(paramService.node, originNotifyData) != E_OK) { + LOGE("Get origin notify data fail"); + return; + } + trashNotifyData.isDir = paramService.node.isDir == TYPE_DIR_STR; + originNotifyData.isDir = trashNotifyData.isDir; + if (paramService.node.isRecycled) { + trashNotifyData.type = NotifyType::NOTIFY_ADDED; + originNotifyData.type = NotifyType::NOTIFY_DELETED; + } else { + trashNotifyData.type = NotifyType::NOTIFY_DELETED; + originNotifyData.type = NotifyType::NOTIFY_ADDED; + } + CloudDiskNotify::GetInstance().AddNotify(trashNotifyData); + CloudDiskNotify::GetInstance().AddNotify(originNotifyData); +} + +static void HandleDelete(const NotifyParamService ¶mService, const ParamServiceOther ¶mOthers) +{ + if (paramService.cloudId.empty()) { + NotifyData notifyData{"", false, NotifyType::NOTIFY_DELETED}; + notifyData.uri = CLOUDDISK_URI_PREFIX; + notifyData.uri.replace(CLOUDDISK_URI_PREFIX.find(BUNDLENAME_FLAG), BUNDLENAME_FLAG.length(), + paramOthers.bundleName); + notifyData.isDir = true; + CloudDiskNotify::GetInstance().AddNotify(notifyData); + } else { + for (auto notifyData : (paramOthers.notifyDataList)) { + CloudDiskNotify::GetInstance().AddNotify(notifyData); + } + } +} + +static void HandleDeleteBatch(const NotifyParamService ¶mService, const ParamServiceOther ¶mOthers) +{ + for (auto notifyData : (paramOthers.notifyDataList)) { + CloudDiskNotify::GetInstance().AddNotify(notifyData); + } +} + +void CloudDiskNotify::TryNotifyService(const NotifyParamService ¶mService, const ParamServiceOther ¶mOthers) +{ + switch (paramService.opsType) { + case NotifyOpsType::SERVICE_INSERT: + HandleInsert(paramService, paramOthers); + break; + case NotifyOpsType::SERVICE_UPDATE: + HandleUpdate(paramService, paramOthers); + break; + case NotifyOpsType::SERVICE_UPDATE_RECYCLE: + HandleUpdateRecycle(paramService, paramOthers); + break; + case NotifyOpsType::SERVICE_DELETE: + HandleDelete(paramService, paramOthers); + break; + case NotifyOpsType::SERVICE_DELETE_BATCH: + HandleDeleteBatch(paramService, paramOthers); + break; + default: + LOGE("bad ops, opsType: %{public}d", paramService.opsType); + break; + } +} + +int32_t CloudDiskNotify::GetDeleteNotifyData(const vector &deleteIds, + vector ¬ifyDataList, + const ParamServiceOther ¶mOthers) +{ + shared_ptr rdbStore = GetRdbStore(paramOthers.bundleName, paramOthers.userId); + if (rdbStore == nullptr) { + LOGE("Get rdb store fail, bundleName: %{public}s", paramOthers.bundleName.c_str()); + return E_RDB; + } + for (auto deleteId : deleteIds) { + NotifyData notifyData{"", false, NotifyType::NOTIFY_DELETED}; + string cloudId = static_cast(deleteId); + CacheNode curNode{cloudId}; + if (rdbStore->GetCurNode(cloudId, curNode) == E_OK && rdbStore->GetNotifyUri(curNode, notifyData.uri) == E_OK) { + notifyData.isDir = curNode.isDir == TYPE_DIR_STR; + notifyDataList.push_back(notifyData); + } + } + return E_OK; +} + +void CloudDiskNotify::AddNotify(const NotifyData ¬ifyData) +{ + LOGD("push cur notify into list type: %{public}d, uri: %{public}s, isDir: %{public}d", notifyData.type, + GetAnonyString(notifyData.uri).c_str(), notifyData.isDir); + if (notifyData.type == NotifyType::NOTIFY_NONE) { + return; + } + + auto notifyFunc = [notifyData] { + auto obsMgrClient = AAFwk::DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + LOGE("obsMgrClient is null"); + return; + } + Parcel parcel; + parcel.WriteUint32(1); + parcel.WriteBool(notifyData.isDir); + parcel.WriteBool(notifyData.isLocalOperation); + parcel.WriteString(notifyData.extraUri); + uintptr_t buf = parcel.GetData(); + if (parcel.GetDataSize() == 0) { + LOGE("parcel.getDataSize fail"); + return; + } + + auto *uBuf = new (std::nothrow) uint8_t[parcel.GetDataSize()]; + if (uBuf == nullptr) { + return; + } + int32_t ret = memcpy_s(uBuf, parcel.GetDataSize(), reinterpret_cast(buf), parcel.GetDataSize()); + if (ret != 0) { + LOGE("Parcel Data copy failed, err: %{public}d", ret); + delete[] uBuf; + return; + } + ChangeInfo changeInfo({static_cast(notifyData.type), {Uri(notifyData.uri)}, uBuf, + parcel.GetDataSize()}); + obsMgrClient->NotifyChangeExt(changeInfo); + delete[] uBuf; + }; + ffrt::thread(notifyFunc).detach(); +} + +void CloudDiskNotify::NotifyChangeOuter() +{ + LOGD("Start Notify Outer"); + list tmpNfList_; + { + lock_guard lock(mutex_); + if (nfList_.empty()) { + return; + } + nfList_.swap(tmpNfList_); + nfList_.clear(); + } + + auto obsMgrClient = AAFwk::DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + LOGE("obsMgrClient is null"); + return; + } + for (auto cacheNode = tmpNfList_.begin(); cacheNode != tmpNfList_.end(); ++cacheNode) { + Parcel parcel; + parcel.WriteUint32(static_cast(cacheNode->isDirList.size())); + for (auto isDir = cacheNode->isDirList.begin(); isDir != cacheNode->isDirList.end(); ++isDir) { + parcel.WriteBool(*isDir); + } + uintptr_t buf = parcel.GetData(); + if (parcel.GetDataSize() == 0) { + LOGE("parcel.getDataSize fail"); + return; + } + + auto *uBuf = new (std::nothrow) uint8_t[parcel.GetDataSize()]; + if (uBuf == nullptr) { + return; + } + int32_t ret = memcpy_s(uBuf, parcel.GetDataSize(), reinterpret_cast(buf), parcel.GetDataSize()); + if (ret != 0) { + LOGE("Parcel Data copy failed, err: %{public}d", ret); + delete[] uBuf; + return; + } + ChangeInfo changeInfo({static_cast(cacheNode->notifyType), cacheNode->uriList, uBuf, + parcel.GetDataSize()}); + obsMgrClient->NotifyChangeExt(changeInfo); + delete[] uBuf; + } +} +} // namespace OHOS::FileManagement::CloudDisk diff --git a/cloud_file/services/clouddisk_database/src/clouddisk_notify_utils.cpp b/cloud_file/services/clouddisk_database/src/clouddisk_notify_utils.cpp new file mode 100644 index 0000000..3c77afb --- /dev/null +++ b/cloud_file/services/clouddisk_database/src/clouddisk_notify_utils.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2024 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 "clouddisk_notify_utils.h" +#include "clouddisk_rdb_utils.h" +#include "file_column.h" +#include "cloud_pref_impl.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudDisk { +const uint32_t MAX_QUERY_TIMES = 1024; +const string BUNDLENAME_FLAG = ""; +const string CLOUDDISK_URI_PREFIX = "file:///data/storage/el2/cloud"; +const string BACKFLASH = "/"; +const string ROOT_CLOUD_ID = "rootId"; +const int32_t CloudDiskNotifyUtils::maxCacheCnt_; +list> CloudDiskNotifyUtils::cacheList_; +unordered_map>::iterator> CloudDiskNotifyUtils::cacheMap_; +mutex CloudDiskNotifyUtils::cacheMutex_; + +static bool isRoot(const fuse_ino_t &ino) +{ + return ino == FUSE_ROOT_ID; +} + +static int32_t GetUriRecursively(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + shared_ptr inoPtr, string &uri) +{ + string bundleName = inoPtr->bundleName; + string realPrefix = CLOUDDISK_URI_PREFIX; + realPrefix.replace(realPrefix.find(BUNDLENAME_FLAG), BUNDLENAME_FLAG.length(), bundleName); + uint32_t queryTimes = 0; + while (!isRoot(inoPtr->parent)) { + inoPtr = func(data, inoPtr->parent); + if (!inoPtr || inoPtr->fileName.empty()) { + break; + } + uri = inoPtr->fileName + BACKFLASH + uri; + queryTimes++; + if (uri.length() > PATH_MAX || queryTimes > MAX_QUERY_TIMES) { + return E_INVAL_ARG; + } + } + uri = realPrefix + BACKFLASH + uri; + LOGD("GetUriRecursively uri: %{public}s", GetAnonyString(uri).c_str()); + return E_OK; +} + +int32_t CloudDiskNotifyUtils::GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + const fuse_ino_t &ino, NotifyData ¬ifyData) +{ + if (isRoot(ino)) { + return E_INVAL_ARG; + } + auto inoPtr = func(data, ino); + if (inoPtr == nullptr) { + LOGE("inode not found"); + return E_INVAL_ARG; + } + notifyData.uri = inoPtr->fileName; + notifyData.isDir = inoPtr->stat.st_mode & S_IFDIR; + return GetUriRecursively(data, func, inoPtr, notifyData.uri); +} + +int32_t CloudDiskNotifyUtils::GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + const fuse_ino_t &parent, const string &name, NotifyData ¬ifyData) +{ + auto inoPtr = func(data, parent); + if (inoPtr == nullptr) { + LOGE("inode not found"); + return E_INVAL_ARG; + } + notifyData.uri = name; + if (!inoPtr->fileName.empty()) { + notifyData.uri = inoPtr->fileName + BACKFLASH + notifyData.uri; + } + return GetUriRecursively(data, func, inoPtr, notifyData.uri); +} + +int32_t CloudDiskNotifyUtils::GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + shared_ptr inoPtr, NotifyData ¬ifyData) +{ + if (inoPtr == nullptr) { + LOGE("inode not found"); + return E_INVAL_ARG; + } + notifyData.uri = inoPtr->fileName; + notifyData.isDir = inoPtr->stat.st_mode & S_IFDIR; + return GetUriRecursively(data, func, inoPtr, notifyData.uri); +} + +int32_t CloudDiskNotifyUtils::GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + shared_ptr pInoPtr, const string &name, NotifyData ¬ifyData) +{ + if (pInoPtr == nullptr) { + LOGE("inode not found"); + return E_INVAL_ARG; + } + notifyData.uri = name; + if (!pInoPtr->fileName.empty()) { + notifyData.uri = pInoPtr->fileName + BACKFLASH + notifyData.uri; + } + return GetUriRecursively(data, func, pInoPtr, notifyData.uri); +} + +int32_t CloudDiskNotifyUtils::GetCacheNode(const string &cloudId, CacheNode &cacheNode) +{ + lock_guard lock(cacheMutex_); + auto it = cacheMap_.find(cloudId); + if (it == cacheMap_.end()) { + LOGI("Not fount in cache, id: %{public}s", cloudId.c_str()); + return E_INVAL_ARG; + } + cacheList_.splice(cacheList_.begin(), cacheList_, it->second); + cacheNode = it->second->second; + return E_OK; +} + +void CloudDiskNotifyUtils::PutCacheNode(const string &cloudId, const CacheNode &cacheNode) +{ + if (cacheNode.isDir != TYPE_DIR_STR) { + return; + } + lock_guard lock(cacheMutex_); + auto it = cacheMap_.find(cloudId); + if (it != cacheMap_.end()) { + LOGD("update cache name: %{public}s", GetAnonyString(cacheNode.fileName).c_str()); + it->second->second = cacheNode; + cacheList_.splice(cacheList_.begin(), cacheList_, it->second); + return; + } + if (cacheMap_.size() == maxCacheCnt_) { + LOGI("upto max, delete last one"); + string deleteCloudId = cacheList_.back().first; + cacheList_.pop_back(); + cacheMap_.erase(deleteCloudId); + } + LOGD("insert to cache name: %{public}s", GetAnonyString(cacheNode.fileName).c_str()); + cacheList_.emplace_front(cloudId, cacheNode); + cacheMap_[cloudId] = cacheList_.begin(); +} + +int32_t CloudDiskNotifyUtils::GetUriFromCache(const string &bundleName, + const string &rootId, + const CacheNode &cacheNode, + string &uri) +{ + CacheNode tmpCacheNode; + PutCacheNode(cacheNode.cloudId, cacheNode); + uri = cacheNode.fileName; + tmpCacheNode = cacheNode; + int32_t ret; + while (tmpCacheNode.parentCloudId != rootId && tmpCacheNode.parentCloudId != ROOT_CLOUD_ID) { + ret = GetCacheNode(tmpCacheNode.parentCloudId, tmpCacheNode); + if (ret != E_OK) { + return ret; + } + uri = tmpCacheNode.fileName + BACKFLASH + uri; + } + string realPrefix = CLOUDDISK_URI_PREFIX; + realPrefix.replace(realPrefix.find(BUNDLENAME_FLAG), BUNDLENAME_FLAG.length(), bundleName); + uri = realPrefix + BACKFLASH + uri; + return E_OK; +} +} // namespace OHOS::FileManagement::CloudDisk \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/src/clouddisk_rdb_transaction.cpp b/cloud_file/services/clouddisk_database/src/clouddisk_rdb_transaction.cpp new file mode 100644 index 0000000..0088360 --- /dev/null +++ b/cloud_file/services/clouddisk_database/src/clouddisk_rdb_transaction.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2024 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 "clouddisk_rdb_transaction.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; + +constexpr int32_t E_HAS_DB_ERROR = -222; +constexpr int32_t E_OK = 0; +constexpr int32_t CREATE_TRANSATION_MAX_TRY_TIMES = 30; +constexpr int32_t COMMIT_MAX_TRY_TIMES = 3; +constexpr int32_t TRANSACTION_WAIT_INTERVAL = 50; + +TransactionOperations::TransactionOperations( + const shared_ptr &rdbStore) : rdbStore_(rdbStore) {} + +TransactionOperations::~TransactionOperations() +{ + if (isStart && !isFinish) { + LOGI("TransactionOperations::RollBack"); + TransactionRollback(); + } +} + +template +int32_t RetryTransaction(Func func, int maxAttempts, int waitTimeMs) +{ + int curTryTime = 0; + while (curTryTime < maxAttempts) { + int32_t errCode = func(); + if (errCode != NativeRdb::E_OK) { + curTryTime++; + LOGE("try %{public}d times...", curTryTime); + this_thread::sleep_for(chrono::milliseconds(waitTimeMs)); + continue; + } + return E_OK; + } + LOGE("Transaction operation still failed after try %{public}d times, abort.", maxAttempts); + return E_HAS_DB_ERROR; +} + +std::pair> TransactionOperations::Start( + NativeRdb::Transaction::TransactionType type) +{ + if (isStart || isFinish) { + LOGE("start transaction failed, transaction has been started."); + return make_pair(E_HAS_DB_ERROR, nullptr); + } + + LOGI("TransactionOperations::Start"); + int32_t errCode = BeginTransaction(type); + if (errCode == E_OK) { + isStart = true; + } + return make_pair(errCode, transaction_); +} + +void TransactionOperations::Finish() +{ + if (!isStart || isFinish) { + return; + } + + if (!isFinish) { + LOGI("TransactionOperations::Finish"); + int32_t ret = TransactionCommit(); + if (ret == E_OK) { + isFinish = true; + isStart = false; + transaction_.reset(); + return; + } + LOGE("TransactionCommit failed, errCode=%{public}d, try to rollback", ret); + ret = TransactionRollback(); + if (ret != E_OK) { + LOGE("TransactionRollback failed, errCode=%{public}d", ret); + } + } +} + +int32_t TransactionOperations::BeginTransaction(NativeRdb::Transaction::TransactionType type) +{ + if (rdbStore_ == nullptr) { + LOGE("Pointer rdbStore_ is nullptr. Maybe it didn't init successfully."); + return E_HAS_DB_ERROR; + } + LOGI("Start transaction"); + int curTryTime = 0; + while (curTryTime < CREATE_TRANSATION_MAX_TRY_TIMES) { + int32_t errCode = E_OK; + std::tie(errCode, transaction_) = rdbStore_->CreateTransaction(type); + if (errCode == NativeRdb::E_SQLITE_LOCKED || errCode == NativeRdb::E_DATABASE_BUSY || + errCode == NativeRdb::E_SQLITE_BUSY) { + curTryTime++; + LOGE("Sqlite database file is locked! try %{public}d times...", curTryTime); + this_thread::sleep_for(chrono::milliseconds(TRANSACTION_WAIT_INTERVAL)); + continue; + } else if (errCode != NativeRdb::E_OK) { + LOGE("Start Transaction failed, errCode=%{public}d", errCode); + return errCode; + } + if (transaction_ != nullptr) { + isStart = true; + return E_OK; + } + } + LOGE("RdbStore is still in transaction after try %{public}d times, abort.", CREATE_TRANSATION_MAX_TRY_TIMES); + return E_HAS_DB_ERROR; +} + +int32_t TransactionOperations::TransactionCommit() +{ + if (transaction_ == nullptr) { + return E_HAS_DB_ERROR; + } + LOGI("Try commit transaction"); + + return RetryTransaction( + [this]() { + return transaction_->Commit(); + }, COMMIT_MAX_TRY_TIMES, TRANSACTION_WAIT_INTERVAL); +} + +int32_t TransactionOperations::TransactionRollback() +{ + if (transaction_ == nullptr) { + return E_HAS_DB_ERROR; + } + LOGI("Try rollback transaction"); + + return RetryTransaction( + [this]() { + return transaction_->Rollback(); + }, COMMIT_MAX_TRY_TIMES, TRANSACTION_WAIT_INTERVAL); +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/src/clouddisk_rdb_utils.cpp b/cloud_file/services/clouddisk_database/src/clouddisk_rdb_utils.cpp new file mode 100644 index 0000000..cd0d44f --- /dev/null +++ b/cloud_file/services/clouddisk_database/src/clouddisk_rdb_utils.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2023-2024 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. + */ + +#define FUSE_USE_VERSION 34 + +#include "clouddisk_rdb_utils.h" + +#include + +#include "utils_log.h" +#include "dfs_error.h" +#include "clouddisk_db_const.h" +#include "file_column.h" +#include "result_set.h" + +namespace OHOS::FileManagement::CloudDisk { +using namespace std; +using namespace NativeRdb; + +static const int32_t LOCAL_ID_OFFSET = 100; +static const uint32_t STAT_MODE_REG = 0660; +static const uint32_t STAT_MODE_DIR = 0771; + +int32_t CloudDiskRdbUtils::GetInt(const string &key, int32_t &val, + const shared_ptr resultSet) +{ + if (resultSet == nullptr) { + LOGE("result set is nullptr"); + return E_RDB; + } + int32_t index; + int32_t err = resultSet->GetColumnIndex(key, index); + if (err != E_OK) { + LOGE("result set get column index err %{public}d", err); + return E_RDB; + } + err = resultSet->GetInt(index, val); + if (err != 0) { + LOGE("result set get int err %{public}d", err); + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskRdbUtils::GetLong(const string &key, int64_t &val, + const shared_ptr resultSet) +{ + if (resultSet == nullptr) { + LOGE("result set is nullptr"); + return E_RDB; + } + int32_t index; + int32_t err = resultSet->GetColumnIndex(key, index); + if (err != E_OK) { + LOGE("result set get column index err %{public}d", err); + return E_RDB; + } + err = resultSet->GetLong(index, val); + if (err != 0) { + LOGE("result set get int err %{public}d", err); + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskRdbUtils::GetString(const string &key, string &val, + const shared_ptr resultSet) +{ + if (resultSet == nullptr) { + LOGE("result set is nullptr"); + return E_RDB; + } + int32_t index; + int32_t err = resultSet->GetColumnIndex(key, index); + if (err != E_OK) { + LOGE("result set get column index err %{public}d", err); + return E_RDB; + } + err = resultSet->GetString(index, val); + if (err != 0) { + LOGE("result set get string err %{public}d", err); + return E_RDB; + } + return E_OK; +} + +static void FillFileInfo(const RowEntity &rowEntity, CloudDiskFileInfo &info) +{ + rowEntity.Get(FileColumn::FILE_NAME).GetString(info.name); + rowEntity.Get(FileColumn::CLOUD_ID).GetString(info.cloudId); + rowEntity.Get(FileColumn::PARENT_CLOUD_ID).GetString(info.parentCloudId); + int32_t int_variable; + rowEntity.Get(FileColumn::POSITION).GetInt(int_variable); + info.location = static_cast(int_variable); + int64_t long_variable; + rowEntity.Get(FileColumn::FILE_SIZE).GetLong(long_variable); + info.size = static_cast(long_variable); + rowEntity.Get(FileColumn::FILE_TIME_ADDED).GetLong(long_variable); + info.atime = static_cast(long_variable); + rowEntity.Get(FileColumn::META_TIME_EDITED).GetLong(long_variable); + info.ctime = static_cast(long_variable); + rowEntity.Get(FileColumn::FILE_TIME_EDITED).GetLong(long_variable); + info.mtime = static_cast(long_variable); + rowEntity.Get(FileColumn::IS_DIRECTORY).GetInt(int_variable); + info.IsDirectory = (int_variable == DIRECTORY); + info.mode = (info.IsDirectory) ? (S_IFDIR | STAT_MODE_DIR) : (S_IFREG | STAT_MODE_REG); + rowEntity.Get(FileColumn::ROW_ID).GetLong(long_variable); + info.localId = static_cast(long_variable) + LOCAL_ID_OFFSET; +} + +int32_t CloudDiskRdbUtils::ResultSetToFileInfo(const shared_ptr resultSet, + CloudDiskFileInfo &info) +{ + if (resultSet == nullptr) { + LOGE("result set is nullptr"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("result set to file info go to next row failed"); + return E_RDB; + } + RowEntity rowEntity; + if (resultSet->GetRow(rowEntity) != E_OK) { + LOGE("result set to file info get row failed"); + return E_RDB; + } + FillFileInfo(rowEntity, info); + return E_OK; +} + +size_t CloudDiskRdbUtils::FuseDentryAlignSize(const char *name) +{ + return fuse_add_direntry({}, nullptr, 0, name, nullptr, 0); +} + +int32_t CloudDiskRdbUtils::ResultSetToFileInfos(const shared_ptr resultSet, + vector &infos) +{ + if (resultSet == nullptr) { + LOGE("result set is nullptr"); + return E_RDB; + } + off_t nextOff = 0; + while (resultSet->GoToNextRow() == E_OK) { + CloudDiskFileInfo info; + GetString(FileColumn::FILE_NAME, info.name, resultSet); + int32_t isDirectory; + GetInt(FileColumn::IS_DIRECTORY, isDirectory, resultSet); + info.IsDirectory = (isDirectory == DIRECTORY); + info.mode = (info.IsDirectory) ? (S_IFDIR | STAT_MODE_DIR) : (S_IFREG | STAT_MODE_REG); + nextOff += FuseDentryAlignSize(info.name.c_str()); + info.nextOff = nextOff; + infos.emplace_back(info); + } + return E_OK; +} +} \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/src/clouddisk_rdbstore.cpp b/cloud_file/services/clouddisk_database/src/clouddisk_rdbstore.cpp new file mode 100644 index 0000000..60e7552 --- /dev/null +++ b/cloud_file/services/clouddisk_database/src/clouddisk_rdbstore.cpp @@ -0,0 +1,2428 @@ +/* + * Copyright (c) 2024 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 "clouddisk_rdbstore.h" + +#include +#include +#include +#include +#include + +#include "cloud_pref_impl.h" +#include "clouddisk_db_const.h" +#include "clouddisk_notify.h" +#include "clouddisk_notify_utils.h" +#include "clouddisk_rdb_transaction.h" +#include "clouddisk_rdb_utils.h" +#include "clouddisk_sync_helper.h" +#include "clouddisk_type_const.h" +#include "data_sync_const.h" +#include "dfs_error.h" +#include "directory_ex.h" +#include "file_column.h" +#include "ffrt_inner.h" +#include "nlohmann/json.hpp" +#include "parameter.h" +#include "parameters.h" +#include "rdb_errno.h" +#include "rdb_sql_utils.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudDisk { +using namespace std; +using namespace OHOS::NativeRdb; +using namespace CloudSync; + +enum XATTR_CODE { + ERROR_CODE = -1, + CLOUD_LOCATION = 1, + CLOUD_RECYCLE, + IS_FAVORITE, + FILE_SYNC_STATUS, + IS_EXT_ATTR, + HAS_THM, + TIME_RECYCLED, + RECYCLE_PATH, +}; +static constexpr int32_t LOOKUP_QUERY_LIMIT = 1; +static constexpr int32_t CHECK_QUERY_LIMIT = 2000; +static const uint32_t SET_STATE = 1; +static const uint32_t CANCEL_STATE = 0; +static const uint32_t MAX_FILE_NAME_SIZE = 246; +static const uint32_t MAX_QUERY_TIMES = 1024; +static const uint32_t STAT_MODE_DIR = 0771; +static const uint32_t STAT_MODE_FILE = 0771; +static const uint32_t STAT_MODE_REG = 0660; +const string BUNDLENAME_FLAG = ""; +const string CLOUDDISK_URI_PREFIX = "file:///data/storage/el2/cloud"; +const string BACKFLASH = "/"; +static const string RECYCLE_FILE_NAME = ".trash"; +static const string ROOT_CLOUD_ID = "rootId"; +static const std::string FILEMANAGER_KEY = "persist.kernel.bundle_name.filemanager"; +// srcPath only used in restore files +static const string SRC_PATH_KEY = "srcPath"; +static const string LOCAL_PATH_MNT_HMDFS = "/mnt/hmdfs/"; +static const string LOCAL_PATH_CLOUD_DATA = "/cloud/data/"; +static const string FILE_SCHEME = "file"; +static const int32_t DIRECTLY_RECYCLED_COPY = 4; +static const int32_t VERSION_COPY = 0; +static const int32_t FLAG_NOT_EXIST = 2; +static const int32_t FLAG_TO_BE_UPLOAD = 1; + +static const std::string CloudSyncTriggerFunc(const std::vector &args) +{ + size_t size = args.size(); + if (size != ARGS_SIZE) { + LOGE("CloudSyncTriggerFunc args size error, %{public}zu", size); + return ""; + } + int32_t userId = std::strtol(args[ARG_USER_ID].c_str(), nullptr, 0); + string bundleName = args[ARG_BUNDLE_NAME]; + LOGD("begin cloud sync trigger, bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId); + return ""; +} + +CloudDiskRdbStore::CloudDiskRdbStore(const std::string &bundleName, const int32_t &userId) + : bundleName_(bundleName), userId_(userId) +{ + RdbInit(); +} + +CloudDiskRdbStore::~CloudDiskRdbStore() +{ + Stop(); +} + +int32_t CloudDiskRdbStore::ReBuildDatabase(const string &databasePath) +{ + LOGI("database need to be rebuilded"); + int32_t errCode = RdbHelper::DeleteRdbStore(databasePath); + if (errCode != NativeRdb::E_OK) { + LOGE("Delete CloudDisk Database is failed, err = %{public}d", errCode); + return errCode; + } + errCode = 0; + CloudDiskDataCallBack rdbDataCallBack; + rdbStore_ = RdbHelper::GetRdbStore(config_, CLOUD_DISK_RDB_VERSION, rdbDataCallBack, errCode); + if (rdbStore_ == nullptr) { + LOGE("ReGetRdbStore is failed, userId_ = %{public}d, bundleName_ = %{public}s, errCode = %{public}d", + userId_, bundleName_.c_str(), errCode); + return errCode; + } + DatabaseRestore(); + return E_OK; +} + +int32_t CloudDiskRdbStore::RdbInit() +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return EBUSY; + } + LOGI("Init rdb store, userId_ = %{public}d, bundleName_ = %{public}s", userId_, bundleName_.c_str()); + string baseDir = "/data/service/el2/" + to_string(userId_) + "/hmdfs/cloudfile_manager/"; + string customDir = baseDir.append(system::GetParameter(FILEMANAGER_KEY, "")); + string name = CLOUD_DISK_DATABASE_NAME; + int32_t errCode = 0; + string databasePath = RdbSqlUtils::GetDefaultDatabasePath(customDir, CLOUD_DISK_DATABASE_NAME, errCode); + if (errCode != NativeRdb::E_OK) { + LOGE("Create Default Database Path is failed, errCode = %{public}d", errCode); + return E_PATH; + } + config_.SetName(name); + config_.SetPath(databasePath); + config_.SetReadConSize(CONNECT_SIZE); + config_.SetScalarFunction("cloud_sync_func", ARGS_SIZE, CloudSyncTriggerFunc); + errCode = 0; + CloudDiskDataCallBack rdbDataCallBack; + rdbStore_ = RdbHelper::GetRdbStore(config_, CLOUD_DISK_RDB_VERSION, rdbDataCallBack, errCode); + if (rdbStore_ == nullptr) { + LOGE("GetRdbStore is failed, userId_ = %{public}d, bundleName_ = %{public}s, errCode = %{public}d", + userId_, bundleName_.c_str(), errCode); + if (errCode == NativeRdb::E_SQLITE_CORRUPT) { + if (ReBuildDatabase(databasePath)) { + LOGE("clouddisk db image is malformed, ReBuild failed"); + } + } + return errCode; + } else if (errCode == NativeRdb::E_SQLITE_CORRUPT) { DatabaseRestore(); } + return E_OK; +} + +void CloudDiskRdbStore::Stop() +{ + if (rdbStore_ == nullptr) { + return; + } + rdbStore_ = nullptr; +} + +shared_ptr CloudDiskRdbStore::GetRaw() +{ + return rdbStore_; +} + +void CloudDiskRdbStore::DatabaseRestore() +{ + if (rdbStore_ == nullptr) { + LOGE("rdbStore_ is nullptr"); + return; + } + LOGI("clouddisk db image is malformed, need to restore"); + auto fileName = "/data/service/el2/" + to_string(userId_) + "/hmdfs/cloudfile_manager/" + + system::GetParameter(FILEMANAGER_KEY, "") + "/backup/clouddisk_backup.db"; + if (access(fileName.c_str(), F_OK) == 0) { + int32_t ret = -1; + { + lock_guard lock(backupMutex_); + ret = rdbStore_->Restore(fileName); + } + if (ret != 0) { + LOGE("cloudisk restore failed, ret %{public}d", ret); + } + } else { + LOGE("clouddisk backup db is not exist"); + } +} + +int32_t CloudDiskRdbStore::LookUp(const std::string &parentCloudId, + const std::string &fileName, CloudDiskFileInfo &info) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (fileName.empty() || parentCloudId.empty()) { + LOGE("look up parameters is invalid"); + return E_INVAL_ARG; + } + AbsRdbPredicates lookUpPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + lookUpPredicates + .EqualTo(FileColumn::PARENT_CLOUD_ID, parentCloudId)->And() + ->EqualTo(FileColumn::FILE_NAME, fileName)->And()->EqualTo(FileColumn::FILE_TIME_RECYCLED, "0")->And() + ->EqualTo(FileColumn::ROOT_DIRECTORY, bundleName_)->And() + ->NotEqualTo(FileColumn::DIRTY_TYPE, to_string(static_cast(DirtyType::TYPE_DELETED))); + lookUpPredicates.Limit(LOOKUP_QUERY_LIMIT); + auto resultSet = rdbStore_->QueryByStep(lookUpPredicates, FileColumn::FILE_SYSTEM_QUERY_COLUMNS); + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfo(move(resultSet), info); + if (ret != E_OK) { + LOGE("lookup file info is failed, ret %{public}d", ret); + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::GetAttr(const std::string &cloudId, CloudDiskFileInfo &info) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID) { + LOGE("getAttr parameter is invalid"); + return E_INVAL_ARG; + } + AbsRdbPredicates getAttrPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + getAttrPredicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(getAttrPredicates, FileColumn::FILE_SYSTEM_QUERY_COLUMNS); + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfo(move(resultSet), info); + if (ret != E_OK) { + LOGE("get file attr is failed, ret %{public}d", ret); + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::SetAttr(const std::string &fileName, const std::string &parentCloudId, + const std::string &cloudId, const unsigned long long &size) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty()) { + LOGE("cloudId is empty"); + return E_INVAL_ARG; + } + if (cloudId == ROOT_CLOUD_ID) { + LOGE("cloudId is rootId"); + return E_INVAL_ARG; + } + + ValuesBucket setAttr; + setAttr.PutLong(FileColumn::FILE_SIZE, static_cast(size)); + TransactionOperations rdbTransaction(rdbStore_); + auto [ret, transaction] = rdbTransaction.Start(); + if (ret != E_OK) { + LOGE("rdbstore begin transaction failed, ret = %{public}d", ret); + return ret; + } + int32_t changedRows = -1; + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + std::tie(ret, changedRows) = transaction->Update(setAttr, predicates); + if (ret != E_OK) { + LOGE("setAttr size fail, ret: %{public}d, changeRow is %{public}d", ret, changedRows); + return E_RDB; + } + + MetaBase metaBase(fileName, cloudId); + metaBase.size = size; + auto callback = [&metaBase] (MetaBase &m) { + m.size = metaBase.size; + }; + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId_, bundleName_, parentCloudId); + ret = metaFile->DoLookupAndUpdate(fileName, callback); + if (ret != E_OK) { + LOGE("update new dentry failed, ret = %{public}d", ret); + return ret; + } + rdbTransaction.Finish(); + return E_OK; +} + +int32_t CloudDiskRdbStore::ReadDir(const std::string &cloudId, vector &infos) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + CLOUDID_IS_NULL(cloudId); + AbsRdbPredicates readDirPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + readDirPredicates.EqualTo(FileColumn::PARENT_CLOUD_ID, cloudId) + ->And()->EqualTo(FileColumn::FILE_TIME_RECYCLED, "0")->And() + ->EqualTo(FileColumn::ROOT_DIRECTORY, bundleName_)->And() + ->NotEqualTo(FileColumn::DIRTY_TYPE, to_string(static_cast(DirtyType::TYPE_DELETED))); + auto resultSet = rdbStore_->QueryByStep(readDirPredicates, { FileColumn::FILE_NAME, FileColumn::IS_DIRECTORY }); + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfos(move(resultSet), infos); + if (ret != E_OK) { + LOGE("read directory is failed, ret %{public}d", ret); + return E_RDB; + } + return E_OK; +} + +static int32_t GetFileExtension(const std::string &fileName, std::string &extension) +{ + size_t dotIndex = fileName.rfind("."); + if (dotIndex != string::npos) { + extension = fileName.substr(dotIndex + 1); + return E_OK; + } + LOGE("Failed to obtain file extension"); + return E_INVAL_ARG; +} + +static void FillFileType(const std::string &fileName, ValuesBucket &fileInfo) +{ + string extension; + if (!GetFileExtension(fileName, extension)) { + fileInfo.PutString(FileColumn::FILE_CATEGORY, extension); + } +} + +static int64_t UTCTimeMilliSeconds() +{ + struct timespec t; + clock_gettime(CLOCK_REALTIME, &t); + return t.tv_sec * SECOND_TO_MILLISECOND + t.tv_nsec / MILLISECOND_TO_NANOSECOND; +} + +static int32_t CheckNameForSpace(const std::string& fileName, const int32_t isDir) +{ + if (fileName.empty()) { + return EINVAL; + } + if (fileName[0] == ' ') { + LOGI("Illegal name"); + return EINVAL; + } + if (isDir == DIRECTORY) { + if ((fileName.length() >= 1 && fileName[fileName.length() - 1] == ' ') || fileName == RECYCLE_FILE_NAME) { + LOGI("Illegal name"); + return EINVAL; + } + } + return E_OK; +} + +static int32_t CheckName(const std::string &fileName) +{ + if (fileName.empty() || + fileName == "." || + fileName == ".." || + fileName.length() > MAX_FILE_NAME_SIZE) { + return EINVAL; + } + std::map illegalCharacter = { + {'<', true}, + {'>', true}, + {'|', true}, + {':', true}, + {'?', true}, + {'/', true}, + {'\\', true}, + {'"', true}, + {'*', true}, + }; + for (char c : fileName) { + if (illegalCharacter.find(c) != illegalCharacter.end()) { + LOGI("Illegal name"); + return EINVAL; + } + } + return E_OK; +} + +static int32_t CreateFile(const std::string &fileName, const std::string &filePath, ValuesBucket &fileInfo, + struct stat *statInfo) +{ + int32_t ret = stat(filePath.c_str(), statInfo); + if (ret) { + LOGE("filePath %{private}s is invalid", GetAnonyString(filePath).c_str()); + return E_PATH; + } + fileInfo.PutInt(FileColumn::IS_DIRECTORY, FILE); + fileInfo.PutLong(FileColumn::FILE_SIZE, statInfo->st_size); + fileInfo.PutLong(FileColumn::FILE_TIME_EDITED, CloudFileUtils::Timespec2Milliseconds(statInfo->st_mtim)); + fileInfo.PutLong(FileColumn::META_TIME_EDITED, CloudFileUtils::Timespec2Milliseconds(statInfo->st_mtim)); + fileInfo.PutLong(FileColumn::LCD_FLAG, NO_THM_TO_DOWNLOAD); + fileInfo.PutLong(FileColumn::THM_FLAG, NO_THM_TO_DOWNLOAD); + FillFileType(fileName, fileInfo); + return E_OK; +} + +static int32_t CreateDentry(MetaBase &metaBase, uint32_t userId, const std::string &bundleName, + const std::string &fileName, const std::string &parentCloudId) +{ + auto callback = [&metaBase] (MetaBase &m) { + m.cloudId = metaBase.cloudId; + m.atime = metaBase.atime; + m.mtime = metaBase.mtime; + m.size = metaBase.size; + m.mode = metaBase.mode; + m.position = metaBase.position; + m.fileType = metaBase.fileType; + m.noUpload = metaBase.noUpload; + }; + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, parentCloudId); + int32_t ret = metaFile->DoLookupAndUpdate(fileName, callback); + if (ret != E_OK) { + LOGE("update new dentry failed, ret = %{public}d", ret); + return ret; + } + return E_OK; +} + +static void UpdateMetabase(MetaBase &metaBase, int64_t fileTimeAdded, struct stat *statInfo) +{ + metaBase.atime = static_cast(fileTimeAdded); + metaBase.mtime = static_cast(CloudFileUtils::Timespec2Milliseconds(statInfo->st_mtim)); + metaBase.mode = statInfo->st_mode; + metaBase.size = static_cast(statInfo->st_size); + metaBase.position = LOCAL; + metaBase.fileType = FILE_TYPE_CONTENT; +} + +static void HandleCreateValue(ValuesBucket &fileInfo, const std::string &cloudId, const std::string &parentCloudId, + const std::string &fileName, const std::string &bundleName) +{ + fileInfo.PutString(FileColumn::CLOUD_ID, cloudId); + fileInfo.PutString(FileColumn::FILE_NAME, fileName); + fileInfo.PutString(FileColumn::PARENT_CLOUD_ID, parentCloudId); + fileInfo.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_NO_NEED_UPLOAD)); + fileInfo.PutLong(FileColumn::OPERATE_TYPE, static_cast(OperationType::NEW)); + fileInfo.PutString(FileColumn::ROOT_DIRECTORY, bundleName); +} + +int32_t CloudDiskRdbStore::Create(const std::string &cloudId, const std::string &parentCloudId, + const std::string &fileName, bool noNeedUpload) +{ + int32_t ret = CheckName(fileName); + if (ret != E_OK) { + return ret; + } + ret = CheckNameForSpace(fileName, FILE); + if (ret != E_OK) { + return ret; + } + RDBPTR_IS_NULLPTR(rdbStore_); + ValuesBucket fileInfo; + if (cloudId.empty() || parentCloudId.empty() || fileName.empty()) { + LOGE("create parameter is invalid"); + return E_INVAL_ARG; + } + + MetaBase metaBase(fileName, cloudId); + if (noNeedUpload) { + fileInfo.PutInt(FileColumn::NO_NEED_UPLOAD, NO_UPLOAD); + metaBase.noUpload = NO_UPLOAD; + } + + int64_t fileTimeAdded = UTCTimeMilliSeconds(); + fileInfo.PutLong(FileColumn::FILE_TIME_ADDED, fileTimeAdded); + HandleCreateValue(fileInfo, cloudId, parentCloudId, fileName, bundleName_); + struct stat statInfo {}; + string filePath = CloudFileUtils::GetLocalFilePath(cloudId, bundleName_, userId_); + if (CreateFile(fileName, filePath, fileInfo, &statInfo)) { + LOGE("file path is invalid, cannot create file record"); + return E_PATH; + } + TransactionOperations rdbTransaction(rdbStore_); + auto [rdbRet, transaction] = rdbTransaction.Start(); + if (rdbRet != E_OK) { + LOGE("rdbstore begin transaction failed, ret = %{public}d", ret); + return E_RDB; + } + int64_t outRowId = 0; + std::tie(rdbRet, outRowId) = transaction->Insert(FileColumn::FILES_TABLE, fileInfo); + if (rdbRet != E_OK) { + LOGE("insert new file record in DB is failed, ret = %{public}d", ret); + return rdbRet; + } + + UpdateMetabase(metaBase, fileTimeAdded, &statInfo); + ret = CreateDentry(metaBase, userId_, bundleName_, fileName, parentCloudId); + if (ret != E_OK) { + LOGE("create new dentry failed, ret = %{public}d", ret); + return ret; + } + rdbTransaction.Finish(); + return E_OK; +} + +int32_t CloudDiskRdbStore::MkDir(const std::string &cloudId, const std::string &parentCloudId, + const std::string &directoryName, bool noNeedUpload) +{ + int32_t ret = CheckName(directoryName); + if (ret != E_OK) { + return ret; + } + ret = CheckNameForSpace(directoryName, DIRECTORY); + if (ret != E_OK) { + return ret; + } + RDBPTR_IS_NULLPTR(rdbStore_); + ValuesBucket dirInfo; + if (cloudId.empty() || parentCloudId.empty() || directoryName.empty()) { + LOGE("make directory parameter is invalid"); + return E_INVAL_ARG; + } + + MetaBase metaBase(directoryName, cloudId); + if (noNeedUpload) { + dirInfo.PutInt(FileColumn::NO_NEED_UPLOAD, NO_UPLOAD); + metaBase.noUpload = NO_UPLOAD; + } + + dirInfo.PutString(FileColumn::CLOUD_ID, cloudId); + dirInfo.PutString(FileColumn::FILE_NAME, directoryName); + int64_t fileTimeAdded = UTCTimeMilliSeconds(); + dirInfo.PutLong(FileColumn::FILE_TIME_ADDED, fileTimeAdded); + int64_t fileTimeEdited = UTCTimeMilliSeconds(); + dirInfo.PutLong(FileColumn::FILE_TIME_EDITED, fileTimeEdited); + int64_t metaTimeEdited = UTCTimeMilliSeconds(); + dirInfo.PutLong(FileColumn::META_TIME_EDITED, metaTimeEdited); + dirInfo.PutInt(FileColumn::IS_DIRECTORY, DIRECTORY); + dirInfo.PutString(FileColumn::PARENT_CLOUD_ID, parentCloudId); + dirInfo.PutLong(FileColumn::OPERATE_TYPE, static_cast(OperationType::NEW)); + dirInfo.PutInt(FileColumn::FILE_STATUS, FileStatus::TO_BE_UPLOADED); + dirInfo.PutString(FileColumn::ROOT_DIRECTORY, bundleName_); + TransactionOperations rdbTransaction(rdbStore_); + std::shared_ptr transaction; + std::tie(ret, transaction) = rdbTransaction.Start(); + if (ret != E_OK) { + LOGE("rdbstore begin transaction failed, ret = %{public}d", ret); + return ret; + } + int64_t outRowId = 0; + std::tie(ret, outRowId) = transaction->Insert(FileColumn::FILES_TABLE, dirInfo); + if (ret != E_OK) { + LOGE("insert new directory record in DB is failed, ret = %{public}d", ret); + return ret; + } + + metaBase.atime = static_cast(fileTimeAdded); + metaBase.mtime = static_cast(fileTimeEdited); + metaBase.mode = S_IFDIR | STAT_MODE_DIR; + metaBase.position = LOCAL; + metaBase.fileType = FILE_TYPE_CONTENT; + ret = CreateDentry(metaBase, userId_, bundleName_, directoryName, parentCloudId); + if (ret != E_OK) { + LOGE("create new dentry failed, ret = %{public}d", ret); + return ret; + } + rdbTransaction.Finish(); + if (!noNeedUpload) { + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + } + return E_OK; +} + +static void HandleWriteValue(ValuesBucket &write, int32_t position, struct stat &statInfo) +{ + write.PutLong(FileColumn::FILE_SIZE, statInfo.st_size); + write.PutLong(FileColumn::FILE_TIME_EDITED, CloudFileUtils::Timespec2Milliseconds(statInfo.st_mtim)); + write.PutLong(FileColumn::META_TIME_EDITED, CloudFileUtils::Timespec2Milliseconds(statInfo.st_mtim)); + write.PutLong(FileColumn::FILE_TIME_VISIT, CloudFileUtils::Timespec2Milliseconds(statInfo.st_atim)); + write.PutInt(FileColumn::FILE_STATUS, FileStatus::TO_BE_UPLOADED); + if (position != LOCAL) { + write.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_FDIRTY)); + write.PutLong(FileColumn::OPERATE_TYPE, static_cast(OperationType::UPDATE)); + } else { + write.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_NEW)); + } +} + +static int32_t WriteUpdateDentry(MetaBase &metaBase, uint32_t userId, const std::string &bundleName, + const std::string &fileName, const std::string &parentCloudId) +{ + auto callback = [&metaBase] (MetaBase &m) { + m.mtime = metaBase.mtime; + m.size = metaBase.size; + }; + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, parentCloudId); + LOGD("write update dentry start"); + int32_t ret = metaFile->DoChildUpdate(fileName, callback); + if (ret != E_OK) { + LOGE("update new dentry failed, ret = %{public}d", ret); + return ret; + } + return ret; +} + +int32_t CloudDiskRdbStore::Write(const std::string &fileName, const std::string &parentCloudId, + const std::string &cloudId) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID) { + LOGE("write parameter is invalid"); + return E_INVAL_ARG; + } + TransactionOperations rdbTransaction(rdbStore_); + auto [ret, transaction] = rdbTransaction.Start(); + if (ret != E_OK) { + LOGE("rdbstore begin transaction failed, ret = %{public}d", ret); + return ret; + } + string filePath = CloudFileUtils::GetLocalFilePath(cloudId, bundleName_, userId_); + struct stat statInfo {}; + ret = stat(filePath.c_str(), &statInfo); + if (ret) { + LOGE("filePath %{private}s is invalid", GetAnonyString(filePath).c_str()); + return E_PATH; + } + CloudDiskFileInfo info; + if (GetAttr(cloudId, info)) { + LOGE("get write cloudId info in DB fail"); + return E_RDB; + } + int32_t position = static_cast(info.location); + ValuesBucket write; + HandleWriteValue(write, position, statInfo); + int32_t changedRows = -1; + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + std::tie(ret, changedRows) = transaction->Update(write, predicates); + if (ret != E_OK) { + LOGE("write file record in DB fail, ret %{public}d", ret); + return E_RDB; + } + MetaBase metaBase(fileName, cloudId); + metaBase.mtime = static_cast(CloudFileUtils::Timespec2Milliseconds(statInfo.st_mtim)); + metaBase.size = static_cast(statInfo.st_size); + ret = WriteUpdateDentry(metaBase, userId_, bundleName_, fileName, parentCloudId); + if (ret != E_OK) { + LOGE("write update dentry failed, ret %{public}d", ret); + return E_RDB; + } + rdbTransaction.Finish(); + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + return E_OK; +} + +int32_t CloudDiskRdbStore::LocationSetXattr(const std::string &name, const std::string &parentCloudId, + const std::string &cloudId, const std::string &value) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + int32_t val = -1; + istringstream transfer(value); + transfer >> val; + if (val != LOCAL && val != CLOUD && val != LOCAL_AND_CLOUD) { + LOGE("setxattr unknown value"); + return E_INVAL_ARG; + } + ValuesBucket setXAttr; + setXAttr.PutInt(FileColumn::POSITION, val); + int32_t changedRows = -1; + TransactionOperations rdbTransaction(rdbStore_); + auto [ret, transaction] = rdbTransaction.Start(); + if (ret != E_OK) { + LOGE("rdbstore begin transaction failed, ret = %{public}d", ret); + return ret; + } + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + std::tie(ret, changedRows) = transaction->Update(setXAttr, predicates); + if (ret != E_OK) { + LOGE("set xAttr location fail, ret %{public}d", ret); + return E_RDB; + } + MetaBase metaBase(name, cloudId); + auto callback = [&val] (MetaBase &m) { + m.position = val; + }; + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId_, bundleName_, parentCloudId); + ret = metaFile->DoLookupAndUpdate(name, callback); + if (ret != E_OK) { + LOGE("update new dentry failed, ret = %{public}d", ret); + return ret; + } + rdbTransaction.Finish(); + return E_OK; +} + +int32_t CloudDiskRdbStore::UpdateTHMStatus(MetaBase &metaBase, int32_t status) +{ + ValuesBucket fileInfo; + if (metaBase.fileType == FILE_TYPE_THUMBNAIL) { + fileInfo.PutInt(FileColumn::THM_FLAG, status); + } else { + fileInfo.PutInt(FileColumn::LCD_FLAG, status); + } + string srcCloudId; + GetSrcCloudId(metaBase.cloudId, srcCloudId); + TransactionOperations rdbTransaction(rdbStore_); + auto [ret, transaction] = rdbTransaction.Start(); + int32_t changedRows = -1; + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, srcCloudId); + std::tie(ret, changedRows) = transaction->Update(fileInfo, predicates); + if (ret !=E_OK) { + LOGE("set thm_flag failed, ret = %{public}d", ret); + return E_RDB; + } + rdbTransaction.Finish(); + return E_OK; +} + +int32_t CloudDiskRdbStore::HasTHMSetXattr(const std::string &name, const std::string &key, + const std::string &cloudId, const std::string &value) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (!all_of(value.begin(), value.end(), ::isdigit)) { + return E_INVAL_ARG; + } + int32_t val = std::stoi(value); + if (val != 0 && val != 1) { + LOGE("setxattr unknown value"); + return E_INVAL_ARG; + } + + ValuesBucket setXAttr; + if (val == 0) { + if (key == CLOUD_HAS_LCD) { + setXAttr.PutInt(FileColumn::LCD_FLAG, NO_THM_TO_DOWNLOAD); + } else { + setXAttr.PutInt(FileColumn::THM_FLAG, NO_THM_TO_DOWNLOAD); + } + } else { + if (key == CLOUD_HAS_LCD) { + setXAttr.PutInt(FileColumn::LCD_FLAG, DOWNLOADED_THM); + } else { + setXAttr.PutInt(FileColumn::THM_FLAG, DOWNLOADED_THM); + } + } + int32_t dirtyType; + TransactionOperations rdbTransaction(rdbStore_); + auto [ret, transaction] = rdbTransaction.Start(); + RETURN_ON_ERR(GetDirtyType(cloudId, dirtyType)); + if (dirtyType == static_cast(DirtyType::TYPE_SYNCED)) { + setXAttr.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_MDIRTY)); + } + int32_t changedRows = -1; + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + std::tie(ret, changedRows) = transaction->Update(setXAttr, predicates); + if (ret != E_OK) { + LOGE("set xAttr thm_flag fail, ret %{public}d", ret); + return E_RDB; + } + rdbTransaction.Finish(); + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + return E_OK; +} + + +int32_t CloudDiskRdbStore::GetRowId(const std::string &cloudId, int64_t &rowId) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + CLOUDID_IS_NULL(cloudId); + AbsRdbPredicates getRowIdPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + getRowIdPredicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(getRowIdPredicates, {FileColumn::ROW_ID}); + if (resultSet == nullptr) { + LOGE("get nullptr result set"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("getRowId result set go to next row failed"); + return E_RDB; + } + CloudDiskRdbUtils::GetLong(FileColumn::ROW_ID, rowId, resultSet); + return E_OK; +} + +static int32_t RecycleSetValue(TrashOptType val, ValuesBucket &setXAttr, int32_t position) +{ + if (position != LOCAL) { + setXAttr.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_MDIRTY)); + } else { + setXAttr.PutInt(FileColumn::OPERATE_TYPE, static_cast(OperationType::NEW)); + } + if (val == TrashOptType::RESTORE) { + setXAttr.PutInt(FileColumn::OPERATE_TYPE, static_cast(OperationType::RESTORE)); + setXAttr.PutLong(FileColumn::FILE_TIME_RECYCLED, CANCEL_STATE); + setXAttr.PutInt(FileColumn::DIRECTLY_RECYCLED, CANCEL_STATE); + setXAttr.PutLong(FileColumn::META_TIME_EDITED, UTCTimeMilliSeconds()); + } else if (val == TrashOptType::RECYCLE) { + int64_t recycledTime = UTCTimeMilliSeconds(); + setXAttr.PutInt(FileColumn::OPERATE_TYPE, static_cast(OperationType::DELETE)); + setXAttr.PutLong(FileColumn::FILE_TIME_RECYCLED, recycledTime); + setXAttr.PutInt(FileColumn::DIRECTLY_RECYCLED, SET_STATE); + setXAttr.PutLong(FileColumn::META_TIME_EDITED, recycledTime); + } else { + LOGE("invalid value"); + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::GetParentCloudId(const std::string &cloudId, std::string &parentCloudId) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + AbsRdbPredicates getParentCloudIdPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + getParentCloudIdPredicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(getParentCloudIdPredicates, { FileColumn::PARENT_CLOUD_ID }); + if (resultSet == nullptr) { + LOGE("get nullptr parentCloudId resultSet"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("get parentCloudId go to next row failed"); + return E_RDB; + } + int32_t ret = CloudDiskRdbUtils::GetString(FileColumn::PARENT_CLOUD_ID, parentCloudId, resultSet); + if (ret != E_OK) { + LOGE("get parent cloudId failed"); + return ret; + } + return E_OK; +} + +static string ConvertUriToSrcPath(const string &uriStr) +{ + Uri uri(uriStr); + string scheme = uri.GetScheme(); + if (scheme != FILE_SCHEME) { + return "/"; + } + const string sandboxPrefix = "/data/storage/el2/cloud"; + string filePath = uri.GetPath().substr(sandboxPrefix.length()); + size_t pos = filePath.rfind("/"); + filePath = pos == 0 ? "/" : filePath.substr(0, pos); + return filePath; +} + +int32_t CloudDiskRdbStore::GetSourcePath(const string &attr, const string &parentCloudId, string &sourcePath) +{ + nlohmann::json jsonObject = nlohmann::json::parse(attr, nullptr, false); + if (jsonObject.is_discarded() || (!jsonObject.is_object())) { + LOGD("jsonObject is discarded"); + jsonObject = nlohmann::json::object(); + } + if (jsonObject.contains(SRC_PATH_KEY) && jsonObject[SRC_PATH_KEY].is_string()) { + sourcePath = jsonObject[SRC_PATH_KEY].get(); + return E_OK; + } + + string uri; + int32_t ret = GetUriFromDB(parentCloudId, uri); + if (ret == E_OK) { + sourcePath == ConvertUriToSrcPath(uri); + } else { + LOGI("file src path fail, restore to root dir"); + } + return E_OK; +} + +int32_t CloudDiskRdbStore::SourcePathSetValue(const string &cloudId, const string &attr, ValuesBucket &setXattr) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + string uri; + CacheNode cacheNode = {cloudId}; + RETURN_ON_ERR(GetCurNode(cloudId, cacheNode)); + int32_t ret = GetNotifyUri(cacheNode, uri); + if (ret != E_OK) { + LOGE("failed to get source path, ret=%{public}d", ret); + return ret; + } + string filePath = ConvertUriToSrcPath(uri); + nlohmann::json jsonObject = nlohmann::json::parse(attr, nullptr, false); + if (jsonObject.is_discarded() || (!jsonObject.is_object())) { + LOGD("jsonObject is discarded"); + jsonObject = nlohmann::json::object(); + } + jsonObject[SRC_PATH_KEY] = filePath; + string attrStr = jsonObject.dump(); + setXattr.PutString(FileColumn::ATTRIBUTE, attrStr); + return E_OK; +} + +static int32_t UpdateParent(const int32_t userId, const string &bundleName, const string &srcPath, + string &parentCloudId) +{ + // root dir no need create + if (srcPath.empty() || srcPath == "/") { + parentCloudId = ROOT_CLOUD_ID; + return E_OK; + } + + string parentDir = LOCAL_PATH_MNT_HMDFS + to_string(userId) + LOCAL_PATH_CLOUD_DATA + bundleName + srcPath; + if (!ForceCreateDirectory(parentDir)) { + LOGE("create parent dir fail, %{public}s", GetAnonyString(parentDir).c_str()); + return errno; + } + parentCloudId = CloudFileUtils::GetCloudId(parentDir); + return E_OK; +} + +int32_t CloudDiskRdbStore::RecycleSetXattr(const std::string &name, const std::string &parentCloudId, + const std::string &cloudId, const std::string &value) +{ + bool isNum = std::all_of(value.begin(), value.end(), ::isdigit); + if (!isNum) { + return EINVAL; + } + int32_t val = std::stoi(value); + if (val == static_cast(TrashOptType::RESTORE)) { + return HandleRestoreXattr(name, parentCloudId, cloudId); + } + if (val == static_cast(TrashOptType::RECYCLE)) { + return HandleRecycleXattr(name, parentCloudId, cloudId); + } + return EINVAL; +} + +int32_t CloudDiskRdbStore::CheckIsConflict(const string &name, const string &parentCloudId, string &newName) +{ + MetaBase metaBase(name); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId_, bundleName_, parentCloudId); + int32_t ret = metaFile->DoLookup(metaBase); + if (ret != E_OK) { + if (ret == ENOENT) { + LOGI("no conflict file at target dir."); + return E_OK; + } + LOGE("lookup conflict name fail, ret = %{public}d", ret); + return ret; + } + + RETURN_ON_ERR(MetaFileMgr::GetInstance().GetNewName(metaFile, name, newName)); + + return E_OK; +} + +int32_t CloudDiskRdbStore::RestoreUpdateRdb(const string &cloudId, const struct RestoreInfo &restoreInfo, + const ValuesBucket &setXattr) +{ + TransactionOperations rdbTransactionUpdate(rdbStore_); + auto [ret, transaction] = rdbTransactionUpdate.Start(); + if (ret != E_OK) { + LOGE("rdbstore begin transaction failed, ret = %{public}d", ret); + return ret; + } + + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + + int32_t changedRows = -1; + tie(ret, changedRows) = transaction->Update(setXattr, predicates); + if (ret != E_OK) { + LOGE("resotre update rdb failed, ret = %{public}d", ret); + return E_RDB; + } + + ret = MetaFileMgr::GetInstance().RemoveFromRecycleDentryfile(userId_, bundleName_, restoreInfo); + if (ret != E_OK) { + LOGE("recycled restore set dentry failed, ret = %{public}d", ret); + return ret; + } + rdbTransactionUpdate.Finish(); + + return E_OK; +} + +int32_t CloudDiskRdbStore::HandleRestoreXattr(const string &name, const string &parentCloudId, const string &cloudId) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + int64_t rowId = 0; + int32_t position = -1; + string attr; + TransactionOperations rdbTransaction(rdbStore_); + auto [ret, transaction] = rdbTransaction.Start(); + if (ret != E_OK) { + LOGE("rdbstore begin transaction failed, ret = %{public}d", ret); + return ret; + } + ret = GetRecycleInfo(transaction, cloudId, rowId, position, attr); + if (ret != E_OK) { + LOGE("get recycle fields fail, ret %{public}d", ret); + return E_RDB; + } + rdbTransaction.Finish(); + + string realParentCloudId = parentCloudId; + string srcPath = "/"; + RETURN_ON_ERR(GetSourcePath(attr, parentCloudId, srcPath)); + RETURN_ON_ERR(UpdateParent(userId_, bundleName_, srcPath, realParentCloudId)); + + string newName = name; + RETURN_ON_ERR(CheckIsConflict(name, realParentCloudId, newName)); + + ValuesBucket setXAttr; + setXAttr.PutString(FileColumn::PARENT_CLOUD_ID, realParentCloudId); + setXAttr.PutString(FileColumn::FILE_NAME, newName); + RETURN_ON_ERR(RecycleSetValue(TrashOptType::RESTORE, setXAttr, position)); + struct RestoreInfo restoreInfo = {name, realParentCloudId, newName, rowId}; + ret = RestoreUpdateRdb(cloudId, restoreInfo, setXAttr); + if (ret != E_OK) { + LOGE("handle restore rdb update fail, ret = %{public}d", ret); + return ret; + } + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + return E_OK; +} + +int32_t CloudDiskRdbStore::HandleRecycleXattr(const string &name, const string &parentCloudId, const string &cloudId) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + int64_t rowId = 0; + int32_t position = -1; + string attr; + TransactionOperations rdbTransaction(rdbStore_); + auto [ret, transaction] = rdbTransaction.Start(); + if (ret != E_OK) { + LOGE("rdbstore begin transaction failed, ret = %{public}d", ret); + return ret; + } + ret = GetRecycleInfo(transaction, cloudId, rowId, position, attr); + if (ret != E_OK) { + LOGE("get rowId and position fail, ret %{public}d", ret); + return E_RDB; + } + ValuesBucket setXAttr; + SourcePathSetValue(cloudId, attr, setXAttr); + ret = RecycleSetValue(TrashOptType::RECYCLE, setXAttr, position); + if (ret != E_OK) { + return ret; + } + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + int32_t changedRows = -1; + std::tie(ret, changedRows) = transaction->Update(setXAttr, predicates); + if (ret != E_OK) { + LOGE("set xAttr location fail, ret %{public}d", ret); + return E_RDB; + } + ret = MetaFileMgr::GetInstance().MoveIntoRecycleDentryfile(userId_, bundleName_, name, parentCloudId, rowId); + if (ret != E_OK) { + LOGE("recycle set dentryfile failed, ret = %{public}d", ret); + return ret; + } + rdbTransaction.Finish(); + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + return E_OK; +} + +int32_t CloudDiskRdbStore::GetRecycleInfo(shared_ptr transaction, const std::string &cloudId, + int64_t &rowId, int32_t &position, string &attr) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + CLOUDID_IS_NULL(cloudId); + AbsRdbPredicates getRowIdAndPositionPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + getRowIdAndPositionPredicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = transaction->QueryByStep(getRowIdAndPositionPredicates, + {FileColumn::ROW_ID, FileColumn::POSITION, FileColumn::ATTRIBUTE}); + if (resultSet == nullptr) { + LOGE("get nullptr result set"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("getRowIdAndPositionPredicates result set go to next row failed"); + return E_RDB; + } + int32_t ret = CloudDiskRdbUtils::GetLong(FileColumn::ROW_ID, rowId, resultSet); + if (ret != E_OK) { + LOGE("get rowId failed"); + return ret; + } + ret = CloudDiskRdbUtils::GetInt(FileColumn::POSITION, position, resultSet); + if (ret != E_OK) { + LOGE("get position failed"); + return ret; + } + ret = CloudDiskRdbUtils::GetString(FileColumn::ATTRIBUTE, attr, resultSet); + if (ret != E_OK) { + LOGE("get file attribute failed"); + return ret; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::FavoriteSetXattr(const std::string &cloudId, const std::string &value) +{ + LOGD("favoriteSetXattr, value %{public}s", value.c_str()); + RDBPTR_IS_NULLPTR(rdbStore_); + bool isNum = std::all_of(value.begin(), value.end(), ::isdigit); + if (!isNum) { + return EINVAL; + } + int32_t val = std::stoi(value); + ValuesBucket setXAttr; + if (val == 0) { + setXAttr.PutInt(FileColumn::IS_FAVORITE, CANCEL_STATE); + setXAttr.PutLong(FileColumn::META_TIME_EDITED, UTCTimeMilliSeconds()); + } else if (val == 1) { + setXAttr.PutInt(FileColumn::IS_FAVORITE, SET_STATE); + setXAttr.PutLong(FileColumn::META_TIME_EDITED, UTCTimeMilliSeconds()); + } else { + return E_RDB; + } + int32_t changedRows = -1; + vector bindArgs; + bindArgs.emplace_back(cloudId); + int32_t ret = rdbStore_->Update(changedRows, FileColumn::FILES_TABLE, setXAttr, + FileColumn::CLOUD_ID + " = ?", bindArgs); + if (ret != E_OK) { + LOGE("set xAttr location fail, ret %{public}d", ret); + return E_RDB; + } + return E_OK; +} + +int32_t CheckXattr(const std::string &key) +{ + if (key == CLOUD_FILE_LOCATION) { + return CLOUD_LOCATION; + } else if (key == CLOUD_CLOUD_RECYCLE_XATTR) { + return CLOUD_RECYCLE; + } else if (key == IS_FAVORITE_XATTR) { + return IS_FAVORITE; + } else if (key == IS_FILE_STATUS_XATTR) { + return FILE_SYNC_STATUS; + } else if (key == CLOUD_EXT_ATTR) { + return IS_EXT_ATTR; + } else if (key == CLOUD_HAS_LCD || key == CLOUD_HAS_THM) { + return HAS_THM; + } else if (key == CLOUD_TIME_RECYCLED) { + return TIME_RECYCLED; + } else if (key == CLOUD_RECYCLE_PATH) { + return RECYCLE_PATH; + } else { + return ERROR_CODE; + } +} + +int32_t CloudDiskRdbStore::LocationGetXattr(const std::string &name, const std::string &key, std::string &value, + const std::string &parentCloudId) +{ + if (key != CLOUD_FILE_LOCATION) { + LOGE("getxattr parameter is invalid"); + return E_INVAL_ARG; + } + MetaBase metaBase(name); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId_, bundleName_, parentCloudId); + int32_t ret = metaFile->DoLookup(metaBase); + if (ret != E_OK) { + LOGE("lookup dentry failed, ret = %{public}d", ret); + return ENOENT; + } + value = std::to_string(metaBase.position); + return E_OK; +} + +int32_t CloudDiskRdbStore::FavoriteGetXattr(const std::string &cloudId, const std::string &key, std::string &value) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID || key != IS_FAVORITE_XATTR) { + LOGE("getxattr parameter is invalid"); + return E_INVAL_ARG; + } + AbsRdbPredicates getXAttrPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + getXAttrPredicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(getXAttrPredicates, { FileColumn::IS_FAVORITE }); + if (resultSet == nullptr) { + LOGE("get nullptr getxattr result"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("getxattr result set go to next row failed"); + return E_RDB; + } + int32_t isFavorite; + CloudDiskRdbUtils::GetInt(FileColumn::IS_FAVORITE, isFavorite, resultSet); + value = to_string(isFavorite); + return E_OK; +} + +int32_t CloudDiskRdbStore::FileStatusGetXattr(const std::string &cloudId, const std::string &key, std::string &value) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID || key != IS_FILE_STATUS_XATTR) { + LOGE("getxattr parameter is invalid"); + return E_INVAL_ARG; + } + AbsRdbPredicates getXAttrPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + getXAttrPredicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(getXAttrPredicates, { FileColumn::FILE_STATUS }); + if (resultSet == nullptr) { + LOGE("get nullptr getxattr result"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("getxattr result set go to next row failed"); + return E_RDB; + } + int32_t fileStatus; + int32_t ret = CloudDiskRdbUtils::GetInt(FileColumn::FILE_STATUS, fileStatus, resultSet); + if (ret != E_OK) { + LOGE("get file status failed"); + return ret; + } + value = to_string(fileStatus); + return E_OK; +} + +int32_t CloudDiskRdbStore::TimeRecycledGetXattr(const string &cloudId, const string &key, string &value) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID || key != CLOUD_TIME_RECYCLED) { + LOGE("getxattr parameter is invalid"); + return E_INVAL_ARG; + } + AbsRdbPredicates getXAttrPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + getXAttrPredicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(getXAttrPredicates, { FileColumn::FILE_TIME_RECYCLED }); + if (resultSet == nullptr) { + LOGE("get nullptr getxattr result"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("getxattr result set go to next row failed"); + return E_RDB; + } + int64_t timeRecycled = 0; + CloudDiskRdbUtils::GetLong(FileColumn::FILE_TIME_RECYCLED, timeRecycled, resultSet); + value = to_string(timeRecycled); + return E_OK; +} + +int32_t CloudDiskRdbStore::GetExtAttrValue(const std::string &cloudId, const std::string &key, std::string &value) +{ + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID || key.empty()) { + LOGE("get ext attr value parameter is invalid"); + return E_INVAL_ARG; + } + + std::string res; + int32_t pos = 0; + int32_t ret = GetExtAttr(cloudId, res, pos); + if (ret != E_OK || res.empty()) { + LOGE("get ext attr value res is empty"); + return E_RDB; + } + + nlohmann::json jsonObj = nlohmann::json::parse(res, nullptr, false); + if (jsonObj.is_discarded()) { + LOGE("get ext jsonObj parse failed"); + return E_RDB; + } + + LOGD("GetExtAttrValue, name %{public}s", key.c_str()); + if (!jsonObj.contains(key) || !jsonObj[key].is_string()) { + LOGE("get ext not a string"); + return E_RDB; + } + + value = jsonObj[key].get(); + return E_OK; +} + +int32_t CloudDiskRdbStore::GetExtAttr(const std::string &cloudId, std::string &value, int32_t &position) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID) { + LOGE("get ext attr parameter is invalid"); + return E_INVAL_ARG; + } + AbsRdbPredicates getAttrPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + getAttrPredicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(getAttrPredicates, FileColumn::EXT_ATTR_QUERY_COLUMNS); + if (resultSet == nullptr) { + LOGE("get nullptr get ext attr result"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("get ext attr result set go to next row failed"); + return E_RDB; + } + + int32_t ret = CloudDiskRdbUtils::GetString(FileColumn::ATTRIBUTE, value, resultSet); + if (ret != E_OK) { + LOGE("get ext attr value failed"); + return ret; + } + + ret = CloudDiskRdbUtils::GetInt(FileColumn::POSITION, position, resultSet); + if (ret != E_OK) { + LOGE("get location value failed"); + return ret; + } + + return E_OK; +} + +int32_t CloudDiskRdbStore::GetXAttr(const std::string &cloudId, const std::string &key, std::string &value, + const CacheNode &node, const std::string &extAttrKey) +{ + int32_t num = CheckXattr(key); + int32_t ret; + switch (num) { + case CLOUD_LOCATION: + ret = LocationGetXattr(node.fileName, key, value, node.parentCloudId); + break; + case IS_FAVORITE: + ret = FavoriteGetXattr(cloudId, key, value); + break; + case FILE_SYNC_STATUS: + ret = FileStatusGetXattr(cloudId, key, value); + break; + case IS_EXT_ATTR: + ret = GetExtAttrValue(cloudId, extAttrKey, value); + break; + case TIME_RECYCLED: + ret = TimeRecycledGetXattr(cloudId, key, value); + break; + default: + ret = ENOSYS; + break; + } + return ret; +} + +static int32_t ExtAttributeSetValue(const std::string &key, const std::string &value, + ValuesBucket &setXAttr, std::string &xattrList, int32_t pos) +{ + auto jsonObj = nlohmann::json::parse(xattrList, nullptr, false); + if (jsonObj.is_discarded() || (!jsonObj.is_object())) { + LOGD("jsonObj is discarded"); + jsonObj = nlohmann::json::object(); + } + + auto it = jsonObj.find(key); + if (it == jsonObj.end()) { + jsonObj.emplace(key, value); + } else { + jsonObj[key] = value; + } + + std::string jsonValue; + try { + jsonValue = jsonObj.dump(); + } catch (nlohmann::json::type_error& err) { + LOGE("failed to dump json object, reason: %{public}s", err.what()); + return E_INVAL_ARG; + } + + setXAttr.PutString(FileColumn::ATTRIBUTE, jsonValue); + if (pos != LOCAL) { + setXAttr.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_MDIRTY)); + setXAttr.PutLong(FileColumn::OPERATE_TYPE, static_cast(OperationType::UNKNOWN_TYPE)); + } + setXAttr.PutLong(FileColumn::META_TIME_EDITED, UTCTimeMilliSeconds()); + return E_OK; +} + +int32_t CloudDiskRdbStore::ExtAttributeSetXattr(const std::string &cloudId, const std::string &value, + const std::string &key) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + ValuesBucket setAttr; + int32_t changedRows = -1; + TransactionOperations rdbTransaction(rdbStore_); + auto [ret, transaction] = rdbTransaction.Start(); + if (ret != E_OK) { + LOGE("Ext rdbstore begin transaction failed, ret = %{public}d", ret); + return ret; + } + std::string xattrList; + int32_t pos = 0; + RETURN_ON_ERR(GetExtAttr(cloudId, xattrList, pos)); + RETURN_ON_ERR(ExtAttributeSetValue(key, value, setAttr, xattrList, pos)); + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + std::tie(ret, changedRows) = transaction->Update(setAttr, predicates); + if (ret != E_OK) { + LOGE("ext attr location fail, ret %{public}d", ret); + return E_RDB; + } + rdbTransaction.Finish(); + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + return E_OK; +} + +int32_t CloudDiskRdbStore::SetXAttr(const std::string &cloudId, const std::string &key, const std::string &value, + const std::string &name, const std::string &parentCloudId) +{ + int32_t num = CheckXattr(key); + int32_t ret; + switch (num) { + case CLOUD_LOCATION: + ret = LocationSetXattr(name, parentCloudId, cloudId, value); + break; + case CLOUD_RECYCLE: + ret = RecycleSetXattr(name, parentCloudId, cloudId, value); + break; + case IS_FAVORITE: + ret = FavoriteSetXattr(cloudId, value); + break; + case IS_EXT_ATTR: + ret = ExtAttributeSetXattr(cloudId, value, name); + break; + case HAS_THM: + ret = HasTHMSetXattr(name, key, cloudId, value); + break; + default: + ret = ENOSYS; + break; + } + return ret; +} + +static void FileRename(ValuesBucket &values, const int32_t &position, const std::string &newFileName) +{ + values.PutString(FileColumn::FILE_NAME, newFileName); + values.PutInt(FileColumn::FILE_STATUS, FileStatus::TO_BE_UPLOADED); + FillFileType(newFileName, values); + if (position != LOCAL) { + values.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_MDIRTY)); + values.PutLong(FileColumn::OPERATE_TYPE, static_cast(OperationType::RENAME)); + } +} + +static void FileMove(ValuesBucket &values, const int32_t &position, const std::string &newParentCloudId) +{ + values.PutString(FileColumn::PARENT_CLOUD_ID, newParentCloudId); + values.PutInt(FileColumn::FILE_STATUS, FileStatus::TO_BE_UPLOADED); + if (position != LOCAL) { + values.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_MDIRTY)); + values.PutLong(FileColumn::OPERATE_TYPE, static_cast(OperationType::MOVE)); + } +} + +static void FileMoveAndRename(ValuesBucket &values, const int32_t &position, const std::string &newParentCloudId, + const std::string &newFileName) +{ + values.PutString(FileColumn::PARENT_CLOUD_ID, newParentCloudId); + values.PutString(FileColumn::FILE_NAME, newFileName); + values.PutInt(FileColumn::FILE_STATUS, FileStatus::TO_BE_UPLOADED); + FillFileType(newFileName, values); + if (position != LOCAL) { + values.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_MDIRTY)); + values.PutLong(FileColumn::OPERATE_TYPE, static_cast(OperationType::MOVE)); + } +} + +static void HandleRenameValue(ValuesBucket &rename, int32_t position, const CacheNode &oldNode, + const CacheNode &newNode) +{ + string oldParentCloudId = oldNode.parentCloudId; + string oldFileName = oldNode.fileName; + string newParentCloudId = newNode.parentCloudId; + string newFileName = newNode.fileName; + rename.PutLong(FileColumn::META_TIME_EDITED, UTCTimeMilliSeconds()); + if (oldFileName != newFileName && oldParentCloudId == newParentCloudId) { + FileRename(rename, position, newFileName); + } + if (oldFileName == newFileName && oldParentCloudId != newParentCloudId) { + FileMove(rename, position, newParentCloudId); + } + if (oldFileName != newFileName && oldParentCloudId != newParentCloudId) { + FileMoveAndRename(rename, position, newParentCloudId, newFileName); + } +} + +int32_t CloudDiskRdbStore::Rename(const std::string &oldParentCloudId, const std::string &oldFileName, + const std::string &newParentCloudId, const std::string &newFileName) +{ + int32_t ret = CheckName(newFileName); + if (ret != E_OK) { + return ret; + } + RDBPTR_IS_NULLPTR(rdbStore_); + if (oldParentCloudId.empty() || oldFileName.empty() || newParentCloudId.empty() || newFileName.empty()) { + LOGE("rename parameters is invalid"); + return E_INVAL_ARG; + } + MetaBase metaBase(oldFileName); + auto oldMetaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId_, bundleName_, oldParentCloudId); + ret = oldMetaFile->DoLookup(metaBase); + if (ret != E_OK) { + LOGE("lookup dentry failed, ret = %{public}d", ret); + return EINVAL; + } + ret = CheckNameForSpace(newFileName, S_ISDIR(metaBase.mode)); + if (ret != E_OK) { + return ret; + } + ValuesBucket rename; + CacheNode newNode = {.parentCloudId = newParentCloudId, .fileName = newFileName}; + CacheNode oldNode = {.parentCloudId = oldParentCloudId, .fileName = oldFileName}; + HandleRenameValue(rename, metaBase.position, oldNode, newNode); + vector bindArgs; + bindArgs.emplace_back(metaBase.cloudId); + auto newMetaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId_, bundleName_, newParentCloudId); + ret = oldMetaFile->DoRename(metaBase, newFileName, newMetaFile); + if (ret != E_OK) { + LOGE("rename dentry failed, ret = %{public}d", ret); + return EINVAL; + } + function rdbUpdate = [this, rename, bindArgs] { + int32_t changedRows = -1; + int32_t ret = rdbStore_ ->Update(changedRows, FileColumn::FILES_TABLE, rename, + FileColumn::CLOUD_ID + " = ?", bindArgs); + if (ret != E_OK) { + LOGE("rename file fail, ret %{public}d", ret); + } + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + }; + ffrt::thread(rdbUpdate).detach(); + return E_OK; +} + +int32_t CloudDiskRdbStore::GetHasChild(const std::string &cloudId, bool &hasChild) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + CLOUDID_IS_NULL(cloudId); + AbsRdbPredicates readDirPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + readDirPredicates.EqualTo(FileColumn::PARENT_CLOUD_ID, cloudId) + ->And()->EqualTo(FileColumn::FILE_TIME_RECYCLED, "0")->And() + ->NotEqualTo(FileColumn::DIRTY_TYPE, to_string(static_cast(DirtyType::TYPE_DELETED))); + auto resultSet = rdbStore_->QueryByStep(readDirPredicates, {FileColumn::FILE_NAME}); + if (resultSet == nullptr) { + LOGE("get nullptr result set"); + return E_RDB; + } + if (resultSet->GoToNextRow() == E_OK) { + hasChild = true; + } else { + hasChild = false; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::UnlinkSynced(const std::string &cloudId) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + CLOUDID_IS_NULL(cloudId); + int32_t changedRows = -1; + ValuesBucket updateValue; + vector whereArgs = {cloudId}; + updateValue.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_DELETED)); + int32_t ret = rdbStore_->Update(changedRows, FileColumn::FILES_TABLE, updateValue, FileColumn::CLOUD_ID + " = ?", + whereArgs); + if (ret != E_OK) { + LOGE("unlink synced directory fail, ret %{public}d", ret); + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::UnlinkLocal(const std::string &cloudId) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + CLOUDID_IS_NULL(cloudId); + int32_t changedRows = -1; + vector whereArgs = {cloudId}; + int32_t ret = rdbStore_->Delete(changedRows, FileColumn::FILES_TABLE, FileColumn::CLOUD_ID + " = ?", whereArgs); + if (ret != E_OK) { + LOGE("unlink local directory fail, ret %{public}d", ret); + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::Unlink(const std::string &cloudId, const int32_t &noUpload) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID) { + LOGE("Unlink parameters is invalid"); + return E_INVAL_ARG; + } + if (noUpload == NO_UPLOAD) { + RETURN_ON_ERR(UnlinkLocal(cloudId)); + } else { + RETURN_ON_ERR(UnlinkSynced(cloudId)); + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + } + return E_OK; +} + +int32_t CloudDiskRdbStore::GetDirtyType(const std::string &cloudId, int32_t &dirtyType) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + AbsRdbPredicates predicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(predicates, {FileColumn::DIRTY_TYPE}); + if (resultSet == nullptr) { + LOGE("get null result"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("get current node resultSet fail"); + return E_RDB; + } + + int32_t ret = CloudDiskRdbUtils::GetInt(FileColumn::DIRTY_TYPE, dirtyType, resultSet); + if (ret != E_OK) { + LOGE("get file status fail"); + return ret; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::GetSrcCloudId(const std::string &cloudId, std::string &srcCloudId) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + AbsRdbPredicates predicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep(predicates, {FileColumn::SRC_CLOUD_ID}); + if (resultSet == nullptr) { + LOGE("get null result"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("get current node resultSet fail"); + return E_RDB; + } + + int32_t ret = CloudDiskRdbUtils::GetString(FileColumn::SRC_CLOUD_ID, srcCloudId, resultSet); + if (ret != E_OK) { + LOGE("get file src_cloudid failed, ret = %{public}d", ret); + return ret; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::GetCurNode(const std::string &cloudId, CacheNode &curNode) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (cloudId.empty() || cloudId == ROOT_CLOUD_ID) { + LOGE("parameter invalid"); + return E_INVAL_ARG; + } + AbsRdbPredicates predicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, cloudId); + auto resultSet = rdbStore_->QueryByStep( + predicates, {FileColumn::PARENT_CLOUD_ID, FileColumn::IS_DIRECTORY, FileColumn::FILE_NAME}); + if (resultSet == nullptr) { + LOGE("get null result"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("get current node resultSet fail"); + return E_RDB; + } + RowEntity rowEntity; + if (resultSet->GetRow(rowEntity) != E_OK) { + LOGE("result set to file info get row failed"); + return E_RDB; + } + + int32_t isDirectory; + rowEntity.Get(FileColumn::PARENT_CLOUD_ID).GetString(curNode.parentCloudId); + rowEntity.Get(FileColumn::FILE_NAME).GetString(curNode.fileName); + rowEntity.Get(FileColumn::IS_DIRECTORY).GetInt(isDirectory); + curNode.isDir = isDirectory ? "directory" : "file"; + + return E_OK; +} + +int32_t CloudDiskRdbStore::GetParentNode(const std::string &parentCloudId, std::string &nextCloudId, + std::string &fileName) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + if (parentCloudId.empty()) { + LOGE("parameter invalid"); + return E_INVAL_ARG; + } + AbsRdbPredicates predicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + predicates.EqualTo(FileColumn::CLOUD_ID, parentCloudId); + auto resultSet = rdbStore_->QueryByStep(predicates, {FileColumn::PARENT_CLOUD_ID, FileColumn::FILE_NAME}); + if (resultSet == nullptr) { + LOGE("get null result"); + return E_RDB; + } + if (resultSet->GoToNextRow() != E_OK) { + LOGE("get current node resultSet fail"); + return E_RDB; + } + RowEntity rowEntity; + if (resultSet->GetRow(rowEntity) != E_OK) { + LOGE("result set to file info get row failed"); + return E_RDB; + } + rowEntity.Get(FileColumn::PARENT_CLOUD_ID).GetString(nextCloudId); + rowEntity.Get(FileColumn::FILE_NAME).GetString(fileName); + return E_OK; +} + +int32_t CloudDiskRdbStore::GetUriFromDB(const std::string &parentCloudId, std::string &uri) +{ + string realPrefix = CLOUDDISK_URI_PREFIX; + realPrefix.replace(realPrefix.find(BUNDLENAME_FLAG), BUNDLENAME_FLAG.length(), bundleName_); + if (parentCloudId.empty() || parentCloudId == rootId_ || parentCloudId == ROOT_CLOUD_ID) { + uri = realPrefix + BACKFLASH + uri; + return E_OK; + } + + string nextCloudId; + string fileName; + int32_t ret = GetParentNode(parentCloudId, nextCloudId, fileName); + if (ret != E_OK) { + LOGI("get parentnode fail, parentCloudId: %{public}s", parentCloudId.c_str()); + return ret; + } + uri = fileName + BACKFLASH + uri; + uint32_t queryTimes = 0; + while (nextCloudId != ROOT_CLOUD_ID) { + ret = GetParentNode(nextCloudId, nextCloudId, fileName); + if (ret != E_OK) { + return E_OK; + } + uri = fileName + BACKFLASH + uri; + queryTimes++; + if (uri.length() > PATH_MAX || queryTimes > MAX_QUERY_TIMES) { + return E_INVAL_ARG; + } + } + uri = realPrefix + BACKFLASH + uri; + return E_OK; +} + +int32_t CloudDiskRdbStore::GetNotifyUri(const CacheNode &cacheNode, std::string &uri) +{ + int32_t ret = CheckRootIdValid(); + if (ret != E_OK) { + LOGE("rootId is invalid"); + return ret; + } + ret = CloudDiskNotifyUtils::GetUriFromCache(bundleName_, rootId_, cacheNode, uri); + if (ret == E_OK) { + return ret; + } + LOGD("get uri from cache fail, name: %{public}s", GetAnonyString(cacheNode.fileName).c_str()); + uri = cacheNode.fileName; + ret = GetUriFromDB(cacheNode.parentCloudId, uri); + if (ret == E_OK) { + return ret; + } + LOGI("get uri from db fail, name: %{public}s", GetAnonyString(cacheNode.fileName).c_str()); + return ret; +} + +int32_t CloudDiskRdbStore::GetNotifyData(const CacheNode &cacheNode, NotifyData ¬ifyData) +{ + int32_t ret = GetNotifyUri(cacheNode, notifyData.uri); + if (ret == E_OK) { + notifyData.isDir = cacheNode.isDir == "directory"; + } + return ret; +} + +int32_t CloudDiskRdbStore::CheckRootIdValid() +{ + if (!rootId_.empty()) { + return E_OK; + } + CloudPrefImpl cloudPrefImpl(userId_, bundleName_, FileColumn::FILES_TABLE); + cloudPrefImpl.GetString(ROOT_CLOUD_ID, rootId_); + if (rootId_.empty()) { + LOGE("get rootId fail"); + return E_INVAL_ARG; + } + LOGI("load rootis succ, rootId: %{public}s", rootId_.c_str()); + return E_OK; +} + +static void GenCloudSyncTriggerFuncParams(RdbStore &store, std::string &userId, std::string &bundleName) +{ + string databasePath = store.GetPath(); + string str = "cloudfile/"; + size_t startPos = databasePath.find(str); + size_t endPos = databasePath.find("/rdb"); + if (startPos != std::string::npos && endPos != std::string::npos) { + startPos += str.size(); + string tempStr = databasePath.substr(startPos, endPos - startPos); + size_t pos = tempStr.find('/'); + if (pos != std::string::npos) { + userId = tempStr.substr(0, pos); + bundleName = tempStr.substr(pos + 1); + LOGI("generate CloudSyncTriggerFunc parameters success, userId: %{public}s, bundleName: %{public}s", + userId.c_str(), bundleName.c_str()); + return; + } + } + LOGE("generate CloudSyncTriggerFunc parameters fail"); + return; +} + +static const std::string &CreateFolderTriggerSync(RdbStore &store) +{ + string userId; + string bundleName; + GenCloudSyncTriggerFuncParams(store, userId, bundleName); + static const string CREATE_FOLDERS_NEW_CLOUD_SYNC = + "CREATE TRIGGER folders_new_cloud_sync_trigger AFTER INSERT ON " + FileColumn::FILES_TABLE + + " FOR EACH ROW WHEN new.isDirectory == 1 AND new.dirty_type == " + + std::to_string(static_cast(DirtyType::TYPE_NEW)) + + " BEGIN SELECT cloud_sync_func(" + "'" + userId + "', " + "'" + bundleName + "'); END;"; + return CREATE_FOLDERS_NEW_CLOUD_SYNC; +} + +static const std::string &UpdateFileTriggerSync(RdbStore &store) +{ + string userId; + string bundleName; + GenCloudSyncTriggerFuncParams(store, userId, bundleName); + static const string CREATE_FILES_UPDATE_CLOUD_SYNC = + "CREATE TRIGGER files_update_cloud_sync_trigger AFTER UPDATE ON " + FileColumn::FILES_TABLE + + " FOR EACH ROW WHEN OLD.dirty_type IN (0,1,2,3) AND new.dirty_type IN (2,3)" + + " AND OLD.meta_time_edited != new.meta_time_edited" + + " BEGIN SELECT cloud_sync_func(" + "'" + userId + "', " + "'" + bundleName + "'); END;"; + return CREATE_FILES_UPDATE_CLOUD_SYNC; +} + +static const std::string &DeleteFileTriggerSync(RdbStore &store) +{ + string userId; + string bundleName; + GenCloudSyncTriggerFuncParams(store, userId, bundleName); + static const string CREATE_FILES_DELETE_CLOUD_SYNC = + "CREATE TRIGGER files_delete_cloud_sync_trigger AFTER UPDATE ON " + FileColumn::FILES_TABLE + + " FOR EACH ROW WHEN OLD.dirty_type IN (0,2,3) AND new.dirty_type == " + + std::to_string(static_cast(DirtyType::TYPE_DELETED)) + + " BEGIN SELECT cloud_sync_func(" + "'" + userId + "', " + "'" + bundleName + "'); END;"; + return CREATE_FILES_DELETE_CLOUD_SYNC; +} + +static const std::string &LocalFileTriggerSync(RdbStore &store) +{ + string userId; + string bundleName; + GenCloudSyncTriggerFuncParams(store, userId, bundleName); + static const string CREATE_FILES_LOCAL_CLOUD_SYNC = + "CREATE TRIGGER files_local_cloud_sync_trigger AFTER UPDATE ON " + FileColumn::FILES_TABLE + + " FOR EACH ROW WHEN OLD.dirty_type IN (1,6) AND new.dirty_type == " + + std::to_string(static_cast(DirtyType::TYPE_NEW)) + + " AND OLD.file_status NOT IN (0,1) AND new.file_status NOT IN (1,2)" + + " BEGIN SELECT cloud_sync_func(" + "'" + userId + "', " + "'" + bundleName + "'); END;"; + return CREATE_FILES_LOCAL_CLOUD_SYNC; +} + +static int32_t ExecuteSql(RdbStore &store) +{ + static const vector onCreateSqlStrs = { + FileColumn::CREATE_FILE_TABLE, + FileColumn::CREATE_PARENT_CLOUD_ID_INDEX, + }; + for (const string& sqlStr : onCreateSqlStrs) { + if (store.ExecuteSql(sqlStr) != NativeRdb::E_OK) { + return NativeRdb::E_ERROR; + } + } + return NativeRdb::E_OK; +} + +int32_t CloudDiskDataCallBack::OnCreate(RdbStore &store) +{ + if (ExecuteSql(store) != NativeRdb::E_OK) { + return NativeRdb::E_ERROR; + } + return NativeRdb::E_OK; +} + +static void VersionAddParentCloudIdIndex(RdbStore &store) +{ + const string executeSqlStr = FileColumn::CREATE_PARENT_CLOUD_ID_INDEX; + int32_t ret = store.ExecuteSql(executeSqlStr); + if (ret != NativeRdb::E_OK) { + LOGE("add parent cloud id index fail, err %{public}d", ret); + } +} + +static void VersionFixFileTrigger(RdbStore &store) +{ + const string dropFilesUpdateTrigger = "DROP TRIGGER IF EXISTS files_update_cloud_sync_trigger"; + if (store.ExecuteSql(dropFilesUpdateTrigger) != NativeRdb::E_OK) { + LOGE("drop files_update_cloud_sync_trigger fail"); + } + const string addUpdateFileTrigger = UpdateFileTriggerSync(store); + int32_t ret = store.ExecuteSql(addUpdateFileTrigger); + if (ret != NativeRdb::E_OK) { + LOGE("add update file trigger fail, err %{public}d", ret); + } + const string addDeleteFileTrigger = DeleteFileTriggerSync(store); + ret = store.ExecuteSql(addDeleteFileTrigger); + if (ret != NativeRdb::E_OK) { + LOGE("add delete file trigger fail, err %{public}d", ret); + } + const string addLocalFileTrigger = LocalFileTriggerSync(store); + ret = store.ExecuteSql(addLocalFileTrigger); + if (ret != NativeRdb::E_OK) { + LOGE("add local file trigger fail, err %{public}d", ret); + } +} + +static void VersionFixCreateAndLocalTrigger(RdbStore &store) +{ + const string dropFilesCreateTrigger = "DROP TRIGGER IF EXISTS files_new_cloud_sync_trigger"; + if (store.ExecuteSql(dropFilesCreateTrigger) != NativeRdb::E_OK) { + LOGE("drop files_new_cloud_sync_trigger fail"); + } + const string dropFilesLocalTrigger = "DROP TRIGGER IF EXISTS files_local_cloud_sync_trigger"; + if (store.ExecuteSql(dropFilesLocalTrigger) != NativeRdb::E_OK) { + LOGE("drop files_local_cloud_sync_trigger fail"); + } + const string addLocalFileTrigger = LocalFileTriggerSync(store); + int32_t ret = store.ExecuteSql(addLocalFileTrigger); + if (ret != NativeRdb::E_OK) { + LOGE("add local file trigger fail, err %{public}d", ret); + } + const string addCreateFolderTrigger = CreateFolderTriggerSync(store); + ret = store.ExecuteSql(addCreateFolderTrigger); + if (ret != NativeRdb::E_OK) { + LOGE("add create folder trigger fail, err %{public}d", ret); + } +} + +static void VersionAddFileStatusAndErrorCode(RdbStore &store) +{ + const string addIsFavorite = FileColumn::ADD_IS_FAVORITE; + int32_t ret = store.ExecuteSql(addIsFavorite); + if (ret != NativeRdb::E_OK) { + LOGE("add is_favorite fail, err %{public}d", ret); + } +} + +static void VersionAddFileStatus(RdbStore &store) +{ + const string addFileStatus = FileColumn::ADD_FILE_STATUS; + int32_t ret = store.ExecuteSql(addFileStatus); + if (ret != NativeRdb::E_OK) { + LOGE("add file_status fail, err %{public}d", ret); + } +} + +static void VersionSetFileStatusDefault(RdbStore &store) +{ + const string setFileStatus = FileColumn::SET_FILE_STATUS_DEFAULT; + int32_t ret = store.ExecuteSql(setFileStatus); + if (ret != NativeRdb::E_OK) { + LOGE("set file_status fail, err %{public}d", ret); + } +} + +static void VersionFixSyncMetatimeTrigger(RdbStore &store) +{ + const string dropFilesUpdateTrigger = "DROP TRIGGER IF EXISTS files_update_cloud_sync_trigger"; + if (store.ExecuteSql(dropFilesUpdateTrigger) != NativeRdb::E_OK) { + LOGE("drop files_update_cloud_sync_trigger fail"); + } + const string addUpdateFileTrigger = UpdateFileTriggerSync(store); + int32_t ret = store.ExecuteSql(addUpdateFileTrigger); + if (ret != NativeRdb::E_OK) { + LOGE("add update file trigger fail, err %{public}d", ret); + } +} + +static void VersionFixRetryTrigger(RdbStore &store) +{ + const string dropFilesLocalTrigger = "DROP TRIGGER IF EXISTS files_local_cloud_sync_trigger"; + if (store.ExecuteSql(dropFilesLocalTrigger) != NativeRdb::E_OK) { + LOGE("drop local file trigger fail"); + } + const string addFilesLocalTrigger = LocalFileTriggerSync(store); + int32_t ret = store.ExecuteSql(addFilesLocalTrigger); + if (ret != NativeRdb::E_OK) { + LOGE("add local file trigger fail, err %{public}d", ret); + } +} + +static void VersionRemoveCloudSyncFuncTrigger(RdbStore &store) +{ + const string dropNewFolderTrigger = "DROP TRIGGER IF EXISTS folders_new_cloud_sync_trigger"; + if (store.ExecuteSql(dropNewFolderTrigger) != NativeRdb::E_OK) { + LOGE("drop folders_new_cloud_sync_trigger fail"); + } + const string dropUpdateFileTrigger = "DROP TRIGGER IF EXISTS files_update_cloud_sync_trigger"; + if (store.ExecuteSql(dropUpdateFileTrigger) != NativeRdb::E_OK) { + LOGE("drop files_update_cloud_sync_trigger fail"); + } + const string dropFileDeleteTrigger = "DROP TRIGGER IF EXISTS files_delete_cloud_sync_trigger"; + if (store.ExecuteSql(dropFileDeleteTrigger) != NativeRdb::E_OK) { + LOGE("drop files_delete_cloud_sync_trigger fail"); + } + const string dropFileLocalTrigger = "DROP TRIGGER IF EXISTS files_local_cloud_sync_trigger"; + if (store.ExecuteSql(dropFileLocalTrigger) != NativeRdb::E_OK) { + LOGE("drop files_local_cloud_sync_trigger fail"); + } +} + +static void VersionAddThmFlag(RdbStore &store) +{ + const string addThmFlag = FileColumn::ADD_THM_FLAG; + int32_t ret = store.ExecuteSql(addThmFlag); + if (ret != NativeRdb::E_OK) { + LOGE("add thm_flag fail, err %{public}d", ret); + } + const string addLcdFlag = FileColumn::ADD_LCD_FLAG; + ret = store.ExecuteSql(addLcdFlag); + if (ret != NativeRdb::E_OK) { + LOGE("add lcd_flag fail, err %{public}d", ret); + } + const string addUploadFlag = FileColumn::ADD_UPLOAD_FLAG; + ret = store.ExecuteSql(addUploadFlag); + if (ret != NativeRdb::E_OK) { + LOGE("add no_need_upload fail, err %{public}d", ret); + } +} + +static void VersionAddSrcCloudId(RdbStore &store) +{ + const string addSrcCloudId = FileColumn::ADD_SRC_CLOUD_ID; + int32_t ret = store.ExecuteSql(addSrcCloudId); + if (ret != NativeRdb::E_OK) { + LOGE("add src_cloud_id fail, err %{public}d", ret); + } +} + +static void VersionAddThmSize(RdbStore &store) +{ + const string addThmSize = FileColumn::ADD_THM_SIZE; + int32_t ret = store.ExecuteSql(addThmSize); + if (ret != NativeRdb::E_OK) { + LOGE("add thm_size fail, err %{public}d", ret); + } + const string addLcdSize = FileColumn::ADD_LCD_SIZE; + ret = store.ExecuteSql(addLcdSize); + if (ret != NativeRdb::E_OK) { + LOGE("add lcd_size fail, err %{public}d", ret); + } +} + +static int32_t GetMetaBaseData(CloudDiskFileInfo &info, const shared_ptr resultSet) +{ + RETURN_ON_ERR(CloudDiskRdbUtils::GetString(FileColumn::CLOUD_ID, info.cloudId, resultSet)); + RETURN_ON_ERR(CloudDiskRdbUtils::GetString(FileColumn::FILE_NAME, info.name, resultSet)); + int32_t isDir = 0; + RETURN_ON_ERR(CloudDiskRdbUtils::GetInt(FileColumn::IS_DIRECTORY, isDir, resultSet)); + info.IsDirectory = static_cast(isDir); + int32_t position = 0; + RETURN_ON_ERR(CloudDiskRdbUtils::GetInt(FileColumn::POSITION, position, resultSet)); + info.location = static_cast(position); + int64_t atime = 0; + RETURN_ON_ERR(CloudDiskRdbUtils::GetLong(FileColumn::FILE_TIME_ADDED, atime, resultSet)); + info.atime = static_cast(atime); + int64_t mtime = 0; + RETURN_ON_ERR(CloudDiskRdbUtils::GetLong(FileColumn::FILE_TIME_EDITED, mtime, resultSet)); + info.mtime = static_cast(mtime); + int64_t size = 0; + RETURN_ON_ERR(CloudDiskRdbUtils::GetLong(FileColumn::FILE_SIZE, size, resultSet)); + info.size = static_cast(size); + int64_t rowId = 0; + RETURN_ON_ERR(CloudDiskRdbUtils::GetLong(FileColumn::ROW_ID, rowId, resultSet)); + info.rowId = static_cast(rowId); + return E_OK; +} + +static int32_t GetUserIdAndBundleName(RdbStore &store, uint32_t &userId, string &bundleName) +{ + string userIdStr; + GenCloudSyncTriggerFuncParams(store, userIdStr, bundleName); + bool isValid = std::all_of(userIdStr.begin(), userIdStr.end(), ::isdigit); + if (!isValid) { + LOGE("invalid user Id"); + return E_INVAL_ARG; + } + userId = static_cast(std::stoi(userIdStr)); + return E_OK; +} + +static int32_t GenerateDentryRecursively(RdbStore &store, const string &parentCloudId) +{ + LOGD("Generate dentry recursively parentCloudId:%{public}s", parentCloudId.c_str()); + uint32_t userId; + string bundleName; + RETURN_ON_ERR(GetUserIdAndBundleName(store, userId, bundleName)); + AbsRdbPredicates lookUpPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + lookUpPredicates.EqualTo(FileColumn::PARENT_CLOUD_ID, parentCloudId) + ->And()->EqualTo(FileColumn::FILE_TIME_RECYCLED, "0"); + int32_t rowCount = 0; + uint64_t offset = 0; + do { + lookUpPredicates.Limit(offset, CHECK_QUERY_LIMIT); + auto resultSet = store.Query(lookUpPredicates, FileColumn::FILE_SYSTEM_QUERY_COLUMNS); + if (resultSet == nullptr) { + LOGE("failed to get result set at offset:%{public}" PRIu64 "", offset); + continue; + } + int32_t ret = resultSet->GetRowCount(rowCount); + if (ret != E_OK || rowCount < 0) { + LOGE("failed to get row count at offset:%{public}" PRIu64 ", ret: %{public}d", offset, ret); + continue; + } + if (rowCount == 0) { + return E_OK; + } + CloudDiskFileInfo info; + while (resultSet->GoToNextRow() == 0) { + RETURN_ON_ERR(GetMetaBaseData(info, resultSet)); + MetaBase metaBase(info.name); + auto callback = [info] (MetaBase &m) { + m.cloudId = info.cloudId; + m.atime = info.atime; + m.mtime = info.mtime; + m.size = info.size; + m.mode = (info.IsDirectory) ? (S_IFDIR | STAT_MODE_DIR) : (S_IFREG | STAT_MODE_REG); + m.position = info.location; + m.fileType = FILE_TYPE_CONTENT; + }; + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, parentCloudId); + ret = metaFile->DoLookupAndUpdate(info.name, callback); + if (ret != E_OK) { + LOGE("insert new dentry failed, ret = %{public}d", ret); + return ret; + } + if (info.IsDirectory) {RETURN_ON_ERR(GenerateDentryRecursively(store, info.cloudId));} + } + offset += CHECK_QUERY_LIMIT; + } while (rowCount != 0); + return E_OK; +} + +static int32_t GenerateRecycleDentryRecursively(RdbStore &store) +{ + uint32_t userId; + string bundleName; + RETURN_ON_ERR(GetUserIdAndBundleName(store, userId, bundleName)); + AbsRdbPredicates lookUpPredicates = AbsRdbPredicates(FileColumn::FILES_TABLE); + lookUpPredicates.NotEqualTo(FileColumn::FILE_TIME_RECYCLED, "0"); + int32_t rowCount = 0; + uint64_t offset = 0; + do { + lookUpPredicates.Limit(offset, CHECK_QUERY_LIMIT); + auto resultSet = store.Query(lookUpPredicates, FileColumn::FILE_SYSTEM_QUERY_COLUMNS); + if (resultSet == nullptr) { + LOGE("failed to get result set at offset:%{public}" PRIu64 "", offset); + continue; + } + int32_t ret = resultSet->GetRowCount(rowCount); + if (ret != E_OK || rowCount < 0) { + LOGE("failed to get row count at offset:%{public}" PRIu64 ", ret: %{public}d", offset, ret); + continue; + } + if (rowCount == 0) { + return E_OK; + } + CloudDiskFileInfo info; + while (resultSet->GoToNextRow() == 0) { + RETURN_ON_ERR(GetMetaBaseData(info, resultSet)); + string uniqueName = info.name + "_" + std::to_string(info.rowId); + MetaBase metaBase(uniqueName); + auto callback = [info] (MetaBase &m) { + m.cloudId = info.cloudId; + m.atime = info.atime; + m.mtime = info.mtime; + m.size = info.size; + m.mode = (info.IsDirectory) ? (S_IFDIR | STAT_MODE_DIR) : (S_IFREG | STAT_MODE_REG); + m.position = info.location; + m.fileType = FILE_TYPE_CONTENT; + }; + RETURN_ON_ERR(MetaFileMgr::GetInstance().CreateRecycleDentry(userId, bundleName)); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, RECYCLE_CLOUD_ID); + ret = metaFile->DoLookupAndUpdate(uniqueName, callback); + if (ret != E_OK) { + LOGE("insert new dentry failed, ret = %{public}d", ret); + return ret; + } + } + offset += CHECK_QUERY_LIMIT; + } while (rowCount != 0); + return E_OK; +} + +static void VersionAddCheckFlag(RdbStore &store) +{ + const string addCheckFlag = FileColumn::ADD_CHECK_FLAG; + int32_t ret = store.ExecuteSql(addCheckFlag); + if (ret != NativeRdb::E_OK) { + LOGE("add check_flag fail, ret = %{public}d", ret); + } + ret = GenerateDentryRecursively(store, ROOT_CLOUD_ID); + if (ret != E_OK) { + LOGE("failed to generate dentry recursively, ret = %{public}d", ret); + } + ret = GenerateRecycleDentryRecursively(store); + if (ret != E_OK) { + LOGE("failed to generate recycle ndentry recursively, ret = %{public}d", ret); + } +} + +static void VersionAddRootDirectory(RdbStore &store) +{ + const string addRootDirectory = "ALTER Table " + FileColumn::FILES_TABLE + + " ADD COLUMN " + FileColumn::ROOT_DIRECTORY + " TEXT"; + int32_t ret = store.ExecuteSql(addRootDirectory); + if (ret != NativeRdb::E_OK) { + LOGE("add root_directory fail, ret = %{public}d", ret); + } + ValuesBucket rootDirectory; + rootDirectory.PutString(FileColumn::ROOT_DIRECTORY, system::GetParameter(FILEMANAGER_KEY, "")); + int32_t changedRows = -1; + vector bindArgs; + ret = store.Update(changedRows, FileColumn::FILES_TABLE, rootDirectory, "", bindArgs); + if (ret != NativeRdb::E_OK) { + LOGE("set root_directory fail, err %{public}d", ret); + } +} + +static void VersionAddAttribute(RdbStore &store) +{ + const string attrbute = FileColumn::ADD_ATTRIBUTE; + int32_t ret = store.ExecuteSql(attrbute); + if (ret != NativeRdb::E_OK) { + LOGE("add attrbute fail, ret = %{public}d", ret); + } +} + +int32_t CloudDiskDataCallBack::OnUpgrade(RdbStore &store, int32_t oldVersion, int32_t newVersion) +{ + LOGD("OnUpgrade old:%d, new:%d", oldVersion, newVersion); + if (oldVersion < VERSION_ADD_PARENT_CLOUD_ID_INDEX) { + VersionAddParentCloudIdIndex(store); + } + if (oldVersion < VERSION_FIX_FILE_TRIGGER) { + VersionFixFileTrigger(store); + } + if (oldVersion < VERSION_FIX_CREATE_AND_LOCAL_TRIGGER) { + VersionFixCreateAndLocalTrigger(store); + } + if (oldVersion < VERSION_ADD_STATUS_ERROR_FAVORITE) { + VersionAddFileStatusAndErrorCode(store); + } + if (oldVersion < VERSION_ADD_FILE_STATUS) { + VersionAddFileStatus(store); + } + if (oldVersion < VERSION_SET_FILE_STATUS_DEFAULT) { + VersionSetFileStatusDefault(store); + } + if (oldVersion < VERSION_ADD_CHECK_FLAG) { + VersionAddCheckFlag(store); + } + if (oldVersion < VERSION_ADD_ROOT_DIRECTORY) { + VersionAddRootDirectory(store); + } + if (oldVersion < VERSION_FIX_SYNC_METATIME_TRIGGER) { + VersionFixSyncMetatimeTrigger(store); + } + if (oldVersion < VERSION_FIX_RETRY_TRIGGER) { + VersionFixRetryTrigger(store); + } + + if (oldVersion < VERSION_REMOVE_CLOUD_SYNC_FUNC_TRIGGER) { + VersionRemoveCloudSyncFuncTrigger(store); + } + + if (oldVersion < VERSION_ADD_ATTRIBUTE) { + VersionAddAttribute(store); + } + if (oldVersion < VERSION_ADD_THM_FLAG) { + VersionAddThmFlag(store); + } + if (oldVersion < VERSION_ADD_SRC_CLOUD_ID) { + VersionAddSrcCloudId(store); + } + if (oldVersion < VERSION_ADD_THM_SIZE) { + VersionAddThmSize(store); + } + return NativeRdb::E_OK; +} + +int32_t CloudDiskRdbStore::CreateDentryFile(MetaBase metaBase, std::string destParentCloudId) +{ + auto metaFileCallBack = [&metaBase] (MetaBase &m) { + m.size = metaBase.size; + m.name = metaBase.name; + m.cloudId = metaBase.cloudId; + m.atime = metaBase.atime; + m.mtime = metaBase.mtime; + m.fileType = metaBase.fileType; + m.mode = metaBase.mode; + }; + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId_, bundleName_, destParentCloudId); + int32_t ret = metaFile->DoLookupAndCreate(metaBase.name, metaFileCallBack); + if (ret != E_OK) { + LOGE("create new dentry failed, ret : %{public}d", ret); + } + return ret; +} + +static void getCopyValues(std::string srcCloudId, std::string destCloudId, std::string destParentCloudId, + std::shared_ptr resultSet, ValuesBucket &fileInfo) +{ + int32_t isDirectory; + CloudDiskRdbUtils::GetInt(FileColumn::IS_DIRECTORY, isDirectory, resultSet); + std::string sha256; + CloudDiskRdbUtils::GetString(FileColumn::FILE_SHA256, sha256, resultSet); + int64_t fileTimeRecycled; + CloudDiskRdbUtils::GetLong(FileColumn::FILE_TIME_RECYCLED, fileTimeRecycled, resultSet); + int64_t metaTimeEdited; + CloudDiskRdbUtils::GetLong(FileColumn::META_TIME_EDITED, metaTimeEdited, resultSet); + int64_t fileTimeVisit; + CloudDiskRdbUtils::GetLong(FileColumn::FILE_TIME_VISIT, fileTimeVisit, resultSet); + int32_t syncStatus; + CloudDiskRdbUtils::GetInt(FileColumn::SYNC_STATUS, syncStatus, resultSet); + std::string fileCalegory; + CloudDiskRdbUtils::GetString(FileColumn::FILE_CATEGORY, fileCalegory, resultSet); + int32_t isFavorite; + CloudDiskRdbUtils::GetInt(FileColumn::IS_FAVORITE, isFavorite, resultSet); + int32_t checkFlag; + CloudDiskRdbUtils::GetInt(FileColumn::CHECK_FLAG, checkFlag, resultSet); + std::string rootDirectory; + CloudDiskRdbUtils::GetString(FileColumn::ROOT_DIRECTORY, rootDirectory, resultSet); + std::string attribute; + CloudDiskRdbUtils::GetString(FileColumn::ATTRIBUTE, attribute, resultSet); + int32_t thmFlag; + CloudDiskRdbUtils::GetInt(FileColumn::THM_FLAG, thmFlag, resultSet); + thmFlag = thmFlag == FLAG_NOT_EXIST ? thmFlag : FLAG_TO_BE_UPLOAD; + int32_t lcdFlag; + CloudDiskRdbUtils::GetInt(FileColumn::LCD_FLAG, lcdFlag, resultSet); + lcdFlag = lcdFlag == FLAG_NOT_EXIST ? lcdFlag : FLAG_TO_BE_UPLOAD; + int32_t noNeedUpload; + CloudDiskRdbUtils::GetInt(FileColumn::NO_NEED_UPLOAD, noNeedUpload, resultSet); + + fileInfo.PutString(FileColumn::CLOUD_ID, destCloudId); + fileInfo.PutInt(FileColumn::IS_DIRECTORY, isDirectory); + fileInfo.PutString(FileColumn::PARENT_CLOUD_ID, destParentCloudId); + fileInfo.PutString(FileColumn::FILE_SHA256, sha256); + fileInfo.PutLong(FileColumn::FILE_TIME_RECYCLED, fileTimeRecycled); + fileInfo.PutLong(FileColumn::META_TIME_EDITED, metaTimeEdited); + fileInfo.PutLong(FileColumn::FILE_TIME_VISIT, fileTimeVisit); + fileInfo.PutInt(FileColumn::DIRECTLY_RECYCLED, DIRECTLY_RECYCLED_COPY); + fileInfo.PutLong(FileColumn::VERSION, VERSION_COPY); + fileInfo.PutLong(FileColumn::OPERATE_TYPE, static_cast(OperationType::COPY)); + fileInfo.PutInt(FileColumn::SYNC_STATUS, syncStatus); + fileInfo.PutInt(FileColumn::POSITION, CLOUD); + fileInfo.PutInt(FileColumn::DIRTY_TYPE, static_cast(DirtyType::TYPE_COPY)); + fileInfo.PutString(FileColumn::FILE_CATEGORY, fileCalegory); + fileInfo.PutInt(FileColumn::IS_FAVORITE, isFavorite); + fileInfo.PutInt(FileColumn::FILE_STATUS, static_cast(FileStatus::UNKNOW)); + fileInfo.PutInt(FileColumn::CHECK_FLAG, checkFlag); + fileInfo.PutString(FileColumn::ROOT_DIRECTORY, rootDirectory); + fileInfo.PutString(FileColumn::ATTRIBUTE, attribute); + fileInfo.PutInt(FileColumn::THM_FLAG, thmFlag); + fileInfo.PutInt(FileColumn::LCD_FLAG, lcdFlag); + fileInfo.PutInt(FileColumn::NO_NEED_UPLOAD, noNeedUpload); + fileInfo.PutString(FileColumn::SRC_CLOUD_ID, srcCloudId); +} + +int32_t CloudDiskRdbStore::InsertCopyData(std::string srcCloudId, std::string destCloudId, + std::string destParentCloudId, + std::shared_ptr resultSet) +{ + RDBPTR_IS_NULLPTR(rdbStore_); + ValuesBucket fileInfo; + int32_t ret; + getCopyValues(srcCloudId, destCloudId, destParentCloudId, resultSet, fileInfo); + std::string fileName; + CloudDiskRdbUtils::GetString(FileColumn::FILE_NAME, fileName, resultSet); + std::string oldName = fileName; + RETURN_ON_ERR(CheckIsConflict(oldName, destParentCloudId, fileName)); + fileInfo.PutString(FileColumn::FILE_NAME, fileName); + int64_t fileSize; + CloudDiskRdbUtils::GetLong(FileColumn::FILE_SIZE, fileSize, resultSet); + fileInfo.PutLong(FileColumn::FILE_SIZE, fileSize); + int64_t fileTimeAdded = UTCTimeMilliSeconds(); + fileInfo.PutLong(FileColumn::FILE_TIME_ADDED, fileTimeAdded); + int32_t fileType; + CloudDiskRdbUtils::GetInt(FileColumn::FILE_TYPE, fileType, resultSet); + fileInfo.PutInt(FileColumn::FILE_TYPE, fileType); + int64_t fileTimeEdited = UTCTimeMilliSeconds(); + fileInfo.PutLong(FileColumn::FILE_TIME_EDITED, fileTimeEdited); + + TransactionOperations rdbTransaction(rdbStore_); + auto [rdbRet, transaction] = rdbTransaction.Start(); + if (rdbRet != E_OK) { + LOGE("rdbstore begin transaction failed ,ret = %{public}d", rdbRet); + return E_RDB; + } + int64_t outRowId = 0; + std::tie(rdbRet, outRowId) = transaction->Insert(FileColumn::FILES_TABLE, fileInfo); + if (rdbRet != E_OK) { + LOGE("insert new file record in DB failed ,ret = %{public}d", rdbRet); + return rdbRet; + } + + MetaBase metaBase(fileName, destCloudId); + metaBase.size = static_cast(fileSize); + metaBase.fileType = fileType; + metaBase.atime = static_cast(fileTimeAdded); + metaBase.mtime = static_cast(fileTimeEdited); + metaBase.mode = metaBase.mode = S_IFREG | STAT_MODE_FILE; + ret = CreateDentryFile(metaBase, destParentCloudId); + if (ret != E_OK) { + LOGE("create new dentry failed, ret = %{public}d", ret); + return ret; + } + rdbTransaction.Finish(); + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); + return ret; +} + +int32_t CloudDiskRdbStore::CopyFile(std::string srcCloudId, std::string destCloudId, std::string bundleName, + const int userId, std::string destPath) +{ + std::string parentCloudId = CloudFileUtils::GetCloudId(destPath); + AbsRdbPredicates getCopyMsg = AbsRdbPredicates(FileColumn::FILES_TABLE); + getCopyMsg.EqualTo(FileColumn::CLOUD_ID, srcCloudId); + auto resultSet = rdbStore_->QueryByStep(getCopyMsg, FileColumn::DISK_CLOUD_FOR_COPY); + if (resultSet == nullptr) { + LOGE("Query failed, no such file in rdb"); + return E_RDB; + } + + if (resultSet->GoToNextRow() != E_OK) { + LOGE("result set to file info go to next row failed"); + return E_RDB; + } + + int32_t ret = InsertCopyData(srcCloudId, destCloudId, parentCloudId, resultSet); + if (ret!= E_OK) { + LOGE("Failed to insert copy data to the rdb, ret = %{public}d", ret); + } + return ret; +} +} \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/src/clouddisk_sync_helper.cpp b/cloud_file/services/clouddisk_database/src/clouddisk_sync_helper.cpp new file mode 100644 index 0000000..fa01eab --- /dev/null +++ b/cloud_file/services/clouddisk_database/src/clouddisk_sync_helper.cpp @@ -0,0 +1,103 @@ +/* + * 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 "clouddisk_sync_helper.h" + +#include "utils_log.h" +#include "dfs_error.h" +#include "common_timer_errors.h" +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +constexpr int32_t MIN_USER_ID = 100; + +CloudDiskSyncHelper& CloudDiskSyncHelper::GetInstance() +{ + static CloudDiskSyncHelper instance_; + return instance_; +} + +CloudDiskSyncHelper::CloudDiskSyncHelper() : timer_(std::make_unique("CloudDiskTriggerSync")) +{ + timer_->Setup(); +} + +CloudDiskSyncHelper::~CloudDiskSyncHelper() +{ + if (timer_) { + timer_->Shutdown(true); + timer_ = nullptr; + } +} + +void CloudDiskSyncHelper::RegisterTriggerSync(const std::string &bundleName, const int32_t &userId) +{ + if (timer_ == nullptr || bundleName.empty() || userId < MIN_USER_ID) { + LOGE("TriggerSync parameter is invalid"); + return; + } + LOGD("begin trigger sync, bundleName = %{public}s, userId = %{public}d", bundleName.c_str(), userId); + UnregisterRepeatingTriggerSync(bundleName, userId); + string keyId = to_string(userId) + bundleName; + function callback = [this, bundleName, userId] { OnTriggerSyncCallback(bundleName, userId); }; + uint32_t timerId = timer_->Register(callback, SYNC_INTERVAL, true); + if (timerId == Utils::TIMER_ERR_DEAL_FAILED) { + LOGE("Register timer failed"); + return; + } + shared_ptr triggerInfoPtr = make_shared(); + triggerInfoPtr->timerId = timerId; + triggerInfoPtr->callback = callback; + lock_guard lock(triggerMapMutex_); + triggerInfoMap_.emplace(keyId, triggerInfoPtr); +} + +void CloudDiskSyncHelper::UnregisterRepeatingTriggerSync(const std::string &bundleName, const int32_t &userId) +{ + if (timer_ == nullptr || bundleName.empty() || userId < MIN_USER_ID) { + LOGE("UnregisterRepeatingTrigger parameter is invalid"); + return; + } + string keyId = to_string(userId) + bundleName; + bool isSuccess = false; + lock_guard lock(triggerMapMutex_); + auto iterator = triggerInfoMap_.find(keyId); + if (iterator != triggerInfoMap_.end()) { + LOGD("bundleName: %{public}s, userId: %{public}d is exist", bundleName.c_str(), userId); + auto triggerInfoPtr = iterator->second; + timer_->Unregister(triggerInfoPtr->timerId); + triggerInfoMap_.erase(keyId); + isSuccess = true; + } + LOGD("Unregister repeating trigger result is %{public}d", isSuccess); +} + +void CloudDiskSyncHelper::OnTriggerSyncCallback(const std::string &bundleName, const int32_t &userId) +{ + string keyId = to_string(userId) + bundleName; + { + lock_guard lock(triggerMapMutex_); + triggerInfoMap_.erase(keyId); + } + LOGI("cloud sync manager trigger sync, bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId); + int32_t ret = CloudSync::CloudSyncManagerLite::GetInstance().TriggerSync(bundleName, userId); + if (ret != 0) { + LOGE("cloud sync manager trigger sync err %{public}d", ret); + } +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/clouddisk_database/src/file_column.cpp b/cloud_file/services/clouddisk_database/src/file_column.cpp new file mode 100644 index 0000000..f659c8c --- /dev/null +++ b/cloud_file/services/clouddisk_database/src/file_column.cpp @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2023-2024 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 "file_column.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +const std::string FileColumn::CLOUD_ID = "cloud_id"; +const std::string FileColumn::IS_DIRECTORY = "isDirectory"; +const std::string FileColumn::FILE_NAME = "file_name"; +const std::string FileColumn::PARENT_CLOUD_ID = "parent_cloud_id"; +const std::string FileColumn::FILE_SIZE = "file_size"; +const std::string FileColumn::FILE_SHA256 = "sha256"; +const std::string FileColumn::FILE_TIME_ADDED = "time_added"; +const std::string FileColumn::FILE_TIME_EDITED = "time_edited"; +const std::string FileColumn::FILE_TIME_RECYCLED = "time_recycled"; +const std::string FileColumn::META_TIME_EDITED = "meta_time_edited"; +const std::string FileColumn::FILE_TIME_VISIT = "time_visit"; +const std::string FileColumn::DIRECTLY_RECYCLED = "directly_recycled"; +const std::string FileColumn::VERSION = "version"; +const std::string FileColumn::OPERATE_TYPE = "operateType"; +const std::string FileColumn::SYNC_STATUS = "sync_status"; +const std::string FileColumn::POSITION = "position"; +const std::string FileColumn::THM_FLAG = "thm_flag"; +const std::string FileColumn::LCD_FLAG = "lcd_flag"; +const std::string FileColumn::NO_NEED_UPLOAD = "no_need_upload"; +const std::string FileColumn::DIRTY_TYPE = "dirty_type"; +const std::string FileColumn::MIME_TYPE = "mimetype"; +const std::string FileColumn::FILE_TYPE = "file_type"; +const std::string FileColumn::FILE_CATEGORY = "file_category"; +const std::string FileColumn::IS_FAVORITE = "isFavorite"; +const std::string FileColumn::FILE_STATUS = "file_status"; +const std::string FileColumn::ROW_ID = "rowid"; +const std::string FileColumn::CHECK_FLAG = "check_flag"; +const std::string FileColumn::ROOT_DIRECTORY = "root_directory"; +const std::string FileColumn::ATTRIBUTE = "attribute"; +const std::string FileColumn::FILES_TABLE = "CloudDisk"; +const std::string FileColumn::PARENT_CLOUD_ID_INDEX = "parentCloudId_index"; +const std::string FileColumn::SRC_CLOUD_ID = "src_cloud_id"; +const std::string FileColumn::THM_SIZE = "thm_size"; +const std::string FileColumn::LCD_SIZE = "lcd_size"; + +const std::string FileColumn::CREATE_FILE_TABLE = "CREATE TABLE IF NOT EXISTS " + + FILES_TABLE + " (" + + CLOUD_ID + " TEXT PRIMARY KEY NOT NULL, " + + IS_DIRECTORY + " INT, " + + FILE_NAME + " TEXT NOT NULL, " + + PARENT_CLOUD_ID + " TEXT NOT NULL, " + + FILE_SIZE + " BIGINT, " + + FILE_SHA256 + " TEXT, " + + FILE_TIME_ADDED + " BIGINT, " + + FILE_TIME_EDITED + " BIGINT, " + + FILE_TIME_RECYCLED + " BIGINT DEFAULT 0, " + + META_TIME_EDITED + " BIGINT, " + + FILE_TIME_VISIT + " BIGINT DEFAULT 0, " + + DIRECTLY_RECYCLED + " INT DEFAULT 0, " + + VERSION + " BIGINT DEFAULT 0, " + + OPERATE_TYPE + " BIGINT DEFAULT 0, " + + SYNC_STATUS + " INT DEFAULT 0, " + + POSITION + " INT DEFAULT 1, " + + DIRTY_TYPE + " INT DEFAULT 1, " + + MIME_TYPE + " TEXT, " + + FILE_TYPE + " INT, " + + FILE_CATEGORY + " TEXT, " + + IS_FAVORITE + " INT DEFAULT 0, " + + FILE_STATUS + " INT DEFAULT 4, " + + CHECK_FLAG + " INT DEFAULT 0, " + + ROOT_DIRECTORY + " TEXT, " + + ATTRIBUTE + " TEXT, " + + THM_FLAG + " INT DEFAULT 0, " + + LCD_FLAG + " INT DEFAULT 0, " + + NO_NEED_UPLOAD + " INT DEFAULT 0, " + + SRC_CLOUD_ID + " TEXT, " + + THM_SIZE + "BIGINT DEFAULT 0, " + + LCD_SIZE + "BIGINT DEFAULT 0)"; + +const std::string FileColumn::CREATE_PARENT_CLOUD_ID_INDEX = "CREATE INDEX IF NOT EXISTS " + + PARENT_CLOUD_ID_INDEX + " ON " + FILES_TABLE + + " (" + PARENT_CLOUD_ID + ")"; + +const std::string FileColumn::ADD_IS_FAVORITE = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + IS_FAVORITE + " INT DEFAULT 0"; + +const std::string FileColumn::ADD_FILE_STATUS = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + FILE_STATUS + " INT"; + +const std::string FileColumn::SET_FILE_STATUS_DEFAULT = "UPDATE " + FILES_TABLE + + " SET " + FILE_STATUS + " = 4 WHERE " + FILE_STATUS + " IS NULL"; + +const std::string FileColumn::ADD_CHECK_FLAG = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + CHECK_FLAG + " INT DEFAULT 0"; + +const std::string FileColumn::ADD_ATTRIBUTE = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + ATTRIBUTE + " TEXT"; + +const std::string FileColumn::ADD_THM_FLAG = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + THM_FLAG + " INT DEFAULT 0"; + +const std::string FileColumn::ADD_LCD_FLAG = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + LCD_FLAG + " INT DEFAULT 0"; + +const std::string FileColumn::ADD_UPLOAD_FLAG = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + NO_NEED_UPLOAD + " INT DEFAULT 0"; + +const std::string FileColumn::ADD_SRC_CLOUD_ID = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + SRC_CLOUD_ID + " TEXT"; + +const std::string FileColumn::ADD_THM_SIZE = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + THM_SIZE + " BIGINT DEFAULT 0"; + +const std::string FileColumn::ADD_LCD_SIZE = "ALTER Table " + FILES_TABLE + + " ADD COLUMN " + LCD_SIZE + " BIGINT DEFAULT 0"; + +const std::vector FileColumn::FILE_SYSTEM_QUERY_COLUMNS = { + FILE_NAME, + CLOUD_ID, + PARENT_CLOUD_ID, + POSITION, + FILE_SIZE, + META_TIME_EDITED, + FILE_TIME_ADDED, + FILE_TIME_EDITED, + IS_DIRECTORY, + ROW_ID +}; + +const std::vector FileColumn::DISK_CLOUD_SYNC_COLUMNS = { + CLOUD_ID, + IS_DIRECTORY, + FILE_NAME, + PARENT_CLOUD_ID, + FILE_SIZE, + FILE_SHA256, + FILE_TIME_ADDED, + FILE_TIME_EDITED, + FILE_TIME_RECYCLED, + META_TIME_EDITED, + DIRECTLY_RECYCLED, + VERSION, + OPERATE_TYPE, + ROOT_DIRECTORY, + ATTRIBUTE, + THM_FLAG, + LCD_FLAG, + ROW_ID, + THM_SIZE, + LCD_SIZE +}; + +//File copy requires all fields in the database, and one is added here when adding a new column ... +const std::vector FileColumn::DISK_CLOUD_FOR_COPY = { + CLOUD_ID, + IS_DIRECTORY, + FILE_NAME, + PARENT_CLOUD_ID, + FILE_SIZE, + FILE_SHA256, + FILE_TIME_ADDED, + FILE_TIME_EDITED, + FILE_TIME_RECYCLED, + META_TIME_EDITED, + FILE_TIME_VISIT, + DIRECTLY_RECYCLED, + VERSION, + OPERATE_TYPE, + SYNC_STATUS, + POSITION, + DIRTY_TYPE, + MIME_TYPE, + FILE_TYPE, + FILE_CATEGORY, + IS_FAVORITE, + FILE_STATUS, + CHECK_FLAG, + ROOT_DIRECTORY, + ATTRIBUTE, + THM_FLAG, + LCD_FLAG, + NO_NEED_UPLOAD, + SRC_CLOUD_ID, +}; + +const std::vector FileColumn::LOCAL_COLUMNS = { + FILE_TIME_VISIT, SYNC_STATUS, POSITION, DIRTY_TYPE, + MIME_TYPE, IS_DIRECTORY, FILE_TYPE, FILE_CATEGORY, +}; + +const std::vector FileColumn::PULL_QUERY_COLUMNS = { + CLOUD_ID, FILE_TIME_RECYCLED, VERSION, DIRTY_TYPE, POSITION, + FILE_TIME_EDITED, FILE_SHA256, FILE_SIZE, FILE_NAME, PARENT_CLOUD_ID, ROW_ID, + IS_DIRECTORY, FILE_TIME_ADDED, FILE_TYPE, ROOT_DIRECTORY, DIRECTLY_RECYCLED, + THM_FLAG, LCD_FLAG, +}; + +const std::vector FileColumn::DISK_ON_UPLOAD_COLUMNS = { + CLOUD_ID, + PARENT_CLOUD_ID, + FILE_NAME, + FILE_TIME_EDITED, + META_TIME_EDITED, + FILE_TIME_RECYCLED, + ROW_ID, + THM_FLAG, + LCD_FLAG, +}; + +const std::vector FileColumn::EXT_ATTR_QUERY_COLUMNS = { + ATTRIBUTE, + POSITION +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon.cfg b/cloud_file/services/cloudfiledaemon.cfg new file mode 100644 index 0000000..0dc01b8 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon.cfg @@ -0,0 +1,22 @@ +{ + "services": [{ + "name": "cloudfiledaemon", + "path": ["/system/bin/sa_main", "/system/profile/cloudfiledaemon.json"], + "uid": "1009", + "gid": ["dfs", "user_data_rw", "system", "ddms", "netsys_socket", "dfs_share", "readproc"], + "sandbox": 0, + "secon": "u:r:cloudfiledaemon:s0", + "apl": "system_basic", + "permission" : [ + "ohos.permission.CLOUDFILE_SYNC", + "ohos.permission.DISTRIBUTED_DATASYNC", + "ohos.permission.MANAGE_LOCAL_ACCOUNTS", + "ohos.permission.ACCESS_SERVICE_DM", + "ohos.permission.INTERNET", + "ohos.permission.USE_CLOUD_DRIVE_SERVICE", + "ohos.permission.READ_CLOUD_SYNC_CONFIG", + "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS", + "ohos.permission.GET_BUNDLE_INFO" + ] + }] +} \ No newline at end of file diff --git a/cloud_file/services/cloudfiledaemon/BUILD.gn b/cloud_file/services/cloudfiledaemon/BUILD.gn new file mode 100644 index 0000000..cf48a76 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/BUILD.gn @@ -0,0 +1,110 @@ +# Copyright (C) 2023-2024 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("cloudfiledaemon") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + cloud_disk = [ + "src/cloud_disk/database_manager.cpp", + "src/cloud_disk/file_operations_base.cpp", + "src/cloud_disk/file_operations_cloud.cpp", + "src/cloud_disk/file_operations_helper.cpp", + "src/cloud_disk/file_operations_local.cpp", + "src/cloud_disk/fuse_operations.cpp", + "src/cloud_disk/account_status.cpp", + "src/cloud_disk/account_status_listener.cpp", + ] + + sources = [ + "src/fuse_manager/cloud_daemon_statistic.cpp", + "src/fuse_manager/fuse_manager.cpp", + "src/ipc/cloud_daemon.cpp", + "src/ipc/cloud_daemon_stub.cpp", + ] + + sources += cloud_disk + + configs += [ "${utils_path}:compiler_configs" ] + + defines = [ "LOG_TAG=\"CloudFileDaemon\"" ] + + include_dirs = [ + "include", + "${utils_path}/cloud_disk/include", + "${utils_path}/dentry/include", + "${utils_path}/log/include", + "${utils_path}/system/include", + "${innerkits_native_path}/cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${services_path}/cloudfiledaemon/include/fuse_manager/", + "${services_path}/cloudfiledaemon/include/ipc/", + "${services_path}/cloudsyncservice/include/data_sync/", + "${clouddisk_database_path}/include", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit_core", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/account_status.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/account_status.h new file mode 100644 index 0000000..db84d43 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/account_status.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 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 CLOUD_FILE_DAEMON_ACCOUNT_STATUS_H +#define CLOUD_FILE_DAEMON_ACCOUNT_STATUS_H + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class AccountStatus { +public: + enum AccountState { + ACCOUNT_LOGIN, + ACCOUNT_LOGOUT, + }; + static bool IsNeedCleanCache(); + static void SetAccountState(AccountState accountState); + static AccountStatus::AccountState GetAccountState(); + +private: + static inline AccountState preAccountState_{AccountState::ACCOUNT_LOGIN}; + static inline AccountState accountState_{AccountState::ACCOUNT_LOGIN}; +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_ACCOUNT_STATUS_H \ No newline at end of file diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/account_status_listener.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/account_status_listener.h new file mode 100644 index 0000000..ec891f9 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/account_status_listener.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 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 CLOUD_FILE_DAEMON_ACCOUNT_STATUS_LISTENER_H +#define CLOUD_FILE_DAEMON_ACCOUNT_STATUS_LISTENER_H + +#include "common_event_subscriber.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class AccountStatusListener { +public: + explicit AccountStatusListener() = default; + ~AccountStatusListener(); + void Start(); + void Stop(); + +private: + std::shared_ptr commonEventSubscriber_ = nullptr; +}; + +class AccountStatusSubscriber : public EventFwk::CommonEventSubscriber { +public: + AccountStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); + ~AccountStatusSubscriber() override {} + void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; + void RemovedClean(const EventFwk::CommonEventData &eventData); +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_ACCOUNT_STATUS_LISTENER_H \ No newline at end of file diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/cloud_disk_inode.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/cloud_disk_inode.h new file mode 100644 index 0000000..e121300 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/cloud_disk_inode.h @@ -0,0 +1,106 @@ +/* + * 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 CLOUD_FILE_DAEMON_CLOUD_DISK_INODE_H +#define CLOUD_FILE_DAEMON_CLOUD_DISK_INODE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cloud_asset_read_session.h" +#include "ffrt_inner.h" +#include "file_operations_base.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { + +enum CLOUD_DISK_INODE_LAYER { + CLOUD_DISK_INODE_ZERO_LAYER = 0, // data + CLOUD_DISK_INODE_FIRST_LAYER, // bundleName + CLOUD_DISK_INODE_OTHER_LAYER // others +}; + +enum CLOUD_DISK_INODE_LAYER_LOCALID { + CLOUD_DISK_INODE_LAYER_LOCALID_UNKNOWN = 0, // placeholder + CLOUD_DISK_INODE_ROOT_LAYER_LOCALID, // / + CLOUD_DISK_INODE_ZERO_LAYER_LOCALID, // data + CLOUD_DISK_INODE_FIRST_LAYER_LOCALID // bundleName +}; + +enum CLOUD_DISK_FILE_DIRTY { + CLOUD_DISK_FILE_UNKNOWN = 0, + CLOUD_DISK_FILE_CREATE, + CLOUD_DISK_FILE_WRITE +}; + +enum CLOUD_DISK_FILE_TYPE { + CLOUD_DISK_FILE_TYPE_UNKNOWN = 0, + CLOUD_DISK_FILE_TYPE_LOCAL, + CLOUD_DISK_FILE_TYPE_CLOUD +}; + +struct CloudDiskFile { + int type{CLOUD_DISK_FILE_TYPE_UNKNOWN}; + int fileDirty{CLOUD_DISK_FILE_UNKNOWN}; + int32_t fd{-1}; + std::atomic refCount{0}; + std::shared_ptr readSession{nullptr}; + bool isWriteOpen{false}; + ffrt::mutex readLock; + ffrt::mutex openLock; + std::shared_mutex sessionLock; +}; + +struct CloudDiskInode { + int layer{CLOUD_DISK_INODE_ZERO_LAYER}; + struct stat stat; + std::string cloudId{"rootId"}; + std::string bundleName; + std::string fileName; + fuse_ino_t parent{0}; + std::atomic refCount{0}; + std::string path; // just used in local file operation + std::shared_ptr filePtr; + + /* ops means file operation that uses local or database */ + std::shared_ptr ops{nullptr}; +}; + +struct CloudDiskFuseData { + int userId; + int64_t bundleNameId{1}; + int64_t fileId{0}; + std::shared_ptr rootNode{nullptr}; + std::unordered_map> inodeCache; + std::unordered_map> fileCache; + std::unordered_map localIdCache; + std::shared_mutex bundleNameIdLock; + std::shared_mutex cacheLock; + std::shared_mutex fileLock; + std::shared_mutex fileIdLock; + std::shared_mutex localIdLock; + struct fuse_session *se; +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_CLOUD_DISK_INODE_H diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/database_manager.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/database_manager.h new file mode 100644 index 0000000..aca61da --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/database_manager.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 CLOUD_FILE_DAEMON_CLOUD_DISK_DATABASE_MANAGER_H +#define CLOUD_FILE_DAEMON_CLOUD_DISK_DATABASE_MANAGER_H +#include +#include +#include +#include + +#include "clouddisk_rdbstore.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class DatabaseManager final { +public: + static DatabaseManager &GetInstance(); + std::shared_ptr GetRdbStore(const std::string &bundleName, + int32_t userId); + void ClearRdbStore(); + DatabaseManager(const DatabaseManager&) = delete; + DatabaseManager& operator=(const DatabaseManager&) = delete; +private: + DatabaseManager() = default; + ~DatabaseManager() = default; + std::shared_mutex mapLock_; + std::unordered_map>rdbMap_; +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_CLOUD_DISK_DATABASE_MANAGER_H diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_base.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_base.h new file mode 100644 index 0000000..f049bae --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_base.h @@ -0,0 +1,66 @@ +/* + * 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 CLOUD_FILE_DAEMON_FILE_OPERATIONS_BASE_H +#define CLOUD_FILE_DAEMON_FILE_OPERATIONS_BASE_H + +#define FUSE_USE_VERSION 34 + +#include +#include +#include + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class FileOperationsBase { +public: + virtual void Lookup(fuse_req_t req, fuse_ino_t parent, const char *name); + virtual void Access(fuse_req_t req, fuse_ino_t ino, int mask); + virtual void GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi); + virtual void Open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi); + virtual void Forget(fuse_req_t req, fuse_ino_t ino, uint64_t nLookup); + virtual void ForgetMulti(fuse_req_t req, size_t count, struct fuse_forget_data *forgets); + virtual void MkDir(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode); + virtual void RmDir(fuse_req_t req, fuse_ino_t parent, const char *name); + virtual void Unlink(fuse_req_t req, fuse_ino_t parent, const char *name); + virtual void Release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi); + virtual void MkNod(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, dev_t rdev); + virtual void Create(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, struct fuse_file_info *fi); + virtual void ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi); + virtual void SetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value, size_t size, int flags); + virtual void GetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + size_t size); + virtual void Rename(fuse_req_t req, fuse_ino_t parent, const char *name, + fuse_ino_t newParent, const char *newName, unsigned int flags); + virtual void Read(fuse_req_t req, fuse_ino_t ino, size_t size, + off_t offset, struct fuse_file_info *fi); + virtual void WriteBuf(fuse_req_t req, fuse_ino_t ino, struct fuse_bufvec *bufv, + off_t off, struct fuse_file_info *fi); + virtual void SetAttr(fuse_req_t req, fuse_ino_t ino, struct stat *attr, + int valid, struct fuse_file_info *fi); + virtual void Lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence, + struct fuse_file_info *fi); + virtual void Ioctl(fuse_req_t req, fuse_ino_t ino, int cmd, void *arg, struct fuse_file_info *fi, + unsigned flags, const void *inBuf, size_t inBufsz, size_t outBufsz); +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_FILE_OPERATIONS_BASE_H diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_cloud.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_cloud.h new file mode 100644 index 0000000..66a4667 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_cloud.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023-2024 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 CLOUD_FILE_DAEMON_FILE_OPERATIONS_CLOUD_H +#define CLOUD_FILE_DAEMON_FILE_OPERATIONS_CLOUD_H + +#include "file_operations_base.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class FileOperationsCloud final : public FileOperationsBase { +public: + void Lookup(fuse_req_t req, fuse_ino_t parent, const char *name) override; + void Access(fuse_req_t req, fuse_ino_t ino, int mask) override; + void GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) override; + void Open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) override; + void MkDir(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode) override; + void RmDir(fuse_req_t req, fuse_ino_t parent, const char *name) override; + void Unlink(fuse_req_t req, fuse_ino_t parent, const char *name) override; + void Release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) override; + void MkNod(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, dev_t rdev) override; + void Create(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, struct fuse_file_info *fi) override; + void ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) override; + void SetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value, size_t size, int flags) override; + void GetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + size_t size) override; + void Rename(fuse_req_t req, fuse_ino_t parent, const char *name, + fuse_ino_t newParent, const char *newName, unsigned int flags) override; + void Read(fuse_req_t req, fuse_ino_t ino, size_t size, + off_t offset, struct fuse_file_info *fi) override; + void WriteBuf(fuse_req_t req, fuse_ino_t ino, struct fuse_bufvec *bufv, + off_t off, struct fuse_file_info *fi) override; + void SetAttr(fuse_req_t req, fuse_ino_t ino, struct stat *attr, + int valid, struct fuse_file_info *fi) override; + void Lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence, + struct fuse_file_info *fi) override; + void Ioctl(fuse_req_t req, fuse_ino_t ino, int cmd, void *arg, struct fuse_file_info *fi, + unsigned flags, const void *inBuf, size_t inBufsz, size_t outBufsz) override; +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_FILE_OPERATIONS_CLOUD_H diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_helper.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_helper.h new file mode 100644 index 0000000..dc71680 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_helper.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2023-2024 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 CLOUD_FILE_DAEMON_FILE_OPERATIONS_HELPER_H +#define CLOUD_FILE_DAEMON_FILE_OPERATIONS_HELPER_H + +#include "cloud_disk_inode.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class FileOperationsHelper { +public: + static int32_t GetNextLayer(std::shared_ptr inoPtr, fuse_ino_t parent); + static int32_t GetFixedLayerRootId(int32_t layer); + static std::string GetCloudDiskRootPath(int32_t userId); + static std::string GetCloudDiskLocalPath(int32_t userId, std::string fileName); + static void GetInodeAttr(std::shared_ptr ino, struct stat *statBuf); + static std::shared_ptr FindCloudDiskInode(struct CloudDiskFuseData *data, + int64_t key); + static std::shared_ptr FindCloudDiskFile(struct CloudDiskFuseData *data, + int64_t key); + static int64_t FindLocalId(struct CloudDiskFuseData *data, const std::string &key); + static void AddDirEntry(fuse_req_t req, std::string &buf, size_t &size, const char *name, + std::shared_ptr ino); + static void FuseReplyLimited(fuse_req_t req, const char *buf, size_t bufSize, + off_t off, size_t maxSize); + static void PutCloudDiskInode(struct CloudDiskFuseData *data, + std::shared_ptr inoPtr, uint64_t num, int64_t key); + static void PutCloudDiskFile(struct CloudDiskFuseData *data, + std::shared_ptr filePtr, int64_t key); + static void PutLocalId(struct CloudDiskFuseData *data, + std::shared_ptr inoPtr, uint64_t num, const std::string &key); + static std::shared_ptr GenerateCloudDiskInode(struct CloudDiskFuseData *data, + fuse_ino_t parent, + const std::string &fileName, + const std::string &path); +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_FILE_OPERATIONS_HELPER_H diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_local.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_local.h new file mode 100644 index 0000000..fad2d13 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/file_operations_local.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023-2024 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 CLOUD_FILE_DAEMON_FILE_OPERATIONS_LOCAL_H +#define CLOUD_FILE_DAEMON_FILE_OPERATIONS_LOCAL_H + +#include "file_operations_base.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class FileOperationsLocal final : public FileOperationsBase { +public: + void Lookup(fuse_req_t req, fuse_ino_t parent, const char *name) override; + void GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) override; + void ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) override; +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_FILE_OPERATIONS_LOCAL_H diff --git a/cloud_file/services/cloudfiledaemon/include/cloud_disk/fuse_operations.h b/cloud_file/services/cloudfiledaemon/include/cloud_disk/fuse_operations.h new file mode 100644 index 0000000..db53a31 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/cloud_disk/fuse_operations.h @@ -0,0 +1,61 @@ +/* + * 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 CLOUD_FILE_DAEMON_FUSE_OPERATIONS_H +#define CLOUD_FILE_DAEMON_FUSE_OPERATIONS_H + +#include "file_operations_base.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +class FuseOperations final { +public: + static void Lookup(fuse_req_t req, fuse_ino_t parent, const char *name); + static void Access(fuse_req_t req, fuse_ino_t ino, int mask); + static void GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi); + static void Open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi); + static void Forget(fuse_req_t req, fuse_ino_t ino, uint64_t nLookup); + static void ForgetMulti(fuse_req_t req, size_t count, struct fuse_forget_data *forgets); + static void MkDir(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode); + static void RmDir(fuse_req_t req, fuse_ino_t parent, const char *name); + static void Unlink(fuse_req_t req, fuse_ino_t parent, const char *name); + static void Release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi); + static void MkNod(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, dev_t rdev); + static void Create(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, struct fuse_file_info *fi); + static void ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi); + static void SetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value, size_t size, int flags); + static void GetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + size_t size); + static void Rename(fuse_req_t req, fuse_ino_t parent, const char *name, + fuse_ino_t newParent, const char *newName, unsigned int flags); + static void Read(fuse_req_t req, fuse_ino_t ino, size_t size, + off_t offset, struct fuse_file_info *fi); + static void WriteBuf(fuse_req_t req, fuse_ino_t ino, struct fuse_bufvec *bufv, + off_t off, struct fuse_file_info *fi); + static void SetAttr(fuse_req_t req, fuse_ino_t ino, struct stat *attr, + int valid, struct fuse_file_info *fi); + static void Lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence, + struct fuse_file_info *fi); + static void Ioctl(fuse_req_t req, fuse_ino_t ino, int cmd, void *arg, struct fuse_file_info *fi, + unsigned flags, const void *inBuf, size_t inBufsz, size_t outBufsz); +}; +} // CloudDisk +} // FileManagement +} // OHOS +#endif // CLOUD_FILE_DAEMON_FUSE_OPERATIONS_H diff --git a/cloud_file/services/cloudfiledaemon/include/fuse_manager/cloud_daemon_statistic.h b/cloud_file/services/cloudfiledaemon/include/fuse_manager/cloud_daemon_statistic.h new file mode 100644 index 0000000..8183736 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/fuse_manager/cloud_daemon_statistic.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024 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 CLOUD_DAEMON_STATISTIC_H +#define CLOUD_DAEMON_STATISTIC_H + +#include +#include + +#define FILE_TYPE_MAX 3 +#define OPEN_SIZE_MAX 9 +#define OPEN_TIME_MAX 7 +#define READ_SIZE_MAX 6 +#define READ_TIME_MAX 10 + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using namespace std; + +class CloudDaemonStatistic final { +public: + static CloudDaemonStatistic &GetInstance(); + CloudDaemonStatistic(const CloudDaemonStatistic&) = delete; + CloudDaemonStatistic& operator=(const CloudDaemonStatistic&) = delete; + + /* size should be BYTE based, time should be MS based */ + void UpdateOpenSizeStat(uint64_t size); + void UpdateOpenTimeStat(uint32_t type, uint64_t time); + void UpdateReadSizeStat(uint64_t size); + void UpdateReadTimeStat(uint64_t size, uint64_t time); + void UpdateStatData(); + mutex mutex_; +private: + CloudDaemonStatistic() = default; + ~CloudDaemonStatistic() = default; + void AddFileData(); + void ClearStat(); + void OutputToFile(); + vector openSizeStat_ = vector(OPEN_SIZE_MAX, 0); + vector> openTimeStat_ = + vector>(FILE_TYPE_MAX, vector(OPEN_TIME_MAX, 0)); + vector readSizeStat_ = vector(READ_SIZE_MAX, 0); + vector> readTimeStat_ = + vector>(READ_SIZE_MAX, vector(READ_TIME_MAX, 0)); +}; +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS + +#endif // CLOUD_DAEMON_STATISTIC_H diff --git a/cloud_file/services/cloudfiledaemon/include/fuse_manager/fuse_manager.h b/cloud_file/services/cloudfiledaemon/include/fuse_manager/fuse_manager.h new file mode 100644 index 0000000..da8b6a9 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/fuse_manager/fuse_manager.h @@ -0,0 +1,47 @@ +/* + * 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 FUSE_MANAGER_H +#define FUSE_MANAGER_H + +#include +#include +#include + +struct fuse_session; + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using namespace std; + +class FuseManager final { +public: + static FuseManager &GetInstance(); + int32_t StartFuse(int32_t userId, int32_t devFd, const string &path); + FuseManager(const FuseManager&) = delete; + FuseManager& operator=(const FuseManager&) = delete; + struct fuse_session* GetSession(std::string path); +private: + FuseManager() = default; + ~FuseManager() = default; +private: + std::mutex sessionMutex_; + map sessions_; +}; +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS +#endif // FUSE_MANAGER_H diff --git a/cloud_file/services/cloudfiledaemon/include/ipc/cloud_daemon.h b/cloud_file/services/cloudfiledaemon/include/ipc/cloud_daemon.h new file mode 100644 index 0000000..2dd50c7 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/ipc/cloud_daemon.h @@ -0,0 +1,66 @@ +/* + * 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 CLOUD_DAEMON_H +#define CLOUD_DAEMON_H + +#include +#include +#include + +#include "iremote_stub.h" +#include "nocopyable.h" +#include "refbase.h" +#include "system_ability.h" + +#include "cloud_daemon_stub.h" +#include "i_cloud_daemon.h" +#include "account_status_listener.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; + +class CloudDaemon final : public SystemAbility, public CloudDaemonStub, protected NoCopyable { + DECLARE_SYSTEM_ABILITY(CloudDaemon); + +public: + explicit CloudDaemon(int32_t saID, bool runOnCreate = true); + virtual ~CloudDaemon() = default; + + void OnStart() override; + void OnStop() override; + ServiceRunningState QueryServiceState() const + { + return state_; + } + int32_t StartFuse(int32_t userId, int32_t deviceFd, const std::string &path) override; + +private: + CloudDaemon(); + ServiceRunningState state_ { ServiceRunningState::STATE_NOT_START }; + static sptr instance_; + static std::mutex instanceLock_; + bool registerToService_ { false }; + void PublishSA(); + void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; + std::shared_ptr accountStatusListener_ = nullptr; + void ExecuteStartFuse(int32_t userId, int32_t devFd, const std::string& path); +}; +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_DAEMON_H diff --git a/cloud_file/services/cloudfiledaemon/include/ipc/cloud_daemon_stub.h b/cloud_file/services/cloudfiledaemon/include/ipc/cloud_daemon_stub.h new file mode 100644 index 0000000..0d7044e --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/include/ipc/cloud_daemon_stub.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 CLOUD_DAEMON_STUB_H +#define CLOUD_DAEMON_STUB_H + +#include + +#include "i_cloud_daemon.h" +#include "iremote_stub.h" +#include "message_option.h" +#include "message_parcel.h" +#include "refbase.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using CloudDaemonInterface = std::function; +class CloudDaemonStub : public IRemoteStub { +public: + CloudDaemonStub(); + virtual ~CloudDaemonStub() = default; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + std::map opToInterfaceMap_; + + int32_t HandleStartFuseInner(MessageParcel &data, MessageParcel &reply); +}; +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_DAEMON_STUB_H diff --git a/cloud_file/services/cloudfiledaemon/src/cloud_disk/account_status.cpp b/cloud_file/services/cloudfiledaemon/src/cloud_disk/account_status.cpp new file mode 100644 index 0000000..0e192e9 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/cloud_disk/account_status.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 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 "account_status.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +bool AccountStatus::IsNeedCleanCache() +{ + AccountState tempPreAccountState = preAccountState_; + AccountState tempAccountState = accountState_; + preAccountState_ = AccountState::ACCOUNT_LOGIN; + accountState_ = AccountState::ACCOUNT_LOGIN; + return (tempPreAccountState == AccountState::ACCOUNT_LOGOUT && tempAccountState == AccountState::ACCOUNT_LOGIN) || + (tempPreAccountState == AccountState::ACCOUNT_LOGIN && tempAccountState == AccountState::ACCOUNT_LOGOUT); +} + +void AccountStatus::SetAccountState(AccountState accountState) +{ + preAccountState_ = accountState_; + accountState_ = accountState; +} + +AccountStatus::AccountState AccountStatus::GetAccountState() +{ + return accountState_; +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp b/cloud_file/services/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp new file mode 100644 index 0000000..5106861 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2024 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 "account_status_listener.h" + +#include + +#include "cloud_daemon_statistic.h" +#include "cloud_file_utils.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "account_status.h" +#include "file_operations_base.h" +#include "file_operations_helper.h" +#include "fuse_manager.h" +#include "meta_file.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { + +constexpr int32_t BASE_USER_RANGE = 200000; +static const std::string LOCAL_PATH_MNT_FUSE = "/mnt/data/"; +static const std::string LOCAL_PATH_CLOUD_FUSE = "/cloud_fuse"; +static const std::string LOCAL_PATH_DATA = "/data"; + +static void SwapMemory() +{ + std::FILE *file = fopen("/proc/self/reclaim", "r+"); + if (file == nullptr) { + LOGE("Failed to open reclaim, errno:%{public}d", errno); + return; + } + std::string content = "1"; + size_t ret = fwrite(content.c_str(), sizeof(char), content.size(), file); + if (ret < content.size() || ferror(file)) { + LOGE("Failed to write reclaim, errno:%{public}d", errno); + } + if (fclose(file)) { + LOGE("Failed to close reclaim, errno:%{public}d", errno); + } + return; +} + +AccountStatusSubscriber::AccountStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo) + : EventFwk::CommonEventSubscriber(subscribeInfo) +{ +} + +void AccountStatusSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + auto action = eventData.GetWant().GetAction(); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { + LOGI("Account Login!"); + AccountStatus::SetAccountState(AccountStatus::AccountState::ACCOUNT_LOGIN); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { + LOGI("Account Logout!"); + AccountStatus::SetAccountState(AccountStatus::AccountState::ACCOUNT_LOGOUT); + SwapMemory(); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF && + AccountStatus::GetAccountState() == AccountStatus::AccountState::ACCOUNT_LOGIN) { + LOGI("Screen Off and Swap Memory!"); + SwapMemory(); + CloudFile::CloudDaemonStatistic::GetInstance().UpdateStatData(); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + LOGI("Package removed and Clean clouddisk!"); + RemovedClean(eventData); + } +} + +AccountStatusListener::~AccountStatusListener() +{ + Stop(); +} + +void AccountStatusListener::Start() +{ + /* subscribe Account login and logout status */ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + EventFwk::CommonEventSubscribeInfo info(matchingSkills); + commonEventSubscriber_ = std::make_shared(info); + auto subRet = EventFwk::CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); + LOGI("Subscriber end, SubscribeResult = %{public}d", subRet); +} + +void AccountStatusListener::Stop() +{ + if (commonEventSubscriber_ != nullptr) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(commonEventSubscriber_); + commonEventSubscriber_ = nullptr; + } +} + +void AccountStatusSubscriber::RemovedClean(const EventFwk::CommonEventData &eventData) +{ + auto bundleName = eventData.GetWant().GetBundle(); + std::string userIdKey = "uid"; + auto userId = eventData.GetWant().GetIntParam(userIdKey.c_str(), -1); + if (userId < 0) { + LOGE("Get UserId Failed!"); + return; + } + userId = userId / BASE_USER_RANGE; + struct fuse_session *se = nullptr; + struct stat childSt {}; + struct stat parentSt {}; + std::string childDest = LOCAL_PATH_MNT_FUSE + std::to_string(userId) + LOCAL_PATH_CLOUD_FUSE + + LOCAL_PATH_DATA + "/" + bundleName; + std::string parentDest = LOCAL_PATH_MNT_FUSE + std::to_string(userId) + LOCAL_PATH_CLOUD_FUSE + + LOCAL_PATH_DATA; + std::string getSessionPath = LOCAL_PATH_MNT_FUSE + std::to_string(userId) + LOCAL_PATH_CLOUD_FUSE; + se = CloudFile::FuseManager::GetInstance().GetSession(getSessionPath); + if (se == nullptr) { + LOGE("Session is Null!"); + return; + } + if (stat(childDest.c_str(), &childSt) == -1) { + LOGE("Stat childDest Failed!"); + return; + } + if (stat(parentDest.c_str(), &parentSt) == -1) { + LOGE("Stat parentDest Failed!"); + return; + } + auto data = reinterpret_cast(se->userdata); + auto node = FileOperationsHelper::FindCloudDiskInode(data, static_cast(childSt.st_ino)); + if (node == nullptr) { + LOGE("Node is Null!"); + return; + } + std::string localIdKey = std::to_string(node->parent) + node->fileName; + int64_t key = static_cast(childSt.st_ino); + FileOperationsHelper::PutCloudDiskInode(data, node, node->refCount, key); + FileOperationsHelper::PutLocalId(data, node, node->refCount, localIdKey); + if (fuse_lowlevel_notify_inval_entry(se, parentSt.st_ino, bundleName.c_str(), bundleName.size())) { + fuse_lowlevel_notify_inval_inode(se, childSt.st_ino, 0, 0); + } + MetaFileMgr::GetInstance().CloudDiskClearAll(); + LOGI("Package Removed Complete Clean"); +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudfiledaemon/src/cloud_disk/database_manager.cpp b/cloud_file/services/cloudfiledaemon/src/cloud_disk/database_manager.cpp new file mode 100644 index 0000000..1a48dff --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/cloud_disk/database_manager.cpp @@ -0,0 +1,48 @@ +/* + * 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 "database_manager.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +DatabaseManager &DatabaseManager::GetInstance() +{ + static DatabaseManager instance_; + return instance_; +} + +shared_ptr DatabaseManager::GetRdbStore(const string &bundleName, int32_t userId) +{ + std::unique_lock wLock(mapLock_, std::defer_lock); + string key = to_string(userId) + bundleName; + + wLock.lock(); + if (rdbMap_.find(key) == rdbMap_.end()) { + rdbMap_[key] = make_shared(bundleName, userId); + } + wLock.unlock(); + + return rdbMap_[key]; +} + +void DatabaseManager::ClearRdbStore() +{ + std::unique_lock wLock(mapLock_); + rdbMap_.clear(); +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp b/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp new file mode 100644 index 0000000..362f77c --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2023-2024 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 "file_operations_base.h" +#include "cloud_disk_inode.h" +#include "file_operations_helper.h" + +#include + +#include "cloud_file_fault_event.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +using namespace OHOS::FileManagement::CloudFile; +void FileOperationsBase::Lookup(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + LOGE("Lookup operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::Access(fuse_req_t req, fuse_ino_t ino, int mask) +{ + LOGE("Access operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + LOGE("GetAttr operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::Open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + LOGE("Open operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::Forget(fuse_req_t req, fuse_ino_t ino, uint64_t nLookup) +{ + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto node = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (node == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::FORGET, + CloudFile::FaultType::WARNING, EINVAL, "Forget an invalid inode"}); + return (void) fuse_reply_none(req); + } + string localIdKey = std::to_string(node->parent) + node->fileName; + int64_t key = static_cast(ino); + FileOperationsHelper::PutCloudDiskInode(data, node, nLookup, key); + FileOperationsHelper::PutLocalId(data, node, nLookup, localIdKey); + fuse_reply_none(req); +} + +void FileOperationsBase::ForgetMulti(fuse_req_t req, size_t count, struct fuse_forget_data *forgets) +{ + auto data = reinterpret_cast(fuse_req_userdata(req)); + for (size_t i = 0; i < count; i++) { + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(forgets[i].ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::FORGETMULTI, + CloudFile::FaultType::WARNING, EINVAL, "ForgetMulti got an invalid inode"}); + continue; + } + string localIdKey = std::to_string(inoPtr->parent) + inoPtr->fileName; + FileOperationsHelper::PutCloudDiskInode(data, inoPtr, forgets[i].nlookup, forgets[i].ino); + FileOperationsHelper::PutLocalId(data, inoPtr, forgets[i].nlookup, localIdKey); + } + fuse_reply_none(req); +} + +void FileOperationsBase::MkNod(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, dev_t rdev) +{ + LOGE("MkNod operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::Create(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, struct fuse_file_info *fi) +{ + LOGE("Create operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) +{ + LOGE("ReadDir operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::SetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value, size_t size, int flags) +{ + LOGE("SetXattr operation is not supported!"); + fuse_reply_err(req, EINVAL); +} + +void FileOperationsBase::GetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + size_t size) +{ + LOGE("GetXattr operation is not supported!"); + fuse_reply_err(req, EINVAL); +} + +void FileOperationsBase::MkDir(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode) +{ + LOGE("MkDir operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::RmDir(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + LOGE("RmDir operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::Unlink(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + LOGE("Unlink operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::Rename(fuse_req_t req, fuse_ino_t parent, const char *name, + fuse_ino_t newParent, const char *newName, unsigned int flags) +{ + LOGE("Rename operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::Read(fuse_req_t req, fuse_ino_t ino, size_t size, + off_t offset, struct fuse_file_info *fi) +{ + LOGE("Read operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::WriteBuf(fuse_req_t req, fuse_ino_t ino, struct fuse_bufvec *bufv, + off_t off, struct fuse_file_info *fi) +{ + LOGE("WriteBuf operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsBase::Release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + LOGE("Release operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} +void FileOperationsBase::SetAttr(fuse_req_t req, fuse_ino_t ino, struct stat *attr, int valid, + struct fuse_file_info *fi) +{ + LOGE("SetAttr operation is not supported!"); + fuse_reply_err(req, EINVAL); +} +void FileOperationsBase::Lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence, + struct fuse_file_info *fi) +{ + LOGE("Lseek operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} +void FileOperationsBase::Ioctl(fuse_req_t req, fuse_ino_t ino, int cmd, void *arg, struct fuse_file_info *fi, + unsigned flags, const void *inBuf, size_t inBufsz, size_t outBufsz) +{ + LOGE("Ioctl operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp b/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp new file mode 100644 index 0000000..c3eb1b7 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp @@ -0,0 +1,1933 @@ +/* + * Copyright (c) 2024 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 "file_operations_cloud.h" + +#include +#include +#include +#include +#include + +#include "account_status.h" +#include "cloud_disk_inode.h" +#include "cloud_file_fault_event.h" +#include "cloud_file_kit.h" +#include "cloud_file_utils.h" +#include "clouddisk_rdb_transaction.h" +#include "clouddisk_rdb_utils.h" +#include "clouddisk_notify.h" +#include "database_manager.h" +#include "directory_ex.h" +#include "ffrt_inner.h" +#include "parameter.h" +#include "parameters.h" +#include "file_operations_helper.h" +#include "hitrace_meter.h" +#include "securec.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +using namespace CloudFile; +enum XATTR_CODE { + ERROR_CODE = -1, + HMDFS_PERMISSION, + CLOUD_LOCATION, + CLOUD_RECYCLE, + IS_FAVORITE, + HAS_THM +}; +namespace { + static const uint32_t STAT_NLINK_REG = 1; + static const uint32_t STAT_NLINK_DIR = 2; + static const uint32_t CLOUD_FILE_LAYER = 2; + static const uint32_t USER_LOCAL_ID_OFFSET = 100; + static const uint32_t STAT_MODE_REG = 0660; + static const uint32_t STAT_MODE_DIR = 0771; + static const uint32_t MILLISECOND_TO_SECONDS_TIMES = 1000; + static const uint32_t RECYCLE_LOCAL_ID = 4; + static const string FILE_LOCAL = "1"; + static const string ROOT_CLOUD_ID = "rootId"; + static const string RECYCLE_NAME = ".trash"; + static const uint64_t UNKNOWN_INODE_ID = 0; + static const std::string FILEMANAGER_KEY = "persist.kernel.bundle_name.filemanager"; + static const string LOCAL_PATH_DATA_STORAGE = "/data/storage/el2/cloud/"; + static const unsigned int MAX_READ_SIZE = 4 * 1024 * 1024; + static const std::chrono::seconds READ_TIMEOUT_S = 16s; + static const std::chrono::seconds OPEN_TIMEOUT_S = 4s; +} + +const int32_t MAX_SIZE = 4096; +constexpr unsigned HMDFS_IOC = 0xf2; +constexpr unsigned CLOUD_COPY_CMD = 0x0c; +#define HMDFS_IOC_COPY_FILE _IOW(HMDFS_IOC, CLOUD_COPY_CMD, struct CloudDiskCopy) + +struct CloudDiskCopy { + char destPath[MAX_SIZE]; +}; + +static void InitInodeAttr(struct CloudDiskFuseData *data, fuse_ino_t parent, + struct CloudDiskInode *childInode, const MetaBase &metaBase, const int64_t &inodeId) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, + static_cast(parent)); + childInode->stat = parentInode->stat; + childInode->stat.st_ino = static_cast(inodeId); + childInode->stat.st_mtime = metaBase.mtime / MILLISECOND_TO_SECONDS_TIMES; + childInode->stat.st_atime = metaBase.atime / MILLISECOND_TO_SECONDS_TIMES; + + childInode->bundleName = parentInode->bundleName; + childInode->fileName = metaBase.name; + childInode->layer = FileOperationsHelper::GetNextLayer(parentInode, parent); + childInode->parent = parent; + childInode->cloudId = metaBase.cloudId; + childInode->ops = make_shared(); + + if (S_ISDIR(metaBase.mode)) { + childInode->stat.st_mode = S_IFDIR | STAT_MODE_DIR; + childInode->stat.st_nlink = STAT_NLINK_DIR; + } else { + childInode->stat.st_mode = S_IFREG | STAT_MODE_REG; + childInode->stat.st_nlink = STAT_NLINK_REG; + childInode->stat.st_size = metaBase.size; + } +} + +static void InsertFileAttr(struct CloudDiskFuseData *data, struct fuse_file_info *fi, + shared_ptr filePtr) +{ + std::unique_lock wLock(data->fileLock, std::defer_lock); + wLock.lock(); + data->fileCache[fi->fh] = filePtr; + wLock.unlock(); + filePtr->refCount++; +} + +static shared_ptr InitFileAttr(struct CloudDiskFuseData *data, struct fuse_file_info *fi) +{ + std::unique_lock wLock(data->fileLock, std::defer_lock); + shared_ptr filePtr = FileOperationsHelper::FindCloudDiskFile(data, fi->fh); + if (filePtr == nullptr) { + filePtr = make_shared(); + wLock.lock(); + data->fileCache[fi->fh] = filePtr; + wLock.unlock(); + } + filePtr->refCount++; + return filePtr; +} + +static void InitLocalIdCache(struct CloudDiskFuseData *data, const std::string &key, const int64_t val) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + std::unique_lock wLock(data->localIdLock, std::defer_lock); + int64_t localId = FileOperationsHelper::FindLocalId(data, key); + if (localId == -1) { + wLock.lock(); + data->localIdCache[key] = val; + wLock.unlock(); + } +} + +static void LookUpRecycleBin(struct CloudDiskFuseData *data, fuse_ino_t parent, + shared_ptr parentInode, struct fuse_entry_param *e) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + std::unique_lock cacheWLock(data->cacheLock, std::defer_lock); + auto child = FileOperationsHelper::FindCloudDiskInode(data, RECYCLE_LOCAL_ID); + if (child == nullptr) { + child = make_shared(); + child->stat = parentInode->stat; + child->stat.st_ino = RECYCLE_LOCAL_ID; + child->bundleName = parentInode->bundleName; + child->fileName = RECYCLE_NAME; + child->layer = FileOperationsHelper::GetNextLayer(parentInode, parent); + child->parent = parent; + child->cloudId = RECYCLE_CLOUD_ID; + child->ops = make_shared(); + child->stat.st_mode = S_IFDIR | STAT_MODE_DIR; + child->stat.st_nlink = STAT_NLINK_DIR; + cacheWLock.lock(); + data->inodeCache[RECYCLE_LOCAL_ID] = child; + cacheWLock.unlock(); + } + e->ino = static_cast(RECYCLE_LOCAL_ID); + FileOperationsHelper::GetInodeAttr(child, &e->attr); +} + +static shared_ptr UpdateChildCache(struct CloudDiskFuseData *data, int64_t localId, + shared_ptr child) +{ + std::unique_lock cacheWLock(data->cacheLock, std::defer_lock); + std::unique_lock localIdWLock(data->localIdLock, std::defer_lock); + if (child == nullptr) { + child = make_shared(); + cacheWLock.lock(); + data->inodeCache[localId] = child; + cacheWLock.unlock(); + } else { + auto old_key = std::to_string(child->parent) + child->fileName; + localIdWLock.lock(); + data->localIdCache.erase(old_key); + localIdWLock.unlock(); + } + return child; +} + +static int32_t LookupRecycledFile(struct CloudDiskFuseData *data, const char *name, + const std::string bundleName, struct fuse_entry_param *e) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + MetaBase metaBase(name); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, bundleName, + RECYCLE_CLOUD_ID); + int ret = metaFile->DoLookup(metaBase); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::LOOKUP, + CloudFile::FaultType::FILE, ret, "file " + GetAnonyString(name) + " not found in recyclebin"}); + return ret; + } + int64_t inodeId = static_cast(CloudFileUtils::DentryHash(metaBase.cloudId)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, inodeId); + if (inoPtr == nullptr) { + string nameStr = name; + size_t lastSlash = nameStr.find_last_of("_"); + metaBase.name = nameStr.substr(0, lastSlash); + inoPtr = UpdateChildCache(data, inodeId, inoPtr); + inoPtr->refCount++; + InitInodeAttr(data, RECYCLE_LOCAL_ID, inoPtr.get(), metaBase, inodeId); + inoPtr->parent = UNKNOWN_INODE_ID; + } + e->ino = static_cast(inodeId); + FileOperationsHelper::GetInodeAttr(inoPtr, &e->attr); + return 0; +} + +static int32_t DoCloudLookup(fuse_req_t req, fuse_ino_t parent, const char *name, + struct fuse_entry_param *e) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + if (parent == FUSE_ROOT_ID) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::LOOKUP, + CloudFile::FaultType::WARNING, EINVAL, "cloud file operations should not get a fuse root inode"}); + return EINVAL; + } + + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, + static_cast(parent)); + if (parentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::LOOKUP, + CloudFile::FaultType::INODE_FILE, EINVAL, "fail to find parent inode"}); + return EINVAL; + } + if (name == RECYCLE_NAME) { + LookUpRecycleBin(data, parent, parentInode, e); + return 0; + } else if (parent == RECYCLE_LOCAL_ID) { + int32_t ret = LookupRecycledFile(data, name, parentInode->bundleName, e); + if (ret != 0) { + LOGE("fail to lookup recycledfile"); + return ret; + } + return 0; + } + MetaBase metaBase(name); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, parentInode->bundleName, + parentInode->cloudId); + int32_t ret = metaFile->DoLookup(metaBase); + if (ret != 0) { + LOGE("lookup dentry failed, name:%{public}s, ret = %{public}d", GetAnonyString(name).c_str(), ret); + return ENOENT; + } + string key = std::to_string(parent) + name; + int64_t inodeId = static_cast(CloudFileUtils::DentryHash(metaBase.cloudId)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, inodeId); + // if inoPtr is nullptr, UpdateChildCache will create it + auto child = UpdateChildCache(data, inodeId, inoPtr); + child->refCount++; + InitInodeAttr(data, parent, child.get(), metaBase, inodeId); + InitLocalIdCache(data, key, inodeId); + e->ino = static_cast(inodeId); + FileOperationsHelper::GetInodeAttr(child, &e->attr); + return 0; +} + +void FileOperationsCloud::Lookup(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + struct fuse_entry_param e; + e.attr_timeout = 1.0; + e.entry_timeout = 1.0; + int32_t err = DoCloudLookup(req, parent, name, &e); + if (err) { + fuse_reply_err(req, err); + } else { + fuse_reply_entry(req, &e); + } +} + +void FileOperationsCloud::Access(fuse_req_t req, fuse_ino_t ino, int mask) +{ + LOGI("Access operation is not supported!"); + fuse_reply_err(req, ENOSYS); +} + +void FileOperationsCloud::GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + fuse_reply_attr(req, &inoPtr->stat, 0); +} + +static bool HandleCloudError(fuse_req_t req, CloudError error) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (error == CloudError::CK_NO_ERROR) { + return false; + } + if (error == CloudError::CK_NETWORK_ERROR) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::WARNING, ENOTCONN, "network error"}); + fuse_reply_err(req, ENOTCONN); + } else if (error == CloudError::CK_SERVER_ERROR) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::WARNING, EIO, "server error"}); + fuse_reply_err(req, EIO); + } else if (error == CloudError::CK_LOCAL_ERROR) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::WARNING, EINVAL, "local error"}); + fuse_reply_err(req, EINVAL); + } else { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::WARNING, EIO, "unknown error"}); + fuse_reply_err(req, EIO); + } + return true; +} + +static shared_ptr GetDatabase(int32_t userId, const string &bundleName) +{ + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::OPEN, + CloudFile::FaultType::DRIVERKIT, EINVAL, "get cloud file helper instance failed"}); + return nullptr; + } + + if (AccountStatus::IsNeedCleanCache()) { + auto ret = instance->CleanCloudUserInfo(userId); + if (ret != 0) { + return nullptr; + } + LOGI("execute clean cloud user info success"); + } + + auto database = instance->GetCloudDatabase(userId, bundleName); + if (database == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READ, + CloudFile::FaultType::QUERY_DATABASE, EINVAL, "get cloud file kit database fail"}); + return nullptr; + } + return database; +} + +static void DoCloudOpen(fuse_req_t req, shared_ptr filePtr, + struct fuse_file_info *fi) +{ + auto error = make_shared(); + auto openFinish = make_shared(false); + auto cond = make_shared(); + + ffrt::submit([filePtr, error, openFinish, cond] { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto session = filePtr->readSession; + if (!session) { + LOGE("readSession is nullptr"); + return; + } + *error = session->InitSession(); + { + unique_lock lck(filePtr->openLock); + *openFinish = true; + } + cond->notify_one(); + LOGI("download done"); + return; + }); + + unique_lock lck(filePtr->openLock); + auto waitStatus = cond->wait_for(lck, OPEN_TIMEOUT_S, [openFinish] { + return *openFinish; + }); + if (!waitStatus) { + LOGE("init session timeout"); + fuse_reply_err(req, ENETUNREACH); + return; + } + if (!HandleCloudError(req, *error)) { + filePtr->type = CLOUD_DISK_FILE_TYPE_CLOUD; + fuse_reply_open(req, fi); + } else { + filePtr->readSession = nullptr; + LOGE("open fail"); + } + return; +} + +static void GetNewSession(shared_ptr inoPtr, shared_ptr filePtr, + string &path, struct CloudDiskFuseData *data, shared_ptr database) +{ + string cloudId = inoPtr->cloudId; + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(inoPtr->parent)); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, + parentInode->bundleName, parentInode->cloudId); + MetaBase metaBase(inoPtr->fileName); + auto ret = metaFile->DoLookup(metaBase); + string assets = "content"; + if (metaBase.fileType == FILE_TYPE_THUMBNAIL) { + assets = "thumbnail"; + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t ret = rdbStore->GetSrcCloudId(inoPtr->cloudId, cloudId); + } + if (metaBase.fileType == FILE_TYPE_LCD) { + assets = "lcd"; + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t ret = rdbStore->GetSrcCloudId(inoPtr->cloudId, cloudId); + } + LOGD("cloudId %s", cloudId.c_str()); + filePtr->readSession = database->NewAssetReadSession(data->userId, "file", cloudId, assets, path); +} + +static void CloudOpen(fuse_req_t req, + shared_ptr inoPtr, struct fuse_file_info *fi, string path) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + shared_ptr filePtr; + if (inoPtr->filePtr != nullptr) { + filePtr = inoPtr->filePtr; + InsertFileAttr(data, fi, filePtr); + } else { + filePtr = InitFileAttr(data, fi); + inoPtr->filePtr = filePtr; + } + + std::unique_lock wSesLock(filePtr->sessionLock); + if (filePtr->readSession) { + filePtr->type = CLOUD_DISK_FILE_TYPE_CLOUD; + fuse_reply_open(req, fi); + return; + } + + auto database = GetDatabase(data->userId, inoPtr->bundleName); + if (!database) { + fuse_reply_err(req, EPERM); + LOGE("database is null"); + return; + } + GetNewSession(inoPtr, filePtr, path, data, database); + if (filePtr->readSession) { + DoCloudOpen(req, filePtr, fi); + } else { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::OPEN, + CloudFile::FaultType::DRIVERKIT, EPERM, "readSession is null"}); + fuse_reply_err(req, EPERM); + } + return; +} + +void FileOperationsCloud::Open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + std::unique_lock wLock(data->fileIdLock, std::defer_lock); + wLock.lock(); + data->fileId++; + fi->fh = static_cast(data->fileId); + wLock.unlock(); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::OPEN, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + string path = CloudFileUtils::GetLocalFilePath(inoPtr->cloudId, inoPtr->bundleName, data->userId); + unsigned int flags = static_cast(fi->flags); + if (access(path.c_str(), F_OK) == 0) { + if ((flags & O_ACCMODE) & O_WRONLY) { + flags &= ~O_WRONLY; + flags |= O_RDWR; + } + if (flags & O_APPEND) { + flags &= ~O_APPEND; + } + if (flags & O_DIRECT) { + flags &= ~O_DIRECT; + } + int32_t fd = open(path.c_str(), flags); + if (fd < 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::OPEN, + CloudFile::FaultType::FILE, errno, "open file failed path:" + GetAnonyString(path) + + " errno: " + std::to_string(errno)}); + return (void) fuse_reply_err(req, errno); + } + auto filePtr = InitFileAttr(data, fi); + filePtr->type = CLOUD_DISK_FILE_TYPE_LOCAL; + filePtr->fd = fd; + filePtr->isWriteOpen = (flags & O_RDWR) | (flags & O_WRONLY); + fuse_reply_open(req, fi); + } else { + path = CloudFileUtils::GetLocalDKCachePath(inoPtr->cloudId, inoPtr->bundleName, data->userId); + CloudOpen(req, inoPtr, fi, path); + } +} + +static int32_t CreateLocalFile(const string &cloudId, const string &bundleName, int32_t userId, mode_t mode) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + string bucketPath = CloudFileUtils::GetLocalBucketPath(cloudId, bundleName, userId); + string path = CloudFileUtils::GetLocalFilePath(cloudId, bundleName, userId); + if (access(bucketPath.c_str(), F_OK) != 0) { + if (mkdir(bucketPath.c_str(), STAT_MODE_DIR) != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKNOD, + CloudFile::FaultType::FILE, errno, "mkdir bucketpath failed :" + GetAnonyString(bucketPath) + + " err: " + std::to_string(errno)}); + return -errno; + } + } + int32_t fd = open(path.c_str(), (mode & O_NOFOLLOW) | O_CREAT | O_RDWR, STAT_MODE_REG); + if (fd < 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKNOD, + CloudFile::FaultType::FILE, errno, "create file failed :" + GetAnonyString(path) + + " err: " + std::to_string(errno)}); + return -errno; + } + return fd; +} + +void RemoveLocalFile(const string &path) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + int32_t err = remove(path.c_str()); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKNOD, + CloudFile::FaultType::WARNING, errno, "remove file " + GetAnonyString(path) + " failed, "+ + "error: " + std::to_string(errno)}); + } +} + +int32_t GenerateCloudId(int32_t userId, string &cloudId, const string &bundleName) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto dkDatabasePtr = GetDatabase(userId, bundleName); + if (dkDatabasePtr == nullptr) { + LOGE("Failed to get database"); + return ENOSYS; + } + + vector ids; + auto ret = dkDatabasePtr->GenerateIds(1, ids); + if (ret != 0 || ids.size() == 0) { + return ENOSYS; + } + cloudId = ids[0]; + return 0; +} + +static int32_t GetParentUpload(shared_ptr parentInode, struct CloudDiskFuseData *data, + bool &parentNoUpload) +{ + auto grandparentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(parentInode->parent)); + if (grandparentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKNOD, + CloudFile::FaultType::INODE_FILE, EINVAL, "grandparentInode not found"}); + return EINVAL; + } + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, + grandparentInode->bundleName, grandparentInode->cloudId); + MetaBase metaBase(parentInode->fileName); + auto ret = metaFile->DoLookup(metaBase); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{grandparentInode->bundleName, + CloudFile::FaultOperation::MKNOD, CloudFile::FaultType::DENTRY_FILE, ret, "file " + + GetAnonyString(parentInode->fileName) + " not found"}); + return ret; + } + parentNoUpload = (metaBase.noUpload == NO_UPLOAD); + return 0; +} + +int32_t DoCreatFile(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, struct fuse_entry_param &e) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + struct CloudDiskFuseData *data = reinterpret_cast(fuse_req_userdata(req)); + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(parent)); + + string cloudId; + int32_t err = GenerateCloudId(data->userId, cloudId, parentInode->bundleName); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKNOD, + CloudFile::FaultType::FILE, err, "Failed to generate cloud id"}); + return -err; + } + int32_t fd = CreateLocalFile(cloudId, parentInode->bundleName, data->userId, mode); + if (fd < 0) { + LOGD("Create local file failed error:%{public}d", fd); + return fd; + } + string path = CloudFileUtils::GetLocalFilePath(cloudId, parentInode->bundleName, data->userId); + bool noNeedUpload = false; + if (parentInode->cloudId != ROOT_CLOUD_ID) { + err = GetParentUpload(parentInode, data, noNeedUpload); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKNOD, + CloudFile::FaultType::FILE, err, "Failed to get parent no upload"}); + close(fd); + RemoveLocalFile(path); + return -err; + } + } + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + shared_ptr rdbStore = + databaseManager.GetRdbStore(parentInode->bundleName, data->userId); + err = rdbStore->Create(cloudId, parentInode->cloudId, name, noNeedUpload); + if (err != 0) { + close(fd); + RemoveLocalFile(path); + return -EINVAL; + } + err = DoCloudLookup(req, parent, name, &e); + if (err != 0) { + close(fd); + RemoveLocalFile(path); + return -err; + } + return fd; +} + +void FileOperationsCloud::MkNod(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, dev_t rdev) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + struct fuse_entry_param e; + int32_t err = DoCreatFile(req, parent, name, mode, e); + if (err < 0) { + fuse_reply_err(req, -err); + return; + } + close(err); + fuse_reply_entry(req, &e); +} + +void FileOperationsCloud::Create(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, struct fuse_file_info *fi) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + struct fuse_entry_param e; + int32_t err = DoCreatFile(req, parent, name, mode, e); + if (err < 0) { + fuse_reply_err(req, -err); + return; + } + auto filePtr = InitFileAttr(data, fi); + std::unique_lock wLock(data->fileIdLock, std::defer_lock); + wLock.lock(); + data->fileId++; + fi->fh = static_cast(data->fileId); + wLock.unlock(); + filePtr->fd = err; + filePtr->type = CLOUD_DISK_FILE_TYPE_LOCAL; + filePtr->fileDirty = CLOUD_DISK_FILE_CREATE; + fuse_reply_create(req, &e, fi); +} + +static size_t FindNextPos(const vector &childInfos, off_t off) +{ + for (size_t i = 0; i < childInfos.size(); i++) { + /* Find the first valid offset beyond @off */ + if (childInfos[i].nextOff > off) { + return i + 1; + } + } + /* If @off is beyond all valid offset, then return the index after the last info */ + if (!childInfos.empty() && childInfos.back().nextOff < off) { + return childInfos.size(); + } + return 0; +} + +static size_t FindNextPos(const vector &childInfos, off_t off) +{ + for (size_t i = 0; i < childInfos.size(); i++) { + /* Find the first valid offset beyond @off */ + if (childInfos[i].nextOff > off) { + return i + 1; + } + } + /* If @off is beyond all valid offset, then return the index after the last info */ + if (!childInfos.empty() && childInfos.back().nextOff < off) { + return childInfos.size(); + } + return 0; +} + +static int32_t GetChildInfos(fuse_req_t req, fuse_ino_t ino, vector &childInfos) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + LOGE("inode not found"); + return EINVAL; + } + string parentCloudId = inoPtr->cloudId; + + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + shared_ptr rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t err = rdbStore->ReadDir(parentCloudId, childInfos); + if (err != 0) { + LOGE("Readdir failed cloudId:%{public}s err:%{public}d", parentCloudId.c_str(), err); + return err; + } + return 0; +} + +template +static size_t CloudSeekDir(fuse_req_t req, fuse_ino_t ino, off_t off, + const std::vector &childInfos) +{ + if (off == 0 || childInfos.empty()) { + return 0; + } + + size_t i = 0; + for (; i < childInfos.size(); i++) { + if (childInfos[i].nextOff == off) { + /* Start position should be the index of next entry */ + return i + 1; + } + } + if (i == childInfos.size()) { + /* The directory may changed recently, find the next valid index for this offset */ + return FindNextPos(childInfos, off); + } + + return 0; +} + +template +static void AddDirEntryToBuf(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + const std::vector &childInfos) +{ + size_t startPos = CloudSeekDir(req, ino, off, childInfos); + string buf; + buf.resize(size); + if (childInfos.empty() || startPos == childInfos.size()) { + LOGW("empty buffer replied"); + return (void)fuse_reply_buf(req, buf.c_str(), 0); + } + + size_t nextOff = 0; + size_t remain = size; + static const struct stat statInfoDir = { .st_mode = S_IFDIR | STAT_MODE_DIR }; + static const struct stat statInfoReg = { .st_mode = S_IFREG | STAT_MODE_REG }; + for (size_t i = startPos; i < childInfos.size(); i++) { + size_t alignSize = CloudDiskRdbUtils::FuseDentryAlignSize(childInfos[i].name.c_str()); + if (alignSize > remain) { + break; + } + alignSize = fuse_add_direntry(req, &buf[nextOff], alignSize, childInfos[i].name.c_str(), + childInfos[i].mode != S_IFREG ? &statInfoDir : &statInfoReg, + off + static_cast(nextOff) + static_cast(alignSize)); + nextOff += alignSize; + remain -= alignSize; + } + (void)fuse_reply_buf(req, buf.c_str(), size - remain); +} + +static void ReadDirForRecycle(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) +{ + int32_t err = -1; + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READDIR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, + inode->bundleName, RECYCLE_NAME); + std::vector childInfos; + err = metaFile->LoadChildren(childInfos); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inode->bundleName, CloudFile::FaultOperation::READDIR, + CloudFile::FaultType::DENTRY_FILE, err, "load children failed, err = " + std::to_string(err)}); + fuse_reply_err(req, EINVAL); + return; + } + size_t nextOff = 0; + for (size_t i = 0; i < childInfos.size(); ++i) { + size_t alignSize = CloudDiskRdbUtils::FuseDentryAlignSize(childInfos[i].name.c_str()); + nextOff += alignSize; + childInfos[i].nextOff = static_cast(nextOff); + } + AddDirEntryToBuf(req, ino, size, off, childInfos); +} + +void FileOperationsCloud::ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (ino == RECYCLE_LOCAL_ID) { + ReadDirForRecycle(req, ino, size, off, fi); + return; + } + + vector childInfos; + int32_t err = GetChildInfos(req, ino, childInfos); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READDIR, + CloudFile::FaultType::QUERY_DATABASE, err, "failed to get child infos, err = " + std::to_string(err)}); + return (void)fuse_reply_err(req, EINVAL); + } + AddDirEntryToBuf(req, ino, size, off, childInfos); +} + +int32_t CheckXattr(const char *name) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + LOGD("start CheckXattr name is:%{public}s", name); + if (CloudFileUtils::CheckIsHmdfsPermission(name)) { + return HMDFS_PERMISSION; + } else if (CloudFileUtils::CheckIsCloudLocation(name)) { + return CLOUD_LOCATION; + } else if (CloudFileUtils::CheckIsCloudRecycle(name)) { + return CLOUD_RECYCLE; + } else if (CloudFileUtils::CheckIsFavorite(name)) { + return IS_FAVORITE; + } else if (CloudFileUtils::CheckIsHasLCD(name) || CloudFileUtils::CheckIsHasTHM(name)) { + return HAS_THM; + } else { + LOGD("no definition Xattr name:%{public}s", name); + return ERROR_CODE; + } +} + +void HandleCloudLocation(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + fuse_reply_err(req, EINVAL); + LOGE("inode not found"); + return; + } + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(inoPtr->parent)); + if (parentInode == nullptr) { + LOGE("parent inode not found"); + return (void) fuse_reply_err(req, EINVAL); + } + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t err = rdbStore->SetXAttr(inoPtr->cloudId, CLOUD_FILE_LOCATION, value, inoPtr->fileName, + parentInode->cloudId); + if (err != 0) { + LOGE("set cloud id fail %{public}d", err); + fuse_reply_err(req, EINVAL); + return; + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_SETXATTR, inoPtr}); + fuse_reply_err(req, 0); +} + +void HandleCloudRecycle(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + string parentCloudId; + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(inoPtr->parent)); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + if (parentInode == nullptr) { + int32_t ret = rdbStore->GetParentCloudId(inoPtr->cloudId, parentCloudId); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SETEXTATTR, + CloudFile::FaultType::DATABASE, ret, "fail to get parentCloudId"}); + fuse_reply_err(req, EINVAL); + return; + } + } else { + parentCloudId = parentInode->cloudId; + } + int32_t ret = MetaFileMgr::GetInstance().CreateRecycleDentry(data->userId, inoPtr->bundleName); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, + CloudFile::FaultOperation::SETEXTATTR, CloudFile::FaultType::DENTRY_FILE, ret, + "create recycle dentry failed"}); + fuse_reply_err(req, ret); + return; + } + ret = rdbStore->SetXAttr(inoPtr->cloudId, CLOUD_CLOUD_RECYCLE_XATTR, value, + inoPtr->fileName, parentCloudId); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, + CloudFile::FaultOperation::SETEXTATTR, CloudFile::FaultType::MODIFY_DATABASE, ret, + "set cloud recycle xattr fail, ret = " + std::to_string(ret)}); + fuse_reply_err(req, EINVAL); + return; + } + int32_t val = std::stoi(value); + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + val == 0 ? NotifyOpsType::DAEMON_RESTORE : NotifyOpsType::DAEMON_RECYCLE, inoPtr}); + fuse_reply_err(req, 0); +} + +void HandleFavorite(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t err = rdbStore->SetXAttr(inoPtr->cloudId, IS_FAVORITE_XATTR, value); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, CloudFile::FaultOperation::SETEXTATTR, + CloudFile::FaultType::MODIFY_DATABASE, err, "set cloud is favorite xattr fail, err = " + + std::to_string(err)}); + fuse_reply_err(req, EINVAL); + return; + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_SETXATTR, inoPtr}); + fuse_reply_err(req, 0); +} + +void HandleHasTHM(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + fuse_reply_err(req, EINVAL); + std::string errMsg = "inode not found"; + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{"", CloudFile::FaultOperation::SETATTR, + CloudFile::FaultType::DENTRY_FILE, EINVAL, errMsg}); + return; + } + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t err = rdbStore->SetXAttr(inoPtr->cloudId, name, value); + if (err != 0) { + std::string errMsg = "set has thm fail " + to_string(err); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{inoPtr->bundleName, CloudFile::FaultOperation::SETATTR, + CloudFile::FaultType::DENTRY_FILE, EINVAL, errMsg}); + fuse_reply_err(req, EINVAL); + return; + } + fuse_reply_err(req, 0); +} + +void HandleExtAttribute(fuse_req_t req, fuse_ino_t ino, const char *name, const char *value) +{ + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t err = rdbStore->SetXAttr(inoPtr->cloudId, CLOUD_EXT_ATTR, value, name); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, CloudFile::FaultOperation::SETEXTATTR, + CloudFile::FaultType::MODIFY_DATABASE, err, "set cloud ext attr fail, err = " + std::to_string(err)}); + fuse_reply_err(req, EINVAL); + return; + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_SETXATTR, inoPtr}); + fuse_reply_err(req, 0); +} + +void FileOperationsCloud::SetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value, size_t size, int flags) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + LOGD("Setxattr begin name:%{public}s", name); + int32_t checknum = CheckXattr(name); + switch (checknum) { + case HMDFS_PERMISSION: + fuse_reply_err(req, 0); + break; + case CLOUD_LOCATION: + HandleCloudLocation(req, ino, name, value); + break; + case CLOUD_RECYCLE: + HandleCloudRecycle(req, ino, name, value); + break; + case IS_FAVORITE: + HandleFavorite(req, ino, name, value); + break; + case HAS_THM: + HandleHasTHM(req, ino, name, value); + break; + default: + HandleExtAttribute(req, ino, name, value); + break; + } +} + +string GetIsFavorite(fuse_req_t req, shared_ptr inoPtr) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + string favorite; + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int res = rdbStore->GetXAttr(inoPtr->cloudId, IS_FAVORITE_XATTR, favorite); + if (res != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::QUERY_DATABASE, res, "local file get isFavorite fail"}); + return "null"; + } + return favorite; +} + +static string GetFileStatus(fuse_req_t req, struct CloudDiskInode *inoPtr) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + string fileStatus; + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inoPtr is null"}); + return "null"; + } + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int res = rdbStore->GetXAttr(inoPtr->cloudId, IS_FILE_STATUS_XATTR, fileStatus); + if (res != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::QUERY_DATABASE, res, "local file get file_status fail"}); + return "null"; + } + return fileStatus; +} + +string GetLocation(fuse_req_t req, shared_ptr inoPtr) +{ + string location; + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(inoPtr->parent)); + if (parentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + return "null"; + } + CacheNode newNode = {.parentCloudId = parentInode->cloudId, .fileName = inoPtr->fileName}; + int res = rdbStore->GetXAttr(inoPtr->cloudId, CLOUD_FILE_LOCATION, location, newNode); + if (res != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::QUERY_DATABASE, res, "local file get location fail"}); + return "null"; + } + return location; +} + +string GetTimeRecycled(fuse_req_t req, shared_ptr inoPtr) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + string timeRecycled; + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int res = rdbStore->GetXAttr(inoPtr->cloudId, CLOUD_TIME_RECYCLED, timeRecycled); + if (res != 0) { + LOGE("local file get time recycled fail"); + return "null"; + } + return timeRecycled; +} + +string GetRecyclePath(fuse_req_t req, shared_ptr inoPtr) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int64_t rowId; + int res = rdbStore->GetRowId(inoPtr->cloudId, rowId); + if (res != 0) { + LOGE("local file get recycle path fail"); + return "null"; + } + string recyclePath = LOCAL_PATH_DATA_STORAGE + RECYCLE_NAME + "/" + + inoPtr->fileName + "_" + to_string(rowId); + return recyclePath; +} + +string GetExtAttr(fuse_req_t req, shared_ptr inoPtr, const char *extAttrKey) +{ + string extAttr; + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "get ext attr inoPtr is null"}); + return "null"; + } + + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + CacheNode newNode = {}; + int res = rdbStore->GetXAttr(inoPtr->cloudId, CLOUD_EXT_ATTR, extAttr, newNode, extAttrKey); + if (res != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::FILE, res, "get ext attr is null"}); + return "null"; + } + return extAttr; +} + +void FileOperationsCloud::GetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + size_t size) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + string buf; + if (CloudFileUtils::CheckIsHmdfsPermission(name)) { + buf = to_string(inoPtr->layer + CLOUD_FILE_LAYER); + } else if (CloudFileUtils::CheckIsCloud(name)) { + buf = inoPtr->cloudId; + } else if (CloudFileUtils::CheckIsFavorite(name)) { + buf = GetIsFavorite(req, inoPtr); + } else if (CloudFileUtils::CheckFileStatus(name)) { + buf = GetFileStatus(req, inoPtr.get()); + } else if (CloudFileUtils::CheckIsCloudLocation(name)) { + buf = GetLocation(req, inoPtr); + } else if (CloudFileUtils::CheckIsTimeRecycled(name)) { + buf = GetTimeRecycled(req, inoPtr); + } else if (CloudFileUtils::CheckIsRecyclePath(name)) { + buf = GetRecyclePath(req, inoPtr); + } else { + buf = GetExtAttr(req, inoPtr, name); + } + if (buf == "null") { + fuse_reply_err(req, ENODATA); + return; + } + if (size == 0) { + fuse_reply_xattr(req, buf.size()); + return; + } + if (buf.size() > size) { + fuse_reply_err(req, ERANGE); + return; + } + if (buf.size() > 0) { + fuse_reply_buf(req, buf.c_str(), buf.size()); + } else { + fuse_reply_err(req, 0); + } +} + +void FileOperationsCloud::MkDir(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(parent)); + if (parentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKDIR, + CloudFile::FaultType::INNER_ERROR, EINVAL, "parent inode not found"}); + return (void) fuse_reply_err(req, EINVAL); + } + string fileName = name; + bool noNeedUpload; + if (fileName == ".cloudthumbnails" && parentInode->cloudId == ROOT_CLOUD_ID) { + noNeedUpload = true; + } else if (parentInode->cloudId != ROOT_CLOUD_ID) { + int32_t err = GetParentUpload(parentInode, data, noNeedUpload); + if (err != 0) { + LOGE("Failed to get parent no upload"); + return (void) fuse_reply_err(req, err); + } + } + string cloudId; + int32_t err = GenerateCloudId(data->userId, cloudId, parentInode->bundleName); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::MKDIR, CloudFile::FaultType::FILE, err, "Failed to generate cloud id"}); + return (void) fuse_reply_err(req, err); + } + + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + shared_ptr rdbStore = databaseManager.GetRdbStore(parentInode->bundleName, data->userId); + err = rdbStore->MkDir(cloudId, parentInode->cloudId, name, noNeedUpload); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKDIR, + CloudFile::FaultType::DATABASE, err, "Failed to mkdir to DB err:" + std::to_string(err)}); + return (void) fuse_reply_err(req, EINVAL); + } + + struct fuse_entry_param e; + err = DoCloudLookup(req, parent, name, &e); + if (err != 0) { + LOGE("Failed to find dir %{private}s", GetAnonyString(name).c_str()); + fuse_reply_err(req, err); + } else { + fuse_reply_entry(req, &e); + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_MKDIR, parentInode, parent, name}); +} + +void RDBUnlinkAsync(shared_ptr rdbStore, const string& cloudId, int32_t noUpload) +{ + function rdbUnlink = [rdbStore, cloudId, noUpload] { + if (rdbStore->Unlink(cloudId, noUpload) != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", + CloudFile::FaultOperation::UNLINK, CloudFile::FaultType::DATABASE, EINVAL, + "Failed to unlink DB cloudId: " + cloudId}); + } + }; + ffrt::thread(rdbUnlink).detach(); +} + +int32_t DoCloudUnlink(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(parent)); + if (parentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::UNLINK, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + return EINVAL; + } + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + shared_ptr rdbStore = databaseManager.GetRdbStore(parentInode->bundleName, data->userId); + MetaBase metaBase(name); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, + parentInode->bundleName, parentInode->cloudId); + if (int32_t ret = metaFile->DoLookup(metaBase); ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::UNLINK, CloudFile::FaultType::DENTRY_FILE, ret, + "lookup denty failed, name: " + GetAnonyString(name)}); + return ret; + } + string cloudId = metaBase.cloudId; + int32_t isDirectory = S_ISDIR(metaBase.mode); + int32_t position = metaBase.position; + int32_t noUpload = metaBase.noUpload; + if (int32_t ret = metaFile->DoRemove(metaBase); ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::UNLINK, CloudFile::FaultType::DENTRY_FILE, ret, "remove dentry failed, ret = " + + std::to_string(ret)}); + return ret; + } + LOGD("doUnlink, dentry file has been deleted"); + if (isDirectory == FILE && position != CLOUD) { + string localPath = CloudFileUtils::GetLocalFilePath(cloudId, parentInode->bundleName, data->userId); + LOGI("unlink %{public}s", GetAnonyString(localPath).c_str()); + int32_t ret = unlink(localPath.c_str()); + if (ret != 0 && errno == ENOENT) { + std::string errMsg = "doCloudUnlink, unlink local file ret ENOENT."; + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{parentInode->bundleName, CloudFile::FaultOperation::UNLINK, + CloudFile::FaultType::WARNING, errno, errMsg}); + } else if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::UNLINK, CloudFile::FaultType::FILE, errno, + "Failed to unlink cloudId:" + cloudId + ", errno: " + std::to_string(errno)}); + (void)metaFile->DoCreate(metaBase); + return errno; + } + } + RDBUnlinkAsync(rdbStore, cloudId, noUpload); + return 0; +} + +std::shared_ptr LoadMetaFileChildren(const CloudDiskFuseData* data, const MetaBase& metaBase, + shared_ptr parentInode, const fuse_req_t& req) +{ + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, + parentInode->bundleName, metaBase.cloudId); + std::vector bases; + if (int err = metaFile->LoadChildren(bases); err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::RMDIR, CloudFile::FaultType::DENTRY_FILE, err, "load children failed, err = " + + std::to_string(err)}); + fuse_reply_err(req, EINVAL); + return nullptr; + } + if (!bases.empty()) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::RMDIR, CloudFile::FaultType::DENTRY_FILE, ENOTEMPTY, "Directory not empty"}); + fuse_reply_err(req, ENOTEMPTY); + return nullptr; + } + return metaFile; +} + +void FileOperationsCloud::RmDir(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(parent)); + if (parentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RMDIR, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + return (void) fuse_reply_err(req, EINVAL); + } + auto parentMetaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, + parentInode->bundleName, parentInode->cloudId); + MetaBase metaBase(name); + int32_t err = parentMetaFile->DoLookup(metaBase); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::RMDIR, CloudFile::FaultType::DENTRY_FILE, err, "lookup dir failed, err = " + + std::to_string(err)}); + return (void) fuse_reply_err(req, EINVAL); + } + + std::shared_ptr metaFile = LoadMetaFileChildren(data, metaBase, parentInode, req); + if (metaFile == nullptr) { + return; + } + + err = DoCloudUnlink(req, parent, name); + if (err != 0) { + fuse_reply_err(req, err); + return; + } + MetaFileMgr::GetInstance().Clear(static_cast(data->userId), parentInode->bundleName, metaBase.cloudId); + if (unlink(metaFile->GetDentryFilePath().c_str()) != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::RMDIR, CloudFile::FaultType::WARNING, errno, "fail to delete dentry: " + + std::to_string(errno)}); + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_RMDIR, nullptr, parent, name}); + return (void) fuse_reply_err(req, 0); +} + +void FileOperationsCloud::Unlink(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + int32_t err = DoCloudUnlink(req, parent, name); + if (err != 0) { + fuse_reply_err(req, err); + return; + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_UNLINK, nullptr, parent, name}); + return (void) fuse_reply_err(req, 0); +} + +void FileOperationsCloud::Rename(fuse_req_t req, fuse_ino_t parent, const char *name, + fuse_ino_t newParent, const char *newName, unsigned int flags) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (flags) { + LOGE("Fuse failed to support flag"); + fuse_reply_err(req, EINVAL); + return; + } + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(parent)); + auto newParentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(newParent)); + if (!parentInode || !newParentInode) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RENAME, + CloudFile::FaultType::INODE_FILE, EINVAL, "rename old or new parent not found"}); + fuse_reply_err(req, EINVAL); + return; + } + + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + shared_ptr rdbStore = databaseManager.GetRdbStore(parentInode->bundleName, + data->userId); + int32_t err = rdbStore->Rename(parentInode->cloudId, name, newParentInode->cloudId, newName); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::RENAME, CloudFile::FaultType::DATABASE, err, + "Failed to Rename DB name: " + GetAnonyString(name) + "err:" + std::to_string(err)}); + fuse_reply_err(req, EINVAL); + return; + } + bool isDir = false; + string key = std::to_string(parent) + name; + int64_t localId = FileOperationsHelper::FindLocalId(data, key); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, localId); + if (inoPtr != nullptr) { + inoPtr->fileName = newName; + inoPtr->parent = newParent; + isDir = S_ISDIR(inoPtr->stat.st_mode); + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_RENAME, nullptr, parent, name, newParent, newName}, + {FileStatus::UNKNOW, isDir}); + return (void) fuse_reply_err(req, 0); +} + +static void DoCloudRead(fuse_req_t req, shared_ptr filePtr, + off_t offset, size_t size, shared_ptr buf) +{ + auto readSize = make_shared(); + auto error = make_shared(); + auto readFinish = make_shared(false); + auto cond = make_shared(); + + ffrt::submit([filePtr, error, readFinish, cond, offset, size, buf, readSize] { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto session = filePtr->readSession; + if (!session) { + LOGE("readSession is nullptr"); + return; + } + *readSize = session->PRead(offset, size, buf.get(), *error); + { + unique_lock lck(filePtr->readLock); + *readFinish = true; + } + cond->notify_one(); + LOGI("download done"); + return; + }); + + unique_lock lck(filePtr->readLock); + auto waitStatus = cond->wait_for(lck, READ_TIMEOUT_S, [readFinish] { + return *readFinish; + }); + if (!waitStatus) { + LOGE("PRead timeout"); + fuse_reply_err(req, ENETUNREACH); + return; + } + if (!HandleCloudError(req, *error)) { + filePtr->type = CLOUD_DISK_FILE_TYPE_CLOUD; + fuse_reply_buf(req, buf.get(), *readSize); + } else { + filePtr->readSession = nullptr; + LOGE("read fail"); + } + return; +} + +void FileOperationsCloud::Read(fuse_req_t req, fuse_ino_t ino, size_t size, + off_t offset, struct fuse_file_info *fi) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (size > MAX_READ_SIZE) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READ, + CloudFile::FaultType::WARNING, EINVAL, "Read size is larger than the kernel pre-read window"}); + fuse_reply_err(req, EINVAL); + return; + } + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto filePtr = FileOperationsHelper::FindCloudDiskFile(data, fi->fh); + if (filePtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READ, + CloudFile::FaultType::FILE, EINVAL, "file not found"}); + fuse_reply_err(req, EINVAL); + return; + } + if (filePtr->type == CLOUD_DISK_FILE_TYPE_LOCAL) { + struct fuse_bufvec buf = FUSE_BUFVEC_INIT(size); + + buf.buf[0].flags = static_cast (FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK); + buf.buf[0].fd = filePtr->fd; + buf.buf[0].pos = offset; + + fuse_reply_data(req, &buf, static_cast (0)); + return; + } + + shared_ptr buf = nullptr; + + buf.reset(new char[size], [](char* ptr) { + delete[] ptr; + }); + + if (!buf) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READ, + CloudFile::FaultType::FILE, ENOMEM, "buffer is null"}); + fuse_reply_err(req, ENOMEM); + return; + } + DoCloudRead(req, filePtr, offset, size, buf); +} + +static void UpdateCloudDiskInode(shared_ptr rdbStore, shared_ptr inoPtr) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + CloudDiskFileInfo childInfo; + int32_t err = rdbStore->GetAttr(inoPtr->cloudId, childInfo); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETATTR, + CloudFile::FaultType::QUERY_DATABASE, err, "update file fail"}); + return; + } + inoPtr->stat.st_size = childInfo.size; + inoPtr->stat.st_mtime = childInfo.mtime / MILLISECOND_TO_SECONDS_TIMES; +} + +static void UpdateCloudStore(CloudDiskFuseData *data, const std::string &fileName, const std::string &parentCloudId, + int fileDirty, shared_ptr inoPtr) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t dirtyType; + int res = rdbStore->GetDirtyType(inoPtr->cloudId, dirtyType); + if (res != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RELEASE, + CloudFile::FaultType::QUERY_DATABASE, res, "get file status fail, err: " + std::to_string(res)}); + } + res = rdbStore->Write(fileName, parentCloudId, inoPtr->cloudId); + if (res != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RELEASE, + CloudFile::FaultType::MODIFY_DATABASE, res, "write file fail"}); + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_WRITE, inoPtr}, {dirtyType, false, fileDirty}); + UpdateCloudDiskInode(rdbStore, inoPtr); +} + +static int32_t UpdateCacheDentrySize(CloudDiskFuseData *data, fuse_ino_t ino) +{ + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::WRITE, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + return EINVAL; + } + string filePath = CloudFileUtils::GetLocalFilePath(inoPtr->cloudId, inoPtr->bundleName, data->userId); + struct stat statInfo {}; + int32_t ret = stat(filePath.c_str(), &statInfo); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, CloudFile::FaultOperation::WRITE, + CloudFile::FaultType::FILE, errno, "filePath " + GetAnonyString(filePath) + " is invalid"}); + return errno; + } + MetaBase metaBase(inoPtr->fileName); + metaBase.mtime = static_cast(CloudFileUtils::Timespec2Milliseconds(statInfo.st_mtim)); + metaBase.size = static_cast(statInfo.st_size); + auto callback = [&metaBase] (MetaBase &m) { + m.size = metaBase.size; + m.mtime = metaBase.mtime; + }; + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, + static_cast(inoPtr->parent)); + if (parentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::WRITE, + CloudFile::FaultType::INODE_FILE, EINVAL, "fail to find parent inode"}); + return EINVAL; + } + string parentCloudId = parentInode->cloudId; + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, inoPtr->bundleName, parentCloudId); + ret = metaFile->DoChildUpdate(inoPtr->fileName, callback); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::WRITE, + CloudFile::FaultType::DENTRY_FILE, ret, "update new dentry failed, ret = " + std::to_string(ret)}); + return ret; + } + inoPtr->stat.st_size = static_caststat.st_size)>(metaBase.size); + inoPtr->stat.st_mtime = + static_caststat.st_mtime)>(metaBase.mtime / MILLISECOND_TO_SECONDS_TIMES); + return 0; +} + +void FileOperationsCloud::WriteBuf(fuse_req_t req, fuse_ino_t ino, struct fuse_bufvec *bufv, + off_t off, struct fuse_file_info *fi) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + struct fuse_bufvec out_buf = FUSE_BUFVEC_INIT(fuse_buf_size(bufv)); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto filePtr = FileOperationsHelper::FindCloudDiskFile(data, fi->fh); + if (filePtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::WRITE, + CloudFile::FaultType::DRIVERKIT, EINVAL, "file not found"}); + fuse_reply_err(req, EINVAL); + return; + } + if (filePtr->type != CLOUD_DISK_FILE_TYPE_LOCAL) { + fuse_reply_err(req, EINVAL); + LOGE("write on cloud file not supported"); + return; + } + out_buf.buf[0].flags = (fuse_buf_flags)(FUSE_BUF_IS_FD | FUSE_BUF_FD_SEEK); + out_buf.buf[0].fd = filePtr->fd; + out_buf.buf[0].pos = off; + int res = fuse_buf_copy(&out_buf, bufv, (fuse_buf_copy_flags)(0)); + if (res < 0) { + fuse_reply_err(req, -res); + } else { + if (filePtr != nullptr) { filePtr->fileDirty = CLOUD_DISK_FILE_WRITE; } + int32_t ret = UpdateCacheDentrySize(data, ino); + if (ret != 0) { + LOGE("write size in cache and dentry fail, ret = %{public}d", ret); + } + fuse_reply_write(req, (size_t) res); + } +} + +static void UploadLocalFile(CloudDiskFuseData *data, const std::string &fileName, const std::string &parentCloudId, + int fileDirty, shared_ptr inoPtr) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + MetaBase metaBase(fileName); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, inoPtr->bundleName, parentCloudId); + int32_t ret = metaFile->DoLookup(metaBase); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, CloudFile::FaultOperation::RELEASE, + CloudFile::FaultType::DENTRY_FILE, ret, "local file get location from dentryfile fail, ret = " + + std::to_string(ret)}); + } else if (metaBase.position == LOCAL) { + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t dirtyType; + ret = rdbStore->GetDirtyType(inoPtr->cloudId, dirtyType); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, + CloudFile::FaultOperation::RELEASE, CloudFile::FaultType::DRIVERKIT_DATABASE, ret, + "get file status fail, err: " + std::to_string(ret)}); + } + ret = rdbStore->Write(fileName, parentCloudId, inoPtr->cloudId); + if (ret != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RELEASE, + CloudFile::FaultType::DRIVERKIT_DATABASE, ret, "write file fail"}); + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_WRITE, inoPtr}, {dirtyType, false, fileDirty}); + UpdateCloudDiskInode(rdbStore, inoPtr); + } +} + +static bool DocloudClose(struct CloudDiskFuseData *data, shared_ptr filePtr, + shared_ptr parentInode, shared_ptr inoPtr) +{ + bool res; + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(data->userId, + parentInode->bundleName, parentInode->cloudId); + MetaBase metaBase(inoPtr->fileName); + auto ret = metaFile->DoLookup(metaBase); + if (metaBase.fileType == FILE_TYPE_CONTENT) { + res = filePtr->readSession->Close(false); + } else { + res = filePtr->readSession->Close(true); + string path = CloudFileUtils::GetLocalBucketPath(inoPtr->cloudId, inoPtr->bundleName, data->userId); + string tmpPath = CloudFileUtils::GetLocalDKCachePath(inoPtr->cloudId, inoPtr->bundleName, data->userId); + ret = rename(tmpPath.c_str(), path.c_str()); + if (ret == NativeRdb::E_OK) { + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbstore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + rdbstore->UpdateTHMStatus(metaBase, CloudSync::DOWNLOADED_THM); + } + } + return res; +} + +void FileOperationsCloud::Release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RELEASE, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, + static_cast(inoPtr->parent)); + if (parentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RELEASE, + CloudFile::FaultType::INODE_FILE, EINVAL, "fail to find parent inode"}); + fuse_reply_err(req, EINVAL); + return; + } + string parentCloudId = parentInode->cloudId; + shared_ptr filePtr = FileOperationsHelper::FindCloudDiskFile(data, fi->fh); + if (filePtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{parentInode->bundleName, + CloudFile::FaultOperation::RELEASE, CloudFile::FaultType::DRIVERKIT, EINVAL, "file not found"}); + fuse_reply_err(req, EINVAL); + return; + } + FileOperationsHelper::PutCloudDiskFile(data, filePtr, fi->fh); + filePtr->refCount--; + if (filePtr->refCount == 0) { + inoPtr->filePtr = nullptr; + if (filePtr->type == CLOUD_DISK_FILE_TYPE_LOCAL) { + close(filePtr->fd); + if (filePtr->fileDirty != CLOUD_DISK_FILE_UNKNOWN) { + UpdateCloudStore(data, inoPtr->fileName, parentCloudId, filePtr->fileDirty, inoPtr); + } else if (filePtr->isWriteOpen) { + UploadLocalFile(data, inoPtr->fileName, parentCloudId, filePtr->fileDirty, inoPtr); + } + } else if (filePtr->type == CLOUD_DISK_FILE_TYPE_CLOUD && filePtr->readSession != nullptr) { + bool res = DocloudClose(data, filePtr, parentInode, inoPtr); + if (!res) { + LOGE("close error"); + } + filePtr->readSession = nullptr; + LOGD("readSession released"); + } + } + fuse_reply_err(req, 0); +} + +void HandleTruncateError(shared_ptr inoPtr, shared_ptr rdbStore, + shared_ptr parentInode, fuse_req_t req) +{ + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, + CloudFile::FaultOperation::SETATTR, CloudFile::FaultType::FILE, errno, "truncate failed, err: " + + std::to_string(errno)}); + int res = rdbStore->SetAttr(inoPtr->fileName, parentInode->cloudId, inoPtr->cloudId, inoPtr->stat.st_size); + if (res != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, + CloudFile::FaultOperation::SETATTR, CloudFile::FaultType::DATABASE, res, + "update rdb size failed, res: " + std::to_string(res)}); + fuse_reply_err(req, EINVAL); + } else { + fuse_reply_err(req, errno); + } +} + +std::optional FuseFileTruncate(struct fuse_file_info* fi, struct CloudDiskFuseData* data, + shared_ptr inoPtr, fuse_req_t req, struct stat *attr) +{ + int32_t res = -1; + if (fi) { + auto filePtr = FileOperationsHelper::FindCloudDiskFile(data, fi->fh); + if (filePtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, + CloudFile::FaultOperation::SETATTR, CloudFile::FaultType::DRIVERKIT, EINVAL, "file not found"}); + fuse_reply_err(req, EINVAL); + return std::nullopt; + } + res = ftruncate(filePtr->fd, attr->st_size); + } else { + string path = CloudFileUtils::GetLocalFilePath(inoPtr->cloudId, inoPtr->bundleName, data->userId); + res = truncate(path.c_str(), attr->st_size); + } + return res; +} + +void FileOperationsCloud::SetAttr(fuse_req_t req, fuse_ino_t ino, struct stat *attr, + int valid, struct fuse_file_info *fi) +{ + if (WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_DAEMON) != 0) { + LOGE("wait move error"); + return (void) fuse_reply_err(req, EBUSY); + } + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SETATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "get an invalid inode!"}); + return (void) fuse_reply_err(req, EINVAL); + } + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, + static_cast(inoPtr->parent)); + if (static_cast(valid) & FUSE_SET_ATTR_SIZE) { + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); + int32_t res = rdbStore->SetAttr(inoPtr->fileName, parentInode->cloudId, inoPtr->cloudId, attr->st_size); + if (res != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{inoPtr->bundleName, + CloudFile::FaultOperation::SETATTR, CloudFile::FaultType::DATABASE, res, + "update rdb size failed, res: " + std::to_string(res)}); + return (void) fuse_reply_err(req, EINVAL); + } + + auto ret = FuseFileTruncate(fi, data, inoPtr, req, attr); + if (!ret.has_value()) { + return; + } + + if (ret.value() == -1) { + HandleTruncateError(inoPtr, rdbStore, parentInode, req); + return; + } + UpdateCloudDiskInode(rdbStore, inoPtr); + } + CloudDiskNotify::GetInstance().TryNotify({data, FileOperationsHelper::FindCloudDiskInode, + NotifyOpsType::DAEMON_SETATTR, inoPtr}); + fuse_reply_attr(req, &inoPtr->stat, 0); +} + +void FileOperationsCloud::Lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence, + struct fuse_file_info *fi) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto data = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + LOGE("get an invalid inode!"); + fuse_reply_err(req, EINVAL); + return; + } + shared_ptr filePtr = FileOperationsHelper::FindCloudDiskFile(data, fi->fh); + if (filePtr == nullptr) { + fuse_reply_err(req, EINVAL); + LOGE("file not found"); + return; + } + if (filePtr->type != CLOUD_DISK_FILE_TYPE_LOCAL) { + fuse_reply_err(req, ENOSYS); + LOGE("lseek on cloud file not supported"); + return; + } + off_t res = lseek(filePtr->fd, off, whence); + if (res != -1) + fuse_reply_lseek(req, res); + else + fuse_reply_err(req, errno); +} + +void FileOperationsCloud::Ioctl(fuse_req_t req, fuse_ino_t ino, int cmd, void *arg, struct fuse_file_info *fi, + unsigned flags, const void *inBuf, size_t inBufsz, size_t outBufsz) +{ + if (static_cast(cmd) == HMDFS_IOC_COPY_FILE) { + auto dataReq = reinterpret_cast(fuse_req_userdata(req)); + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(dataReq, static_cast(ino)); + if (inoPtr == nullptr) { + LOGE("Failed to find inode for cloud disk"); + fuse_reply_err(req, EINVAL); + return; + } + if (S_ISDIR(inoPtr->stat.st_mode)) { + LOGE("Dir is not supported"); + fuse_reply_err(req, ENOSYS); + return; + } + + const struct CloudDiskCopy *dataCopy = reinterpret_cast(inBuf); + std::string dest(dataCopy->destPath); + std::string destPath = CloudFileUtils::GetRealPath(dest); + DatabaseManager &databaseManager = DatabaseManager::GetInstance(); + shared_ptr rdbStore = + databaseManager.GetRdbStore(inoPtr->bundleName, dataReq->userId); + + std::string destCloudId; + int32_t ret = GenerateCloudId(dataReq->userId, destCloudId, inoPtr->bundleName); + if (ret != 0) { + LOGE("Failed generate cloud id, ret: %{public}d", ret); + fuse_reply_err(req, ENOSYS); + return; + } + if ((rdbStore->CopyFile(inoPtr->cloudId, destCloudId, inoPtr->bundleName, dataReq->userId, destPath) != 0)) { + fuse_reply_err(req, EIO); + return; + } + fuse_reply_ioctl(req, 0, NULL, 0); + } else { + LOGE("Invalid argument, cmd is not supported"); + fuse_reply_err(req, EINVAL); + return; + } +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp b/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp new file mode 100644 index 0000000..03b35c1 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2023-2024 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 "file_operations_helper.h" + +#include +#include + +#include "cloud_file_fault_event.h" +#include "file_operations_cloud.h" +#include "file_operations_local.h" +#include "securec.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +namespace { + static const string LOCAL_PATH_DATA_SERVICE_EL2 = "/data/service/el2/"; + static const string LOCAL_PATH_HMDFS_CLOUD_DATA = "/hmdfs/cloud/data/"; + static const string LOCAL_PATH_HMDFS_CLOUD = "/hmdfs/cloud/"; + static const int32_t BUNDLE_NAME_OFFSET = 1000000000; + static const int32_t STAT_MODE_DIR = 0771; +} + +string FileOperationsHelper::GetCloudDiskRootPath(int32_t userId) +{ + return LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + LOCAL_PATH_HMDFS_CLOUD; +} + +string FileOperationsHelper::GetCloudDiskLocalPath(int32_t userId, string fileName) +{ + if (fileName == "data") { + return LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + + LOCAL_PATH_HMDFS_CLOUD_DATA; + } else if (fileName == "/") { + return GetCloudDiskRootPath(userId); + } else { + return LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + + LOCAL_PATH_HMDFS_CLOUD_DATA + fileName; + } +} + +void FileOperationsHelper::GetInodeAttr(shared_ptr ino, struct stat *statBuf) +{ + statBuf->st_ino = ino->stat.st_ino; + statBuf->st_uid = ino->stat.st_uid; + statBuf->st_gid = ino->stat.st_gid; + statBuf->st_mtime = ino->stat.st_mtime; + statBuf->st_ctime = ino->stat.st_ctime; + statBuf->st_atime = ino->stat.st_atime; + statBuf->st_mode = ino->stat.st_mode; + statBuf->st_nlink = ino->stat.st_nlink; + if (statBuf->st_mode & S_IFREG) { + statBuf->st_size = ino->stat.st_size; + } +} + +int32_t FileOperationsHelper::GetNextLayer(std::shared_ptr inoPtr, fuse_ino_t ino) +{ + if (ino == FUSE_ROOT_ID) { + return CLOUD_DISK_INODE_ZERO_LAYER; + } + if (inoPtr->layer >= CLOUD_DISK_INODE_OTHER_LAYER) { + return CLOUD_DISK_INODE_OTHER_LAYER; + } else { + return inoPtr->layer + 1; + } +} + +int32_t FileOperationsHelper::GetFixedLayerRootId(int32_t layer) +{ + if (layer == CLOUD_DISK_INODE_ZERO_LAYER) { + return CLOUD_DISK_INODE_ZERO_LAYER_LOCALID; + } else if (layer == CLOUD_DISK_INODE_FIRST_LAYER) { + return CLOUD_DISK_INODE_FIRST_LAYER_LOCALID; + } + return CLOUD_DISK_INODE_LAYER_LOCALID_UNKNOWN; +} + +shared_ptr FileOperationsHelper::FindCloudDiskInode(struct CloudDiskFuseData *data, + int64_t key) +{ + shared_ptr ret; + shared_lock rLock(data->cacheLock, std::defer_lock); + rLock.lock(); + auto it = data->inodeCache.find(key); + if (it != data->inodeCache.end()) { + ret = it->second; + } else { + ret = nullptr; + } + rLock.unlock(); + return ret; +} + +shared_ptr FileOperationsHelper::FindCloudDiskFile(struct CloudDiskFuseData *data, + int64_t key) +{ + shared_ptr ret; + shared_lock rLock(data->fileLock, std::defer_lock); + rLock.lock(); + auto it = data->fileCache.find(key); + if (it != data->fileCache.end()) { + ret = it->second; + } else { + ret = nullptr; + } + rLock.unlock(); + return ret; +} + +int64_t FileOperationsHelper::FindLocalId(struct CloudDiskFuseData *data, const std::string &key) +{ + int64_t ret = -1; + shared_lock rLock(data->localIdLock, std::defer_lock); + rLock.lock(); + auto it = data->localIdCache.find(key); + if (it != data->localIdCache.end()) { + ret = it->second; + } else { + ret = -1; + } + rLock.unlock(); + return ret; +} + +void FileOperationsHelper::AddDirEntry(fuse_req_t req, std::string &buf, size_t &size, const char *name, + std::shared_ptr ino) +{ + size_t oldSize = size; + size += fuse_add_direntry(req, NULL, 0, name, NULL, 0); + buf.resize(size); + fuse_add_direntry(req, &buf[oldSize], size - oldSize, name, &ino->stat, size); +} + +void FileOperationsHelper::FuseReplyLimited(fuse_req_t req, const char *buf, size_t bufSize, + off_t off, size_t maxSize) +{ + if (off < static_cast(bufSize)) { + size_t size = (bufSize - off) < maxSize ? (bufSize - off) : maxSize; + fuse_reply_buf(req, buf + off, size); + } else { + fuse_reply_buf(req, NULL, 0); + } +} + +shared_ptr FileOperationsHelper::GenerateCloudDiskInode(struct CloudDiskFuseData *data, + fuse_ino_t parent, + const string &fileName, + const string &path) +{ + std::unique_lock cWLock(data->cacheLock, std::defer_lock); + std::unique_lock lWLock(data->localIdLock, std::defer_lock); + shared_ptr child = make_shared(); + int32_t err = stat(path.c_str(), &child->stat); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{child->bundleName, CloudFile::FaultOperation::READDIR, + CloudFile::FaultType::INODE_FILE, errno, "GenerateCloudDiskInode " + GetAnonyString(path) + " error" + + "err: " + std::to_string(errno)}); + return nullptr; + } + child->stat.st_mode |= STAT_MODE_DIR; + auto parentInode = FindCloudDiskInode(data, parent); + if (parentInode == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{child->bundleName, CloudFile::FaultOperation::READDIR, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + return nullptr; + } + child->refCount++; + child->parent = parent; + child->path = path; + child->layer = GetNextLayer(parentInode, parent); + int64_t localId = GetFixedLayerRootId(child->layer); + if (child->layer >= CLOUD_DISK_INODE_FIRST_LAYER) { + std::lock_guard bWLock(data->bundleNameIdLock); + data->bundleNameId++; + localId = data->bundleNameId + BUNDLE_NAME_OFFSET; + } + child->stat.st_ino = static_cast(localId); + child->ops = make_shared(); + cWLock.lock(); + data->inodeCache[localId] = child; + cWLock.unlock(); + lWLock.lock(); + data->localIdCache[path] = localId; + lWLock.unlock(); + if (child->layer == CLOUD_DISK_INODE_FIRST_LAYER) { + child->bundleName = fileName; + child->ops = make_shared(); + } + return child; +} + +void FileOperationsHelper::PutCloudDiskInode(struct CloudDiskFuseData *data, + shared_ptr inoPtr, uint64_t num, int64_t key) +{ + std::unique_lock wLock(data->cacheLock, std::defer_lock); + if (inoPtr == nullptr) { + LOGD("Get an invalid inode!"); + return; + } + inoPtr->refCount -= num; + if (inoPtr->refCount == 0) { + LOGD("node released: %{public}" PRId64 "", key); + wLock.lock(); + data->inodeCache.erase(key); + wLock.unlock(); + } +} + +void FileOperationsHelper::PutCloudDiskFile(struct CloudDiskFuseData *data, + shared_ptr filePtr, int64_t key) +{ + std::unique_lock wLock(data->fileLock, std::defer_lock); + if (filePtr == nullptr) { + LOGD("Get an invalid file!"); + return; + } + if (filePtr->refCount == 0) { + LOGD("file released: %{public}" PRId64 "", key); + wLock.lock(); + data->fileCache.erase(key); + wLock.unlock(); + } +} + +void FileOperationsHelper::PutLocalId(struct CloudDiskFuseData *data, + std::shared_ptr inoPtr, + uint64_t num, const std::string &key) +{ + std::unique_lock wLock(data->localIdLock, std::defer_lock); + if (inoPtr == nullptr) { + LOGD("Get an invalid inode!"); + return; + } + inoPtr->refCount -= num; + if (inoPtr->refCount == 0) { + LOGD("node released: %{public}s", key.c_str()); + wLock.lock(); + data->localIdCache.erase(key); + wLock.unlock(); + } +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp b/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp new file mode 100644 index 0000000..69fa05d --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2023-2024 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 "file_operations_local.h" + +#include +#include + +#include "cloud_file_fault_event.h" +#include "file_operations_cloud.h" +#include "file_operations_helper.h" +#include "utils_log.h" +#include "xcollie_helper.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +static const int32_t BUNDLE_NAME_OFFSET = 1000000000; +static const int32_t STAT_MODE_DIR = 0771; +static const float LOOKUP_TIMEOUT = 60.0; +#ifdef HICOLLIE_ENABLE +static const unsigned int LOOKUP_TIMEOUT_S = 1; +static const unsigned int GETATTR_TIMEOUT_S = 1; +#endif + +static int32_t DoLocalLookup(fuse_req_t req, fuse_ino_t parent, const char *name, + struct fuse_entry_param *e) +{ + bool createFlag = false; + struct CloudDiskFuseData *data = reinterpret_cast(fuse_req_userdata(req)); + string path = FileOperationsHelper::GetCloudDiskLocalPath(data->userId, name); + std::unique_lock cWLock(data->cacheLock, std::defer_lock); + string key = std::to_string(parent) + name; + int64_t localId = FileOperationsHelper::FindLocalId(data, key); + auto child = FileOperationsHelper::FindCloudDiskInode(data, localId); + if (child == nullptr) { + child = make_shared(); + createFlag = true; + LOGD("new child %{public}s", name); + } + std::unique_lock lWLock(data->localIdLock, std::defer_lock); + child->refCount++; + if (createFlag) { + if (stat(path.c_str(), &child->stat) != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{child->bundleName, CloudFile::FaultOperation::LOOKUP, + CloudFile::FaultType::INODE_FILE, errno, "lookup " + GetAnonyString(path) + " error, err: " + + std::to_string(errno)}); + return errno; + } + child->stat.st_mode |= STAT_MODE_DIR; + child->parent = parent; + child->path = path; + auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(parent)); + child->layer = FileOperationsHelper::GetNextLayer(parentInode, parent); + localId = FileOperationsHelper::GetFixedLayerRootId(child->layer); + if (child->layer >= CLOUD_DISK_INODE_FIRST_LAYER) { + std::lock_guard bWLock(data->bundleNameIdLock); + data->bundleNameId++; + localId = data->bundleNameId + BUNDLE_NAME_OFFSET; + } + child->stat.st_ino = static_cast(localId); + child->ops = make_shared(); + cWLock.lock(); + data->inodeCache[localId] = child; + cWLock.unlock(); + lWLock.lock(); + data->localIdCache[key] = localId; + lWLock.unlock(); + } + if (child->layer >= CLOUD_DISK_INODE_FIRST_LAYER) { + child->bundleName = name; + child->ops = make_shared(); + } + e->ino = static_cast(localId); + FileOperationsHelper::GetInodeAttr(child, &e->attr); + return 0; +} + +void FileOperationsLocal::Lookup(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + struct fuse_entry_param e; + int32_t err; + e.attr_timeout = LOOKUP_TIMEOUT; + e.entry_timeout = LOOKUP_TIMEOUT; +#ifdef HICOLLIE_ENABLE + auto xcollieId = XCollieHelper::SetTimer("CloudDisk_Lookup", LOOKUP_TIMEOUT_S, nullptr, nullptr, false); +#endif + err = DoLocalLookup(req, parent, name, &e); + if (err) { + fuse_reply_err(req, err); + } else { + fuse_reply_entry(req, &e); + } +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif +} + +void FileOperationsLocal::GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ +#ifdef HICOLLIE_ENABLE + auto xcollieId = XCollieHelper::SetTimer("CloudDisk_GetAttr", GETATTR_TIMEOUT_S, nullptr, nullptr, false); +#endif + struct CloudDiskFuseData *data = reinterpret_cast(fuse_req_userdata(req)); + if (ino == FUSE_ROOT_ID) { + string path = FileOperationsHelper::GetCloudDiskRootPath(data->userId); + + struct stat statBuf; + int err = stat(path.c_str(), &statBuf); + if (err != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETATTR, + CloudFile::FaultType::FILE, errno, "lookup " + GetAnonyString(path) + " error, err: " + + std::to_string(errno)}); + fuse_reply_err(req, errno); +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif + return; + } + fuse_reply_attr(req, &statBuf, 0); +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif + return; + } + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif + return; + } + fuse_reply_attr(req, &inoPtr->stat, 0); +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif +} + +void FileOperationsLocal::ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) +{ + (void) fi; + string path; + struct CloudDiskFuseData *data = + reinterpret_cast(fuse_req_userdata(req)); + if (ino == FUSE_ROOT_ID) { + path = FileOperationsHelper::GetCloudDiskRootPath(data->userId); + } else { + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READDIR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + path = inoPtr->path; + } + DIR* dir = opendir(path.c_str()); + if (dir == NULL) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READDIR, + CloudFile::FaultType::FILE, errno, "opendir error " + std::to_string(errno) + ", path: " + + GetAnonyString(path)}); + return; + } + + struct dirent *entry; + string entryData; + size_t len = 0; + while ((entry = readdir(dir)) != NULL) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { + continue; + } + + string childPath = FileOperationsHelper::GetCloudDiskLocalPath(data->userId, + entry->d_name); + int64_t key = FileOperationsHelper::FindLocalId(data, std::to_string(ino) + + entry->d_name); + auto childPtr = FileOperationsHelper::FindCloudDiskInode(data, key); + if (childPtr == nullptr) { + childPtr = FileOperationsHelper::GenerateCloudDiskInode(data, ino, + entry->d_name, childPath.c_str()); + } + if (childPtr == nullptr) { + continue; + } + FileOperationsHelper::AddDirEntry(req, entryData, len, entry->d_name, childPtr); + } + FileOperationsHelper::FuseReplyLimited(req, entryData.c_str(), len, off, size); + closedir(dir); + return; +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp b/cloud_file/services/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp new file mode 100644 index 0000000..e3d70ab --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp @@ -0,0 +1,396 @@ +/* + * 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 "fuse_operations.h" + +#include "cloud_disk_inode.h" +#include "cloud_file_fault_event.h" +#include "file_operations_helper.h" +#include "file_operations_local.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; + +static std::shared_ptr GetCloudDiskInode(fuse_req_t req, fuse_ino_t ino) +{ + struct CloudDiskFuseData *data = reinterpret_cast(fuse_req_userdata(req)); + return FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); +} + +void FuseOperations::Lookup(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + if (parent == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Lookup(req, parent, name); + return; + } + auto inoPtr = GetCloudDiskInode(req, parent); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::LOOKUP, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->Lookup(req, parent, name); +} + +void FuseOperations::Access(fuse_req_t req, fuse_ino_t ino, int mask) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Access(req, ino, mask); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + fuse_reply_err(req, EINVAL); + LOGE("inode not found"); + return; + } + inoPtr->ops->Access(req, ino, mask); +} + +void FuseOperations::GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->GetAttr(req, ino, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->GetAttr(req, ino, fi); +} + +void FuseOperations::Open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Open(req, ino, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::OPEN, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->Open(req, ino, fi); +} + +void FuseOperations::Forget(fuse_req_t req, fuse_ino_t ino, uint64_t nLookup) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Forget(req, ino, nLookup); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::FORGET, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->Forget(req, ino, nLookup); +} + +void FuseOperations::ForgetMulti(fuse_req_t req, size_t count, struct fuse_forget_data *forgets) +{ + if (count == 0 || forgets[0].ino == FUSE_ROOT_ID) { + return; + } + auto inoPtr = GetCloudDiskInode(req, forgets[0].ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::FORGETMULTI, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->ForgetMulti(req, count, forgets); +} + +void FuseOperations::MkNod(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, dev_t rdev) +{ + if (parent == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->MkNod(req, parent, name, mode, rdev); + return; + } + auto inoPtr = GetCloudDiskInode(req, parent); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKNOD, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->MkNod(req, parent, name, mode, rdev); +} + +void FuseOperations::Create(fuse_req_t req, fuse_ino_t parent, const char *name, + mode_t mode, struct fuse_file_info *fi) +{ + if (parent == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Create(req, parent, name, mode, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, parent); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::CREATE, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->Create(req, parent, name, mode, fi); +} + +void FuseOperations::ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) +{ + (void) fi; + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->ReadDir(req, ino, size, off, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READDIR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->ReadDir(req, ino, size, off, fi); +} + +void FuseOperations::SetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + const char *value, size_t size, int flags) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->SetXattr(req, ino, name, value, size, flags); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->SetXattr(req, ino, name, value, size, flags); +} + +void FuseOperations::GetXattr(fuse_req_t req, fuse_ino_t ino, const char *name, + size_t size) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->GetXattr(req, ino, name, size); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::GETEXTATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->GetXattr(req, ino, name, size); +} + +void FuseOperations::MkDir(fuse_req_t req, fuse_ino_t parent, const char *name, mode_t mode) +{ + if (parent == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->MkDir(req, parent, name, mode); + return; + } + auto inoPtr = GetCloudDiskInode(req, parent); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::MKDIR, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->MkDir(req, parent, name, mode); +} + +void FuseOperations::RmDir(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + if (parent == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->RmDir(req, parent, name); + return; + } + auto inoPtr = GetCloudDiskInode(req, parent); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RMDIR, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->RmDir(req, parent, name); +} + +void FuseOperations::Unlink(fuse_req_t req, fuse_ino_t parent, const char *name) +{ + if (parent == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Unlink(req, parent, name); + return; + } + auto inoPtr = GetCloudDiskInode(req, parent); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::UNLINK, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->Unlink(req, parent, name); +} + +void FuseOperations::Rename(fuse_req_t req, fuse_ino_t parent, const char *name, + fuse_ino_t newParent, const char *newName, unsigned int flags) +{ + if (parent == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Rename(req, parent, name, newParent, newName, flags); + return; + } + auto inoPtr = GetCloudDiskInode(req, parent); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RENAME, + CloudFile::FaultType::INODE_FILE, EINVAL, "parent inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->Rename(req, parent, name, newParent, newName, flags); +} + +void FuseOperations::Read(fuse_req_t req, fuse_ino_t ino, size_t size, + off_t offset, struct fuse_file_info *fi) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Read(req, ino, size, offset, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::READ, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->Read(req, ino, size, offset, fi); +} + +void FuseOperations::WriteBuf(fuse_req_t req, fuse_ino_t ino, struct fuse_bufvec *bufv, + off_t off, struct fuse_file_info *fi) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->WriteBuf(req, ino, bufv, off, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::WRITE, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->WriteBuf(req, ino, bufv, off, fi); +} + +void FuseOperations::Release(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Release(req, ino, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::RELEASE, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->Release(req, ino, fi); +} +void FuseOperations::SetAttr(fuse_req_t req, fuse_ino_t ino, struct stat *attr, + int valid, struct fuse_file_info *fi) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->SetAttr(req, ino, attr, valid, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + CLOUD_FILE_FAULT_REPORT(CloudFile::CloudFileFaultInfo{"", CloudFile::FaultOperation::SETATTR, + CloudFile::FaultType::INODE_FILE, EINVAL, "inode not found"}); + fuse_reply_err(req, EINVAL); + return; + } + inoPtr->ops->SetAttr(req, ino, attr, valid, fi); +} +void FuseOperations::Lseek(fuse_req_t req, fuse_ino_t ino, off_t off, int whence, + struct fuse_file_info *fi) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Lseek(req, ino, off, whence, fi); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + fuse_reply_err(req, EINVAL); + LOGE("inode not found"); + return; + } + inoPtr->ops->Lseek(req, ino, off, whence, fi); +} +void FuseOperations::Ioctl(fuse_req_t req, fuse_ino_t ino, int cmd, void *arg, struct fuse_file_info *fi, + unsigned flags, const void *inBuf, size_t inBufsz, size_t outBufsz) +{ + if (ino == FUSE_ROOT_ID) { + auto opsPtr = make_shared(); + opsPtr->Ioctl(req, ino, cmd, arg, fi, flags, inBuf, inBufsz, outBufsz); + return; + } + auto inoPtr = GetCloudDiskInode(req, ino); + if (inoPtr == nullptr) { + LOGE("inode not found"); + fuse_reply_err(req, ENOENT); + return; + } + inoPtr->ops->Ioctl(req, ino, cmd, arg, fi, flags, inBuf, inBufsz, outBufsz); +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp b/cloud_file/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp new file mode 100644 index 0000000..6e0d44b --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2024 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 "cloud_daemon_statistic.h" + +#include +#include +#include +#include + +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using namespace std; + +#define FILE_SIZE_BYTE_TO_KB 1024 +#define FILE_SIZE_KB_TO_MB 1024 +#define STAT_TIME_MS_TO_S 1000 +#define CLOUD_FILE_DIR_MOD 0770 +#define CLOUD_FILE_MOD 0660 + +static const string STAT_DATA_DIR_NAME = "/data/service/el1/public/cloudfile/cloud_data_statistic"; +static const string STAT_DATA_FILE_NAME = "cloud_sync_read_file_stat"; +static const vector OPEN_SIZE_RANGE_VECTOR = { 256, 512, 1 * FILE_SIZE_KB_TO_MB, 2 * FILE_SIZE_KB_TO_MB, + 4 * FILE_SIZE_KB_TO_MB, 6 * FILE_SIZE_KB_TO_MB, 8 * FILE_SIZE_KB_TO_MB, 15 * FILE_SIZE_KB_TO_MB }; +static const vector OPEN_TIME_RANGE_VECTOR = { 250, 500, 1000, 1500, 2000, 5000 }; +static const vector READ_SIZE_RANGE_VECTOR = { 128, 256, 512, 1 * FILE_SIZE_KB_TO_MB, 2 * FILE_SIZE_KB_TO_MB, + 4 * FILE_SIZE_KB_TO_MB }; +static const vector READ_TIME_RANGE_VECTOR = { 300, 600, 900, 1200, 1500, 2000, 3000, 5000, 8000 }; + +static uint32_t GetRangeIndex(uint64_t value, const vector rangeVector) +{ + uint32_t index = 0; + for (; index < rangeVector.size(); index++) { + if (value <= rangeVector[index]) { + break; + } + } + return index; +} + +static void CheckOverflow(uint64_t &data, uint64_t addValue) +{ + if (data >= UINT64_MAX - addValue) { + LOGE("update fail, overflow, data = %{public}llu, addValue = %{public}llu", + static_cast(data), + static_cast(addValue)); + data = 0; + } else { + data += addValue; + } +} + +void CloudDaemonStatistic::UpdateOpenSizeStat(uint64_t size) +{ + uint32_t index = GetRangeIndex(size / FILE_SIZE_BYTE_TO_KB, OPEN_SIZE_RANGE_VECTOR); + if (index >= OPEN_SIZE_MAX) { + LOGE("update open size stat fail, index overflow, index = %{public}u.", index); + return; + } + CheckOverflow(openSizeStat_[index], 1); +} + +void CloudDaemonStatistic::UpdateOpenTimeStat(uint32_t type, uint64_t time) +{ + uint32_t index = GetRangeIndex(time, OPEN_TIME_RANGE_VECTOR); + if (index >= OPEN_TIME_MAX) { + LOGE("update open time stat fail, index overflow, index = %{public}u.", index); + return; + } + CheckOverflow(openTimeStat_[type][index], 1); +} + +void CloudDaemonStatistic::UpdateReadSizeStat(uint64_t size) +{ + uint32_t index = GetRangeIndex(size / FILE_SIZE_BYTE_TO_KB, READ_SIZE_RANGE_VECTOR); + if (index >= READ_SIZE_MAX) { + LOGE("update read size stat fail, index overflow, index = %{public}u.", index); + return; + } + CheckOverflow(readSizeStat_[index], 1); +} + +void CloudDaemonStatistic::UpdateReadTimeStat(uint64_t size, uint64_t time) +{ + uint32_t indexSize = GetRangeIndex(size / FILE_SIZE_BYTE_TO_KB, READ_SIZE_RANGE_VECTOR); + uint32_t indexTime = GetRangeIndex(time, READ_TIME_RANGE_VECTOR); + if (indexSize >= READ_SIZE_MAX || indexTime >= READ_TIME_MAX) { + LOGE("update read time stat fail, index overflow, indexSize = %{public}u, indexTime = %{public}u.", + indexSize, indexTime); + return; + } + CheckOverflow(readTimeStat_[indexSize][indexTime], 1); +} + +void CloudDaemonStatistic::AddFileData() +{ + /* file not exist means first time, no former data, normal case */ + auto ret = access(STAT_DATA_DIR_NAME.c_str(), F_OK); + if (ret != 0) { + LOGI("dir cloud_data_statistic not exist, ret = %{public}d.", ret); + return; + } + std::ifstream statDataFile(STAT_DATA_DIR_NAME + "/" + STAT_DATA_FILE_NAME); + if (!statDataFile) { + LOGI("file cloud_sync_read_file_stat not exist."); + return; + } + + uint64_t tmpData; + for (uint32_t i = 0; i < OPEN_SIZE_MAX; i++) { + statDataFile >> tmpData; + CheckOverflow(openSizeStat_[i], tmpData); + } + for (uint32_t i = 0; i < FILE_TYPE_MAX; i++) { + for (uint32_t j = 0; j < OPEN_TIME_MAX; j++) { + statDataFile >> tmpData; + CheckOverflow(openTimeStat_[i][j], tmpData); + } + } + for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { + statDataFile >> tmpData; + CheckOverflow(readSizeStat_[i], tmpData); + } + for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { + for (uint32_t j = 0; j < READ_TIME_MAX; j++) { + statDataFile >> tmpData; + CheckOverflow(readTimeStat_[i][j], tmpData); + } + } + statDataFile.close(); +} + +void CloudDaemonStatistic::OutputToFile() +{ + string tmpStr = ""; + + if (access(STAT_DATA_DIR_NAME.c_str(), F_OK) != 0) { + auto ret = mkdir(STAT_DATA_DIR_NAME.c_str(), CLOUD_FILE_DIR_MOD); + if (ret != 0) { + LOGE("mkdir cloud_data_statistic fail, ret = %{public}d.", ret); + return; + } + } + string statFilePath = STAT_DATA_DIR_NAME + "/" + STAT_DATA_FILE_NAME; + if (access(statFilePath.c_str(), F_OK) != 0) { + auto fd = creat(statFilePath.c_str(), CLOUD_FILE_MOD); + if (fd < 0) { + LOGE("create file cloud_sync_read_file_stat fail."); + return; + } + close(fd); + } + + std::ofstream statDataFile(statFilePath); + if (!statDataFile) { + LOGE("open out stream file cloud_sync_read_file_stat fail."); + return; + } + + for (uint32_t i = 0; i < OPEN_SIZE_MAX; i++) { + tmpStr += (to_string(openSizeStat_[i]) + " "); + } + statDataFile << tmpStr << endl << endl; + tmpStr = ""; + + for (uint32_t i = 0; i < FILE_TYPE_MAX; i++) { + for (uint32_t j = 0; j < OPEN_TIME_MAX; j++) { + tmpStr += (to_string(openTimeStat_[i][j]) + " "); + } + tmpStr += "\n"; + } + statDataFile << tmpStr << endl; + tmpStr = ""; + + for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { + tmpStr += (to_string(readSizeStat_[i]) + " "); + } + statDataFile << tmpStr << endl << endl; + tmpStr = ""; + + for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { + for (uint32_t j = 0; j < READ_TIME_MAX; j++) { + tmpStr += (to_string(readTimeStat_[i][j]) + " "); + } + tmpStr += "\n"; + } + statDataFile << tmpStr << endl; + statDataFile.close(); +} + +void CloudDaemonStatistic::ClearStat() +{ + for (uint32_t i = 0; i < OPEN_SIZE_MAX; i++) { + openSizeStat_[i] = 0; + } + for (uint32_t i = 0; i < FILE_TYPE_MAX; i++) { + for (uint32_t j = 0; j < OPEN_TIME_MAX; j++) { + openTimeStat_[i][j] = 0; + } + } + for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { + readSizeStat_[i] = 0; + } + for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { + for (uint32_t j = 0; j < READ_TIME_MAX; j++) { + readTimeStat_[i][j] = 0; + } + } +} + +void CloudDaemonStatistic::UpdateStatData() +{ + lock_guard lock(mutex_); + AddFileData(); + OutputToFile(); + ClearStat(); +} + +CloudDaemonStatistic &CloudDaemonStatistic::GetInstance() +{ + static CloudDaemonStatistic instance_; + return instance_; +} + +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp b/cloud_file/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp new file mode 100644 index 0000000..119ec4e --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp @@ -0,0 +1,1758 @@ +/* + * Copyright (c) 2023-2024 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 "fuse_manager/fuse_manager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cloud_daemon_statistic.h" +#include "cloud_disk_inode.h" +#include "cloud_file_fault_event.h" +#include "cloud_file_kit.h" +#include "cloud_file_utils.h" +#include "clouddisk_type_const.h" +#include "database_manager.h" +#include "datetime_ex.h" +#include "dfs_error.h" +#include "directory_ex.h" +#include "fdsan.h" +#include "ffrt_inner.h" +#include "fuse_operations.h" +#ifdef HICOLLIE_ENABLE +#include "xcollie_helper.h" +#endif +#include "hitrace_meter.h" +#include "meta_file.h" +#include "securec.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using namespace std; +using PAGE_FLAG_TYPE = const uint32_t; + +static const string LOCAL_PATH_DATA_SERVICE_EL2 = "/data/service/el2/"; +static const string LOCAL_PATH_HMDFS_ACCOUNT = "/hmdfs/account"; +static const string LOCAL_PATH_HMDFS_CLOUD_CACHE = "/hmdfs/cache/cloud_cache"; +static const string CLOUD_CACHE_DIR = "/pread_cache"; +static const string CLOUD_CACHE_XATTR_NAME = "user.cloud.cacheMap"; +static const string VIDEO_TYPE_PREFIX = "VID_"; +static const string HMDFS_PATH_PREFIX = "/mnt/hmdfs/"; +static const string LOCAL_PATH_SUFFIX = "/account/device_view/local"; +static const string CLOUD_MERGE_VIEW_PATH_SUFFIX = "/account/cloud_merge_view"; +static const string PATH_TEMP_SUFFIX = ".temp.fuse"; +static const string PHOTOS_BUNDLE_NAME = "com.ohos.photos"; +static const unsigned int OID_USER_DATA_RW = 1008; +static const unsigned int STAT_NLINK_REG = 1; +static const unsigned int STAT_NLINK_DIR = 2; +static const unsigned int STAT_MODE_REG = 0770; +static const unsigned int STAT_MODE_DIR = 0771; +static const unsigned int MAX_READ_SIZE = 4 * 1024 * 1024; +static const unsigned int KEY_FRAME_SIZE = 8192; +static const unsigned int MAX_IDLE_THREADS = 6; +static const unsigned int READ_CACHE_SLEEP = 10 * 1000; +static const unsigned int CACHE_PAGE_NUM = 2; +static const unsigned int HMDFS_IOC = 0xf2; +static const unsigned int FUSE_BUFFER_SIZE = 512 * 1024; +static const std::chrono::seconds READ_TIMEOUT_S = 16s; +static const std::chrono::seconds OPEN_TIMEOUT_S = 4s; +#ifdef HICOLLIE_ENABLE +static const unsigned int LOOKUP_TIMEOUT_S = 1; +static const unsigned int FORGET_TIMEOUT_S = 1; +#endif + +#define HMDFS_IOC_HAS_CACHE _IOW(HMDFS_IOC, 6, struct HmdfsHasCache) +#define HMDFS_IOC_CANCEL_READ _IO(HMDFS_IOC, 8) +#define HMDFS_IOC_RESET_READ _IO(HMDFS_IOC, 9) +PAGE_FLAG_TYPE PG_READAHEAD = 0x00000001; +PAGE_FLAG_TYPE PG_UPTODATE = 0x00000002; +PAGE_FLAG_TYPE PG_REFERENCED = 0x00000004; +PAGE_FLAG_TYPE PG_NEEDBECLEANED = 0x00000020; + +enum CLOUD_READ_STATUS { + READING = 0, + READ_FINISHED, + READ_CANCELED, +}; + +enum CLOUD_CACHE_STATUS : int { + NOT_CACHE = 0, + HAS_CACHED, +}; + +struct ReadCacheInfo { + std::mutex mutex; + std::condition_variable cond{}; + uint32_t flags{0}; +}; + +struct ReadSlice { + size_t sizeHead{0}; + size_t sizeTail{0}; + off_t offHead{0}; + off_t offTail{0}; +}; + +struct ReadSize { + size_t size{0}; + size_t sizeDone{0}; +}; + +struct ReadArguments { + size_t size{0}; + off_t offset{0}; + pid_t pid{0}; + shared_ptr readResult{nullptr}; + shared_ptr readStatus{nullptr}; + shared_ptr ckError{nullptr}; + shared_ptr cond{nullptr}; + shared_ptr buf{nullptr}; + + ReadArguments(size_t readSize, off_t readOffset, pid_t readPid) : size(readSize), offset(readOffset), pid(readPid) + { + readResult = make_shared(-1); + readStatus = make_shared(READING); + ckError = make_shared(); + cond = make_shared(); + if (0 < readSize && readSize <= MAX_READ_SIZE) { + buf.reset(new char[readSize], [](char *ptr) { delete[] ptr; }); + } + } +}; + +struct CloudInode { + shared_ptr mBase{nullptr}; + string path; + fuse_ino_t parent{0}; + atomic refCount{0}; + shared_ptr readSession{nullptr}; + atomic sessionRefCount{0}; + std::shared_mutex sessionLock; + ffrt::mutex readLock; + ffrt::mutex openLock; + std::mutex readArgsLock; + off_t offset{0xffffffff}; + std::map> readCacheMap; + /* variable readArguments for cancel*/ + std::set> readArgsSet; + /* process's read status for ioctl, true when canceled */ + std::map readCtlMap; + std::unique_ptr cacheFileIndex{nullptr}; + bool SetReadCacheFlag(int64_t index, PAGE_FLAG_TYPE flag) + { + std::shared_lock lock(sessionLock); + auto it = readCacheMap.find(index); + if (it != readCacheMap.end()) { + std::unique_lock flock(it->second->mutex); + it->second->flags |= flag; + return true; + } + return false; + } + bool IsReadAhead(int64_t index) + { + std::shared_lock lock(sessionLock); + auto it = readCacheMap.find(index); + if (it == readCacheMap.end()) { + return false; + } + std::unique_lock flock(it->second->mutex); + return it->second->flags & PG_READAHEAD; + } + + bool IsReadFinished(int64_t index) + { + std::shared_lock lock(sessionLock); + auto it = readCacheMap.find(index); + if (it == readCacheMap.end()) { + return false; + } + std::unique_lock flock(it->second->mutex); + return it->second->flags & PG_UPTODATE; + } +}; + +struct DoCloudReadParams { + shared_ptr cInode{nullptr}; + shared_ptr readSession{nullptr}; + shared_ptr readArgsHead{nullptr}; + shared_ptr readArgsTail{nullptr}; +}; + +struct HmdfsHasCache { + int64_t offset; + int64_t readSize; +}; + +struct FuseData { + int userId; + shared_ptr rootNode{nullptr}; + /* store CloudInode by path */ + map> inodeCache; + std::shared_mutex cacheLock; + shared_ptr database; + struct fuse_session *se; +}; + +static void InsertReadArgs(shared_ptr cInode, vector> readArgsList) +{ + std::unique_lock lock(cInode->readArgsLock); + for (auto &it : readArgsList) { + if (it) { + cInode->readArgsSet.insert(it); + } + } +} + +static void EraseReadArgs(shared_ptr cInode, vector> readArgsList) +{ + std::unique_lock lock(cInode->readArgsLock); + for (auto &it : readArgsList) { + if (it) { + auto readArgs = cInode->readArgsSet.find(it); + if (readArgs != cInode->readArgsSet.end()) { + cInode->readArgsSet.erase(readArgs); + } + } + } +} + +static pid_t GetPidFromTid(pid_t tid) +{ + pid_t tgid = 0; + std::string path = "/proc/" + to_string(tid) + "/status"; + std::ifstream procTidStatusFile(path); + if (!procTidStatusFile.is_open()) { + LOGD("Failed to open %{public}s", path.c_str()); + return tgid; + } + std::string line; + while (std::getline(procTidStatusFile, line)) { + if (line.find("Tgid:") != std::string::npos) { + size_t colonPos = line.find(':'); + if (colonPos != std::string::npos) { + std::string tgidStr = line.substr(colonPos + 1); + tgid = std::atoi(tgidStr.c_str()); + } + break; + } + } + procTidStatusFile.close(); + return tgid; +} + +static string GetLocalPath(int32_t userId, const string &relativePath) +{ + return HMDFS_PATH_PREFIX + to_string(userId) + LOCAL_PATH_SUFFIX + relativePath; +} + +static string GetCacheTmpPath(int32_t userId, const string &relativePath) +{ + return HMDFS_PATH_PREFIX + to_string(userId) + LOCAL_PATH_SUFFIX + "/files/.cloud_cache/pread_cache/" + + relativePath + PATH_TEMP_SUFFIX; +} + +static string GetLowerPath(int32_t userId, const string &relativePath) +{ + return LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + LOCAL_PATH_HMDFS_ACCOUNT + "/" + relativePath; +} + +static int HandleCloudError(CloudError error, FaultOperation faultOperation, string prepareTraceId) +{ + int ret = 0; + switch (error) { + case CloudError::CK_NO_ERROR: + ret = 0; + break; + case CloudError::CK_NETWORK_ERROR: + ret = -ENOTCONN; + break; + case CloudError::CK_SERVER_ERROR: + ret = -EIO; + break; + case CloudError::CK_LOCAL_ERROR: + ret = -EINVAL; + break; + default: + ret = -EIO; + break; + } + if (ret < 0) { + string msg = "handle cloud failed, ret code: " + to_string(ret) + + " prepareTraceId: " + prepareTraceId; + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::WARNING, ret, msg}); + } + return ret; +} + +#ifdef HICOLLIE_ENABLE + +struct XcollieInput { + shared_ptr node_; + FaultOperation faultOperation_; +}; + +static void XcollieCallback(void *xcollie) +{ + auto xcollieInput = reinterpret_cast(xcollie); + if (xcollieInput == nullptr) { + return; + } + shared_ptr inode = xcollieInput->node_; + if (inode == nullptr) { + return; + } + + FaultType faultType = FaultType::TIMEOUT; + switch (xcollieInput->faultOperation_) { + case FaultOperation::LOOKUP: + faultType = FaultType::CLOUD_FILE_LOOKUP_TIMEOUT; + break; + case FaultOperation::FORGET: + faultType = FaultType::CLOUD_FILE_FORGET_TIMEOUT; + break; + default: + break; + } + + string msg = "In XcollieCallback, path:" + GetAnonyString((inode->path).c_str()); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, xcollieInput->faultOperation_, + faultType, EWOULDBLOCK, msg}); +} +#endif + +static shared_ptr GetDatabase(struct FuseData *data) +{ + if (!data->database) { + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + return nullptr; + } + + data->database = instance->GetCloudDatabase(data->userId, PHOTOS_BUNDLE_NAME); + if (data->database == nullptr) { + LOGE("get cloud file kit database fail"); + return nullptr; + } + } + return data->database; +} + +static shared_ptr FindNode(struct FuseData *data, const uint64_t &cloudId) +{ + shared_ptr ret = nullptr; + std::shared_lock rLock(data->cacheLock, std::defer_lock); + rLock.lock(); + if (data->inodeCache.count(cloudId) != 0) { + ret = data->inodeCache.at(cloudId); + } + rLock.unlock(); + return ret; +} + +static shared_ptr GetRootInode(struct FuseData *data, fuse_ino_t ino) +{ + std::unique_lock wLock(data->cacheLock, std::defer_lock); + shared_ptr ret; + + wLock.lock(); + if (!data->rootNode) { + data->rootNode = make_shared(); + data->rootNode->path = "/"; + data->rootNode->refCount = 1; + data->rootNode->mBase = make_shared(); + data->rootNode->mBase->mode = S_IFDIR; + data->rootNode->mBase->mtime = static_cast(GetSecondsSince1970ToNow()); + LOGD("create rootNode"); + } + ret = data->rootNode; + wLock.unlock(); + + return ret; +} + +static shared_ptr GetCloudInode(struct FuseData *data, fuse_ino_t ino) +{ + if (ino == FUSE_ROOT_ID) { + return GetRootInode(data, ino); + } else { + uint64_t cloudId = static_cast(ino); + auto ret = FindNode(data, cloudId); + if (ret == nullptr) { + LOGE("get inode from cache failed."); + } + return ret; + } +} + +static string CloudPath(struct FuseData *data, fuse_ino_t ino) +{ + auto inode = GetCloudInode(data, ino); + if (inode) { + return inode->path; + } else { + LOGE("find node is nullptr"); + return ""; + } +} + +static void GetMetaAttr(struct FuseData *data, shared_ptr ino, struct stat *stbuf) +{ + string inoKey = ino->mBase->cloudId + ino->mBase->name; + stbuf->st_ino = static_cast(CloudDisk::CloudFileUtils::DentryHash(inoKey)); + stbuf->st_uid = OID_USER_DATA_RW; + stbuf->st_gid = OID_USER_DATA_RW; + stbuf->st_mtime = static_cast(ino->mBase->mtime); + if (ino->mBase->mode & S_IFDIR) { + stbuf->st_mode = S_IFDIR | STAT_MODE_DIR; + stbuf->st_nlink = STAT_NLINK_DIR; + LOGD("directory, ino:%s", GetAnonyString(ino->path).c_str()); + } else { + stbuf->st_mode = S_IFREG | STAT_MODE_REG; + stbuf->st_nlink = STAT_NLINK_REG; + stbuf->st_size = static_castst_size)>(ino->mBase->size); + LOGD("regular file, ino:%s, size: %lld", GetAnonyString(ino->path).c_str(), (long long)stbuf->st_size); + } +} + +static int CloudDoLookupHelper(fuse_ino_t parent, const char *name, struct fuse_entry_param *e, + FuseData *data, string& parentName) +{ + shared_ptr child; + bool create = false; + string childName = (parent == FUSE_ROOT_ID) ? parentName + name : parentName + "/" + name; + std::unique_lock wLock(data->cacheLock, std::defer_lock); + + LOGD("parent: %{private}s, name: %s", GetAnonyString(parentName).c_str(), GetAnonyString(name).c_str()); + + MetaBase mBase(name); + int err = MetaFile(data->userId, parentName).DoLookup(mBase); + if (err) { + LOGE("lookup %s error, err: %{public}d", GetAnonyString(childName).c_str(), err); + return err; + } + string inoKey = mBase.cloudId + mBase.name; + uint64_t cloudId = static_cast(CloudDisk::CloudFileUtils::DentryHash(inoKey)); + child = FindNode(data, cloudId); + if (!child) { + child = make_shared(); + create = true; + LOGD("new child %{public}s", GetAnonyString(childName).c_str()); + } + child->refCount++; + if (create) { + child->mBase = make_shared(mBase); +#ifdef HICOLLIE_ENABLE + XcollieInput xcollieInput{child, FaultOperation::LOOKUP}; + auto xcollieId = XCollieHelper::SetTimer("CloudFileDaemon_CloudLookup", LOOKUP_TIMEOUT_S, + XcollieCallback, &xcollieInput, false); +#endif + wLock.lock(); + data->inodeCache[cloudId] = child; + wLock.unlock(); +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif + } else if (*(child->mBase) != mBase) { + LOGW("invalidate %s", GetAnonyString(childName).c_str()); + child->mBase = make_shared(mBase); + } + if (child->path != childName) { + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::LOOKUP, + FaultType::INODE_FILE, ENOMEM, "hash collision"}); + } + child->path = childName; + child->parent = parent; + LOGD("lookup success, child: %{private}s, refCount: %lld", GetAnonyString(child->path).c_str(), + static_cast(child->refCount)); + GetMetaAttr(data, child, &e->attr); + e->ino = static_cast(cloudId); + return 0; +} + +static int CloudDoLookup(fuse_req_t req, fuse_ino_t parent, const char *name, + struct fuse_entry_param *e) +{ + struct FuseData *data = static_cast(fuse_req_userdata(req)); + string parentName = CloudPath(data, parent); + if (parentName == "") { + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::LOOKUP, + FaultType::FILE, ENOENT, "parent name is empty"}); + return ENOENT; + } + + return CloudDoLookupHelper(parent, name, e, data, parentName); +} + +static void CloudLookup(fuse_req_t req, fuse_ino_t parent, + const char *name) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + struct fuse_entry_param e; + int err; + + err = CloudDoLookup(req, parent, name, &e); + if (err) { + fuse_reply_err(req, err); + } else { + fuse_reply_entry(req, &e); + } +} + +static void PutNode(struct FuseData *data, shared_ptr node, uint64_t num) +{ + std::unique_lock wLock(data->cacheLock, std::defer_lock); + node->refCount -= num; + LOGD("%s, put num: %lld, current refCount: %d", + GetAnonyString(node->path).c_str(), (long long)num, node->refCount.load()); + if (node->refCount == 0) { + LOGD("node released: %s", GetAnonyString(node->path).c_str()); +#ifdef HICOLLIE_ENABLE + XcollieInput xcollieInput{node, FaultOperation::FORGET}; + auto xcollieId = XCollieHelper::SetTimer("CloudFileDaemon_CloudForget", FORGET_TIMEOUT_S, + XcollieCallback, &xcollieInput, false); +#endif + if (node->mBase != nullptr && (node->mBase->mode & S_IFDIR)) { + LOGW("PutNode directory inode, path is %{public}s", GetAnonyString(node->path).c_str()); + } + string inoKey = node->mBase->cloudId + node->mBase->name; + uint64_t cloudId = static_cast(CloudDisk::CloudFileUtils::DentryHash(inoKey)); + wLock.lock(); + data->inodeCache.erase(cloudId); + wLock.unlock(); +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif + } +} + +static void CloudForget(fuse_req_t req, fuse_ino_t ino, + uint64_t nlookup) +{ + struct FuseData *data = static_cast(fuse_req_userdata(req)); + shared_ptr node = GetCloudInode(data, ino); + if (node) { + LOGD("forget %s, nlookup: %lld", GetAnonyString(node->path).c_str(), (long long)nlookup); + PutNode(data, node, nlookup); + } + fuse_reply_none(req); +} + +static void CloudGetAttr(fuse_req_t req, fuse_ino_t ino, + struct fuse_file_info *fi) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + struct stat buf; + struct FuseData *data = static_cast(fuse_req_userdata(req)); + (void) fi; + + LOGD("getattr, %s", GetAnonyString(CloudPath(data, ino)).c_str()); + shared_ptr node = GetCloudInode(data, ino); + if (!node || !node->mBase) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::GETATTR, + FaultType::INODE_FILE, ENOMEM, "failed to get cloud inode"}); + return; + } + GetMetaAttr(data, node, &buf); + + fuse_reply_attr(req, &buf, 0); +} + +static string GetAssetKey(int fileType) +{ + switch (fileType) { + case FILE_TYPE_CONTENT: + return "content"; + case FILE_TYPE_THUMBNAIL: + return "thumbnail"; + case FILE_TYPE_LCD: + return "lcd"; + default: + LOGE("bad fileType %{public}d", fileType); + return ""; + } +} + +static string GetCloudMergeViewPath(int32_t userId, const string &relativePath) +{ + return HMDFS_PATH_PREFIX + to_string(userId) + CLOUD_MERGE_VIEW_PATH_SUFFIX + relativePath; +} + +static string GetAssetPath(shared_ptr cInode, struct FuseData *data) +{ + string path; + filesystem::path parentPath; + path = GetCacheTmpPath(data->userId, cInode->path); + parentPath = filesystem::path(path).parent_path(); + ForceCreateDirectory(parentPath.string()); + LOGD("fileType: %d, create dir: %s, relative path: %s", + cInode->mBase->fileType, GetAnonyString(parentPath.string()).c_str(), GetAnonyString(cInode->path).c_str()); + return path; +} + +static void fuse_inval(fuse_session *se, fuse_ino_t parentIno, fuse_ino_t childIno, const string &childName) +{ + auto task = [se, parentIno, childIno, childName] { + if (fuse_lowlevel_notify_inval_entry(se, parentIno, childName.c_str(), childName.size())) { + fuse_lowlevel_notify_inval_inode(se, childIno, 0, 0); + } + }; + ffrt::submit(task, {}, {}, ffrt::task_attr().qos(ffrt_qos_background)); +} + +static int CloudOpenOnLocal(struct FuseData *data, shared_ptr cInode, struct fuse_file_info *fi) +{ + string localPath = GetLocalPath(data->userId, cInode->path); + string tmpPath = GetCacheTmpPath(data->userId, cInode->path); + string cloudMergeViewPath = GetCloudMergeViewPath(data->userId, cInode->path); + if (remove(cloudMergeViewPath.c_str()) < 0) { + LOGE("Failed to update kernel dentry cache, errno: %{public}d", errno); + return 0; + } + + filesystem::path parentPath = filesystem::path(localPath).parent_path(); + ForceCreateDirectory(parentPath.string()); + if (rename(tmpPath.c_str(), localPath.c_str()) < 0) { + LOGE("Failed to rename tmpPath to localPath, errno: %{public}d", errno); + return -errno; + } + + string lowerPath = GetLowerPath(data->userId, cInode->path); + char resolvedPath[PATH_MAX + 1] = {'\0'}; + char *realPath = realpath(lowerPath.c_str(), resolvedPath); + if (realPath == nullptr) { + LOGE("Failed to realpath, errno: %{public}d", errno); + return 0; + } + unsigned int flags = static_cast(fi->flags); + if (flags & O_DIRECT) { + flags &= ~O_DIRECT; + } + auto fd = open(realPath, flags); + if (fd < 0) { + LOGE("Failed to open local file, errno: %{public}d", errno); + return 0; + } + auto fdsan = new fdsan_fd(fd); + fi->fh = reinterpret_cast(fdsan); + return 0; +} + +static int HandleOpenResult(CloudFile::CloudError ckError, struct FuseData *data, + shared_ptr cInode, struct fuse_file_info *fi) +{ + string prepareTraceId; + if (cInode->readSession) { + prepareTraceId = cInode->readSession->GetPrepareTraceId(); + } + auto ret = HandleCloudError(ckError, FaultOperation::OPEN, prepareTraceId); + if (ret < 0) { + return ret; + } + if (cInode->mBase->fileType != FILE_TYPE_CONTENT) { + ret = CloudOpenOnLocal(data, cInode, fi); + if (ret < 0) { + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::OPEN, + FaultType::INODE_FILE, ret, "inner error"}); + return ret; + } + } + cInode->sessionRefCount++; + LOGI("open success, sessionRefCount: %{public}d", cInode->sessionRefCount.load()); + return 0; +} + +static uint64_t UTCTimeMilliSeconds() +{ + struct timespec t; + clock_gettime(CLOCK_REALTIME, &t); + return t.tv_sec * CloudDisk::SECOND_TO_MILLISECOND + t.tv_nsec / CloudDisk::MILLISECOND_TO_NANOSECOND; +} + +static void DownloadThmOrLcd(shared_ptr cInode, shared_ptr err, shared_ptr openFinish, + shared_ptr cond) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto session = cInode->readSession; + if (!session) { + LOGE("readSession is nullptr"); + return; + } + *err = session->InitSession(); + { + unique_lock lck(cInode->openLock); + *openFinish = true; + } + cond->notify_one(); + LOGI("download done, path: %{public}s", GetAnonyString(cInode->path).c_str()); + return; +} + +static bool IsVideoType(const string &name) +{ + return name.find(VIDEO_TYPE_PREFIX) == 0; +} + +static void LoadCacheFileIndex(shared_ptr cInode, int32_t userId) +{ + string cachePath = LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + LOCAL_PATH_HMDFS_CLOUD_CACHE + + CLOUD_CACHE_DIR + cInode->path; + int filePageSize = static_cast(cInode->mBase->size / MAX_READ_SIZE + 1); + CLOUD_CACHE_STATUS *tmp = new CLOUD_CACHE_STATUS[filePageSize](); + std::unique_ptr mp(tmp); + if (access(cachePath.c_str(), F_OK) != 0) { + cInode->cacheFileIndex = std::move(mp); + string parentPath = filesystem::path(cachePath).parent_path().string(); + if (!ForceCreateDirectory(parentPath)) { + LOGE("failed to create parent dir"); + return; + } + std::FILE *file = fopen(cachePath.c_str(), "a+"); + if (file == nullptr) { + LOGE("failed to open cache file, ret: %{public}d", errno); + return; + } + int fd = fileno(file); + if (fd < 0) { + LOGE("failed to get fd, ret: %{public}d", errno); + } else { + if (ftruncate(fd, cInode->mBase->size) == -1) { + LOGE("failed to truncate file, ret: %{public}d", errno); + } + } + if (fclose(file)) { + LOGE("failed to close cache file, ret: %{public}d", errno); + } + return; + } + + if (getxattr(cachePath.c_str(), CLOUD_CACHE_XATTR_NAME.c_str(), mp.get(), + sizeof(CLOUD_CACHE_STATUS[filePageSize])) < 0 && + errno != ENODATA) { + LOGE("getxattr fail, err: %{public}d", errno); + cInode->cacheFileIndex = std::move(mp); + return; + } + for (int i = 0; i < filePageSize; i++) { + if (mp.get()[i] == HAS_CACHED) { + auto memInfo = std::make_shared(); + memInfo->flags = PG_UPTODATE; + cInode->readCacheMap[i] = memInfo; + } + } + cInode->cacheFileIndex = std::move(mp); +} + +static int DoCloudOpen(shared_ptr cInode, struct fuse_file_info *fi, struct FuseData *data) +{ + auto error = make_shared(); + auto openFinish = make_shared(false); + auto cond = make_shared(); + ffrt::submit([cInode, error, openFinish, cond, data] { + if (IsVideoType(cInode->mBase->name)) { + LoadCacheFileIndex(cInode, data->userId); + } + DownloadThmOrLcd(cInode, error, openFinish, cond); + }); + unique_lock lck(cInode->openLock); + auto waitStatus = cond->wait_for(lck, OPEN_TIMEOUT_S, [openFinish] { + return *openFinish; + }); + if (!waitStatus) { + string prepareTraceId = cInode->readSession->GetPrepareTraceId(); + string msg = "init session timeout, path: " + GetAnonyString((cInode->path).c_str()) + + " prepareTraceId: " + prepareTraceId; + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::OPEN, + FaultType::OPEN_CLOUD_FILE_TIMEOUT, ENETUNREACH, msg}); + return -ENETUNREACH; + } + return HandleOpenResult(*error, data, cInode, fi); +} + +static bool IsLocalFile(struct FuseData *data, shared_ptr cInode) +{ + string localPath = GetLowerPath(data->userId, cInode->path); + return access(localPath.c_str(), F_OK) == 0; +} + +static bool NeedReCloudOpen(struct FuseData *data, shared_ptr cInode) +{ + if (cInode->mBase->fileType == FILE_TYPE_CONTENT) { + return false; + } + return !IsLocalFile(data, cInode); +} + +static void HandleReopen(fuse_req_t req, struct FuseData *data, shared_ptr cInode, + struct fuse_file_info *fi) +{ + do { + if (cInode->mBase->fileType == FILE_TYPE_CONTENT) { + break; + } + string localPath = GetLowerPath(data->userId, cInode->path); + char realPath[PATH_MAX + 1]{'\0'}; + if (realpath(localPath.c_str(), realPath) == nullptr) { + LOGE("realpath failed with %{public}d", errno); + break; + } + unsigned int flags = static_cast(fi->flags); + if (flags & O_DIRECT) { + flags &= ~O_DIRECT; + } + auto fd = open(realPath, flags); + if (fd < 0) { + LOGE("Failed to open local file, errno: %{public}d", errno); + break; + } + auto fdsan = new fdsan_fd(fd); + fi->fh = reinterpret_cast(fdsan); + } while (0); + + cInode->sessionRefCount++; + LOGI("open success, sessionRefCount: %{public}d", cInode->sessionRefCount.load()); + fuse_reply_open(req, fi); +} + +static void UpdateReadStat(shared_ptr cInode, uint64_t startTime) +{ + uint64_t endTime = UTCTimeMilliSeconds(); + CloudDaemonStatistic &readStat = CloudDaemonStatistic::GetInstance(); + readStat.UpdateOpenSizeStat(cInode->mBase->size); + readStat.UpdateOpenTimeStat(cInode->mBase->fileType, (endTime > startTime) ? (endTime - startTime) : 0); +} + +static string GetPrepareTraceId(int32_t userId) +{ + string prepareTraceId; + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + } else { + prepareTraceId = instance->GetPrepareTraceId(userId); + LOGI("get new prepareTraceId %{public}s", prepareTraceId.c_str()); + } + return prepareTraceId; +} + +static void CloudOpenHelper(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi, + struct FuseData *data, shared_ptr& cInode) +{ + pid_t pid = GetPidFromTid(req->ctx.pid); + string recordId = MetaFileMgr::GetInstance().CloudIdToRecordId(cInode->mBase->cloudId); + shared_ptr database = GetDatabase(data); + std::unique_lock wSesLock(cInode->sessionLock, std::defer_lock); + string prepareTraceId = GetPrepareTraceId(data->userId); + + LOGI("%{public}d open %{public}s", pid, GetAnonyString(CloudPath(data, ino)).c_str()); + if (!database) { + LOGE("database is null"); + fuse_inval(data->se, cInode->parent, ino, cInode->mBase->name); + fuse_reply_err(req, EPERM); + return; + } + wSesLock.lock(); + if (!cInode->readSession || NeedReCloudOpen(data, cInode)) { + /* + * 'recordType' is fixed to "media" now + * 'assetKey' is one of "content"/"lcd"/"thumbnail" + */ + LOGD("recordId: %s", recordId.c_str()); + uint64_t startTime = UTCTimeMilliSeconds(); + cInode->readSession = database->NewAssetReadSession(data->userId, "media", recordId, + GetAssetKey(cInode->mBase->fileType), GetAssetPath(cInode, data)); + if (cInode->readSession) { + cInode->readSession->SetPrepareTraceId(prepareTraceId); + auto ret = DoCloudOpen(cInode, fi, data); + if (ret == 0) { + fuse_reply_open(req, fi); + } else { + fuse_inval(data->se, cInode->parent, ino, cInode->mBase->name); + fuse_reply_err(req, -ret); + cInode->readSession = nullptr; + } + UpdateReadStat(cInode, startTime); + wSesLock.unlock(); + return; + } + } + if (!cInode->readSession) { + fuse_inval(data->se, cInode->parent, ino, cInode->mBase->name); + fuse_reply_err(req, EPERM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::OPEN, + FaultType::DRIVERKIT, EPERM, "readSession is null or fix size fail"}); + } else { + HandleReopen(req, data, cInode, fi); + } + wSesLock.unlock(); +} + +static void CloudOpen(fuse_req_t req, fuse_ino_t ino, + struct fuse_file_info *fi) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + struct FuseData *data = static_cast(fuse_req_userdata(req)); + fi->fh = UINT64_MAX; + shared_ptr cInode = GetCloudInode(data, ino); + if (!cInode) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::OPEN, + FaultType::INODE_FILE, ENOMEM, "failed to get cloud inode"}); + return; + } + CloudOpenHelper(req, ino, fi, data, cInode); +} + +static void CloudRelease(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + pid_t pid = GetPidFromTid(req->ctx.pid); + struct FuseData *data = static_cast(fuse_req_userdata(req)); + shared_ptr cInode = GetCloudInode(data, ino); + if (!cInode) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::RELEASE, + FaultType::INODE_FILE, ENOMEM, "failed to get cloud inode"}); + return; + } + std::unique_lock wSesLock(cInode->sessionLock, std::defer_lock); + LOGI("%{public}d release %{public}s, sessionRefCount: %{public}d", pid, + GetAnonyString(cInode->path).c_str(), cInode->sessionRefCount.load()); + wSesLock.lock(); + cInode->sessionRefCount--; + if (fi->fh != UINT64_MAX) { + auto fdsan = reinterpret_cast(fi->fh); + delete fdsan; + fi->fh = UINT64_MAX; + } + if (cInode->sessionRefCount == 0) { + if (cInode->mBase->fileType == FILE_TYPE_CONTENT && (!cInode->readSession->Close(false))) { + LOGE("Failed to close readSession"); + } + cInode->readSession = nullptr; + cInode->readCacheMap.clear(); + { + std::unique_lock lock(cInode->readArgsLock); + cInode->readCtlMap.clear(); + } + if (cInode->cacheFileIndex) { + string cachePath = LOCAL_PATH_DATA_SERVICE_EL2 + to_string(data->userId) + LOCAL_PATH_HMDFS_CLOUD_CACHE + + CLOUD_CACHE_DIR + cInode->path; + if (setxattr(cachePath.c_str(), CLOUD_CACHE_XATTR_NAME.c_str(), cInode->cacheFileIndex.get(), + sizeof(int[cInode->mBase->size / MAX_READ_SIZE + 1]), 0) < 0) { + LOGE("setxattr fail, err: %{public}d", errno); + } + } + LOGD("readSession released"); + } + wSesLock.unlock(); + + LOGI("release end"); + fuse_inval(data->se, cInode->parent, ino, cInode->mBase->name); + fuse_reply_err(req, 0); +} + +static void CloudReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, + off_t off, struct fuse_file_info *fi) +{ + struct FuseData *data = static_cast(fuse_req_userdata(req)); + LOGE("readdir %s, not support", GetAnonyString(CloudPath(data, ino)).c_str()); + fuse_reply_err(req, ENOENT); +} + +static void CloudForgetMulti(fuse_req_t req, size_t count, + struct fuse_forget_data *forgets) +{ + struct FuseData *data = static_cast(fuse_req_userdata(req)); + LOGD("forget_multi"); + for (size_t i = 0; i < count; i++) { + shared_ptr node = GetCloudInode(data, forgets[i].ino); + if (!node) { + continue; + } + LOGD("forget (i=%zu) %s, nlookup: %lld", i, GetAnonyString(node->path).c_str(), (long long)forgets[i].nlookup); + PutNode(data, node, forgets[i].nlookup); + } + fuse_reply_none(req); +} + +static void HasCache(fuse_req_t req, fuse_ino_t ino, const void *inBuf) +{ + struct FuseData *data = static_cast(fuse_req_userdata(req)); + shared_ptr cInode = GetCloudInode(data, ino); + if (!cInode || !cInode->readSession) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::IOCTL, + FaultType::INODE_FILE, ENOMEM, "failed to get cloud inode"}); + return; + } + + const struct HmdfsHasCache *ioctlData = reinterpret_cast(inBuf); + if (!ioctlData || ioctlData->offset < 0 || ioctlData->readSize < 0) { + fuse_reply_err(req, EINVAL); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::IOCTL, + FaultType::WARNING, EINVAL, "invalid argument in ioctl"}); + return; + } + int64_t headIndex = ioctlData->offset / MAX_READ_SIZE; + int64_t tailIndex = (ioctlData->offset + ioctlData->readSize - 1) / MAX_READ_SIZE; + if (cInode->IsReadFinished(headIndex) && cInode->IsReadFinished(tailIndex)) { + fuse_reply_ioctl(req, 0, NULL, 0); + } else { + fuse_reply_err(req, EIO); + } +} + +static bool CheckReadIsCanceled(pid_t pid, shared_ptr cInode) +{ + std::unique_lock lock(cInode->readArgsLock); + return cInode->readCtlMap[pid]; +} + +static void CancelRead(fuse_req_t req, fuse_ino_t ino) +{ + pid_t pid = GetPidFromTid(req->ctx.pid); + struct FuseData *data = static_cast(fuse_req_userdata(req)); + shared_ptr cInode = GetCloudInode(data, ino); + if (!cInode) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::INODE_FILE, ENOMEM, "failed to get cloud inode"}); + return; + } + LOGI("Cancel read for pid: %{public}d", pid); + { + std::unique_lock lock(cInode->readArgsLock); + cInode->readCtlMap[pid] = true; + for (const auto &it : cInode->readArgsSet) { + if (it->pid == pid) { + { + std::unique_lock lck(cInode->readLock); + *it->readStatus = READ_CANCELED; + } + it->cond->notify_one(); + } + } + } + std::unique_lock wSesLock(cInode->sessionLock, std::defer_lock); + wSesLock.lock(); + for (auto &it : cInode->readCacheMap) { + std::unique_lock lock(it.second->mutex); + if (!(it.second->flags & PG_UPTODATE)) { + it.second->cond.notify_all(); + } + } + wSesLock.unlock(); + + fuse_reply_ioctl(req, 0, NULL, 0); +} + +static void ResetRead(fuse_req_t req, fuse_ino_t ino) +{ + pid_t pid = GetPidFromTid(req->ctx.pid); + struct FuseData *data = static_cast(fuse_req_userdata(req)); + shared_ptr cInode = GetCloudInode(data, ino); + if (!cInode) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::INODE_FILE, ENOMEM, "failed to get cloud inode"}); + return; + } + LOGI("Reset read for pid: %{public}d", pid); + { + std::unique_lock lock(cInode->readArgsLock); + cInode->readCtlMap[pid] = false; + } + fuse_reply_ioctl(req, 0, NULL, 0); +} + +static void CloudIoctl(fuse_req_t req, fuse_ino_t ino, int cmd, void *arg, struct fuse_file_info *fi, + unsigned flags, const void *inBuf, size_t inBufsz, size_t outBufsz) +{ + switch (static_cast(cmd)) { + case HMDFS_IOC_HAS_CACHE: + HasCache(req, ino, inBuf); + break; + case HMDFS_IOC_CANCEL_READ: + CancelRead(req, ino); + break; + case HMDFS_IOC_RESET_READ: + ResetRead(req, ino); + break; + default: + fuse_reply_err(req, ENOTTY); + } +} + +static bool CheckAndWait(pid_t pid, shared_ptr cInode, off_t off) +{ + int64_t cacheIndex = off / MAX_READ_SIZE; + if (cInode->IsReadAhead(cacheIndex)) { + auto it = cInode->readCacheMap[cacheIndex]; + std::unique_lock lock(it->mutex); + auto waitStatus = it->cond.wait_for( + lock, READ_TIMEOUT_S, [&] { return (it->flags & PG_UPTODATE) || CheckReadIsCanceled(pid, cInode); }); + if (!waitStatus) { + LOGE("CheckAndWait timeout: %{public}ld", static_cast(cacheIndex)); + return false; + } + } + /* true when read finish and not canceled */ + return !CheckReadIsCanceled(pid, cInode); +} + +static void SaveCacheToFile(shared_ptr readArgs, + shared_ptr cInode, + int64_t cacheIndex, + int32_t userId) +{ + string cachePath = + LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + LOCAL_PATH_HMDFS_CLOUD_CACHE + CLOUD_CACHE_DIR + cInode->path; + char *realPaths = realpath(cachePath.c_str(), nullptr); + if (realPaths == nullptr) { + LOGE("realpath failed"); + return; + } + std::FILE *file = fopen(realPaths, "r+"); + free(realPaths); + if (file == nullptr) { + LOGE("Failed to open cache file, err: %{public}d", errno); + return; + } + int fd = fileno(file); + if (fd < 0) { + LOGE("Failed to get fd, err: %{public}d", errno); + return; + } + if (cInode->cacheFileIndex.get()[cacheIndex] == NOT_CACHE && + pwrite(fd, readArgs->buf.get(), *readArgs->readResult, readArgs->offset) == *readArgs->readResult) { + LOGI("Write to cache file, offset: %{public}ld*4M ", static_cast(cacheIndex)); + cInode->cacheFileIndex.get()[cacheIndex] = HAS_CACHED; + } + if (fclose(file)) { + LOGE("Failed to close cache file, err: %{public}d", errno); + } +} + +static void CloudReadOnCloudFile(pid_t pid, + int32_t userId, + shared_ptr readArgs, + shared_ptr cInode, + shared_ptr readSession) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + LOGI("PRead CloudFile, path: %{public}s, size: %{public}zd, off: %{public}lu", GetAnonyString(cInode->path).c_str(), + readArgs->size, static_cast(readArgs->offset)); + + uint64_t startTime = UTCTimeMilliSeconds(); + bool isReading = true; + int64_t cacheIndex = readArgs->offset / MAX_READ_SIZE; + std::unique_lock wSesLock(cInode->sessionLock, std::defer_lock); + + wSesLock.lock(); + if (readArgs->offset % MAX_READ_SIZE == 0 && cInode->readCacheMap.find(cacheIndex) == cInode->readCacheMap.end()) { + auto memInfo = std::make_shared(); + memInfo->flags = PG_READAHEAD; + cInode->readCacheMap[cacheIndex] = memInfo; + isReading = false; + LOGI("To do read cloudfile, offset: %{public}ld*4M", static_cast(cacheIndex)); + } + wSesLock.unlock(); + if (isReading && !CheckAndWait(pid, cInode, readArgs->offset)) { + return; + } + + *readArgs->readResult = + readSession->PRead(readArgs->offset, readArgs->size, readArgs->buf.get(), *readArgs->ckError); + + uint64_t endTime = UTCTimeMilliSeconds(); + uint64_t readTime = (endTime > startTime) ? (endTime - startTime) : 0; + CloudDaemonStatistic &readStat = CloudDaemonStatistic::GetInstance(); + readStat.UpdateReadSizeStat(readArgs->size); + readStat.UpdateReadTimeStat(readArgs->size, readTime); + + { + unique_lock lck(cInode->readLock); + *readArgs->readStatus = READ_FINISHED; + } + readArgs->cond->notify_one(); + if (readArgs->offset % MAX_READ_SIZE == 0) { + cInode->SetReadCacheFlag(cacheIndex, PG_UPTODATE); + wSesLock.lock(); + if (cInode->readCacheMap.find(cacheIndex) != cInode->readCacheMap.end()) { + cInode->readCacheMap[cacheIndex]->cond.notify_all(); + LOGI("Read cloudfile done and notify all waiting threads, offset: %{public}ld*4M", + static_cast(cacheIndex)); + } + if (IsVideoType(cInode->mBase->name) && *readArgs->readResult > 0) { + ffrt::submit( + [userId, readArgs, cInode, cacheIndex] { SaveCacheToFile(readArgs, cInode, cacheIndex, userId); }); + } + wSesLock.unlock(); + } + return; +} + +static void CloudReadOnCacheFile(shared_ptr readArgs, + shared_ptr cInode, + shared_ptr readSession, + int32_t userId) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (static_cast(readArgs->offset) >= cInode->mBase->size) { + return; + } + usleep(READ_CACHE_SLEEP); + uint64_t startTime = UTCTimeMilliSeconds(); + int64_t cacheIndex = readArgs->offset / MAX_READ_SIZE; + std::unique_lock wSesLock(cInode->sessionLock, std::defer_lock); + + wSesLock.lock(); + if (cInode->readCacheMap.find(cacheIndex) != cInode->readCacheMap.end()) { + wSesLock.unlock(); + return; + } + auto memInfo = std::make_shared(); + memInfo->flags = PG_READAHEAD; + cInode->readCacheMap[cacheIndex] = memInfo; + wSesLock.unlock(); + + readArgs->size = MAX_READ_SIZE; + readArgs->buf.reset(new char[MAX_READ_SIZE], [](char *ptr) { delete[] ptr; }); + LOGI("To do preread cloudfile path: %{public}s, size: %{public}zd, offset: %{public}ld*4M", + GetAnonyString(cInode->path).c_str(), readArgs->size, static_cast(cacheIndex)); + *readArgs->readResult = + readSession->PRead(readArgs->offset, readArgs->size, readArgs->buf.get(), *readArgs->ckError); + + uint64_t endTime = UTCTimeMilliSeconds(); + uint64_t readTime = (endTime > startTime) ? (endTime - startTime) : 0; + CloudDaemonStatistic &readStat = CloudDaemonStatistic::GetInstance(); + readStat.UpdateReadSizeStat(readArgs->size); + readStat.UpdateReadTimeStat(readArgs->size, readTime); + + cInode->SetReadCacheFlag(cacheIndex, PG_UPTODATE); + wSesLock.lock(); + if (cInode->readCacheMap.find(cacheIndex) != cInode->readCacheMap.end()) { + cInode->readCacheMap[cacheIndex]->cond.notify_all(); + LOGI("Preread cloudfile done and notify all waiting threads, offset: %{public}ld*4M", + static_cast(cacheIndex)); + } + if (IsVideoType(cInode->mBase->name) && *readArgs->readResult > 0) { + ffrt::submit([readArgs, cInode, cacheIndex, userId] { SaveCacheToFile(readArgs, cInode, cacheIndex, userId); }); + } + wSesLock.unlock(); + return; +} + +static void CloudReadOnLocalFile(fuse_req_t req, shared_ptr buf, size_t size, + off_t off, struct fuse_file_info *fi) +{ + auto fdsan = reinterpret_cast(fi->fh); + auto readSize = pread(fdsan->get(), buf.get(), size, off); + if (readSize < 0) { + fuse_reply_err(req, errno); + string msg = "Failed to read local file, errno: " + to_string(errno); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::FILE, errno, msg}); + return; + } + fuse_reply_buf(req, buf.get(), min(size, static_cast(readSize))); + return; +} + +static void InitReadSlice(size_t size, off_t off, ReadSlice &readSlice) +{ + readSlice.offHead = off; + readSlice.offTail = (off + static_cast(size)) / MAX_READ_SIZE * MAX_READ_SIZE; + if (readSlice.offTail > readSlice.offHead) { + readSlice.sizeHead = static_cast(readSlice.offTail - readSlice.offHead); + readSlice.sizeTail = MAX_READ_SIZE; + } else { + readSlice.sizeHead = static_cast(readSlice.offTail + MAX_READ_SIZE - readSlice.offHead); + } + if ((static_cast(size) + off) % MAX_READ_SIZE == 0) { + readSlice.offTail -= MAX_READ_SIZE; + readSlice.sizeTail = 0; + } +} + +static bool FixData(fuse_req_t req, shared_ptr buf, ReadSize sizes, + shared_ptr readArgs, string prepareTraceId) +{ + size_t size = sizes.size; + size_t sizeDone = sizes.sizeDone; + if (*readArgs->readResult < 0) { + fuse_reply_err(req, ENOMEM); + string msg = "Pread failed, readResult: " + to_string(*readArgs->readResult) + + " prepareTraceId: " + prepareTraceId; + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::WARNING, ENOMEM, msg}); + return false; + } + + auto ret = HandleCloudError(*readArgs->ckError, FaultOperation::READ, prepareTraceId); + if (ret < 0) { + fuse_reply_err(req, -ret); + return false; + } + + int32_t copyRet = memcpy_s(buf.get() + sizeDone, min(size - sizeDone, static_cast(*readArgs->readResult)), + readArgs->buf.get(), min(size - sizeDone, static_cast(*readArgs->readResult))); + if (copyRet != 0) { + fuse_reply_err(req, ENETUNREACH); + string msg = "Parcel data copy failed, err=" + to_string(copyRet); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::FILE, copyRet, msg}); + return false; + } + return true; +} + +static bool WaitData(fuse_req_t req, shared_ptr cInode, shared_ptr readArgs) +{ + std::unique_lock lock(cInode->readLock); + auto waitStatus = readArgs->cond->wait_for(lock, READ_TIMEOUT_S, [readArgs] { return *readArgs->readStatus; }); + if (*readArgs->readStatus == READ_CANCELED) { + LOGI("read is cancelled"); + fuse_reply_err(req, EIO); + return false; + } + if (!waitStatus) { + std::unique_lock wSesLock(cInode->sessionLock, std::defer_lock); + int64_t cacheIndex = readArgs->offset / MAX_READ_SIZE; + cInode->SetReadCacheFlag(cacheIndex, PG_UPTODATE); + wSesLock.lock(); + if (cInode->readCacheMap.find(cacheIndex) != cInode->readCacheMap.end()) { + cInode->readCacheMap[cacheIndex]->cond.notify_all(); + } + wSesLock.unlock(); + LOGE("Pread timeout, offset: %{public}ld*4M", static_cast(cacheIndex)); + fuse_reply_err(req, ENETUNREACH); + return false; + } + return true; +} + +static void WaitAndFixData(fuse_req_t req, + shared_ptr buf, + size_t size, + shared_ptr cInode, + vector> readArgsList) +{ + size_t sizeDone = 0; + string prepareTraceId; + if (cInode->readSession) { + prepareTraceId = cInode->readSession->GetPrepareTraceId(); + } + for (auto &it : readArgsList) { + if (!it) { + continue; + } + if (!WaitData(req, cInode, it)) { + return; + } + ReadSize sizes; + sizes.size = size; + sizes.sizeDone = sizeDone; + if (!FixData(req, buf, sizes, it, prepareTraceId)) { + return; + } + sizeDone += it->size; + } + fuse_reply_buf(req, buf.get(), min(size, sizeDone)); +} + +static ssize_t ReadCacheFile(shared_ptr readArgs, const string &path, int32_t userId) +{ + string cachePath = + LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + LOCAL_PATH_HMDFS_CLOUD_CACHE + CLOUD_CACHE_DIR + path; + char *realPaths = realpath(cachePath.c_str(), nullptr); + if (realPaths == nullptr) { + LOGE("realpath failed"); + return -1; + } + std::FILE *file = fopen(realPaths, "r"); + free(realPaths); + if (file == nullptr) { + LOGE("fopen faild, errno: %{public}d", errno); + return -1; + } + int fd = fileno(file); + if (fd < 0) { + LOGE("get fd faild, errno: %{public}d", errno); + return fd; + } + ssize_t bytesRead = pread(fd, readArgs->buf.get(), readArgs->size, readArgs->offset); + if (fclose(file)) { + LOGE("fclose failed, errno: %{public}d", errno); + } + return bytesRead; +} + +static bool DoReadSlice(fuse_req_t req, + shared_ptr cInode, + shared_ptr readSession, + shared_ptr readArgs, + bool needCheck) +{ + pid_t pid = GetPidFromTid(req->ctx.pid); + if (!readArgs) { + return true; + } + if (!readArgs->buf) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::FILE, ENOMEM, "buffer is null"}); + return false; + } + int64_t cacheIndex = readArgs->offset / MAX_READ_SIZE; + struct FuseData *data = static_cast(fuse_req_userdata(req)); + if (IsVideoType(cInode->mBase->name) && cInode->cacheFileIndex.get()[cacheIndex] == HAS_CACHED) { + LOGI("DoReadSlice from local: %{public}ld", static_cast(cacheIndex)); + *readArgs->readResult = ReadCacheFile(readArgs, cInode->path, data->userId); + if (*readArgs->readResult >= 0) { + unique_lock lock(cInode->readLock); + *readArgs->readStatus = READ_FINISHED; + return true; + } else { + LOGI("read cache file failed, errno: %{public}d", errno); + } + } + + LOGI("DoReadSlice from cloud: %{public}ld", static_cast(cacheIndex)); + if (needCheck && !CheckAndWait(pid, cInode, readArgs->offset)) { + fuse_reply_err(req, ENETUNREACH); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::CLOUD_READ_FILE_TIMEOUT, ENETUNREACH, "network timeout"}); + return false; + } + ffrt::submit([pid, readArgs, cInode, readSession, data] { + CloudReadOnCloudFile(pid, data->userId, readArgs, cInode, readSession); + }); + return true; +} + +static bool DoCloudRead(fuse_req_t req, int flags, DoCloudReadParams params) +{ + pid_t pid = GetPidFromTid(req->ctx.pid); + if (!DoReadSlice(req, params.cInode, params.readSession, params.readArgsHead, true)) { + return false; + } + if (!DoReadSlice(req, params.cInode, params.readSession, params.readArgsTail, false)) { + return false; + } + // no prefetch when contains O_NOFOLLOW + unsigned int unflags = static_cast(flags); + if (unflags & O_NOFOLLOW) { + return true; + } + + struct FuseData *data = static_cast(fuse_req_userdata(req)); + for (uint32_t i = 1; i <= CACHE_PAGE_NUM; i++) { + int64_t cacheIndex = static_cast( + (params.readArgsTail ? params.readArgsTail->offset : params.readArgsHead->offset) / MAX_READ_SIZE + i); + if (IsVideoType(params.cInode->mBase->name) && params.cInode->cacheFileIndex.get()[cacheIndex] == HAS_CACHED) { + continue; + } + auto readArgsCache = make_shared(0, cacheIndex * MAX_READ_SIZE, pid); + if (!readArgsCache) { + LOGE("Init readArgsCache failed"); + break; + } + ffrt::submit([readArgsCache, params, data] { + CloudReadOnCacheFile(readArgsCache, params.cInode, params.readSession, data->userId); + }); + } + return true; +} + +static bool CloudReadHelper(fuse_req_t req, size_t size, shared_ptr cInode) +{ + pid_t pid = GetPidFromTid(req->ctx.pid); + if (CheckReadIsCanceled(pid, cInode)) { + LOGI("read is cancelled"); + fuse_reply_err(req, EIO); + return false; + } + if (size > MAX_READ_SIZE) { + fuse_reply_err(req, EINVAL); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::WARNING, EINVAL, "input size exceeds MAX_READ_SIZE"}); + return false; + } + return true; +} + +static void CloudRead(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) +{ + pid_t pid = GetPidFromTid(req->ctx.pid); + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + shared_ptr buf = nullptr; + struct FuseData *data = static_cast(fuse_req_userdata(req)); + shared_ptr cInode = GetCloudInode(data, ino); + if (!cInode) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::INODE_FILE, ENOMEM, "failed to get cloud inode"}); + return; + } + LOGI("CloudRead: %{public}s, size=%{public}zd, off=%{public}lu", + GetAnonyString(CloudPath(data, ino)).c_str(), size, (unsigned long)off); + + if (!CloudReadHelper(req, size, cInode)) { + return; + } + auto dkReadSession = cInode->readSession; + if (!dkReadSession) { + fuse_reply_err(req, EPERM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::FILE, EPERM, "readSession is nullptr"}); + return; + } + buf.reset(new char[size], [](char *ptr) { delete[] ptr; }); + if (!buf) { + fuse_reply_err(req, ENOMEM); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{PHOTOS_BUNDLE_NAME, FaultOperation::READ, + FaultType::FILE, ENOMEM, "buffer is null"}); + return; + } + if (fi->fh != UINT64_MAX) { + CloudReadOnLocalFile(req, buf, size, off, fi); + return; + } + + ReadSlice readSlice; + /* slice read request into 4M pages */ + InitReadSlice(size, off, readSlice); + /* init readArgs for current page, and next page if cross pages */ + auto readArgsHead = make_shared(readSlice.sizeHead, readSlice.offHead, pid); + shared_ptr readArgsTail = nullptr; + if (readSlice.sizeTail > 0) { + readArgsTail = make_shared(readSlice.sizeTail, readSlice.offTail, pid); + } + if (!DoCloudRead(req, fi->flags, {cInode, dkReadSession, readArgsHead, readArgsTail})) { + return; + } + /* wait and reply current req data */ + InsertReadArgs(cInode, {readArgsHead, readArgsTail}); + WaitAndFixData(req, buf, size, cInode, {readArgsHead, readArgsTail}); + EraseReadArgs(cInode, {readArgsHead, readArgsTail}); +} + +static const struct fuse_lowlevel_ops cloudDiskFuseOps = { + .lookup = CloudDisk::FuseOperations::Lookup, + .forget = CloudDisk::FuseOperations::Forget, + .getattr = CloudDisk::FuseOperations::GetAttr, + .setattr = CloudDisk::FuseOperations::SetAttr, + .mknod = CloudDisk::FuseOperations::MkNod, + .mkdir = CloudDisk::FuseOperations::MkDir, + .unlink = CloudDisk::FuseOperations::Unlink, + .rmdir = CloudDisk::FuseOperations::RmDir, + .rename = CloudDisk::FuseOperations::Rename, + .open = CloudDisk::FuseOperations::Open, + .read = CloudDisk::FuseOperations::Read, + .release = CloudDisk::FuseOperations::Release, + .readdir = CloudDisk::FuseOperations::ReadDir, + .setxattr = CloudDisk::FuseOperations::SetXattr, + .getxattr = CloudDisk::FuseOperations::GetXattr, + .access = CloudDisk::FuseOperations::Access, + .create = CloudDisk::FuseOperations::Create, + .ioctl = CloudDisk::FuseOperations::Ioctl, + .write_buf = CloudDisk::FuseOperations::WriteBuf, + .forget_multi = CloudDisk::FuseOperations::ForgetMulti, + .lseek = CloudDisk::FuseOperations::Lseek, +}; + +static const struct fuse_lowlevel_ops cloudMediaFuseOps = { + .lookup = CloudLookup, + .forget = CloudForget, + .getattr = CloudGetAttr, + .open = CloudOpen, + .read = CloudRead, + .release = CloudRelease, + .readdir = CloudReadDir, + .ioctl = CloudIoctl, + .forget_multi = CloudForgetMulti, +}; + +static bool CheckPathForStartFuse(const string &path) +{ + char resolvedPath[PATH_MAX] = {'\0'}; + char* ret = realpath(path.c_str(), resolvedPath); + if (ret == nullptr) { + return false; + } + std::string realPath(resolvedPath); + std::string pathPrefix = "/mnt/data/"; + if (realPath.rfind(pathPrefix, 0) != 0) { + return false; + } + + size_t userIdBeginPos = pathPrefix.length(); + size_t userIdEndPos = realPath.find("/", userIdBeginPos); + const std::string userId = realPath.substr(userIdBeginPos, userIdEndPos - userIdBeginPos); + if (userId.find_first_not_of("0123456789") != std::string::npos) { + return false; + } + + size_t suffixBeginPos = userIdEndPos + 1; + const std::string pathSuffix1 = "cloud"; + const std::string pathSuffix2 = "cloud_fuse"; + if (realPath.rfind(pathSuffix1) == suffixBeginPos && + suffixBeginPos + pathSuffix1.length() == realPath.length()) { + return true; + } + if (realPath.rfind(pathSuffix2) == suffixBeginPos && + suffixBeginPos + pathSuffix2.length() == realPath.length()) { + return true; + } + return false; +} + +static int SetNewSessionInfo(struct fuse_session *se, struct fuse_loop_config &config, + int32_t devFd, const string &path, int32_t userId) +{ + se->fd = devFd; + se->bufsize = FUSE_BUFFER_SIZE; + se->mountpoint = strdup(path.c_str()); + if (se->mountpoint == nullptr) { + return -ENOMEM; + } + + fuse_daemonize(true); + int ret = fuse_session_loop_mt(se, &config); + + fuse_session_unmount(se); + LOGI("fuse_session_unmount"); + if (se->mountpoint) { + free(se->mountpoint); + se->mountpoint = nullptr; + } + + fuse_session_destroy(se); + // clear fd + MetaFileMgr::GetInstance().ClearAll(); + MetaFileMgr::GetInstance().CloudDiskClearAll(); + CloudDisk::DatabaseManager::GetInstance().ClearRdbStore(); + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance != nullptr) { + instance->Release(userId); + } else { + LOGE("get cloudfile helper instance failed"); + } + return ret; +} + +int32_t FuseManager::StartFuse(int32_t userId, int32_t devFd, const string &path) +{ + LOGI("FuseManager::StartFuse entry"); + struct fuse_loop_config config; + struct fuse_args args = FUSE_ARGS_INIT(0, nullptr); + struct CloudDisk::CloudDiskFuseData cloudDiskData; + struct FuseData data; + struct fuse_session *se = nullptr; + if (!CheckPathForStartFuse(path) || fuse_opt_add_arg(&args, path.c_str())) { + LOGE("Mount path invalid"); + return -EINVAL; + } + if (path.find("cloud_fuse") != string::npos) { + fuse_set_log_func([](enum fuse_log_level level, const char *fmt, va_list ap) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" + char *str = nullptr; + if (vasprintf(&str, fmt, ap) < 0) { + LOGE("FUSE: log failed"); + return ; + } + + LOGE("FUSE: %{public}s", str); + free(str); +#pragma clang diagnostic pop + }); + se = fuse_session_new(&args, &cloudDiskFuseOps, + sizeof(cloudDiskFuseOps), &cloudDiskData); + if (se == nullptr) { + LOGE("cloud disk fuse_session_new error"); + return -EINVAL; + } + cloudDiskData.userId = userId; + cloudDiskData.se = se; + config.max_idle_threads = 1; + std::lock_guard lock(sessionMutex_); + sessions_[path] = se; + } else { + se = fuse_session_new(&args, &cloudMediaFuseOps, sizeof(cloudMediaFuseOps), &data); + if (se == nullptr) { + LOGE("cloud media fuse_session_new error"); + return -EINVAL; + } + data.userId = userId; + data.se = se; + config.max_idle_threads = MAX_IDLE_THREADS; + } + LOGI("fuse_session_new success, userId: %{public}d", userId); + int ret = SetNewSessionInfo(se, config, devFd, path, userId); + return ret; +} + +struct fuse_session* FuseManager::GetSession(std::string path) +{ + std::lock_guard lock(sessionMutex_); + auto iterator = sessions_.find(path); + if (iterator != sessions_.end()) { + return iterator->second; + } else { + return nullptr; + } +} + +FuseManager &FuseManager::GetInstance() +{ + static FuseManager instance_; + return instance_; +} + +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp b/cloud_file/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp new file mode 100644 index 0000000..b9f1a21 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp @@ -0,0 +1,233 @@ +/* + * 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 "ipc/cloud_daemon.h" + +#include +#include +#include +#include +#include +#include + +#include "cloud_file_fault_event.h" +#include "dfs_error.h" +#include "fuse_manager/fuse_manager.h" +#include "iremote_object.h" +#include "parameters.h" +#include "plugin_loader.h" +#include "system_ability_definition.h" +#include "utils_directory.h" +#include "utils_log.h" +#ifdef HICOLLIE_ENABLE +#include "xcollie_helper.h" +#endif + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using namespace std; +using namespace CloudDisk; + +namespace { + static const string LOCAL_PATH_DATA_SERVICE_EL2 = "/data/service/el2/"; + static const string LOCAL_PATH_HMDFS_DENTRY_CACHE = "/hmdfs/cache/account_cache/dentry_cache/"; + static const string LOCAL_PATH_HMDFS_CACHE_CLOUD = "/hmdfs/cache/account_cache/dentry_cache/cloud"; + static const int32_t STAT_MODE_DIR = 0771; + static const int32_t STAT_MODE_DIR_DENTRY_CACHE = 02771; + static const int32_t OID_DFS = 1009; +} +REGISTER_SYSTEM_ABILITY_BY_ID(CloudDaemon, FILEMANAGEMENT_CLOUD_DAEMON_SERVICE_SA_ID, true); + +CloudDaemon::CloudDaemon(int32_t saID, bool runOnCreate) : SystemAbility(saID, runOnCreate) +{ + accountStatusListener_ = make_shared(); +} + +void CloudDaemon::PublishSA() +{ + LOGI("Begin to init"); + if (!registerToService_) { + bool ret = SystemAbility::Publish(this); + if (!ret) { + throw runtime_error("Failed to publish the daemon"); + } + registerToService_ = true; + } + LOGI("Init finished successfully"); +} + +static bool CheckDeviceInLinux() +{ + struct utsname uts; + if (uname(&uts) == -1) { + LOGE("uname get failed."); + return false; + } + if (strcmp(uts.sysname, "Linux") == 0) { + LOGI("uname system is linux."); + return true; + } + return false; +} + +static void ModSysParam() +{ + if (CheckDeviceInLinux()) { + const string photos = "persist.kernel.bundle_name.photos"; + const string clouddrive = "persist.kernel.bundle_name.clouddrive"; + system::SetParameter(photos, ""); + system::SetParameter(clouddrive, ""); + } +} + +void CloudDaemon::OnStart() +{ + LOGI("Begin to start service"); + if (state_ == ServiceRunningState::STATE_RUNNING) { + LOGI("Daemon has already started"); + return; + } + + try { + PublishSA(); + AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); + mode_t mode = 002; + umask(mode); + ModSysParam(); + } catch (const exception &e) { + LOGE("%{public}s", e.what()); + } + + state_ = ServiceRunningState::STATE_RUNNING; + /* load cloud file ext plugin */ + CloudFile::PluginLoader::GetInstance().LoadCloudKitPlugin(); + LOGI("Start service successfully"); +} + +void HandleStartMove(int32_t userId) +{ + const string moveFile = "persist.kernel.move.finish"; + system::SetParameter(moveFile, "false"); + const std::string filemanagerKey = "persist.kernel.bundle_name.filemanager"; + string subList[] = {"com.ohos.photos", system::GetParameter(filemanagerKey, "")}; + string srcBase = "/data/service/el1/public/cloudfile/" + to_string(userId); + string dstBase = "/data/service/el2/" + to_string(userId) + "/hmdfs/cloudfile_manager"; + string removePath = srcBase + "/" + subList[1] + "/backup"; + bool ret = Storage::DistributedFile::Utils::ForceRemoveDirectoryDeepFirst(removePath); + if (!ret) { + LOGE("remove failed path: %{public}s", GetAnonyString(removePath).c_str()); + } + const auto copyOptions = filesystem::copy_options::overwrite_existing | filesystem::copy_options::recursive; + for (auto sub : subList) { + string srcPath = srcBase + '/' + sub; + string dstPath = dstBase + '/' + sub; + if (access(srcPath.c_str(), F_OK) != 0) { + LOGI("srcPath %{public}s not found", GetAnonyString(srcPath).c_str()); + continue; + } + LOGI("Begin to move path: %{public}s", GetAnonyString(srcPath).c_str()); + error_code errCode; + filesystem::copy(srcPath, dstPath, copyOptions, errCode); + if (errCode.value() != 0) { + LOGE("copy failed path: %{public}s, errCode: %{public}d", + GetAnonyString(srcPath).c_str(), errCode.value()); + } + LOGI("End move path: %{public}s", GetAnonyString(srcPath).c_str()); + bool ret = Storage::DistributedFile::Utils::ForceRemoveDirectoryDeepFirst(srcPath); + if (!ret) { + LOGE("remove failed path: %{public}s", GetAnonyString(srcPath).c_str()); + } + } + system::SetParameter(moveFile, "true"); +} + +void CloudDaemon::OnStop() +{ + LOGI("Begin to stop"); + state_ = ServiceRunningState::STATE_NOT_START; + registerToService_ = false; + LOGI("Stop finished successfully"); +} + +void CloudDaemon::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) +{ + LOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId); + accountStatusListener_->Start(); +} + +void CloudDaemon::ExecuteStartFuse(int32_t userId, int32_t devFd, const std::string& path) +{ + std::thread([=]() { + int32_t ret = FuseManager::GetInstance().StartFuse(userId, devFd, path); + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::FILE, ret, "start fuse, ret = " + std::to_string(ret)}); + }).detach(); +} + +int32_t CloudDaemon::StartFuse(int32_t userId, int32_t devFd, const string &path) +{ +#ifdef HICOLLIE_ENABLE + const int32_t TIMEOUT_S = 2; + int32_t xcollieId = XCollieHelper::SetTimer("CloudFileDaemon_StartFuse", TIMEOUT_S, nullptr, nullptr, true); +#endif + LOGI("Start Fuse"); + ExecuteStartFuse(userId, devFd, path); + + string dentryPath = LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + LOCAL_PATH_HMDFS_CACHE_CLOUD; + if (access(dentryPath.c_str(), F_OK) != 0) { + string cachePath = LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + LOCAL_PATH_HMDFS_DENTRY_CACHE; + if (mkdir(cachePath.c_str(), STAT_MODE_DIR) != 0 && errno != EEXIST) { +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::FILE, errno, "create accout_cache path error " + std::to_string(errno)}); + return E_PATH; + } + if (chmod(cachePath.c_str(), STAT_MODE_DIR_DENTRY_CACHE) != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::FILE, errno, "chmod cachepath error " + std::to_string(errno)}); + } + if (chown(cachePath.c_str(), OID_DFS, OID_DFS) != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::FILE, errno, "chown cachepath error " + std::to_string(errno)}); + } + if (mkdir(dentryPath.c_str(), STAT_MODE_DIR) != 0 && errno != EEXIST) { +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::FILE, errno, "create dentrypath " + std::to_string(errno)}); + return E_PATH; + } + if (chown(dentryPath.c_str(), OID_DFS, OID_DFS) != 0) { + CLOUD_FILE_FAULT_REPORT(CloudFileFaultInfo{"", CloudFile::FaultOperation::SESSION, + CloudFile::FaultType::FILE, errno, "chown cachepath error " + std::to_string(errno)}); + } + } + if (path.find("cloud_fuse") != string::npos) { + std::thread([userId]() { + HandleStartMove(userId); + }).detach(); + } +#ifdef HICOLLIE_ENABLE + XCollieHelper::CancelTimer(xcollieId); +#endif + return E_OK; +} +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp b/cloud_file/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp new file mode 100644 index 0000000..f2a0ab0 --- /dev/null +++ b/cloud_file/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp @@ -0,0 +1,63 @@ +/* + * 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 "ipc/cloud_daemon_stub.h" + +#include "cloud_file_daemon_interface_code.h" +#include "dfs_error.h" +#include "dfsu_memory_guard.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +CloudDaemonStub::CloudDaemonStub() +{ + opToInterfaceMap_[static_cast(CloudFileDaemonInterfaceCode::CLOUD_DAEMON_CMD_START_FUSE)] = + [this](MessageParcel &data, MessageParcel &reply) { + return this->HandleStartFuseInner(data, reply); + }; +} + +int32_t CloudDaemonStub::OnRemoteRequest(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + CloudSync::DfsuMemoryGuard cacheGuard; + if (data.ReadInterfaceToken() != GetDescriptor()) { + return CLOUD_DAEMON_DESCRIPTOR_IS_EMPTY; + } + auto interfaceIndex = opToInterfaceMap_.find(code); + if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { + LOGE("Cannot response request %d: unknown tranction", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + auto memberFunc = interfaceIndex->second; + return memberFunc(data, reply); +} + +int32_t CloudDaemonStub::HandleStartFuseInner(MessageParcel &data, MessageParcel &reply) +{ + LOGI("Begin StartFuseInner"); + auto userId = data.ReadInt32(); + auto fd = data.ReadFileDescriptor(); + auto path = data.ReadString(); + int32_t res = StartFuse(userId, int32_t(fd), path); + reply.WriteInt32(res); + LOGI("End StartFuseInner"); + return E_OK; +} +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/services/cloudfileservice.cfg b/cloud_file/services/cloudfileservice.cfg new file mode 100644 index 0000000..7f35daa --- /dev/null +++ b/cloud_file/services/cloudfileservice.cfg @@ -0,0 +1,38 @@ +{ + "jobs": [{ + "name" : "services:cloudfileservice", + "cmds" : [ + "mkdir /data/service/el1/public/cloudfile 0711 dfs dfs", + "restorecon /data/service/el1/public/cloudfile" + ] + }], + "services": [{ + "name": "cloudfileservice", + "path": ["/system/bin/sa_main", "/system/profile/cloudfileservice.json"], + "uid": "dfs", + "gid": ["dfs", "user_data_rw", "system", "ddms", "netsys_socket", "dfs_share"], + "sandbox": 0, + "jobs" : { + "on-start" : "services:cloudfileservice" + }, + "secon": "u:r:cloudfiledaemon:s0", + "apl": "system_basic", + "ondemand": true, + "permission" : [ + "ohos.permission.CLOUDFILE_SYNC", + "ohos.permission.DISTRIBUTED_DATASYNC", + "ohos.permission.MANAGE_LOCAL_ACCOUNTS", + "ohos.permission.ACCESS_SERVICE_DM", + "ohos.permission.GET_NETWORK_INFO", + "ohos.permission.INTERNET", + "ohos.permission.USE_CLOUD_DRIVE_SERVICE", + "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS", + "ohos.permission.USE_CLOUD_DRIVE_SERVICE", + "ohos.permission.READ_CLOUD_SYNC_CONFIG", + "ohos.permission.MANAGE_SETTINGS", + "ohos.permission.GET_BUNDLE_INFO", + "ohos.permission.GET_RUNNING_INFO", + "ohos.permission.RUNNING_STATE_OBSERVER" + ] + }] +} \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice.para b/cloud_file/services/cloudsyncservice.para new file mode 100644 index 0000000..1b99228 --- /dev/null +++ b/cloud_file/services/cloudsyncservice.para @@ -0,0 +1,22 @@ +# Copyright (c) 2024 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. + +persist.kernel.cloudsync.network_unavailable = false +persist.kernel.cloudsync.battery_level_low = false +persist.kernel.cloudsync.status = 0 +persist.kernel.cloudsync.temperature_abnormal_sync = false +persist.kernel.cloudsync.temperature_abnormal_thumb = false +persist.kernel.medialibrarydata.stopflag = 0 +persist.kernel.move.finish = false +persist.kernel.cloudsync.screen_off_enable_download = true +persist.kernel.clouddisk_version = 5.1.0.300 diff --git a/cloud_file/services/cloudsyncservice.para.dac b/cloud_file/services/cloudsyncservice.para.dac new file mode 100644 index 0000000..a02e9f5 --- /dev/null +++ b/cloud_file/services/cloudsyncservice.para.dac @@ -0,0 +1,22 @@ +# Copyright (c) 2024 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. + +persist.kernel.cloudsync.network_unavailable = dfs:samgr:0640 +persist.kernel.cloudsync.battery_level_low = dfs:samgr:0640 +persist.kernel.cloudsync.status = dfs:user_data_rw:0640 +persist.kernel.cloudsync.temperature_abnormal_sync = dfs:user_data_rw:0640 +persist.kernel.cloudsync.temperature_abnormal_thumb = dfs:user_data_rw:0640 +persist.kernel.medialibrarydata.stopflag = dfs:user_data_rw:0640 +persist.kernel.move.finish = dfs:user_data_rw:0640 +persist.kernel.cloudsync.screen_off_enable_download = dfs:samgr:0640 +persist.kernel.clouddisk_version = dfs:user_data_rw:0644 diff --git a/cloud_file/services/cloudsyncservice/BUILD.gn b/cloud_file/services/cloudsyncservice/BUILD.gn new file mode 100644 index 0000000..b3da909 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/BUILD.gn @@ -0,0 +1,336 @@ +# Copyright (C) 2024 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. + +import("//build/config/components/idl_tool/idl.gni") +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +config("cloud_sync_service_public_config") { + include_dirs = [ "${target_gen_dir}" ] +} + +idl_gen_interface("cloud_sync_service_interface") { + sources = [ "ICloudSyncService.idl" ] +} + +ohos_source_set("cloud_sync_service_proxy") { + configs = [ ":optimize-size" ] + public_configs = [ ":cloud_sync_service_public_config" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${innerkits_native_path}/cloudsync_kit_inner", + ] + + output_values = get_target_outputs(":cloud_sync_service_interface") + sources = filter_include(output_values, [ "*_proxy.cpp" ]) + sources += [ "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp" ] + + deps = [ ":cloud_sync_service_interface" ] + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_source_set("cloud_sync_service_stub") { + configs = [ ":optimize-size" ] + public_configs = [ ":cloud_sync_service_public_config" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${innerkits_native_path}/cloudsync_kit_inner", + ] + + output_values = get_target_outputs(":cloud_sync_service_interface") + sources = filter_include(output_values, [ "*_stub.cpp" ]) + sources += [ "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp" ] + + deps = [ ":cloud_sync_service_interface" ] + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_shared_library("cloudsync_sa") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + public_configs = [ ":cloud_sync_service_public_config" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + include_dirs = [ + "include", + "include/cycle_task", + "include/cycle_task/tasks", + "include/transport", + "include/transport/softbus", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${innerkits_native_path}/cloudsync_kit_inner", + ] + + cycle_task = [ + "src/cycle_task/cycle_task.cpp", + "src/cycle_task/cycle_task_runner.cpp", + "src/cycle_task/tasks/optimize_cache_task.cpp", + "src/cycle_task/tasks/optimize_storage_task.cpp", + "src/cycle_task/tasks/periodic_check_task.cpp", + "src/cycle_task/tasks/report_statistics_task.cpp", + "src/cycle_task/tasks/save_subscription_task.cpp", + "src/cycle_task/tasks/database_backup_task.cpp", + ] + + transport = [ + "src/transport/file_transfer_manager.cpp", + "src/transport/message_handler.cpp", + "src/transport/softbus/session_manager.cpp", + "src/transport/softbus/softbus_adapter.cpp", + "src/transport/softbus/softbus_session.cpp", + ] + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp", + "src/ipc/cloud_sync_service.cpp", + "src/ipc/download_asset_callback_manager.cpp", + "src/ipc/download_asset_callback_proxy.cpp", + "src/sync_rule/battery_status_listener.cpp", + "src/sync_rule/package_status_listener.cpp", + "src/sync_rule/screen_status_listener.cpp", + "src/sync_rule/user_status_listener.cpp", + ] + + sources += cycle_task + sources += transport + + output_values = get_target_outputs(":cloud_sync_service_interface") + sources += filter_include(output_values, [ "*_stub.cpp" ]) + + defines = [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + + deps = [ + ":cloud_sync_service_interface", + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "preferences:native_preferences", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + } + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_static_library("cloudsync_sa_static") { + branch_protector_ret = "pac_ret" + public_configs = [ ":cloud_sync_service_public_config" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + include_dirs = [ + "include", + "include/cycle_task", + "include/cycle_task/tasks", + "include/transport", + "include/transport/softbus", + "${clouddisk_database_path}/include", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + ] + + cycle_task = [ + "src/cycle_task/cycle_task.cpp", + "src/cycle_task/cycle_task_runner.cpp", + "src/cycle_task/tasks/optimize_cache_task.cpp", + "src/cycle_task/tasks/optimize_storage_task.cpp", + "src/cycle_task/tasks/periodic_check_task.cpp", + "src/cycle_task/tasks/report_statistics_task.cpp", + "src/cycle_task/tasks/save_subscription_task.cpp", + "src/cycle_task/tasks/database_backup_task.cpp", + ] + + transport = [ + "src/transport/file_transfer_manager.cpp", + "src/transport/message_handler.cpp", + "src/transport/softbus/session_manager.cpp", + "src/transport/softbus/softbus_adapter.cpp", + "src/transport/softbus/softbus_session.cpp", + ] + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp", + "src/ipc/cloud_sync_service.cpp", + "src/ipc/download_asset_callback_manager.cpp", + "src/ipc/download_asset_callback_proxy.cpp", + "src/sync_rule/battery_status_listener.cpp", + "src/sync_rule/package_status_listener.cpp", + "src/sync_rule/screen_status_listener.cpp", + "src/sync_rule/user_status_listener.cpp", + ] + + sources += cycle_task + sources += transport + + output_values = get_target_outputs(":cloud_sync_service_interface") + sources += filter_include(output_values, [ "*_stub.cpp" ]) + + defines = [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + + deps = [ + ":cloud_sync_service_interface", + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "e2fsprogs:libext2_uuid", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "power_manager:powermgr_client", + "preferences:native_preferences", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + defines += [ "SUPPORT_MEDIA_LIBRARY" ] + } + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + deps += + [ "${cloud_file_path}/adapter/cloud_adapter_example:cloud_adapter" ] + + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + + if (cloudsync_service_power) { + external_deps += [ "battery_manager:batterysrv_client" ] + + defines += [ "SUPPORT_POWER" ] + } + + if (is_emulator) { + defines += [ "EMULATOR" ] + } + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} diff --git a/cloud_file/services/cloudsyncservice/ICloudSyncService.idl b/cloud_file/services/cloudsyncservice/ICloudSyncService.idl new file mode 100644 index 0000000..a72b363 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/ICloudSyncService.idl @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2025 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. + */ + +sequenceable OHOS.IRemoteObject; +sequenceable cloud_sync_common..OHOS.FileManagement.CloudSync.AssetInfoObj; +sequenceable cloud_sync_common..OHOS.FileManagement.CloudSync.CleanFileInfoObj; +sequenceable cloud_sync_common..OHOS.FileManagement.CloudSync.CleanOptions; +sequenceable cloud_sync_common..OHOS.FileManagement.CloudSync.DentryFileInfoObj; +sequenceable cloud_sync_common..OHOS.FileManagement.CloudSync.OptimizeSpaceOptions; +sequenceable cloud_sync_common..OHOS.FileManagement.CloudSync.SwitchDataObj; + +interface OHOS.FileManagement.CloudSync.ICloudSyncService +{ + void UnRegisterCallbackInner([in] String bundleName); + void UnRegisterFileSyncCallbackInner([in] String bundleName); + void RegisterCallbackInner([in] IRemoteObject remoteObject, [in] String bundleName); + void RegisterFileSyncCallbackInner([in] IRemoteObject remoteObject, [in] String bundleName); + void StartSyncInner([in] boolean forceFlag, [in] String bundleName); + void StartFileSyncInner([in] boolean forceFlag, [in] String bundleName); + void TriggerSyncInner([in] String bundleName, [in] int userId); + void StopSyncInner([in] String bundleName, [in] boolean forceFlag); + void StopFileSyncInner([in] String bundleName, [in] boolean forceFlag); + void ResetCursor([in] String bundleName); + void ChangeAppSwitch([in] String accoutId, [in] String bundleName, [in] boolean status); + void OptimizeStorage([in] OptimizeSpaceOptions optimizeOptions, [in] boolean isCallbackValid, + [in] IRemoteObject optimizeCallback); + void StopOptimizeStorage(); + void Clean([in] String accountId, [in] CleanOptions cleanOptions); + void NotifyDataChange([in] String accoutId, [in] String bundleName); + void NotifyEventChange([in] int userId, [in] String eventId, [in] String extraData); + void EnableCloud([in] String accoutId, [in] SwitchDataObj switchData); + void DisableCloud([in] String accoutId); + void StartDownloadFile([in] String path); + void StartFileCache([in] String[] pathVec, [out] long downloadId, [in] int fieldkey, [in] boolean isCallbackValid, + [in] IRemoteObject downloadCallback, [in] int timeout); + void StopDownloadFile([in] String path, [in] boolean needClean); + void StopFileCache([in] long downloadId, [in] boolean needClean, [in] int timeout); + void DownloadThumb(); + void RegisterDownloadFileCallback([in] IRemoteObject downloadCallback); + void RegisterFileCacheCallback([in] IRemoteObject downloadCallback); + void UnregisterDownloadFileCallback(); + void UnregisterFileCacheCallback(); + void UploadAsset([in] int userId, [in] String request, [out] String resultStr); + void DownloadFile([in] int userId, [in] String bundleName, [in] AssetInfoObj assetInfoObj); + void DownloadFiles([in] int userId, [in] String bundleName, [in] AssetInfoObj[] assetInfoObj, + [out] boolean[] assetResultMap); + void DownloadAsset([in] unsigned long taskId, [in] int userId, [in] String bundleName, [in] String networkId, + [in] AssetInfoObj assetInfoObj); + void RegisterDownloadAssetCallback([in] IRemoteObject remoteObject); + void DeleteAsset([in] int userId, [in] String uri); + void GetSyncTimeInner([out] long syncTime, [in] String bundleName); + void CleanCacheInner([in] String uri); + void BatchCleanFile([in] CleanFileInfoObj[] fileInfo, [out] String[] failCloudId); + void BatchDentryFileInsert([in] DentryFileInfoObj[] fileInfo, [out] String[] failCloudId); +} \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/cycle_task/cycle_task.h b/cloud_file/services/cloudsyncservice/include/cycle_task/cycle_task.h new file mode 100644 index 0000000..e587395 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/cycle_task/cycle_task.h @@ -0,0 +1,67 @@ +/* + * 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 OHOS_CLOUD_SYNC_SERVICE_CYCLE_TASK_H +#define OHOS_CLOUD_SYNC_SERVICE_CYCLE_TASK_H +#include +#include +#include +#include + +#include "cloud_pref_impl.h" +#include "dfs_error.h" +#include "data_sync_manager.h" +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +class CycleTask { +public: + enum IntervalTime { + ONE_DAY = 24 * 60 * 60, + TWO_DAY = ONE_DAY * 2, + THREE_DAY = ONE_DAY * 3, + ONE_WEEK = ONE_DAY * 7, + }; + CycleTask(std::string taskName, + std::set bundleNames, + int32_t intervalTime, + std::shared_ptr dataSyncManager); + virtual ~CycleTask() = default; + std::string GetTaskName() const; + void RunTask(int32_t userId); + void SetRunnableBundleNames(std::shared_ptr> &bundleNames); + std::shared_ptr GetDataSyncManager() const; + static const std::string FILE_PATH; + +protected: + int32_t userId_; + std::string taskName_; + std::set bundleNames_; + int32_t intervalTime_; + std::shared_ptr dataSyncManager_; + +private: + void GetLastRunTime(std::time_t &time); + void SetLastRunTime(std::time_t time); + bool IsEligibleToRun(std::time_t currentTime, std::string bundleName); + virtual int32_t RunTaskForBundle(int32_t userId, std::string bundleName) = 0; + + std::unique_ptr cloudPrefImpl_; + std::shared_ptr> runnableBundleNames_; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_SERVICE_CYCLE_TASK_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/cycle_task/cycle_task_runner.h b/cloud_file/services/cloudsyncservice/include/cycle_task/cycle_task_runner.h new file mode 100644 index 0000000..a985398 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/cycle_task/cycle_task_runner.h @@ -0,0 +1,49 @@ +/* + * 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 OHOS_CLOUD_SYNC_SERVICE_CYCLE_TASK_RUNNER_H +#define OHOS_CLOUD_SYNC_SERVICE_CYCLE_TASK_RUNNER_H + +#include +#include +#include +#include "cloud_pref_impl.h" +#include "cycle_task.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +class CycleTaskRunner { +public: + static const std::string FILE_PATH; + static const int32_t DEFAULT_VALUE; + static const int32_t DEFAULT_USER_ID; + CycleTaskRunner(std::shared_ptr dataSyncManager); + void StartTask(); + +private: + void InitTasks(); + void SetRunableBundleNames(); + + int32_t userId_{0}; + std::time_t setUpTime_{0}; + std::shared_ptr dataSyncManager_; + std::vector> cycleTasks_ {}; +}; + +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_SERVICE_CYCLE_TASK_RUNNER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/database_backup_task.h b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/database_backup_task.h new file mode 100644 index 0000000..49e031d --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/database_backup_task.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_SYNC_SERVICE_DATABASE_BACKUP_TASK_H +#define OHOS_CLOUD_SYNC_SERVICE_DATABASE_BACKUP_TASK_H +#include "cloud_pref_impl.h" +#include "cycle_task.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { + +class DatabaseBackupTask : public CycleTask { +public: + DatabaseBackupTask(std::shared_ptr dataSyncManager); + int32_t RunTaskForBundle(int32_t userId, std::string bundleName) override; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_SERVICE_DATABASE_BACKUP_TASK_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/optimize_cache_task.h b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/optimize_cache_task.h new file mode 100644 index 0000000..e6d3004 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/optimize_cache_task.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 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 OHOS_CLOUD_SYNC_SERVICE_OPTIMIZE_CACHE_TASK_H +#define OHOS_CLOUD_SYNC_SERVICE_OPTIMIZE_CACHE_TASK_H +#include "cloud_pref_impl.h" +#include "cycle_task.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { + +class OptimizeCacheTask : public CycleTask { +public: + OptimizeCacheTask(std::shared_ptr dataSyncManager); + int32_t RunTaskForBundle(int32_t userId, std::string bundleName) override; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_SERVICE_OPTIMIZE_CACHE_TASK_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/optimize_storage_task.h b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/optimize_storage_task.h new file mode 100644 index 0000000..de87f6e --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/optimize_storage_task.h @@ -0,0 +1,33 @@ +/* + * 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 OHOS_CLOUD_SYNC_SERVICE_OPTIMIZE_STORAGE_TASK_H +#define OHOS_CLOUD_SYNC_SERVICE_OPTIMIZE_STORAGE_TASK_H +#include "cloud_pref_impl.h" +#include "cycle_task.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { + +class OptimizeStorageTask : public CycleTask { +public: + OptimizeStorageTask(std::shared_ptr dataSyncManager); + int32_t RunTaskForBundle(int32_t userId, std::string bundleName) override; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_SERVICE_OPTIMIZE_STORAGE_TASK_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/periodic_check_task.h b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/periodic_check_task.h new file mode 100644 index 0000000..69ade1c --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/periodic_check_task.h @@ -0,0 +1,35 @@ +/* + * 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 OHOS_CLOUD_SYNC_SERVICE_FULL_AUDIT_TASK_H +#define OHOS_CLOUD_SYNC_SERVICE_FULL_AUDIT_TASK_H +#include "cloud_pref_impl.h" +#include "cycle_task.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { + +const std::string PeriodicCheckTaskName = "periodic_check_task"; + +class PeriodicCheckTask : public CycleTask { +public: + PeriodicCheckTask(std::shared_ptr dataSyncManager); + int32_t RunTaskForBundle(int32_t userId, std::string bundleName) override; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_SERVICE_FULL_AUDIT_TASK_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/report_statistics_task.h b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/report_statistics_task.h new file mode 100644 index 0000000..1460418 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/report_statistics_task.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_SYNC_SERVICE_REPORT_STATISTICS_TASK_H +#define OHOS_CLOUD_SYNC_SERVICE_REPORT_STATISTICS_TASK_H +#include "cloud_pref_impl.h" +#include "cycle_task.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { + +class ReportStatisticsTask : public CycleTask { +public: + ReportStatisticsTask(std::shared_ptr dataSyncManager); + int32_t RunTaskForBundle(int32_t userId, std::string bundleName) override; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_SERVICE_SERVICE_REPORT_STATISTICS_TASK_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/save_subscription_task.h b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/save_subscription_task.h new file mode 100644 index 0000000..b05fdec --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/cycle_task/tasks/save_subscription_task.h @@ -0,0 +1,32 @@ +/* + * 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 OHOS_CLOUD_SYNC_SERVICE_SAVE_SUBSCRIPTION_TASK_H +#define OHOS_CLOUD_SYNC_SERVICE_SAVE_SUBSCRIPTION_TASK_H +#include "cloud_pref_impl.h" +#include "cycle_task.h" +namespace OHOS { +namespace FileManagement { +namespace CloudSync { + +class SaveSubscriptionTask : public CycleTask { +public: + SaveSubscriptionTask(std::shared_ptr dataSyncManager); + int32_t RunTaskForBundle(int32_t userId, std::string bundleName) override; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_CLOUD_SYNC_SERVICE_SAVE_SUBSCRIPTION_TASK_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/ipc/cloud_sync_service.h b/cloud_file/services/cloudsyncservice/include/ipc/cloud_sync_service.h new file mode 100644 index 0000000..b272720 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/ipc/cloud_sync_service.h @@ -0,0 +1,139 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_SYNC_SERVICE_H +#define OHOS_FILEMGMT_CLOUD_SYNC_SERVICE_H + +#include + +#include "iservice_registry.h" +#include "nocopyable.h" +#include "system_ability.h" +#include "system_ability_load_callback_stub.h" + +#include "cloud_sync_service_stub.h" +#include "file_transfer_manager.h" +#include "i_cloud_download_callback.h" +#include "i_cloud_sync_callback.h" +#include "svc_death_recipient.h" +#include "sync_rule/battery_status_listener.h" +#include "sync_rule/package_status_listener.h" +#include "sync_rule/screen_status_listener.h" +#include "sync_rule/user_status_listener.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncService final : public SystemAbility, public CloudSyncServiceStub, protected NoCopyable { + DECLARE_SYSTEM_ABILITY(CloudSyncService); + +public: + explicit CloudSyncService(int32_t saID, bool runOnCreate = true); + virtual ~CloudSyncService() = default; + ErrCode UnRegisterCallbackInner(const std::string &bundleName = "") override; + ErrCode UnRegisterFileSyncCallbackInner(const std::string &bundleName = "") override; + ErrCode RegisterCallbackInner(const sptr &remoteObject, const std::string &bundleName = "") override; + ErrCode RegisterFileSyncCallbackInner(const sptr &remoteObject, + const std::string &bundleName = "") override; + ErrCode StartSyncInner(bool forceFlag, const std::string &bundleName = "") override; + ErrCode StartFileSyncInner(bool forceFlag, const std::string &bundleName = "") override; + ErrCode TriggerSyncInner(const std::string &bundleName, int32_t userId) override; + ErrCode StopSyncInner(const std::string &bundleName = "", bool forceFlag = false) override; + ErrCode StopFileSyncInner(const std::string &bundleName = "", bool forceFlag = false) override; + ErrCode ResetCursor(const std::string &bundleName = "") override; + ErrCode OptimizeStorage(const OptimizeSpaceOptions &optimizeOptions, + bool isCallbackValid, + const sptr &optimizeCallback) override; + ErrCode StopOptimizeStorage() override; + ErrCode ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) override; + ErrCode Clean(const std::string &accountId, const CleanOptions &cleanOptions) override; + ErrCode NotifyDataChange(const std::string &accoutId, const std::string &bundleName) override; + ErrCode NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) override; + ErrCode EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) override; + ErrCode DisableCloud(const std::string &accoutId) override; + ErrCode StartDownloadFile(const std::string &path) override; + ErrCode StartFileCache(const std::vector &uriVec, + int64_t &downloadId, + int32_t fieldkey, + bool isCallbackValid, + const sptr &downloadCallback, + int32_t timeout = -1) override; + ErrCode StopDownloadFile(const std::string &path, bool needClean = false) override; + ErrCode StopFileCache(int64_t downloadId, bool needClean = false, int32_t timeout = -1) override; + ErrCode DownloadThumb() override; + ErrCode RegisterDownloadFileCallback(const sptr &downloadCallback) override; + ErrCode RegisterFileCacheCallback(const sptr &downloadCallback) override; + ErrCode UnregisterDownloadFileCallback() override; + ErrCode UnregisterFileCacheCallback() override; + ErrCode UploadAsset(const int32_t userId, const std::string &request, std::string &result) override; + ErrCode DownloadFile(const int32_t userId, const std::string &bundleName, + const AssetInfoObj &assetInfoObj) override; + ErrCode DownloadFiles(const int32_t userId, + const std::string &bundleName, + const std::vector &assetInfoObj, + std::vector &assetResultMap) override; + ErrCode DownloadAsset(const uint64_t taskId, + const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + const AssetInfoObj &assetInfoObj) override; + ErrCode RegisterDownloadAssetCallback(const sptr &remoteObject) override; + ErrCode DeleteAsset(const int32_t userId, const std::string &uri) override; + ErrCode GetSyncTimeInner(int64_t &syncTime, const std::string &bundleName = "") override; + ErrCode CleanCacheInner(const std::string &uri) override; + void SetDeathRecipient(const sptr &remoteObject); + ErrCode BatchCleanFile(const std::vector &fileInfo, + std::vector &failCloudId) override; + ErrCode BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId) override; + +private: + std::string GetHmdfsPath(const std::string &uri, int32_t userId); + void OnStart(const SystemAbilityOnDemandReason &startReason) override; + void OnActive(const SystemAbilityOnDemandReason &startReason) override; + void OnStop() override; + void PublishSA(); + void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; + void PreInit(); + void Init(); + void HandleStartReason(const SystemAbilityOnDemandReason &startReason); + void HandlePackageRemoved(const SystemAbilityOnDemandReason &startReason); + int32_t GetBundleNameUserInfo(BundleNameUserInfo &bundleNameUserInfo); + void GetBundleNameUserInfo(const std::vector &uriVec, BundleNameUserInfo &bundleNameUserInfo); + void CovertBundleName(std::string &bundleName); + + class LoadRemoteSACallback : public SystemAbilityLoadCallbackStub { + public: + void OnLoadSACompleteForRemote(const std::string &deviceId, + int32_t systemAbilityId, + const sptr &remoteObject); + std::condition_variable proxyConVar_; + std::atomic isLoadSuccess_{false}; + }; + + int32_t LoadRemoteSA(const std::string &deviceId); + + static inline std::mutex loadRemoteSAMutex_; + + std::shared_ptr dataSyncManager_; + std::shared_ptr userStatusListener_; + std::shared_ptr batteryStatusListener_; + std::shared_ptr packageStatusListener_; + std::shared_ptr screenStatusListener_; + std::shared_ptr fileTransferManager_; + sptr deathRecipient_; + static inline std::map> remoteObjectMap_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_SERVICE_H diff --git a/cloud_file/services/cloudsyncservice/include/ipc/download_asset_callback_manager.h b/cloud_file/services/cloudsyncservice/include/ipc/download_asset_callback_manager.h new file mode 100644 index 0000000..a15ec54 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/ipc/download_asset_callback_manager.h @@ -0,0 +1,38 @@ +/* + * 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 OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_MANAGER_H +#define OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_MANAGER_H + +#include "nocopyable.h" + +#include "i_download_asset_callback.h" +#include "svc_death_recipient.h" + +namespace OHOS::FileManagement::CloudSync { +class DownloadAssetCallbackManager final : public NoCopyable { +public: + using TaskId = uint64_t; + static DownloadAssetCallbackManager &GetInstance(); + void AddCallback(const sptr &callback); + void OnDownloadFinshed(const TaskId taskId, const std::string &uri, const int32_t result); + +private: + sptr callbackProxy_; + sptr deathRecipient_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_MANAGER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/ipc/download_asset_callback_proxy.h b/cloud_file/services/cloudsyncservice/include/ipc/download_asset_callback_proxy.h new file mode 100644 index 0000000..58832d0 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/ipc/download_asset_callback_proxy.h @@ -0,0 +1,36 @@ +/* + * 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 OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_PROXY_H +#define OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_PROXY_H + +#include "iremote_proxy.h" + +#include "i_download_asset_callback.h" + +namespace OHOS::FileManagement::CloudSync { +class DownloadAssetCallbackProxy : public IRemoteProxy { +public: + explicit DownloadAssetCallbackProxy(const sptr &impl) : IRemoteProxy(impl) {} + ~DownloadAssetCallbackProxy() override {} + + void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DOWNLOAD_ASSET_CALLBACK_PROXY_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/sync_rule/battery_status_listener.h b/cloud_file/services/cloudsyncservice/include/sync_rule/battery_status_listener.h new file mode 100644 index 0000000..21feee8 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/sync_rule/battery_status_listener.h @@ -0,0 +1,51 @@ +/* + * 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 OHOS_FILEMGMT_BATTERY_STATUS_LISTENER_H +#define OHOS_FILEMGMT_BATTERY_STATUS_LISTENER_H + +#include "common_event_subscriber.h" +#include "data_sync_manager.h" + +namespace OHOS::FileManagement::CloudSync { +class BatteryStatusListener : public std::enable_shared_from_this { +public: + explicit BatteryStatusListener(std::shared_ptr dataSyncManager); + ~BatteryStatusListener(); + void Start(); + void Stop(); + void OnStatusNormal(); + void OnStatusAbnormal(); + void OnPowerConnected(); + +private: + std::shared_ptr dataSyncManager_; + std::shared_ptr commonEventSubscriber_ = nullptr; + SyncTriggerType triggerType_{SyncTriggerType::BATTERY_OK_TRIGGER}; +}; + +class BatteryStatusSubscriber : public EventFwk::CommonEventSubscriber { +public: + BatteryStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + std::shared_ptr listener); + ~BatteryStatusSubscriber() override {} + void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; + +private: + std::shared_ptr listener_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_BATTERY_STATUS_LISTENER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/sync_rule/i_user_status_observer.h b/cloud_file/services/cloudsyncservice/include/sync_rule/i_user_status_observer.h new file mode 100644 index 0000000..f69535a --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/sync_rule/i_user_status_observer.h @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2024 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 I_USER_STATUS_OBSERVER_H +#define I_USER_STATUS_OBSERVER_H + +namespace OHOS::FileManagement::CloudSync { +class IUserStatusObserver { +public: + IUserStatusObserver() = default; + virtual ~IUserStatusObserver() = default; + virtual void OnUserUnlocked() = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // I_USER_STATUS_OBSERVER_H diff --git a/cloud_file/services/cloudsyncservice/include/sync_rule/package_status_listener.h b/cloud_file/services/cloudsyncservice/include/sync_rule/package_status_listener.h new file mode 100644 index 0000000..8b1cca8 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/sync_rule/package_status_listener.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2025 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 OHOS_FILEMGMT_PACKAGE_STATUS_LISTENER_H +#define OHOS_FILEMGMT_PACKAGE_STATUS_LISTENER_H + +#include "common_event_subscriber.h" +#include "data_sync_manager.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +class PackageStatusListener : public std::enable_shared_from_this { +public: + explicit PackageStatusListener(std::shared_ptr dataSyncManager); + ~PackageStatusListener(); + void Start(); + void Stop(); + void RemovedClean(const std::string &bundleName, const int32_t userId); + bool IsCloudSyncOn(const int32_t userId, const std::string &bundleName); + +private: + std::shared_ptr dataSyncManager_; + std::shared_ptr commonEventSubscriber_ = nullptr; +}; + +class PackageStatusSubscriber : public EventFwk::CommonEventSubscriber { +public: + PackageStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + std::shared_ptr listener); + ~PackageStatusSubscriber() override {} + void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; + +private: + std::shared_ptr listener_; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS + +#endif // OHOS_FILEMGMT_PACKAGE_STATUS_LISTENER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/sync_rule/screen_status_listener.h b/cloud_file/services/cloudsyncservice/include/sync_rule/screen_status_listener.h new file mode 100644 index 0000000..9663aed --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/sync_rule/screen_status_listener.h @@ -0,0 +1,51 @@ +/* + * 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 OHOS_FILEMGMT_SCREEN_STATUS_LISTENER_H +#define OHOS_FILEMGMT_SCREEN_STATUS_LISTENER_H + +#include "common_event_subscriber.h" +#include "data_sync_manager.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +class ScreenStatusListener : public std::enable_shared_from_this { +public: + explicit ScreenStatusListener(std::shared_ptr dataSyncManager); + ~ScreenStatusListener(); + void Start(); + void Stop(); + void ScreenOff(); + +private: + std::shared_ptr dataSyncManager_; + std::shared_ptr commonEventSubscriber_ = nullptr; +}; + +class ScreenStatusSubscriber : public EventFwk::CommonEventSubscriber { +public: + ScreenStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + std::shared_ptr listener); + ~ScreenStatusSubscriber() override {} + void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; +private: + std::shared_ptr listener_; +}; +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS + +#endif // OHOS_FILEMGMT_SCREEN_STATUS_LISTENER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/sync_rule/user_status_listener.h b/cloud_file/services/cloudsyncservice/include/sync_rule/user_status_listener.h new file mode 100644 index 0000000..b4ca62e --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/sync_rule/user_status_listener.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 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 USER_STATUS_LISTENER_H +#define USER_STATUS_LISTENER_H + +#include +#include + +#include "common_event_subscriber.h" +#include "data_sync_manager.h" +#include "i_user_status_observer.h" + +namespace OHOS::FileManagement::CloudSync { +class UserStatusListener : public std::enable_shared_from_this { +public: + explicit UserStatusListener(std::shared_ptr dataSyncManager); + ~UserStatusListener(); + void Start(); + void Stop(); + void AddObserver(std::shared_ptr observer); + void NotifyUserUnlocked(); + void DoCleanVideoCache(); + void DoUnloadSA(); + +private: + std::shared_ptr commonEventSubscriber_ = nullptr; + std::mutex obsVecMutex_; + std::vector> observers_; + std::shared_ptr dataSyncManager_; +}; + +class UserStatusSubscriber : public EventFwk::CommonEventSubscriber { +public: + UserStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + std::shared_ptr listener); + ~UserStatusSubscriber() override {} + void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; + +private: + std::shared_ptr listener_; +}; +} // namespace OHOS::FileManagement::CloudSync +#endif // USER_STATUS_LISTENER_H diff --git a/cloud_file/services/cloudsyncservice/include/transport/file_transfer_manager.h b/cloud_file/services/cloudsyncservice/include/transport/file_transfer_manager.h new file mode 100644 index 0000000..275d7f5 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/transport/file_transfer_manager.h @@ -0,0 +1,74 @@ +/* + * 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 OHOS_FILEMGMT_FILE_TRANSFER_MANAGER_H +#define OHOS_FILEMGMT_FILE_TRANSFER_MANAGER_H + +#include +#include +#include +#include +#include +#include + +#include "message_handler.h" +#include "session_manager.h" +namespace OHOS::FileManagement::CloudSync { +class FileTransferManager : public RecieveDataHandler, public std::enable_shared_from_this { +public: + explicit FileTransferManager(std::shared_ptr sessionManager); + ~FileTransferManager(){}; + + void Init(); + + void DownloadFileFromRemoteDevice(const std::string &networkId, + const int32_t userId, + const uint64_t taskId, + const std::string &uri); + void OnMessageHandle(const std::string &senderNetworkId, + int receiverSessionId, + const void *data, + unsigned int dataLen) override; + void OnFileRecvHandle(const std::string &senderNetworkId, const char *filePath, int result) override; + void OnSessionClosed() override; + void HandleDownloadFileRequest(MessageHandler &msgHandler, + const std::string &senderNetworkId, + int receiverSessionId); + void HandleDownloadFileResponse(MessageHandler &msgHandler); + void HandleRecvFileFinished(); + +private: + struct TaskInfo { + std::string uri; + std::string relativePath; + uint64_t taskId; + }; + bool IsFileExists(const std::string &filePath); + std::tuple + UriToPath(const std::string &uri, const int32_t userId, bool isCheckFileExists = true); + void AddTransTask(const std::string &uri, const int32_t userId, uint64_t taskId); + void FinishTransTask(const std::string &relativePath, int result); + void RemoveTransTask(uint64_t taskId); + void IncTransTaskCount(); + void DecTransTaskCount(); + std::mutex taskMutex_; + std::vector taskInfos_; + std::atomic taskCount_{0}; + + std::shared_ptr sessionManager_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_FILE_TRANSFER_MANAGER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/transport/message_handler.h b/cloud_file/services/cloudsyncservice/include/transport/message_handler.h new file mode 100644 index 0000000..8e1b153 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/transport/message_handler.h @@ -0,0 +1,97 @@ +/* + * 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 OHOS_FILEMGMT_MESSAGE_HANDLER_H +#define OHOS_FILEMGMT_MESSAGE_HANDLER_H + +#include + +namespace OHOS::FileManagement::CloudSync { +constexpr int32_t NETWORK_ID_SIZE_MAX = 65; + +template +constexpr T GET_ALIGNED_SIZE(T x, int alignWidth) +{ + return (x + (alignWidth - 1)) & ~(alignWidth - 1); +} + +#pragma pack(1) +struct MessageHeader { + uint8_t magic; + uint8_t version; + uint16_t msgType; + uint32_t dataLen; + int32_t errorCode; +}; + +struct SessionDeviceInfo { + char sourceNetworkId[NETWORK_ID_SIZE_MAX]; + char tartgeNetworkId[NETWORK_ID_SIZE_MAX]; +}; + +struct UserData { + uint64_t taskId; + uint32_t userId; + uint32_t uriLen; + char uri[0]; +}; +#pragma pack() + +enum MsgType : uint16_t { + MSG_DOWNLOAD_FILE_REQ = 0, + MSG_DOWNLOAD_FILE_RSP, + MSG_FINISH_FILE_RECV, +}; + +struct MessageInputInfo { + std::string srcNetworkId; + std::string dstNetworkId; + std::string uri; + uint16_t msgType; + int32_t errorCode; + int32_t userId; + uint64_t taskId; +}; + +class MessageHandler { +public: + MessageHandler() = default; + MessageHandler(MessageInputInfo &info); + + bool PackData(uint8_t *data, uint32_t totalLen); + bool UnPackData(uint8_t *data, uint32_t totalLen); + void GetMessageHeader(MessageHeader &header); + uint32_t GetDataSize(); + uint64_t GetTaskId(); + uint16_t GetMsgType(); + int32_t GetUserId(); + int32_t GetErrorCode(); + + std::string GetUri(); + std::string GetSrcNetworkId(); + std::string GetDstNetworkId(); + +private: + MessageHeader msgHdr_{0}; + std::string srcNetworkId_; + std::string dstNetworkId_; + std::string uri_; + int32_t userId_{0}; + uint64_t taskId_{0}; + uint32_t dataSize_{0}; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_MESSAGE_HANDLER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/transport/softbus/i_softbus_listener.h b/cloud_file/services/cloudsyncservice/include/transport/softbus/i_softbus_listener.h new file mode 100644 index 0000000..c2272e4 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/transport/softbus/i_softbus_listener.h @@ -0,0 +1,36 @@ +/* + * 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 OHOS_FILEMGMT_I_SOFTBUS_LISTENER_H +#define OHOS_FILEMGMT_I_SOFTBUS_LISTENER_H + +#include +#include "socket.h" + +namespace OHOS::FileManagement::CloudSync { +class ISoftbusListener { +public: + virtual ~ISoftbusListener() = default; + virtual void OnSessionOpened(int socket, int result) = 0; + virtual void OnSessionClosed(int socket) = 0; + virtual void OnDataReceived(const std::string &senderNetworkId, + int receiverSessionId, + const void *data, + unsigned int dataLen) = 0; + virtual void OnFileReceived(const std::string &senderNetworkId, const char *filePath, int result) = 0; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_I_SOFTBUS_LISTENER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/transport/softbus/session_manager.h b/cloud_file/services/cloudsyncservice/include/transport/softbus/session_manager.h new file mode 100644 index 0000000..fdda195 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/transport/softbus/session_manager.h @@ -0,0 +1,89 @@ +/* + * 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 OHOS_FILEMGMT_SESSION_MANAGER_H +#define OHOS_FILEMGMT_SESSION_MANAGER_H + +#include +#include +#include +#include +#include +#include +#include + +#include "i_softbus_listener.h" +#include "sync_rule/i_user_status_observer.h" +#include "softbus_session.h" +namespace OHOS::FileManagement::CloudSync { +class RecieveDataHandler; +class SessionManager : public ISoftbusListener, public std::enable_shared_from_this, + public IUserStatusObserver { +public: + SessionManager() = default; + ~SessionManager(); + + void Init(); + + int32_t SendData(const std::string &peerNetworkId, const void *data, uint32_t dataLen); + int32_t SendData(int sessionId, const void *data, uint32_t dataLen); + int32_t SendFile(const std::string &peerNetworkId, + const std::vector &sFileList, + const std::vector &dFileList); + + void ReleaseSession(SoftbusSession::DataType type, const std::string &peerDeviceId); + + void OnSessionOpened(int socket, int result) override; + void OnSessionClosed(int socket) override; + void OnDataReceived(const std::string &senderNetworkId, + int receiverSessionId, + const void *data, + unsigned int dataLen) override; + void OnFileReceived(const std::string &senderNetworkId, const char *filePath, int result) override; + + void RegisterDataHandler(std::shared_ptr handler); + void OnUserUnlocked() override; + +private: + void CreateServer(); + void RemoveServer(); + + std::shared_ptr CreateSession(SoftbusSession::DataType type, const std::string &peerDeviceId); + std::shared_ptr GetSendSession(SoftbusSession::DataType type, const std::string &peerDeviceId); + void CacheSendSession(std::shared_ptr session); + void RemoveSendSession(int sessionId); + + bool IsSessionOpened(int sessionId); + bool IsDeviceIdVailid(const std::string &peerDeviceId); + + std::mutex sessionVecMutex_; + std::vector> sendSessionVec_; + std::shared_ptr dataHandler_; + bool SetFileRecvListenerFlag_{true}; +}; + +class RecieveDataHandler { +public: + virtual ~RecieveDataHandler() = default; + virtual void OnMessageHandle(const std::string &senderNetworkId, + int receiverSessionId, + const void *data, + unsigned int dataLen) = 0; + virtual void OnFileRecvHandle(const std::string &senderNetworkId, const char *filePath, int result) = 0; + virtual void OnSessionClosed(); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_SESSION_MANAGER_H diff --git a/cloud_file/services/cloudsyncservice/include/transport/softbus/softbus_adapter.h b/cloud_file/services/cloudsyncservice/include/transport/softbus/softbus_adapter.h new file mode 100644 index 0000000..0fa29f4 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/transport/softbus/softbus_adapter.h @@ -0,0 +1,84 @@ +/* + * 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 OHOS_FILEMGMT_SOFTBUS_ADAPTER_H +#define OHOS_FILEMGMT_SOFTBUS_ADAPTER_H + +#include +#include +#include +#include +#include + +#include "nocopyable.h" +#include "session.h" +#include "socket.h" + +#include "i_softbus_listener.h" + +namespace OHOS::FileManagement::CloudSync { +class SoftbusAdapter : public NoCopyable { +public: + static SoftbusAdapter &GetInstance(); + + int32_t CreateSessionServer(const char *packageName, const char *sessionName); + int32_t RemoveSessionServer(const char *packageName, const char *sessionName); + + int OpenSession(char *sessionName, + char *peerDeviceId, + char *groupId, + TransDataType dataType); + + int OpenSessionByP2P(char *sessionName, char *peerDeviceId, char *groupId, bool isFileType); + void CloseSession(int sessionId); + + static void OnBind(int socket, PeerSocketInfo info); + static void OnShutdown(int32_t socket, ShutdownReason reason); + static void OnFile(int32_t socket, FileEvent *event); + static void OnBytes(int sessionId, const void *data, unsigned int dataLen); + static int OnReceiveFileProcess(int sessionId, const char *firstFile, uint64_t bytesUpload, uint64_t bytesTotal); + static void OnReceiveFileFinished(int sessionId, const char *files, int fileCnt); + static const char* GetRecvPath(); + + int SendBytes(int sessionId, const void *data, unsigned int dataLen); + int SendFile(int sessionId, const std::vector &sFileList, const std::vector &dFileList); + std::string GetSessionNameFromMap(int sessionId); + std::string GetPeerNetworkId(int sessionId); + int32_t GetSocketNameFromMap(std::string sessionAndPack); + bool IsFromServer(int sessionId); + + void RegisterSessionListener(std::string sessionName, std::shared_ptr listener); + void UnRegisterSessionListener(std::string sessionName); + + std::shared_ptr GetListener(std::string sessionName); + bool IsSessionOpened(int sessionId); + void AcceptSesion(int sessionId, const std::string &sessionName, const std::string &networkId); + void RemoveSesion(int sessionId); + +private: + SoftbusAdapter() = default; + std::unordered_map> listeners_; + std::shared_mutex listenerMutex_; + + std::mutex sessionMutex_; + std::unordered_map sessionOpenedMap_; + std::unordered_map sessionNameMap_; + std::unordered_map networkIdMap_; + std::unordered_map sessionAndPackageMap_; + static constexpr const int QOS_COUNT = 3; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_SOFTBUS_ADAPTER_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/include/transport/softbus/softbus_session.h b/cloud_file/services/cloudsyncservice/include/transport/softbus/softbus_session.h new file mode 100644 index 0000000..8803e36 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/include/transport/softbus/softbus_session.h @@ -0,0 +1,57 @@ +/* + * 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 OHOS_FILEMGMT_SOFTBUS_SESSION_H +#define OHOS_FILEMGMT_SOFTBUS_SESSION_H + +#include +#include +#include + +namespace OHOS::FileManagement::CloudSync { +constexpr int32_t INVALID_SESSION_ID = -1; +class SoftbusSession { +public: + enum DataType : int32_t { + TYPE_BYTES, + TYPE_FILE, + }; + SoftbusSession(const std::string &peerDeviceId, const std::string &sessionName, DataType type); + virtual ~SoftbusSession() = default; + int32_t Start(); + int32_t Stop(); + int32_t SendData(const void *data, uint32_t dataLen); + int32_t SendFile(const std::vector &sFileList, const std::vector &dFileList); + int32_t GetSessionId(); + DataType GetDataType(); + std::string GetPeerDeviceId(); + int32_t WaitSessionOpened(int sessionId); + +protected: + int sessionId_{INVALID_SESSION_ID}; + +private: + void CancelReleaseSessionIfNeeded(); + void CancelDelayReleaseSessionTask(); + std::string ToBeAnonymous(const std::string &name); + + std::string peerDeviceId_; + std::string sessionName_; + DataType type_{TYPE_BYTES}; + std::mutex sessionMutex_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_SOFTBUS_SESSION_H \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/cycle_task/cycle_task.cpp b/cloud_file/services/cloudsyncservice/src/cycle_task/cycle_task.cpp new file mode 100644 index 0000000..30b2970 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/cycle_task/cycle_task.cpp @@ -0,0 +1,110 @@ +/* + * 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 "cycle_task.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +CycleTask::CycleTask(std::string taskName, + std::set bundleNames, + int32_t intervalTime, + std::shared_ptr dataSyncManager) + : userId_(-1), + taskName_(taskName), + bundleNames_(bundleNames), + intervalTime_(intervalTime), + dataSyncManager_(dataSyncManager) +{ +} + +const std::string CycleTask::FILE_PATH = "CycleTask"; + +void CycleTask::SetRunnableBundleNames(std::shared_ptr> &bundleNames) +{ + this->runnableBundleNames_ = bundleNames; +} + +std::shared_ptr CycleTask::GetDataSyncManager() const +{ + return this->dataSyncManager_; +} + +std::string CycleTask::GetTaskName() const +{ + return this->taskName_; +} + +void CycleTask::SetLastRunTime(std::time_t time) +{ + if (cloudPrefImpl_ == nullptr) { + LOGE(" cloudPrefImpl is nullptr"); + return; + } + cloudPrefImpl_->SetLong("lastRunTime-" + taskName_, time); +} + +void CycleTask::GetLastRunTime(std::time_t &time) +{ + if (cloudPrefImpl_ == nullptr) { + LOGE(" cloudPrefImpl is nullptr"); + time = std::time(nullptr); + return; + } + cloudPrefImpl_->GetLong("lastRunTime-" + taskName_, time); +} + +bool CycleTask::IsEligibleToRun(std::time_t currentTime, std::string bundleName) +{ + std::time_t lastRuntime; + GetLastRunTime(lastRuntime); + if (lastRuntime == 0) { + SetLastRunTime(currentTime); + LOGE("skip first run, bundle name is %{public}s", bundleName.c_str()); + return false; + } + if ((bundleNames_.find(bundleName) != bundleNames_.end() || bundleNames_.size() == 0) && + difftime(currentTime, lastRuntime) >= intervalTime_) { + return true; + } + return false; +} + +void CycleTask::RunTask(int32_t userId) +{ + if (runnableBundleNames_ == nullptr) { + LOGE("runnableBundleNames_ is nullptr"); + return; + } + userId_ = userId; + std::time_t currentTime = std::time(nullptr); + for (const auto &bundleName : *runnableBundleNames_) { + cloudPrefImpl_ = std::make_unique(userId_, bundleName, FILE_PATH); + if (IsEligibleToRun(currentTime, bundleName)) { + LOGI("begin task, task name is %{public}s, bundle name is %{public}s", + taskName_.c_str(), bundleName.c_str()); + int32_t ret = RunTaskForBundle(userId, bundleName); + if (ret == E_OK) { + SetLastRunTime(currentTime); + } + LOGI("end task, task name is %{public}s, bundle name is %{public}s, ret is %{public}d", + taskName_.c_str(), bundleName.c_str(), ret); + } + } +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/cycle_task/cycle_task_runner.cpp b/cloud_file/services/cloudsyncservice/src/cycle_task/cycle_task_runner.cpp new file mode 100644 index 0000000..e798c4a --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/cycle_task/cycle_task_runner.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2023-2025 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 "cycle_task_runner.h" +#include "cloud_status.h" +#include "cycle_task.h" +#include "data_syncer_rdb_col.h" +#include "data_syncer_rdb_store.h" +#include "os_account_manager.h" +#include "parameter.h" +#include "result_set.h" +#include "tasks/database_backup_task.h" +#include "tasks/optimize_cache_task.h" +#include "tasks/optimize_storage_task.h" +#include "tasks/periodic_check_task.h" +#include "tasks/report_statistics_task.h" +#include "tasks/save_subscription_task.h" +#include "utils_log.h" +#include + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +using namespace std; + +CycleTaskRunner::CycleTaskRunner(std::shared_ptr dataSyncManager) +{ + dataSyncManager_ = dataSyncManager; + vector activeUsers; + if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUsers) != E_OK || activeUsers.empty()) { + LOGE("query active user failed"); + return; + } + userId_ = activeUsers.front(); + setUpTime_ = std::time(nullptr); + if (dataSyncManager_ == nullptr) { + LOGI("dataSyncManager is nullptr"); + return; + } + InitTasks(); + SetRunableBundleNames(); +} + +void CycleTaskRunner::StartTask() +{ +#ifdef EMULATOR + return; +#endif + + constexpr int32_t MOVE_FILE_TIME_SERVICE = 5; + int status = WaitParameter("persist.kernel.move.finish", "true", MOVE_FILE_TIME_SERVICE); + if (status != 0) { + LOGE("wait move error, return value %{public}d.", status); + return; + } + for (const auto &task_data : cycleTasks_) { + task_data->RunTask(userId_); + } +} + +void CycleTaskRunner::InitTasks() +{ + //push tasks here + cycleTasks_.push_back(std::make_shared(dataSyncManager_)); + cycleTasks_.push_back(std::make_shared(dataSyncManager_)); + cycleTasks_.push_back(std::make_shared(dataSyncManager_)); + cycleTasks_.push_back(std::make_shared(dataSyncManager_)); + cycleTasks_.push_back(std::make_shared(dataSyncManager_)); + + //do periodic check task last + cycleTasks_.push_back(std::make_shared(dataSyncManager_)); +} + +static int32_t GetString(const string &key, string &val, NativeRdb::ResultSet &resultSet) +{ + int32_t index; + int32_t err = resultSet.GetColumnIndex(key, index); + if (err != NativeRdb::E_OK) { + LOGE("result set get %{public}s column index err %{public}d", key.c_str(), err); + return E_RDB; + } + + err = resultSet.GetString(index, val); + if (err != 0) { + LOGE("result set get string err %{public}d", err); + return E_RDB; + } + + return E_OK; +} + +void CycleTaskRunner::SetRunableBundleNames() +{ + std::shared_ptr> runnableBundleNames = make_shared>(); + std::shared_ptr resultSet = nullptr; + int32_t ret = DataSyncerRdbStore::GetInstance().QueryDataSyncer(userId_, resultSet); + if (ret != 0 || resultSet == nullptr) { + LOGE("query data syncer fail %{public}d", ret); + return; + } + while (resultSet->GoToNextRow() == E_OK) { + string bundleName; + ret = GetString(BUNDLE_NAME, bundleName, *resultSet); + if (ret != E_OK) { + LOGE("get bundle name failed"); + continue; + } + std::time_t currentTime = std::time(nullptr); + std::unique_ptr cloudPrefImpl = + std::make_unique(userId_, bundleName, CycleTask::FILE_PATH); + std::time_t lastCheckTime; + if (cloudPrefImpl == nullptr) { + LOGE("cloudPrefImpl is nullptr"); + continue; + } + cloudPrefImpl->GetLong("lastCheckTime", lastCheckTime); + if (lastCheckTime != 0 && difftime(currentTime, lastCheckTime) < CycleTask::ONE_DAY) { + continue; + } + bool cloudStatus = CloudStatus::IsCloudStatusOkay(bundleName, userId_); + if (!cloudStatus) { + LOGI(" %{public}s cloud status is not ok, skip task, ret is %{public}d", bundleName.c_str(), ret); + cloudPrefImpl->SetLong("lastCheckTime", currentTime); + continue; + } + cloudPrefImpl->Delete("lastCheckTime"); + runnableBundleNames->insert(bundleName); + } + + for (auto task_data : cycleTasks_) { + task_data->SetRunnableBundleNames(runnableBundleNames); + } +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/database_backup_task.cpp b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/database_backup_task.cpp new file mode 100644 index 0000000..fc919b6 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/database_backup_task.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024 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 "database_backup_task.h" +#include "clouddisk_rdbstore.h" +#include "parameters.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +using namespace std; +using namespace OHOS::FileManagement::CloudDisk; +static const std::string FILEMANAGER_KEY = "persist.kernel.bundle_name.filemanager"; +static const uint32_t STAT_MODE_DIR = 0771; +DatabaseBackupTask::DatabaseBackupTask(std::shared_ptr dataSyncManager) + : CycleTask("database_backup_task", {system::GetParameter(FILEMANAGER_KEY, "")}, ONE_DAY, dataSyncManager) +{ +} + +int32_t DatabaseBackupTask::RunTaskForBundle(int32_t userId, std::string bundleName) +{ + LOGI("%{public}s backup database entry", bundleName.c_str()); + auto directoryName = "/data/service/el2/" + to_string(userId_) + + "/hmdfs/cloudfile_manager/" + bundleName + "/backup"; + if (access(directoryName.c_str(), F_OK) != 0) { + if (errno == ENOENT) { + if (mkdir(directoryName.c_str(), STAT_MODE_DIR) != 0) { + LOGE("mkdir backup failed :%{public}s err:%{public}d", GetAnonyString(directoryName).c_str(), errno); + return errno; + } + } else { + LOGE("access backup dir failed :%{public}s err:%{public}d", GetAnonyString(directoryName).c_str(), errno); + return errno; + } + } + auto fileName = directoryName + "/clouddisk_backup.db"; + std::thread backup([fileName, userId, bundleName] { + auto cloudDiskRdbStore = make_shared(bundleName, userId); + auto rdb = cloudDiskRdbStore->GetRaw(); + if (!rdb) { + LOGE("clouddisk rdb init fail"); + return; + } + auto ret = rdb->Backup(fileName); + if (ret != 0) { + LOGE("clouddisk backup failed, ret %{public}d", ret); + } + }); + backup.detach(); + return E_OK; +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp new file mode 100644 index 0000000..a2f66a5 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 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 "optimize_cache_task.h" +#include "cloud_file_kit.h" +#include "parameters.h" +#include "system_load.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +static const std::string FILEMANAGER_KEY = "persist.kernel.bundle_name.filemanager"; +OptimizeCacheTask::OptimizeCacheTask(std::shared_ptr dataSyncManager) + : CycleTask("optimize_cache_task", {"com.ohos.photos", system::GetParameter(FILEMANAGER_KEY, "")}, ONE_DAY, + dataSyncManager) +{} + +int32_t OptimizeCacheTask::RunTaskForBundle(int32_t userId, std::string bundleName) +{ + if (!SystemLoadStatus::IsLoadStatusUnderHot()) { + LOGE("OptimizeCacheTask::RunTaskForBundle system load is over hot"); + return E_STOP; + } + return dataSyncManager_->OptimizeCache(userId, bundleName); +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp new file mode 100644 index 0000000..705e994 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp @@ -0,0 +1,60 @@ +/* + * 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 "optimize_storage_task.h" +#include "cloud_file_kit.h" +#include "system_load.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +OptimizeStorageTask::OptimizeStorageTask(std::shared_ptr dataSyncManager) + : CycleTask("optimize_storage_task", {"com.ohos.photos"}, ONE_DAY, dataSyncManager) +{ +} + +int32_t OptimizeStorageTask::RunTaskForBundle(int32_t userId, std::string bundleName) +{ + if (!SystemLoadStatus::IsLoadStatusUnderHot()) { + LOGE("OptimizeStorageTask::RunTaskForBundle system load is over hot"); + return E_STOP; + } + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + return E_NULLPTR; + } + auto dataSyncManager_ = GetDataSyncManager(); + if (dataSyncManager_->CleanRemainFile(bundleName, userId) != E_OK) { + LOGW(" clean reamin file fail"); + } + std::map param; + auto ret = instance->GetAppConfigParams(userId, bundleName, param); + if (ret != E_OK || param.empty()) { + LOGE("GetAppConfigParams failed"); + return ret; + } + + int32_t agingDays = std::stoi(param["validDays"]); + int32_t agingPolicy = std::stoi(param["dataAgingPolicy"]); + if (agingPolicy == 0) { + return dataSyncManager_->OptimizeStorage(bundleName, userId, agingDays); + } + return E_OK; +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp new file mode 100644 index 0000000..aff5ec9 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp @@ -0,0 +1,48 @@ +/* + * 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 "battery_status.h" +#include "periodic_check_task.h" +#include "parameters.h" +#include "screen_status.h" +#include "system_load.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +static const std::string FILEMANAGER_KEY = "persist.kernel.bundle_name.filemanager"; +PeriodicCheckTask::PeriodicCheckTask(std::shared_ptr dataSyncManager) + : CycleTask(PeriodicCheckTaskName, {"com.ohos.photos", system::GetParameter(FILEMANAGER_KEY, "")}, + THREE_DAY, + dataSyncManager) +{ +} + +int32_t PeriodicCheckTask::RunTaskForBundle(int32_t userId, std::string bundleName) +{ + if (ScreenStatus::IsScreenOn() || !BatteryStatus::IsCharging() + || !SystemLoadStatus::IsLoadStatusUnderHot()) { + LOGI("PeriodicCheckTask::RunTaskForBundle isScreenOn or not charging"); + return E_STOP; + } + int32_t ret = dataSyncManager_->TriggerStartSync(bundleName, userId, false, SyncTriggerType::TASK_TRIGGER); + if (ret != E_OK) { + LOGE("trigger %{public}s periodic sync failed", bundleName.c_str()); + } + return ret; +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp new file mode 100644 index 0000000..98d290d --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 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 "report_statistics_task.h" + +#include "parameters.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +ReportStatisticsTask::ReportStatisticsTask(std::shared_ptr dataSyncManager) + : CycleTask("report_statistics_task", {"com.ohos.photos"}, ONE_DAY, dataSyncManager) +{ +} + +int32_t ReportStatisticsTask::RunTaskForBundle(int32_t userId, std::string bundleName) +{ + int32_t ret = dataSyncManager_->ReportEntry(bundleName, userId); + if (ret != E_OK) { + LOGE("report failed"); + } + return ret; +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/save_subscription_task.cpp b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/save_subscription_task.cpp new file mode 100644 index 0000000..f2f4d7f --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/cycle_task/tasks/save_subscription_task.cpp @@ -0,0 +1,47 @@ +/* + * 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 "save_subscription_task.h" + +#include "cloud_file_kit.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +SaveSubscriptionTask::SaveSubscriptionTask(std::shared_ptr dataSyncManager) + : CycleTask("save_subscription_task", {}, ONE_DAY, dataSyncManager) +{ +} + +int32_t SaveSubscriptionTask::RunTaskForBundle(int32_t userId, std::string bundleName) +{ + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + return E_NULLPTR; + } + + auto cloudSyncHelper = instance->GetCloudSyncHelper(userId, bundleName); + if (cloudSyncHelper == nullptr) { + LOGE("get cloudSyncHelper failed"); + return E_NULLPTR; + } + + return cloudSyncHelper->SaveSubScription(); +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/ipc/cloud_sync_service.cpp b/cloud_file/services/cloudsyncservice/src/ipc/cloud_sync_service.cpp new file mode 100644 index 0000000..4bf1fb6 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/ipc/cloud_sync_service.cpp @@ -0,0 +1,1111 @@ +/* + * 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 "ipc/cloud_sync_service.h" + +#include +#include + +#include "battery_status.h" +#include "cloud_file_kit.h" +#include "cloud_status.h" +#include "clouddisk_rdb_utils.h" +#include "cycle_task/cycle_task_runner.h" +#include "data_sync_const.h" +#include "data_syncer_rdb_store.h" +#include "dfs_error.h" +#include "dfsu_access_token_helper.h" +#include "directory_ex.h" +#include "ipc/download_asset_callback_manager.h" +#include "meta_file.h" +#include "net_conn_callback_observer.h" +#include "network_status.h" +#include "parameters.h" +#include "periodic_check_task.h" +#include "plugin_loader.h" +#include "sandbox_helper.h" +#include "screen_status.h" +#include "session_manager.h" +#include "system_ability_definition.h" +#include "system_load.h" +#include "task_state_manager.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +using namespace OHOS; +using namespace CloudFile; +constexpr int32_t MIN_USER_ID = 100; +constexpr int LOAD_SA_TIMEOUT_MS = 4000; +const std::string CLOUDDRIVE_KEY = "persist.kernel.bundle_name.clouddrive"; +REGISTER_SYSTEM_ABILITY_BY_ID(CloudSyncService, FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, false); + +CloudSyncService::CloudSyncService(int32_t saID, bool runOnCreate) : SystemAbility(saID, runOnCreate) +{ +} + +void CloudSyncService::PublishSA() +{ + LOGI("Begin to init"); + if (!SystemAbility::Publish(this)) { + throw runtime_error("Failed to publish the daemon"); + } + LOGI("Init finished successfully"); +} + +void CloudSyncService::PreInit() +{ + /* load cloud file ext plugin */ + CloudFile::PluginLoader::GetInstance().LoadCloudKitPlugin(true); + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + dataSyncManager_ = make_shared(); + } else { + dataSyncManager_ = instance->GetDataSyncManager(); + } + + batteryStatusListener_ = make_shared(dataSyncManager_); + screenStatusListener_ = make_shared(dataSyncManager_); + userStatusListener_ = make_shared(dataSyncManager_); + packageStatusListener_ = make_shared(dataSyncManager_); +} + +void CloudSyncService::Init() +{ + /* Get Init Charging status */ + BatteryStatus::GetInitChargingStatus(); + ScreenStatus::InitScreenStatus(); +} + +constexpr int TEST_MAIN_USR_ID = 100; +int32_t CloudSyncService::GetBundleNameUserInfo(BundleNameUserInfo &bundleNameUserInfo) +{ + string bundleName; + if (DfsuAccessTokenHelper::GetCallerBundleName(bundleName)) { + return E_INVAL_ARG; + } + bundleNameUserInfo.bundleName = bundleName; + + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + if (callerUserId == 0) { + callerUserId = TEST_MAIN_USR_ID; // for root user change id to main user for test + } + bundleNameUserInfo.userId = callerUserId; + + auto callerPid = DfsuAccessTokenHelper::GetPid(); + bundleNameUserInfo.pid = callerPid; + + return E_OK; +} + +void CloudSyncService::CovertBundleName(std::string &bundleName) +{ + auto clouddriveBundleName = system::GetParameter(CLOUDDRIVE_KEY, ""); + if (bundleName == clouddriveBundleName) { + bundleName = GALLERY_BUNDLE_NAME; + } +} + +void CloudSyncService::GetBundleNameUserInfo(const std::vector &uriVec, + BundleNameUserInfo &bundleNameUserInfo) +{ + Uri uri(uriVec[0]); + string bundleName = uri.GetAuthority(); + bundleNameUserInfo.bundleName = bundleName; + + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + if (callerUserId == 0) { + callerUserId = TEST_MAIN_USR_ID; // for root user change id to main user for test + } + bundleNameUserInfo.userId = callerUserId; + + auto callerPid = DfsuAccessTokenHelper::GetPid(); + bundleNameUserInfo.pid = callerPid; +} + +std::string CloudSyncService::GetHmdfsPath(const std::string &uri, int32_t userId) +{ + const std::string HMDFS_DIR = "/mnt/hmdfs/"; + const std::string DATA_DIR = "/account/device_view/local/data/"; + const std::string FILE_DIR = "data/storage/el2/distributedfiles/"; + const std::string URI_PREFIX = "://"; + if (uri.empty() || uri.find("..") != std::string::npos) { + return ""; + } + + std::string bundleName; + size_t uriPrefixPos = uri.find(URI_PREFIX); + if (uriPrefixPos == std::string::npos) { + return ""; + } + uriPrefixPos += URI_PREFIX.length(); + size_t bundleNameEndPos = uri.find('/', uriPrefixPos); + if (bundleNameEndPos == std::string::npos) { + return ""; + } + bundleName = uri.substr(uriPrefixPos, bundleNameEndPos - uriPrefixPos); + + std::string relativePath; + size_t fileDirPos = uri.find(FILE_DIR); + if (fileDirPos == std::string::npos) { + return ""; + } + fileDirPos += FILE_DIR.length(); + relativePath = uri.substr(fileDirPos); + + std::string outputPath = HMDFS_DIR + std::to_string(userId) + DATA_DIR + bundleName + "/" + relativePath; + std::string dir = outputPath.substr(0, outputPath.find_last_of('/')); + + ForceCreateDirectory(dir); + return outputPath; +} + +void CloudSyncService::OnStart(const SystemAbilityOnDemandReason& startReason) +{ + PreInit(); + try { + PublishSA(); + AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); + AddSystemAbilityListener(SOFTBUS_SERVER_SA_ID); + AddSystemAbilityListener(RES_SCHED_SYS_ABILITY_ID); + AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID); + } catch (const exception &e) { + LOGE("%{public}s", e.what()); + } + LOGI("Start service successfully"); + Init(); + LOGI("init service successfully"); + system::SetParameter(CLOUD_FILE_SERVICE_SA_STATUS_FLAG, CLOUD_FILE_SERVICE_SA_START); + TaskStateManager::GetInstance().StartTask(); + // 跟随进程生命周期 + ffrt::submit([startReason, this]() { + this->HandleStartReason(startReason); + }); +} + +void CloudSyncService::OnActive(const SystemAbilityOnDemandReason& startReason) +{ + LOGI("active service successfully"); + system::SetParameter(CLOUD_FILE_SERVICE_SA_STATUS_FLAG, CLOUD_FILE_SERVICE_SA_START); + TaskStateManager::GetInstance().StartTask(); + ffrt::submit([startReason, this]() { + this->HandleStartReason(startReason); + }); +} + +void CloudSyncService::OnStop() +{ + LOGI("Stop finished successfully"); +} + +void CloudSyncService::HandleStartReason(const SystemAbilityOnDemandReason& startReason) +{ + string reason = startReason.GetName(); + int32_t userId = 0; + + LOGI("Begin to start service reason: %{public}s", reason.c_str()); + + if (reason == "usual.event.USER_UNLOCKED") { + return; + } + + if (dataSyncManager_->GetUserId(userId) != E_OK) { + return; + } + + if (reason == "usual.event.wifi.CONN_STATE") { + dataSyncManager_->TriggerRecoverySync(SyncTriggerType::NETWORK_AVAIL_TRIGGER); + dataSyncManager_->DownloadThumb(); + dataSyncManager_->CacheVideo(); + } else if (reason == "usual.event.BATTERY_OKAY") { + dataSyncManager_->TriggerRecoverySync(SyncTriggerType::BATTERY_OK_TRIGGER); + dataSyncManager_->DownloadThumb(); + } else if (reason == "usual.event.SCREEN_OFF" || reason == "usual.event.POWER_CONNECTED") { + dataSyncManager_->DownloadThumb(); + dataSyncManager_->CacheVideo(); + } else if (reason == "usual.event.PACKAGE_REMOVED") { + HandlePackageRemoved(startReason); + } + + if (reason != "load") { + shared_ptr taskRunner = make_shared(dataSyncManager_); + taskRunner->StartTask(); + } +} + +void CloudSyncService::HandlePackageRemoved(const SystemAbilityOnDemandReason& startReason) +{ + std::string bundleName; + std::string userId; + auto extraData = startReason.GetExtraData().GetWant(); + auto iter = extraData.find("bundleName"); + if (iter != extraData.end()) { + bundleName = iter->second; + } else { + LOGE("Cant find bundleName"); + return; + } + iter = extraData.find("userId"); + if (iter != extraData.end()) { + userId = iter->second; + } else { + LOGE("Cant find userId"); + return; + } + int32_t userIdNum = std::atoi(userId.c_str()); + if (userIdNum < 0 || (userIdNum == 0 && userId != "0")) { + LOGE("Get UserId Failed!"); + return; + } + packageStatusListener_->RemovedClean(bundleName, userIdNum); +} + +void CloudSyncService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) +{ + LOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId); + if (systemAbilityId == COMMON_EVENT_SERVICE_ID) { + userStatusListener_->Start(); + batteryStatusListener_->Start(); + screenStatusListener_->Start(); + packageStatusListener_->Start(); + } else if (systemAbilityId == SOFTBUS_SERVER_SA_ID) { + auto sessionManager = make_shared(); + sessionManager->Init(); + userStatusListener_->AddObserver(sessionManager); + fileTransferManager_ = make_shared(sessionManager); + fileTransferManager_->Init(); + } else if (systemAbilityId == RES_SCHED_SYS_ABILITY_ID) { + SystemLoadStatus::InitSystemload(dataSyncManager_); + } else if (systemAbilityId == COMM_NET_CONN_MANAGER_SYS_ABILITY_ID) { + NetworkStatus::InitNetwork(dataSyncManager_); + } else { + LOGE("unexpected"); + } +} + +void CloudSyncService::LoadRemoteSACallback::OnLoadSACompleteForRemote(const std::string &deviceId, + int32_t systemAbilityId, + const sptr &remoteObject) +{ + LOGI("Load CloudSync SA success,systemAbilityId:%{public}d, remoteObj result:%{public}s", systemAbilityId, + (remoteObject == nullptr ? "false" : "true")); + unique_lock lock(loadRemoteSAMutex_); + if (remoteObject == nullptr) { + isLoadSuccess_.store(false); + } else { + isLoadSuccess_.store(true); + remoteObjectMap_[deviceId] = remoteObject; + } + proxyConVar_.notify_one(); +} + +void CloudSyncService::SetDeathRecipient(const sptr &remoteObject) +{ + LOGD("set death recipient"); + auto deathCallback = [this](const wptr &obj) { + unique_lock lock(loadRemoteSAMutex_); + for (auto it = remoteObjectMap_.begin(); it != remoteObjectMap_.end();) { + if (it->second.GetRefPtr() == obj.GetRefPtr()) { + it = remoteObjectMap_.erase(it); + LOGD("remote sa died"); + } else { + ++it; + } + } + }; + deathRecipient_ = sptr(new SvcDeathRecipient(deathCallback)); + remoteObject->AddDeathRecipient(deathRecipient_); +} + +int32_t CloudSyncService::LoadRemoteSA(const std::string &deviceId) +{ + unique_lock lock(loadRemoteSAMutex_); + auto iter = remoteObjectMap_.find(deviceId); + if (iter != remoteObjectMap_.end()) { + return E_OK; + } + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Samgr is nullptr"); + return E_SA_LOAD_FAILED; + } + sptr cloudSyncLoadCallback = new LoadRemoteSACallback(); + if (cloudSyncLoadCallback == nullptr) { + LOGE("cloudSyncLoadCallback is nullptr"); + return E_SA_LOAD_FAILED; + } + int32_t ret = samgr->LoadSystemAbility(FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, deviceId, cloudSyncLoadCallback); + if (ret != E_OK) { + LOGE("Failed to Load systemAbility, systemAbilityId:%{public}d, ret code:%{public}d", + FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID, ret); + return E_SA_LOAD_FAILED; + } + + auto waitStatus = cloudSyncLoadCallback->proxyConVar_.wait_for( + lock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS), + [cloudSyncLoadCallback]() { return cloudSyncLoadCallback->isLoadSuccess_.load(); }); + if (!waitStatus) { + LOGE("Load CloudSynd SA timeout"); + return E_SA_LOAD_FAILED; + } + SetDeathRecipient(remoteObjectMap_[deviceId]); + return E_OK; +} + +static int32_t GetTargetBundleName(string &targetBundleName, string &callerBundleName) +{ + if (DfsuAccessTokenHelper::GetCallerBundleName(callerBundleName)) { + return E_INVAL_ARG; + } + if (targetBundleName == "") { + targetBundleName = callerBundleName; + } + if (targetBundleName != callerBundleName && + !DfsuAccessTokenHelper::CheckCallerPermission(PERM_CLOUD_SYNC_MANAGER)) { + LOGE("permission denied: cloudfile_sync_manager"); + return E_PERMISSION_DENIED; + } + return E_OK; +} + +static int32_t CheckPermissions(const string &permission, bool isSystemApp) +{ + if (!permission.empty() && !DfsuAccessTokenHelper::CheckCallerPermission(permission)) { + LOGE("permission denied"); + return E_PERMISSION_DENIED; + } + if (isSystemApp && !DfsuAccessTokenHelper::IsSystemApp()) { + LOGE("caller hap is not system hap"); + return E_PERMISSION_SYSTEM; + } + return E_OK; +} + +int32_t CloudSyncService::UnRegisterCallbackInner(const string &bundleName) +{ + LOGI("Begin UnRegisterCallbackInner"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + dataSyncManager_->UnRegisterCloudSyncCallback(targetBundleName, callerBundleName); + LOGI("End UnRegisterCallbackInner"); + return E_OK; +} + +int32_t CloudSyncService::UnRegisterFileSyncCallbackInner(const string &bundleName) +{ + LOGI("Begin UnRegisterFileSyncCallbackInner"); + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + dataSyncManager_->UnRegisterCloudSyncCallback(targetBundleName, callerBundleName); + LOGI("End UnRegisterFileSyncCallbackInner"); + return E_OK; +} + +int32_t CloudSyncService::RegisterCallbackInner(const sptr &remoteObject, const string &bundleName) +{ + LOGI("Begin RegisterCallbackInner"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + if (remoteObject == nullptr) { + LOGE("remoteObject is nullptr"); + return E_INVAL_ARG; + } + + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + + auto callback = iface_cast(remoteObject); + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + dataSyncManager_->RegisterCloudSyncCallback(targetBundleName, callerBundleName, callerUserId, callback); + LOGI("End RegisterCallbackInner"); + return E_OK; +} + +int32_t CloudSyncService::RegisterFileSyncCallbackInner(const sptr &remoteObject, + const string &bundleName) +{ + LOGI("Begin RegisterFileSyncCallbackInner"); + if (remoteObject == nullptr) { + LOGE("remoteObject is nullptr"); + return E_INVAL_ARG; + } + + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + + auto callback = iface_cast(remoteObject); + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + dataSyncManager_->RegisterCloudSyncCallback(targetBundleName, callerBundleName, callerUserId, callback); + LOGI("End RegisterFileSyncCallbackInner"); + return E_OK; +} + +int32_t CloudSyncService::StartSyncInner(bool forceFlag, const string &bundleName) +{ + LOGI("Begin StartSyncInner"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + ret = dataSyncManager_->TriggerStartSync(targetBundleName, callerUserId, forceFlag, SyncTriggerType::APP_TRIGGER); + LOGI("End StartSyncInner"); + return ret; +} + +int32_t CloudSyncService::StartFileSyncInner(bool forceFlag, const string &bundleName) +{ + LOGI("Begin StartFileSyncInner"); + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + ret = dataSyncManager_->TriggerStartSync(targetBundleName, callerUserId, forceFlag, SyncTriggerType::APP_TRIGGER); + LOGI("End StartFileSyncInner"); + return ret; +} + +int32_t CloudSyncService::TriggerSyncInner(const std::string &bundleName, int32_t userId) +{ + LOGI("Begin TriggerSyncInner"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + if (bundleName.empty() || userId < MIN_USER_ID) { + LOGE("Trigger sync parameter is invalid"); + return E_INVAL_ARG; + } + int32_t ret = dataSyncManager_->TriggerStartSync(bundleName, userId, false, SyncTriggerType::APP_TRIGGER); + LOGI("End StartSyncInner"); + return ret; +} + +int32_t CloudSyncService::StopSyncInner(const string &bundleName, bool forceFlag) +{ + LOGI("Begin StopSyncInner"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + ret = dataSyncManager_->TriggerStopSync(targetBundleName, callerUserId, forceFlag, SyncTriggerType::APP_TRIGGER); + LOGI("End StopSyncInner"); + return ret; +} + +int32_t CloudSyncService::StopFileSyncInner(const string &bundleName, bool forceFlag) +{ + LOGI("Begin StopFileSyncInner"); + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + ret = dataSyncManager_->TriggerStopSync(targetBundleName, callerUserId, forceFlag, SyncTriggerType::APP_TRIGGER); + LOGI("End StopFileSyncInner"); + return ret; +} + +int32_t CloudSyncService::ResetCursor(const string &bundleName) +{ + LOGI("Begin ResetCursor"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + ret = dataSyncManager_->ResetCursor(targetBundleName, callerUserId); + LOGI("End ResetCursor"); + return ret; +} + +int32_t CloudSyncService::GetSyncTimeInner(int64_t &syncTime, const string &bundleName) +{ + LOGI("Begin GetSyncTimeInner"); + string targetBundleName = bundleName; + string callerBundleName = ""; + int32_t ret = GetTargetBundleName(targetBundleName, callerBundleName); + if (ret != E_OK) { + LOGE("get bundle name failed: %{public}d", ret); + return ret; + } + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + ret = DataSyncerRdbStore::GetInstance().GetLastSyncTime(callerUserId, targetBundleName, syncTime); + LOGI("End GetSyncTimeInner"); + return ret; +} + +int32_t CloudSyncService::BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId) +{ + LOGI("Begin BatchDentryFileInsert"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + std::vector dentryFileInfo; + for (const auto &obj : fileInfo) { + DentryFileInfo tmpFileInfo{obj.cloudId, obj.size, obj.modifiedTime, obj.path, obj.fileName, obj.fileType}; + dentryFileInfo.emplace_back(tmpFileInfo); + } + + int32_t ret = dataSyncManager_->BatchDentryFileInsert(dentryFileInfo, failCloudId); + LOGI("End BatchDentryFileInsert"); + return ret; +} + +int32_t CloudSyncService::CleanCacheInner(const std::string &uri) +{ + LOGI("Begin CleanCacheInner"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + string bundleName; + if (DfsuAccessTokenHelper::GetCallerBundleName(bundleName)) { + return E_INVAL_ARG; + } + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + int32_t ret = dataSyncManager_->CleanCache(bundleName, callerUserId, uri); + LOGI("End CleanCacheInner"); + return E_OK; +} + +int32_t CloudSyncService::OptimizeStorage(const OptimizeSpaceOptions &optimizeOptions, + bool isCallbackValid, + const sptr &optimizeCallback) +{ + LOGI("Begin OptimizeStorage"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + + CovertBundleName(bundleNameUserInfo.bundleName); + LOGI("OptimizeStorage, bundleName: %{private}s, agingDays: %{public}d, callerUserId: %{public}d", + bundleNameUserInfo.bundleName.c_str(), optimizeOptions.agingDays, bundleNameUserInfo.userId); + if (!isCallbackValid) { + return dataSyncManager_->OptimizeStorage(bundleNameUserInfo.bundleName, bundleNameUserInfo.userId, + optimizeOptions.agingDays); + } + + auto optimizeCb = iface_cast(optimizeCallback); + ret = dataSyncManager_->StartOptimizeStorage(bundleNameUserInfo, optimizeOptions, optimizeCb); + LOGI("End OptimizeStorage"); + return ret; +} + +int32_t CloudSyncService::StopOptimizeStorage() +{ + LOGI("Begin StopOptimizeStorage"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + CovertBundleName(bundleNameUserInfo.bundleName); + ret = dataSyncManager_->StopOptimizeStorage(bundleNameUserInfo); + LOGI("End StopOptimizeStorage"); + return ret; +} + +int32_t CloudSyncService::ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) +{ + LOGI("Begin ChangeAppSwitch"); + RETURN_ON_ERR(CheckPermissions("", true)); + + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + LOGI("ChangeAppSwitch, bundleName: %{private}s, status: %{public}d, callerUserId: %{public}d", bundleName.c_str(), + status, callerUserId); + + /* update app switch status */ + int32_t ret = CloudStatus::ChangeAppSwitch(bundleName, callerUserId, status); + if (ret != E_OK) { + LOGE("CloudStatus::ChangeAppSwitch failed, ret: %{public}d", ret); + return ret; + } + if (status) { + ret = dataSyncManager_->TriggerStartSync(bundleName, callerUserId, false, SyncTriggerType::CLOUD_TRIGGER); + } else { + system::SetParameter(CLOUDSYNC_STATUS_KEY, CLOUDSYNC_STATUS_SWITCHOFF); + ret = dataSyncManager_->TriggerStopSync(bundleName, callerUserId, false, SyncTriggerType::CLOUD_TRIGGER); + } + if (ret != E_OK) { + LOGE("dataSyncManager Trigger failed, status: %{public}d", status); + return ret; + } + + ret = dataSyncManager_->ChangeAppSwitch(bundleName, callerUserId, status); + LOGI("End ChangeAppSwitch"); + return ret; +} + +int32_t CloudSyncService::NotifyDataChange(const std::string &accoutId, const std::string &bundleName) +{ + LOGI("Begin NotifyDataChange"); + RETURN_ON_ERR(CheckPermissions("", true)); + + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + int32_t ret = dataSyncManager_->TriggerStartSync(bundleName, callerUserId, false, SyncTriggerType::CLOUD_TRIGGER); + LOGI("End NotifyDataChange"); + return E_OK; +} + +int32_t CloudSyncService::NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) +{ + LOGI("Begin NotifyEventChange"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC_MANAGER, true)); + + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + return E_NULLPTR; + } + + string appBundleName; + string prepareTraceId; + auto ret = instance->ResolveNotificationEvent(userId, extraData, appBundleName, prepareTraceId); + if (ret != E_OK) { + LOGE("ResolveNotificationEvent failed, ret:%{public}d", ret); + return E_CLOUD_SDK; + } + + std::thread([this, appBundleName, userId, prepareTraceId]() { + dataSyncManager_->TriggerStartSync(appBundleName, userId, false, SyncTriggerType::CLOUD_TRIGGER, + prepareTraceId); + }).detach(); + LOGI("End NotifyEventChange"); + return E_OK; +} + +int32_t CloudSyncService::DisableCloud(const std::string &accoutId) +{ + LOGI("Begin DisableCloud"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC_MANAGER, true)); + + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + system::SetParameter(CLOUDSYNC_STATUS_KEY, CLOUDSYNC_STATUS_LOGOUT); + int32_t ret = dataSyncManager_->DisableCloud(callerUserId); + LOGI("End DisableCloud"); + return E_OK; +} + +int32_t CloudSyncService::EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) +{ + LOGI("Begin EnableCloud"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC_MANAGER, true)); + LOGI("End EnableCloud"); + return E_OK; +} + +int32_t CloudSyncService::Clean(const std::string &accountId, const CleanOptions &cleanOptions) +{ + LOGI("Begin Clean"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC_MANAGER, true)); + + for (auto &iter : cleanOptions.appActionsData) { + LOGD("Clean key is: %s, value is: %d", iter.first.c_str(), iter.second); + } + + MetaFileMgr::GetInstance().ClearAll(); + MetaFileMgr::GetInstance().CloudDiskClearAll(); + auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + LOGI("Clean callerUserId is: %{public}d", callerUserId); + for (auto iter = cleanOptions.appActionsData.begin(); iter != cleanOptions.appActionsData.end(); ++iter) { + dataSyncManager_->CleanCloudFile(callerUserId, iter->first, iter->second); + } + LOGI("End Clean"); + return E_OK; +} + +int32_t CloudSyncService::StartFileCache(const std::vector &uriVec, + int64_t &downloadId, + int32_t fieldkey, + bool isCallbackValid, + const sptr &downloadCallback, + int32_t timeout) +{ + LOGI("Begin StartFileCache"); + if (!DfsuAccessTokenHelper::CheckCallerPermission(PERM_AUTH_URI)) { + for (auto &uri : uriVec) { + if (!DfsuAccessTokenHelper::CheckUriPermission(uri)) { + LOGE("permission denied"); + return E_PERMISSION_DENIED; + } + } + } + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + LOGE("GetBundleNameUserInfo failed."); + return ret; + } + + sptr downloadCb = nullptr; + if (isCallbackValid) { + downloadCb = iface_cast(downloadCallback); + } + ret = dataSyncManager_->StartDownloadFile(bundleNameUserInfo, uriVec, downloadId, fieldkey, downloadCb, timeout); + if (ret != E_OK && ret != E_INVAL_ARG) { + ret = E_BROKEN_IPC; + } + LOGI("End StartFileCache"); + return ret; +} + +int32_t CloudSyncService::StartDownloadFile(const std::string &path) +{ + LOGI("Begin StartDownloadFile"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + std::vector pathVec; + pathVec.push_back(path); + int64_t downloadId = 0; + ret = dataSyncManager_->StartDownloadFile(bundleNameUserInfo, pathVec, downloadId, CloudSync::FIELDKEY_CONTENT, + nullptr); + LOGI("End StartDownloadFile"); + return ret; +} + +int32_t CloudSyncService::StopDownloadFile(const std::string &path, bool needClean) +{ + LOGI("Begin StopDownloadFile"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + + ret = dataSyncManager_->StopDownloadFile(bundleNameUserInfo, path, needClean); + LOGI("End StopDownloadFile"); + return ret; +} + +int32_t CloudSyncService::StopFileCache(int64_t downloadId, bool needClean, int32_t timeout) +{ + LOGI("Begin StopFileCache"); + RETURN_ON_ERR(CheckPermissions(PERM_AUTH_URI, false)); + + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + + ret = dataSyncManager_->StopFileCache(bundleNameUserInfo, downloadId, needClean, timeout); + if (ret != E_OK && ret != E_INVAL_ARG) { + ret = E_BROKEN_IPC; + } + LOGI("End StopFileCache"); + return ret; +} + +int32_t CloudSyncService::DownloadThumb() +{ + LOGI("Begin DownloadThumb"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + int32_t ret = dataSyncManager_->TriggerDownloadThumb(); + LOGI("End DownloadThumb"); + return ret; +} + +int32_t CloudSyncService::RegisterDownloadFileCallback(const sptr &downloadCallback) +{ + LOGI("Begin RegisterDownloadFileCallback"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + auto downloadCb = iface_cast(downloadCallback); + ret = dataSyncManager_->RegisterDownloadFileCallback(bundleNameUserInfo, downloadCb); + LOGI("End RegisterDownloadFileCallback"); + return ret; +} + +int32_t CloudSyncService::RegisterFileCacheCallback(const sptr &downloadCallback) +{ + LOGI("Begin RegisterDownloadFileCallback"); + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + auto downloadCb = iface_cast(downloadCallback); + ret = dataSyncManager_->RegisterDownloadFileCallback(bundleNameUserInfo, downloadCb); + LOGI("End RegisterDownloadFileCallback"); + return ret; +} + +int32_t CloudSyncService::UnregisterDownloadFileCallback() +{ + LOGI("Begin UnregisterDownloadFileCallback"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + + ret = dataSyncManager_->UnregisterDownloadFileCallback(bundleNameUserInfo); + LOGI("End UnregisterDownloadFileCallback"); + return ret; +} + +int32_t CloudSyncService::UnregisterFileCacheCallback() +{ + LOGI("Begin UnregisterFileCacheCallback"); + BundleNameUserInfo bundleNameUserInfo; + int ret = GetBundleNameUserInfo(bundleNameUserInfo); + if (ret != E_OK) { + return ret; + } + + ret = dataSyncManager_->UnregisterDownloadFileCallback(bundleNameUserInfo); + LOGI("End UnregisterFileCacheCallback"); + return ret; +} + +int32_t CloudSyncService::UploadAsset(const int32_t userId, const std::string &request, std::string &result) +{ + LOGI("Begin UploadAsset"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + return E_NULLPTR; + } + + string bundleName("distributeddata"); + TaskStateManager::GetInstance().StartTask(bundleName, TaskType::UPLOAD_ASSET_TASK); + auto ret = instance->OnUploadAsset(userId, request, result); + TaskStateManager::GetInstance().CompleteTask(bundleName, TaskType::UPLOAD_ASSET_TASK); + LOGI("End UploadAsset"); + return ret; +} + +int32_t CloudSyncService::DownloadFile(const int32_t userId, + const std::string &bundleName, + const AssetInfoObj &assetInfoObj) +{ + LOGI("Begin DownloadFile"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + return E_NULLPTR; + } + + auto assetsDownloader = instance->GetCloudAssetsDownloader(userId, bundleName); + if (assetsDownloader == nullptr) { + LOGE("get asset downloader failed"); + return E_NULLPTR; + } + + Asset asset; + asset.assetName = assetInfoObj.assetName; + + asset.uri = GetHmdfsPath(assetInfoObj.uri, userId); + if (asset.uri.empty()) { + LOGE("fail to get download path from %{public}s", GetAnonyString(assetInfoObj.uri).c_str()); + return E_INVAL_ARG; + } + + // Not to pass the assetinfo.fieldkey + DownloadAssetInfo assetsToDownload{assetInfoObj.recordType, assetInfoObj.recordId, {}, asset, {}}; + TaskStateManager::GetInstance().StartTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK); + auto ret = assetsDownloader->DownloadAssets(assetsToDownload); + TaskStateManager::GetInstance().CompleteTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK); + LOGI("End DownloadFile"); + return ret; +} + +int32_t CloudSyncService::DownloadFiles(const int32_t userId, + const std::string &bundleName, + const std::vector &assetInfoObj, + std::vector &assetResultMap) +{ + LOGI("Begin DownloadFiles"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + auto instance = CloudFile::CloudFileKit::GetInstance(); + if (instance == nullptr) { + LOGE("get cloud file helper instance failed"); + return E_NULLPTR; + } + + auto assetsDownloader = instance->GetCloudAssetsDownloader(userId, bundleName); + if (assetsDownloader == nullptr) { + LOGE("get asset downloader failed"); + return E_NULLPTR; + } + + std::vector assetsToDownload; + for (const auto &obj : assetInfoObj) { + Asset asset; + asset.assetName = obj.assetName; + asset.uri = GetHmdfsPath(obj.uri, userId); + if (asset.uri.empty()) { + LOGE("fail to get download path from %{private}s", GetAnonyString(obj.uri).c_str()); + return E_INVAL_ARG; + } + DownloadAssetInfo assetToDownload{obj.recordType, obj.recordId, {}, asset, {}}; + assetsToDownload.emplace_back(assetToDownload); + } + + TaskStateManager::GetInstance().StartTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK); + auto ret = assetsDownloader->DownloadAssets(assetsToDownload, assetResultMap); + TaskStateManager::GetInstance().CompleteTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK); + LOGI("End DownloadFiles"); + return ret; +} + +int32_t CloudSyncService::DownloadAsset(const uint64_t taskId, + const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + const AssetInfoObj &assetInfoObj) +{ + LOGI("Begin DownloadAsset"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + if (networkId == "edge2cloud") { + LOGE("now not support"); + return E_INVAL_ARG; + } + // Load sa for remote device + if (LoadRemoteSA(networkId) != E_OK) { // maybe need to convert deviceId + return E_SA_LOAD_FAILED; + } + + string uri = assetInfoObj.uri; + fileTransferManager_->DownloadFileFromRemoteDevice(networkId, userId, taskId, uri); + LOGI("End DownloadAsset"); + return E_OK; +} + +int32_t CloudSyncService::RegisterDownloadAssetCallback(const sptr &remoteObject) +{ + LOGI("Begin RegisterDownloadAssetCallback"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + if (remoteObject == nullptr) { + LOGE("remoteObject is nullptr"); + return E_INVAL_ARG; + } + auto callback = iface_cast(remoteObject); + DownloadAssetCallbackManager::GetInstance().AddCallback(callback); + LOGI("End RegisterDownloadAssetCallback"); + return E_OK; +} + +int32_t CloudSyncService::DeleteAsset(const int32_t userId, const std::string &uri) +{ + LOGI("Begin DeleteAsset"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + std::string physicalPath = ""; + int ret = AppFileService::SandboxHelper::GetPhysicalPath(uri, std::to_string(userId), physicalPath); + if (ret != 0 || !AppFileService::SandboxHelper::IsValidPath(physicalPath)) { + LOGE("Get physical path failed with %{public}d", ret); + return E_GET_PHYSICAL_PATH_FAILED; + } + + LOGD("delete assert, path %{public}s", GetAnonyString(physicalPath).c_str()); + + ret = unlink(physicalPath.c_str()); + if (ret != 0) { + LOGE("fail to delete asset, errno %{public}d", errno); + return E_DELETE_FAILED; + } + LOGI("End DeleteAsset"); + return E_OK; +} + +int32_t CloudSyncService::BatchCleanFile(const std::vector &fileInfo, + std::vector &failCloudId) +{ + LOGI("Begin BatchCleanFile"); + RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC, true)); + + std::vector cleanFilesInfo; + for (const auto &obj : fileInfo) { + CleanFileInfo tmpFileInfo{obj.cloudId, obj.size, obj.modifiedTime, obj.path, obj.fileName, obj.attachment}; + cleanFilesInfo.emplace_back(tmpFileInfo); + } + + int32_t ret = dataSyncManager_->BatchCleanFile(cleanFilesInfo, failCloudId); + LOGI("End BatchCleanFile"); + return ret; +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/services/cloudsyncservice/src/ipc/download_asset_callback_manager.cpp b/cloud_file/services/cloudsyncservice/src/ipc/download_asset_callback_manager.cpp new file mode 100644 index 0000000..ae68271 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/ipc/download_asset_callback_manager.cpp @@ -0,0 +1,56 @@ +/* + * 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 "ipc/download_asset_callback_manager.h" + +#include + +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +DownloadAssetCallbackManager &DownloadAssetCallbackManager::GetInstance() +{ + static DownloadAssetCallbackManager instance; + return instance; +} + +void DownloadAssetCallbackManager::AddCallback(const sptr &callback) +{ + if (callback == nullptr) { + return; + } + callbackProxy_ = callback; + auto remoteObject = callback->AsObject(); + auto deathCb = [this](const wptr &obj) { + callbackProxy_ = nullptr; + LOGE("client died"); + }; + deathRecipient_ = sptr(new SvcDeathRecipient(deathCb)); + remoteObject->AddDeathRecipient(deathRecipient_); +} + +void DownloadAssetCallbackManager::OnDownloadFinshed(const TaskId taskId, const std::string &uri, const int32_t result) +{ + auto callback = callbackProxy_; + if (callback == nullptr) { + LOGE("callbackProxy_ is nullptr"); + return; + } + LOGD("On Download finished, taskId:%{public}" PRIu64 ", uri:%{public}s, ret:%{public}d", + taskId, GetAnonyString(uri).c_str(), result); + callback->OnFinished(taskId, uri, result); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/ipc/download_asset_callback_proxy.cpp b/cloud_file/services/cloudsyncservice/src/ipc/download_asset_callback_proxy.cpp new file mode 100644 index 0000000..80e9c0b --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/ipc/download_asset_callback_proxy.cpp @@ -0,0 +1,64 @@ +/* + * 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 "ipc/download_asset_callback_proxy.h" + +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +void DownloadAssetCallbackProxy::OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) +{ + LOGI("Start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(GetDescriptor())) { + LOGE("Failed to write interface token"); + return; + } + + if (!data.WriteUint64(taskId)) { + LOGE("Failed to send the uri"); + return; + } + + if (!data.WriteString(uri)) { + LOGE("Failed to send the uri"); + return; + } + + if (!data.WriteInt32(result)) { + LOGE("Failed to send the state"); + return; + } + + auto remote = Remote(); + if (!remote) { + LOGE("remote is nullptr"); + return; + } + int32_t ret = remote->SendRequest(IDownloadAssetCallback::SERVICE_CMD_ON_DOWNLOAD_FINSHED, data, reply, option); + if (ret != E_OK) { + LOGE("Failed to send out the requeset, ret:%{public}d", ret); + return; + } + LOGI("End"); + return; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp b/cloud_file/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp new file mode 100644 index 0000000..c2df4bc --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp @@ -0,0 +1,98 @@ +/* + * 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 "sync_rule/battery_status_listener.h" + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "battery_status.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { + +BatteryStatusSubscriber::BatteryStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + std::shared_ptr listener) + : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) +{ +} + +void BatteryStatusSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + auto action = eventData.GetWant().GetAction(); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_OKAY) { + LOGI("Battery status changed: BATTERY_STATUS_OKAY"); + listener_->OnStatusNormal(); + return; + } + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING) { + LOGI("Charging status changed: charging"); + BatteryStatus::SetChargingStatus(true); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING) { + BatteryStatus::SetChargingStatus(false); + LOGI("Charging status changed: discharging"); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) { + listener_->OnPowerConnected(); + } else { + LOGI("OnReceiveEvent action is invalid"); + } +} + +BatteryStatusListener::BatteryStatusListener(std::shared_ptr dataSyncManager) +{ + dataSyncManager_ = dataSyncManager; +} + +BatteryStatusListener::~BatteryStatusListener() +{ + Stop(); +} + +void BatteryStatusListener::Start() +{ + /* subscribe Battery Okay Status and Charging status */ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_OKAY); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + EventFwk::CommonEventSubscribeInfo info(matchingSkills); + commonEventSubscriber_ = std::make_shared(info, shared_from_this()); + auto subRet = EventFwk::CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); + LOGI("Subscriber end, SubscribeResult = %{public}d", subRet); +} + +void BatteryStatusListener::Stop() +{ + if (commonEventSubscriber_ != nullptr) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(commonEventSubscriber_); + commonEventSubscriber_ = nullptr; + } +} + +void BatteryStatusListener::OnStatusNormal() +{ + dataSyncManager_->TriggerRecoverySync(triggerType_); + dataSyncManager_->TriggerDownloadThumb(); + LOGI("battery status OK"); +} + +void BatteryStatusListener::OnStatusAbnormal() {} + +void BatteryStatusListener::OnPowerConnected() +{ + dataSyncManager_->DownloadThumb(); + dataSyncManager_->CacheVideo(); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/sync_rule/package_status_listener.cpp b/cloud_file/services/cloudsyncservice/src/sync_rule/package_status_listener.cpp new file mode 100644 index 0000000..47756db --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/sync_rule/package_status_listener.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2025 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 "sync_rule/package_status_listener.h" + +#include "cloud_status.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "data_syncer_rdb_store.h" +#include "result_set.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +constexpr int32_t BASE_USER_RANGE = 200000; + +PackageStatusSubscriber::PackageStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + std::shared_ptr listener) + : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) +{ +} + +void PackageStatusSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + auto action = eventData.GetWant().GetAction(); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + auto bundleName = eventData.GetWant().GetBundle(); + std::string userIdKey = "uid"; + auto userId = eventData.GetWant().GetIntParam(userIdKey.c_str(), -1); + if (userId < 0) { + LOGE("Get UserId Failed!"); + return; + } + userId = userId / BASE_USER_RANGE; + listener_->RemovedClean(bundleName, userId); + } +} + +PackageStatusListener::PackageStatusListener(std::shared_ptr dataSyncManager) +{ + dataSyncManager_ = dataSyncManager; +} + +PackageStatusListener::~PackageStatusListener() +{ + Stop(); +} + +void PackageStatusListener::RemovedClean(const std::string &bundleName, const int32_t userId) +{ + LOGI("RemovedClean Start"); + if (!IsCloudSyncOn(userId, bundleName)) { + LOGI("Cloud Sync is Off"); + return; + } + int ret = CloudStatus::ChangeAppSwitch(bundleName, userId, false); + if (ret != 0) { + LOGE("CloudStatus ChangeAppSwitch failed, ret: %{public}d", ret); + return; + } + ret = dataSyncManager_->TriggerStopSync(bundleName, userId, false, SyncTriggerType::CLOUD_TRIGGER); + if (ret != 0) { + LOGE("DataSyncerManager Trigger Stopsync failed, ret: %{public}d", ret); + return; + } + ret = dataSyncManager_->ChangeAppSwitch(bundleName, userId, false); + if (ret != 0) { + LOGE("DataSyncerManager ChangeAppSwitch failed, ret: %{public}d", ret); + return; + } + ret = dataSyncManager_->CleanCloudFile(userId, bundleName, CLEAR_DATA); + if (ret != 0) { + LOGE("CleanCloudFile failed, ret: %{public}d", ret); + return; + } + LOGI("RemovedClean Complete"); +} + +void PackageStatusListener::Start() +{ + /* subscribe Package Removed Status */ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + EventFwk::CommonEventSubscribeInfo info(matchingSkills); + commonEventSubscriber_ = std::make_shared(info, shared_from_this()); + auto subRet = EventFwk::CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); + LOGI("PackageStatusSubscirber SubscribeResult = %{public}d", subRet); +} + +void PackageStatusListener::Stop() +{ + if (commonEventSubscriber_ != nullptr) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(commonEventSubscriber_); + commonEventSubscriber_ = nullptr; + } +} + +bool PackageStatusListener::IsCloudSyncOn(const int32_t userId, const std::string &bundleName) +{ + std::shared_ptr resultSet; + int32_t ret = DataSyncerRdbStore::GetInstance().QueryCloudSync(userId, bundleName, resultSet); + if (ret != 0 || resultSet == nullptr) { + LOGE("DataSyncerRdbStore Query failed!"); + return false; + } + int rowCount = 0; + ret = resultSet->GetRowCount(rowCount); + if (ret != 0 || rowCount < 0) { + LOGE("Get Row Count failed, ret: %{public}d, rowCount: %{public}d", ret, rowCount); + return false; + } + return rowCount == 1; +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp b/cloud_file/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp new file mode 100644 index 0000000..38077cb --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp @@ -0,0 +1,81 @@ +/* + * 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 "sync_rule/screen_status_listener.h" + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "screen_status.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +ScreenStatusSubscriber::ScreenStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + std::shared_ptr listener) + : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) +{ +} +void ScreenStatusSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + auto action = eventData.GetWant().GetAction(); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON) { + LOGI("Screen On!"); + ScreenStatus::SetScreenState(ScreenStatus::ScreenState::SCREEN_ON); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) { + LOGI("Screen Off!"); + ScreenStatus::SetScreenState(ScreenStatus::ScreenState::SCREEN_OFF); + listener_->ScreenOff(); + } +} + +ScreenStatusListener::ScreenStatusListener(std::shared_ptr dataSyncManager) +{ + dataSyncManager_ = dataSyncManager; +} + +ScreenStatusListener::~ScreenStatusListener() +{ + Stop(); +} + +void ScreenStatusListener::ScreenOff() +{ + dataSyncManager_->DownloadThumb(); + dataSyncManager_->CacheVideo(); +} + +void ScreenStatusListener::Start() +{ + /* subscribe Battery Okay Status and Charging status */ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF); + EventFwk::CommonEventSubscribeInfo info(matchingSkills); + commonEventSubscriber_ = std::make_shared(info, shared_from_this()); + auto subRet = EventFwk::CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); + LOGI("Subscriber end, SubscribeResult = %{public}d", subRet); +} + +void ScreenStatusListener::Stop() +{ + if (commonEventSubscriber_ != nullptr) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(commonEventSubscriber_); + commonEventSubscriber_ = nullptr; + } +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/sync_rule/user_status_listener.cpp b/cloud_file/services/cloudsyncservice/src/sync_rule/user_status_listener.cpp new file mode 100644 index 0000000..af36303 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/sync_rule/user_status_listener.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2024 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 "sync_rule/user_status_listener.h" + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "iservice_registry.h" +#include "parameters.h" +#include "system_ability_definition.h" +#include "task_state_manager.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { + +UserStatusSubscriber::UserStatusSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, + std::shared_ptr listener) : EventFwk::CommonEventSubscriber(subscribeInfo), listener_(listener) +{ +} + +void UserStatusSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + auto action = eventData.GetWant().GetAction(); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED) { + LOGI("user unlocked"); + listener_->NotifyUserUnlocked(); + return; + } + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { + LOGI("account logout"); + listener_->DoCleanVideoCache(); + return; + } + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_STOPPING) { + LOGI("account stopping"); + listener_->DoUnloadSA(); + return; + } +} + +UserStatusListener::UserStatusListener(std::shared_ptr dataSyncManager) +{ + dataSyncManager_ = dataSyncManager; +} + +UserStatusListener::~UserStatusListener() +{ + Stop(); +} + +void UserStatusListener::AddObserver(std::shared_ptr observer) +{ + std::lock_guard lck(obsVecMutex_); + observers_.push_back(observer); +} + +void UserStatusListener::NotifyUserUnlocked() +{ + std::lock_guard lck(obsVecMutex_); + for (auto &observer : observers_) { + observer->OnUserUnlocked(); + } +} + +void UserStatusListener::Start() +{ + /* subscribe user unlock event */ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_STOPPING); + EventFwk::CommonEventSubscribeInfo info(matchingSkills); + commonEventSubscriber_ = std::make_shared(info, shared_from_this()); + auto subRet = EventFwk::CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); + LOGI("Subscriber end, SubscribeResult = %{public}d", subRet); +} + +void UserStatusListener::Stop() +{ + if (commonEventSubscriber_ != nullptr) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(commonEventSubscriber_); + commonEventSubscriber_ = nullptr; + } +} + +void UserStatusListener::DoCleanVideoCache() +{ + dataSyncManager_->CleanVideoCache(); +} + +void UserStatusListener::DoUnloadSA() +{ + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("get samgr failed"); + return; + } + system::SetParameter(CLOUD_FILE_SERVICE_SA_STATUS_FLAG, CLOUD_FILE_SERVICE_SA_END); + int32_t ret = samgrProxy->UnloadSystemAbility(FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID); + if (ret != ERR_OK) { + LOGE("remove system ability failed"); + return; + } + LOGI("unload cloudfileservice end"); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/transport/file_transfer_manager.cpp b/cloud_file/services/cloudsyncservice/src/transport/file_transfer_manager.cpp new file mode 100644 index 0000000..d74c251 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/transport/file_transfer_manager.cpp @@ -0,0 +1,270 @@ +/* + * 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 "file_transfer_manager.h" + +#include +#include + +#include "dfs_error.h" +#include "ipc/download_asset_callback_manager.h" +#include "sandbox_helper.h" +#include "task_state_manager.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +static const string CALLER_NAME = "distributeddata"; + +FileTransferManager::FileTransferManager(std::shared_ptr sessionManager) + : sessionManager_(sessionManager) +{ +} + +void FileTransferManager::Init() +{ + sessionManager_->RegisterDataHandler(shared_from_this()); +} + +void FileTransferManager::DownloadFileFromRemoteDevice(const std::string &networkId, + const int32_t userId, + const uint64_t taskId, + const std::string &uri) +{ + IncTransTaskCount(); + MessageInputInfo info = {.srcNetworkId = "", + .dstNetworkId = networkId, + .uri = uri, + .msgType = MSG_DOWNLOAD_FILE_REQ, + .errorCode = 0, + .userId = userId, + .taskId = taskId}; + MessageHandler msgHandler(info); + uint32_t dataLen = msgHandler.GetDataSize(); + auto data = make_unique(dataLen); + msgHandler.PackData(data.get(), dataLen); + LOGI("send data, dataLen:%{public}d, taskId: %{public}" PRIu64 "", dataLen, taskId); + auto ret = sessionManager_->SendData(networkId, data.get(), dataLen); + if (ret != E_OK) { + LOGE("download file failed, uri:%{public}s, ret:%{public}d", GetAnonyString(uri).c_str(), ret); + DownloadAssetCallbackManager::GetInstance().OnDownloadFinshed(taskId, uri, ret); + DecTransTaskCount(); + } else { + AddTransTask(uri, userId, taskId); + } +} + +void FileTransferManager::HandleDownloadFileRequest(MessageHandler &msgHandler, + const std::string &senderNetworkId, + int receiverSessionId) +{ + IncTransTaskCount(); + auto uri = msgHandler.GetUri(); + auto userId = msgHandler.GetUserId(); + auto [physicalPath, relativePath] = UriToPath(uri, userId); + uint32_t errorCode = E_OK; + if (!relativePath.empty()) { + auto result = sessionManager_->SendFile(senderNetworkId, {physicalPath}, {relativePath}); + if (result != E_OK) { + LOGE("send file failed, relativePath:%{public}s, ret:%{public}d", + GetAnonyString(relativePath).c_str(), result); + errorCode = E_SEND_FILE; + DecTransTaskCount(); + } + } else { + errorCode = E_FILE_NOT_EXIST; + DecTransTaskCount(); + } + auto taskId = msgHandler.GetTaskId(); + MessageInputInfo info = {.srcNetworkId = "", + .dstNetworkId = senderNetworkId, + .uri = uri, + .msgType = MSG_DOWNLOAD_FILE_RSP, + .errorCode = errorCode, + .userId = userId, + .taskId = taskId}; + MessageHandler resp(info); + uint32_t dataLen = resp.GetDataSize(); + auto data = make_unique(dataLen); + resp.PackData(data.get(), dataLen); + auto ret = sessionManager_->SendData(receiverSessionId, data.get(), dataLen); + if (ret != E_OK) { + LOGE("response failed: %{public}d, sessionId:%{public}d", ret, receiverSessionId); + } + LOGD("send response, sessionId:%{public}d", receiverSessionId); +} + +void FileTransferManager::HandleDownloadFileResponse(MessageHandler &msgHandler) +{ + LOGD("recviceve response msg"); + auto errorCode = msgHandler.GetErrorCode(); + if (errorCode == E_OK) { + LOGD("callback after file recv finished"); + return; + } + auto uri = msgHandler.GetUri(); + auto taskId = msgHandler.GetTaskId(); + DownloadAssetCallbackManager::GetInstance().OnDownloadFinshed(taskId, uri, errorCode); + DecTransTaskCount(); + RemoveTransTask(taskId); +} + +void FileTransferManager::HandleRecvFileFinished() +{ + LOGI("file transfer finished"); + DecTransTaskCount(); // task finished, may be can unload sa +} + +void FileTransferManager::OnMessageHandle(const std::string &senderNetworkId, + int receiverSessionId, + const void *data, + unsigned int dataLen) +{ + MessageHandler msgHandler; + bool ret = msgHandler.UnPackData((uint8_t *)data, dataLen); + if (!ret) { + LOGE("package data invalid"); + return; + } + auto msgType = msgHandler.GetMsgType(); + if (msgType == MSG_DOWNLOAD_FILE_REQ) { + HandleDownloadFileRequest(msgHandler, senderNetworkId, receiverSessionId); + } else if (msgType == MSG_DOWNLOAD_FILE_RSP) { + HandleDownloadFileResponse(msgHandler); + } else if (msgType == MSG_FINISH_FILE_RECV) { + HandleRecvFileFinished(); + } else { + LOGE("error msg type:%{public}d", msgType); + } +} + +void FileTransferManager::OnFileRecvHandle(const std::string &senderNetworkId, const char *filePath, int result) +{ + LOGE("received file, file path:%{public}s, result:%{public}d", GetAnonyString(filePath).c_str(), result); + DecTransTaskCount(); // allways dec task count when finsh one task + if (filePath != nullptr) { + FinishTransTask(string(filePath), result); + } + + MessageInputInfo info = {.msgType = MSG_FINISH_FILE_RECV}; + MessageHandler req(info); + uint32_t dataLen = req.GetDataSize(); + auto data = make_unique(dataLen); + req.PackData(data.get(), dataLen); + auto ret = sessionManager_->SendData(senderNetworkId, data.get(), dataLen); + if (ret != E_OK) { + LOGE("response failed: %{public}d", ret); + } + LOGI("send file recv finished msg"); +} + +void FileTransferManager::OnSessionClosed() // avoid sa cannot unload when session disconnect +{ + taskCount_.store(0); + TaskStateManager::GetInstance().CompleteTask(CALLER_NAME, TaskType::DOWNLOAD_REMOTE_ASSET_TASK); +} + +bool FileTransferManager::IsFileExists(const std::string &filePath) +{ + if (access(filePath.c_str(), F_OK) != E_OK) { + LOGE("file is not exist, path:%{public}s, error:%{public}s", GetAnonyString(filePath).c_str(), strerror(errno)); + return false; + } + return true; +} + +std::tuple FileTransferManager::UriToPath(const std::string &uri, + const int32_t userId, + bool isCheckFileExists) +{ + string physicalPath = ""; + int ret = AppFileService::SandboxHelper::GetPhysicalPath(uri, std::to_string(userId), physicalPath); + if (ret != 0 || !AppFileService::SandboxHelper::IsValidPath(physicalPath)) { + LOGE("Get physical path failed with %{public}d", ret); + return {"", ""}; + } + + if (isCheckFileExists) { + if (!this->IsFileExists(physicalPath)) { + return {"", ""}; + } + } + + const string HMDFS_DIR = "/mnt/hmdfs/"; + const string DATA_DIR = HMDFS_DIR + to_string(userId) + "/account/device_view/local/data"; + + std::string relativePath; + size_t fileDirPos = physicalPath.find(DATA_DIR); + if (fileDirPos == std::string::npos) { + return {"", ""}; + } + fileDirPos += DATA_DIR.length(); + relativePath = physicalPath.substr(fileDirPos); + + return {physicalPath, relativePath}; +} + +void FileTransferManager::AddTransTask(const std::string &uri, const int32_t userId, uint64_t taskId) +{ + lock_guard lock(taskMutex_); + auto [physicalPath, relativePath] = UriToPath(uri, userId, false); + TaskInfo info = {uri, relativePath, taskId}; + taskInfos_.push_back(info); +} + +void FileTransferManager::RemoveTransTask(uint64_t taskId) +{ + LOGI("remove task:%{public}" PRIu64 "", taskId); + lock_guard lock(taskMutex_); + for (auto iter = taskInfos_.begin(); iter != taskInfos_.end();) { + if ((*iter).taskId == taskId) { + iter = taskInfos_.erase(iter); + } else { + ++iter; + } + } +} + +void FileTransferManager::FinishTransTask(const std::string &relativePath, int result) +{ + lock_guard lock(taskMutex_); + for (auto iter = taskInfos_.begin(); iter != taskInfos_.end();) { + if ((*iter).relativePath == relativePath) { + DownloadAssetCallbackManager::GetInstance().OnDownloadFinshed((*iter).taskId, (*iter).uri, result); + iter = taskInfos_.erase(iter); + return; // match the first one + } else { + ++iter; + } + } + LOGE("not found task, relativePath:%{public}s", GetAnonyString(relativePath).c_str()); +} + +void FileTransferManager::IncTransTaskCount() +{ + TaskStateManager::GetInstance().StartTask(CALLER_NAME, TaskType::DOWNLOAD_REMOTE_ASSET_TASK); + taskCount_.fetch_add(1); +} + +void FileTransferManager::DecTransTaskCount() +{ + auto count = taskCount_.fetch_sub(1); + if (count == 1) { + TaskStateManager::GetInstance().CompleteTask(CALLER_NAME, TaskType::DOWNLOAD_REMOTE_ASSET_TASK); + } else if (count < 1) { + taskCount_.store(0); + } +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/services/cloudsyncservice/src/transport/message_handler.cpp b/cloud_file/services/cloudsyncservice/src/transport/message_handler.cpp new file mode 100644 index 0000000..869c5df --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/transport/message_handler.cpp @@ -0,0 +1,177 @@ +/* + * 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 "message_handler.h" + +#include +#include + +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +constexpr uint8_t MSG_MAGIC = 0xF8; +constexpr uint8_t VERSION = 0x1; +constexpr int8_t ALIGN_WIDH = 8; +MessageHandler::MessageHandler(MessageInputInfo &info) + : srcNetworkId_(info.srcNetworkId), + dstNetworkId_(info.dstNetworkId), + uri_(info.uri), + userId_(info.userId), + taskId_(info.taskId) +{ + msgHdr_.msgType = info.msgType; + msgHdr_.errorCode = info.errorCode; + auto totalSize = sizeof(MessageHeader) + sizeof(SessionDeviceInfo) + sizeof(UserData) + uri_.size(); + dataSize_ = GET_ALIGNED_SIZE(totalSize, ALIGN_WIDH); +} + +bool MessageHandler::PackData(uint8_t *data, uint32_t totalLen) +{ + if (!data || totalLen < dataSize_) { + LOGE("Invalid param, totalLen:%{public}d, dataSize:%{public}d", totalLen, dataSize_); + return false; + } + + uint8_t *ptr = data; + MessageHeader *head = reinterpret_cast(ptr); + head->magic = MSG_MAGIC; + head->version = VERSION; + head->msgType = htole16(msgHdr_.msgType); + head->dataLen = htole32(totalLen - sizeof(MessageHeader)); + head->errorCode = static_cast(htole32(msgHdr_.errorCode)); + + ptr += sizeof(MessageHeader); + SessionDeviceInfo *deviceInfo = reinterpret_cast(ptr); + auto ret = strcpy_s(deviceInfo->sourceNetworkId, NETWORK_ID_SIZE_MAX, srcNetworkId_.c_str()); + if (ret != 0) { + LOGE("strcpy for source device id failed, ret is %{public}d", ret); + return false; + } + + ret = strcpy_s(deviceInfo->tartgeNetworkId, NETWORK_ID_SIZE_MAX, dstNetworkId_.c_str()); + if (ret != 0) { + LOGE("strcpy for source device id failed, ret is %{public}d", ret); + return false; + } + + ptr += sizeof(SessionDeviceInfo); + UserData *userData = reinterpret_cast(ptr); + userData->taskId = htole64(taskId_); + userData->userId = htole32(userId_); + userData->uriLen = htole32(uri_.size()); // not include '\0' + ptr += sizeof(UserData); + + uint8_t *end = data + totalLen; + ret = memcpy_s(userData->uri, end - ptr, uri_.c_str(), uri_.size()); + if (ret != 0) { + LOGE("memcpy failed, error:%{public}d", errno); + return false; + } + return true; +} + +bool MessageHandler::UnPackData(uint8_t *data, uint32_t totalLen) +{ + if (!data || totalLen < sizeof(MessageHeader)) { + LOGE("invalid input data, totalLen:%{public}d", totalLen); + return false; + } + + uint8_t *ptr = data; + uint32_t leftSize = totalLen; + MessageHeader *head = reinterpret_cast(ptr); + msgHdr_.magic = head->magic; + msgHdr_.version = head->version; + msgHdr_.msgType = le16toh(head->msgType); + msgHdr_.dataLen = le32toh(head->dataLen); + msgHdr_.errorCode = static_cast(le32toh(head->errorCode)); + if (msgHdr_.magic != MSG_MAGIC) { + LOGE("not valid data"); + return false; + } + + leftSize -= sizeof(MessageHeader); + if (leftSize < sizeof(SessionDeviceInfo)) { + LOGE("failed to parse sessionDeviceInfo, leftsize:%{public}d", leftSize); + return false; + } + ptr += sizeof(MessageHeader); + SessionDeviceInfo *deviceInfo = reinterpret_cast(ptr); + srcNetworkId_ = string(deviceInfo->sourceNetworkId, strnlen(deviceInfo->sourceNetworkId, NETWORK_ID_SIZE_MAX)); + dstNetworkId_ = string(deviceInfo->tartgeNetworkId, strnlen(deviceInfo->tartgeNetworkId, NETWORK_ID_SIZE_MAX)); + + leftSize -= sizeof(SessionDeviceInfo); + if (leftSize < sizeof(UserData)) { + LOGE("failed to parse UserData, leftsize:%{public}d", leftSize); + return false; + } + ptr += sizeof(SessionDeviceInfo); + UserData *userData = reinterpret_cast(ptr); + taskId_ = le64toh(userData->taskId); + userId_ = static_cast(le32toh(userData->userId)); + auto uriLen = userData->uriLen; + if (uriLen > PATH_MAX) { + LOGE("exception uriLen:%{public}d", uriLen); + return false; + } + uri_ = string(userData->uri, uriLen); + return true; +} + +uint32_t MessageHandler::GetDataSize() +{ + return dataSize_; +} + +void MessageHandler::GetMessageHeader(MessageHeader &header) +{ + header = msgHdr_; +} +uint64_t MessageHandler::GetTaskId() +{ + return taskId_; +} + +int32_t MessageHandler::GetUserId() +{ + return userId_; +} + +std::string MessageHandler::GetUri() +{ + return uri_; +} + +std::string MessageHandler::GetSrcNetworkId() +{ + return srcNetworkId_; +} + +std::string MessageHandler::GetDstNetworkId() +{ + return dstNetworkId_; +} + +uint16_t MessageHandler::GetMsgType() +{ + return msgHdr_.msgType; +} + +int32_t MessageHandler::GetErrorCode() +{ + return msgHdr_.errorCode; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/transport/softbus/session_manager.cpp b/cloud_file/services/cloudsyncservice/src/transport/softbus/session_manager.cpp new file mode 100644 index 0000000..160b510 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/transport/softbus/session_manager.cpp @@ -0,0 +1,205 @@ +/* + * 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 "session_manager.h" + +#include +#include + +#include "dfs_error.h" +#include "softbus_adapter.h" +#include "softbus_session.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +const string SERVICE_NAME = "OHOS.Filemanagement.Dfs.ICloudSyncService"; +/* need config softbus_trans_permission.json */ +const string SESSION_NAME = "DistributedFileService_edge2edge_Session"; + +SessionManager::~SessionManager() +{ + RemoveServer(); +} + +void SessionManager::Init() +{ + CreateServer(); +} + +void SessionManager::CreateServer() +{ + auto ret = SoftbusAdapter::GetInstance().CreateSessionServer(SERVICE_NAME.c_str(), SESSION_NAME.c_str()); + if (ret != E_OK) { + LOGE("create session server failed"); + return; + } + SoftbusAdapter::GetInstance().RegisterSessionListener(SESSION_NAME.c_str(), shared_from_this()); +} + +void SessionManager::OnUserUnlocked() +{ + if (SetFileRecvListenerFlag_) { + LOGI("file recive listener has been successfully set up"); + return; + } + /* setfileReceiveListener again when user unlocked to avoid register fall when user locked */ + LOGI("UserUnlocked, SetFileReceiveListener again"); +} + +void SessionManager::RemoveServer() +{ + auto ret = SoftbusAdapter::GetInstance().RemoveSessionServer(SERVICE_NAME.c_str(), SESSION_NAME.c_str()); + if (ret != E_OK) { + LOGE("create session server failed"); + return; + } + + SoftbusAdapter::GetInstance().UnRegisterSessionListener(SESSION_NAME.c_str()); +} + +int32_t SessionManager::SendData(int sessionId, const void *data, uint32_t dataLen) +{ + return SoftbusAdapter::GetInstance().SendBytes(sessionId, data, dataLen); +} + +int32_t SessionManager::SendData(const std::string &peerNetworkId, const void *data, uint32_t dataLen) +{ + auto sendSession = CreateSession(SoftbusSession::DataType::TYPE_BYTES, peerNetworkId); + if (sendSession == nullptr) { + return E_CREATE_SESSION; + } + return sendSession->SendData(data, dataLen); +} + +int32_t SessionManager::SendFile(const std::string &peerNetworkId, + const std::vector &sFileList, + const std::vector &dFileList) +{ + auto sendSession = CreateSession(SoftbusSession::DataType::TYPE_FILE, peerNetworkId); + if (sendSession == nullptr) { + return E_CREATE_SESSION; + } + return sendSession->SendFile(sFileList, dFileList); +} + +std::shared_ptr SessionManager::CreateSession(SoftbusSession::DataType type, + const std::string &peerDeviceId) +{ + if (!IsDeviceIdVailid(peerDeviceId)) { + LOGE("peer DeviceId is Invalid"); + return nullptr; + } + + lock_guard lock(sessionVecMutex_); + for (auto session : sendSessionVec_) { + if ((session->GetDataType() == type) && (session->GetPeerDeviceId() == peerDeviceId)) { + return session; + } + } + + auto sendSession = make_shared(peerDeviceId, SESSION_NAME.c_str(), type); + auto ret = sendSession->Start(); + if (ret != E_OK) { + LOGE("create session failed"); + return nullptr; + } + + CacheSendSession(sendSession); + return sendSession; +} + +bool SessionManager::IsDeviceIdVailid(const std::string &peerDeviceId) +{ + return true; +} + +void SessionManager::ReleaseSession(SoftbusSession::DataType type, const std::string &peerDeviceId) +{ + auto sendSession = GetSendSession(type, peerDeviceId); + if (sendSession == nullptr) { + LOGE("session not exist"); + return; + } + + sendSession->Stop(); +} + +void SessionManager::OnSessionOpened(int socket, int result) +{ + if (result != E_OK) { + LOGE("OnSessionOpened failed:%{public}d", result); + } +} + +void SessionManager::OnSessionClosed(int32_t socket) +{ + RemoveSendSession(socket); + if (dataHandler_ != nullptr) { + dataHandler_->OnSessionClosed(); + } +} + +void SessionManager::OnDataReceived(const std::string &senderNetworkId, + int receiverSessionId, + const void *data, + unsigned int dataLen) +{ + if (dataHandler_ != nullptr) { + dataHandler_->OnMessageHandle(senderNetworkId, receiverSessionId, data, dataLen); + } +} + +void SessionManager::OnFileReceived(const std::string &senderNetworkId, const char *filePath, int result) +{ + if (dataHandler_ != nullptr) { + dataHandler_->OnFileRecvHandle(senderNetworkId, filePath, result); + } +} + +void SessionManager::RegisterDataHandler(std::shared_ptr handler) +{ + dataHandler_ = handler; +} + +std::shared_ptr SessionManager::GetSendSession(SoftbusSession::DataType type, + const std::string &peerDeviceId) +{ + lock_guard lock(sessionVecMutex_); + for (auto session : sendSessionVec_) { + if ((session->GetDataType() == type) && (session->GetPeerDeviceId() == peerDeviceId)) { + return session; + } + } + return nullptr; +} + +void SessionManager::CacheSendSession(std::shared_ptr session) +{ + sendSessionVec_.push_back(session); +} + +void SessionManager::RemoveSendSession(int sessionId) +{ + lock_guard lock(sessionVecMutex_); + for (auto iter = sendSessionVec_.begin(); iter != sendSessionVec_.end();) { + if ((*iter)->GetSessionId() == sessionId) { + iter = sendSessionVec_.erase(iter); + } else { + ++iter; + } + } +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/transport/softbus/softbus_adapter.cpp b/cloud_file/services/cloudsyncservice/src/transport/softbus/softbus_adapter.cpp new file mode 100644 index 0000000..5c55fa6 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/transport/softbus/softbus_adapter.cpp @@ -0,0 +1,395 @@ +/* + * 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 "softbus_adapter.h" + +#include +#include +#include + +#include "dfs_error.h" +#include "utils_log.h" + + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +constexpr int MIN_BW = 1024 * 1024 * 40; +constexpr int MAX_WAIT_TIMEOUT = 10000; +constexpr int MIN_LATENCY = 1000; +const string SERVICE_NAME = "OHOS.Filemanagement.Dfs.ICloudSyncService"; + +SoftbusAdapter &SoftbusAdapter::GetInstance() +{ + static SoftbusAdapter instance; + return instance; +} + +int32_t SoftbusAdapter::CreateSessionServer(const char *packageName, const char *sessionName) +{ + SocketInfo info = { + .name = const_cast(sessionName), + .pkgName = const_cast(packageName), + }; + int socket = ::Socket(info); + if (socket <= 0) { + LOGE("Failed to CreateSessionServer ret:%{public}d, sessionName:%{public}s", socket, sessionName); + return ERR_BAD_VALUE; + } + std::string saveKey = std::string(sessionName) + std::string(packageName); + { + lock_guard lock(sessionMutex_); + auto sessionAndPackage = sessionAndPackageMap_.find(socket); + if (sessionAndPackage == sessionAndPackageMap_.end()) { + sessionAndPackageMap_.insert({socket, saveKey}); + } + } + QosTV serverQos[] = { + { .qos = QOS_TYPE_MIN_BW, .value = MIN_BW}, + { .qos = QOS_TYPE_MAX_WAIT_TIMEOUT, .value = MAX_WAIT_TIMEOUT }, + { .qos = QOS_TYPE_MIN_LATENCY, .value = MIN_LATENCY}, + }; + + ISocketListener listener = { + .OnBind = SoftbusAdapter::OnBind, + .OnShutdown = SoftbusAdapter::OnShutdown, + .OnBytes = SoftbusAdapter::OnBytes, + .OnMessage = nullptr, + .OnStream = nullptr, + .OnFile = SoftbusAdapter::OnFile, + }; + + int32_t ret = ::Listen(socket, serverQos, QOS_COUNT, &listener); + if (ret != 0) { + LOGE("Failed to CreateSessionServer sessionName:%{public}s", sessionName); + return ret; + } + LOGD("Succeed to CreateSessionServer, sessionName:%{public}s", sessionName); + return E_OK; +} + +int32_t SoftbusAdapter::RemoveSessionServer(const char *packageName, const char *sessionName) +{ + std::string val = std::string(sessionName) + std::string(packageName); + int32_t socket = SoftbusAdapter::GetInstance().GetSocketNameFromMap(val); + string existSessionName = SoftbusAdapter::GetInstance().GetSessionNameFromMap(socket); + if (strcmp(existSessionName.c_str(), sessionName) != 0) { + LOGE("Failed to RemoveSessionServer sessionName:%{public}s", sessionName); + return ERR_BAD_VALUE; + } + SoftbusAdapter::GetInstance().RemoveSesion(socket); + ::Shutdown(socket); + LOGD("Succeed to RemoveSessionServer, sessionName:%{public}s", sessionName); + return E_OK; +} + +void SoftbusAdapter::OnBind(int socket, PeerSocketInfo info) +{ + string sessionName = info.name; + string networkId = info.networkId; + if (sessionName.empty()) { + LOGE("get session name failed"); + return; + } + + auto listener = SoftbusAdapter::GetInstance().GetListener(sessionName); + if (!listener) { + LOGD("UnRegisterListener for session %{public}d", socket); + return; + } + + listener->OnSessionOpened(socket, 0); + SoftbusAdapter::GetInstance().AcceptSesion(socket, sessionName, networkId); +} + +void SoftbusAdapter::OnShutdown(int32_t socket, ShutdownReason reason) +{ + LOGD("Session OnShutdown, sessionId:%{public}d, reason:%{public}d", socket, reason); + string sessionName = SoftbusAdapter::GetInstance().GetSessionNameFromMap(socket); + if (sessionName.empty()) { + LOGE("get session name failed"); + return; + } + + auto listener = SoftbusAdapter::GetInstance().GetListener(sessionName); + if (!listener) { + LOGD("UnRegisterListener for session %{public}d", socket); + return; + } + + listener->OnSessionClosed(socket); + SoftbusAdapter::GetInstance().RemoveSesion(socket); +} + +void SoftbusAdapter::OnBytes(int socket, const void *data, unsigned int dataLen) +{ + LOGD("OnBytes invoked, dataLen:%{public}d", dataLen); + string sessionName = SoftbusAdapter::GetInstance().GetSessionNameFromMap(socket); + if (sessionName.empty()) { + LOGE("get session name failed"); + return; + } + + string peerDeviceId = SoftbusAdapter::GetInstance().GetPeerNetworkId(socket); + if (peerDeviceId.empty()) { + LOGE("get peerDeviceId name failed"); + return; + } + + auto listener = SoftbusAdapter::GetInstance().GetListener(sessionName); + if (!listener) { + LOGD("UnRegisterListener for session %{public}d", socket); + return; + } + + listener->OnDataReceived(peerDeviceId, socket, data, dataLen); +} + +int SoftbusAdapter::OnReceiveFileProcess(int sessionId, + const char *firstFile, + uint64_t bytesUpload, + uint64_t bytesTotal) +{ + LOGD( + "File receive process sessionId = %{public}d, first file:%{public}s, bytesUpload:%{public}" PRIu64 ", " + "bytesTotal:%{public}" PRIu64 "", + sessionId, GetAnonyString(firstFile).c_str(), bytesUpload, bytesTotal); + return E_OK; +} + +void SoftbusAdapter::OnReceiveFileFinished(int sessionId, const char *files, int fileCnt) +{ + LOGD("OnReceiveFileFinished invoked, files:%{public}s, fileCnt:%{public}d", files, fileCnt); + string sessionName = SoftbusAdapter::GetInstance().GetSessionNameFromMap(sessionId); + if (sessionName.empty()) { + LOGE("get session name failed"); + return; + } + + string peerNetworkId = SoftbusAdapter::GetInstance().GetPeerNetworkId(sessionId); + if (peerNetworkId.empty()) { + LOGE("get peerDeviceId name failed"); + return; + } + + auto listener = SoftbusAdapter::GetInstance().GetListener(sessionName); + if (!listener) { + LOGD("UnRegisterListener for session %{public}d", sessionId); + return; + } + + listener->OnFileReceived(peerNetworkId, files, E_OK); +} + +const char* SoftbusAdapter::GetRecvPath() +{ + return "/mnt/hmdfs/100/account/device_view/local/data/"; +} + +void SoftbusAdapter::OnFile(int32_t socket, FileEvent *event) +{ + if (event->type == FILE_EVENT_RECV_UPDATE_PATH) { + event->UpdateRecvPath = GetRecvPath; + } +} + +int SoftbusAdapter::OpenSession(char *sessionName, + char *peerDeviceId, + char *groupId, + TransDataType dataType) +{ + SocketInfo info = { + .name = sessionName, + .peerName = sessionName, + .peerNetworkId = peerDeviceId, + .pkgName = const_cast(SERVICE_NAME.c_str()), + .dataType = dataType, + }; + int32_t socket = Socket(info); + if (socket <= 0) { + return ERR_BAD_VALUE; + } + std::string saveKey = std::string(sessionName) + std::string(SERVICE_NAME); + { + lock_guard lock(sessionMutex_); + auto sessionAndPackage = sessionAndPackageMap_.find(socket); + if (sessionAndPackage == sessionAndPackageMap_.end()) { + sessionAndPackageMap_.insert({socket, saveKey}); + } + } + QosTV clientQos[] = { + { .qos = QOS_TYPE_MIN_BW, .value = MIN_BW}, + { .qos = QOS_TYPE_MAX_WAIT_TIMEOUT, .value = MAX_WAIT_TIMEOUT }, + { .qos = QOS_TYPE_MIN_LATENCY, .value = MIN_LATENCY}, + }; + + ISocketListener listener = { + .OnBind = SoftbusAdapter::OnBind, + .OnShutdown = SoftbusAdapter::OnShutdown, + .OnBytes = SoftbusAdapter::OnBytes, + .OnFile = SoftbusAdapter::OnFile, + }; + SoftbusAdapter::GetInstance().AcceptSesion(socket, sessionName, peerDeviceId); + int32_t ret = ::Bind(socket, clientQos, QOS_COUNT, &listener); + if (ret != 0) { + ::Shutdown(socket); + } + return socket; +} + +int SoftbusAdapter::OpenSessionByP2P(char *sessionName, + char *peerDeviceId, + char *groupId, + bool isFileType) +{ + TransDataType dataType; + if (isFileType) { + dataType = DATA_TYPE_FILE; + } else { + dataType = DATA_TYPE_BYTES; + } + return OpenSession(sessionName, peerDeviceId, groupId, dataType); +} + +void SoftbusAdapter::CloseSession(int sessionId) +{ + ::CloseSession(sessionId); +} + +int SoftbusAdapter::SendBytes(int sessionId, const void *data, unsigned int dataLen) +{ + return ::SendBytes(sessionId, data, dataLen); +} + +int SoftbusAdapter::SendFile(int sessionId, + const std::vector &sFileList, + const std::vector &dFileList) +{ + vector sourceFileList; + vector destFileList; + + for (const string &file : sFileList) { + sourceFileList.push_back(file.data()); + } + + for (const string &file : dFileList) { + destFileList.push_back(file.data()); + } + + return ::SendFile(sessionId, sourceFileList.data(), destFileList.data(), sourceFileList.size()); +} + +/* should use this interface when session closed */ +std::string SoftbusAdapter::GetSessionNameFromMap(int sessionId) +{ + lock_guard lock(sessionMutex_); + auto iter = sessionNameMap_.find(sessionId); + if (iter != sessionNameMap_.end()) { + return iter->second; + } + return ""; +} + +int32_t SoftbusAdapter::GetSocketNameFromMap(std::string sessionAndPack) +{ + lock_guard lock(sessionMutex_); + int32_t socket = -1; + for (const auto& pair : sessionAndPackageMap_) { + if (pair.second == sessionAndPack) { + socket = pair.first; + break; + } + } + return socket; +} + +std::string SoftbusAdapter::GetPeerNetworkId(int sessionId) +{ + lock_guard lock(sessionMutex_); + auto iter = networkIdMap_.find(sessionId); + if (iter != networkIdMap_.end()) { + return iter->second; + } + return ""; +} + +void SoftbusAdapter::RegisterSessionListener(std::string sessionName, std::shared_ptr listener) +{ + std::unique_lock lock(listenerMutex_); + listeners_[sessionName] = listener; +} + +void SoftbusAdapter::UnRegisterSessionListener(std::string sessionName) +{ + std::unique_lock lock(listenerMutex_); + listeners_.erase(sessionName); +} + +std::shared_ptr SoftbusAdapter::GetListener(std::string sessionName) +{ + shared_lock lock(listenerMutex_); + if (listeners_.count(sessionName) == 0) { + return nullptr; + } + return listeners_[sessionName]; +} + +bool SoftbusAdapter::IsSessionOpened(int sessionId) +{ + lock_guard lock(sessionMutex_); + auto iter = sessionOpenedMap_.find(sessionId); + if (iter == sessionOpenedMap_.end()) { + return false; + } + return iter->second; +} + +void SoftbusAdapter::AcceptSesion(int sessionId, const std::string &sessionName, const std::string &networkId) +{ + lock_guard lock(sessionMutex_); + auto iter = sessionOpenedMap_.find(sessionId); + if (iter == sessionOpenedMap_.end()) { + sessionOpenedMap_.insert({sessionId, true}); + } + + auto sessionNameMap = sessionNameMap_.find(sessionId); + if (sessionNameMap == sessionNameMap_.end()) { + sessionNameMap_.insert({sessionId, sessionName}); + } + + auto networkIdMap = networkIdMap_.find(sessionId); + if (networkIdMap == networkIdMap_.end()) { + networkIdMap_.insert({sessionId, networkId}); + } +} + +void SoftbusAdapter::RemoveSesion(int sessionId) +{ + lock_guard lock(sessionMutex_); + auto iter = sessionOpenedMap_.find(sessionId); + if (iter != sessionOpenedMap_.end()) { + sessionOpenedMap_.erase(iter); + } + + auto sessionNameMap = sessionNameMap_.find(sessionId); + if (sessionNameMap != sessionNameMap_.end()) { + sessionNameMap_.erase(sessionNameMap); + } + + auto networkIdMap = networkIdMap_.find(sessionId); + if (networkIdMap != networkIdMap_.end()) { + networkIdMap_.erase(networkIdMap); + } +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/services/cloudsyncservice/src/transport/softbus/softbus_session.cpp b/cloud_file/services/cloudsyncservice/src/transport/softbus/softbus_session.cpp new file mode 100644 index 0000000..9bb9897 --- /dev/null +++ b/cloud_file/services/cloudsyncservice/src/transport/softbus/softbus_session.cpp @@ -0,0 +1,139 @@ +/* + * 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 "softbus_session.h" + +#include +#include + +#include "dfs_error.h" +#include "softbus_adapter.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +const std::string GROUP_TYPE_P2P = "CloudSyncService_P2PGroup"; +constexpr int OPEN_SESSION_RETRY_TIMES = 10 * 30; +constexpr int OPEN_SESSION_RETRY_INTERVAL_MS = 100; +constexpr int LOG_SPAN = 10; +constexpr int32_t HEAD_SIZE = 3; +constexpr int32_t END_SIZE = 3; +constexpr int32_t MIN_SIZE = HEAD_SIZE + END_SIZE + 3; +constexpr const char *REPLACE_CHAIN = "***"; +constexpr const char *DEFAULT_ANONYMOUS = "******"; + +SoftbusSession::SoftbusSession(const std::string &peerDeviceId, const std::string &sessionName, DataType type) + : peerDeviceId_(peerDeviceId), sessionName_(sessionName), type_(type) +{ +} + +int32_t SoftbusSession::Start() +{ + CancelReleaseSessionIfNeeded(); + if (sessionId_ != INVALID_SESSION_ID) { + LOGI("session is exist, no need open again"); + return E_OK; + } + + std::unique_lock lock(sessionMutex_); + if (sessionId_ == INVALID_SESSION_ID) { + LOGI("open session with device: %{public}s", ToBeAnonymous(peerDeviceId_).c_str()); + int session = SoftbusAdapter::GetInstance().OpenSessionByP2P( + const_cast(sessionName_.c_str()), const_cast(peerDeviceId_.c_str()), + const_cast(GROUP_TYPE_P2P.c_str()), (type_ == DataType::TYPE_FILE)); + if (session < 0) { + LOGE("open session failed"); + return E_OPEN_SESSION; + } + + auto ret = WaitSessionOpened(session); + if (ret != E_OK) { + return ret; + } + sessionId_ = session; + } + + return E_OK; +} + +int32_t SoftbusSession::Stop() +{ + LOGD("stop connection"); + std::unique_lock lock(sessionMutex_); + SoftbusAdapter::GetInstance().CloseSession(sessionId_); + sessionId_ = INVALID_SESSION_ID; + return E_OK; +} + +int32_t SoftbusSession::SendData(const void *data, uint32_t dataLen) +{ + return SoftbusAdapter::GetInstance().SendBytes(sessionId_, data, dataLen); +} + +int32_t SoftbusSession::SendFile(const std::vector &sFileList, const std::vector &dFileList) +{ + return SoftbusAdapter::GetInstance().SendFile(sessionId_, sFileList, dFileList); +} + +int32_t SoftbusSession::GetSessionId() +{ + return sessionId_; +} + +SoftbusSession::DataType SoftbusSession::GetDataType() +{ + return type_; +} + +std::string SoftbusSession::GetPeerDeviceId() +{ + return peerDeviceId_; +} + +void SoftbusSession::CancelReleaseSessionIfNeeded() {} + +void SoftbusSession::CancelDelayReleaseSessionTask() {} + +int32_t SoftbusSession::WaitSessionOpened(int sessionId) +{ + int retryTimes = 0; + int logSpan = LOG_SPAN; + while (retryTimes++ < OPEN_SESSION_RETRY_TIMES) { + if (!SoftbusAdapter::GetInstance().IsSessionOpened(sessionId)) { + std::this_thread::sleep_for(std::chrono::milliseconds(OPEN_SESSION_RETRY_INTERVAL_MS)); + if (retryTimes % logSpan == 0) { + LOGI("openSession, waiting for:%{public}d ms", retryTimes * OPEN_SESSION_RETRY_INTERVAL_MS); + } + continue; + } + return E_OK; + } + LOGE("wait session opened timeout"); + return E_WAIT_SESSION_OPENED; +} + +std::string SoftbusSession::ToBeAnonymous(const std::string &name) +{ + if (name.length() <= HEAD_SIZE) { + return DEFAULT_ANONYMOUS; + } + + if (name.length() < MIN_SIZE) { + return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN); + } + + return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN + name.substr(name.length() - END_SIZE, END_SIZE)); +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/test/fuzztest/BUILD.gn b/cloud_file/test/fuzztest/BUILD.gn new file mode 100644 index 0000000..bb3970a --- /dev/null +++ b/cloud_file/test/fuzztest/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2024 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. +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +group("cloud_file_fuzztest") { + testonly = true + + deps = [ + "${cloud_file_path}/test/fuzztest/clouddaemonstub_fuzzer:CloudDaemonStubFuzzTest", + "${cloud_file_path}/test/fuzztest/ffrttimer_fuzzer:FfrtTimerFuzzTest", + ] +} diff --git a/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/BUILD.gn new file mode 100644 index 0000000..0683398 --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/BUILD.gn @@ -0,0 +1,59 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CloudDaemonManagerFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/clouddaemonmanager_fuzzer" + include_dirs = [ + "${cloud_file_path}/test/fuzztest/fuzz_common", + "${innerkits_native_path}/cloud_daemon_kit_inner", + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "-Dprivate=public", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.cpp" ] + + deps = [ + "${innerkits_native_path}/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + "${services_path}/cloudfiledaemon:cloudfiledaemon", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":CloudDaemonManagerFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.cpp b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.cpp new file mode 100644 index 0000000..df034fa --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 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 "clouddaemonmanager_fuzzer.h" + +#include +#include + +#include "cloud_daemon_manager.h" +#include "cloud_daemon_manager_impl.h" +#include "cloud_fuzzer_helper.h" +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; + +using namespace OHOS::FileManagement::CloudFile; +using namespace std; + +void StartFuseFuzzTest(const uint8_t *data, size_t size) +{ + FuzzData fuzzData(data, size); + int32_t userId = fuzzData.GetData(); + int32_t devFd = fuzzData.GetData(); + int len = static_cast(fuzzData.GetRemainSize()); + std::string path = fuzzData.GetStringFromData(len); + CloudDaemonManager::GetInstance().StartFuse(userId, devFd, path); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size <= (OHOS::U32_AT_SIZE << 1)) { + return 0; + } + + OHOS::StartFuseFuzzTest(data, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.h b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.h new file mode 100644 index 0000000..677ef88 --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/clouddaemonmanager_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 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 CLOUD_DAEMON_MANAGER_FUZZER_H +#define CLOUD_DAEMON_MANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "clouddaemonmanager_fuzzer" + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/corpus/init b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/project.xml b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/BUILD.gn new file mode 100644 index 0000000..a3349e1 --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/BUILD.gn @@ -0,0 +1,59 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CloudDaemonStubFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/clouddaemonstub_fuzzer" + include_dirs = [ + "${services_path}/cloudfiledaemon/include/ipc", + "${services_path}/cloudfiledaemon/include", + "${utils_path}/log/include", + "${innerkits_native_path}/cloud_daemon_kit_inner", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${cloud_file_path}/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp", + "${cloud_file_path}/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.cpp", + ] + + deps = [ + "${innerkits_native_path}/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":CloudDaemonStubFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.cpp b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.cpp new file mode 100644 index 0000000..8f978af --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2024 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 "clouddaemonstub_fuzzer.h" + +#include +#include +#include +#include + +#include "cloud_daemon_stub.h" +#include "securec.h" +#include "message_parcel.h" +#include "cloud_file_daemon_interface_code.h" +#include "dfs_error.h" + +namespace OHOS { + +constexpr size_t U32_AT_SIZE = 4; + +using namespace OHOS::FileManagement::CloudFile; +using namespace std; +using namespace OHOS::FileManagement; + +const std::u16string CLOUD_DEAMON_TOKEN = u"ohos.filemanagement.distributedfile.clouddaemon"; + +namespace FileManagement { +namespace CloudFile { +class CloudDaemonStubImpl : public CloudDaemonStub { +public: + CloudDaemonStubImpl() = default; + ~CloudDaemonStubImpl() override {} + int32_t StartFuse(int32_t userId, int32_t deviceFd, const std::string &path) override + { + return E_OK; + } +}; +} +} + +void HandleStartFuseInnerFuzzTest( + std::shared_ptr cloudDaemonStubStr, + std::unique_ptr data, size_t size) +{ + // CLOUD_DAEMON_CMD_START_FUSE + uint32_t code = static_cast(CloudFileDaemonInterfaceCode::CLOUD_DAEMON_CMD_START_FUSE); + MessageParcel datas; + datas.WriteInterfaceToken(CLOUD_DEAMON_TOKEN); + datas.WriteBuffer(data.get(), size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + + cloudDaemonStubStr->OnRemoteRequest(code, datas, reply, option); +} + +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE) { + return 0; + } + + auto str = std::make_unique(size + 1); + (void)memset_s(str.get(), size + 1, 0x00, size + 1); + if (memcpy_s(str.get(), size, data, size) != EOK) { + return 0; + } + + auto cloudDaemonStubStr = std::make_shared(); + + OHOS::HandleStartFuseInnerFuzzTest(cloudDaemonStubStr, move(str), size); + return 0; +} diff --git a/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.h b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.h new file mode 100644 index 0000000..8c5ac63 --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/clouddaemonstub_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 CLOUD_DAEMON_STUB_FUZZER_H +#define CLOUD_DAEMON_STUB_FUZZER_H + + +#define FUZZ_PROJECT_NAME "clouddaemonstub_fuzzer" + + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/corpus/init b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/project.xml b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/clouddaemonstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/clouddisknotify_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/BUILD.gn new file mode 100644 index 0000000..0966f00 --- /dev/null +++ b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CloudDiskNotifyFuzzTest") { + use_exceptions = true + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/clouddisknotify_fuzzer" + include_dirs = [ + "${cloud_file_path}/test/fuzztest/fuzz_common", + "${services_path}/clouddisk_database/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + + sources = [ "${cloud_file_path}/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.cpp" ] + + deps = [ + "${services_path}/clouddisk_database:clouddisk_database", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "ability_runtime:dataobs_manager", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "libfuse:libfuse", + "relational_store:native_rdb", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":CloudDiskNotifyFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.cpp b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.cpp new file mode 100644 index 0000000..b153d73 --- /dev/null +++ b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2024 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 "clouddisknotify_fuzzer.h" + +#include +#include +#include + +#include "cloud_fuzzer_helper.h" +#include "clouddisk_notify.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; +constexpr int SPLITE_SIZE = 5; +constexpr size_t DIVIDED_NUM = 2; +constexpr uint32_t OPS_TYE_SIZE = 11; + +using namespace OHOS::FileManagement::CloudDisk; +using namespace std; + +void TryNotifyServiceFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int len = static_cast((size - U32_AT_SIZE)) / SPLITE_SIZE; + if (len <= 0) { + return; + } + NotifyParamService paramService; + paramService.notifyType = static_cast(fuzzData.GetData()); + CacheNode cacheNode; + cacheNode.cloudId = fuzzData.GetStringFromData(len); + cacheNode.fileName = fuzzData.GetStringFromData(len); + cacheNode.isDir = (size % DIVIDED_NUM == 0) ? "file" : "directory"; + cacheNode.parentCloudId = fuzzData.GetStringFromData(len); + paramService.node = cacheNode; + ParamServiceOther paramOthers; + paramOthers.userId = fuzzData.GetData(); + paramOthers.bundleName = fuzzData.GetStringFromData(len); + NotifyData notifyData; + notifyData.uri = fuzzData.GetStringFromData(len); + notifyData.isDir = (size % DIVIDED_NUM == 0); + notifyData.type = paramService.notifyType; + paramOthers.notifyDataList.emplace_back(notifyData); + paramService.opsType = static_cast(fuzzData.GetData() % OPS_TYE_SIZE); + CloudDiskNotify::GetInstance().TryNotifyService(paramService, paramOthers); +} + +void GetDeleteNotifyDataFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + ParamServiceOther paramOthers; + paramOthers.userId = fuzzData.GetData(); + vector deleteIds; + int len = static_cast((size - U32_AT_SIZE) >> 1); + string cloudId = fuzzData.GetStringFromData(len); + deleteIds.emplace_back(cloudId); + paramOthers.bundleName = fuzzData.GetStringFromData(len); + vector notifyDataList; + CloudDiskNotify::GetInstance().GetDeleteNotifyData(deleteIds, notifyDataList, paramOthers); +} + +void AddNotifyFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + NotifyData notifyData; + notifyData.type = static_cast(fuzzData.GetData()); + int len = static_cast(size - U32_AT_SIZE); + notifyData.uri = fuzzData.GetStringFromData(len); + notifyData.isDir = (size % DIVIDED_NUM == 0); + CloudDiskNotify::GetInstance().AddNotify(notifyData); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size <= (OHOS::U32_AT_SIZE << 1) + static_cast(OHOS::SPLITE_SIZE)) { + return 0; + } + + OHOS::FuzzData fuzzdata(data, size); + OHOS::TryNotifyServiceFuzzTest(fuzzdata, size); + OHOS::GetDeleteNotifyDataFuzzTest(fuzzdata, size); + OHOS::AddNotifyFuzzTest(fuzzdata, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.h b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.h new file mode 100644 index 0000000..136095d --- /dev/null +++ b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/clouddisknotify_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 CLOUD_DISK_NOTIFY_FUZZER_H +#define CLOUD_DISK_NOTIFY_FUZZER_H + + +#define FUZZ_PROJECT_NAME "clouddisknotify_fuzzer" + + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/clouddisknotify_fuzzer/corpus/init b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/clouddisknotify_fuzzer/project.xml b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/clouddisknotify_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/BUILD.gn new file mode 100644 index 0000000..17e834c --- /dev/null +++ b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CloudDownloadCallbackStubFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/clouddownloadcallbackstub_fuzzer" + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/test/fuzztest/fuzz_common", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.cpp" ] + + deps = [ + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":CloudDownloadCallbackStubFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.cpp b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.cpp new file mode 100644 index 0000000..ac12da2 --- /dev/null +++ b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2024 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 "clouddownloadcallbackstub_fuzzer.h" + +#include +#include + +#include "cloud_download_callback_client.h" +#include "cloud_download_callback_stub.h" +#include "cloud_fuzzer_helper.h" +#include "cloud_sync_common.h" + +#include "message_parcel.h" +#include "utils_log.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t U64_AT_SIZE = 8; +constexpr size_t SPLITE_SIZE = 3; + +using namespace OHOS::FileManagement::CloudSync; +using namespace std; + +class CloudDownloadCallbackTest : public CloudDownloadCallback { +public: + void OnDownloadProcess(const DownloadProgressObj &progress) override {} +}; + +bool WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(CloudDownloadCallbackStub::GetDescriptor())) { + LOGE("Write token failed."); + return false; + } + return true; +} + +void HandleOnProcessFuzzTest(std::shared_ptr cloudDownloadCallbackStubStr, + const uint8_t *data, + size_t size) +{ + FuzzData fuzzData(data, size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + DownloadProgressObj downloadProgressObj; + downloadProgressObj.refCount = fuzzData.GetData(); + downloadProgressObj.downloadId = fuzzData.GetData(); + downloadProgressObj.state = + static_cast(fuzzData.GetData() % (SPLITE_SIZE + 1)); + downloadProgressObj.downloadErrorType = + static_cast(fuzzData.GetData() % (SPLITE_SIZE + SPLITE_SIZE)); + downloadProgressObj.downloadedSize = fuzzData.GetData(); + downloadProgressObj.totalSize = fuzzData.GetData(); + int len = static_cast(size - (OHOS::U32_AT_SIZE * SPLITE_SIZE + OHOS::U64_AT_SIZE * SPLITE_SIZE)); + downloadProgressObj.path = fuzzData.GetStringFromData(len); + datas.WriteParcelable(&downloadProgressObj); + datas.RewindRead(0); + // SERVICE_CMD_ON_PROCESS + uint32_t code = 0; + MessageParcel reply; + MessageOption option; + + cloudDownloadCallbackStubStr->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size < (OHOS::U32_AT_SIZE * OHOS::SPLITE_SIZE + OHOS::U64_AT_SIZE * OHOS::SPLITE_SIZE)) { + return 0; + } + + auto cloudDownloadCallbackPtr = std::make_shared(); + auto cloudDownloadCallbackStubStr = + std::make_shared(cloudDownloadCallbackPtr); + OHOS::HandleOnProcessFuzzTest(cloudDownloadCallbackStubStr, data, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.h b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.h new file mode 100644 index 0000000..a8fbf7f --- /dev/null +++ b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/clouddownloadcallbackstub_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 CLOUD_DOWMLOAD_ASSET_CALLBACK_STUB_FUZZER_H +#define CLOUD_DOWMLOAD_ASSET_CALLBACK_STUB_FUZZER_H + + +#define FUZZ_PROJECT_NAME "clouddownloadcallbackstub_fuzzer" + + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/corpus/init b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/project.xml b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/clouddownloadcallbackstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/BUILD.gn new file mode 100644 index 0000000..d1458fe --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/BUILD.gn @@ -0,0 +1,62 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CloudSyncAssetManagerFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/cloudsyncassetmanager_fuzzer" + include_dirs = [ + "${cloud_file_path}/test/fuzztest/fuzz_common", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "-Dprivate=public", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.cpp" ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_asset_kit_inner", + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":CloudSyncAssetManagerFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.cpp b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.cpp new file mode 100644 index 0000000..47de2b2 --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2024 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 "cloudsyncassetmanager_fuzzer.h" + +#include +#include +#include + +#include "cloud_fuzzer_helper.h" +#include "cloud_sync_asset_manager_impl.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t BOOL_AT_SIZE = 1; +constexpr size_t SPLITE_SIZE = 6; +constexpr size_t NETWORK_ID_SIZE = 65; + +using namespace OHOS::FileManagement::CloudSync; +using namespace std; + +void UploadAssetFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int32_t userId = fuzzData.GetData(); + std::string request = fuzzData.GetStringFromData(static_cast(size - U32_AT_SIZE)); + std::string result; + CloudSyncAssetManager::GetInstance().UploadAsset(userId, request, result); +} + +void DownloadFileFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int32_t userId = fuzzData.GetData(); + int len = static_cast((size - U32_AT_SIZE) / SPLITE_SIZE); + if (len <= 0) { + return; + } + AssetInfo assetInfo = { + .uri = fuzzData.GetStringFromData(len), + .recordType = fuzzData.GetStringFromData(len), + .recordId = fuzzData.GetStringFromData(len), + .fieldKey = fuzzData.GetStringFromData(len), + .assetName = fuzzData.GetStringFromData(len), + }; + std::string bundleName = fuzzData.GetStringFromData(len); + CloudSyncAssetManager::GetInstance().DownloadFile(userId, bundleName, assetInfo); +} + +void DownloadFilesFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int32_t userId = fuzzData.GetData(); + int len = static_cast((size - U32_AT_SIZE) / SPLITE_SIZE); + if (len <= 0) { + return; + } + AssetInfo assetInfo = { + .uri = fuzzData.GetStringFromData(len), + .recordType = fuzzData.GetStringFromData(len), + .recordId = fuzzData.GetStringFromData(len), + .fieldKey = fuzzData.GetStringFromData(len), + .assetName = fuzzData.GetStringFromData(len), + }; + vector assetInfos; + assetInfos.emplace_back(assetInfo); + std::string bundleName = fuzzData.GetStringFromData(len); + vector assetResultMap; + CloudSyncAssetManager::GetInstance().DownloadFiles(userId, bundleName, assetInfos, assetResultMap); +} + +void DownloadFileCallbackFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int32_t userId = fuzzData.GetData(); + std::string networkId = fuzzData.GetStringFromData(static_cast(NETWORK_ID_SIZE)); + auto remainSize = fuzzData.GetRemainSize(); + int len = static_cast(remainSize / SPLITE_SIZE); + if (len <= 0) { + return; + } + std::string bundleName = fuzzData.GetStringFromData(len); + AssetInfo assetInfo = { + .uri = fuzzData.GetStringFromData(len), + .recordType = fuzzData.GetStringFromData(len), + .recordId = fuzzData.GetStringFromData(len), + .fieldKey = fuzzData.GetStringFromData(len), + .assetName = fuzzData.GetStringFromData(len), + }; + auto callback = [](const std::string &, int32_t) {}; + CloudSyncAssetManager::GetInstance().DownloadFile(userId, bundleName, networkId, assetInfo, callback); +} + +void DeleteAssetFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int32_t userId = fuzzData.GetData(); + std::string uri = fuzzData.GetStringFromData(static_cast(size - U32_AT_SIZE)); + CloudSyncAssetManager::GetInstance().DeleteAsset(userId, uri); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || + size <= (OHOS::U32_AT_SIZE + static_cast(OHOS::NETWORK_ID_SIZE + OHOS::SPLITE_SIZE))) { + return 0; + } + + OHOS::FuzzData fuzzData(data, size); + OHOS::UploadAssetFuzzTest(fuzzData, size); + OHOS::DownloadFileFuzzTest(fuzzData, size); + OHOS::DownloadFilesFuzzTest(fuzzData, size); + OHOS::DownloadFileCallbackFuzzTest(fuzzData, size); + OHOS::DeleteAssetFuzzTest(fuzzData, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.h b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.h new file mode 100644 index 0000000..4a6ce3d --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/cloudsyncassetmanager_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 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 CLOUD_SYNC_ASSET_MANAGER_FUZZER_H +#define CLOUD_SYNC_ASSET_MANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "cloudsyncassetmanager_fuzzer" + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/corpus/init b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/project.xml b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncassetmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/BUILD.gn new file mode 100644 index 0000000..cb93e76 --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CloudSyncCallbackStubFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/cloudsynccallbackstub_fuzzer" + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/test/fuzztest/fuzz_common", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.cpp" ] + + deps = [ + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":CloudSyncCallbackStubFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.cpp b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.cpp new file mode 100644 index 0000000..2942594 --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2024 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 "cloudsynccallbackstub_fuzzer.h" + +#include +#include + +#include "cloud_fuzzer_helper.h" +#include "cloud_sync_callback_client.h" +#include "cloud_sync_callback_stub.h" + +#include "message_parcel.h" +#include "utils_log.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; + +using namespace OHOS::FileManagement::CloudSync; +using namespace std; + +class CloudSyncCallbackTest : public CloudSyncCallbackStub { +public: + void OnSyncStateChanged(SyncType type, SyncPromptState state) override {} + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override {} +}; + +bool WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(CloudSyncCallbackStub::GetDescriptor())) { + LOGE("Write token failed."); + return false; + } + return true; +} + +void HandleOnSyncStateChangedFuzzTest(std::shared_ptr cloudSyncCallbackStubStr, + const uint8_t *data, + size_t size) +{ + FuzzData fuzzData(data, size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int32_t state = fuzzData.GetData(); + datas.WriteInt32(state); + int32_t error = fuzzData.GetData(); + datas.WriteInt32(error); + datas.RewindRead(0); + // SERVICE_CMD_ON_SYNC_STATE_CHANGED + uint32_t code = 0; + MessageParcel reply; + MessageOption option; + + cloudSyncCallbackStubStr->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size < OHOS::U32_AT_SIZE) { + return 0; + } + + auto cloudSyncCallackPtr = std::make_shared(); + auto cloudSyncCallbackStubStr = + std::make_shared(cloudSyncCallackPtr); + OHOS::HandleOnSyncStateChangedFuzzTest(cloudSyncCallbackStubStr, data, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.h b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.h new file mode 100644 index 0000000..e9d5a9c --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/cloudsynccallbackstub_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 CLOUD_SYNC_CALLBACK_STUB_FUZZER_H +#define CLOUD_SYNC_CALLBACK_STUB_FUZZER_H + + +#define FUZZ_PROJECT_NAME "cloudsynccallbackstub_fuzzer" + + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/corpus/init b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/project.xml b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsynccallbackstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/BUILD.gn new file mode 100644 index 0000000..d87dd7e --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CloudSyncManagerFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/cloudsyncmanager_fuzzer" + include_dirs = [ + "${cloud_file_path}/test/fuzztest/fuzz_common", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "-Dprivate=public", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.cpp" ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":CloudSyncManagerFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.cpp b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.cpp new file mode 100644 index 0000000..8dade56 --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.cpp @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2024 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 "cloudsyncmanager_fuzzer.h" + +#include +#include +#include + +#include "cloud_fuzzer_helper.h" +#include "cloud_sync_manager.h" +#include "cloud_sync_manager_impl.h" +#include "service_proxy.h" +#include "i_cloud_download_callback.h" +#include "i_cloud_sync_callback.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t BOOL_AT_SIZE = 1; + +using namespace OHOS::FileManagement::CloudSync; +using namespace std; +class ICloudSyncCallbackTest : public IRemoteStub { +public: + void OnSyncStateChanged(SyncType type, SyncPromptState state) override {} + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override {} +}; + +class ICloudDownloadCallbackTest : public IRemoteStub { +public: + void OnDownloadProcess(const DownloadProgressObj &progress) override {} +}; + +void RegisterCallbackFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + std::string bundleName = fuzzData.GetStringFromData(static_cast(size)); + auto cloudSyncCallback = make_shared(); + CloudSyncManager::GetInstance().RegisterCallback(cloudSyncCallback, bundleName); +} + +void UnRegisterCallbackFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + std::string bundleName = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().UnRegisterCallback(bundleName); +} + +void StartSyncFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + std::string bundleName = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().StartSync(bundleName); +} + +void GetSyncTimeFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int64_t syncTime{0}; + std::string bundleName = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().GetSyncTime(syncTime, bundleName); +} + +void StartSyncCallbackFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + bool forceFlag = fuzzData.GetData(); + auto cloudSyncCallback = make_shared(); + CloudSyncManager::GetInstance().StartSync(forceFlag, cloudSyncCallback); +} + +void TriggerSyncFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int32_t userId = 100; + std::string bundleName = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().TriggerSync(bundleName, userId); + + fuzzData.ResetData(size); + userId = fuzzData.GetData(); + bundleName = fuzzData.GetStringFromData(static_cast(size - U32_AT_SIZE)); + CloudSyncManager::GetInstance().TriggerSync(bundleName, userId); +} + +void StopSyncFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + std::string bundleName = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().StopSync(bundleName); +} + +void ChangeAppSwitchFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + bool status = fuzzData.GetData(); + int len = static_cast((size - BOOL_AT_SIZE) >> 1); + std::string accoutId = fuzzData.GetStringFromData(len); + string bundleName = fuzzData.GetStringFromData(static_cast(len)); + CloudSyncManager::GetInstance().ChangeAppSwitch(accoutId, bundleName, status); +} + +void NotifyDataChangeFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int len = static_cast(size >> 1); + std::string accoutId = fuzzData.GetStringFromData(len); + std::string bundleName = fuzzData.GetStringFromData(len); + CloudSyncManager::GetInstance().NotifyDataChange(accoutId, bundleName); +} + +void StartDownloadFileFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + string uri = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().StartDownloadFile(uri); +} + +void StartFileCacheFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + string uri = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().StartFileCache(uri); +} + +void StopDownloadFileFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + bool needClean = fuzzData.GetData(); + string uri = fuzzData.GetStringFromData(static_cast(size - BOOL_AT_SIZE)); + CloudSyncManager::GetInstance().StopDownloadFile(uri, needClean); +} + +void RegisterDownloadFileCallbackFuzzTest(FuzzData &fuzzData, size_t size) +{ + auto downloadCallback = make_shared(); + CloudSyncManager::GetInstance().RegisterDownloadFileCallback(downloadCallback); + CloudSyncManager::GetInstance().UnregisterDownloadFileCallback(); +} + +void EnableCloudFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int len = static_cast(size >> 1); + std::string accoutId = fuzzData.GetStringFromData(len); + string itemStr = fuzzData.GetStringFromData(len - static_cast(BOOL_AT_SIZE)); + bool itemBool = fuzzData.GetData(); + SwitchDataObj switchDataObj; + switchDataObj.switchData.insert({itemStr, itemBool}); + CloudSyncManager::GetInstance().EnableCloud(accoutId, switchDataObj); + auto proxy = ServiceProxy::GetInstance(); + CloudSyncManagerImpl::GetInstance().SetDeathRecipient(proxy->AsObject()); +} + +void DisableCloudFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + std::string accoutId = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().DisableCloud(accoutId); +} + +void CleanFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + int len = static_cast(size >> 1); + std::string accoutId = fuzzData.GetStringFromData(len); + int32_t itemInt = fuzzData.GetData(); + auto remainSize = fuzzData.GetRemainSize(); + string itemStr = fuzzData.GetStringFromData(static_cast(remainSize)); + CleanOptions cleanOptions; + cleanOptions.appActionsData.insert({itemStr, itemInt}); + CloudSyncManager::GetInstance().Clean(accoutId, cleanOptions); +} + +void CleanCacheFuzzTest(FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + string uri = fuzzData.GetStringFromData(static_cast(size)); + CloudSyncManager::GetInstance().CleanCache(uri); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size <= (OHOS::U32_AT_SIZE << 1)) { + return 0; + } + + OHOS::FuzzData fuzzData(data, size); + OHOS::RegisterCallbackFuzzTest(fuzzData, size); + OHOS::UnRegisterCallbackFuzzTest(fuzzData, size); + OHOS::StartSyncFuzzTest(fuzzData, size); + OHOS::GetSyncTimeFuzzTest(fuzzData, size); + OHOS::StartSyncCallbackFuzzTest(fuzzData, size); + OHOS::TriggerSyncFuzzTest(fuzzData, size); + OHOS::StopSyncFuzzTest(fuzzData, size); + OHOS::ChangeAppSwitchFuzzTest(fuzzData, size); + OHOS::NotifyDataChangeFuzzTest(fuzzData, size); + OHOS::StartDownloadFileFuzzTest(fuzzData, size); + OHOS::StartFileCacheFuzzTest(fuzzData, size); + OHOS::StopDownloadFileFuzzTest(fuzzData, size); + OHOS::RegisterDownloadFileCallbackFuzzTest(fuzzData, size); + OHOS::EnableCloudFuzzTest(fuzzData, size); + OHOS::DisableCloudFuzzTest(fuzzData, size); + OHOS::CleanFuzzTest(fuzzData, size); + OHOS::CleanCacheFuzzTest(fuzzData, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.h b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.h new file mode 100644 index 0000000..7319831 --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/cloudsyncmanager_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 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 CLOUD_SYNC_MANAGER_FUZZER_H +#define CLOUD_SYNC_MANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "cloudsyncmanager_fuzzer" + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/corpus/init b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/project.xml b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/BUILD.gn new file mode 100644 index 0000000..059131b --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/BUILD.gn @@ -0,0 +1,85 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CloudSyncServiceStubFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/cloudsyncservicestub_fuzzer" + include_dirs = [ + "${cloud_file_path}/test/fuzztest/fuzz_common", + "${innerkits_native_path}/cloudsync_kit_inner", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/cycle_task", + "${services_path}/cloudsyncservice/include/cycle_task/tasks", + "${services_path}/cloudsyncservice/include/data_sync", + "${services_path}/cloudsyncservice/include/data_sync/cloud_disk_data_sync", + "${services_path}/cloudsyncservice/include/data_sync/gallery_data_sync", + "${services_path}/cloudsyncservice/include/ipc", + "${services_path}/cloudsyncservice/include/sync_rule", + "${services_path}/cloudsyncservice/include/transport", + "${services_path}/cloudsyncservice/include/transport/softbus", + "${utils_path}/dentry/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "-Dprivate=public", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ + "${cloud_file_path}/services/cloudsyncservice/src/ipc/cloud_sync_service_stub.cpp", + "${cloud_file_path}/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.cpp", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken_shared", + "access_token:libtokensetproc_shared", + "c_utils:utils", + "device_manager:devicemanagersdk", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } +} + +group("fuzztest") { + testonly = true + deps = [] +} diff --git a/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.cpp b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.cpp new file mode 100644 index 0000000..23b864a --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.cpp @@ -0,0 +1,721 @@ +/* + * Copyright (c) 2024 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 "cloudsyncservicestub_fuzzer.h" + +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "cloud_file_sync_service_interface_code.h" +#include "cloud_fuzzer_helper.h" +#include "cloud_sync_service.h" +#include "cloud_sync_service_stub.h" +#include "i_cloud_download_callback.h" +#include "i_cloud_sync_callback.h" +#include "i_download_asset_callback.h" +#include "task_state_manager.h" + +#include "message_parcel.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "utils_log.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t U64_AT_SIZE = 8; +constexpr size_t BOOL_AT_SIZE = 1; +constexpr int SPLITE_SIZE = 5; +const std::u16string CLOUD_SYNC_SERVICE_TOKEN = u"OHOS.Filemanagement.Dfs.ICloudSyncService"; +constexpr int32_t SERVICE_SA_ID = 5204; + +using namespace OHOS::FileManagement::CloudSync; +using namespace std; +class ICloudSyncCallbackTest : public IRemoteStub { +public: + void OnSyncStateChanged(SyncType type, SyncPromptState state) override {} + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override {} +}; + +class ICloudDownloadCallbackTest : public IRemoteStub { +public: + void OnDownloadProcess(const DownloadProgressObj &progress) override {} +}; + +class IDownloadAssetCallbackTest : public IRemoteStub { +public: + void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) override {} +}; + +void NativeTokenGet(bool isSystem) +{ + uint64_t tokenId; + static const char *perms[] = {"ohos.permission.CLOUDFILE_SYNC", "ohos.permission.CLOUDFILE_SYNC_MANAGER", + "ohos.permission.PROXY_AUTHORIZATION_URI"}; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 3, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .aplStr = "system_core", + }; + + infoInstance.processName = "CloudOnRemoteRequestFuzzerTest"; + tokenId = GetAccessTokenId(&infoInstance); + if (isSystem) { + const uint64_t systemAppMask = (static_cast(1) << 32); + tokenId |= systemAppMask; + } + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +bool WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(CLOUD_SYNC_SERVICE_TOKEN)) { + LOGE("Write token failed."); + return false; + } + return true; +} + +void HandleChangeAppSwitchFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + bool status = fuzzData.GetData(); + int pos = static_cast((size - BOOL_AT_SIZE) >> 1); + std::string accountId = fuzzData.GetStringFromData(pos); + std::string bundleName = fuzzData.GetStringFromData(pos); + datas.WriteString(accountId); + datas.WriteString(bundleName); + datas.WriteBool(status); + datas.RewindRead(0); + // SERVICE_CMD_CHANGE_APP_SWITCH + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_CHANGE_APP_SWITCH); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleCleanFuzzTest(std::shared_ptr cloudSyncServiceStubStr, FuzzData &fuzzData, size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + std::string uri = fuzzData.GetStringFromData(static_cast(size)); + datas.WriteString(uri); + datas.RewindRead(0); + // SERVICE_CMD_CLEAN + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_CLEAN); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleDeleteAssetFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int32_t userId = fuzzData.GetData(); + datas.WriteInt32(userId); + int len = static_cast(size - U32_AT_SIZE); + std::string uri = fuzzData.GetStringFromData(len); + datas.WriteString(uri); + datas.RewindRead(0); + // SERVICE_CMD_DELETE_ASSET + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DELETE_ASSET); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleDisableCloudFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + string accountId = fuzzData.GetStringFromData(static_cast(size)); + datas.WriteString(accountId); + datas.RewindRead(0); + // SERVICE_CMD_DISABLE_CLOUD + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DISABLE_CLOUD); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleDownloadFileFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int32_t userId = fuzzData.GetData(); + datas.WriteInt32(userId); + int pos = static_cast(size - U32_AT_SIZE) / (SPLITE_SIZE + 1); + string bundleName = fuzzData.GetStringFromData(pos); + datas.WriteString(bundleName); + AssetInfo assetInfo = {.uri = fuzzData.GetStringFromData(pos), + .recordType = fuzzData.GetStringFromData(pos), + .recordId = fuzzData.GetStringFromData(pos), + .fieldKey = fuzzData.GetStringFromData(pos), + .assetName = fuzzData.GetStringFromData(pos)}; + AssetInfoObj assetInfoObj(assetInfo); + datas.WriteParcelable(&assetInfoObj); + datas.RewindRead(0); + // SERVICE_CMD_DOWNLOAD_FILE + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DOWNLOAD_FILE); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleEnableCloudFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int pos = static_cast(size >> 1); + string accountId = fuzzData.GetStringFromData(pos); + datas.WriteString(accountId); + int itemStrLen = pos / SPLITE_SIZE; + if (itemStrLen <= static_cast(BOOL_AT_SIZE)) { + return; + } + std::map switchData; + for (int i = 0; i < SPLITE_SIZE; i++) { + string itemStr = fuzzData.GetStringFromData(itemStrLen - static_cast(BOOL_AT_SIZE)); + bool itemBool = fuzzData.GetData(); + switchData.insert(pair(itemStr, itemBool)); + } + SwitchDataObj switchDataObj; + switchDataObj.switchData = switchData; + datas.WriteParcelable(&switchDataObj); + datas.RewindRead(0); + // SERVICE_CMD_ENABLE_CLOUD + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_ENABLE_CLOUD); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleNotifyDataChangeFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int pos = static_cast(size >> 1); + string accountId = fuzzData.GetStringFromData(pos); + datas.WriteString(accountId); + string bundleName = fuzzData.GetStringFromData(pos); + datas.WriteString(bundleName); + datas.RewindRead(0); + // SERVICE_CMD_NOTIFY_DATA_CHANGE + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_NOTIFY_DATA_CHANGE); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleRegisterCallbackInnerFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + sptr callback = new (std::nothrow) ICloudSyncCallbackTest(); + if (callback == nullptr) { + return; + } + datas.WriteRemoteObject(callback->AsObject().GetRefPtr()); + string bundleName = fuzzData.GetStringFromData(static_cast(size)); + datas.WriteString(bundleName); + datas.RewindRead(0); + // SERVICE_CMD_REGISTER_CALLBACK + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_REGISTER_CALLBACK); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleRegisterDownloadFileCallbackFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + sptr callback = new (std::nothrow) ICloudDownloadCallbackTest(); + if (callback == nullptr) { + return; + } + datas.WriteRemoteObject(callback->AsObject().GetRefPtr()); + datas.RewindRead(0); + // SERVICE_CMD_REGISTER_DOWNLOAD_FILE_CALLBACK + uint32_t code = + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_REGISTER_DOWNLOAD_FILE_CALLBACK); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleStartDownloadFileFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + string path = fuzzData.GetStringFromData(static_cast(size)); + datas.WriteString(path); + datas.RewindRead(0); + // SERVICE_CMD_START_DOWNLOAD_FILE + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_START_DOWNLOAD_FILE); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleStartSyncInnerFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + auto forceFlag = fuzzData.GetData(); + datas.WriteBool(forceFlag); + string bundleName = fuzzData.GetStringFromData(static_cast(size - BOOL_AT_SIZE)); + datas.WriteString(bundleName); + datas.RewindRead(0); + // SERVICE_CMD_START_SYNC + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_START_SYNC); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleStopDownloadFileFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + string path = fuzzData.GetStringFromData(static_cast(size)); + datas.WriteString(path); + datas.RewindRead(0); + // SERVICE_CMD_STOP_DOWNLOAD_FILE + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_STOP_DOWNLOAD_FILE); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleStopSyncInnerFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + const uint8_t *data, + size_t size) +{ + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + datas.WriteBuffer(data, size); + datas.RewindRead(0); + // SERVICE_CMD_STOP_SYNC + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_STOP_SYNC); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleUnRegisterCallbackInnerFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + string bundleName = fuzzData.GetStringFromData(static_cast(size)); + datas.WriteString(bundleName); + datas.RewindRead(0); + // SERVICE_CMD_UNREGISTER_CALLBACK + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_UNREGISTER_CALLBACK); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleUnRegisterDownloadFileCallbackFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + const uint8_t *data, + size_t size) +{ + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + datas.WriteBuffer(data, size); + datas.RewindRead(0); + // SERVICE_CMD_UNREGISTER_DOWNLOAD_FILE_CALLBACK + uint32_t code = + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_UNREGISTER_DOWNLOAD_FILE_CALLBACK); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleUploadAssetFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int32_t userId = fuzzData.GetData(); + datas.WriteInt32(userId); + int len = static_cast(size - U32_AT_SIZE); + string request = fuzzData.GetStringFromData(len); + datas.WriteString(request); + datas.RewindRead(0); + // SERVICE_CMD_UPLOAD_ASSET + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_UPLOAD_ASSET); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleTriggerSyncInnerFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int len = static_cast(size - U32_AT_SIZE); + string bundleName = fuzzData.GetStringFromData(len); + datas.WriteString(bundleName); + int32_t userId = fuzzData.GetData(); + datas.WriteInt32(userId); + datas.RewindRead(0); + // SERVICE_CMD_TRIGGER_SYNC + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_TRIGGER_SYNC); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleNotifyEventChangeFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int32_t userId = fuzzData.GetData(); + datas.WriteInt32(userId); + + int pos = static_cast((size - U32_AT_SIZE) >> 1); + string eventIdStr = fuzzData.GetStringFromData(pos); + string extraDataStr = fuzzData.GetStringFromData(pos); + datas.WriteString(eventIdStr); + datas.WriteString(extraDataStr); + datas.RewindRead(0); + // SERVICE_CMD_NOTIFY_EVENT_CHANGE + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_NOTIFY_EVENT_CHANGE); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleStartFileCacheFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int32_t userId = fuzzData.GetData(); + datas.WriteInt32(userId); + int pos = static_cast((size - U32_AT_SIZE) >> 1); + string eventIdStr = fuzzData.GetStringFromData(pos); + string extraDataStr = fuzzData.GetStringFromData(pos); + datas.WriteString(eventIdStr); + datas.WriteString(extraDataStr); + datas.RewindRead(0); + // SERVICE_CMD_START_FILE_CACHE + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_START_FILE_CACHE); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleDownloadFilesFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int32_t userId = fuzzData.GetData(); + datas.WriteInt32(userId); + int32_t vecSize = fuzzData.GetData() % SPLITE_SIZE + 1; + auto remainSize = fuzzData.GetRemainSize(); + if (static_cast(remainSize) <= vecSize * SPLITE_SIZE + 1) { + return; + } + int len = static_cast(remainSize / (vecSize * SPLITE_SIZE + 1)); + string bundleName = fuzzData.GetStringFromData(len); + datas.WriteString(bundleName); + datas.WriteInt32(vecSize); + for (auto i = 0; i < vecSize; i++) { + AssetInfo assetInfo = {.uri = fuzzData.GetStringFromData(len), + .recordType = fuzzData.GetStringFromData(len), + .recordId = fuzzData.GetStringFromData(len), + .fieldKey = fuzzData.GetStringFromData(len), + .assetName = fuzzData.GetStringFromData(len)}; + AssetInfoObj assetInfoObj(assetInfo); + datas.WriteParcelable(&assetInfoObj); + } + datas.RewindRead(0); + // SERVICE_CMD_DOWNLOAD_FILES + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DOWNLOAD_FILES); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleDownloadAssetFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + uint64_t taskId = fuzzData.GetData(); + datas.WriteUint64(taskId); + int32_t userId = fuzzData.GetData(); + datas.WriteUint32(userId); + int len = static_cast(fuzzData.GetRemainSize() >> 1); + string bundleName = fuzzData.GetStringFromData(len); + datas.WriteString(bundleName); + string networkId = fuzzData.GetStringFromData(len); + datas.WriteString(networkId); + + fuzzData.ResetData(size); + len = static_cast(size) / SPLITE_SIZE; + AssetInfo assetInfo = {.uri = fuzzData.GetStringFromData(len), + .recordType = fuzzData.GetStringFromData(len), + .recordId = fuzzData.GetStringFromData(len), + .fieldKey = fuzzData.GetStringFromData(len), + .assetName = fuzzData.GetStringFromData(len)}; + AssetInfoObj assetInfoObj(assetInfo); + datas.WriteParcelable(&assetInfoObj); + datas.RewindRead(0); + // SERVICE_CMD_DOWNLOAD_ASSET + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DOWNLOAD_ASSET); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleRegisterDownloadAssetCallbackFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + sptr callback = new (std::nothrow) IDownloadAssetCallbackTest(); + if (callback == nullptr) { + return; + } + datas.WriteRemoteObject(callback->AsObject().GetRefPtr()); + datas.RewindRead(0); + // SERVICE_CMD_REGISTER_DOWNLOAD_ASSET_CALLBACK + uint32_t code = + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_REGISTER_DOWNLOAD_ASSET_CALLBACK); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleGetSyncTimeFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + string bundleName = fuzzData.GetStringFromData(static_cast(size)); + datas.WriteString(bundleName); + datas.RewindRead(0); + // SERVICE_CMD_GET_SYNC_TIME + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_GET_SYNC_TIME); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} + +void HandleCleanCacheFuzzTest(std::shared_ptr cloudSyncServiceStubStr, + FuzzData &fuzzData, + size_t size) +{ + fuzzData.ResetData(size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + string uri = fuzzData.GetStringFromData(static_cast(size)); + datas.WriteString(uri); + datas.RewindRead(0); + // SERVICE_CMD_CLEAN_CACHE + uint32_t code = static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_CLEAN_CACHE); + MessageParcel reply; + MessageOption option; + + cloudSyncServiceStubStr->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size < OHOS::U32_AT_SIZE * static_cast(OHOS::SPLITE_SIZE)) { + return 0; + } + + OHOS::NativeTokenGet(true); + auto cloudSyncServiceStubStr = + std::make_shared(OHOS::SERVICE_SA_ID); + if (cloudSyncServiceStubStr->dataSyncManager_ == nullptr) { + cloudSyncServiceStubStr->dataSyncManager_ = + std::make_shared(); + } + + OHOS::FuzzData fuzzData(data, size); + OHOS::HandleChangeAppSwitchFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleCleanFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleDeleteAssetFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleDisableCloudFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleDownloadFileFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleEnableCloudFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleNotifyDataChangeFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleRegisterCallbackInnerFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleRegisterDownloadFileCallbackFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleStartDownloadFileFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleStartSyncInnerFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleStopDownloadFileFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleStopSyncInnerFuzzTest(cloudSyncServiceStubStr, data, size); + OHOS::HandleUnRegisterCallbackInnerFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleUnRegisterDownloadFileCallbackFuzzTest(cloudSyncServiceStubStr, data, size); + OHOS::HandleUploadAssetFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleTriggerSyncInnerFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleNotifyEventChangeFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleStartFileCacheFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleDownloadFilesFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleDownloadAssetFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleRegisterDownloadAssetCallbackFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleGetSyncTimeFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + OHOS::HandleCleanCacheFuzzTest(cloudSyncServiceStubStr, fuzzData, size); + if (OHOS::FileManagement::CloudSync::TaskStateManager::GetInstance().unloadTaskHandle_ != nullptr) { + OHOS::FileManagement::CloudSync::TaskStateManager::GetInstance().queue_.wait( + OHOS::FileManagement::CloudSync::TaskStateManager::GetInstance().unloadTaskHandle_); + } + return 0; +} diff --git a/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.h b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.h new file mode 100644 index 0000000..7d1303f --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/cloudsyncservicestub_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 CLOUD_SYNC_SERVICE_STUB_FUZZER_H +#define CLOUD_SYNC_SERVICE_STUB_FUZZER_H + + +#define FUZZ_PROJECT_NAME "cloudsyncservicestub_fuzzer" + + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/corpus/init b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/project.xml b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/cloudsyncservicestub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/BUILD.gn new file mode 100644 index 0000000..2372fe2 --- /dev/null +++ b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("CycleTaskRunnerFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/cycletaskrunner_fuzzer" + include_dirs = [ + "${innerkits_native_path}/cloud_file_kit_inner", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/test/fuzztest/fuzz_common", + "${services_path}/cloudsyncservice/include/cycle_task", + "${services_path}/cloudsyncservice/include/cycle_task/tasks", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "-Dprivate=public", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.cpp" ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "hilog:libhilog", + "preferences:native_preferences", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":CycleTaskRunnerFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/corpus/init b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.cpp b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.cpp new file mode 100644 index 0000000..96f572d --- /dev/null +++ b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2024 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 "cycletaskrunner_fuzzer.h" + +#include +#include +#include +#include +#include +#include + +#include "cloud_file_kit.h" +#include "cloud_fuzzer_helper.h" +#include "cycle_task_runner.h" +#include "optimize_storage_task.h" +#include "periodic_check_task.h" +#include "report_statistics_task.h" +#include "save_subscription_task.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; +constexpr int SPLITE_SIZE = 3; +using namespace std; +using namespace OHOS::FileManagement; +using namespace OHOS::FileManagement::CloudSync; + +class CloudFileKitMock : public CloudFile::CloudFileKit {}; + +__attribute__((used)) static bool g_isInit = + CloudFile::CloudFileKit::RegisterCloudInstance(new (std::nothrow) CloudFileKitMock()); + +void CycleTaskDerivedFuzzTest(const uint8_t *data, size_t size) +{ + FuzzData fuzzData(data, size); + auto dataSyncManager = make_shared(); + CycleTaskRunner cyclerunner(dataSyncManager); + cyclerunner.StartTask(); + + int32_t userId = fuzzData.GetData(); + auto remainSize = fuzzData.GetRemainSize(); + std::string bundleName = fuzzData.GetStringFromData(static_cast(remainSize)); + std::set bundleNames; + bundleNames.insert(bundleName); + auto bundleNamesPtr = make_shared>(bundleNames); + shared_ptr saveSubscriptionTaskPtr = make_shared(dataSyncManager); + saveSubscriptionTaskPtr->SetRunnableBundleNames(bundleNamesPtr); + saveSubscriptionTaskPtr->RunTask(userId); + saveSubscriptionTaskPtr->RunTaskForBundle(userId, bundleName); + + shared_ptr optimizeStorageTaskPtr = make_shared(dataSyncManager); + optimizeStorageTaskPtr->SetRunnableBundleNames(bundleNamesPtr); + optimizeStorageTaskPtr->RunTask(userId); + optimizeStorageTaskPtr->RunTaskForBundle(userId, bundleName); + + shared_ptr reportStatisticsTaskPtr = make_shared(dataSyncManager); + reportStatisticsTaskPtr->SetRunnableBundleNames(bundleNamesPtr); + reportStatisticsTaskPtr->RunTask(userId); + reportStatisticsTaskPtr->RunTaskForBundle(userId, bundleName); + + shared_ptr periodicCheckTaskPtr = make_shared(dataSyncManager); + periodicCheckTaskPtr->SetRunnableBundleNames(bundleNamesPtr); + periodicCheckTaskPtr->RunTask(userId); + periodicCheckTaskPtr->RunTaskForBundle(userId, bundleName); + periodicCheckTaskPtr->GetTaskName(); + periodicCheckTaskPtr->GetDataSyncManager(); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || (size <= OHOS::U32_AT_SIZE << OHOS::SPLITE_SIZE)) { + return 0; + } + + OHOS::CycleTaskDerivedFuzzTest(data, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.h b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.h new file mode 100644 index 0000000..d47fc16 --- /dev/null +++ b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/cycletaskrunner_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 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 CYCLE_TASK_RUNNER_FUZZER_H +#define CYCLE_TASK_RUNNER_FUZZER_H + +#define FUZZ_PROJECT_NAME "cycletaskrunner_fuzzer" + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/project.xml b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/cycletaskrunner_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/BUILD.gn new file mode 100644 index 0000000..fab8a7a --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/BUILD.gn @@ -0,0 +1,59 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("DownloadAssetCallbackStubFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/downloadassetcallbackstub_fuzzer" + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/test/fuzztest/fuzz_common", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.cpp" ] + + deps = [ "${utils_path}:libdistributedfileutils_lite" ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "cloud_file:cloudsync_asset_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":DownloadAssetCallbackStubFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/corpus/init b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.cpp b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.cpp new file mode 100644 index 0000000..091e084 --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2024 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 "downloadassetcallbackstub_fuzzer.h" + +#include +#include + +#include "cloud_fuzzer_helper.h" +#include "download_asset_callback_client.h" +#include "download_asset_callback_stub.h" + +#include "message_parcel.h" +#include "utils_log.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t U64_AT_SIZE = 8; + +using namespace OHOS::FileManagement::CloudSync; +using namespace std; + +bool WriteInterfaceToken(MessageParcel &datas) +{ + if (!datas.WriteInterfaceToken(DownloadAssetCallbackStub::GetDescriptor())) { + LOGE("Write token failed."); + return false; + } + return true; +} + +void HandleOnFinishedFuzzTest(std::shared_ptr downloadAssetCallbackStubStr, + const uint8_t *data, + size_t size) +{ + FuzzData fuzzData(data, size); + MessageParcel datas; + if (!WriteInterfaceToken(datas)) { + return; + } + int32_t taskId = fuzzData.GetData(); + datas.WriteUint64(taskId); + int32_t result = fuzzData.GetData(); + string uri = fuzzData.GetStringFromData(static_cast(size - U32_AT_SIZE - U64_AT_SIZE)); + datas.WriteString(uri); + datas.WriteInt32(result); + datas.RewindRead(0); + // SERVICE_CMD_ON_DOWNLOAD_FINSHED + uint32_t code = 0; + MessageParcel reply; + MessageOption option; + + downloadAssetCallbackStubStr->OnRemoteRequest(code, datas, reply, option); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size < (OHOS::U32_AT_SIZE + OHOS::U64_AT_SIZE)) { + return 0; + } + + auto downloadAssetCallbackStubStr = + std::make_shared(); + OHOS::HandleOnFinishedFuzzTest(downloadAssetCallbackStubStr, data, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.h b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.h new file mode 100644 index 0000000..b544a8f --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/downloadassetcallbackstub_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 DOWMLOAD_ASSET_CALLBACK_STUB_FUZZER_H +#define DOWMLOAD_ASSET_CALLBACK_STUB_FUZZER_H + + +#define FUZZ_PROJECT_NAME "downloadassetcallbackstub_fuzzer" + + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/project.xml b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcallbackstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/BUILD.gn new file mode 100644 index 0000000..47dbbf2 --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("DownloadAssetCbMgrFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = + "${cloud_file_path}/test/fuzztest/downloadassetcbmgr_fuzzer" + include_dirs = [ + "${cloud_file_path}/test/fuzztest/fuzz_common", + "${innerkits_native_path}/cloudsync_kit_inner", + "${services_path}/cloudsyncservice/include/ipc", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.cpp" ] + + deps = [ "${services_path}/cloudsyncservice:cloudsync_sa_static" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":DownloadAssetCbMgrFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/corpus/init b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.cpp b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.cpp new file mode 100644 index 0000000..8852ee8 --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 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 "downloadassetcbmgr_fuzzer.h" + +#include +#include + +#include "cloud_fuzzer_helper.h" +#include "download_asset_callback_manager.h" +#include "iremote_stub.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t U64_AT_SIZE = 8; + +using namespace std; +using namespace OHOS::FileManagement::CloudSync; + +class IDownloadAssetCallbackTest : public IRemoteStub { +public: + using TaskId = uint64_t; + void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) override {} +}; + +bool DoSomethingInterestingWithMyAPI(const uint8_t *data, size_t size) +{ + FuzzData fuzzData(data, size); + sptr callback = new (std::nothrow) IDownloadAssetCallbackTest(); + if (callback == nullptr) { + return false; + } + uint64_t taskId = fuzzData.GetData(); + int32_t result = fuzzData.GetData(); + size_t remainSize = fuzzData.GetRemainSize(); + string uri = fuzzData.GetStringFromData(static_cast(remainSize)); + DownloadAssetCallbackManager::GetInstance().AddCallback(callback); + DownloadAssetCallbackManager::GetInstance().OnDownloadFinshed(taskId, uri, result); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size <= OHOS::U32_AT_SIZE + OHOS::U64_AT_SIZE) { + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} \ No newline at end of file diff --git a/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.h b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.h new file mode 100644 index 0000000..2129486 --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/downloadassetcbmgr_fuzzer.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 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 DOWNLOAD_ASSET_CB_MGR_FUZZER_H +#define DOWNLOAD_ASSET_CB_MGR_FUZZER_H + +#define FUZZ_PROJECT_NAME "downloadassetcbmgr_fuzzer" + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/project.xml b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/downloadassetcbmgr_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/ffrttimer_fuzzer/BUILD.gn b/cloud_file/test/fuzztest/ffrttimer_fuzzer/BUILD.gn new file mode 100644 index 0000000..8369165 --- /dev/null +++ b/cloud_file/test/fuzztest/ffrttimer_fuzzer/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") +ohos_fuzztest("FfrtTimerFuzzTest") { + module_out_path = "cloud_file/cloud_file" + fuzz_config_file = "${cloud_file_path}/test/fuzztest/ffrttimer_fuzzer" + include_dirs = [ + "${cloud_file_path}/test/fuzztest/fuzz_common", + "${utils_path}/inner_api", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-flto", + "-fvisibility=hidden", + "--coverage", + ] + ldflags = [ + "-flto", + "--coverage", + ] + sources = [ "${cloud_file_path}/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.cpp" ] + + deps = [ "${utils_path}:libdistributedfileutils_lite" ] + + external_deps = [ + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + ] +} + +group("fuzztest") { + testonly = true + deps = [ ":FfrtTimerFuzzTest" ] +} diff --git a/cloud_file/test/fuzztest/ffrttimer_fuzzer/corpus/init b/cloud_file/test/fuzztest/ffrttimer_fuzzer/corpus/init new file mode 100644 index 0000000..e7c3fec --- /dev/null +++ b/cloud_file/test/fuzztest/ffrttimer_fuzzer/corpus/init @@ -0,0 +1,14 @@ +# Copyright (c) 2024 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. + +FUZZ \ No newline at end of file diff --git a/cloud_file/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.cpp b/cloud_file/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.cpp new file mode 100644 index 0000000..15b8321 --- /dev/null +++ b/cloud_file/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 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 "ffrttimer_fuzzer.h" + +#include +#include + +#include "cloud_fuzzer_helper.h" +#include "ffrt_timer.h" + +namespace OHOS { +constexpr size_t U32_AT_SIZE = 4; + +using namespace OHOS::FileManagement::CloudFile; +using namespace std; + +bool DoSomethingInterestingWithMyAPI(const uint8_t *data, size_t size) +{ + FuzzData fuzzData(data, size); + int len = static_cast(size - (U32_AT_SIZE << 1)); + string name = fuzzData.GetStringFromData(len + 1); + FfrtTimer fTimer{name}; + uint32_t interval = fuzzData.GetData(); + uint32_t repatTimes = fuzzData.GetData(); + fTimer.Start([]() -> void {}, interval, repatTimes); + fTimer.Start([]() -> void {}, interval, repatTimes); + fTimer.Stop(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr || size <= (OHOS::U32_AT_SIZE << 1)) { + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(data, size); + return 0; +} diff --git a/cloud_file/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.h b/cloud_file/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.h new file mode 100644 index 0000000..ce85eb9 --- /dev/null +++ b/cloud_file/test/fuzztest/ffrttimer_fuzzer/ffrttimer_fuzzer.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 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 FFRT_TIMER_FUZZER_H +#define FFRT_TIMER_FUZZER_H + + +#define FUZZ_PROJECT_NAME "ffrttimer_fuzzer" + + +#endif \ No newline at end of file diff --git a/cloud_file/test/fuzztest/ffrttimer_fuzzer/project.xml b/cloud_file/test/fuzztest/ffrttimer_fuzzer/project.xml new file mode 100644 index 0000000..7133b2b --- /dev/null +++ b/cloud_file/test/fuzztest/ffrttimer_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/cloud_file/test/fuzztest/fuzz_common/cloud_fuzzer_helper.h b/cloud_file/test/fuzztest/fuzz_common/cloud_fuzzer_helper.h new file mode 100644 index 0000000..50d07d1 --- /dev/null +++ b/cloud_file/test/fuzztest/fuzz_common/cloud_fuzzer_helper.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2024 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 CLOUD_FUZZER_HELPER_H +#define CLOUD_FUZZER_HELPER_H + +#include "securec.h" +#include + +namespace OHOS { +class FuzzData { +public: + FuzzData(const uint8_t *data, size_t size) + { + baseData = data; + baseSize = size; + } + + void ResetData(size_t newSize) + { + if (newSize <= baseSize) { + baseSize = newSize; + } + basePos = 0; + } + + template + T GetData() + { + T object{}; + size_t objectSize = sizeof(object); + if (baseData == nullptr || objectSize > baseSize - basePos) { + return object; + } + if (memcpy_s(&object, objectSize, baseData + basePos, objectSize) != EOK) { + return {}; + } + basePos = basePos + objectSize; + return object; + } + + size_t GetRemainSize() const + { + return baseSize - basePos; + } + + std::string GetStringFromData(int len) + { + if (len <= 0 || baseData == nullptr || basePos >= baseSize) { + return ""; + } + + std::string cstr; + for (int i = 0; i < len; ++i) { + if (basePos >= baseSize) { + basePos = 0; + } + char tmp = GetData(); + if (tmp == '\0') { + cstr.push_back('1'); + } else { + cstr.push_back(tmp); + } + } + return cstr; + } + +private: + const uint8_t *baseData{nullptr}; + size_t baseSize{0}; + size_t basePos{0}; +}; +} // namespace OHOS +#endif // CLOUD_FUZZER_HELPER_H diff --git a/cloud_file/test/mock/battersrvclient_mock.cpp b/cloud_file/test/mock/battersrvclient_mock.cpp new file mode 100644 index 0000000..6a1b54f --- /dev/null +++ b/cloud_file/test/mock/battersrvclient_mock.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 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 "battersrvclient_mock.h" +#include "utils_log.h" + +namespace OHOS::PowerMgr { + +int32_t BatterySrvClient::GetCapacity() +{ + return FileManagement::CloudSync::DfsBatterySrvClient::dfsBatterySrvClient->GetCapacity(); +} + +} \ No newline at end of file diff --git a/cloud_file/test/mock/battersrvclient_mock.h b/cloud_file/test/mock/battersrvclient_mock.h new file mode 100644 index 0000000..7f4b165 --- /dev/null +++ b/cloud_file/test/mock/battersrvclient_mock.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 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 OHOS_DFS_BATTERYSRVCLENT_MOCK_H +#define OHOS_DFS_BATTERYSRVCLENT_MOCK_H + +#include +#include "battery_srv_client.h" + +namespace OHOS::FileManagement::CloudSync { + +class DfsBatterySrvClient { +public: + virtual int32_t GetCapacity() = 0; +public: + DfsBatterySrvClient() = default; + virtual ~DfsBatterySrvClient() = default; + static inline std::shared_ptr dfsBatterySrvClient = nullptr; +}; + +class BatterySrvClientMock : public DfsBatterySrvClient { +public: + MOCK_METHOD0(GetCapacity, int32_t()); +}; + +} +#endif \ No newline at end of file diff --git a/cloud_file/test/mock/cloud_daemon_manager_impl_mock.cpp b/cloud_file/test/mock/cloud_daemon_manager_impl_mock.cpp new file mode 100644 index 0000000..2180a53 --- /dev/null +++ b/cloud_file/test/mock/cloud_daemon_manager_impl_mock.cpp @@ -0,0 +1,50 @@ +/* + * 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 "cloud_daemon_manager_impl.h" +#include "cloud_daemon_service_proxy.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +using namespace OHOS::FileManagement; +CloudDaemonManagerImpl &CloudDaemonManagerImpl::GetInstance() +{ + static CloudDaemonManagerImpl instance; + return instance; +} + +int32_t CloudDaemonManagerImpl::StartFuse(int32_t userId, int32_t devFd, const string &path) +{ + auto CloudDaemonServiceProxy = CloudDaemonServiceProxy::GetInstance(); + if (!CloudDaemonServiceProxy) { + LOGE("proxy is null"); + return E_SA_LOAD_FAILED; + } + return E_OK; +} + +void CloudDaemonManagerImpl::SetDeathRecipient(const sptr &remoteObject) +{ + auto deathCallback = [this](const wptr &obj) { + LOGE("service died. Died remote obj"); + CloudDaemonServiceProxy::InvaildInstance(); + isFirstCall_.clear(); + }; + deathRecipient_ = sptr(new SvcDeathRecipient(deathCallback)); + remoteObject->AddDeathRecipient(deathRecipient_); +} +} // namespace OHOS::FileManagement::CloudFile diff --git a/cloud_file/test/mock/cloud_daemon_manager_mock.cpp b/cloud_file/test/mock/cloud_daemon_manager_mock.cpp new file mode 100644 index 0000000..c1e88fd --- /dev/null +++ b/cloud_file/test/mock/cloud_daemon_manager_mock.cpp @@ -0,0 +1,29 @@ +/* + * 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 "cloud_daemon_manager_impl.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +CloudDaemonManager &CloudDaemonManager::GetInstance() +{ + return CloudDaemonManagerImpl::GetInstance(); +} + +int32_t CloudDaemonManager::StartFuse(int32_t userId, int32_t devFd, const string &path) +{ + return 0; +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/test/mock/cloud_download_uri_manager_hook.cpp b/cloud_file/test/mock/cloud_download_uri_manager_hook.cpp new file mode 100644 index 0000000..7b10b36 --- /dev/null +++ b/cloud_file/test/mock/cloud_download_uri_manager_hook.cpp @@ -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. + */ + +#include "cloud_download_uri_manager.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; +CloudDownloadUriManager& CloudDownloadUriManager::GetInstance() +{ + static CloudDownloadUriManager mgr; + return mgr; +} + +void CloudDownloadUriManager::RemoveUri(const std::string& path) +{ + if (pathUriMap_.find(path) != pathUriMap_.end()) { + LOGI("download_file : remove path [ %{public}s ] success", GetAnonyString(path).c_str()); + pathUriMap_.erase(path); + } +} + +std::string CloudDownloadUriManager::GetUri(const std::string& path) +{ + if (path.empty()) { + LOGI("path is empty"); + return ""; + } + return path; +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/test/mock/cloud_file_kit_mock.cpp b/cloud_file/test/mock/cloud_file_kit_mock.cpp new file mode 100644 index 0000000..87b991e --- /dev/null +++ b/cloud_file/test/mock/cloud_file_kit_mock.cpp @@ -0,0 +1,30 @@ + +/* + * Copyright (c) 2024 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 +#include "cloud_file_kit.h" + +namespace OHOS::FileManagement::CloudSync { + +class CloudFileKitMock : public CloudFile::CloudFileKit { +public: + MOCK_METHOD2(GetCloudUserInfo, int32_t(const int32_t userId, CloudFile::CloudUserInfo &userInfo)); + MOCK_METHOD3(GetAppSwitchStatus, int32_t(const std::string &bundleName, const int32_t userId, bool &switchStatus)); + MOCK_METHOD3(GetAppConfigParams, int32_t(const int32_t userId, + const std::string &bundleName, std::map ¶m)); +}; + +} \ No newline at end of file diff --git a/cloud_file/test/mock/clouddisk_notify_mock.cpp b/cloud_file/test/mock/clouddisk_notify_mock.cpp new file mode 100644 index 0000000..025825b --- /dev/null +++ b/cloud_file/test/mock/clouddisk_notify_mock.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 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. + */ +/* + * Copyright (c) 2024 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 "clouddisk_notify.h" + +namespace OHOS::FileManagement::CloudDisk { + +CloudDiskNotify &CloudDiskNotify::GetInstance() +{ + static CloudDiskNotify instance_; + return instance_; +} + +void CloudDiskNotify::TryNotify(const NotifyParamDisk ¶mDisk, const ParamDiskOthers ¶mOthers) {} + +void CloudDiskNotify::TryNotifyService(const NotifyParamService ¶mService, const ParamServiceOther ¶mOthers) {} + +int32_t CloudDiskNotify::GetDeleteNotifyData(const vector &deleteIds, + vector ¬ifyDataList, + const ParamServiceOther ¶mOthers) +{ + return 0; +} + +void CloudDiskNotify::AddNotify(const NotifyData ¬ifyData) {} + +void CloudDiskNotify::NotifyChangeOuter() {} +} // namespace OHOS::FileManagement::CloudDisk diff --git a/cloud_file/test/mock/cloudsyncservice/transport/softbus_adapter_mock.cpp b/cloud_file/test/mock/cloudsyncservice/transport/softbus_adapter_mock.cpp new file mode 100644 index 0000000..a7788c0 --- /dev/null +++ b/cloud_file/test/mock/cloudsyncservice/transport/softbus_adapter_mock.cpp @@ -0,0 +1,130 @@ +/* +* Copyright (c) 2024 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 "softbus_adapter_mock.h" + +namespace OHOS::FileManagement::CloudSync { + +SoftbusAdapter &SoftbusAdapter::GetInstance() +{ + static SoftbusAdapter adapter; + return adapter; +} + +int32_t SoftbusAdapter::CreateSessionServer(const char *packageName, const char *sessionName) +{ + if (ISoftbusAdapterMock::iSoftbusAdapterMock_ == nullptr) { + return -1; + } + return ISoftbusAdapterMock::iSoftbusAdapterMock_->CreateSessionServer(packageName, sessionName); +} + +int32_t SoftbusAdapter::RemoveSessionServer(const char *packageName, const char *sessionName) +{ + return 0; +} + +int32_t SoftbusAdapter::OpenSession(char *sessionName, char *peerDeviceId, char *groupId, TransDataType dataType) +{ + if (ISoftbusAdapterMock::iSoftbusAdapterMock_ == nullptr) { + return -1; + } + return ISoftbusAdapterMock::iSoftbusAdapterMock_->OpenSession(sessionName, + peerDeviceId, groupId, dataType); +} + +int SoftbusAdapter::OpenSessionByP2P(char *sessionName, char *peerDeviceId, char *groupId, bool isFileType) +{ + TransDataType dataType; + if (isFileType) { + dataType = DATA_TYPE_FILE; + } else { + dataType = DATA_TYPE_BYTES; + } + return OpenSession(sessionName, peerDeviceId, groupId, dataType); +} + +int SoftbusAdapter::SendBytes(int sessionId, const void *data, unsigned int dataLen) +{ + if (ISoftbusAdapterMock::iSoftbusAdapterMock_ == nullptr) { + return -1; + } + return ISoftbusAdapterMock::iSoftbusAdapterMock_->SendBytes(sessionId, data, dataLen); +} + +int SoftbusAdapter::SendFile(int sessionId, const std::vector &sFileList, + const std::vector &dFileList) +{ + if (ISoftbusAdapterMock::iSoftbusAdapterMock_ == nullptr) { + return -1; + } + return ISoftbusAdapterMock::iSoftbusAdapterMock_->SendFile(sessionId, sFileList, dFileList); +} + +void SoftbusAdapter::OnBind(int socket, PeerSocketInfo info) +{ + return; +} + +void SoftbusAdapter::OnShutdown(int32_t socket, ShutdownReason reason) +{ + return; +} + +void SoftbusAdapter::OnFile(int32_t socket, FileEvent *event) +{ + return; +} +void SoftbusAdapter::OnBytes(int sessionId, const void *data, unsigned int dataLen) +{ + return; +} + +int SoftbusAdapter::OnReceiveFileProcess(int sessionId, const char *firstFile, + uint64_t bytesUpload, uint64_t bytesTotal) +{ + return 0; +} + +void SoftbusAdapter::OnReceiveFileFinished(int sessionId, const char *files, int fileCnt) +{ + return; +} + +const char* SoftbusAdapter::GetRecvPath() +{ + return ""; +} + +void SoftbusAdapter::RegisterSessionListener(std::string sessionName, std::shared_ptr listener) +{ + return; +} + +void SoftbusAdapter::UnRegisterSessionListener(std::string sessionName) +{ + return; +} + +void SoftbusAdapter::CloseSession(int sessionId) +{ + return; +} + +bool SoftbusAdapter::IsSessionOpened(int sessionId) +{ + return false; +} +} \ No newline at end of file diff --git a/cloud_file/test/mock/cloudsyncservice/transport/softbus_adapter_mock.h b/cloud_file/test/mock/cloudsyncservice/transport/softbus_adapter_mock.h new file mode 100644 index 0000000..0eec03a --- /dev/null +++ b/cloud_file/test/mock/cloudsyncservice/transport/softbus_adapter_mock.h @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2024 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 FILEMANAGEMENT_cloud_file_SOFTBUS_ADAPTER_MOCK_H +#define FILEMANAGEMENT_cloud_file_SOFTBUS_ADAPTER_MOCK_H + +#include +#include "transport/softbus/softbus_adapter.h" + +namespace OHOS::FileManagement::CloudSync { +class ISoftbusAdapterMock { +public: + ISoftbusAdapterMock() = default; + virtual ~ISoftbusAdapterMock() = default; + + virtual int32_t CreateSessionServer(const char *packageName, const char *sessionName) = 0; + virtual int32_t OpenSession(char *sessionName, char *peerDeviceId, char *groupId, TransDataType dataType) = 0; + virtual int OpenSessionByP2P(char *sessionName, char *peerDeviceId, char *groupId, bool isFileType) = 0; + + virtual int SendBytes(int sessionId, const void *data, unsigned int dataLen) = 0; + virtual int SendFile(int sessionId, const std::vector &sFileList, + const std::vector &dFileList) = 0; +public: + static inline std::shared_ptr iSoftbusAdapterMock_ = nullptr; +}; + +class SoftbusAdapterMock : public ISoftbusAdapterMock { +public: + MOCK_METHOD2(CreateSessionServer, int32_t(const char *packageName, const char *sessionName)); + MOCK_METHOD4(OpenSession, int32_t(char *sessionName, char *peerDeviceId, char *groupId, TransDataType dataType)); + MOCK_METHOD4(OpenSessionByP2P, int(char *sessionName, char *peerDeviceId, char *groupId, bool isFileType)); + MOCK_METHOD3(SendBytes, int(int sessionId, const void *data, unsigned int dataLen)); + MOCK_METHOD3(SendFile, int(int sessionId, const std::vector &sFileList, + const std::vector &dFileList)); +}; +} +#endif // FILEMANAGEMENT_cloud_file_SOFTBUS_ADAPTER_MOCK_H diff --git a/cloud_file/test/mock/cloudsyncservice/transport/softbus_session_mock.cpp b/cloud_file/test/mock/cloudsyncservice/transport/softbus_session_mock.cpp new file mode 100644 index 0000000..a20851f --- /dev/null +++ b/cloud_file/test/mock/cloudsyncservice/transport/softbus_session_mock.cpp @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2024 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 "softbus_session_mock.h" + +namespace OHOS::FileManagement::CloudSync { + +SoftbusSession::SoftbusSession(const std::string &peerDeviceId, const std::string &sessionName, DataType type) + : peerDeviceId_(peerDeviceId), sessionName_(sessionName), type_(type) +{ +} + +int32_t SoftbusSession::Start() +{ + if (ISoftbusSessionMock::iSoftbusSessionMock_ == nullptr) { + return -1; + } + return ISoftbusSessionMock::iSoftbusSessionMock_->Start(); +} + +int32_t SoftbusSession::Stop() +{ + return 0; +} + +int32_t SoftbusSession::SendData(const void *data, uint32_t dataLen) +{ + if (ISoftbusSessionMock::iSoftbusSessionMock_ == nullptr) { + return -1; + } + return ISoftbusSessionMock::iSoftbusSessionMock_->SendData(data, dataLen); +} + +int32_t SoftbusSession::SendFile(const std::vector &sFileList, const std::vector &dFileList) +{ + if (ISoftbusSessionMock::iSoftbusSessionMock_ == nullptr) { + return -1; + } + return ISoftbusSessionMock::iSoftbusSessionMock_->SendFile(sFileList, dFileList); +} + +int32_t SoftbusSession::WaitSessionOpened(int sessionId) +{ + return 0; +} + +SoftbusSession::DataType SoftbusSession::GetDataType() +{ + return type_; +} + +std::string SoftbusSession::GetPeerDeviceId() +{ + return peerDeviceId_; +} + +int32_t SoftbusSession::GetSessionId() +{ + return 0; +} +} diff --git a/cloud_file/test/mock/cloudsyncservice/transport/softbus_session_mock.h b/cloud_file/test/mock/cloudsyncservice/transport/softbus_session_mock.h new file mode 100644 index 0000000..8efbc41 --- /dev/null +++ b/cloud_file/test/mock/cloudsyncservice/transport/softbus_session_mock.h @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2024 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 FILEMANAGEMENT_cloud_file_SOFTBUS_SESSION_MOCK_H +#define FILEMANAGEMENT_cloud_file_SOFTBUS_SESSION_MOCK_H + +#include +#include "transport/softbus/softbus_session.h" + +namespace OHOS::FileManagement::CloudSync { +class ISoftbusSessionMock { +public: + enum DataType : int32_t { + TYPE_BYTES, + TYPE_FILE, + }; + ISoftbusSessionMock() = default; + ISoftbusSessionMock(const std::string &peerDeviceId, const std::string &sessionName, DataType type); + virtual ~ISoftbusSessionMock() = default; + + virtual int32_t Start() = 0; + + virtual int32_t SendData(const void *data, uint32_t dataLen) = 0; + virtual int32_t SendFile(const std::vector &sFileList, + const std::vector &dFileList) = 0; + virtual int32_t WaitSessionOpened(int sessionId) = 0; +public: + static inline std::shared_ptr iSoftbusSessionMock_ = nullptr; +}; + +class SoftbusSessionMock : public ISoftbusSessionMock { +public: + MOCK_METHOD0(Start, int32_t()); + MOCK_METHOD0(Stop, int32_t()); + MOCK_METHOD2(SendData, int32_t(const void *data, uint32_t dataLen)); + MOCK_METHOD2(SendFile, int32_t(const std::vector &sFileList, + const std::vector &dFileList)); + MOCK_METHOD1(WaitSessionOpened, int32_t(int sessionId)); +}; +} +#endif // FILEMANAGEMENT_cloud_file_SOFTBUS_SESSION_MOCK_H diff --git a/cloud_file/test/mock/device_manager_impl_mock.cpp b/cloud_file/test/mock/device_manager_impl_mock.cpp new file mode 100644 index 0000000..0989df7 --- /dev/null +++ b/cloud_file/test/mock/device_manager_impl_mock.cpp @@ -0,0 +1,346 @@ +/* + * 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 "device_manager_impl.h" +#include "device_manager_impl_mock.h" +#include "dm_constants.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::Storage::DistributedFile; +#ifndef NORMAL_MOCK +const std::string NETWORKID_ONE = "45656596896323231"; +const std::string NETWORKID_TWO = "45656596896323232"; +const std::string NETWORKID_THREE = "45656596896323233"; +constexpr int32_t NETWORKTYPE_WITH_WIFI = 2; +constexpr int32_t NETWORKTYPE_NONE_WIFI = 4; +#endif +DeviceManagerImpl &DeviceManagerImpl::GetInstance() +{ + GTEST_LOG_(INFO) << "GetInstance start"; + static DeviceManagerImpl instance; + return instance; +} + +int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) +{ + return DfsDeviceManagerImpl::dfsDeviceManagerImpl->InitDeviceManager(pkgName, dmInitCallback); +} + +int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) +{ + return DfsDeviceManagerImpl::dfsDeviceManagerImpl->UnInitDeviceManager(pkgName); +} + +int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, + const std::string &extra, + std::vector &deviceList) +{ + return DfsDeviceManagerImpl::dfsDeviceManagerImpl->GetTrustedDeviceList(pkgName, extra, deviceList); +} + +int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, + const std::string &extra, + bool isRefresh, + std::vector &deviceList) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetAvailableDeviceList(const std::string &pkgName, + std::vector &deviceList) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetDeviceInfo(const std::string &pkgName, + const std::string networkId, + DmDeviceInfo &deviceInfo) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) +{ + return DfsDeviceManagerImpl::dfsDeviceManagerImpl->GetLocalDeviceInfo(pkgName, info); +} + +int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, + const std::string &extra, + std::shared_ptr callback) +{ + return DfsDeviceManagerImpl::dfsDeviceManagerImpl->RegisterDevStateCallback(pkgName, extra, callback); +} + +int32_t DeviceManagerImpl::RegisterDevStatusCallback(const std::string &pkgName, + const std::string &extra, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) +{ + return DfsDeviceManagerImpl::dfsDeviceManagerImpl->UnRegisterDevStateCallback(pkgName); +} + +int32_t DeviceManagerImpl::UnRegisterDevStatusCallback(const std::string &pkgName) +{ + return 0; +} + +int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, + const DmSubscribeInfo &subscribeInfo, + const std::string &extra, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, + uint64_t tokenId, + const std::string &filterOptions, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + return 0; +} + +int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::string &pkgName) +{ + return 0; +} + +int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, + const DmPublishInfo &publishInfo, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId) +{ + return 0; +} + +int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, + int32_t authType, + const DmDeviceInfo &deviceInfo, + const std::string &extra, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + return 0; +} + +int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) +{ + return 0; +} + +int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, + const std::string &authPara, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &dmFaParam) +{ + return 0; +} + +int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t action, const std::string ¶ms) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, + const std::string &netWorkId, + std::string &udid) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, + const std::string &netWorkId, + std::string &uuid) +{ + return 0; +} + +int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ + return 0; +} + +int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ + return 0; +} + +int32_t DeviceManagerImpl::RequestCredential(const std::string &pkgName, + const std::string &reqJsonStr, + std::string &returnJsonStr) +{ + return 0; +} + +int32_t DeviceManagerImpl::ImportCredential(const std::string &pkgName, const std::string &credentialInfo) +{ + return 0; +} + +int32_t DeviceManagerImpl::DeleteCredential(const std::string &pkgName, const std::string &deleteInfo) +{ + return 0; +} + +int32_t DeviceManagerImpl::RegisterCredentialCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::UnRegisterCredentialCallback(const std::string &pkgName) +{ + return 0; +} + +int32_t DeviceManagerImpl::NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event) +{ + return 0; +} + +int32_t DeviceManagerImpl::OnDmServiceDied() +{ + return 0; +} + +int32_t DeviceManagerImpl::GetEncryptedUuidByNetworkId(const std::string &pkgName, + const std::string &networkId, + std::string &uuid) +{ + return 0; +} + +int32_t DeviceManagerImpl::GenerateEncryptedUuid(const std::string &pkgName, + const std::string &uuid, + const std::string &appId, + std::string &encryptedUuid) +{ + return 0; +} + +int32_t DeviceManagerImpl::CheckAPIAccessPermission() +{ + return 0; +} + +int32_t DeviceManagerImpl::CheckNewAPIAccessPermission() +{ + return 0; +} + +int32_t DeviceManagerImpl::GetLocalDeviceNetWorkId(const std::string &pkgName, std::string &networkId) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetLocalDeviceId(const std::string &pkgName, std::string &deviceId) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetLocalDeviceName(const std::string &pkgName, std::string &deviceName) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetLocalDeviceType(const std::string &pkgName, int32_t &deviceType) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetDeviceName(const std::string &pkgName, + const std::string &networkId, + std::string &deviceName) +{ + return 0; +} + +int32_t DeviceManagerImpl::GetDeviceType(const std::string &pkgName, const std::string &networkId, int32_t &deviceType) +{ + return 0; +} + +int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, + int32_t bindType, + const std::string &deviceId, + const std::string &bindParam, + std::shared_ptr callback) +{ + return 0; +} + +int32_t DeviceManagerImpl::UnBindDevice(const std::string &pkgName, const std::string &deviceId) +{ + return 0; +} + +#ifdef NORMAL_MOCK +int32_t DeviceManagerImpl::GetNetworkTypeByNetworkId(const std::string &pkgName, + const std::string &netWorkId, + int32_t &netWorkType) +{ + return DfsDeviceManagerImpl::dfsDeviceManagerImpl->GetNetworkTypeByNetworkId(pkgName, netWorkId, netWorkType); +} +#else +int32_t DeviceManagerImpl::GetNetworkTypeByNetworkId(const std::string &pkgName, + const std::string &netWorkId, + int32_t &netWorkType) +{ + GTEST_LOG_(INFO) << "GetTrustedDeviceList start"; + if (netWorkId == NETWORKID_ONE) { + return ERR_DM_INPUT_PARA_INVALID; + } + + if (netWorkId == NETWORKID_TWO) { + netWorkType = NETWORKTYPE_WITH_WIFI; + return DM_OK; + } + + netWorkType = NETWORKTYPE_NONE_WIFI; + return DM_OK; +} +#endif +} // namespace DistributedHardware +} // namespace OHOS diff --git a/cloud_file/test/mock/device_manager_impl_mock.h b/cloud_file/test/mock/device_manager_impl_mock.h new file mode 100644 index 0000000..81d15c0 --- /dev/null +++ b/cloud_file/test/mock/device_manager_impl_mock.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2024 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 OHOS_cloud_file_DEVICE_MANAGER_MOCK_H +#define OHOS_cloud_file_DEVICE_MANAGER_MOCK_H + +#include +#include +#include + +#include "device_manager.h" +#include "softbus_bus_center.h" + +namespace OHOS::Storage::DistributedFile { +using namespace OHOS::DistributedHardware; +class DfsDeviceManagerImpl { +public: + virtual ~DfsDeviceManagerImpl() = default; +public: + virtual int32_t InitDeviceManager(const std::string &pkgName, + std::shared_ptr dmInitCallback) = 0; + virtual int32_t UnInitDeviceManager(const std::string &pkgName) = 0; + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, + const std::string &extra, std::vector &deviceList) = 0; + virtual int32_t RegisterDevStateCallback(const std::string &pkgName, + const std::string &extra, std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) = 0; + virtual int32_t GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) = 0; + #ifdef NORMAL_MOCK + virtual int32_t GetNetworkTypeByNetworkId(const std::string &pkgName, const std::string &netWorkId, + int32_t &netWorkType) = 0; + #endif +public: + virtual int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info) = 0; +public: + static inline std::shared_ptr dfsDeviceManagerImpl = nullptr; +}; + +class DeviceManagerImplMock : public DfsDeviceManagerImpl { +public: + MOCK_METHOD2(InitDeviceManager, int32_t(const std::string &pkgName, + std::shared_ptr dmInitCallback)); + MOCK_METHOD1(UnInitDeviceManager, int32_t(const std::string &pkgName)); + MOCK_METHOD3(GetTrustedDeviceList, int32_t(const std::string &pkgName, + const std::string &extra, std::vector &deviceList)); + MOCK_METHOD3(RegisterDevStateCallback, int32_t(const std::string &pkgName, + const std::string &extra, std::shared_ptr callback)); + MOCK_METHOD1(UnRegisterDevStateCallback, int32_t(const std::string &pkgName)); + MOCK_METHOD2(GetLocalNodeDeviceInfo, int32_t(const char *pkgName, NodeBasicInfo *info)); + MOCK_METHOD2(GetLocalDeviceInfo, int32_t(const std::string &pkgName, DmDeviceInfo &info)); + #ifdef NORMAL_MOCK + MOCK_METHOD3(GetNetworkTypeByNetworkId, int32_t(const std::string &pkgName, const std::string &netWorkId, + int32_t &netWorkType)); + #endif +}; +} +#endif \ No newline at end of file diff --git a/cloud_file/test/mock/device_manager_mock.cpp b/cloud_file/test/mock/device_manager_mock.cpp new file mode 100644 index 0000000..bc8f705 --- /dev/null +++ b/cloud_file/test/mock/device_manager_mock.cpp @@ -0,0 +1,29 @@ +/* + * 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 "device_manager.h" + +#include "device_manager_impl.h" +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DeviceManager &DeviceManager::GetInstance() +{ + GTEST_LOG_(INFO) << "GetInstance start"; + return DeviceManagerImpl::GetInstance(); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/cloud_file/test/mock/if_system_ability_manager_mock.h b/cloud_file/test/mock/if_system_ability_manager_mock.h new file mode 100644 index 0000000..630a947 --- /dev/null +++ b/cloud_file/test/mock/if_system_ability_manager_mock.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2024 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 INTERFACES_INNERKITS_SAMGR_INCLUDE_IF_SYSTEM_ABILITY_MANAGER_MOCK_H +#define INTERFACES_INNERKITS_SAMGR_INCLUDE_IF_SYSTEM_ABILITY_MANAGER_MOCK_H + +#include "if_system_ability_manager.h" + +namespace OHOS { +class ISystemAbilityManagerMock : public ISystemAbilityManager { +public: + MOCK_METHOD0(AsObject, sptr()); + MOCK_METHOD1(ListSystemAbilities, std::vector(unsigned int dumpFlags)); + MOCK_METHOD1(GetSystemAbility, sptr(int32_t systemAbilityId)); + MOCK_METHOD1(CheckSystemAbility, sptr(int32_t systemAbilityId)); + MOCK_METHOD1(RemoveSystemAbility, int32_t(int32_t systemAbilityId)); + MOCK_METHOD2(SubscribeSystemAbility, int32_t(int32_t systemAbilityId, + const sptr& listener)); + MOCK_METHOD2(UnSubscribeSystemAbility, int32_t(int32_t systemAbilityId, + const sptr& listener)); + MOCK_METHOD2(GetSystemAbility, sptr(int32_t systemAbilityId, const std::string& deviceId)); + MOCK_METHOD2(CheckSystemAbility, sptr(int32_t systemAbilityId, const std::string& deviceId)); + MOCK_METHOD2(AddOnDemandSystemAbilityInfo, int32_t(int32_t systemAbilityId, + const std::u16string& localAbilityManagerName)); + MOCK_METHOD2(CheckSystemAbility, sptr(int32_t systemAbilityId, bool& isExist)); + MOCK_METHOD3(AddSystemAbility, int32_t(int32_t systemAbilityId, const sptr& ability, + const SAExtraProp& extraProp)); + MOCK_METHOD2(AddSystemProcess, int32_t(const std::u16string& procName, const sptr& procObject)); + MOCK_METHOD2(LoadSystemAbility, sptr(int32_t systemAbilityId, int32_t timeout)); + MOCK_METHOD2(LoadSystemAbility, int32_t(int32_t systemAbilityId, const sptr& callback)); + MOCK_METHOD3(LoadSystemAbility, int32_t(int32_t systemAbilityId, const std::string& deviceId, + const sptr& callback)); + MOCK_METHOD1(UnloadSystemAbility, int32_t(int32_t systemAbilityId)); + MOCK_METHOD1(CancelUnloadSystemAbility, int32_t(int32_t systemAbilityId)); + MOCK_METHOD0(UnloadAllIdleSystemAbility, int32_t()); + MOCK_METHOD2(GetSystemProcessInfo, int32_t(int32_t systemAbilityId, SystemProcessInfo& systemProcessInfo)); + MOCK_METHOD1(GetRunningSystemProcess, int32_t(std::list& systemProcessInfos)); + MOCK_METHOD1(SubscribeSystemProcess, int32_t(const sptr& listener)); + MOCK_METHOD4(SendStrategy, int32_t(int32_t type, std::vector& systemAbilityIds, + int32_t level, std::string& action)); + MOCK_METHOD1(UnSubscribeSystemProcess, int32_t(const sptr& listener)); + MOCK_METHOD2(GetOnDemandReasonExtraData, int32_t(int64_t extraDataId, MessageParcel& extraDataParcel)); + MOCK_METHOD3(GetOnDemandPolicy, int32_t(int32_t systemAbilityId, OnDemandPolicyType type, + std::vector& abilityOnDemandEvents)); + MOCK_METHOD3(UpdateOnDemandPolicy, int32_t(int32_t systemAbilityId, OnDemandPolicyType type, + const std::vector& abilityOnDemandEvents)); + MOCK_METHOD1(GetOnDemandSystemAbilityIds, int32_t(std::vector& systemAbilityIds)); + MOCK_METHOD2(GetExtensionSaIds, int32_t(const std::string& extension, std::vector &saIds)); + MOCK_METHOD2(GetExtensionRunningSaList, int32_t(const std::string& extension, + std::vector>& saList)); + MOCK_METHOD2(GetRunningSaExtensionInfoList, int32_t(const std::string& extension, + std::vector& infoList)); + MOCK_METHOD3(GetCommonEventExtraDataIdlist, int32_t(int32_t systemAbilityId, + std::vector& extraDataIdList, const std::string& eventName)); + MOCK_METHOD1(GetLocalAbilityManagerProxy, sptr(int32_t)); +}; +} // namespace OHOS + +#endif // INTERFACES_INNERKITS_SAMGR_INCLUDE_IF_SYSTEM_ABILITY_MANAGER_MOCK_H \ No newline at end of file diff --git a/cloud_file/test/mock/ipc/cloud_sync_service_proxy_mock.cpp b/cloud_file/test/mock/ipc/cloud_sync_service_proxy_mock.cpp new file mode 100644 index 0000000..a19d9ba --- /dev/null +++ b/cloud_file/test/mock/ipc/cloud_sync_service_proxy_mock.cpp @@ -0,0 +1,95 @@ +/* + * 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 "cloud_sync_service_proxy.h" + +#include + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "iservice_registry.h" +#include "i_cloud_sync_service_mock.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +int32_t CloudSyncServiceProxy::RegisterCallbackInner(const sptr &remoteObject, + const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StartSyncInner(bool forceFlag, const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::StopSyncInner(const std::string &bundleName, bool forceFlag) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::Clean(const std::string &accountId, const CleanOptions &cleanOptions) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::NotifyDataChange(const std::string &accoutId, const std::string &bundleName) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) +{ + return E_OK; +} + +int32_t CloudSyncServiceProxy::DisableCloud(const std::string &accoutId) +{ + return E_OK; +} + +sptr CloudSyncServiceProxy::GetInstance() +{ + serviceProxy_ = iface_cast(sptr(new CloudSyncServiceMock())); + return serviceProxy_; +} + +int32_t UploadAsset(const int32_t userId, const std::string &request, std::string &result) +{ + return E_OK; +} + +int32_t DownloadFile(const int32_t userId, const std::string &bundleName, AssetInfoObj &assetInfoObj) +{ + return E_OK; +} + +int32_t DeleteAsset(const int32_t userId, const std::string &uri) +{ + return E_OK; +} + +int32_t DownloadThumb() +{ + return E_OK; +} +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/test/mock/ipc/cloud_sync_service_proxy_unnomal_mock.cpp b/cloud_file/test/mock/ipc/cloud_sync_service_proxy_unnomal_mock.cpp new file mode 100644 index 0000000..901342c --- /dev/null +++ b/cloud_file/test/mock/ipc/cloud_sync_service_proxy_unnomal_mock.cpp @@ -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. + */ +#include "cloud_sync_service_proxy.h" + +#include + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "iservice_registry.h" +#include "i_cloud_sync_service_mock.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace std; + +sptr CloudSyncServiceProxy::GetInstance() +{ + return nullptr; +} + +} // namespace OHOS::FileManagement::CloudSync diff --git a/cloud_file/test/mock/message_parcel_mock.cpp b/cloud_file/test/mock/message_parcel_mock.cpp new file mode 100644 index 0000000..3e250f8 --- /dev/null +++ b/cloud_file/test/mock/message_parcel_mock.cpp @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2024 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 "iremote_broker.h" +#include "message_parcel_mock.h" + +namespace OHOS { +using namespace OHOS::Storage::DistributedFile; + +Parcelable::Parcelable() : Parcelable(false) +{} + +Parcelable::Parcelable(bool asRemote) +{ + asRemote_ = asRemote; + behavior_ = 0; +} + +bool MessageParcel::WriteInterfaceToken(std::u16string name) +{ + return DfsMessageParcel::messageParcel->WriteInterfaceToken(name); +} + +std::u16string MessageParcel::ReadInterfaceToken() +{ + return DfsMessageParcel::messageParcel->ReadInterfaceToken(); +} + +bool Parcel::WriteParcelable(const Parcelable *object) +{ + return DfsMessageParcel::messageParcel->WriteParcelable(object); +} + +bool Parcel::WriteInt32(int32_t value) +{ + return DfsMessageParcel::messageParcel->WriteInt32(value); +} + +int32_t Parcel::ReadInt32() +{ + return DfsMessageParcel::messageParcel->ReadInt32(); +} + +bool Parcel::ReadInt32(int32_t &value) +{ + return DfsMessageParcel::messageParcel->ReadInt32(value); +} + +bool Parcel::WriteRemoteObject(const Parcelable *object) +{ + return DfsMessageParcel::messageParcel->WriteRemoteObject(object); +} + +bool MessageParcel::WriteRemoteObject(const sptr &object) +{ + return DfsMessageParcel::messageParcel->WriteRemoteObject(object); +} + +sptr MessageParcel::ReadRemoteObject() +{ + return DfsMessageParcel::messageParcel->ReadRemoteObject(); +} + +bool Parcel::ReadBool() +{ + return DfsMessageParcel::messageParcel->ReadBool(); +} + +bool Parcel::ReadBool(bool &value) +{ + return DfsMessageParcel::messageParcel->ReadBool(value); +} + +bool Parcel::WriteBool(bool value) +{ + return DfsMessageParcel::messageParcel->WriteBool(value); +} + +bool Parcel::WriteString(const std::string &value) +{ + return DfsMessageParcel::messageParcel->WriteString(value); +} + +bool Parcel::WriteCString(const char *value) +{ + return DfsMessageParcel::messageParcel->WriteCString(value); +} + +bool Parcel::ReadString(std::string &value) +{ + return DfsMessageParcel::messageParcel->ReadString(value); +} + +bool Parcel::ReadStringVector(std::vector *value) +{ + return DfsMessageParcel::messageParcel->ReadStringVector(value); +} + +bool MessageParcel::WriteFileDescriptor(int fd) +{ + return DfsMessageParcel::messageParcel->WriteFileDescriptor(fd); +} + +int MessageParcel::ReadFileDescriptor() +{ + return DfsMessageParcel::messageParcel->ReadFileDescriptor(); +} + +bool Parcel::ReadUint32(uint32_t &value) +{ + return DfsMessageParcel::messageParcel->ReadUint32(value); +} + +bool Parcel::WriteUint64(uint64_t value) +{ + return DfsMessageParcel::messageParcel->WriteUint64(value); +} + +bool Parcel::WriteUint16(uint16_t value) +{ + return DfsMessageParcel::messageParcel->WriteUint16(value); +} + +bool Parcel::ReadUint64(uint64_t &value) +{ + return DfsMessageParcel::messageParcel->ReadUint64(value); +} + +bool Parcel::WriteStringVector(const std::vector &val) +{ + return DfsMessageParcel::messageParcel->WriteStringVector(val); +} +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/mock/message_parcel_mock.h b/cloud_file/test/mock/message_parcel_mock.h new file mode 100644 index 0000000..0c619e6 --- /dev/null +++ b/cloud_file/test/mock/message_parcel_mock.h @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2024 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 OHOS_cloud_file_MESSAGE_PARCEL_MOCK_H +#define OHOS_cloud_file_MESSAGE_PARCEL_MOCK_H + +#include +#include +#include + +#include "message_parcel.h" +#include "iremote_broker.h" + +namespace OHOS::Storage::DistributedFile { +class DfsMessageParcel { +public: + virtual ~DfsMessageParcel() = default; +public: + virtual bool WriteInterfaceToken(std::u16string name) = 0; + virtual std::u16string ReadInterfaceToken() = 0; + virtual bool WriteParcelable(const Parcelable *object) = 0; + virtual bool WriteInt32(int32_t value) = 0; + virtual int32_t ReadInt32() = 0; + virtual bool ReadInt32(int32_t &value) = 0; + virtual bool WriteRemoteObject(const Parcelable *object) = 0; + virtual bool WriteRemoteObject(const sptr &object) = 0; + virtual sptr ReadRemoteObject() = 0; + virtual bool ReadBool(); + virtual bool ReadBool(bool &value) = 0; + virtual bool WriteBool(bool value) = 0; + virtual bool WriteString(const std::string &value) = 0; + virtual bool WriteCString(const char *value) = 0; + virtual bool WriteFileDescriptor(int fd) = 0; + virtual bool ReadString(std::string &value) = 0; + virtual int ReadFileDescriptor() = 0; + virtual bool ReadStringVector(std::vector *value) = 0; + virtual bool ReadUint32(uint32_t &value) = 0; + virtual bool WriteUint64(uint64_t value) = 0; + virtual bool WriteUint16(uint16_t value) = 0; + virtual bool ReadUint64(uint64_t &value) = 0; + virtual bool WriteStringVector(const std::vector &val) = 0; +public: + static inline std::shared_ptr messageParcel = nullptr; +}; + +class MessageParcelMock : public DfsMessageParcel { +public: + MOCK_METHOD1(WriteInterfaceToken, bool(std::u16string name)); + MOCK_METHOD0(ReadInterfaceToken, std::u16string()); + MOCK_METHOD1(WriteParcelable, bool(const Parcelable *object)); + MOCK_METHOD1(WriteInt32, bool(int32_t value)); + MOCK_METHOD0(ReadInt32, int32_t()); + MOCK_METHOD1(ReadInt32, bool(int32_t &value)); + MOCK_METHOD1(WriteRemoteObject, bool(const Parcelable *object)); + MOCK_METHOD1(WriteRemoteObject, bool(const sptr &object)); + MOCK_METHOD0(ReadRemoteObject, sptr()); + MOCK_METHOD0(ReadBool, bool()); + MOCK_METHOD1(ReadBool, bool(bool &value)); + MOCK_METHOD1(WriteBool, bool(bool value)); + MOCK_METHOD1(WriteString, bool(const std::string &value)); + MOCK_METHOD1(WriteCString, bool(const char *value)); + MOCK_METHOD1(WriteFileDescriptor, bool(int fd)); + MOCK_METHOD1(ReadString, bool(std::string &value)); + MOCK_METHOD0(ReadFileDescriptor, int()); + MOCK_METHOD1(ReadStringVector, bool(std::vector *value)); + MOCK_METHOD1(ReadUint32, bool(uint32_t &value)); + MOCK_METHOD1(WriteUint64, bool(uint64_t value)); + MOCK_METHOD1(WriteUint16, bool(uint16_t value)); + MOCK_METHOD1(ReadUint64, bool(uint64_t &value)); + MOCK_METHOD1(WriteStringVector, bool(const std::vector &val)); +}; +} +#endif \ No newline at end of file diff --git a/cloud_file/test/mock/net_conn_client_mock.cpp b/cloud_file/test/mock/net_conn_client_mock.cpp new file mode 100644 index 0000000..b7f8252 --- /dev/null +++ b/cloud_file/test/mock/net_conn_client_mock.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 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 "net_conn_client_mock.h" +namespace OHOS::NetManagerStandard { + +int32_t NetConnClient::GetDefaultNet(NetHandle &netHandle) +{ + return FileManagement::CloudSync::DfsNetConnClient::dfsNetConnClient->GetDefaultNet(netHandle); +} + +} \ No newline at end of file diff --git a/cloud_file/test/mock/net_conn_client_mock.h b/cloud_file/test/mock/net_conn_client_mock.h new file mode 100644 index 0000000..2773781 --- /dev/null +++ b/cloud_file/test/mock/net_conn_client_mock.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024 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 OHOS_DFS_NET_CONN_CLIENT_MOCK_H +#define OHOS_DFS_NET_CONN_CLIENT_MOCK_H +#include +#include "net_conn_client.h" +#include "net_handle.h" + +namespace OHOS::FileManagement::CloudSync { + +class DfsNetConnClient { +public: + static NetManagerStandard::NetConnClient &GetInstance() + { + static NetManagerStandard::NetConnClient client; + return client; + } + virtual int32_t GetDefaultNet(NetManagerStandard::NetHandle &netHandle) = 0; +public: + DfsNetConnClient() = default; + virtual ~DfsNetConnClient() = default; + static inline std::shared_ptr dfsNetConnClient = nullptr; +}; + +class NetConnClientMock : public DfsNetConnClient { +public: + MOCK_METHOD1(GetDefaultNet, int32_t(NetManagerStandard::NetHandle &netHandle)); +}; +} + +#endif \ No newline at end of file diff --git a/cloud_file/test/mock/preference_helper_mock.cpp b/cloud_file/test/mock/preference_helper_mock.cpp new file mode 100644 index 0000000..2f2f26d --- /dev/null +++ b/cloud_file/test/mock/preference_helper_mock.cpp @@ -0,0 +1,78 @@ +/* + * 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 +#include +#include "preferences_helper.h" + +namespace OHOS { +namespace NativePreferences { +#define TEST_PATH "/data/service/el2/123/hmdfs/cloudfile_manager/test_key/" +class PreferencesHelperMock : public Preferences { +public: + MOCK_METHOD2(Get, PreferencesValue(const std::string &key, const PreferencesValue &defValue)); + MOCK_METHOD2(Put, int(const std::string &key, const PreferencesValue &value)); + MOCK_METHOD2(GetInt, int(const std::string &key, const int &defValue)); + MOCK_METHOD2(GetString, std::string(const std::string &key, const std::string &defValue)); + MOCK_METHOD2(GetBool, bool(const std::string &key, const bool &defValue)); + MOCK_METHOD2(GetFloat, float(const std::string &key, const float &defValue)); + MOCK_METHOD2(GetDouble, double(const std::string &key, const double &defValue)); + MOCK_METHOD2(GetLong, int64_t(const std::string &key, const int64_t &defValue)); + MOCK_METHOD0(GetAll, std::map()); + MOCK_METHOD1(HasKey, bool(const std::string &key)); + MOCK_METHOD2(PutInt, int(const std::string &key, int value)); + MOCK_METHOD2(PutString, int(const std::string &key, const std::string &value)); + MOCK_METHOD2(PutBool, int(const std::string &key, bool value)); + MOCK_METHOD2(PutLong, int(const std::string &key, int64_t value)); + MOCK_METHOD2(PutFloat, int(const std::string &key, float value)); + MOCK_METHOD2(PutDouble, int(const std::string &key, double value)); + MOCK_METHOD1(Delete, int(const std::string &key)); + MOCK_METHOD0(Clear, int()); + MOCK_METHOD0(Flush, void()); + MOCK_METHOD0(FlushSync, int()); + MOCK_METHOD2(RegisterObserver, int(std::shared_ptr preferencesObserver, RegisterMode mode)); + MOCK_METHOD2(UnRegisterObserver, int(std::shared_ptr preferencesObserver, RegisterMode mode)); +}; + +std::string PreferencesHelper::GetRealPath(const std::string &path, int &errorCode) +{ + return ""; +} + +std::shared_ptr PreferencesHelper::GetPreferences(const Options &options, int &errCode) +{ + if (options.filePath == "") { + return nullptr; + } + + if (options.filePath == TEST_PATH) { + return nullptr; + } + + std::shared_ptr pref = std::make_shared(); + return pref; +} + +int PreferencesHelper::DeletePreferences(const std::string &path) +{ + return 0; +} + +int PreferencesHelper::RemovePreferencesFromCache(const std::string &path) +{ + return 0; +} +} // End of namespace NativePreferences +} // End of namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/mock/socket_mock.cpp b/cloud_file/test/mock/socket_mock.cpp new file mode 100644 index 0000000..7e9e619 --- /dev/null +++ b/cloud_file/test/mock/socket_mock.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024 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 "socket_mock.h" + +#include "inner_socket.h" + +using namespace OHOS::Storage::DistributedFile; +int32_t Socket(SocketInfo info) +{ + return DfsSocket::dfsSocket->Socket(info); +} + +int32_t Listen(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener) +{ + return DfsSocket::dfsSocket->Listen(socket, qos, qosCount, listener); +} + +int32_t Bind(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener) +{ + return DfsSocket::dfsSocket->Bind(socket, qos, qosCount, listener); +} + +void Shutdown(int32_t socket) +{ + (void)socket; +} + +int SendFile(int32_t socket, const char *sFileList[], const char *dFileList[], uint32_t fileCnt) +{ + return DfsSocket::dfsSocket->SendFile(socket, sFileList, dFileList, fileCnt); +} + +int32_t DfsBind(int32_t socket, const ISocketListener *listener) +{ + return DfsSocket::dfsSocket->DfsBind(socket, listener); +} \ No newline at end of file diff --git a/cloud_file/test/mock/socket_mock.h b/cloud_file/test/mock/socket_mock.h new file mode 100644 index 0000000..0545310 --- /dev/null +++ b/cloud_file/test/mock/socket_mock.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2024 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 OHOS_cloud_file_SOCKET_MOCK_H +#define OHOS_cloud_file_SOCKET_MOCK_H + +#include +#include + +#include "socket.h" + +namespace OHOS::Storage::DistributedFile { +class DfsSocket { +public: + virtual ~DfsSocket() = default; +public: + virtual int32_t Socket(SocketInfo info) = 0; + virtual int32_t Listen(int32_t, const QosTV qos[], uint32_t, const ISocketListener *) = 0; + virtual int32_t Bind(int32_t, const QosTV qos[], uint32_t, const ISocketListener *) = 0; + virtual int SendFile(int32_t, const char *sFileList[], const char *dFileList[], uint32_t) = 0; + virtual int32_t DfsBind(int32_t socket, const ISocketListener *listener) = 0; +public: + static inline std::shared_ptr dfsSocket = nullptr; +}; + +class SocketMock : public DfsSocket { +public: + MOCK_METHOD1(Socket, int32_t(SocketInfo info)); + MOCK_METHOD4(Listen, int32_t(int32_t, const QosTV qos[], uint32_t, const ISocketListener *)); + MOCK_METHOD4(Bind, int32_t(int32_t, const QosTV qos[], uint32_t, const ISocketListener *)); + MOCK_METHOD4(SendFile, int(int32_t, const char *sFileList[], const char *dFileList[], uint32_t)); + MOCK_METHOD2(DfsBind, int32_t(int32_t socket, const ISocketListener *listener)); +}; +} +#endif \ No newline at end of file diff --git a/cloud_file/test/mock/softbus_bus_center_mock.cpp b/cloud_file/test/mock/softbus_bus_center_mock.cpp new file mode 100644 index 0000000..923f75b --- /dev/null +++ b/cloud_file/test/mock/softbus_bus_center_mock.cpp @@ -0,0 +1,45 @@ +/* + * 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 "softbus_bus_center.h" +#include "device_manager_impl_mock.h" + +#include "gtest/gtest.h" + +using namespace OHOS::Storage::DistributedFile; + +int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info) +{ + GTEST_LOG_(INFO) << "GetLocalNodeDeviceInfo start"; + NodeBasicInfo nodeBasicInfo = { + .networkId = "100", + .deviceName = "test", + .deviceTypeId = 1}; + (void)pkgName; + *info = nodeBasicInfo; + return DfsDeviceManagerImpl::dfsDeviceManagerImpl->GetLocalNodeDeviceInfo(pkgName, info); +} + +int32_t GetNodeKeyInfo(const char *pkgName, const char *networkId, + NodeDeviceInfoKey key, uint8_t *info, int32_t infoLen) +{ + GTEST_LOG_(INFO) << "GetNodeKeyInfo start"; + (void)pkgName; + (void)networkId; + (void)key; + (void)info; + (void)infoLen; + return 0; +} \ No newline at end of file diff --git a/cloud_file/test/mock/system_ability_manager_client_mock.cpp b/cloud_file/test/mock/system_ability_manager_client_mock.cpp new file mode 100644 index 0000000..11e4866 --- /dev/null +++ b/cloud_file/test/mock/system_ability_manager_client_mock.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2024 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 "system_ability_manager_client_mock.h" +#include "if_system_ability_manager_mock.h" +#include "utils_log.h" + +namespace OHOS { +SystemAbilityManagerClient& SystemAbilityManagerClient::GetInstance() +{ + static auto instance = std::make_shared(); + return *instance; +} + +sptr SystemAbilityManagerClient::GetSystemAbilityManager() +{ + return FileManagement::CloudSync::DfsSystemAbilityManagerClient::smc->GetSystemAbilityManager(); +} +} \ No newline at end of file diff --git a/cloud_file/test/mock/system_ability_manager_client_mock.h b/cloud_file/test/mock/system_ability_manager_client_mock.h new file mode 100644 index 0000000..068bc5a --- /dev/null +++ b/cloud_file/test/mock/system_ability_manager_client_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 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 TEST_SYSTEM_ABILITY_MANAGER_CLENT_MOCK_H +#define TEST_SYSTEM_ABILITY_MANAGER_CLENT_MOCK_H + +#include +#include "iservice_registry.h" + +namespace OHOS::FileManagement::CloudSync { +class DfsSystemAbilityManagerClient { +public: + virtual SystemAbilityManagerClient& GetInstance() = 0; + virtual sptr GetSystemAbilityManager() = 0; +public: + DfsSystemAbilityManagerClient() = default; + virtual ~DfsSystemAbilityManagerClient() = default; + static inline std::shared_ptr smc = nullptr; +}; + +class SystemAbilityManagerClientMock : public DfsSystemAbilityManagerClient { +public: + MOCK_METHOD0(GetInstance, SystemAbilityManagerClient&()); + MOCK_METHOD0(GetSystemAbilityManager, sptr()); +}; +} + +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/BUILD.gn b/cloud_file/test/unittests/BUILD.gn new file mode 100644 index 0000000..136d11b --- /dev/null +++ b/cloud_file/test/unittests/BUILD.gn @@ -0,0 +1,30 @@ +# 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. +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +group("cloudsyncunittests") { + testonly = true + if (!use_libfuzzer) { + deps = [ + "cloud_daemon:cloud_daemon_test", + "cloud_disk:cloud_disk_test", + "cloud_file_kit_inner:cloud_file_kit_inner_test", + "clouddisk_database:clouddisk_database_test", + "cloudsync_api:cloudsync_api_test", + "cloudsync_sa:cloudsync_sa_test", + "services_daemon:services_daemon_test", + "utils:utils_test", + ] + } +} diff --git a/cloud_file/test/unittests/cloud_daemon/BUILD.gn b/cloud_file/test/unittests/cloud_daemon/BUILD.gn new file mode 100644 index 0000000..582a317 --- /dev/null +++ b/cloud_file/test/unittests/cloud_daemon/BUILD.gn @@ -0,0 +1,139 @@ +# 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("cloud_daemon_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager_impl.cpp", + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp", + "../../mock/cloud_daemon_manager_mock.cpp", + "cloud_daemon_manager_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloud_daemon_kit_inner", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gtest_main", + "googletest:gmock_main", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + use_exceptions = true +} + +ohos_unittest("cloud_daemon_manager_impl_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_manager_impl.cpp", + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp", + "cloud_daemon_manager_impl_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloud_daemon_kit_inner", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + use_exceptions = true +} + +ohos_unittest("cloud_daemon_service_proxy_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/src/cloud_daemon_service_proxy.cpp", + "cloud_daemon_service_proxy_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${cloud_file_path}/frameworks/native/cloud_daemon_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloud_daemon_kit_inner", + "${cloud_file_path}/test/unittests/cloud_daemon/include", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + use_exceptions = true +} + +group("cloud_daemon_test") { + testonly = true + + deps = [ + ":cloud_daemon_manager_impl_test", + ":cloud_daemon_manager_test", + ":cloud_daemon_service_proxy_test", + ] +} diff --git a/cloud_file/test/unittests/cloud_daemon/cloud_daemon_manager_impl_test.cpp b/cloud_file/test/unittests/cloud_daemon/cloud_daemon_manager_impl_test.cpp new file mode 100644 index 0000000..aa976de --- /dev/null +++ b/cloud_file/test/unittests/cloud_daemon/cloud_daemon_manager_impl_test.cpp @@ -0,0 +1,123 @@ +/* + * 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 +#include +#include +#include +#include "cloud_daemon_manager_impl.h" +#include "cloud_daemon_service_proxy.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudDaemonManagerImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr cloudDaemonManagerImpl_; +}; + +void CloudDaemonManagerImplTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudDaemonManagerImplTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDaemonManagerImplTest::SetUp(void) +{ + cloudDaemonManagerImpl_ = std::make_shared(); + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDaemonManagerImplTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetInstanceTest + * @tc.desc: Verify the GetInstance function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonManagerImplTest, GetInstanceTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest Start"; + try { + CloudDaemonManagerImpl::GetInstance(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest ERROR"; + } + GTEST_LOG_(INFO) << "GetInstanceTest End"; +} + +/** + * @tc.name: StartFuseTest + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonManagerImplTest, StartFuseTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest Start"; + try { + int32_t devFd = -1; + string path = "path"; + int32_t userId = 100; + auto res = CloudDaemonManagerImpl::GetInstance().StartFuse(userId, devFd, path); + EXPECT_EQ(res, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuse ERROR"; + } + GTEST_LOG_(INFO) << "StartFuse End"; +} + +/** + * @tc.name: SetDeathRecipientTest + * @tc.desc: Verify the SetDeathRecipient function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonManagerImplTest, SetDeathRecipientTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetDeathRecipientTest Start"; + try { + auto CloudDaemonServiceProxy = CloudDaemonServiceProxy::GetInstance(); + EXPECT_NE(CloudDaemonServiceProxy, nullptr); + auto remoteObject = CloudDaemonServiceProxy->AsObject(); + EXPECT_NE(remoteObject, nullptr); + cloudDaemonManagerImpl_->SetDeathRecipient(remoteObject); + EXPECT_EQ(cloudDaemonManagerImpl_->isFirstCall_.test_and_set(), false); + EXPECT_NE(cloudDaemonManagerImpl_->deathRecipient_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetDeathRecipientTest ERROR"; + } + GTEST_LOG_(INFO) << "SetDeathRecipientTest End"; +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_daemon/cloud_daemon_manager_test.cpp b/cloud_file/test/unittests/cloud_daemon/cloud_daemon_manager_test.cpp new file mode 100644 index 0000000..90b017c --- /dev/null +++ b/cloud_file/test/unittests/cloud_daemon/cloud_daemon_manager_test.cpp @@ -0,0 +1,71 @@ +/* + * 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 +#include +#include "cloud_daemon_manager_impl.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudDaemonManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudDaemonManagerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudDaemonManagerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDaemonManagerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDaemonManagerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetInstanceTest + * @tc.desc: Verify the GetInstance function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonManagerTest, GetInstanceTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest Start"; + try { + CloudDaemonManager::GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest ERROR"; + } + GTEST_LOG_(INFO) << "GetInstanceTest End"; +} +} // namespace OHOS::FileManagement::CloudFile::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_daemon/cloud_daemon_service_proxy_test.cpp b/cloud_file/test/unittests/cloud_daemon/cloud_daemon_service_proxy_test.cpp new file mode 100644 index 0000000..0744c27 --- /dev/null +++ b/cloud_file/test/unittests/cloud_daemon/cloud_daemon_service_proxy_test.cpp @@ -0,0 +1,188 @@ +/* + * 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 "cloud_daemon_service_mock.h" +#include "cloud_daemon_service_proxy.h" +#include "cloud_file_daemon_interface_code.h" +#include "dfs_error.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "utils_log.h" +#include +#include +#include +#include + +static bool g_isamflag = true; +static bool g_smcflag = true; + +namespace OHOS { +class RemoteObject : public IRemoteObject { +public: + virtual int32_t GetObjectRefCount() + { + return 0; + } + virtual int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + return 0; + } + virtual bool AddDeathRecipient(const sptr &recipient) + { + return 0; + } + virtual bool RemoveDeathRecipient(const sptr &recipient) + { + return false; + } + virtual int Dump(int fd, const std::vector &args) + { + return 0; + } +}; + +sptr ISystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId) +{ + if (g_isamflag == true) { + sptr isamObject = sptr(new RemoteObject()); + return isamObject; + } else { + return nullptr; + } + return nullptr; +} + +SystemAbilityManagerClient &SystemAbilityManagerClient::GetInstance() +{ + static auto instance = new SystemAbilityManagerClient(); + return *instance; +} + +sptr SystemAbilityManagerClient::GetSystemAbilityManager() +{ + if (g_smcflag == true) { + sptr smcObject = IPCSkeleton::GetContextObject(); + systemAbilityManager_ = iface_cast(smcObject); + return systemAbilityManager_; + } else { + return nullptr; + } +} +} // namespace OHOS + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudDaemonServiceProxyTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + shared_ptr proxy_ = nullptr; + sptr mock_ = nullptr; +}; + +void CloudDaemonServiceProxyTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudDaemonServiceProxyTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDaemonServiceProxyTest::SetUp(void) +{ + mock_ = sptr(new CloudDaemonServiceMock()); + proxy_ = make_shared(mock_); + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDaemonServiceProxyTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetInstanceTest001 + * @tc.desc: Verify the GetInstance function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonServiceProxyTest, GetInstanceTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest001 Start"; + try { + g_smcflag = false; + auto CloudDaemonServiceProxy = CloudDaemonServiceProxy::GetInstance(); + EXPECT_EQ(CloudDaemonServiceProxy, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetInstanceTest001 End"; +} + +/** + * @tc.name: StartFuseTest001 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonServiceProxyTest, StartFuseTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest001 Start"; + try { + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int32_t userId = 100; + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "continue"; + int ret = proxy_->StartFuse(userId, devFd, path); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest001 ERROR"; + } + GTEST_LOG_(INFO) << "StartFuseTest001 End"; +} + +/** + * @tc.name: StartFuseTest002 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonServiceProxyTest, StartFuseTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest002 Start"; + try { + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int32_t userId = 100; + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "continue"; + int ret = proxy_->StartFuse(userId, devFd, path); + EXPECT_EQ(ret, E_BROKEN_IPC); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest002 ERROR"; + } + GTEST_LOG_(INFO) << "StartFuseTest002 End"; +} +} // namespace OHOS::FileManagement::CloudFile::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_daemon/include/cloud_daemon_service_mock.h b/cloud_file/test/unittests/cloud_daemon/include/cloud_daemon_service_mock.h new file mode 100644 index 0000000..7f044a3 --- /dev/null +++ b/cloud_file/test/unittests/cloud_daemon/include/cloud_daemon_service_mock.h @@ -0,0 +1,48 @@ +/* +* 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 MOCK_I_CLOUD_DAEMON_H +#define MOCK_I_CLOUD_DAEMON_H + +#include + +#include "i_cloud_daemon.h" +#include "iremote_stub.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +class CloudDaemonServiceMock : public IRemoteStub { +public: + int code_; + CloudDaemonServiceMock() : code_(0) {} + virtual ~ CloudDaemonServiceMock() {} + + MOCK_METHOD4(SendRequest, int(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)); + + int32_t InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + code_ = code; + return E_OK; + } + + int32_t StartFuse(int32_t userId, int32_t devFd, const string &path) + { + return E_OK; + } +}; +} // OHOS::FileManagement::CloudFile + +#endif // MOCK_I_CLOUD_DAEMON_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/BUILD.gn b/cloud_file/test/unittests/cloud_disk/BUILD.gn new file mode 100644 index 0000000..044fd59 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/BUILD.gn @@ -0,0 +1,462 @@ +# Copyright (C) 2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("account_status_listener_test") { + module_out_path = "cloud_file/cloud_file" + + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/utils/log/include", + "${innerkits_native_path}/cloud_file_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${services_path}/cloudfiledaemon/include/", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${services_path}/cloudfiledaemon/include/fuse_manager/", + ] + + sources = [ + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp", + "${services_path}/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp", + "${services_path}/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp", + "account_status_listener_test.cpp", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner_lite", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "libfuse:libfuse", + "relational_store:native_rdb", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + use_exceptions = true +} + +ohos_unittest("file_operations_cloud_test") { + module_out_path = "cloud_file/cloud_file" + + include_dirs = [ + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/utils/log/include", + "${services_path}/clouddisk_database/include", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${services_path}/cloudfiledaemon/src/cloud_disk/", + "mock", + ] + + sources = [ + "${cloud_file_path}/test/mock/clouddisk_notify_mock.cpp", + "${cloud_file_path}/test/unittests/cloud_disk/mock/file_operations_helper_mock.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/mock/meta_file_clouddisk_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp", + "file_operations_cloud_test.cpp", + "mock/clouddisk_rdbstore_mock.cpp", + "mock/libfuse_mock.cpp", + "mock/system_function_mock.cpp", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "libfuse:libfuse", + "relational_store:native_rdb", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true +} + +ohos_unittest("database_manager_test") { + module_out_path = "cloud_file/cloud_file" + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner/", + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner/", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include/", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include/", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${services_path}/clouddisk_database/include/", + ] + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager.cpp", + "${services_path}/clouddisk_database/src/clouddisk_rdb_transaction.cpp", + "${services_path}/clouddisk_database/src/clouddisk_rdb_utils.cpp", + "${services_path}/clouddisk_database/src/clouddisk_rdbstore.cpp", + "${services_path}/clouddisk_database/src/clouddisk_sync_helper.cpp", + "${services_path}/clouddisk_database/src/file_column.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "database_manager_test.cpp", + ] + + deps = [ + "${cloud_file_path}/adapter/cloud_adapter_example:cloud_adapter", + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner_lite", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "cloud_file:cloudsync_kit_inner", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "preferences:native_preferences", + "relational_store:native_rdb", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + use_exceptions = true +} + +ohos_unittest("file_operations_base_test") { + module_out_path = "cloud_file/cloud_file" + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${cloud_file_path}/test/unittests/cloud_disk/mock/", + "${cloud_file_path}/services/clouddisk_database/include/", + ] + + sources = [ + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp", + "file_operations_base_test.cpp", + "mock/clouddisk_rdbstore_mock.cpp", + "mock/libfuse_mock.cpp", + "mock/system_function_mock.cpp", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "libfuse:libfuse", + "relational_store:native_rdb", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + use_exceptions = true +} + +ohos_unittest("fuse_operations_test") { + module_out_path = "cloud_file/cloud_file" + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "${cloud_file_path}/test/unittests/cloud_disk/mock/", + ] + + sources = [ + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/parameters.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp", + "fuse_operations_test.cpp", + "mock/clouddisk_rdbstore_mock.cpp", + "mock/file_operations_local_mock.cpp", + "mock/libfuse_mock.cpp", + "mock/system_function_mock.cpp", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "libfuse:libfuse", + "relational_store:native_rdb", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true +} + +ohos_unittest("file_operations_local_test") { + module_out_path = "cloud_file/cloud_file" + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "${cloud_file_path}/test/unittests/cloud_disk/mock/", + ] + + sources = [ + "${cloud_file_path}/test/unittests/cloud_disk/mock/file_operations_helper_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/parameters.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp", + "file_operations_local_test.cpp", + "mock/clouddisk_rdbstore_mock.cpp", + "mock/libfuse_mock.cpp", + "mock/system_function_mock.cpp", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "libfuse:libfuse", + "relational_store:native_rdb", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true +} + +ohos_unittest("file_operations_helper_test") { + module_out_path = "cloud_file/cloud_file" + + include_dirs = [ + "${cloud_file_path}/utils/log/include", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "${cloud_file_path}/test/unittests/cloud_disk/mock/", + ] + + sources = [ + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/parameters.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp", + "file_operations_helper_test.cpp", + "mock/clouddisk_rdbstore_mock.cpp", + "mock/libfuse_mock.cpp", + "mock/system_function_mock.cpp", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "libfuse:libfuse", + "relational_store:native_rdb", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DAEMON_API\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true +} + +group("cloud_disk_test") { + testonly = true + + deps = [ + ":account_status_listener_test", + ":database_manager_test", + ":file_operations_base_test", + ":file_operations_cloud_test", + ":file_operations_helper_test", + ":file_operations_local_test", + ":fuse_operations_test", + ] +} diff --git a/cloud_file/test/unittests/cloud_disk/account_status_listener_test.cpp b/cloud_file/test/unittests/cloud_disk/account_status_listener_test.cpp new file mode 100644 index 0000000..c6afd03 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/account_status_listener_test.cpp @@ -0,0 +1,177 @@ +/* + * 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 +#include + +#include "account_status_listener.h" +#include "common_event_manager.h" +#include "common_event_support.h" + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using Want = OHOS::AAFwk::Want; + +constexpr int32_t USER_ID = 101; + +class AccountStatusListenerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr accountStatusListener_ = nullptr; + static inline shared_ptr accountStatusSubscriber_ = nullptr; + static inline shared_ptr subscribeInfo_ = nullptr; +}; + +void AccountStatusListenerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + subscribeInfo_ = make_shared(matchingSkills); + accountStatusSubscriber_ = make_shared(*subscribeInfo_); + accountStatusListener_ = make_shared(); +} + +void AccountStatusListenerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void AccountStatusListenerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void AccountStatusListenerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: OnReceiveEventTest001 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: issuesI90JZZ + */ +HWTEST_F(AccountStatusListenerTest, OnReceiveEventTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest001 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN); + string data(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN); + EventFwk::CommonEventData eventData(want, USER_ID, data); + accountStatusSubscriber_->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest001 ERROR"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest001 End"; +} + +/** + * @tc.name: OnReceiveEventTest002 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: issuesI90JZZ + */ +HWTEST_F(AccountStatusListenerTest, OnReceiveEventTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest002 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); + string data(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); + EventFwk::CommonEventData eventData(want, USER_ID, data); + accountStatusSubscriber_->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest002 ERROR"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest002 End"; +} + +/** + * @tc.name: OnReceiveEventTest003 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: issuesIBMCHL + */ +HWTEST_F(AccountStatusListenerTest, OnReceiveEventTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest003 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + string data(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + EventFwk::CommonEventData eventData(want, USER_ID, data); + accountStatusSubscriber_->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest003 ERROR"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest003 End"; +} + +/** + * @tc.name: StopTest001 + * @tc.desc: Verify the Stop function + * @tc.type: FUNC + * @tc.require: issuesI90JZZ + */ +HWTEST_F(AccountStatusListenerTest, StopTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopTest001 Start"; + try { + accountStatusListener_->commonEventSubscriber_ = std::make_shared(*subscribeInfo_); + accountStatusListener_->Stop(); + EXPECT_TRUE(accountStatusListener_->commonEventSubscriber_ == nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StopTest001 ERROR"; + } + GTEST_LOG_(INFO) << "StopTest001 End"; +} + +/** + * @tc.name: StopTest002 + * @tc.desc: Verify the Stop function + * @tc.type: FUNC + * @tc.require: issuesI90JZZ + */ +HWTEST_F(AccountStatusListenerTest, StopTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopTest002 Start"; + try { + accountStatusListener_->commonEventSubscriber_ = nullptr; + accountStatusListener_->Stop(); + EXPECT_TRUE(accountStatusListener_->commonEventSubscriber_ == nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StopTest002 ERROR"; + } + GTEST_LOG_(INFO) << "StopTest002 End"; +} +} // namespace OHOS::FileManagement::CloudDisk::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/database_manager_test.cpp b/cloud_file/test/unittests/cloud_disk/database_manager_test.cpp new file mode 100644 index 0000000..e3e210e --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/database_manager_test.cpp @@ -0,0 +1,117 @@ +/* + * 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 +#include + +#include "database_manager.h" + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class DatabaseManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr databaseManager_ = nullptr; +}; + +void DatabaseManagerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + databaseManager_ = make_shared(); +} + +void DatabaseManagerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + databaseManager_ = nullptr; +} + +void DatabaseManagerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void DatabaseManagerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetRdbStoreTest001 + * @tc.desc: Verify the GetRdbStore function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(DatabaseManagerTest, GetRdbStoreTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetRdbStoreTest001 start"; + try { + const std::string bundleName = "GetRdbStoreTest"; + const int32_t userId = 123456789; + databaseManager_->GetRdbStore(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetRdbStoreTest001 failed"; + } + GTEST_LOG_(INFO) << "GetRdbStoreTest001 end"; +} + +/** + * @tc.name: GetInstanceTest001 + * @tc.desc: Verify the GetInstance function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(DatabaseManagerTest, GetInstanceTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest001 start"; + try{ + DatabaseManager &instance = databaseManager_->GetInstance(); + EXPECT_NE(&instance, nullptr); + } + catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest001 failed"; + } + GTEST_LOG_(INFO) << "GetInstanceTest001 end"; +} + +/** + * @tc.name: ClearRdbStoreTest001 + * @tc.desc: Verify the ClearRdbStore function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(DatabaseManagerTest, ClearRdbStoreTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ClearRdbStore001 start"; + try{ + databaseManager_->ClearRdbStore(); + EXPECT_TRUE(true); + } + catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ClearRdbStoreTest001 failed"; + } + GTEST_LOG_(INFO) << "ClearRdbStoreTest001 end"; +} +} // namespace OHOS::FileManagement::CloudDisk::Test diff --git a/cloud_file/test/unittests/cloud_disk/file_operations_base_test.cpp b/cloud_file/test/unittests/cloud_disk/file_operations_base_test.cpp new file mode 100644 index 0000000..4083e9c --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/file_operations_base_test.cpp @@ -0,0 +1,675 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "assistant.h" +#include "cloud_disk_inode.h" +#include "dfs_error.h" +#include "file_operations_base.h" +#include "file_operations_helper.h" + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; + +class FileOperationBaseTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline FileOperationsBase* fileoperationBase_ = new FileOperationsBase(); + static inline std::shared_ptr insMock = nullptr; +}; + +void FileOperationBaseTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void FileOperationBaseTest::TearDownTestCase(void) +{ + fileoperationBase_ = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void FileOperationBaseTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + insMock = std::make_shared(); + Assistant::ins = insMock; +} + +void FileOperationBaseTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; + Assistant::ins = nullptr; + insMock = nullptr; +} + +/** + * @tc.name: ForgetTest001 + * @tc.desc: Verify the Forget function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationBaseTest, ForgetTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetTest001 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + uint64_t nLookup = 0; + + fileoperationBase_->Forget(req, FUSE_ROOT_ID, nLookup); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetTest001 End"; +} + +/** + * @tc.name: ForgetTest002 + * @tc.desc: Verify the Forget function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationBaseTest, ForgetTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + uint64_t nLookup = 0; + + fileoperationBase_->Forget(req, 0, nLookup); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetTest002 End"; +} + +/** + * @tc.name: ForgetMultiTest001 + * @tc.desc: Verify the ForgetMulti function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationBaseTest, ForgetMultiTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetMultiTest001 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_forget_data* forgets = nullptr; + + fileoperationBase_->ForgetMulti(req, 0, forgets); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetMultiTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetMultiTest001 End"; +} + +/** + * @tc.name: ForgetMultiTest002 + * @tc.desc: Verify the ForgetMulti function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationBaseTest, ForgetMultiTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetMultiTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_forget_data forgets; + forgets.ino = 2; + + fileoperationBase_->ForgetMulti(req, 1, &forgets); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetMultiTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetMultiTest002 End"; +} + +/** + * @tc.name: ForgetMultiTest003 + * @tc.desc: Verify the ForgetMulti function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationBaseTest, ForgetMultiTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetMultiTest003 Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[2] = std::make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_forget_data forgets; + forgets.ino = 2; + + fileoperationBase_->ForgetMulti(req, 1, &forgets); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetMultiTest003 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetMultiTest003 End"; +} + +/** + * @tc.name: ForgetTest003 + * @tc.desc: Verify the Forget function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationBaseTest, ForgetTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetTest003 Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[1] = std::make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + uint64_t nLookup = 1; + + fileoperationBase_->Forget(req, 1, nLookup); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetTest003 ERROR"; + } +} + +/** + * @tc.name: LookupTest001 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, LookupTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t parent = FUSE_ROOT_ID; + const char *name = "testFile"; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Lookup(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest001 failed"; + } + GTEST_LOG_(INFO) << "LookupTest001 end"; +} + +/** + * @tc.name: AccessTest001 + * @tc.desc: Verify the Access function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, AccessTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessTest001 start"; + try { + fuse_ino_t ino = FUSE_ROOT_ID; + fuse_req_t req = nullptr; + int mask = 0; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Access(req, ino, mask); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AccessTest001 failed"; + } + GTEST_LOG_(INFO) << "AccessTest001 end"; +} + +/** + * @tc.name: GetAttrTest001 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, GetAttrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->GetAttr(req, ino, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest001 failed"; + } + GTEST_LOG_(INFO) << "GetAttrTest001 end"; +} + +/** + * @tc.name: OpenTest001 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, OpenTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Open(req, ino, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest001 failed"; + } + GTEST_LOG_(INFO) << "OpenTest001 end"; +} + +/** + * @tc.name: MkDirTest001 + * @tc.desc: Verify the MkDir function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, MkDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkDirTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t parent = FUSE_ROOT_ID; + const char *name = "testMkdir"; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->MkDir(req, parent, name, 0); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkDirTest001 failed"; + } + GTEST_LOG_(INFO) << "MkDirTest001 end"; +} + +/** + * @tc.name: RmDirTest001 + * @tc.desc: Verify the RmDir function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, RmDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmDirTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t parent = FUSE_ROOT_ID; + const char *name = "testRmDir"; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->RmDir(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RmDirTest001 failed"; + } + GTEST_LOG_(INFO) << "RmDirTest001 end"; +} + +/** + * @tc.name: UnlinkTest001 + * @tc.desc: Verify the Unlink function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, UnlinkTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t parent = FUSE_ROOT_ID; + const char *name = "testUnlink"; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Unlink(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnlinkTest001 failed"; + } + GTEST_LOG_(INFO) << "UnlinkTest001 end"; +} + +/** + * @tc.name: ReleaseTest001 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, ReleaseTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t parent = FUSE_ROOT_ID; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Release(req, parent, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest001 failed"; + } + GTEST_LOG_(INFO) << "ReleaseTest001 end"; +} + +/** + * @tc.name: MkNodTest001 + * @tc.desc: Verify the MkNod function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, MkNodTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkNodTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t parent = FUSE_ROOT_ID; + const char *name = "testMkmod"; + mode_t mode = 0; + dev_t rdev = 0; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->MkNod(req, parent, name, mode, rdev); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkNodTest001 failed"; + } + GTEST_LOG_(INFO) << "MkNodTest001 end"; +} + +/** + * @tc.name: CreateTest001 + * @tc.desc: Verify the Create function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, CreateTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t parent = FUSE_ROOT_ID; + const char *name = "testMkmod"; + mode_t mode = 0; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Create(req, parent, name, mode, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkNodTest001 failed"; + } + GTEST_LOG_(INFO) << "MkNodTest001 end"; +} + +/** + * @tc.name: ReadDirTest001 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, ReadDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + size_t size = 0; + off_t off = 0; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->ReadDir(req, ino, size, off, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest001 failed"; + } + GTEST_LOG_(INFO) << "ReadDirTest001 end"; +} + +/** + * @tc.name: SetXattrTest001 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, SetXattrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + const char *name = "testSetXattr"; + const char *value = ""; + size_t size = 0; + int flags = 0; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->SetXattr(req, ino, name, value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest001 failed"; + } + GTEST_LOG_(INFO) << "SetXattrTest001 end"; +} + +/** + * @tc.name: GetXattrTest001 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, GetXattrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + const char *name = "testGetXattr"; + size_t size = 0; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->GetXattr(req, ino, name, size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest001 failed"; + } + GTEST_LOG_(INFO) << "GetXattrTest001 end"; +} + +/** + * @tc.name: RenameTest001 + * @tc.desc: Verify the Rename function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, RenameTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RenameTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = "testRename"; + fuse_ino_t newParent = FUSE_ROOT_ID; + const char *newName = "renameTest"; + unsigned int flags = 0; + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Rename(req, parent, name, newParent, newName, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RenameTest001 failed"; + } + GTEST_LOG_(INFO) << "RenameTest001 end"; +} + +/** + * @tc.name: ReadTest001 + * @tc.desc: Verify the Read function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, ReadTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + size_t size = 0; + off_t offset = 0; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Read(req, ino, size, offset, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadTest001 failed"; + } + GTEST_LOG_(INFO) << "ReadTest001 end"; +} + +/** + * @tc.name: WriteBufTest001 + * @tc.desc: Verify the WriteBuf function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, WriteBufTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteBufTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + std::shared_ptr buf = std::make_shared(); + off_t offset = 0; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->WriteBuf(req, ino, buf.get(), offset, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WriteBufTest001 failed"; + } + GTEST_LOG_(INFO) << "WriteBufTest001 end"; +} + +/** + * @tc.name: SetAttrTest001 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, SetAttrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + std::shared_ptr attr = std::make_shared(); + int valid = 0; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->SetAttr(req, ino, attr.get(), valid, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest001 failed"; + } + GTEST_LOG_(INFO) << "SetAttrTest001 end"; +} + +/** + * @tc.name: LseekTest001 + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, LseekTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + off_t offset = 0; + int whence = 0; + auto fi = std::make_shared(); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Lseek(req, ino, offset, whence, fi.get()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest001 failed"; + } + GTEST_LOG_(INFO) << "LseekTest001 end"; +} + +/** + * @tc.name: IoctlTest001 + * @tc.desc: Verify the Ioctl function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FileOperationBaseTest, IoctlTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IoctlTest001 start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + int cmd = 0x1234; + void *arg = nullptr; + unsigned flags = 0; + const void *inBuf = nullptr; + size_t inBufsz = 0; + size_t outBufsz = 0; + struct fuse_file_info *fi = nullptr; + + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).Times(1); + fileoperationBase_->Ioctl(req, ino, cmd, arg, fi, flags, inBuf, inBufsz, outBufsz); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IoctlTest001 failed"; + } + GTEST_LOG_(INFO) << "IoctlTest001 end"; +} +} // namespace OHOS::FileManagement::CloudDisk::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/file_operations_cloud_test.cpp b/cloud_file/test/unittests/cloud_disk/file_operations_cloud_test.cpp new file mode 100644 index 0000000..dbcdd98 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/file_operations_cloud_test.cpp @@ -0,0 +1,2914 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "file_operations_cloud.h" + +#include "assistant.h" +#include "cloud_disk_inode.h" +#include "clouddisk_rdb_utils.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudDisk { +size_t CloudDiskRdbUtils::FuseDentryAlignSize(const char *name) +{ + return 0; +} +} + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FileOperationsCloudTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr fileOperationsCloud_ = nullptr; + static inline shared_ptr insMock = nullptr; +}; + +void FileOperationsCloudTest::SetUpTestCase(void) +{ + fileOperationsCloud_ = make_shared(); + insMock = make_shared(); + Assistant::ins = insMock; + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void FileOperationsCloudTest::TearDownTestCase(void) +{ + Assistant::ins = nullptr; + insMock = nullptr; + fileOperationsCloud_ = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void FileOperationsCloudTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FileOperationsCloudTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: LookupTest001 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LookupTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest001 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + + fuse_ino_t parent = FUSE_ROOT_ID; + const char *name = ""; + fileOperationsCloud_->Lookup(nullptr, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest001 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest001 End"; +} + +/** + * @tc.name: LookupTest002 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LookupTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + + fuse_ino_t parent = -1; + const char *name = ""; + fileOperationsCloud_->Lookup(nullptr, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest002 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest002 End"; +} + +/** + * @tc.name: LookupTest003 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LookupTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest003 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_entry(_, _)).WillOnce(Return(E_OK)); + + fuse_ino_t parent = 4; + const char *name = ".trash"; + fileOperationsCloud_->Lookup(nullptr, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest003 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest003 End"; +} + +/** + * @tc.name: LookupTest004 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LookupTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest004 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + + fuse_ino_t parent = 4; + const char *name = "mock"; + fileOperationsCloud_->Lookup(nullptr, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest004 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest004 End"; +} + +/** + * @tc.name: LookupTest005 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LookupTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest005 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_entry(_, _)).WillOnce(Return(E_OK)); + + fuse_ino_t parent = 4; + const char *name = ""; + fileOperationsCloud_->Lookup(nullptr, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest005 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest005 End"; +} + +/** + * @tc.name: LookupTest006 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LookupTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest006 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + + fuse_ino_t parent = 2; + const char *name = "mock"; + fileOperationsCloud_->Lookup(nullptr, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest006 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest006 End"; +} + +/** + * @tc.name: LookupTest007 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LookupTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest007 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_entry(_, _)).WillOnce(Return(E_OK)); + + fuse_ino_t parent = 2; + const char *name = ""; + fileOperationsCloud_->Lookup(nullptr, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest007 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest007 End"; +} + +/** + * @tc.name: AccessTest001 + * @tc.desc: Verify the Access function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, AccessTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessTest001 Start"; + try { + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + + fuse_ino_t ino = FUSE_ROOT_ID; + int mask = 0; + fileOperationsCloud_->Access(nullptr, ino, mask); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AccessTest001 ERROR"; + } + GTEST_LOG_(INFO) << "AccessTest001 End"; +} + +/** + * @tc.name: GetAttrTest001 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetAttrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest001 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t ino = FUSE_ROOT_ID; + struct fuse_file_info *fi = nullptr; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_attr(_, _, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->GetAttr(nullptr, ino, fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest001 End"; +} + +/** + * @tc.name: GetAttrTest002 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetAttrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest002 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t ino = -1; + struct fuse_file_info *fi = nullptr; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetAttr(nullptr, ino, fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest002 End"; +} + +/** + * @tc.name: OpenTest001 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, OpenTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Open(req, ino, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest001 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest001 End"; +} + +/** + * @tc.name: OpenTest002 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, OpenTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest002 Start"; + try { + CloudDiskFuseData data; + data.userId = 0; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_file_info fi; + fi.flags |= (O_ACCMODE | O_WRONLY); + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Open(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest002 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest002 End"; +} + +/** + * @tc.name: OpenTest003 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, OpenTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest003 Start"; + try { + CloudDiskFuseData data; + data.userId = 0; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_file_info fi; + fi.flags |= O_APPEND; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Open(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest003 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest003 End"; +} + +/** + * @tc.name: OpenTest004 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, OpenTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest004 Start"; + try { + CloudDiskFuseData data; + data.userId = 0; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_file_info fi; + fi.flags |= O_DIRECT; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Open(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest004 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest004 End"; +} + +/** + * @tc.name: OpenTest005 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, OpenTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest005 Start"; + try { + CloudDiskFuseData data; + data.userId = 0; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Open(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest005 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest005 End"; +} + +/** + * @tc.name: OpenTest006 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, OpenTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest006 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_file_info fi; + fi.fh = -1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Open(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest006 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest006 End"; +} + +/** + * @tc.name: OpenTest007 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, OpenTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest007 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Open(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest007 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest007 End"; +} + +/** + * @tc.name: MkNodTest001 + * @tc.desc: Verify the MkNod function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, MkNodTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkNodTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + const char *name = ""; + mode_t mode = 0; + dev_t rdev = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->MkNod(req, reinterpret_cast(&ino), name, mode, rdev); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkNodTest001 ERROR"; + } + GTEST_LOG_(INFO) << "MkNodTest001 End"; +} + +/** + * @tc.name: MkNodTest002 + * @tc.desc: Verify the MkNod function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, MkNodTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkNodTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + uint64_t parent = -1; + const char *name = ""; + mode_t mode = 0; + dev_t rdev = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_entry(_, _)).WillOnce(Return(E_OK)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->MkNod(req, parent, name, mode, rdev); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkNodTest002 ERROR"; + } + GTEST_LOG_(INFO) << "MkNodTest002 End"; +} + +/** + * @tc.name: CreateTest001 + * @tc.desc: Verify the Create function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, CreateTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = ""; + mode_t mode = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Create(req, parent, name, mode, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CreateTest001 ERROR"; + } + GTEST_LOG_(INFO) << "CreateTest001 End"; +} + +/** + * @tc.name: CreateTest002 + * @tc.desc: Verify the Create function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, CreateTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = 5; + const char *name = ""; + mode_t mode = 0; + struct fuse_file_info fi; + fi.fh = 4; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_create(_, _, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Create(req, parent, name, mode, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CreateTest002 ERROR"; + } + GTEST_LOG_(INFO) << "CreateTest002 End"; +} + +/** + * @tc.name: ReadDirTest001 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReadDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 4; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_buf(_, _, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->ReadDir(req, ino, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest001 End"; +} + +/** + * @tc.name: ReadDirTest002 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReadDirTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->ReadDir(req, ino, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest002 End"; +} + + +/** + * @tc.name: ReadDirTest003 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReadDirTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_buf(_, _, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->ReadDir(req, ino, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest003 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest003 End"; +} + +/** + * @tc.name: SetXattrTest001 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = HMDFS_PERMISSION_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest001 End"; +} + +/** + * @tc.name: SetXattrTest002 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + string name = CLOUD_FILE_LOCATION; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest002 End"; +} + +/** + * @tc.name: SetXattrTest003 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = CLOUD_FILE_LOCATION; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest003 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest003 End"; +} + +/** + * @tc.name: SetXattrTest004 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest004 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + string name = CLOUD_FILE_LOCATION; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest004 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest004 End"; +} + +/** + * @tc.name: SetXattrTest005 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest005 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + string name = CLOUD_FILE_LOCATION; + const char *value = "test"; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest005 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest005 End"; +} + +/** + * @tc.name: SetXattrTest006 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest006 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + string name = CLOUD_CLOUD_RECYCLE_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest006 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest006 End"; +} + +/** + * @tc.name: SetXattrTest007 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest007 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + string name = CLOUD_CLOUD_RECYCLE_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest007 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest007 End"; +} + +/** + * @tc.name: SetXattrTest008 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest008 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + string name = CLOUD_CLOUD_RECYCLE_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest008 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest008 End"; +} + +/** + * @tc.name: SetXattrTest009 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest009 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + string name = CLOUD_CLOUD_RECYCLE_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest009 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest009 End"; +} + +/** + * @tc.name: SetXattrTest010 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest010 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + string name = IS_FAVORITE_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest010 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest010 End"; +} + +/** + * @tc.name: SetXattrTest011 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest011 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = IS_FAVORITE_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest011 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest011 End"; +} + +/** + * @tc.name: SetXattrTest012 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest012, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest012 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = IS_FAVORITE_XATTR; + const char *value = "test"; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest012 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest012 End"; +} + +/** + * @tc.name: SetXattrTest013 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest013, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest013 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + string name = IS_FILE_STATUS_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest013 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest013 End"; +} + +/** + * @tc.name: SetXattrTest014 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest014, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest014 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = IS_FILE_STATUS_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest014 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest014 End"; +} + +/** + * @tc.name: SetXattrTest015 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest015, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest015 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = IS_FILE_STATUS_XATTR; + const char *value = "test"; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest015 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest015 End"; +} + +/** + * @tc.name: GetXattrTest001 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + size_t size = 0; + string name = HMDFS_PERMISSION_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest001 End"; +} + +/** + * @tc.name: GetXattrTest002 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + string name = HMDFS_PERMISSION_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_xattr(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest002 End"; +} + +/** + * @tc.name: GetXattrTest003 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + string name = CLOUD_CLOUD_ID_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_xattr(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest003 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest003 End"; +} + +/** + * @tc.name: GetXattrTest004 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest004 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + string name = IS_FAVORITE_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest004 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest004 End"; +} + +/** + * @tc.name: GetXattrTest005 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest005 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + size_t size = 0; + string name = IS_FAVORITE_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_xattr(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest005 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest005 End"; +} + +/** + * @tc.name: GetXattrTest006 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest006 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + string name = IS_FILE_STATUS_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest006 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest006 End"; +} + +/** + * @tc.name: GetXattrTest007 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest007 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + size_t size = 0; + string name = IS_FILE_STATUS_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_xattr(_, _)).WillOnce(Return(E_OK)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest007 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest007 End"; +} + +/** + * @tc.name: GetXattrTest008 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest008 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + string name = CLOUD_FILE_LOCATION; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest008 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest008 End"; +} + +/** + * @tc.name: GetXattrTest009 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest009 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + size_t size = 0; + string name = CLOUD_FILE_LOCATION; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest009 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest009 End"; +} + +/** + * @tc.name: GetXattrTest010 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest010 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + size_t size = 0; + string name = CLOUD_FILE_LOCATION; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest010 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest010 End"; +} + +/** + * @tc.name: GetXattrTest011 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest011 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + string name = CLOUD_CLOUD_RECYCLE_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest011 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest011 End"; +} + +/** + * @tc.name: GetXattrTest012 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest012, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest012 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + size_t size = 0; + string name = CLOUD_CLOUD_RECYCLE_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_xattr(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest012 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest012 End"; +} + +/** + * @tc.name: GetXattrTest013 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest013, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest013 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + size_t size = 1; + string name = CLOUD_CLOUD_RECYCLE_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest013 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest013 End"; +} + +/** + * @tc.name: GetXattrTest014 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, GetXattrTest014, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest014 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + size_t size = 1; + string name = HMDFS_PERMISSION_XATTR; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_buf(_, _, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest014 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest014 End"; +} + +/** + * @tc.name: MkDirTest001 + * @tc.desc: Verify the MkDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, MkDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkDirTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = -1; + const char *name = nullptr; + mode_t mode = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->MkDir(req, parent, name, mode); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkDirTest001 ERROR"; + } + GTEST_LOG_(INFO) << "MkDirTest001 End"; +} + +/** + * @tc.name: MkDirTest002 + * @tc.desc: Verify the MkDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, MkDirTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkDirTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = ".cloudthumbnails"; + mode_t mode = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->MkDir(req, parent, name, mode); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkDirTest002 ERROR"; + } + GTEST_LOG_(INFO) << "MkDirTest002 End"; +} + +/** + * @tc.name: MkDirTest003 + * @tc.desc: Verify the MkDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, MkDirTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkDirTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = 3; + const char *name = ""; + mode_t mode = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->MkDir(req, parent, name, mode); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkDirTest003 ERROR"; + } + GTEST_LOG_(INFO) << "MkDirTest003 End"; +} + +/** + * @tc.name: MkDirTest004 + * @tc.desc: Verify the MkDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, MkDirTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkDirTest004 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = 2; + const char *name = ""; + mode_t mode = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->MkDir(req, parent, name, mode); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkDirTest004 ERROR"; + } + GTEST_LOG_(INFO) << "MkDirTest004 End"; +} + +/** + * @tc.name: RmDirTest001 + * @tc.desc: Verify the RmDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, RmDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmDirTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = -1; + const char *name = nullptr; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->RmDir(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RmDirTest001 ERROR"; + } + GTEST_LOG_(INFO) << "RmDirTest001 End"; +} + +/** + * @tc.name: RmDirTest002 + * @tc.desc: Verify the RmDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, RmDirTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmDirTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = "mock"; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->RmDir(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RmDirTest002 ERROR"; + } + GTEST_LOG_(INFO) << "RmDirTest002 End"; +} + +/** + * @tc.name: RmDirTest003 + * @tc.desc: Verify the RmDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, RmDirTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmDirTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = "test"; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->RmDir(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RmDirTest003 ERROR"; + } + GTEST_LOG_(INFO) << "RmDirTest003 End"; +} + +/** + * @tc.name: UnlinkTest001 + * @tc.desc: Verify the Unlink function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, UnlinkTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkTest001 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t parent = -1; + fuse_req_t req = nullptr; + const char *name = ""; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Unlink(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnlinkTest001 ERROR"; + } + GTEST_LOG_(INFO) << "UnlinkTest001 End"; +} + +/** + * @tc.name: UnlinkTest002 + * @tc.desc: Verify the Unlink function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, UnlinkTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkTest002 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t parent = -1; + fuse_req_t req = nullptr; + const char *name = "mock"; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Unlink(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnlinkTest002 ERROR"; + } + GTEST_LOG_(INFO) << "UnlinkTest002 End"; +} + +/** + * @tc.name: UnlinkTest003 + * @tc.desc: Verify the Unlink function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, UnlinkTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkTest003 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t parent = 0; + fuse_req_t req = nullptr; + const char *name = "test"; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, lseek(_, _, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Unlink(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnlinkTest003 ERROR"; + } + GTEST_LOG_(INFO) << "UnlinkTest003 End"; +} + +/** + * @tc.name: RenameTest001 + * @tc.desc: Verify the Rename function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, RenameTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RenameTest001 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t parent = 0; + fuse_ino_t newParent = 0; + fuse_req_t req = nullptr; + const char *name = ""; + const char *newName = ""; + unsigned int flags = 1; + + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Rename(req, parent, name, newParent, newName, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RenameTest001 ERROR"; + } + GTEST_LOG_(INFO) << "RenameTest001 End"; +} + +/** + * @tc.name: RenameTest002 + * @tc.desc: Verify the Rename function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, RenameTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RenameTest002 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t parent = -1; + fuse_ino_t newParent = -1; + fuse_req_t req = nullptr; + const char *name = ""; + const char *newName = ""; + unsigned int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Rename(req, parent, name, newParent, newName, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RenameTest002 ERROR"; + } + GTEST_LOG_(INFO) << "RenameTest002 End"; +} + +/** + * @tc.name: RenameTest003 + * @tc.desc: Verify the Rename function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, RenameTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RenameTest003 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t parent = 2; + fuse_ino_t newParent = 2; + fuse_req_t req = nullptr; + const char *name = "mock"; + const char *newName = "mock"; + unsigned int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Rename(req, parent, name, newParent, newName, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RenameTest003 ERROR"; + } + GTEST_LOG_(INFO) << "RenameTest003 End"; +} + +/** + * @tc.name: RenameTest004 + * @tc.desc: Verify the Rename function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, RenameTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RenameTest004 Start"; + try { + CloudDiskFuseData data; + fuse_ino_t parent = 2; + fuse_ino_t newParent = 2; + fuse_req_t req = nullptr; + const char *name = "test"; + const char *newName = "test"; + unsigned int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Rename(req, parent, name, newParent, newName, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RenameTest004 ERROR"; + } + GTEST_LOG_(INFO) << "RenameTest004 End"; +} + +/** + * @tc.name: ReadTest001 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReadTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + size_t size = 5 * 1024 *1024; + off_t off = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Read(req, reinterpret_cast(&ino), size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ReadTest001 End"; +} + +/** + * @tc.name: ReadTest002 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReadTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + size_t size = 1024; + off_t off = 0; + struct fuse_file_info fi; + fi.fh = -1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Read(req, reinterpret_cast(&ino), size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ReadTest002 End"; +} + +/** + * @tc.name: ReadTest003 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReadTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + size_t size = 1024; + off_t off = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_data(_, _, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Read(req, reinterpret_cast(&ino), size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadTest003 ERROR"; + } + GTEST_LOG_(INFO) << "ReadTest003 End"; +} + +/** + * @tc.name: ReadTest004 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReadTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTest004 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + size_t size = 1024; + off_t off = 0; + struct fuse_file_info fi; + fi.fh = 1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_buf(_, _, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Read(req, reinterpret_cast(&ino), size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadTest004 ERROR"; + } + GTEST_LOG_(INFO) << "ReadTest004 End"; +} + +/** + * @tc.name: WriteBufTest001 + * @tc.desc: Verify the WriteBuf function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, WriteBufTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteBufTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_bufvec *bufv = nullptr; + off_t offset = 0; + struct fuse_file_info fi; + fi.fh = -1; + + EXPECT_CALL(*insMock, fuse_buf_size(_)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->WriteBuf(req, reinterpret_cast(&ino), bufv, offset, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WriteBufTest001 ERROR"; + } + GTEST_LOG_(INFO) << "WriteBufTest001 End"; +} + +/** + * @tc.name: WriteBufTest002 + * @tc.desc: Verify the WriteBuf function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, WriteBufTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteBufTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_bufvec *bufv = nullptr; + off_t offset = 0; + struct fuse_file_info fi; + fi.fh = 1; + + EXPECT_CALL(*insMock, fuse_buf_size(_)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->WriteBuf(req, reinterpret_cast(&ino), bufv, offset, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WriteBufTest002 ERROR"; + } + GTEST_LOG_(INFO) << "WriteBufTest002 End"; +} + +/** + * @tc.name: WriteBufTest003 + * @tc.desc: Verify the WriteBuf function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, WriteBufTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteBufTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_bufvec *bufv = nullptr; + off_t offset = 0; + struct fuse_file_info fi; + fi.fh = 2; + + EXPECT_CALL(*insMock, fuse_buf_size(_)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_buf_copy(_, _, _)).WillOnce(Return(-1)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->WriteBuf(req, reinterpret_cast(&ino), bufv, offset, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WriteBufTest003 ERROR"; + } + GTEST_LOG_(INFO) << "WriteBufTest003 End"; +} + +/** + * @tc.name: WriteBufTest004 + * @tc.desc: Verify the WriteBuf function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, WriteBufTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteBufTest004 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + CloudDiskInode ino; + struct fuse_bufvec *bufv = nullptr; + off_t offset = 0; + struct fuse_file_info fi; + fi.fh = 2; + + EXPECT_CALL(*insMock, fuse_buf_size(_)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_buf_copy(_, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*insMock, fuse_reply_write(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->WriteBuf(req, reinterpret_cast(&ino), bufv, offset, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WriteBufTest004 ERROR"; + } + GTEST_LOG_(INFO) << "WriteBufTest004 End"; +} + +/** + * @tc.name: ReleaseTest001 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReleaseTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Release(req, ino, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest001 End"; +} + +/** + * @tc.name: ReleaseTest002 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReleaseTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Release(req, ino, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest002 End"; +} + +/** + * @tc.name: ReleaseTest003 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReleaseTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + struct fuse_file_info fi; + fi.fh = -1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Release(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest003 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest003 End"; +} + +/** + * @tc.name: ReleaseTest004 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReleaseTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest004 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + struct fuse_file_info fi; + fi.fh = 2; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Release(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest004 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest003 End"; +} + +/** + * @tc.name: ReleaseTest005 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReleaseTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest005 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + struct fuse_file_info fi; + fi.fh = 1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Release(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest005 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest005 End"; +} + +/** + * @tc.name: ReleaseTest006 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReleaseTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest006 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + struct fuse_file_info fi; + fi.fh = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Release(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest006 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest006 End"; +} + +/** + * @tc.name: ReleaseTest007 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, ReleaseTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest007 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + struct fuse_file_info fi; + fi.fh = 3; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Release(req, reinterpret_cast(&ino), &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest007 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest007 End"; +} + +/** + * @tc.name: SetAttrTest001 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + struct stat attr; + int valid = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest001 End"; +} + +/** + * @tc.name: SetAttrTest002 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 1; + struct stat attr; + int valid = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_attr(_, _, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest002 End"; +} + +/** + * @tc.name: SetAttrTest003 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest003 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t ino = 4; + struct stat attr; + int valid = 13; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest003 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest003 End"; +} + +/** + * @tc.name: SetAttrTest004 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest004 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 3; + struct stat attr; + int valid = 13; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest004 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest004 End"; +} + +/** + * @tc.name: SetAttrTest005 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest005 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + struct stat attr; + int valid = 13; + struct fuse_file_info fi; + fi.fh = -1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest005 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest005 End"; +} + +/** + * @tc.name: SetAttrTest006 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest006 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + struct stat attr; + int valid = 13; + struct fuse_file_info fi; + fi.fh = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest006 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest006 End"; +} + +/** + * @tc.name: SetAttrTest007 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest007 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 2; + struct stat attr; + int valid = 13; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, nullptr); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest007 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest007 End"; +} + +/** + * @tc.name: SetAttrTest008 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest008 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + struct stat attr; + int valid = 1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, nullptr); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest008 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest008 End"; +} + +/** + * @tc.name: SetAttrTest009 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest009 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 6; + struct stat attr; + int valid = 13; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, nullptr); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest009 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest009 End"; +} + +/** + * @tc.name: SetAttrTest010 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetAttrTest010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest010 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 7; + struct stat attr; + int valid = 13; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetAttr(req, ino, &attr, valid, nullptr); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest010 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest010 End"; +} + +/** + * @tc.name: LseekTest001 + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LseekTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest001 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + off_t off = 0; + int whence = 0; + struct fuse_file_info fi; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Lseek(req, ino, off, whence, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest001 ERROR"; + } + GTEST_LOG_(INFO) << "LseekTest001 End"; +} + +/** + * @tc.name: LseekTest002 + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LseekTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest002 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + off_t off = 0; + int whence = 0; + struct fuse_file_info fi; + fi.fh = -1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Lseek(req, ino, off, whence, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest002 ERROR"; + } + GTEST_LOG_(INFO) << "LseekTest002 End"; +} + +/** + * @tc.name: LseekTest003 + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LseekTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest003 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + off_t off = 0; + int whence = 0; + struct fuse_file_info fi; + fi.fh = 1; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Lseek(req, ino, off, whence, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest003 ERROR"; + } + GTEST_LOG_(INFO) << "LseekTest003 End"; +} + +/** + * @tc.name: LseekTest004 + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LseekTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest004 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + off_t off = 0; + int whence = 0; + struct fuse_file_info fi; + fi.fh = 2; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, lseek(_, _, _)).WillOnce(Return(-1)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)).WillRepeatedly(Return(E_OK)); + fileOperationsCloud_->Lseek(req, ino, off, whence, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest004 ERROR"; + } + GTEST_LOG_(INFO) << "LseekTest004 End"; +} + +/** + * @tc.name: LseekTest005 + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, LseekTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest005 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + off_t off = 0; + int whence = 0; + struct fuse_file_info fi; + fi.fh = 2; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, lseek(_, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*insMock, fuse_reply_lseek(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->Lseek(req, ino, off, whence, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest005 ERROR"; + } + GTEST_LOG_(INFO) << "LseekTest005 End"; +} + +/** + * @tc.name: IoctlTest001 + * @tc.desc: Verify the Ioctl function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, IoctlTest1, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IoctlTest001 Start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + int cmd = 0x1234; + void *arg = nullptr; + struct fuse_file_info *fi = nullptr; + unsigned flags = 0; + const void *inBuf = nullptr; + size_t inBufsz = 0; + size_t outBufsz = 0; + + fileOperationsCloud_->Ioctl(req, ino, cmd, arg, fi, flags, inBuf, inBufsz, outBufsz); + + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IoctlTest001 ERROR"; + } + GTEST_LOG_(INFO) << "IoctlTest001 End"; +} + +/** + * @tc.name: IoctlTest002 + * @tc.desc: Verify the Ioctl function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, IoctlTest2, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IoctlTest002 Start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + int cmd = 0; + void *arg = nullptr; + struct fuse_file_info *fi = nullptr; + unsigned flags = 0; + const void *inBuf = nullptr; + size_t inBufsz = 0; + size_t outBufsz = 0; + + fileOperationsCloud_->Ioctl(req, ino, cmd, arg, fi, flags, inBuf, inBufsz, outBufsz); + + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IoctlTest002 ERROR"; + } + GTEST_LOG_(INFO) << "IoctlTest002 End"; +} + +/** + * @tc.name: SetXattrTest016 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest016, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest016 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + string name = CLOUD_HAS_THM; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest016 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest010 End"; +} + +/** + * @tc.name: SetXattrTest011 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest017, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest017 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = CLOUD_HAS_THM; + const char *value = ""; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest017 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest017 End"; +} + +/** + * @tc.name: SetXattrTest012 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(FileOperationsCloudTest, SetXattrTest018, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest018 Start"; + try { + CloudDiskFuseData data; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = CLOUD_HAS_THM; + const char *value = "test"; + size_t size = 0; + int flags = 0; + + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + fileOperationsCloud_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest018 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest018 End"; +} + +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/file_operations_helper_test.cpp b/cloud_file/test/unittests/cloud_disk/file_operations_helper_test.cpp new file mode 100644 index 0000000..8811478 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/file_operations_helper_test.cpp @@ -0,0 +1,875 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "fuse_operations.h" +#include "cloud_disk_inode.h" +#include "cloud_file_utils.h" +#include "file_operations_helper.h" +#include "file_operations_base.h" +#include "file_operations_cloud.h" +#include "parameters.h" +#include "utils_log.h" +#include "assistant.h" + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FuseOperationsHelperTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr fuseoperationshelper_ = nullptr; + static inline shared_ptr insMock = nullptr; +}; + +void FuseOperationsHelperTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + fuseoperationshelper_ = make_shared(); + insMock = make_shared(); + Assistant::ins = insMock; +} + +void FuseOperationsHelperTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + fuseoperationshelper_ = nullptr; + Assistant::ins = nullptr; + insMock = nullptr; +} + +void FuseOperationsHelperTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FuseOperationsHelperTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: AddDirEntryTest001 + * @tc.desc: Verify the AddDirEntry function + * @tc.type: FUNC + * @tc.require: issuesIB4SSZ + */ +HWTEST_F(FuseOperationsHelperTest, AddDirEntryPathTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AddDirEntryTest001 start"; + try { + fuse_req_t req = nullptr; + std::string buffer = ""; + size_t size = 0; + const char *name = "testAddDir"; + auto ino = std::make_shared(); + fuseoperationshelper_->AddDirEntry(req, buffer, size, name, ino); + EXPECT_GT(size, 0); + EXPECT_EQ(buffer.size(), size); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AddDirEntryTest001 failed"; + } + GTEST_LOG_(INFO) << "AddDirEntryTest001 end"; +} + +/** + * @tc.name: GetCloudDiskLocalPathTest001 + * @tc.desc: Verify the GetCloudDiskLocalPath function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetCloudDiskLocalPathTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest001 Start"; + try { + int32_t userId = 100; + string fileName = "data"; + + string ret = fuseoperationshelper_->GetCloudDiskLocalPath(userId, fileName); + EXPECT_EQ(ret, "/data/service/el2/100/hmdfs/cloud/data/"); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest001 End"; +} + +/** + * @tc.name: GetCloudDiskLocalPathTest002 + * @tc.desc: Verify the GetCloudDiskLocalPath function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetCloudDiskLocalPathTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest002 Start"; + try { + int32_t userId = 100; + string fileName = "/"; + + string ret = fuseoperationshelper_->GetCloudDiskLocalPath(userId, fileName); + EXPECT_EQ(ret, "/data/service/el2/100/hmdfs/cloud/"); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest002 End"; +} + +/** + * @tc.name: GetCloudDiskLocalPathTest003 + * @tc.desc: Verify the GetCloudDiskLocalPath function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetCloudDiskLocalPathTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest003 Start"; + try { + int32_t userId = 100; + string fileName = "test"; + + string ret = fuseoperationshelper_->GetCloudDiskLocalPath(userId, fileName); + EXPECT_EQ(ret, "/data/service/el2/100/hmdfs/cloud/data/test"); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest003 ERROR"; + } + GTEST_LOG_(INFO) << "GetCloudDiskLocalPathTest003 End"; +} + +/** + * @tc.name: GetInodeAttrTest001 + * @tc.desc: Verify the GetInodeAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetInodeAttrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInodeAttrTest001 Start"; + try { + std::shared_ptr inoPtr = make_shared(); + struct stat statBuf; + inoPtr->stat.st_mode |= S_IFREG; + + fuseoperationshelper_->GetInodeAttr(inoPtr, &statBuf); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInodeAttrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetInodeAttrTest001 End"; +} + +/** + * @tc.name: GetInodeAttrTest002 + * @tc.desc: Verify the GetInodeAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetInodeAttrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInodeAttrTest002 Start"; + try { + std::shared_ptr inoPtr = make_shared(); + struct stat statBuf; + inoPtr->stat.st_mode |= S_IFMT; + + fuseoperationshelper_->GetInodeAttr(inoPtr, &statBuf); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInodeAttrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetInodeAttrTest002 End"; +} + +/** + * @tc.name: GetNextLayerTest001 + * @tc.desc: Verify the GetNextLayer function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetNextLayerTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNextLayerTest001 Start"; + try { + std::shared_ptr inoPtr = make_shared(); + fuse_ino_t ino = FUSE_ROOT_ID; + + int ret = fuseoperationshelper_->GetNextLayer(inoPtr, ino); + EXPECT_EQ(ret, CLOUD_DISK_INODE_ZERO_LAYER); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetNextLayerTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetNextLayerTest001 End"; +} + +/** + * @tc.name: GetNextLayerTest002 + * @tc.desc: Verify the GetNextLayer function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetNextLayerTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNextLayerTest002 Start"; + try { + std::shared_ptr inoPtr = make_shared(); + inoPtr->layer = CLOUD_DISK_INODE_OTHER_LAYER; + fuse_ino_t ino = 0; + + int ret = fuseoperationshelper_->GetNextLayer(inoPtr, ino); + EXPECT_EQ(ret, CLOUD_DISK_INODE_OTHER_LAYER); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetNextLayerTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetNextLayerTest002 End"; +} + +/** + * @tc.name: GetNextLayerTest003 + * @tc.desc: Verify the GetNextLayer function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetNextLayerTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNextLayerTest003 Start"; + try { + std::shared_ptr inoPtr = make_shared(); + inoPtr->layer = CLOUD_DISK_INODE_FIRST_LAYER; + fuse_ino_t ino = 0; + + int ret = fuseoperationshelper_->GetNextLayer(inoPtr, ino); + EXPECT_EQ(ret, CLOUD_DISK_INODE_OTHER_LAYER); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetNextLayerTest003 ERROR"; + } + GTEST_LOG_(INFO) << "GetNextLayerTest003 End"; +} + +/** + * @tc.name: GetFixedLayerRootIdTest001 + * @tc.desc: Verify the GetFixedLayerRootId function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetFixedLayerRootIdTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest001 Start"; + try { + int32_t layer = CLOUD_DISK_INODE_ZERO_LAYER; + + int ret = fuseoperationshelper_->GetFixedLayerRootId(layer); + EXPECT_EQ(ret, CLOUD_DISK_INODE_ZERO_LAYER_LOCALID); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest001 End"; +} + +/** + * @tc.name: GetFixedLayerRootIdTest002 + * @tc.desc: Verify the GetFixedLayerRootId function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetFixedLayerRootIdTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest002 Start"; + try { + int32_t layer = CLOUD_DISK_INODE_FIRST_LAYER; + + int ret = fuseoperationshelper_->GetFixedLayerRootId(layer); + EXPECT_EQ(ret, CLOUD_DISK_INODE_FIRST_LAYER_LOCALID); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest002 End"; +} + +/** + * @tc.name: GetFixedLayerRootIdTest003 + * @tc.desc: Verify the GetFixedLayerRootId function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GetFixedLayerRootIdTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest003 Start"; + try { + int32_t layer = CLOUD_DISK_INODE_OTHER_LAYER; + + int ret = fuseoperationshelper_->GetFixedLayerRootId(layer); + EXPECT_EQ(ret, CLOUD_DISK_INODE_LAYER_LOCALID_UNKNOWN); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest003 ERROR"; + } + GTEST_LOG_(INFO) << "GetFixedLayerRootIdTest003 End"; +} + +/** + * @tc.name: FindCloudDiskInodeTest001 + * @tc.desc: Verify the FindCloudDiskInode function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, FindCloudDiskInodeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FindCloudDiskInodeTest001 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inode = std::make_shared(); + data->inodeCache.insert(std::make_pair(1, inode)); + int64_t key = 1; + + fuseoperationshelper_->FindCloudDiskInode(data, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "FindCloudDiskInodeTest001 ERROR"; + } + GTEST_LOG_(INFO) << "FindCloudDiskInodeTest001 End"; +} + +/** + * @tc.name: FindCloudDiskInodeTest002 + * @tc.desc: Verify the FindCloudDiskInode function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, FindCloudDiskInodeTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FindCloudDiskInodeTest002 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + int64_t key = 0; + + fuseoperationshelper_->FindCloudDiskInode(data, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "FindCloudDiskInodeTest002 ERROR"; + } + GTEST_LOG_(INFO) << "FindCloudDiskInodeTest002 End"; +} + +/** + * @tc.name: FindCloudDiskFileTest001 + * @tc.desc: Verify the FindCloudDiskFile function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, FindCloudDiskFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FindCloudDiskFileTest001 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr file = std::make_shared(); + data->fileCache.insert(std::make_pair(1, file)); + int64_t key = 1; + + fuseoperationshelper_->FindCloudDiskFile(data, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "FindCloudDiskFileTest001 ERROR"; + } + GTEST_LOG_(INFO) << "FindCloudDiskFileTest001 End"; +} + +/** + * @tc.name: FindCloudDiskFileTest002 + * @tc.desc: Verify the FindCloudDiskFile function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, FindCloudDiskFileTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FindCloudDiskFileTest002 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + int64_t key = 0; + + fuseoperationshelper_->FindCloudDiskFile(data, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "FindCloudDiskFileTest002 ERROR"; + } + GTEST_LOG_(INFO) << "FindCloudDiskFileTest002 End"; +} + +/** + * @tc.name: FindLocalIdTest001 + * @tc.desc: Verify the FindLocalId function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, FindLocalIdTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FindLocalIdTest001 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + data->localIdCache.insert(std::make_pair("test", 1)); + string key = "test"; + + int ret = fuseoperationshelper_->FindLocalId(data, key); + delete data; + EXPECT_EQ(ret, 1); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "FindLocalIdTest001 ERROR"; + } + GTEST_LOG_(INFO) << "FindLocalIdTest001 End"; +} + +/** + * @tc.name: FindLocalIdTest002 + * @tc.desc: Verify the FindLocalId function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, FindLocalIdTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FindLocalIdTest002 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + string key = ""; + + int ret = fuseoperationshelper_->FindLocalId(data, key); + delete data; + EXPECT_EQ(ret, -1); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "FindLocalIdTest002 ERROR"; + } + GTEST_LOG_(INFO) << "FindLocalIdTest002 End"; +} + +/** + * @tc.name: FuseReplyLimitedTest001 + * @tc.desc: Verify the FuseReplyLimited function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, FuseReplyLimitedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FuseReplyLimitedTest001 Start"; + try { + fuse_req_t req = nullptr; + const char *buf; + size_t bufSize = 1024; + off_t off = 0; + size_t maxSize = 1024 * 4 * 4; + EXPECT_CALL(*insMock, fuse_reply_buf(_, _, _)).WillOnce(Return(0)); + + fuseoperationshelper_->FuseReplyLimited(req, buf, bufSize, off, maxSize); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "FuseReplyLimitedTest001 ERROR"; + } + GTEST_LOG_(INFO) << "FuseReplyLimitedTest001 End"; +} + +/** + * @tc.name: FuseReplyLimitedTest002 + * @tc.desc: Verify the FuseReplyLimited function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, FuseReplyLimitedTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FuseReplyLimitedTest002 Start"; + try { + fuse_req_t req = nullptr; + const char *buf; + size_t bufSize = 1024; + off_t off = 1024 * 4; + size_t maxSize = 1024 * 4 * 4; + EXPECT_CALL(*insMock, fuse_reply_buf(_, _, _)).WillOnce(Return(0)); + + fuseoperationshelper_->FuseReplyLimited(req, buf, bufSize, off, maxSize); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "FuseReplyLimitedTest002 ERROR"; + } + GTEST_LOG_(INFO) << "FuseReplyLimitedTest002 End"; +} + +/** + * @tc.name: GenerateCloudDiskInodeTest001 + * @tc.desc: Verify the FuseReplyLimited function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GenerateCloudDiskInodeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest001 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + fuse_ino_t parent = 0; + string fileName = ""; + string path = ""; + + fuseoperationshelper_->GenerateCloudDiskInode(data, parent, fileName, path); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest001 End"; +} + +/** + * @tc.name: GenerateCloudDiskInodeTest002 + * @tc.desc: Verify the FuseReplyLimited function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GenerateCloudDiskInodeTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest002 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + fuse_ino_t parent = 0; + string fileName = ""; + string path = "/data"; + + fuseoperationshelper_->GenerateCloudDiskInode(data, parent, fileName, path); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest002 End"; +} + +/** + * @tc.name: GenerateCloudDiskInodeTest003 + * @tc.desc: Verify the FuseReplyLimited function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GenerateCloudDiskInodeTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest003 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inode = std::make_shared(); + data->inodeCache.insert(std::make_pair(1, inode)); + fuse_ino_t parent = 1; + string fileName = ""; + string path = "/data"; + + fuseoperationshelper_->GenerateCloudDiskInode(data, parent, fileName, path); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest003 ERROR"; + } + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest003 End"; +} + +/** + * @tc.name: GenerateCloudDiskInodeTest004 + * @tc.desc: Verify the FuseReplyLimited function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, GenerateCloudDiskInodeTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest004 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inode = std::make_shared(); + data->inodeCache.insert(std::make_pair(0, inode)); + fuse_ino_t parent = 0; + string fileName = ""; + string path = "/data"; + + fuseoperationshelper_->GenerateCloudDiskInode(data, parent, fileName, path); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest004 ERROR"; + } + GTEST_LOG_(INFO) << "GenerateCloudDiskInodeTest004 End"; +} + +/** + * @tc.name: PutCloudDiskInodeTest001 + * @tc.desc: Verify the PutCloudDiskInode function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutCloudDiskInodeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest001 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inoPtr = nullptr; + uint64_t num = 1; + int64_t key = 0; + + fuseoperationshelper_->PutCloudDiskInode(data, inoPtr, num, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest001 ERROR"; + } + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest001 End"; +} + +/** + * @tc.name: PutCloudDiskInodeTest002 + * @tc.desc: Verify the PutCloudDiskInode function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutCloudDiskInodeTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest002 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inoPtr = make_shared(); + inoPtr->refCount.store(1); + uint64_t num = 1; + int64_t key = 0; + + fuseoperationshelper_->PutCloudDiskInode(data, inoPtr, num, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest002 ERROR"; + } + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest002 End"; +} + +/** + * @tc.name: PutCloudDiskInodeTest003 + * @tc.desc: Verify the PutCloudDiskInode function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutCloudDiskInodeTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest003 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inoPtr = make_shared(); + inoPtr->refCount.store(2); + uint64_t num = 1; + int64_t key = 0; + + fuseoperationshelper_->PutCloudDiskInode(data, inoPtr, num, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest003 ERROR"; + } + GTEST_LOG_(INFO) << "PutCloudDiskInodeTest003 End"; +} + +/** + * @tc.name: PutCloudDiskFileTest001 + * @tc.desc: Verify the PutCloudDiskFile function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutCloudDiskFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCloudDiskFileTest001 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr file = nullptr; + int64_t key = 0; + + fuseoperationshelper_->PutCloudDiskFile(data, file, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutCloudDiskFileTest001 ERROR"; + } + GTEST_LOG_(INFO) << "PutCloudDiskFileTest001 End"; +} + +/** + * @tc.name: PutCloudDiskFileTest002 + * @tc.desc: Verify the PutCloudDiskFile function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutCloudDiskFileTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCloudDiskFileTest002 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr file = make_shared(); + file->refCount.store(0); + int64_t key = 0; + + fuseoperationshelper_->PutCloudDiskFile(data, file, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutCloudDiskFileTest002 ERROR"; + } + GTEST_LOG_(INFO) << "PutCloudDiskFileTest002 End"; +} + +/** + * @tc.name: PutCloudDiskFileTest003 + * @tc.desc: Verify the PutCloudDiskFile function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutCloudDiskFileTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCloudDiskFileTest003 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr file = make_shared(); + file->refCount.store(1); + int64_t key = 0; + + fuseoperationshelper_->PutCloudDiskFile(data, file, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutCloudDiskFileTest003 ERROR"; + } + GTEST_LOG_(INFO) << "PutCloudDiskFileTest003 End"; +} + +/** + * @tc.name: PutLocalIdTest001 + * @tc.desc: Verify the PutLocalId function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutLocalIdTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutLocalIdTest001 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inoPtr = nullptr; + uint64_t num = 1; + string key = ""; + + fuseoperationshelper_->PutLocalId(data, inoPtr, num, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutLocalIdTest001 ERROR"; + } + GTEST_LOG_(INFO) << "PutLocalIdTest001 End"; +} + +/** + * @tc.name: PutLocalIdTest002 + * @tc.desc: Verify the PutLocalId function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutLocalIdTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutLocalIdTest002 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inoPtr = make_shared(); + inoPtr->refCount.store(1); + uint64_t num = 1; + string key = ""; + + fuseoperationshelper_->PutLocalId(data, inoPtr, num, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutLocalIdTest002 ERROR"; + } + GTEST_LOG_(INFO) << "PutLocalIdTest002 End"; +} + +/** + * @tc.name: PutLocalIdTest003 + * @tc.desc: Verify the PutLocalId function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsHelperTest, PutLocalIdTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutLocalIdTest003 Start"; + try { + struct CloudDiskFuseData *data = new CloudDiskFuseData; + std::shared_ptr inoPtr = make_shared(); + inoPtr->refCount.store(2); + uint64_t num = 1; + string key = ""; + + fuseoperationshelper_->PutLocalId(data, inoPtr, num, key); + delete data; + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PutLocalIdTest003 ERROR"; + } + GTEST_LOG_(INFO) << "PutLocalIdTest003 End"; +} +} // namespace OHOS::FileManagement::CloudDisk::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/file_operations_local_test.cpp b/cloud_file/test/unittests/cloud_disk/file_operations_local_test.cpp new file mode 100644 index 0000000..f1a3593 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/file_operations_local_test.cpp @@ -0,0 +1,427 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "fuse_operations.h" +#include "cloud_disk_inode.h" +#include "cloud_file_utils.h" +#include "file_operations_helper.h" +#include "file_operations_local.h" +#include "file_operations_base.h" +#include "parameters.h" +#include "utils_log.h" +#include "assistant.h" + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FileOperationsLocalTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline FileOperationsLocal* fileoperationslocal_ = new FileOperationsLocal(); + static inline shared_ptr insMock = nullptr; +}; + +void FileOperationsLocalTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + insMock = make_shared(); + Assistant::ins = insMock; +} + +void FileOperationsLocalTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + fileoperationslocal_ = nullptr; + Assistant::ins = nullptr; + insMock = nullptr; +} + +void FileOperationsLocalTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FileOperationsLocalTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: LookUpTest001 + * @tc.desc: Verify the LookUp function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, LookUpTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookUpTest001 Start"; + try { + CloudDiskFuseData data; + data.userId = 0; + fuse_req_t req = nullptr; + fuse_ino_t parent = 1; + const char *name = "mock"; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(0)); + + fileoperationslocal_->Lookup(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookUpTest001 ERROR"; + } + GTEST_LOG_(INFO) << "LookUpTest001 End"; +} + +/** + * @tc.name: LookUpTest002 + * @tc.desc: Verify the LookUp function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, LookUpTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookUpTest001 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = "mock"; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_entry(_, _)).WillOnce(Return(0)); + + fileoperationslocal_->Lookup(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookUpTest001 ERROR"; + } + GTEST_LOG_(INFO) << "LookUpTest001 End"; +} + +/** + * @tc.name: LookUpTest003 + * @tc.desc: Verify the LookUp function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, LookUpTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookUpTest003 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t parent = 1; + const char *name = "mock"; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_entry(_, _)).WillOnce(Return(0)); + + fileoperationslocal_->Lookup(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookUpTest003 ERROR"; + } + GTEST_LOG_(INFO) << "LookUpTest003 End"; +} + +/** + * @tc.name: LookUpTest004 + * @tc.desc: Verify the LookUp function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, LookUpTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookUpTest004 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t parent = 100; + const char *name = "mock"; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_entry(_, _)).WillOnce(Return(0)); + + fileoperationslocal_->Lookup(req, parent, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookUpTest004 ERROR"; + } + GTEST_LOG_(INFO) << "LookUpTest004 End"; +} + +/** + * @tc.name: GetAttrTest001 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, GetAttrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest001 Start"; + try { + CloudDiskFuseData data; + data.userId = 0; + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(0)); + + fileoperationslocal_->GetAttr(req, ino, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest001 End"; +} + +/** + * @tc.name: GetAttrTest002 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, GetAttrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest002 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_attr(_, _, _)).WillOnce(Return(0)); + + fileoperationslocal_->GetAttr(req, ino, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest002 End"; +} + +/** + * @tc.name: GetAttrTest003 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, GetAttrTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest003 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(0)); + + fileoperationslocal_->GetAttr(req, ino, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest003 ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest003 End"; +} + +/** + * @tc.name: GetAttrTest004 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, GetAttrTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest004 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0 ; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_attr(_, _, _)).WillOnce(Return(0)); + + fileoperationslocal_->GetAttr(req, ino, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest004 ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest004 End"; +} + +/** + * @tc.name: ReadDirTest001 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, ReadDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest001 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_buf(_, _, _)).WillOnce(Return(0)); + + fileoperationslocal_->ReadDir(req, ino, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest001 End"; +} + +/** + * @tc.name: ReadDirTest002 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, ReadDirTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest002 Start"; + try { + CloudDiskFuseData data; + data.userId = 0; + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + + fileoperationslocal_->ReadDir(req, ino, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest002 End"; +} + +/** + * @tc.name: ReadDirTest003 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, ReadDirTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest003 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t ino = -1; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(0)); + + fileoperationslocal_->ReadDir(req, ino, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest003 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest003 End"; +} + +/** + * @tc.name: ReadDirTest004 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, ReadDirTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest004 Start"; + try { + CloudDiskFuseData data; + data.userId = 100; + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + + fileoperationslocal_->ReadDir(req, ino, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest004 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest004 End"; +} + +/** + * @tc.name: ReadDirTest005 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FileOperationsLocalTest, ReadDirTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest005 Start"; + try { + CloudDiskFuseData data; + data.userId = 1; + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + EXPECT_CALL(*insMock, fuse_reply_buf(_, _, _)).WillOnce(Return(0)); + + fileoperationslocal_->ReadDir(req, ino, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest005 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest005 End"; +} +} // namespace OHOS::FileManagement::CloudDisk::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/fuse_operations_test.cpp b/cloud_file/test/unittests/cloud_disk/fuse_operations_test.cpp new file mode 100644 index 0000000..f44db94 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/fuse_operations_test.cpp @@ -0,0 +1,1753 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "fuse_operations.h" +#include "cloud_disk_inode.h" +#include "cloud_file_utils.h" +#include "file_operations_cloud.h" +#include "file_operations_helper.h" +#include "file_operations_base.h" +#include "parameters.h" +#include "utils_log.h" +#include "assistant.h" + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FuseOperationsTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr fuseoperations_ = nullptr; + static inline shared_ptr insMock = nullptr; +}; + +void FuseOperationsTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + fuseoperations_ = make_shared(); + insMock = make_shared(); + Assistant::ins = insMock; +} + +void FuseOperationsTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + fuseoperations_ = nullptr; + Assistant::ins = nullptr; + insMock = nullptr; +} + +void FuseOperationsTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FuseOperationsTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: LookupTest001 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, LookupTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest001 Start"; + try { + fuse_req_t req = nullptr; + const char *name = ""; + + fuseoperations_->Lookup(req, FUSE_ROOT_ID, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest001 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest001 End"; +} + +/** + * @tc.name: LookupTest002 + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, LookupTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + const char *name = ""; + + fuseoperations_->Lookup(req, 0, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest002 ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest002 End"; +} + +/** + * @tc.name: LookupTest + * @tc.desc: Verify the Lookup function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, LookupTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LookupTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + const char *name = ""; + fuse_ino_t parent = 0; + + fuseoperations_->Lookup(req, parent, name); + EXPECT_NE(parent, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LookupTest ERROR"; + } + GTEST_LOG_(INFO) << "LookupTest End"; +} + +/** + * @tc.name:AccessTest001 + * @tc.desc: Verify the Access function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, AccessTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessTest001 Start"; + try { + fuse_req_t req = nullptr; + int mask = 0; + + fuseoperations_->Access(req, FUSE_ROOT_ID, mask); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AccessTest001 ERROR"; + } + GTEST_LOG_(INFO) << "AccessTest001 End"; +} + +/** + * @tc.name:AccessTest002 + * @tc.desc: Verify the Access function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, AccessTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + int mask = 0; + + fuseoperations_->Access(req, 0, mask); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AccessTest002 ERROR"; + } + GTEST_LOG_(INFO) << "AccessTest002 End"; +} + +/** + * @tc.name:AccessTest + * @tc.desc: Verify the Access function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, AccessTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AccessTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + int mask = 0; + + fuseoperations_->Access(req, ino, mask); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AccessTest ERROR"; + } + GTEST_LOG_(INFO) << "AccessTest End"; +} + +/** + * @tc.name:GetAttrTest001 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, GetAttrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest001 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_file_info *fi = nullptr; + + fuseoperations_->GetAttr(req, FUSE_ROOT_ID, fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest001 End"; +} + +/** + * @tc.name:GetAttrTest002 + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, GetAttrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_file_info *fi = nullptr; + + fuseoperations_->GetAttr(req, 0, fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest002 End"; +} + +/** + * @tc.name:GetAttrTest + * @tc.desc: Verify the GetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, GetAttrTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAttrTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + struct fuse_file_info *fi = nullptr; + + fuseoperations_->GetAttr(req, ino, fi); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetAttrTest ERROR"; + } + GTEST_LOG_(INFO) << "GetAttrTest End"; +} + +/** + * @tc.name:OpenTest001 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, OpenTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest001 Start"; + try { + fuse_req_t req = nullptr; + struct fuse_file_info *fi = nullptr; + + fuseoperations_->Open(req, FUSE_ROOT_ID, fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest001 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest001 End"; +} + +/** + * @tc.name:OpenTest002 + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, OpenTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_file_info *fi = nullptr; + + fuseoperations_->Open(req, 0, fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest002 ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest002 End"; +} + +/** + * @tc.name:OpenTest + * @tc.desc: Verify the Open function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, OpenTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + struct fuse_file_info fi; + fi.fh = 1; + + fuseoperations_->Open(req, ino, &fi); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenTest ERROR"; + } + GTEST_LOG_(INFO) << "OpenTest End"; +} + +/** + * @tc.name:ForgetTest001 + * @tc.desc: Verify the Forget function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ForgetTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetTest001 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + uint64_t nLookup = 0; + + fuseoperations_->Forget(req, FUSE_ROOT_ID, nLookup); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetTest001 End"; +} + +/** + * @tc.name:ForgetTest002 + * @tc.desc: Verify the Forget function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ForgetTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + uint64_t nLookup = 0; + + fuseoperations_->Forget(req, 0, nLookup); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetTest002 End"; +} + +/** + * @tc.name:ForgetTest + * @tc.desc: Verify the Forget function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ForgetTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + uint64_t nLookup = 0; + + fuseoperations_->Forget(req, ino, nLookup); + EXPECT_NE(ino, FUSE_ROOT_ID); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetTest ERROR"; + } + GTEST_LOG_(INFO) << "ForgetTest End"; +} + +/** + * @tc.name:ForgetMultiTest001 + * @tc.desc: Verify the ForgetMulti function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ForgetMultiTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetMultiTest001 Start"; + try { + fuse_req_t req = nullptr; + struct fuse_forget_data forgets = { + FUSE_ROOT_ID, + 1, + }; + + fuseoperations_->ForgetMulti(req, 1, &forgets); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetMultiTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetMultiTest001 End"; +} + +/** + * @tc.name:ForgetMultiTest002 + * @tc.desc: Verify the ForgetMulti function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ForgetMultiTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetMultiTest002 Start"; + try { + fuse_req_t req = nullptr; + struct fuse_forget_data forgets = { + 0, + 1, + }; + + fuseoperations_->ForgetMulti(req, 0, &forgets); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetMultiTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetMultiTest002 End"; +} + +/** + * @tc.name:ForgetMultiTest01 + * @tc.desc: Verify the ForgetMulti function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ForgetMultiTest01, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetMultiTest01 Start"; + try { + CloudDiskFuseData data1; + CloudDiskFuseData data2; + (data1.inodeCache)[0] = make_shared(); + (data1.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data1))) + .WillOnce(Return(reinterpret_cast(&data2))); + fuse_req_t req = nullptr; + struct fuse_forget_data forgets; + forgets.ino = 0; + size_t count = 1; + + fuseoperations_->ForgetMulti(req, count, &forgets); + EXPECT_NE(count, 0); + EXPECT_NE((data1.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetMultiTest01 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetMultiTest01 End"; +} + +/** + * @tc.name:ForgetMultiTest02 + * @tc.desc: Verify the ForgetMulti function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ForgetMultiTest02, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForgetMultiTest02 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_forget_data forgets; + forgets.ino = 0; + size_t count = 1; + + fuseoperations_->ForgetMulti(req, count, &forgets); + EXPECT_NE(count, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ForgetMultiTest02 ERROR"; + } + GTEST_LOG_(INFO) << "ForgetMultiTest02 End"; +} + +/** + * @tc.name:MkNodTest001 + * @tc.desc: Verify the MkNod function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, MkNodTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkNodTest001 Start"; + try { + fuse_req_t req = nullptr; + const char *name = ""; + mode_t mode = 0; + dev_t rdev = 0; + + fuseoperations_->MkNod(req, FUSE_ROOT_ID, name, mode, rdev); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkNodTest001 ERROR"; + } + GTEST_LOG_(INFO) << "MkNodTest001 End"; +} + +/** + * @tc.name:MkNodTest002 + * @tc.desc: Verify the MkNod function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, MkNodTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkNodTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + const char *name = ""; + mode_t mode = 0; + dev_t rdev = 0; + + fuseoperations_->MkNod(req, 0, name, mode, rdev); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkNodTest002 ERROR"; + } + GTEST_LOG_(INFO) << "MkNodTest002 End"; +} + +/** + * @tc.name:MkNodTest + * @tc.desc: Verify the MkNod function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, MkNodTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkNodTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = ""; + mode_t mode = 0; + dev_t rdev = 0; + + fuseoperations_->MkNod(req, parent, name, mode, rdev); + EXPECT_NE(parent, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkNodTest ERROR"; + } + GTEST_LOG_(INFO) << "MkNodTest End"; +} + +/** + * @tc.name:CreateTest001 + * @tc.desc: Verify the Create function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, CreateTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateTest001 Start"; + try { + fuse_req_t req = nullptr; + const char *name = ""; + mode_t mode = 0; + struct fuse_file_info fi; + + fuseoperations_->Create(req, FUSE_ROOT_ID, name, mode, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CreateTest001 ERROR"; + } + GTEST_LOG_(INFO) << "CreateTest001 End"; +} + +/** + * @tc.name:CreateTest002 + * @tc.desc: Verify the Create function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, CreateTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + const char *name = ""; + mode_t mode = 0; + struct fuse_file_info fi; + + fuseoperations_->Create(req, 0, name, mode, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CreateTest002 ERROR"; + } + GTEST_LOG_(INFO) << "CreateTest002 End"; +} + +/** + * @tc.name:CreateTest + * @tc.desc: Verify the Create function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, CreateTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateTesT Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = ""; + mode_t mode = 0; + struct fuse_file_info fi; + + fuseoperations_->Create(req, parent, name, mode, &fi); + EXPECT_NE(parent, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CreateTest ERROR"; + } + GTEST_LOG_(INFO) << "CreateTest End"; +} + +/** + * @tc.name:ReadDirTest001 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReadDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest001 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + fuseoperations_->ReadDir(req, FUSE_ROOT_ID, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest001 End"; +} + +/** + * @tc.name:ReadDirTest002 + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReadDirTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + fuseoperations_->ReadDir(req, 0, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest002 End"; +} + +/** + * @tc.name:ReadDirTest + * @tc.desc: Verify the ReadDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReadDirTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadDirTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + fuseoperations_->ReadDir(req, ino, size, off, &fi); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadDirTest ERROR"; + } + GTEST_LOG_(INFO) << "ReadDirTest End"; +} + +/** + * @tc.name:SetXattrTest001 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, SetXattrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest001 Start"; + try { + fuse_req_t req = nullptr; + string name = HMDFS_PERMISSION_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + fuseoperations_->SetXattr(req, FUSE_ROOT_ID, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest001 End"; +} + +/** + * @tc.name:SetXattrTest002 + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, SetXattrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + string name = HMDFS_PERMISSION_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + fuseoperations_->SetXattr(req, 0, name.c_str(), value, size, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest002 End"; +} + +/** + * @tc.name:SetXattrTest + * @tc.desc: Verify the SetXattr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, SetXattrTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetXattrTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + string name = HMDFS_PERMISSION_XATTR; + const char *value = ""; + size_t size = 0; + int flags = 0; + + fuseoperations_->SetXattr(req, ino, name.c_str(), value, size, flags); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetXattrTest ERROR"; + } + GTEST_LOG_(INFO) << "SetXattrTest End"; +} + +/** + * @tc.name:GetXattrTest001 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, GetXattrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest001 Start"; + try { + fuse_req_t req = nullptr; + size_t size = 0; + string name = HMDFS_PERMISSION_XATTR; + + fuseoperations_->GetXattr(req, FUSE_ROOT_ID, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest001 End"; +} + +/** + * @tc.name:GetXattrTest002 + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, GetXattrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + size_t size = 0; + string name = HMDFS_PERMISSION_XATTR; + + fuseoperations_->GetXattr(req, 0, name.c_str(), size); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest002 End"; +} + +/** + * @tc.name:GetXattrTest + * @tc.desc: Verify the GetXattr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, GetXattrTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetXattrTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + string name = HMDFS_PERMISSION_XATTR; + + fuseoperations_->GetXattr(req, ino, name.c_str(), size); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetXattrTest ERROR"; + } + GTEST_LOG_(INFO) << "GetXattrTest End"; +} + +/** + * @tc.name:MkDirTest001 + * @tc.desc: Verify the MkDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, MkDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkDirTest001 Start"; + try { + fuse_req_t req = nullptr; + const char *name = nullptr; + mode_t mode = 0; + + + fuseoperations_->MkDir(req, FUSE_ROOT_ID, name, mode); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkDirTest001 ERROR"; + } + GTEST_LOG_(INFO) << "MkDirTest001 End"; +} + +/** + * @tc.name:MkDirTest002 + * @tc.desc: Verify the MkDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, MkDirTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkDirTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + const char *name = nullptr; + mode_t mode = 0; + + + fuseoperations_->MkDir(req, 0, name, mode); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkDirTest002 ERROR"; + } + GTEST_LOG_(INFO) << "MkDirTest002 End"; +} + +/** + * @tc.name:MkDirTest + * @tc.desc: Verify the MkDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, MkDirTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MkDirTest Start"; + try { + CloudDiskFuseData data1; + CloudDiskFuseData data2; + (data1.inodeCache)[0] = make_shared(); + (data1.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data1))) + .WillOnce(Return(reinterpret_cast(&data2))); + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = nullptr; + mode_t mode = 0; + + + fuseoperations_->MkDir(req, parent, name, mode); + EXPECT_NE(parent, FUSE_ROOT_ID); + EXPECT_NE((data1.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "MkDirTest ERROR"; + } + GTEST_LOG_(INFO) << "MkDirTest End"; +} + +/** + * @tc.name:RmDirTest001 + * @tc.desc: Verify the RmDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, RmDirTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmDirTest001 Start"; + try { + fuse_req_t req = nullptr; + const char *name = nullptr; + + fuseoperations_->RmDir(req, FUSE_ROOT_ID, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RmDirTest001 ERROR"; + } + GTEST_LOG_(INFO) << "RmDirTest001 End"; +} + +/** + * @tc.name:RmDirTest002 + * @tc.desc: Verify the RmDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, RmDirTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmDirTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + const char *name = nullptr; + + fuseoperations_->RmDir(req, 0, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RmDirTest002 ERROR"; + } + GTEST_LOG_(INFO) << "RmDirTest002 End"; +} + +/** + * @tc.name:RmDirTest + * @tc.desc: Verify the RmDir function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, RmDirTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RmDirTest Start"; + try { + CloudDiskFuseData data1; + CloudDiskFuseData data2; + (data1.inodeCache)[0] = make_shared(); + (data1.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data1))) + .WillOnce(Return(reinterpret_cast(&data2))); + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = nullptr; + + fuseoperations_->RmDir(req, parent, name); + EXPECT_NE(parent, FUSE_ROOT_ID); + EXPECT_NE((data1.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RmDirTest ERROR"; + } + GTEST_LOG_(INFO) << "RmDirTest End"; +} + +/** + * @tc.name:UnlinkTest001 + * @tc.desc: Verify the Unlink function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, UnlinkTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkTest001 Start"; + try { + fuse_req_t req = nullptr; + const char *name = nullptr; + + fuseoperations_->Unlink(req, FUSE_ROOT_ID, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnlinkTest001 ERROR"; + } + GTEST_LOG_(INFO) << "UnlinkTest001 End"; +} + +/** + * @tc.name:UnlinkTest002 + * @tc.desc: Verify the Unlink function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, UnlinkTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + const char *name = nullptr; + + fuseoperations_->Unlink(req, 0, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnlinkTest002 ERROR"; + } + GTEST_LOG_(INFO) << "UnlinkTest002 End"; +} + +/** + * @tc.name:UnlinkTest + * @tc.desc: Verify the Unlink function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, UnlinkTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnlinkTest Start"; + try { + CloudDiskFuseData data1; + CloudDiskFuseData data2; + (data1.inodeCache)[0] = make_shared(); + (data1.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data1))) + .WillOnce(Return(reinterpret_cast(&data2))) + .WillOnce(Return(reinterpret_cast(&data2))); + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = nullptr; + + fuseoperations_->Unlink(req, parent, name); + EXPECT_NE(parent, FUSE_ROOT_ID); + EXPECT_NE((data1.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnlinkTest ERROR"; + } + GTEST_LOG_(INFO) << "UnlinkTest End"; +} + +/** + * @tc.name:RenameTest001 + * @tc.desc: Verify the Rename function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, RenameTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RenameTest001 Start"; + try { + fuse_req_t req = nullptr; + const char *name = ""; + const char *newName = ""; + unsigned int flags = 1; + + fuseoperations_->Rename(req, FUSE_ROOT_ID, name, FUSE_ROOT_ID, newName, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RenameTest001 ERROR"; + } + GTEST_LOG_(INFO) << "RenameTest001 End"; +} + +/** + * @tc.name:RenameTest002 + * @tc.desc: Verify the Rename function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, RenameTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RenameTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + const char *name = ""; + const char *newName = ""; + unsigned int flags = 1; + + fuseoperations_->Rename(req, 0, name, FUSE_ROOT_ID, newName, flags); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RenameTest002 ERROR"; + } + GTEST_LOG_(INFO) << "RenameTest002 End"; +} + +/** + * @tc.name:RenameTest + * @tc.desc: Verify the Rename function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, RenameTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RenameTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t parent = 0; + const char *name = ""; + const char *newName = ""; + unsigned int flags = 1; + + fuseoperations_->Rename(req, parent, name, FUSE_ROOT_ID, newName, flags); + EXPECT_NE(parent, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RenameTest ERROR"; + } + GTEST_LOG_(INFO) << "RenameTest End"; +} + +/** + * @tc.name:ReadTest001 + * @tc.desc: Verify the Read function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReadTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTest001 Start"; + try { + fuse_req_t req = nullptr; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + fuseoperations_->Read(req, FUSE_ROOT_ID, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ReadTest001 End"; +} + +/** + * @tc.name:ReadTest002 + * @tc.desc: Verify the Read function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReadTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + fuseoperations_->Read(req, 0, size, off, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ReadTest002 End"; +} + +/** + * @tc.name:ReadTest + * @tc.desc: Verify the Read function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReadTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + size_t size = 0; + off_t off = 0; + struct fuse_file_info fi; + + fuseoperations_->Read(req, ino, size, off, &fi); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReadTest ERROR"; + } + GTEST_LOG_(INFO) << "ReadTest End"; +} + +/** + * @tc.name:WriteBufTest001 + * @tc.desc: Verify the WriteBuf function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, WriteBufTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteBufTest001 Start"; + try { + fuse_req_t req = nullptr; + struct fuse_bufvec *bufv = nullptr; + off_t offset = 0; + struct fuse_file_info fi; + + fuseoperations_->WriteBuf(req, FUSE_ROOT_ID, bufv, offset, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WriteBufTest001 ERROR"; + } + GTEST_LOG_(INFO) << "WriteBufTest001 End"; +} + +/** + * @tc.name:WriteBufTest002 + * @tc.desc: Verify the WriteBuf function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, WriteBufTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteBufTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_bufvec *bufv = nullptr; + off_t offset = 0; + struct fuse_file_info fi; + + fuseoperations_->WriteBuf(req, 0, bufv, offset, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WriteBufTest002 ERROR"; + } + GTEST_LOG_(INFO) << "WriteBufTest002 End"; +} + +/** + * @tc.name:WriteBufTest + * @tc.desc: Verify the WriteBuf function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, WriteBufTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteBufTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + struct fuse_bufvec *bufv = nullptr; + off_t offset = 0; + struct fuse_file_info fi; + + fuseoperations_->WriteBuf(req, ino, bufv, offset, &fi); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WriteBufTest ERROR"; + } + GTEST_LOG_(INFO) << "WriteBufTest End"; +} + +/** + * @tc.name:ReleaseTest001 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReleaseTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest001 Start"; + try { + fuse_req_t req = nullptr; + struct fuse_file_info fi; + + fuseoperations_->Release(req, FUSE_ROOT_ID, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest001 End"; +} + +/** + * @tc.name:ReleaseTest002 + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReleaseTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_file_info fi; + + fuseoperations_->Release(req, 0, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest002 End"; +} + +/** + * @tc.name:ReleaseTest + * @tc.desc: Verify the Release function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, ReleaseTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReleaseTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + struct fuse_file_info fi; + + fuseoperations_->Release(req, ino, &fi); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ReleaseTest ERROR"; + } + GTEST_LOG_(INFO) << "ReleaseTest End"; +} + +/** + * @tc.name:SetAttrTest001 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, SetAttrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest001 Start"; + try { + fuse_req_t req = nullptr; + struct fuse_file_info fi; + struct stat attr; + int valid = 0; + + fuseoperations_->SetAttr(req, FUSE_ROOT_ID, &attr, valid, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest001 End"; +} + +/** + * @tc.name:SetAttrTest002 + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, SetAttrTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + struct fuse_file_info fi; + struct stat attr; + int valid = 0; + + fuseoperations_->SetAttr(req, 0, &attr, valid, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest002 ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest002 End"; +} + +/** + * @tc.name:SetAttrTest + * @tc.desc: Verify the SetAttr function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, SetAttrTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetAttrTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + struct fuse_file_info fi; + struct stat attr; + int valid = 0; + + fuseoperations_->SetAttr(req, ino, &attr, valid, &fi); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetAttrTest ERROR"; + } + GTEST_LOG_(INFO) << "SetAttrTest End"; +} + +/** + * @tc.name:LseekTest001 + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, LseekTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest001 Start"; + try { + fuse_req_t req = nullptr; + off_t off = 0; + int whence = 0; + struct fuse_file_info fi; + + fuseoperations_->Lseek(req, FUSE_ROOT_ID, off, whence, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest001 ERROR"; + } + GTEST_LOG_(INFO) << "LseekTest001 End"; +} + +/** + * @tc.name:LseekTest002 + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, LseekTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest002 Start"; + try { + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + off_t off = 0; + int whence = 0; + struct fuse_file_info fi; + + fuseoperations_->Lseek(req, 0, off, whence, &fi); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest002 ERROR"; + } + GTEST_LOG_(INFO) << "LseekTest002 End"; +} + +/** + * @tc.name:LseekTest + * @tc.desc: Verify the Lseek function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, LseekTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LseekTest Start"; + try { + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + off_t off = 0; + int whence = 0; + struct fuse_file_info fi; + + fuseoperations_->Lseek(req, ino, off, whence, &fi); + EXPECT_NE(ino, FUSE_ROOT_ID); + EXPECT_NE((data.inodeCache)[0], nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LseekTest ERROR"; + } + GTEST_LOG_(INFO) << "LseekTest End"; +} + +/** + * @tc.name: IoctlTest001 + * @tc.desc: Verify the Ioctl function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, IoctlTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IoctlTest001 Start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = FUSE_ROOT_ID; + int cmd = 0; + unsigned flags = true; + + fuseoperations_->Ioctl(req, ino, cmd, nullptr, nullptr, flags, nullptr, 0, 0); + EXPECT_NE(ino, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IoctlTest001 ERROR"; + } + GTEST_LOG_(INFO) << "IoctlTest001 End"; +} + +/** + * @tc.name: IoctlTest002 + * @tc.desc: Verify the Ioctl function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, IoctlTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IoctlTest002 Start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + int cmd = 0; + unsigned flags = true; + + CloudDiskFuseData data; + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); + + fuseoperations_->Ioctl(req, ino, cmd, nullptr, nullptr, flags, nullptr, 0, 0); + EXPECT_NE(ino, FUSE_ROOT_ID); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IoctlTest002 ERROR"; + } + GTEST_LOG_(INFO) << "IoctlTest002 End"; +} + +/** + * @tc.name: IoctlTest003 + * @tc.desc: Verify the Ioctl function + * @tc.type: FUNC + * @tc.require: issuesI92WQP + */ +HWTEST_F(FuseOperationsTest, IoctlTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IoctlTest002 Start"; + try { + fuse_req_t req = nullptr; + fuse_ino_t ino = 0; + int cmd = 0; + unsigned flags = true; + + CloudDiskFuseData data; + (data.inodeCache)[0] = make_shared(); + (data.inodeCache)[0]->ops = make_shared(); + EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) + .WillOnce(Return(reinterpret_cast(&data))); + + fuseoperations_->Ioctl(req, ino, cmd, nullptr, nullptr, flags, nullptr, 0, 0); + EXPECT_NE(ino, FUSE_ROOT_ID); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IoctlTest003 ERROR"; + } + GTEST_LOG_(INFO) << "IoctlTest003 End"; +} +} // namespace OHOS::FileManagement::CloudDisk::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/mock/assistant.h b/cloud_file/test/unittests/cloud_disk/mock/assistant.h new file mode 100644 index 0000000..1c1fcb1 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/mock/assistant.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2024 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 TEST_UNITTESTS_CLOUD_DISK_ASSISTANT_H +#define TEST_UNITTESTS_CLOUD_DISK_ASSISTANT_H +#ifndef FUSE_USE_VERSION +#define FUSE_USE_VERSION 34 +#endif + +#include +#include +#include +#include + +namespace OHOS::FileManagement::CloudDisk { +class Assistant { +public: + static inline std::shared_ptr ins = nullptr; +public: + virtual ~Assistant() = default; + virtual void *fuse_req_userdata(fuse_req_t) = 0; + virtual int fuse_reply_err(fuse_req_t, int) = 0; + virtual int fuse_reply_open(fuse_req_t, const struct fuse_file_info *) = 0; + virtual void fuse_reply_none(fuse_req_t) = 0; + virtual int fuse_reply_data(fuse_req_t, struct fuse_bufvec *, enum fuse_buf_copy_flags) = 0; + virtual size_t fuse_buf_size(const struct fuse_bufvec *) = 0; + virtual ssize_t fuse_buf_copy(struct fuse_bufvec *, struct fuse_bufvec *, enum fuse_buf_copy_flags) = 0; + virtual int fuse_reply_write(fuse_req_t, size_t) = 0; + virtual int fuse_reply_lseek(fuse_req_t, off_t) = 0; + virtual int fuse_reply_buf(fuse_req_t, const char *, size_t) = 0; + virtual int fuse_reply_xattr(fuse_req_t, size_t) = 0; + virtual int fuse_reply_attr(fuse_req_t, const struct stat *, double) = 0; + virtual int fuse_reply_entry(fuse_req_t, const struct fuse_entry_param *) = 0; + virtual int fuse_reply_create(fuse_req_t, const struct fuse_entry_param *, const struct fuse_file_info *) = 0; + virtual int fuse_opt_add_arg(struct fuse_args *args, const char *arg) = 0; + virtual struct fuse_session* fuse_session_new(struct fuse_args *args, const struct fuse_lowlevel_ops *op, + size_t op_size, void *userdata) = 0; + + static int access(const char *name, int type) + { + if (strcmp(name, "mock") == 0) { + return 0; + } + return 1; + } + static int open(const char *file, int oflag) + { + return 0; + } +public: + virtual off_t lseek(int, off_t, int) = 0; +}; + +class AssistantMock : public Assistant { +public: + MOCK_METHOD1(fuse_req_userdata, void*(fuse_req_t)); + MOCK_METHOD2(fuse_reply_err, int(fuse_req_t, int)); + MOCK_METHOD2(fuse_reply_open, int(fuse_req_t, const struct fuse_file_info *)); + MOCK_METHOD1(fuse_reply_none, void(fuse_req_t)); + MOCK_METHOD3(fuse_reply_data, int(fuse_req_t, struct fuse_bufvec *, enum fuse_buf_copy_flags)); + MOCK_METHOD1(fuse_buf_size, size_t(const struct fuse_bufvec *)); + MOCK_METHOD3(fuse_buf_copy, ssize_t(struct fuse_bufvec *, struct fuse_bufvec *, enum fuse_buf_copy_flags)); + MOCK_METHOD2(fuse_reply_write, int(fuse_req_t, size_t)); + MOCK_METHOD2(fuse_reply_lseek, int(fuse_req_t, off_t)); + MOCK_METHOD3(fuse_reply_buf, int(fuse_req_t, const char *, size_t)); + MOCK_METHOD2(fuse_reply_xattr, int(fuse_req_t, size_t)); + MOCK_METHOD3(fuse_reply_attr, int(fuse_req_t, const struct stat *, double)); + MOCK_METHOD2(fuse_reply_entry, int(fuse_req_t, const struct fuse_entry_param *)); + MOCK_METHOD3(fuse_reply_create, int(fuse_req_t, const struct fuse_entry_param *, const struct fuse_file_info *)); + MOCK_METHOD2(fuse_opt_add_arg, int(struct fuse_args *args, const char *arg)); + MOCK_METHOD4(fuse_session_new, struct fuse_session*(struct fuse_args *args, const struct fuse_lowlevel_ops *op, + size_t opSize, void *userData)); +public: + MOCK_METHOD3(lseek, off_t(int, off_t, int)); +}; +} // namespace OHOS::FileManagement::CloudDisk +#endif // TEST_UNITTESTS_CLOUD_DISK_ASSISTANT_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/mock/clouddisk_rdbstore_mock.cpp b/cloud_file/test/unittests/cloud_disk/mock/clouddisk_rdbstore_mock.cpp new file mode 100644 index 0000000..b360365 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/mock/clouddisk_rdbstore_mock.cpp @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2024 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 "clouddisk_rdbstore.h" + +namespace OHOS::FileManagement::CloudDisk { +using namespace std; +using namespace OHOS::NativeRdb; + +CloudDiskRdbStore::CloudDiskRdbStore(const std::string &bundleName, const int32_t &userId) + : bundleName_(bundleName), userId_(userId) +{ + RdbInit(); +} + +CloudDiskRdbStore::~CloudDiskRdbStore() +{ + Stop(); +} + +int32_t CloudDiskRdbStore::ReBuildDatabase(const string &databasePath) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::RdbInit() +{ + return E_OK; +} + +void CloudDiskRdbStore::Stop() +{ + if (rdbStore_ == nullptr) { + return; + } + rdbStore_ = nullptr; +} + +shared_ptr CloudDiskRdbStore::GetRaw() +{ + return rdbStore_; +} + +void CloudDiskRdbStore::DatabaseRestore() +{ +} + +int32_t CloudDiskRdbStore::LookUp(const std::string &parentCloudId, + const std::string &fileName, CloudDiskFileInfo &info) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetAttr(const std::string &cloudId, CloudDiskFileInfo &info) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::SetAttr(const std::string &fileName, const std::string &parentCloudId, + const std::string &cloudId, const unsigned long long &size) +{ + if (cloudId == "") { + return 1; + } else if (size == 1) { + return 1; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::ReadDir(const std::string &cloudId, vector &infos) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::Create(const std::string &cloudId, const std::string &parentCloudId, + const std::string &fileName, bool noNeedUpload) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::MkDir(const std::string &cloudId, const std::string &parentCloudId, + const std::string &directoryName, bool noNeedUpload) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::Write(const std::string &fileName, const std::string &parentCloudId, + const std::string &cloudId) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::LocationSetXattr(const std::string &name, const std::string &parentCloudId, + const std::string &cloudId, const std::string &value) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetRowId(const std::string &cloudId, int64_t &rowId) +{ + if (cloudId == "mock") { + return 1; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::GetParentCloudId(const std::string &cloudId, std::string &parentCloudId) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::RecycleSetXattr(const std::string &name, const std::string &parentCloudId, + const std::string &cloudId, const std::string &value) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::FavoriteSetXattr(const std::string &cloudId, const std::string &value) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::LocationGetXattr(const std::string &name, const std::string &key, std::string &value, + const std::string &parentCloudId) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::FavoriteGetXattr(const std::string &cloudId, const std::string &key, std::string &value) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::FileStatusGetXattr(const std::string &cloudId, const std::string &key, std::string &value) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetExtAttrValue(const std::string &cloudId, const std::string &key, std::string &value) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetExtAttr(const std::string &cloudId, std::string &value, int32_t &position) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetXAttr(const std::string &cloudId, const std::string &key, std::string &value, + const CacheNode &node, const std::string &extAttrKey) +{ + if (cloudId == "rootId") { + return 1; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::ExtAttributeSetXattr(const std::string &cloudId, const std::string &value, + const std::string &key) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::SetXAttr(const std::string &cloudId, const std::string &key, const std::string &value, + const std::string &name, const std::string &parentCloudId) +{ + if (value == "") { + return 1; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::Rename(const std::string &oldParentCloudId, const std::string &oldFileName, + const std::string &newParentCloudId, const std::string &newFileName) +{ + if (oldFileName == "mock" || newFileName == "mock") { + return 1; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::GetHasChild(const std::string &cloudId, bool &hasChild) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::UnlinkSynced(const std::string &cloudId) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::UnlinkLocal(const std::string &cloudId) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::Unlink(const std::string &cloudId, const int32_t &position) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetDirtyType(const std::string &cloudId, int32_t &dirtyType) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetCurNode(const std::string &cloudId, CacheNode &curNode) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetParentNode(const std::string &parentCloudId, std::string &nextCloudId, + std::string &fileName) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetUriFromDB(const std::string &parentCloudId, std::string &uri) +{ + return E_OK; +} + +int32_t CloudDiskRdbStore::GetNotifyUri(const CacheNode &cacheNode, std::string &uri) +{ + if (cacheNode.cloudId == "mock") { + return 1; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::GetNotifyData(const CacheNode &cacheNode, NotifyData ¬ifyData) +{ + if (cacheNode.cloudId == "mock" || cacheNode.fileName == "mock") { + return 1; + } + return E_OK; +} + +int32_t CloudDiskRdbStore::CheckRootIdValid() +{ + return E_OK; +} + +int32_t CloudDiskDataCallBack::OnCreate(RdbStore &store) +{ + return E_OK; +} + +int32_t CloudDiskDataCallBack::OnUpgrade(RdbStore &store, int32_t oldVersion, int32_t newVersion) +{ + return E_OK; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/mock/file_operations_helper_mock.cpp b/cloud_file/test/unittests/cloud_disk/mock/file_operations_helper_mock.cpp new file mode 100644 index 0000000..98c76c0 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/mock/file_operations_helper_mock.cpp @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2024 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 "file_operations_helper.h" + +#include +#include + +#include "file_operations_cloud.h" +#include "file_operations_local.h" +#include "securec.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +namespace { + static const string LOCAL_PATH_DATA_SERVICE_EL2 = "/data/service/el2/"; + static const string LOCAL_PATH_HMDFS_CLOUD_DATA = "/hmdfs/cloud/data/"; + static const string LOCAL_PATH_HMDFS_CLOUD = "/hmdfs/cloud/"; + static const int32_t BUNDLE_NAME_OFFSET = 1000000000; + static const int32_t STAT_MODE_DIR = 0771; + static const int32_t NULL_PTR = -1; + static const int32_t MOCK0 = 0; + static const int32_t MOCK1 = 1; + static const int32_t MOCK2 = 2; + static const int32_t MOCK3 = 3; + static const int32_t MOCK4 = 4; + static const int32_t MOCK5 = 5; + static const int32_t MOCK6 = 6; + static const int32_t MOCK7 = 7; + static const int32_t MOCKUSERID0 = 100; + static const int32_t MOCKUSERID1 = 1; + static const int32_t STATSIZE = 1; +} + +string FileOperationsHelper::GetCloudDiskRootPath(int32_t userId) +{ + if (userId == MOCKUSERID0 || userId == MOCKUSERID1) { + return "/data"; + } + return ""; +} + +string FileOperationsHelper::GetCloudDiskLocalPath(int32_t userId, string fileName) +{ + if (userId == MOCKUSERID0) { + return "/data"; + } + return ""; +} + +void FileOperationsHelper::GetInodeAttr(shared_ptr ino, struct stat *statBuf) +{ + statBuf->st_ino = ino->stat.st_ino; + statBuf->st_uid = ino->stat.st_uid; + statBuf->st_gid = ino->stat.st_gid; + statBuf->st_mtime = ino->stat.st_mtime; + statBuf->st_ctime = ino->stat.st_ctime; + statBuf->st_atime = ino->stat.st_atime; + statBuf->st_mode = ino->stat.st_mode; + statBuf->st_nlink = ino->stat.st_nlink; + if (statBuf->st_mode & S_IFREG) { + statBuf->st_size = ino->stat.st_size; + } +} + +int32_t FileOperationsHelper::GetNextLayer(std::shared_ptr inoPtr, fuse_ino_t ino) +{ + if (ino == FUSE_ROOT_ID) { + return CLOUD_DISK_INODE_ZERO_LAYER; + } + if (inoPtr->layer >= CLOUD_DISK_INODE_OTHER_LAYER) { + return CLOUD_DISK_INODE_OTHER_LAYER; + } else { + return inoPtr->layer + 1; + } +} + +int32_t FileOperationsHelper::GetFixedLayerRootId(int32_t layer) +{ + if (layer == CLOUD_DISK_INODE_ZERO_LAYER) { + return CLOUD_DISK_INODE_ZERO_LAYER_LOCALID; + } else if (layer == CLOUD_DISK_INODE_FIRST_LAYER) { + return CLOUD_DISK_INODE_FIRST_LAYER_LOCALID; + } + return CLOUD_DISK_INODE_LAYER_LOCALID_UNKNOWN; +} + +shared_ptr FileOperationsHelper::FindCloudDiskInode(struct CloudDiskFuseData *data, + int64_t key) +{ + shared_ptr ptr = make_shared(); + if (key == NULL_PTR) { + ptr = nullptr; + } else if (key == MOCK0) { + ptr->parent = -1; + ptr->layer = CLOUD_DISK_INODE_FIRST_LAYER; + ptr->path = ""; + } else if (key == MOCK1) { + ptr->parent = 0; + } else if (key == MOCK2) { + ptr->parent = 0; + ptr->bundleName = "com.ohos.photos"; + ptr->cloudId = "mock"; + ptr->fileName = "mock"; + } else if (key == MOCK3) { + ptr->parent = 0; + ptr->cloudId = "mock"; + ptr->fileName = "test"; + } else if (key == MOCK4) { + ptr->bundleName = "com.ohos.photos"; + ptr->parent = 0; + ptr->cloudId = ""; + ptr->fileName = "test"; + } else if (key == MOCK5) { + ptr = nullptr; + } else if (key == MOCK6) { + ptr->parent = MOCK5; + } else if (key == MOCK7) { + ptr->parent = MOCK7; + ptr->stat.st_size = STATSIZE; + } + return ptr; +} + +shared_ptr FileOperationsHelper::FindCloudDiskFile(struct CloudDiskFuseData *data, + int64_t key) +{ + shared_ptr ptr = make_shared(); + ptr -> type = CLOUD_DISK_FILE_TYPE_LOCAL; + ptr -> refCount = 1; + ptr -> fileDirty = CLOUD_DISK_FILE_CREATE; + if (key == NULL_PTR) { + ptr = nullptr; + } else if (key == MOCK0) { + ptr -> fileDirty = CLOUD_DISK_FILE_UNKNOWN; + } else if (key == MOCK1) { + string recordType = ""; + string recordId = ""; + string assetKey = ""; + string assetPath = ""; + ptr -> type = CLOUD_DISK_FILE_TYPE_CLOUD; + ptr -> readSession = + make_shared(data->userId, recordType, recordId, assetKey, assetPath); + } else if (key == MOCK3) { + ptr -> refCount = 0; + } else if (key == MOCK4) { + ptr = nullptr; + } + return ptr; +} + +int64_t FileOperationsHelper::FindLocalId(struct CloudDiskFuseData *data, const std::string &key) +{ + if (key == "1mock" || key == "0mock") { + return -1; + } + if (data->userId == 1) { + return -1; + } + return 0; +} + +void FileOperationsHelper::AddDirEntry(fuse_req_t req, std::string &buf, size_t &size, const char *name, + std::shared_ptr ino) +{ + size_t oldSize = size; + size += fuse_add_direntry(req, NULL, 0, name, NULL, 0); + buf.resize(size); + fuse_add_direntry(req, &buf[oldSize], size - oldSize, name, &ino->stat, size); +} + +void FileOperationsHelper::FuseReplyLimited(fuse_req_t req, const char *buf, size_t bufSize, + off_t off, size_t maxSize) +{ + if (off < bufSize) { + size_t size = (bufSize - off) < maxSize ? (bufSize - off) : maxSize; + fuse_reply_buf(req, buf + off, size); + } else { + fuse_reply_buf(req, NULL, 0); + } +} + +shared_ptr FileOperationsHelper::GenerateCloudDiskInode(struct CloudDiskFuseData *data, + fuse_ino_t parent, + const string &fileName, + const string &path) +{ + shared_ptr child = make_shared(); + if (data->userId == 1) { + return nullptr; + } + return child; +} + +void FileOperationsHelper::PutCloudDiskInode(struct CloudDiskFuseData *data, + shared_ptr inoPtr, uint64_t num, int64_t key) +{ + std::unique_lock wLock(data->cacheLock, std::defer_lock); + if (inoPtr == nullptr) { + LOGD("Get an invalid inode!"); + return; + } + inoPtr->refCount -= num; + if (inoPtr->refCount == 0) { + LOGD("node released: %{public}" PRId64 "", key); + wLock.lock(); + data->inodeCache.erase(key); + wLock.unlock(); + } +} + +void FileOperationsHelper::PutCloudDiskFile(struct CloudDiskFuseData *data, + shared_ptr filePtr, int64_t key) +{ + std::unique_lock wLock(data->fileLock, std::defer_lock); + if (filePtr == nullptr) { + LOGD("Get an invalid file!"); + return; + } + if (filePtr->refCount == 0) { + LOGD("file released: %{public}" PRId64 "", key); + wLock.lock(); + data->fileCache.erase(key); + wLock.unlock(); + } +} + +void FileOperationsHelper::PutLocalId(struct CloudDiskFuseData *data, + std::shared_ptr inoPtr, + uint64_t num, const std::string &key) +{ + std::unique_lock wLock(data->localIdLock, std::defer_lock); + if (inoPtr == nullptr) { + LOGD("Get an invalid inode!"); + return; + } + inoPtr->refCount -= num; + if (inoPtr->refCount == 0) { + LOGD("node released: %{public}s", key.c_str()); + wLock.lock(); + data->localIdCache.erase(key); + wLock.unlock(); + } +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/mock/file_operations_local_mock.cpp b/cloud_file/test/unittests/cloud_disk/mock/file_operations_local_mock.cpp new file mode 100644 index 0000000..8e292a7 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/mock/file_operations_local_mock.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2023-2024 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 "file_operations_local.h" + +#include +#include + +#include "file_operations_cloud.h" +#include "file_operations_helper.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +static const int32_t BUNDLE_NAME_OFFSET = 1000000000; +static const int32_t STAT_MODE_DIR = 0771; +static const float LOOKUP_TIMEOUT = 60.0; + +void FileOperationsLocal::Lookup(fuse_req_t req, fuse_ino_t parent, const char *name) {} + +void FileOperationsLocal::GetAttr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info *fi) +{ + struct CloudDiskFuseData *data = reinterpret_cast(fuse_req_userdata(req)); + if (ino == FUSE_ROOT_ID) { + string path = FileOperationsHelper::GetCloudDiskRootPath(data->userId); + + struct stat statBuf; + int err = stat(path.c_str(), &statBuf); + if (err != 0) { + LOGE("lookup %{public}s error, err: %{public}d", path.c_str(), err); + fuse_reply_err(req, err); + return; + } + fuse_reply_attr(req, &statBuf, 0); + return; + } + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + fuse_reply_err(req, EINVAL); + LOGE("inode not found"); + return; + } + fuse_reply_attr(req, &inoPtr->stat, 0); +} + +void FileOperationsLocal::ReadDir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info *fi) +{ + (void) fi; + string path; + struct CloudDiskFuseData *data = + reinterpret_cast(fuse_req_userdata(req)); + if (ino == FUSE_ROOT_ID) { + path = FileOperationsHelper::GetCloudDiskRootPath(data->userId); + } else { + auto inoPtr = FileOperationsHelper::FindCloudDiskInode(data, static_cast(ino)); + if (inoPtr == nullptr) { + fuse_reply_err(req, EINVAL); + LOGE("inode not found"); + return; + } + path = inoPtr->path; + } + DIR* dir = opendir(path.c_str()); + if (dir == NULL) { + LOGE("opendir error %{public}d, path:%{public}s", errno, path.c_str()); + return; + } + + struct dirent *entry; + string entryData; + size_t len = 0; + while ((entry = readdir(dir)) != NULL) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { + continue; + } + + string childPath = FileOperationsHelper::GetCloudDiskLocalPath(data->userId, + entry->d_name); + int64_t key = FileOperationsHelper::FindLocalId(data, std::to_string(ino) + + entry->d_name); + auto childPtr = FileOperationsHelper::FindCloudDiskInode(data, key); + if (childPtr == nullptr) { + childPtr = FileOperationsHelper::GenerateCloudDiskInode(data, ino, + entry->d_name, childPath.c_str()); + } + if (childPtr == nullptr) { + continue; + } + FileOperationsHelper::AddDirEntry(req, entryData, len, entry->d_name, childPtr); + } + FileOperationsHelper::FuseReplyLimited(req, entryData.c_str(), len, off, size); + closedir(dir); + return; +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloud_disk/mock/libfuse_mock.cpp b/cloud_file/test/unittests/cloud_disk/mock/libfuse_mock.cpp new file mode 100644 index 0000000..10ab7d6 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/mock/libfuse_mock.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2024 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 "file_operations_base.h" + +#include "assistant.h" + +using namespace OHOS::FileManagement::CloudDisk; +void *fuse_req_userdata(fuse_req_t req) +{ + return Assistant::ins->fuse_req_userdata(req); +} + +int fuse_reply_err(fuse_req_t req, int err) +{ + return Assistant::ins->fuse_reply_err(req, err); +} + +int fuse_reply_open(fuse_req_t req, const struct fuse_file_info *fi) +{ + return Assistant::ins->fuse_reply_open(req, fi); +} + +void fuse_reply_none(fuse_req_t req) +{ + return Assistant::ins->fuse_reply_none(req); +} + +int fuse_reply_data(fuse_req_t req, struct fuse_bufvec *bufv, enum fuse_buf_copy_flags flags) +{ + return Assistant::ins->fuse_reply_data(req, bufv, flags); +} + +size_t fuse_buf_size(const struct fuse_bufvec *bufv) +{ + return Assistant::ins->fuse_buf_size(bufv); +} + +ssize_t fuse_buf_copy(struct fuse_bufvec *dst, struct fuse_bufvec *src, enum fuse_buf_copy_flags flags) +{ + return Assistant::ins->fuse_buf_copy(dst, src, flags); +} + +int fuse_reply_write(fuse_req_t req, size_t count) +{ + return Assistant::ins->fuse_reply_write(req, count); +} + +int fuse_reply_lseek(fuse_req_t req, off_t off) +{ + return Assistant::ins->fuse_reply_lseek(req, off); +} + +int fuse_reply_buf(fuse_req_t req, const char *buf, size_t size) +{ + return Assistant::ins->fuse_reply_buf(req, buf, size); +} + +int fuse_reply_xattr(fuse_req_t req, size_t count) +{ + return Assistant::ins->fuse_reply_xattr(req, count); +} + +int fuse_reply_attr(fuse_req_t req, const struct stat *attr, double attr_timeout) +{ + return Assistant::ins->fuse_reply_attr(req, attr, attr_timeout); +} + +int fuse_reply_entry(fuse_req_t req, const struct fuse_entry_param *e) +{ + return Assistant::ins->fuse_reply_entry(req, e); +} + +int fuse_reply_create(fuse_req_t req, const struct fuse_entry_param *e, const struct fuse_file_info *f) +{ + return Assistant::ins->fuse_reply_create(req, e, f); +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_disk/mock/system_function_mock.cpp b/cloud_file/test/unittests/cloud_disk/mock/system_function_mock.cpp new file mode 100644 index 0000000..96018e4 --- /dev/null +++ b/cloud_file/test/unittests/cloud_disk/mock/system_function_mock.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 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 +#include +#include +#include + +#include "file_operations_base.h" + +#include "assistant.h" + +using namespace OHOS::FileManagement::CloudDisk; +int access(const char *name, int type) +{ + return Assistant::ins->access(name, type); +} + +int open(const char *file, int oflag) +{ + return Assistant::ins->open(file, oflag); +} + +off_t lseek(int fd, off_t offset, int whence) +{ + return Assistant::ins->lseek(fd, offset, whence); +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/BUILD.gn b/cloud_file/test/unittests/cloud_file_kit_inner/BUILD.gn new file mode 100644 index 0000000..ac974f8 --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (C) 2024 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. +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +group("cloud_file_kit_inner_test") { + testonly = true + deps = [ + "big_data_statistics:big_data_statistics_test", + "cloud_kit:cloud_kit_test", + "data_sync:data_sync_test", + ] +} diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/BUILD.gn b/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/BUILD.gn new file mode 100644 index 0000000..aa943db --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/BUILD.gn @@ -0,0 +1,116 @@ +# Copyright (C) 2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("gallery_download_file_stat_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "gallery_download_file_stat_test.cpp" ] + + include_dirs = [ + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + ] + + defines = [ + "private=public", + "LOG_TAG=\"cloud_file_kit_inner_test\"", + ] + use_exceptions = true +} + +ohos_unittest("cloud_file_fault_event_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_file_fault_event.cpp", + "cloud_file_fault_event_test.cpp", + ] + + include_dirs = [ + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + ] + + defines = [ + "private=public", + "LOG_TAG=\"cloud_file_kit_inner_test\"", + ] + use_exceptions = true +} + +ohos_unittest("cloud_report_cacher_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/cloud_report_cacher.cpp", + "cloud_report_cacher_test.cpp", + ] + + include_dirs = [ + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/big_data_statistics", + ] + + deps = [] + + external_deps = [ + "cloud_file:libdistributedfileutils_lite", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "json:nlohmann_json_static", + ] + + defines = [ "private=public" ] + use_exceptions = true +} + +group("big_data_statistics_test") { + testonly = true + deps = [ + ":cloud_file_fault_event_test", + ":cloud_report_cacher_test", + ":gallery_download_file_stat_test", + ] +} diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/cloud_file_fault_event_test.cpp b/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/cloud_file_fault_event_test.cpp new file mode 100644 index 0000000..e7823b3 --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/cloud_file_fault_event_test.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2024 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 +#include +#include "cloud_file_fault_event.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudFileFultEventTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + CloudFaultReportStatus& status = CloudFaultReportStatus::GetInstance(); +}; + +void CloudFileFultEventTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudFileFultEventTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudFileFultEventTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudFileFultEventTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +HWTEST_F(CloudFileFultEventTest, CloudSyncFaultReportTest_001, TestSize.Level1) +{ + std::string functionName = "TestFunction"; + int lineNumber = 123; + CloudSyncFaultInfo event; + event.bundleName_ = "com.example.app"; + event.faultScenario_ = FaultScenarioCode::CLOUD_FULL_SYNC; + event.faultType_ = FaultType::TIMEOUT; + event.faultErrorCode_ = -1; + event.message_ = "Sync failed"; + int32_t result = CloudFileFaultEvent::CloudSyncFaultReport(functionName, lineNumber, event); + EXPECT_EQ(result, event.faultErrorCode_); +} + +HWTEST_F(CloudFileFultEventTest, CloudFileFaultReportTest_001, TestSize.Level1) +{ + std::string functionName = "TestFunction"; + int lineNumber = 123; + CloudFileFaultInfo event; + event.bundleName_ = "com.example.app"; + event.faultOperation_ = FaultOperation::LOOKUP; + event.faultType_ = FaultType::TIMEOUT; + event.faultErrorCode_ = -1; + event.message_ = "Sync failed"; + int32_t result = CloudFileFaultEvent::CloudFileFaultReport(functionName, lineNumber, event); + EXPECT_EQ(result, event.faultErrorCode_); +} + +HWTEST_F(CloudFileFultEventTest, CloudSyncCacheReportTest_001, TestSize.Level1) +{ + std::string functionName = "TestFunction"; + int lineNumber = 123; + CloudCacheFaultInfo event; + event.bundleName_ = "com.example.app"; + event.faultType_ = FaultType::DENTRY_FILE; + event.faultErrorCode_ = -1; + event.message_ = "Sync failed"; + int32_t result = CloudFileFaultEvent::CloudSyncCacheReport(functionName, lineNumber, event); + EXPECT_EQ(result, event.faultErrorCode_); +} + +HWTEST_F(CloudFileFultEventTest, IsAllowToReporttTest_001, TestSize.Level1) +{ + FaultType faultType = FaultType::OPEN_CLOUD_FILE_TIMEOUT; + EXPECT_TRUE(status.IsAllowToReport(faultType)); + EXPECT_FALSE(status.IsAllowToReport(faultType)); + + faultType = FaultType::DENTRY_FILE; + EXPECT_TRUE(status.IsAllowToReport(faultType)); +} + +} diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/cloud_report_cacher_test.cpp b/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/cloud_report_cacher_test.cpp new file mode 100644 index 0000000..df2dc70 --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/cloud_report_cacher_test.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2025 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 +#include +#include "cloud_report_cacher.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudReportCacherTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + CloudReportCacher& Cacher = CloudReportCacher::GetInstance(); +}; + +void CloudReportCacherTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudReportCacherTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudReportCacherTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudReportCacherTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +HWTEST_F(CloudReportCacherTest, InitTest, TestSize.Level1) +{ + std::string bundleName; + std::string traceId; + uint32_t scenarioCode = 1; + + Cacher.Init(bundleName, traceId, scenarioCode); + + bundleName = "bundleName"; + traceId = "traceId"; + Cacher.Init(bundleName, traceId, scenarioCode); + EXPECT_EQ(bundleName, "bundleName"); +} + +HWTEST_F(CloudReportCacherTest, SetScenarioCodeTest, TestSize.Level1) +{ + std::string bundleName; + uint32_t scenarioCode = 1; + + Cacher.SetScenarioCode(bundleName, scenarioCode); + + bundleName = "bundleName"; + Cacher.SetScenarioCode(bundleName, scenarioCode); + EXPECT_EQ(bundleName, "bundleName"); +} + +HWTEST_F(CloudReportCacherTest, PushEventTest, TestSize.Level1) +{ + std::string bundleName = ""; + CloudFaultInfo event; + + Cacher.PushEvent(bundleName, event); + EXPECT_EQ(bundleName, ""); +} + +HWTEST_F(CloudReportCacherTest, ReportTest, TestSize.Level1) +{ + std::string bundleName = ""; + int scheduleType = 0; + + Cacher.Report(bundleName, scheduleType); + scheduleType = 1; + Cacher.Report(bundleName, scheduleType); + EXPECT_EQ(scheduleType, 1); +} + +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat_test.cpp b/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat_test.cpp new file mode 100644 index 0000000..3476fc8 --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat_test.cpp @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2024 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 +#include +#include "gallery_download_file_stat.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +#define TYPE_DOWNLOAD_FILE_IMAGE 1 +#define TYPE_DOWNLOAD_FILE_VIDEO 2 +#define DOWNLOAD_FILE_BYTE_SIZE 1e6 +#define DURAITON_MODE 970 +#define DOWNLOAD_IMAGE_SIZE_RANGE_TWO 2 +#define DOWNLOAD_IMAGE_SIZE_RANGE_FOUR 4 +#define DOWNLOAD_IMAGE_SIZE_RANGE_SIX 6 +#define DOWNLOAD_IMAGE_SIZE_RANGE_EIGHT 8 +#define DOWNLOAD_IMAGE_SIZE_RANGE_FIFTEEN 15 +#define DOWNLOAD_VIDEO_SIZE_RANGE_TWENTY 20 +#define DOWNLOAD_VIDEO_SIZE_RANGE_FORTY 40 +#define DOWNLOAD_VIDEO_SIZE_RANGE_EIGHTY 80 +#define DOWNLOAD_VIDEO_SIZE_RANGE_TWOHUNDRED 200 +#define DOWNLOAD_VIDEO_SIZE_RANGE_FOURHUNDRED 400 +#define DOWNLOAD_VIDEO_SIZE_RANGE_EIGHTHUNDRED 800 + +class GalleryDownloadFileStatTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void GalleryDownloadFileStatTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void GalleryDownloadFileStatTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void GalleryDownloadFileStatTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void GalleryDownloadFileStatTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_001 Start"; + try { + GalleryDownloadFileStat::GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_001 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_001 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_002 Start"; + try { + GalleryDownloadFileStat::GetInstance().OutputToFile(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_002 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_002 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_003 Start"; + try { + GalleryDownloadFileStat::GetInstance().Report(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_003 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_003 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_004 Start"; + try { + GalleryDownloadFileStat galleryDownloadFileStat; + uint32_t mediaType = TYPE_DOWNLOAD_FILE_IMAGE; + uint64_t size = DOWNLOAD_FILE_BYTE_SIZE; + uint64_t duration = DURAITON_MODE; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_004 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_004 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_005 Start"; + try { + GalleryDownloadFileStat galleryDownloadFileStat; + uint32_t mediaType = TYPE_DOWNLOAD_FILE_VIDEO; + uint64_t size = DOWNLOAD_FILE_BYTE_SIZE; + uint64_t duration = DURAITON_MODE; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_005 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_005 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_006 Start"; + try { + GalleryDownloadFileStat galleryDownloadFileStat; + uint32_t mediaType = TYPE_DOWNLOAD_FILE_IMAGE; + uint64_t size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_TWO; + uint64_t duration = DURAITON_MODE; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_FOUR; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_SIX; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_EIGHT; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_FIFTEEN; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_006 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_006 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_007 Start"; + try { + GalleryDownloadFileStat galleryDownloadFileStat; + uint32_t mediaType = TYPE_DOWNLOAD_FILE_VIDEO; + uint64_t size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_TWENTY; + uint64_t duration = DURAITON_MODE; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_FORTY; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_EIGHTY; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_TWOHUNDRED; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_FOURHUNDRED; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_EIGHTHUNDRED; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_007 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_007 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_008 Start"; + try { + GalleryDownloadFileStat galleryDownloadFileStat; + uint32_t mediaType = TYPE_DOWNLOAD_FILE_IMAGE; + uint64_t size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_TWO + TYPE_DOWNLOAD_FILE_IMAGE; + uint64_t duration = DURAITON_MODE; + galleryDownloadFileStat.OutputToFile(); + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_FOUR + TYPE_DOWNLOAD_FILE_IMAGE; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_SIX + TYPE_DOWNLOAD_FILE_IMAGE; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_EIGHT + TYPE_DOWNLOAD_FILE_IMAGE; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_IMAGE_SIZE_RANGE_FIFTEEN + TYPE_DOWNLOAD_FILE_IMAGE; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + galleryDownloadFileStat.Report(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_008 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_008 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_009 Start"; + try { + GalleryDownloadFileStat galleryDownloadFileStat; + uint32_t mediaType = TYPE_DOWNLOAD_FILE_VIDEO; + uint64_t size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_TWENTY + TYPE_DOWNLOAD_FILE_VIDEO; + uint64_t duration = DURAITON_MODE; + galleryDownloadFileStat.OutputToFile(); + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_FORTY + TYPE_DOWNLOAD_FILE_VIDEO; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_EIGHTY + TYPE_DOWNLOAD_FILE_VIDEO; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_TWOHUNDRED + TYPE_DOWNLOAD_FILE_VIDEO; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_FOURHUNDRED + TYPE_DOWNLOAD_FILE_VIDEO; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + + size = DOWNLOAD_FILE_BYTE_SIZE * DOWNLOAD_VIDEO_SIZE_RANGE_EIGHTHUNDRED + TYPE_DOWNLOAD_FILE_VIDEO; + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + galleryDownloadFileStat.Report(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_009 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_009 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_010 Start"; + try { + GalleryDownloadFileStat galleryDownloadFileStat; + uint32_t mediaType = TYPE_DOWNLOAD_FILE_IMAGE; + uint64_t size = DOWNLOAD_FILE_BYTE_SIZE; + uint64_t duration = DURAITON_MODE; + galleryDownloadFileStat.OutputToFile(); + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + galleryDownloadFileStat.Report(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_010 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_010 End"; +} + +HWTEST_F(GalleryDownloadFileStatTest, GalleryDownloadFileStatTest_011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_011 Start"; + try { + GalleryDownloadFileStat galleryDownloadFileStat; + uint32_t mediaType = TYPE_DOWNLOAD_FILE_VIDEO; + uint64_t size = DOWNLOAD_FILE_BYTE_SIZE; + uint64_t duration = DURAITON_MODE; + galleryDownloadFileStat.OutputToFile(); + galleryDownloadFileStat.UpdateDownloadStat(mediaType, size, duration); + galleryDownloadFileStat.Report(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_011 ERROR"; + } + GTEST_LOG_(INFO) << "GalleryDownloadFileStatTest_011 End"; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/cloud_kit/BUILD.gn b/cloud_file/test/unittests/cloud_file_kit_inner/cloud_kit/BUILD.gn new file mode 100644 index 0000000..ff456a7 --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/cloud_kit/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (C) 2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("cloud_file_kit_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/cloud_file_kit.cpp", + "cloud_file_kit_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src", + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner/", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + ] + + defines = [ + "private=public", + "LOG_TAG=\"cloud_file_kit_inner_test\"", + ] + use_exceptions = true +} + +group("cloud_kit_test") { + testonly = true + deps = [ ":cloud_file_kit_test" ] +} diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/cloud_kit/cloud_file_kit_test.cpp b/cloud_file/test/unittests/cloud_file_kit_inner/cloud_kit/cloud_file_kit_test.cpp new file mode 100644 index 0000000..bd6b7df --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/cloud_kit/cloud_file_kit_test.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "cloud_file_kit.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudFile { +namespace Test { +using namespace testing::ext; +using namespace std; + + +class CloudFileKitTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudFileKitTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudFileKitTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudFileKitTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudFileKitTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: StartTest001 + * @tc.desc: Verify the Start function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudFileKitTest, RegisterCloudInstanceTest001, TestSize.Level1) +{ + CloudFileKit *firstInstance = new CloudFileKit(); + EXPECT_TRUE(CloudFileKit::RegisterCloudInstance(firstInstance)); + + CloudFileKit *secondInstance = new CloudFileKit(); + EXPECT_FALSE(CloudFileKit::RegisterCloudInstance(secondInstance)); + + delete firstInstance; + delete secondInstance; +} + +} // namespace Test +} // namespace FileManagement::CloudFile +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/BUILD.gn b/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/BUILD.gn new file mode 100644 index 0000000..1db6838 --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/BUILD.gn @@ -0,0 +1,141 @@ +# Copyright (C) 2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("data_syncer_rdb_store_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync/data_syncer_rdb_store.cpp", + "data_syncer_rdb_store_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/", + "${innerkits_native_path}/cloud_file_kit_inner", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync", + "${cloud_file_path}/test/unittests/clouddisk_database/include", + "${cloud_file_path}/test/unittests/clouddisk_database/mock", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit_core", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "init:libbegetutil", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + ] + + defines = [ + "private=public", + "LOG_TAG=\"cloud_file_kit_inner_test\"", + ] + use_exceptions = true +} + +ohos_unittest("sync_state_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp", + "${innerkits_native_path}/cloud_file_kit_inner/sync_state_manager.h", + "sync_state_manager_test.cpp", + ] + + include_dirs = [ + "${innerkits_native_path}/cloud_file_kit_inner", + "${cloud_file_path}/frameworks/native/distributed_file_inner/include", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "preferences:native_preferences", + ] + + defines = [ + "private=public", + "LOG_TAG=\"cloud_file_kit_inner_test\"", + ] + + use_exceptions = true +} + +ohos_unittest("task_state_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync/task_state_manager.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/parameters.cpp", + "task_state_manager_test.cpp", + ] + + include_dirs = [ + "${innerkits_native_path}/cloud_file_kit_inner", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "commonlibrary/c_utils/base/include/", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit_core", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "libfuse:libfuse", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_TAG=\"cloud_file_kit_inner_test\"", + ] + + use_exceptions = true +} + +group("data_sync_test") { + testonly = true + deps = [ + ":data_syncer_rdb_store_test", + ":sync_state_manager_test", + ":task_state_manager_test", + ] +} diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/data_syncer_rdb_store_test.cpp b/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/data_syncer_rdb_store_test.cpp new file mode 100644 index 0000000..d30666c --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/data_syncer_rdb_store_test.cpp @@ -0,0 +1,339 @@ +/* + * Copyright (c) 2024 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 "data_syncer_rdb_store.h" +#include +#include +#include "dfs_error.h" +#include "file_column.h" +#include "data_syncer_rdb_col.h" +#include "rdb_assistant.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MockDataSyncerRdbStore : public DataSyncerRdbStore { +public: + MOCK_METHOD2(Insert, int32_t(int32_t userId, const string &bundleName)); + MOCK_METHOD3(UpdateSyncState, int32_t(int32_t userId, const string &bundleName, SyncState syncState)); + MOCK_METHOD3(GetLastSyncTime, int32_t(int32_t userId, const string &bundleName, int64_t &time)); + MOCK_METHOD2(QueryDataSyncer, int32_t(int32_t userId, shared_ptr &resultSet)); + MOCK_METHOD2(Query, int32_t(NativeRdb::AbsRdbPredicates predicates, shared_ptr &resultSet)); + MOCK_METHOD0(RdbInit, int32_t()); + MOCK_METHOD0(GetInstance, DataSyncerRdbStore&()); +}; + +class DataSyncerRdbStoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DataSyncerRdbStoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void DataSyncerRdbStoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void DataSyncerRdbStoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void DataSyncerRdbStoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_001 Start"; + try { + MockDataSyncerRdbStore mockDataSyncerRdbStore; + int32_t userId = 1; + EXPECT_CALL(mockDataSyncerRdbStore, Insert(userId, "testbundleName")) + .WillOnce(Return(E_SEVICE_DIED)) + .WillOnce(Return(E_OK)) + .WillOnce(Return(E_RDB)); + + EXPECT_EQ(mockDataSyncerRdbStore.Insert(userId, "testbundleName"), E_SEVICE_DIED); + EXPECT_EQ(mockDataSyncerRdbStore.Insert(userId, "testbundleName"), E_OK); + EXPECT_EQ(mockDataSyncerRdbStore.Insert(userId, "testbundleName"), E_RDB); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_001 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_001 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_002 Start"; + try { + MockDataSyncerRdbStore mockDataSyncerRdbStore; + EXPECT_CALL(mockDataSyncerRdbStore, GetInstance()) + .WillOnce(ReturnRef(mockDataSyncerRdbStore)); + + mockDataSyncerRdbStore.GetInstance(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_002 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_002 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_003 Start"; + try { + MockDataSyncerRdbStore mockDataSyncerRdbStore; + EXPECT_CALL(mockDataSyncerRdbStore, RdbInit()) + .WillOnce(Return(E_RDB)) + .WillOnce(Return(E_OK)); + + EXPECT_EQ(mockDataSyncerRdbStore.RdbInit(), E_RDB); + EXPECT_EQ(mockDataSyncerRdbStore.RdbInit(), E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_003 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_003 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_004 Start"; + try { + MockDataSyncerRdbStore mockDataSyncerRdbStore; + int32_t userId = 1; + string bundleName = "testbundleName"; + EXPECT_CALL(mockDataSyncerRdbStore, UpdateSyncState(userId, bundleName, SyncState::INIT)) + .WillOnce(Return(E_OK)); + EXPECT_CALL(mockDataSyncerRdbStore, UpdateSyncState(userId, bundleName, SyncState::SYNC_SUCCEED)) + .WillOnce(Return(E_OK)); + + EXPECT_EQ(mockDataSyncerRdbStore.UpdateSyncState(userId, bundleName, SyncState::INIT), E_OK); + EXPECT_EQ(mockDataSyncerRdbStore.UpdateSyncState(userId, bundleName, SyncState::SYNC_SUCCEED), E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_004 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_004 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_005 Start"; + try { + MockDataSyncerRdbStore mockDataSyncerRdbStore; + int32_t userId = 1; + string bundleName = "testbundleName"; + int64_t time = 20240713; + EXPECT_CALL(mockDataSyncerRdbStore, GetLastSyncTime(userId, bundleName, time)) + .WillOnce(Return(E_INVAL_ARG)) + .WillOnce(Return(E_OK)); + + EXPECT_EQ(mockDataSyncerRdbStore.GetLastSyncTime(userId, bundleName, time), E_INVAL_ARG); + EXPECT_EQ(mockDataSyncerRdbStore.GetLastSyncTime(userId, bundleName, time), E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_005 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_005 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_006 Start"; + try { + MockDataSyncerRdbStore mockDataSyncerRdbStore; + + EXPECT_CALL(mockDataSyncerRdbStore, Query(_, _)) + .WillOnce(Return(E_RDB)) + .WillOnce(Return(E_OK)); + + NativeRdb::AbsRdbPredicates predicates = NativeRdb::AbsRdbPredicates(DATA_SYNCER_TABLE); + shared_ptr resultSet; + auto queryRet1 = mockDataSyncerRdbStore.Query(predicates, resultSet); + auto queryRet2 = mockDataSyncerRdbStore.Query(predicates, resultSet); + EXPECT_EQ(queryRet1, E_RDB); + EXPECT_EQ(queryRet2, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_006 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_006 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_007 Start"; + try { + MockDataSyncerRdbStore mockDataSyncerRdbStore; + EXPECT_CALL(mockDataSyncerRdbStore, RdbInit()) + .WillOnce(Return(E_RDB)) + .WillOnce(Return(E_OK)); + + EXPECT_EQ(mockDataSyncerRdbStore.RdbInit(), E_RDB); + EXPECT_EQ(mockDataSyncerRdbStore.RdbInit(), E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_007 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_007 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_008 Start"; + try { + DataSyncerRdbStore dataSyncerRdbStore; + int32_t userId = 1; + string bundleName = "testBundleName"; + int32_t ret = dataSyncerRdbStore.Insert(userId, bundleName); + EXPECT_EQ(ret, E_OK); + + userId = 0; + ret = dataSyncerRdbStore.Insert(userId, bundleName); + EXPECT_EQ(ret, E_OK); + + userId = -1; + bundleName = "test01"; + ret = dataSyncerRdbStore.Insert(userId, bundleName); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_008 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_008 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_009 Start"; + try { + DataSyncerRdbStore dataSyncerRdbStore; + int32_t userId = 1; + string bundleName = "testBundleName"; + int32_t ret = dataSyncerRdbStore.Insert(userId, bundleName); + EXPECT_EQ(ret, E_OK); + ret = dataSyncerRdbStore.UpdateSyncState(userId, bundleName, SyncState::SYNC_SUCCEED); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_009 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_009 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_010 Start"; + try { + DataSyncerRdbStore dataSyncerRdbStore; + int32_t userId = 1; + string bundleName = "testBundleName"; + int32_t ret = dataSyncerRdbStore.Insert(userId, bundleName); + EXPECT_EQ(ret, E_OK); + ret = dataSyncerRdbStore.UpdateSyncState(userId, bundleName, SyncState::INIT); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_010 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_010 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_011 Start"; + try { + DataSyncerRdbStore dataSyncerRdbStore; + int32_t userId = 0; + string bundleName = "testBundleName"; + int64_t time = 20240722; + + int32_t ret = dataSyncerRdbStore.GetLastSyncTime(userId, bundleName, time); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_011 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_011 End"; +} + +HWTEST_F(DataSyncerRdbStoreTest, DataSyncerRdbStoreTest_012, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_012 Start"; + try { + DataSyncerRdbStore dataSyncerRdbStore; + int32_t userId = 0; + shared_ptr resultSet; + + int32_t ret = dataSyncerRdbStore.QueryDataSyncer(userId, resultSet); + EXPECT_EQ(ret, E_OK); + userId = 20; + ret = dataSyncerRdbStore.QueryDataSyncer(userId, resultSet); + EXPECT_EQ(ret, E_OK); + + userId = -1; + ret = dataSyncerRdbStore.QueryDataSyncer(userId, resultSet); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_012 ERROR"; + } + GTEST_LOG_(INFO) << "DataSyncerRdbStoreTest_012 End"; +} + + +HWTEST_F(DataSyncerRdbStoreTest, OnUpgradeTest, TestSize.Level1) +{ + CloudDisk::RdbStoreMock store; + DataSyncerRdbCallBack callback; + int32_t oldVersion = 1; + int32_t newVersion = 2; + int32_t result = callback.OnUpgrade(store, oldVersion, newVersion); + EXPECT_EQ(result, E_OK); +} + +HWTEST_F(DataSyncerRdbStoreTest, OnCreateTest01, TestSize.Level1) +{ + CloudDisk::RdbStoreMock store; + DataSyncerRdbCallBack callback; + EXPECT_CALL(store, ExecuteSql(_, _)).WillOnce(Return(E_RDB)); + int32_t result = callback.OnCreate(store); + EXPECT_EQ(result, E_RDB); +} + +HWTEST_F(DataSyncerRdbStoreTest, OnCreateTest02, TestSize.Level1) +{ + CloudDisk::RdbStoreMock store; + DataSyncerRdbCallBack callback; + EXPECT_CALL(store, ExecuteSql(_, _)) + .WillOnce(Return(E_OK)) + .WillOnce(Return(E_OK)); + int32_t result = callback.OnCreate(store); + EXPECT_EQ(result, E_OK); +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/sync_state_manager_test.cpp b/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/sync_state_manager_test.cpp new file mode 100644 index 0000000..38da5b2 --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/sync_state_manager_test.cpp @@ -0,0 +1,467 @@ +/* + * Copyright (c) 2024 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 "sync_state_manager.h" +#include +#include + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MockSyncStateManager : public SyncStateManager { +public: + MOCK_METHOD1(UpdateSyncState, Action(SyncState newState)); + MOCK_METHOD2(CheckAndSetPending, bool(bool forceFlag, SyncTriggerType triggerType)); + MOCK_METHOD0(SetCleaningFlag, void()); + MOCK_METHOD0(ClearCleaningFlag, Action()); + MOCK_METHOD0(CheckCleaningFlag, bool()); + MOCK_METHOD0(GetStopSyncFlag, bool()); + MOCK_METHOD0(SetStopSyncFlag, void()); + MOCK_METHOD0(SetDisableCloudFlag, void()); + MOCK_METHOD0(ClearDisableCloudFlag, Action()); + MOCK_METHOD0(CheckDisableCloudFlag, bool()); + MOCK_METHOD0(GetSyncState, void()); + MOCK_METHOD0(GetForceFlag, bool()); +}; + +class SyncStateManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void SyncStateManagerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void SyncStateManagerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void SyncStateManagerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void SyncStateManagerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_001"; + MockSyncStateManager mockSyncStateManager; + try { + EXPECT_CALL(mockSyncStateManager, SetCleaningFlag()); + mockSyncStateManager.SetCleaningFlag(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_001 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_001 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_002"; + MockSyncStateManager mockSyncStateManager; + try { + EXPECT_CALL(mockSyncStateManager, UpdateSyncState(SyncState::INIT)).Times(1); + EXPECT_CALL(mockSyncStateManager, UpdateSyncState(SyncState::SYNCING)).Times(1); + EXPECT_CALL(mockSyncStateManager, UpdateSyncState(SyncState::SYNC_FAILED)).Times(1); + EXPECT_CALL(mockSyncStateManager, UpdateSyncState(SyncState::SYNC_SUCCEED)).Times(1); + + EXPECT_EQ(mockSyncStateManager.UpdateSyncState(SyncState::INIT), Action::STOP); + EXPECT_EQ(mockSyncStateManager.UpdateSyncState(SyncState::SYNCING), Action::STOP); + EXPECT_EQ(mockSyncStateManager.UpdateSyncState(SyncState::SYNC_FAILED), Action::STOP); + EXPECT_EQ(mockSyncStateManager.UpdateSyncState(SyncState::SYNC_SUCCEED), Action::STOP); + EXPECT_EQ(mockSyncStateManager.ClearCleaningFlag(), Action::STOP); + EXPECT_EQ(mockSyncStateManager.ClearDisableCloudFlag(), Action::STOP); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_002 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_002 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_003"; + MockSyncStateManager mockSyncStateManager; + try { + EXPECT_CALL(mockSyncStateManager, CheckAndSetPending(true, SyncTriggerType::APP_TRIGGER)) + .WillOnce(Return(true)) + .WillOnce(Return(false)); + EXPECT_CALL(mockSyncStateManager, CheckAndSetPending(false, SyncTriggerType::TASK_TRIGGER)) + .WillOnce(Return(true)) + .WillOnce(Return(false)); + ASSERT_TRUE(mockSyncStateManager.CheckAndSetPending(true, SyncTriggerType::APP_TRIGGER)); + ASSERT_FALSE(mockSyncStateManager.CheckAndSetPending(true, SyncTriggerType::APP_TRIGGER)); + ASSERT_TRUE(mockSyncStateManager.CheckAndSetPending(false, SyncTriggerType::TASK_TRIGGER)); + ASSERT_FALSE(mockSyncStateManager.CheckAndSetPending(false, SyncTriggerType::TASK_TRIGGER)); + + EXPECT_CALL(mockSyncStateManager, CheckAndSetPending(false, SyncTriggerType::TASK_TRIGGER)); + EXPECT_CALL(mockSyncStateManager, CheckAndSetPending(true, SyncTriggerType::CLOUD_TRIGGER)); + EXPECT_CALL(mockSyncStateManager, CheckAndSetPending(true, SyncTriggerType::PENDING_TRIGGER)); + EXPECT_CALL(mockSyncStateManager, CheckAndSetPending(true, SyncTriggerType::BATTERY_OK_TRIGGER)); + EXPECT_CALL(mockSyncStateManager, CheckAndSetPending(true, SyncTriggerType::NETWORK_AVAIL_TRIGGER)); + EXPECT_CALL(mockSyncStateManager, CheckAndSetPending(true, SyncTriggerType::SYSTEM_LOAD_TRIGGER)); + mockSyncStateManager.CheckAndSetPending(false, SyncTriggerType::TASK_TRIGGER); + mockSyncStateManager.CheckAndSetPending(true, SyncTriggerType::CLOUD_TRIGGER); + mockSyncStateManager.CheckAndSetPending(true, SyncTriggerType::PENDING_TRIGGER); + mockSyncStateManager.CheckAndSetPending(true, SyncTriggerType::BATTERY_OK_TRIGGER); + mockSyncStateManager.CheckAndSetPending(true, SyncTriggerType::NETWORK_AVAIL_TRIGGER); + mockSyncStateManager.CheckAndSetPending(true, SyncTriggerType::SYSTEM_LOAD_TRIGGER); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_003 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_003 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_004"; + MockSyncStateManager mockSyncStateManager; + try { + EXPECT_CALL(mockSyncStateManager, GetStopSyncFlag()) + .WillOnce(Return(true)) + .WillOnce(Return(false)); + ASSERT_TRUE(mockSyncStateManager.GetStopSyncFlag()); + ASSERT_FALSE(mockSyncStateManager.GetStopSyncFlag()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_004 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_004 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_005"; + MockSyncStateManager mockSyncStateManager; + try { + EXPECT_CALL(mockSyncStateManager, SetStopSyncFlag()); + mockSyncStateManager.SetStopSyncFlag(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_005 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_005 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_006"; + MockSyncStateManager mockSyncStateManager; + try { + EXPECT_CALL(mockSyncStateManager, SetDisableCloudFlag()); + mockSyncStateManager.SetDisableCloudFlag(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_006 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_006 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_007"; + MockSyncStateManager mockSyncStateManager; + try { + EXPECT_CALL(mockSyncStateManager, GetSyncState()); + mockSyncStateManager.GetSyncState(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_007 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_007 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_008"; + MockSyncStateManager mockSyncStateManager; + try { + EXPECT_CALL(mockSyncStateManager, GetForceFlag()); + mockSyncStateManager.GetForceFlag(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_008 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_008 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_009"; + try { + SyncStateManager syncStateManager; + int32_t ret = (int32_t)syncStateManager.UpdateSyncState(SyncState::INIT); + EXPECT_EQ(ret, 0); + ret = (int32_t)syncStateManager.UpdateSyncState(SyncState::SYNCING); + EXPECT_EQ(ret, 0); + ret = (int32_t)syncStateManager.UpdateSyncState(SyncState::SYNC_FAILED); + EXPECT_EQ(ret, 0); + ret = (int32_t)syncStateManager.UpdateSyncState(SyncState::SYNC_SUCCEED); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_009 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_009 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_010"; + try { + SyncStateManager syncStateManager; + bool forceFlag = true; + SyncState syncState = syncStateManager.GetSyncState(); + EXPECT_EQ(static_cast(syncState), 0); + bool ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::APP_TRIGGER); + EXPECT_FALSE(ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_010 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_010 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_011"; + try { + SyncStateManager syncStateManager; + bool forceFlag = true; + + Action action = syncStateManager.UpdateSyncState(SyncState::SYNCING); + EXPECT_EQ(static_cast(action), static_cast(Action::STOP)); + SyncState syncState = syncStateManager.GetSyncState(); + EXPECT_EQ(static_cast(syncState), static_cast(SyncState::SYNCING)); + + bool ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::APP_TRIGGER); + EXPECT_TRUE(ret); + syncStateManager.SetCleaningFlag(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_011 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_011 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_012, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_012"; + try { + SyncStateManager syncStateManager; + bool forceFlag = false; + + Action action = syncStateManager.UpdateSyncState(SyncState::SYNCING); + EXPECT_EQ(static_cast(action), static_cast(Action::STOP)); + SyncState syncState = syncStateManager.GetSyncState(); + EXPECT_EQ(static_cast(syncState), static_cast(SyncState::SYNCING)); + + bool ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::TASK_TRIGGER); + EXPECT_TRUE(ret); + + ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::APP_TRIGGER); + EXPECT_TRUE(ret); + + forceFlag = true; + ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::APP_TRIGGER); + EXPECT_TRUE(ret); + syncStateManager.SetCleaningFlag(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_012 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_012 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_013, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_013"; + try { + SyncStateManager syncStateManager; + bool forceFlag = false; + + syncStateManager.SetCleaningFlag(); + EXPECT_TRUE(syncStateManager.CheckCleaningFlag()); + + bool ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::TASK_TRIGGER); + EXPECT_TRUE(ret); + + ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::APP_TRIGGER); + EXPECT_TRUE(ret); + + forceFlag = true; + ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::APP_TRIGGER); + EXPECT_TRUE(ret); + syncStateManager.SetCleaningFlag(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_013 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_013 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_014, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_014"; + try { + SyncStateManager syncStateManager; + bool forceFlag = false; + + syncStateManager.SetDisableCloudFlag(); + EXPECT_TRUE(syncStateManager.CheckDisableCloudFlag()); + + bool ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::TASK_TRIGGER); + EXPECT_TRUE(ret); + + ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::APP_TRIGGER); + EXPECT_TRUE(ret); + + forceFlag = true; + ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::APP_TRIGGER); + EXPECT_TRUE(ret); + syncStateManager.SetCleaningFlag(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_014 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_014 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_015, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_015"; + try { + SyncStateManager syncStateManager; + syncStateManager.SetCleaningFlag(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_015 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_015 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_016, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_016"; + try { + SyncStateManager syncStateManager; + EXPECT_FALSE(syncStateManager.GetStopSyncFlag()); + syncStateManager.SetStopSyncFlag(); + EXPECT_TRUE(syncStateManager.GetStopSyncFlag()); + + Action action = syncStateManager.UpdateSyncState(SyncState::INIT); + EXPECT_EQ(static_cast(action), static_cast(Action::STOP)); + EXPECT_FALSE(syncStateManager.GetStopSyncFlag()); + + SyncState syncState = syncStateManager.GetSyncState(); + EXPECT_EQ(static_cast(syncState), static_cast(SyncState::INIT)); + syncStateManager.SetStopSyncFlag(); + EXPECT_TRUE(syncStateManager.GetStopSyncFlag()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_016 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_016 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_017, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_017"; + try { + SyncStateManager syncStateManager; + syncStateManager.SetStopSyncFlag(); + EXPECT_TRUE(syncStateManager.GetStopSyncFlag()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_017 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_017 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_018, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_018"; + try { + SyncStateManager syncStateManager; + syncStateManager.SetDisableCloudFlag(); + EXPECT_TRUE(syncStateManager.CheckDisableCloudFlag()); + + syncStateManager.SetCleaningFlag(); + EXPECT_TRUE(syncStateManager.CheckCleaningFlag()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_018 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_018 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_019, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_019"; + try { + SyncStateManager syncStateManager; + SyncState syncState; + bool forceFlag = true; + EXPECT_FALSE(syncStateManager.GetForceFlag()); + + Action action = syncStateManager.ClearDisableCloudFlag(); + EXPECT_EQ(static_cast(action), static_cast(Action::STOP)); + EXPECT_TRUE(!syncStateManager.CheckDisableCloudFlag()); + + bool ret = syncStateManager.CheckAndSetPending(forceFlag, SyncTriggerType::TASK_TRIGGER); + syncState = syncStateManager.GetSyncState(); + EXPECT_EQ(static_cast(syncState), static_cast(SyncState::SYNCING)); + EXPECT_FALSE(ret); + EXPECT_TRUE(syncStateManager.GetForceFlag()); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_019 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_019 End"; +} + +HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_020, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SyncStateManagerTest_020"; + try { + SyncStateManager syncStateManager; + bool forceFlag = false; + syncStateManager.state_ = SyncState::SYNCING; + SyncTriggerType triggerType = SyncTriggerType::SYSTEM_LOAD_TRIGGER; + + syncStateManager.CheckAndSetPending(forceFlag, triggerType); + EXPECT_EQ(syncStateManager.nextAction_, Action::START); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SyncStateManagerTest_020 ERROR"; + } + GTEST_LOG_(INFO) << "SyncStateManagerTest_020 End"; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/task_state_manager_test.cpp b/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/task_state_manager_test.cpp new file mode 100644 index 0000000..0c20166 --- /dev/null +++ b/cloud_file/test/unittests/cloud_file_kit_inner/data_sync/task_state_manager_test.cpp @@ -0,0 +1,391 @@ +/* + * Copyright (c) 2024 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 "task_state_manager.h" +#include +#include + +#include "refbase.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MockTaskStateManager : public TaskStateManager { +public: + MOCK_METHOD0(GetInstance, TaskStateManager&()); + MOCK_METHOD0(DelayUnloadTask, void()); + MOCK_METHOD0(CancelUnloadTask, void()); + MOCK_METHOD0(StartTask, void()); + MOCK_METHOD2(StartTask, void(string bundleName, TaskType task)); + MOCK_METHOD2(CompleteTask, void(string bundleName, TaskType task)); + MOCK_METHOD2(HasTask, bool(string bundleName, TaskType task)); +}; + +class TaskStateManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void TaskStateManagerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void TaskStateManagerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void TaskStateManagerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void TaskStateManagerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_001 Start"; + try { + TaskStateManager::GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_001 Start ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_001 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_002 Start"; + try { + TaskStateManager::GetInstance().HasTask("testBundleName", TaskType::UPLOAD_ASSET_TASK); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_002 Start ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_002 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_003 Start"; + try { + TaskStateManager::GetInstance().HasTask("testBundleName", TaskType::DOWNLOAD_ASSET_TASK); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_003 Start ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_003 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_004 Start"; + try { + MockTaskStateManager mockTaskStateManager; + EXPECT_CALL(mockTaskStateManager, GetInstance()) + .WillOnce(ReturnRef(mockTaskStateManager)); + + mockTaskStateManager.GetInstance(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_004 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_004 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_005 Start"; + try { + MockTaskStateManager mockTaskStateManager; + EXPECT_CALL(mockTaskStateManager, DelayUnloadTask()); + mockTaskStateManager.DelayUnloadTask(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_005 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_005 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_006 Start"; + try { + MockTaskStateManager mockTaskStateManager; + EXPECT_CALL(mockTaskStateManager, CancelUnloadTask()); + mockTaskStateManager.CancelUnloadTask(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_006 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_006 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_007 Start"; + try { + MockTaskStateManager mockTaskStateManager; + EXPECT_CALL(mockTaskStateManager, StartTask()); + mockTaskStateManager.StartTask(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_007 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_007 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_008 Start"; + try { + MockTaskStateManager mockTaskStateManager; + string bundleName = "testbundleName"; + EXPECT_CALL(mockTaskStateManager, StartTask(bundleName, TaskType::SYNC_TASK)); + EXPECT_CALL(mockTaskStateManager, StartTask(bundleName, TaskType::DOWNLOAD_TASK)); + EXPECT_CALL(mockTaskStateManager, StartTask(bundleName, TaskType::UPLOAD_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, StartTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, StartTask(bundleName, TaskType::DOWNLOAD_REMOTE_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, StartTask(bundleName, TaskType::DOWNLOAD_THUMB_TASK)); + EXPECT_CALL(mockTaskStateManager, StartTask(bundleName, TaskType::DISABLE_CLOUD_TASK)); + + mockTaskStateManager.StartTask(bundleName, TaskType::SYNC_TASK); + mockTaskStateManager.StartTask(bundleName, TaskType::DOWNLOAD_TASK); + mockTaskStateManager.StartTask(bundleName, TaskType::UPLOAD_ASSET_TASK); + mockTaskStateManager.StartTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK); + mockTaskStateManager.StartTask(bundleName, TaskType::DOWNLOAD_REMOTE_ASSET_TASK); + mockTaskStateManager.StartTask(bundleName, TaskType::DOWNLOAD_THUMB_TASK); + mockTaskStateManager.StartTask(bundleName, TaskType::DISABLE_CLOUD_TASK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_008 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_008 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_009 Start"; + try { + MockTaskStateManager mockTaskStateManager; + string bundleName = "testbundleName"; + EXPECT_CALL(mockTaskStateManager, CompleteTask(bundleName, TaskType::SYNC_TASK)); + EXPECT_CALL(mockTaskStateManager, CompleteTask(bundleName, TaskType::DOWNLOAD_TASK)); + EXPECT_CALL(mockTaskStateManager, CompleteTask(bundleName, TaskType::UPLOAD_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, CompleteTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, CompleteTask(bundleName, TaskType::DOWNLOAD_REMOTE_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, CompleteTask(bundleName, TaskType::DOWNLOAD_THUMB_TASK)); + EXPECT_CALL(mockTaskStateManager, CompleteTask(bundleName, TaskType::DISABLE_CLOUD_TASK)); + + mockTaskStateManager.CompleteTask(bundleName, TaskType::SYNC_TASK); + mockTaskStateManager.CompleteTask(bundleName, TaskType::DOWNLOAD_TASK); + mockTaskStateManager.CompleteTask(bundleName, TaskType::UPLOAD_ASSET_TASK); + mockTaskStateManager.CompleteTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK); + mockTaskStateManager.CompleteTask(bundleName, TaskType::DOWNLOAD_REMOTE_ASSET_TASK); + mockTaskStateManager.CompleteTask(bundleName, TaskType::DOWNLOAD_THUMB_TASK); + mockTaskStateManager.CompleteTask(bundleName, TaskType::DISABLE_CLOUD_TASK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_009 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_009 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_010 Start"; + try { + MockTaskStateManager mockTaskStateManager; + string bundleName = "testbundleName"; + EXPECT_CALL(mockTaskStateManager, HasTask(bundleName, TaskType::SYNC_TASK)); + EXPECT_CALL(mockTaskStateManager, HasTask(bundleName, TaskType::DOWNLOAD_TASK)); + EXPECT_CALL(mockTaskStateManager, HasTask(bundleName, TaskType::UPLOAD_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, HasTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, HasTask(bundleName, TaskType::DOWNLOAD_REMOTE_ASSET_TASK)); + EXPECT_CALL(mockTaskStateManager, HasTask(bundleName, TaskType::DOWNLOAD_THUMB_TASK)); + EXPECT_CALL(mockTaskStateManager, HasTask(bundleName, TaskType::DISABLE_CLOUD_TASK)); + + mockTaskStateManager.HasTask(bundleName, TaskType::SYNC_TASK); + mockTaskStateManager.HasTask(bundleName, TaskType::DOWNLOAD_TASK); + mockTaskStateManager.HasTask(bundleName, TaskType::UPLOAD_ASSET_TASK); + mockTaskStateManager.HasTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK); + mockTaskStateManager.HasTask(bundleName, TaskType::DOWNLOAD_REMOTE_ASSET_TASK); + mockTaskStateManager.HasTask(bundleName, TaskType::DOWNLOAD_THUMB_TASK); + mockTaskStateManager.HasTask(bundleName, TaskType::DISABLE_CLOUD_TASK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_010 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_010 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_011 Start"; + try { + MockTaskStateManager mockTaskStateManager; + string bundleName = "testbundleName"; + EXPECT_CALL(mockTaskStateManager, HasTask(bundleName, TaskType::SYNC_TASK)) + .WillOnce(Return(true)) + .WillOnce(Return(false)); + + EXPECT_TRUE(mockTaskStateManager.HasTask(bundleName, TaskType::SYNC_TASK)); + EXPECT_FALSE(mockTaskStateManager.HasTask(bundleName, TaskType::SYNC_TASK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_011 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_011 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_012, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_012 Start"; + try { + TaskStateManager taskStateManager; + string bundleName = "testBundleName"; + taskStateManager.StartTask(); + taskStateManager.StartTask(bundleName, TaskType::SYNC_TASK); + taskStateManager.StartTask(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_012 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_012 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_013, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_013 Start"; + try { + TaskStateManager taskStateManager; + string bundleName = "testBundleName"; + taskStateManager.StartTask(bundleName, TaskType::SYNC_TASK); + taskStateManager.CompleteTask(bundleName, TaskType::SYNC_TASK); + taskStateManager.StartTask(); + taskStateManager.GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_013 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_013 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_014, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_014 Start"; + try { + TaskStateManager taskStateManager; + string bundleName = "testBundleName"; + taskStateManager.StartTask(bundleName, TaskType::SYNC_TASK); + taskStateManager.CompleteTask(bundleName, TaskType::SYNC_TASK); + taskStateManager.StartTask(); + taskStateManager.GetInstance(); + EXPECT_FALSE(taskStateManager.HasTask(bundleName, TaskType::SYNC_TASK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_014 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_014 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_015, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_015 Start"; + try { + TaskStateManager taskStateManager; + string bundleName = "testBundleName"; + taskStateManager.StartTask(bundleName, TaskType::SYNC_TASK); + EXPECT_TRUE(taskStateManager.HasTask(bundleName, TaskType::SYNC_TASK)); + taskStateManager.StartTask(bundleName, TaskType::DOWNLOAD_TASK); + EXPECT_TRUE(taskStateManager.HasTask(bundleName, TaskType::DOWNLOAD_TASK)); + + taskStateManager.StartTask(bundleName, TaskType::CLEAN_TASK); + EXPECT_TRUE(taskStateManager.HasTask(bundleName, TaskType::CLEAN_TASK)); + taskStateManager.StartTask(bundleName, TaskType::UPLOAD_ASSET_TASK); + EXPECT_TRUE(taskStateManager.HasTask(bundleName, TaskType::UPLOAD_ASSET_TASK)); + + taskStateManager.StartTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK); + EXPECT_TRUE(taskStateManager.HasTask(bundleName, TaskType::DOWNLOAD_ASSET_TASK)); + taskStateManager.StartTask(bundleName, TaskType::DOWNLOAD_REMOTE_ASSET_TASK); + EXPECT_TRUE(taskStateManager.HasTask(bundleName, TaskType::DOWNLOAD_REMOTE_ASSET_TASK)); + + taskStateManager.StartTask(bundleName, TaskType::DOWNLOAD_THUMB_TASK); + EXPECT_TRUE(taskStateManager.HasTask(bundleName, TaskType::DOWNLOAD_THUMB_TASK)); + taskStateManager.StartTask(bundleName, TaskType::DISABLE_CLOUD_TASK); + EXPECT_TRUE(taskStateManager.HasTask(bundleName, TaskType::DISABLE_CLOUD_TASK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_015 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_015 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_016, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_016 Start"; + try { + TaskStateManager taskStateManager; + string bundleName = "testBundleName"; + + taskStateManager.StartTask(); + EXPECT_FALSE(taskStateManager.HasTask(bundleName, TaskType::SYNC_TASK)); + + taskStateManager.StartTask(bundleName, TaskType::SYNC_TASK); + taskStateManager.CompleteTask(bundleName, TaskType::SYNC_TASK); + EXPECT_FALSE(taskStateManager.HasTask(bundleName, TaskType::SYNC_TASK)); + + taskStateManager.StartTask(); + taskStateManager.GetInstance(); + EXPECT_FALSE(taskStateManager.HasTask(bundleName, TaskType::SYNC_TASK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_016 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_016 End"; +} + +HWTEST_F(TaskStateManagerTest, TaskStateManagerTest_017, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TaskStateManagerTest_017 Start"; + try { + TaskStateManager taskStateManager; + string bundleName = "testBundleName"; + TaskType task = TaskType::SYNC_TASK; + + taskStateManager.CompleteTask(bundleName, task); + auto ret = taskStateManager.taskMaps_.find(bundleName); + EXPECT_EQ(ret, taskStateManager.taskMaps_.end()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TaskStateManagerTest_017 ERROR"; + } + GTEST_LOG_(INFO) << "TaskStateManagerTest_017 End"; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/BUILD.gn b/cloud_file/test/unittests/clouddisk_database/BUILD.gn new file mode 100644 index 0000000..d572dec --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/BUILD.gn @@ -0,0 +1,546 @@ +# Copyright (C) 2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("clouddisk_rdb_utils_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdb_transaction.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdb_utils.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdbstore.cpp", + "${cloud_file_path}/services/clouddisk_database/src/file_column.cpp", + "clouddisk_rdb_utils_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/services/clouddisk_database/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/test/unittests/cloud_disk_database/include", + "include", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${cloud_file_path}/utils/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "e2fsprogs:libext2_uuid", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "power_manager:powermgr_client", + "preferences:native_preferences", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DISK_DATABASE_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("clouddisk_rdbstore_test") { + branch_protector_ret = "pac_ret" + public_configs = + [ "${services_path}/cloudsyncservice:cloud_sync_service_public_config" ] + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_stub.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_stub.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_callback_stub.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/mock/clouddisk_notify_utils_mock.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/mock/clouddisk_rdb_transaction_mock.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/mock/meta_file_clouddisk_mock.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/mock/rdb_mock.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/mock/transaction_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.cpp", + "clouddisk_rdbstore_test.cpp", + ] + + clouddisk_database = [ + "${services_path}/clouddisk_database/src/clouddisk_rdb_utils.cpp", + "${services_path}/clouddisk_database/src/clouddisk_rdbstore.cpp", + "${services_path}/clouddisk_database/src/file_column.cpp", + "${services_path}/clouddisk_database/src/clouddisk_sync_helper.cpp", + "${services_path}/clouddisk_database/src/clouddisk_notify.cpp", + ] + + sources += clouddisk_database + + include_dirs = [ + "${services_path}/clouddisk_database/include", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudfiledaemon/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${utils_path}/log/include", + "${cloud_file_path}/test/unittests/clouddisk_database/include", + "${cloud_file_path}/test/unittests/clouddisk_database/mock", + "${services_path}/cloudfiledaemon/include/cloud_disk", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloud_sync_service_proxy", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "e2fsprogs:libext2_uuid", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "preferences:native_preferences", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004310", + "LOG_TAG=\"CLOUDDISK_DATABASE_TEST\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + + use_exceptions = true +} + +ohos_unittest("clouddisk_notify_test") { + branch_protector_ret = "pac_ret" + public_configs = + [ "${services_path}/cloudsyncservice:cloud_sync_service_public_config" ] + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_notify.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdb_utils.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_sync_helper.cpp", + "${cloud_file_path}/services/clouddisk_database/src/file_column.cpp", + "${cloud_file_path}/test/unittests/cloud_disk/mock/clouddisk_rdbstore_mock.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/mock/clouddisk_notify_utils_mock.cpp", + "clouddisk_notify_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/services/clouddisk_database/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/test/unittests/cloud_disk_database/include", + "include", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${cloud_file_path}/utils/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloud_sync_service_proxy", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "e2fsprogs:libext2_uuid", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "power_manager:powermgr_client", + "preferences:native_preferences", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DISK_DATABASE_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("clouddisk_rdb_transaction_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdb_transaction.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdb_utils.cpp", + "${cloud_file_path}/services/clouddisk_database/src/file_column.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/include/clouddisk_rdbstore_mock.h", + "clouddisk_rdb_transaction_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/services/clouddisk_database/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/test/unittests/cloud_disk_database/include", + "include", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${cloud_file_path}/utils/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "e2fsprogs:libext2_uuid", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "power_manager:powermgr_client", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DISK_DATABASE_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("clouddisk_sync_helper_test") { + module_out_path = "cloud_file/cloud_file" + public_configs = + [ "${services_path}/cloudsyncservice:cloud_sync_service_public_config" ] + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdb_transaction.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdb_utils.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_sync_helper.cpp", + "${cloud_file_path}/services/clouddisk_database/src/file_column.cpp", + "${cloud_file_path}/test/unittests/clouddisk_database/include/clouddisk_rdbstore_mock.h", + "clouddisk_sync_helper_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/services/clouddisk_database/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/test/unittests/cloud_disk_database/include", + "include", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${cloud_file_path}/utils/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloud_sync_service_proxy", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "e2fsprogs:libext2_uuid", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "power_manager:powermgr_client", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DISK_DATABASE_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("clouddisk_notify_utils_test") { + branch_protector_ret = "pac_ret" + public_configs = + [ "${services_path}/cloudsyncservice:cloud_sync_service_public_config" ] + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/service_proxy.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_impl_lite.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src/cloud_sync_manager_lite.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_notify.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_notify_utils.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdb_utils.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_rdbstore.cpp", + "${cloud_file_path}/services/clouddisk_database/src/clouddisk_sync_helper.cpp", + "${cloud_file_path}/services/clouddisk_database/src/file_column.cpp", + "clouddisk_notify_utils_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/services/clouddisk_database/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/test/unittests/cloud_disk_database/include", + "include", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${cloud_file_path}/utils/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloud_sync_service_proxy", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + cflags = [ "--coverage" ] + + ldflags = [ "--coverage" ] + + cflags_cc = [ "--coverage" ] + + external_deps = [ + "e2fsprogs:libext2_uuid", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "power_manager:powermgr_client", + "preferences:native_preferences", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CLOUD_DISK_DATABASE_TEST\"", + ] + + use_exceptions = true +} + +group("clouddisk_database_test") { + testonly = true + deps = [ + ":clouddisk_notify_test", + ":clouddisk_notify_utils_test", + ":clouddisk_rdb_transaction_test", + ":clouddisk_rdb_utils_test", + ":clouddisk_rdbstore_test", + ":clouddisk_sync_helper_test", + ] +} diff --git a/cloud_file/test/unittests/clouddisk_database/clouddisk_notify_test.cpp b/cloud_file/test/unittests/clouddisk_database/clouddisk_notify_test.cpp new file mode 100644 index 0000000..47776c0 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/clouddisk_notify_test.cpp @@ -0,0 +1,933 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "clouddisk_notify.h" +#include "clouddisk_notify_utils.h" +#include "clouddisk_rdbstore.h" +#include "dfs_error.h" +#include "ffrt_inner.h" +#include "file_column.h" +#include "securec.h" +#include "uri.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudDisk { +namespace Test { +using namespace testing::ext; +using namespace std; + +class CloudDiskNotifyTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudDiskNotifyTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudDiskNotifyTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudDiskNotifyTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudDiskNotifyTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: TryNotifyTest001 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.inoPtr = nullptr; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_SETATTR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest002 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 10; + paramDisk.opsType = NotifyOpsType::DAEMON_SETATTR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest003 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.inoPtr = nullptr; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_SETXATTR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest004 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 10; + paramDisk.opsType = NotifyOpsType::DAEMON_SETXATTR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest005 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.inoPtr = nullptr; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 10; + paramDisk.opsType = NotifyOpsType::DAEMON_RECYCLE; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest006 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + ino->bundleName = ""; + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 0; + paramDisk.opsType = NotifyOpsType::DAEMON_RECYCLE; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest007 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + ino->bundleName = "com.ohos.photos"; + ino->cloudId = "mock"; + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_RECYCLE; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest008 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + ino->bundleName = "com.ohos.photos"; + ino->cloudId = "rootId"; + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 10; + paramDisk.opsType = NotifyOpsType::DAEMON_RECYCLE; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest009 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + ino->bundleName = "com.ohos.photos"; + ino->cloudId = "rootId"; + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_RECYCLE; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest010 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + ino->bundleName = "com.ohos.photos"; + ino->cloudId = "rootId"; + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_RESTORE; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest011 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.name = ""; + paramDisk.opsType = NotifyOpsType::DAEMON_MKDIR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest012 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest012, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.name = "test"; + paramDisk.inoPtr = nullptr; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 10; + paramDisk.opsType = NotifyOpsType::DAEMON_MKDIR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest013 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest013, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.name = "test"; + shared_ptr ino = make_shared(); + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_MKDIR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest014 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest014, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.name = ""; + paramDisk.opsType = NotifyOpsType::DAEMON_RMDIR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest015 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest015, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.name = "test"; + paramDisk.inoPtr = nullptr; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 10; + paramDisk.opsType = NotifyOpsType::DAEMON_RMDIR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest016 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest016, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.name = "test"; + shared_ptr ino = make_shared(); + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_RMDIR; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest017 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest017, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.name = "test"; + shared_ptr ino = make_shared(); + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_UNLINK; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest018 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest018, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 10; + paramDisk.opsType = NotifyOpsType::DAEMON_RENAME; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest019 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest019, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.newName = "mock"; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_RENAME; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest020 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest020, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + paramDisk.newName = "test"; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_RENAME; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest021 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest021, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 10; + paramDisk.opsType = NotifyOpsType::DAEMON_WRITE; + ParamDiskOthers paramOthers; + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest022 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest022, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_WRITE; + ParamDiskOthers paramOthers; + paramOthers.dirtyType = static_cast(DirtyType::TYPE_NO_NEED_UPLOAD); + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest023 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest023, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + shared_ptr ino = make_shared(); + paramDisk.inoPtr = ino; + paramDisk.data = new CloudDiskFuseData(); + paramDisk.data->userId = 100; + paramDisk.opsType = NotifyOpsType::DAEMON_WRITE; + ParamDiskOthers paramOthers; + paramOthers.dirtyType = static_cast(DirtyType::TYPE_NEW); + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + delete paramDisk.data; + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyTest024 + * @tc.desc: Verify the TryNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyTest024, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamDisk paramDisk; + ParamDiskOthers paramOthers; + paramOthers.dirtyType = static_cast(DirtyType::TYPE_NEW); + CloudDiskNotify.TryNotify(paramDisk, paramOthers); + GTEST_LOG_(INFO) << "TryNotify End"; +} + +/** + * @tc.name: TryNotifyServiceTest001 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.node.isRecycled = true; + paramService.cloudId = "mock"; + paramService.opsType = NotifyOpsType::SERVICE_INSERT; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest002 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.node.isRecycled = true; + paramService.cloudId = "rootId"; + paramService.opsType = NotifyOpsType::SERVICE_INSERT; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest003 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.node.isRecycled = false; + paramService.node.cloudId = "mock"; + paramService.opsType = NotifyOpsType::SERVICE_INSERT; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest004 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "mock"; + paramService.opsType = NotifyOpsType::SERVICE_UPDATE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest005 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "rootId"; + paramService.node.fileName = "mock"; + paramService.opsType = NotifyOpsType::SERVICE_UPDATE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest006 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "rootId"; + paramService.opsType = NotifyOpsType::SERVICE_UPDATE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest007 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "mock"; + paramService.opsType = NotifyOpsType::SERVICE_UPDATE_RECYCLE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest008 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "rootId"; + paramService.node.cloudId = "mock"; + paramService.opsType = NotifyOpsType::SERVICE_UPDATE_RECYCLE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest009 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "rootId"; + paramService.node.cloudId = "rootId"; + paramService.node.isRecycled = false; + paramService.opsType = NotifyOpsType::SERVICE_UPDATE_RECYCLE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest010 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "rootId"; + paramService.node.cloudId = "rootId"; + paramService.node.isRecycled = true; + paramService.opsType = NotifyOpsType::SERVICE_UPDATE_RECYCLE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest011 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = ""; + paramService.opsType = NotifyOpsType::SERVICE_DELETE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest012 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest012, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "rootId"; + paramService.opsType = NotifyOpsType::SERVICE_DELETE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest013 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest013, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.cloudId = "rootId"; + paramService.opsType = NotifyOpsType::SERVICE_DELETE_BATCH; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: TryNotifyServiceTest014 + * @tc.desc: Verify the TryNotifyService function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, TryNotifyServiceTest014, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TryNotifyService Start"; + CloudDiskNotify CloudDiskNotify; + NotifyParamService paramService; + paramService.opsType = NotifyOpsType::OPS_NONE; + ParamServiceOther paramOthers; + CloudDiskNotify.TryNotifyService(paramService, paramOthers); + GTEST_LOG_(INFO) << "TryNotifyService End"; +} + +/** + * @tc.name: GetDeleteNotifyDataTest001 + * @tc.desc: Verify the GetDeleteNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, GetDeleteNotifyDataTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetDeleteNotifyData Start"; + CloudDiskNotify CloudDiskNotify; + vector deleteIds; + NativeRdb::ValueObject mock0; + NativeRdb::ValueObject mock1; + deleteIds.push_back(mock0); + deleteIds.push_back(mock1); + vector notifyDataList; + ParamServiceOther paramOthers; + paramOthers.bundleName = "com.ohos.photos"; + paramOthers.userId = 100; + int32_t ret = CloudDiskNotify.GetDeleteNotifyData(deleteIds, notifyDataList, paramOthers); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "GetDeleteNotifyData End"; +} + +/** + * @tc.name: AddNotifyTest001 + * @tc.desc: Verify the AddNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, AddNotifyTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AddNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyData notifyData; + notifyData.type == NotifyType::NOTIFY_NONE; + CloudDiskNotify.AddNotify(notifyData); + GTEST_LOG_(INFO) << "AddNotify End"; +} + +/** + * @tc.name: AddNotifyTest002 + * @tc.desc: Verify the AddNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, AddNotifyTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AddNotify Start"; + CloudDiskNotify CloudDiskNotify; + NotifyData notifyData; + notifyData.type == NotifyType::NOTIFY_ADDED; + CloudDiskNotify.AddNotify(notifyData); + GTEST_LOG_(INFO) << "AddNotify End"; +} + +/** + * @tc.name: NotifyChangeOuterTest001 + * @tc.desc: Verify the AddNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, NotifyChangeOuterTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyChangeOuter Start"; + CloudDiskNotify CloudDiskNotify; + CloudDiskNotify.NotifyChangeOuter(); + GTEST_LOG_(INFO) << "NotifyChangeOuter End"; +} + +/** + * @tc.name: NotifyChangeOuterTest002 + * @tc.desc: Verify the AddNotify function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyTest, NotifyChangeOuterTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyChangeOuter Start"; + CacheNotifyInfo nf; + CloudDiskNotify CloudDiskNotify; + CloudDiskNotify.nfList_.push_back(nf); + CloudDiskNotify.NotifyChangeOuter(); + GTEST_LOG_(INFO) << "NotifyChangeOuter End"; +} +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/clouddisk_notify_utils_test.cpp b/cloud_file/test/unittests/clouddisk_database/clouddisk_notify_utils_test.cpp new file mode 100644 index 0000000..6167130 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/clouddisk_notify_utils_test.cpp @@ -0,0 +1,500 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "clouddisk_notify_utils.h" +#include "clouddisk_rdb_utils.h" +#include "file_column.h" +#include "cloud_pref_impl.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudDisk { +namespace Test { +using namespace testing::ext; +using namespace std; +const int32_t MOCKUSERID = 0; +const int32_t MOCK1 = 1; +const int32_t MOCK2 = 2; +const int32_t MOCK3 = 3; + +std::shared_ptr MockFunc(CloudDiskFuseData* data, int64_t inode) +{ + if (data->userId == MOCKUSERID) { + return nullptr; + } + std::shared_ptr inoPtr = make_shared(); + if (data->userId == MOCK1) { + inoPtr->parent = FUSE_ROOT_ID; + } + if (data->userId == MOCK2) { + inoPtr->parent = 0; + inoPtr->fileName = ""; + } + if (data->userId == MOCK3) { + inoPtr->fileName = "MOCK3"; + } + return inoPtr; +} + +class CloudDiskNotifyUtilsTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudDiskNotifyUtilsTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudDiskNotifyUtilsTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudDiskNotifyUtilsTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudDiskNotifyUtilsTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: GetNotifyDataTest001 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + FindCloudDiskInodeFunc func = MockFunc; + fuse_ino_t ino = FUSE_ROOT_ID; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, ino, notifyData); + EXPECT_EQ(ret, E_INVAL_ARG); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest002 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + data->userId = MOCKUSERID; + FindCloudDiskInodeFunc func = MockFunc; + fuse_ino_t ino = 0; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, ino, notifyData); + EXPECT_EQ(ret, E_INVAL_ARG); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest003 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + data->userId = MOCK1; + FindCloudDiskInodeFunc func = MockFunc; + fuse_ino_t ino = 0; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, ino, notifyData); + EXPECT_EQ(ret, E_OK); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest004 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + data->userId = MOCK2; + FindCloudDiskInodeFunc func = MockFunc; + fuse_ino_t ino = 0; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, ino, notifyData); + EXPECT_EQ(ret, E_OK); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest005 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + data->userId = MOCKUSERID; + FindCloudDiskInodeFunc func = MockFunc; + fuse_ino_t parent = 0; + string name = "test"; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, parent, name, notifyData); + EXPECT_EQ(ret, E_INVAL_ARG); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest006 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + data->userId = MOCK2; + FindCloudDiskInodeFunc func = MockFunc; + fuse_ino_t parent = 0; + string name = "test"; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, parent, name, notifyData); + EXPECT_EQ(ret, E_OK); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest01 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest01, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + data->userId = MOCK3; + FindCloudDiskInodeFunc func = MockFunc; + fuse_ino_t parent = 0; + string name = "test"; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, parent, name, notifyData); + EXPECT_EQ(ret, E_INVAL_ARG); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest007 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + FindCloudDiskInodeFunc func = MockFunc; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, nullptr, notifyData); + EXPECT_EQ(ret, E_INVAL_ARG); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest008 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + FindCloudDiskInodeFunc func = MockFunc; + shared_ptr inoPtr = make_shared(); + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, inoPtr, notifyData); + EXPECT_EQ(ret, E_OK); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest009 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + FindCloudDiskInodeFunc func = MockFunc; + string name = "test"; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, nullptr, name, notifyData); + EXPECT_EQ(ret, E_INVAL_ARG); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest010 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + FindCloudDiskInodeFunc func = MockFunc; + shared_ptr pInoPtr = make_shared(); + pInoPtr->fileName = "test"; + string name = "test"; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, pInoPtr, name, notifyData); + EXPECT_EQ(ret, E_OK); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetNotifyDataTest011 + * @tc.desc: Verify the GetNotifyData function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetNotifyDataTest011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNotifyData Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + CloudDiskFuseData* data = new CloudDiskFuseData(); + FindCloudDiskInodeFunc func = MockFunc; + shared_ptr pInoPtr = make_shared(); + pInoPtr->fileName = ""; + string name = "test"; + NotifyData notifyData; + int ret = CloudDiskNotifyUtils.GetNotifyData(data, func, pInoPtr, name, notifyData); + EXPECT_EQ(ret, E_OK); + delete data; + GTEST_LOG_(INFO) << "GetNotifyData End"; +} + +/** + * @tc.name: GetCacheNodeTest001 + * @tc.desc: Verify the GetCacheNode function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetCacheNodeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCacheNode Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + string cloudId = "100"; + CacheNode cacheNode; + int ret = CloudDiskNotifyUtils.GetCacheNode(cloudId, cacheNode); + EXPECT_EQ(ret, E_INVAL_ARG); + GTEST_LOG_(INFO) << "GetCacheNode End"; +} + +/** + * @tc.name: GetCacheNodeTest002 + * @tc.desc: Verify the GetCacheNode function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetCacheNodeTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCacheNode Start"; + CacheNode cacheNode; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + auto iter = (CloudDiskNotifyUtils.cacheList_) + .insert(CloudDiskNotifyUtils.cacheList_.end(), std::make_pair("key", cacheNode)); + (CloudDiskNotifyUtils.cacheMap_).insert(std::make_pair("key", iter)); + string cloudId = "key"; + + int ret = CloudDiskNotifyUtils.GetCacheNode(cloudId, cacheNode); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "GetCacheNode End"; +} + +/** + * @tc.name: PutCacheNodeTest001 + * @tc.desc: Verify the PutCacheNode function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, PutCacheNodeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCacheNode Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + string cloudId = "100"; + CacheNode cacheNode; + cacheNode.isDir = ""; + CloudDiskNotifyUtils.PutCacheNode(cloudId, cacheNode); + GTEST_LOG_(INFO) << "PutCacheNode End"; +} + +/** + * @tc.name: PutCacheNodeTest002 + * @tc.desc: Verify the PutCacheNode function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, PutCacheNodeTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCacheNode Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + string cloudId = "100"; + CacheNode cacheNode; + cacheNode.isDir = "directory"; + CloudDiskNotifyUtils.PutCacheNode(cloudId, cacheNode); + GTEST_LOG_(INFO) << "PutCacheNode End"; +} + +/** + * @tc.name: PutCacheNodeTest003 + * @tc.desc: Verify the PutCacheNode function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, PutCacheNodeTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCacheNode Start"; + CacheNode cacheNode; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + auto iter = (CloudDiskNotifyUtils.cacheList_) + .insert(CloudDiskNotifyUtils.cacheList_.end(), std::make_pair("key", cacheNode)); + (CloudDiskNotifyUtils.cacheMap_).insert(std::make_pair("key", iter)); + string cloudId = "key"; + cacheNode.isDir = TYPE_DIR_STR; + + CloudDiskNotifyUtils.PutCacheNode(cloudId, cacheNode); + auto res = CloudDiskNotifyUtils.cacheMap_.find("key"); + EXPECT_EQ(cloudId, res->first); + GTEST_LOG_(INFO) << "PutCacheNode End"; +} + +/** + * @tc.name: PutCacheNodeTest004 + * @tc.desc: Verify the PutCacheNode function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, PutCacheNodeTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PutCacheNode Start"; + CacheNode cacheNode; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + for (int i = 0; i < CloudDiskNotifyUtils::maxCacheCnt_ - 2; ++i) { + std::stringstream ss; + ss << i; + string str = ss.str(); + auto iter = (CloudDiskNotifyUtils.cacheList_) + .insert(CloudDiskNotifyUtils.cacheList_.end(), std::make_pair(str, cacheNode)); + (CloudDiskNotifyUtils.cacheMap_).insert(std::make_pair(str, iter)); + } + string cloudId = "key"; + cacheNode.isDir = TYPE_DIR_STR; + + CloudDiskNotifyUtils.PutCacheNode(cloudId, cacheNode); + EXPECT_EQ(CloudDiskNotifyUtils.cacheMap_.size(), CloudDiskNotifyUtils::maxCacheCnt_); + GTEST_LOG_(INFO) << "PutCacheNode End"; +} + +/** + * @tc.name: GetUriFromCacheTest001 + * @tc.desc: Verify the GetUriFromCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetUriFromCacheTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetUriFromCache Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + string bundleName = "com.ohos.photos"; + string rootId = "rootId"; + CacheNode cacheNode; + cacheNode.isDir = ""; + cacheNode.cloudId = ""; + string uri = ""; + int ret = CloudDiskNotifyUtils.GetUriFromCache(bundleName, rootId, cacheNode, uri); + EXPECT_EQ(ret, E_INVAL_ARG); + GTEST_LOG_(INFO) << "GetUriFromCache End"; +} + +/** + * @tc.name: GetUriFromCacheTest002 + * @tc.desc: Verify the GetUriFromCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskNotifyUtilsTest, GetUriFromCacheTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetUriFromCache Start"; + CloudDiskNotifyUtils CloudDiskNotifyUtils; + string bundleName = "com.ohos.photos"; + string rootId = "same"; + CacheNode cacheNode; + cacheNode.isDir = ""; + cacheNode.parentCloudId = "same"; + string uri = ""; + int ret = CloudDiskNotifyUtils.GetUriFromCache(bundleName, rootId, cacheNode, uri); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "GetUriFromCache End"; +} +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/clouddisk_rdb_transaction_test.cpp b/cloud_file/test/unittests/clouddisk_database/clouddisk_rdb_transaction_test.cpp new file mode 100644 index 0000000..86ec39e --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/clouddisk_rdb_transaction_test.cpp @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "clouddisk_rdb_transaction.h" +#include "clouddisk_rdbstore_mock.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudDisk { +namespace Test { +using namespace testing::ext; +using namespace std; + +constexpr int32_t E_HAS_DB_ERROR = -222; +constexpr int32_t E_OK = 0; + +class CloudDiskRdbTransactionTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudDiskRdbTransactionTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudDiskRdbTransactionTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudDiskRdbTransactionTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudDiskRdbTransactionTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: StartTest001 + * @tc.desc: Verify the Start function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, StartTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Start Start"; + auto rdb = nullptr; + auto transaction = make_shared(rdb); + auto ret = transaction->Start(); + EXPECT_EQ(ret.first, E_HAS_DB_ERROR); + GTEST_LOG_(INFO) << "Start End"; +} + +/** + * @tc.name: StartTest003 + * @tc.desc: Verify the Start function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, StartTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Start Start"; + auto rdb = std::make_shared(); + auto transaction = make_shared(rdb); + transaction->transaction_ = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)) + .WillRepeatedly(Return(make_pair(NativeRdb::E_OK, transaction->transaction_))); + + auto ret = transaction->Start(); + EXPECT_EQ(ret.first, E_OK); + GTEST_LOG_(INFO) << "Start End"; +} + +/** + * @tc.name: FinishTest001 + * @tc.desc: Verify the Finish function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, FinishTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Finish Start"; + auto rdb = nullptr; + auto transaction = make_shared(rdb); + transaction->Finish(); + GTEST_LOG_(INFO) << "Finish End"; +} + +/** + * @tc.name: FinishTest002 + * @tc.desc: Verify the Finish function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, FinishTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Finish Start"; + auto rdb = std::make_shared(); + auto transaction = make_shared(rdb); + transaction->Finish(); + GTEST_LOG_(INFO) << "Finish End"; +} + +/** + * @tc.name: FinishTest003 + * @tc.desc: Verify the Finish function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, FinishTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Finish Start"; + auto rdb = std::make_shared(); + auto transaction = make_shared(rdb); + transaction->isStart = true; + transaction->transaction_ = std::make_shared(); + + transaction->Finish(); + EXPECT_EQ(transaction->isStart, false); + GTEST_LOG_(INFO) << "Finish End"; +} + +/** + * @tc.name: FinishTest004 + * @tc.desc: Verify the Finish function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, FinishTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Finish Start"; + auto transaction = make_shared(nullptr); + transaction->isStart = true; + transaction->transaction_ = nullptr; + + transaction->Finish(); + EXPECT_EQ(transaction->isFinish, false); + GTEST_LOG_(INFO) << "Finish End"; +} + +/** + * @tc.name: BeginTransactionTest001 + * @tc.desc: Verify the BeginTransaction function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, BeginTransactionTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BeginTransaction Start"; + auto rdb = nullptr; + auto transaction = make_shared(rdb); + int32_t ret = transaction->BeginTransaction(NativeRdb::Transaction::EXCLUSIVE); + EXPECT_EQ(ret, E_HAS_DB_ERROR); + GTEST_LOG_(INFO) << "BeginTransaction End"; +} + +/** + * @tc.name: BeginTransactionTest003 + * @tc.desc: Verify the BeginTransaction function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, BeginTransactionTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BeginTransaction Start"; + auto rdb = std::make_shared(); + auto transaction = make_shared(rdb); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillRepeatedly(Return(make_pair(NativeRdb::E_SQLITE_CONSTRAINT, nullptr))); + + int32_t ret = transaction->BeginTransaction(NativeRdb::Transaction::EXCLUSIVE); + EXPECT_EQ(ret, E_SQLITE_CONSTRAINT); + GTEST_LOG_(INFO) << "BeginTransaction End"; +} + +/** + * @tc.name: BeginTransactionTest004 + * @tc.desc: Verify the BeginTransaction function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, BeginTransactionTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BeginTransaction Start"; + auto rdb = std::make_shared(); + auto transaction = make_shared(rdb); + transaction->transaction_ = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)) + .WillRepeatedly(Return(make_pair(NativeRdb::E_OK, transaction->transaction_))); + + int32_t ret = transaction->BeginTransaction(NativeRdb::Transaction::EXCLUSIVE); + EXPECT_EQ(ret, NativeRdb::E_OK); + GTEST_LOG_(INFO) << "BeginTransaction End"; +} + +/** + * @tc.name: TransactionCommitTest001 + * @tc.desc: Verify the TransactionCommit function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, TransactionCommitTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransactionCommit Start"; + auto rdb = nullptr; + auto transaction = make_shared(rdb); + int32_t ret = transaction->TransactionCommit(); + EXPECT_EQ(ret, E_HAS_DB_ERROR); + GTEST_LOG_(INFO) << "TransactionCommit End"; +} + +/** + * @tc.name: TransactionCommitTest002 + * @tc.desc: Verify the TransactionCommit function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, TransactionCommitTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransactionCommit Start"; + auto rdb = std::make_shared(); + auto transaction = make_shared(rdb); + int32_t ret = transaction->TransactionCommit(); + EXPECT_EQ(ret, E_HAS_DB_ERROR); + GTEST_LOG_(INFO) << "TransactionCommit End"; +} + +/** + * @tc.name: TransactionCommitTest003 + * @tc.desc: Verify the TransactionCommit function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, TransactionCommitTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransactionCommit Start"; + auto rdb = std::make_shared(); + auto transaction = make_shared(rdb); + auto tr = std::make_shared(); + transaction->transaction_ = tr; + EXPECT_CALL(*tr, Commit()).WillRepeatedly(Return(NativeRdb::E_BASE)); + + int32_t ret = transaction->TransactionCommit(); + EXPECT_EQ(ret, E_HAS_DB_ERROR); + GTEST_LOG_(INFO) << "TransactionCommit End"; +} + +/** + * @tc.name: TransactionRollbackTest001 + * @tc.desc: Verify the TransactionRollback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, TransactionRollbackTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransactionRollback Start"; + auto rdb = nullptr; + auto transaction = make_shared(rdb); + int32_t ret = transaction->TransactionRollback(); + EXPECT_EQ(ret, E_HAS_DB_ERROR); + GTEST_LOG_(INFO) << "TransactionRollback End"; +} + +/** + * @tc.name: TransactionRollbackTest002 + * @tc.desc: Verify the TransactionRollback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbTransactionTest, TransactionRollbackTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransactionRollback Start"; + auto rdb = std::make_shared(); + auto transaction = make_shared(rdb); + int32_t ret = transaction->TransactionRollback(); + EXPECT_EQ(ret, E_HAS_DB_ERROR); + GTEST_LOG_(INFO) << "TransactionRollback End"; +} +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/clouddisk_rdb_utils_test.cpp b/cloud_file/test/unittests/clouddisk_database/clouddisk_rdb_utils_test.cpp new file mode 100644 index 0000000..f9b11f6 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/clouddisk_rdb_utils_test.cpp @@ -0,0 +1,540 @@ +/* + * 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 +#include + +#include "clouddisk_rdb_utils.h" +#include "dfs_error.h" +#include "result_set_mock.h" +#include "file_column.h" + +namespace OHOS { +namespace FileManagement::CloudDisk { +namespace Test { +using namespace testing::ext; +using namespace std; + +class CloudDiskRdbUtilsTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudDiskRdbUtilsTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudDiskRdbUtilsTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudDiskRdbUtilsTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudDiskRdbUtilsTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: GetIntTest001 + * @tc.desc: Verify the GetInt function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetIntTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInt Start"; + const string key = FileColumn::IS_DIRECTORY; + int32_t value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetInt(_, _)).WillOnce(Return(E_OK)); + int32_t ret = CloudDiskRdbUtils::GetInt(key, value, resultSet); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "GetInt End"; +} + +/** + * @tc.name: GetIntTest002 + * @tc.desc: Verify the GetInt function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetIntTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInt Start"; + try { + const string key = ""; + int32_t value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetInt(_, _)).WillOnce(Return(E_OK)); + int32_t ret = CloudDiskRdbUtils::GetInt(key, value, std::move(resultSet)); + EXPECT_EQ(ret, E_OK); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetInt ERROR"; + } + GTEST_LOG_(INFO) << "GetInt End"; +} + +/** + * @tc.name: GetIntTest003 + * @tc.desc: Verify the GetInt function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetIntTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInt Start"; + try { + const string key = FileColumn::IS_DIRECTORY; + int32_t value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::GetInt(key, value, std::move(resultSet)); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetInt ERROR"; + } + GTEST_LOG_(INFO) << "GetInt End"; +} + +/** + * @tc.name: GetIntTest004 + * @tc.desc: Verify the GetInt function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetIntTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInt Start"; + try { + const string key = FileColumn::IS_DIRECTORY; + int32_t value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetInt(_, _)).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::GetInt(key, value, std::move(resultSet)); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetInt ERROR"; + } + GTEST_LOG_(INFO) << "GetInt End"; +} + +/** + * @tc.name: GetIntTest005 + * @tc.desc: Verify the GetInt function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetIntTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInt Start"; + try { + const string key = FileColumn::IS_DIRECTORY; + int32_t value; + int32_t ret = CloudDiskRdbUtils::GetInt(key, value, nullptr); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetInt ERROR"; + } + GTEST_LOG_(INFO) << "GetInt End"; +} + +/** + * @tc.name: GetLongTest001 + * @tc.desc: Verify the GetLong function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetLongTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLong Start"; + const string key = FileColumn::FILE_SIZE; + int64_t value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetLong(_, _)).WillOnce(Return(E_OK)); + int32_t ret = CloudDiskRdbUtils::GetLong(key, value, std::move(resultSet)); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "GetLong End"; +} + +/** + * @tc.name: GetLongTest002 + * @tc.desc: Verify the GetLong function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetLongTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLong Start"; + try { + const string key = ""; + int64_t value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetLong(_, _)).WillOnce(Return(E_OK)); + int32_t ret = CloudDiskRdbUtils::GetLong(key, value, std::move(resultSet)); + EXPECT_EQ(ret, E_OK); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetLong ERROR"; + } + GTEST_LOG_(INFO) << "GetLong End"; +} + +/** + * @tc.name: GetLongTest003 + * @tc.desc: Verify the GetLong function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetLongTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLong Start"; + try { + const string key = FileColumn::FILE_SIZE; + int64_t value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::GetLong(key, value, resultSet); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetLong ERROR"; + } + GTEST_LOG_(INFO) << "GetLong End"; +} + +/** + * @tc.name: GetLongTest004 + * @tc.desc: Verify the GetLong function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetLongTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLong Start"; + try { + const string key = FileColumn::FILE_SIZE; + int64_t value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetLong(_, _)).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::GetLong(key, value, resultSet); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetLong ERROR"; + } + GTEST_LOG_(INFO) << "GetLong End"; +} + +/** + * @tc.name: GetLongTest005 + * @tc.desc: Verify the GetLong function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetLongTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLong Start"; + try { + const string key = FileColumn::FILE_SIZE; + int64_t value; + std::shared_ptr resultSet = nullptr; + + int32_t ret = CloudDiskRdbUtils::GetLong(key, value, resultSet); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetLong ERROR"; + } + GTEST_LOG_(INFO) << "GetLong End"; +} + +/** + * @tc.name: GetStringTest001 + * @tc.desc: Verify the GetString function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetStringTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetString Start"; + const string key = FileColumn::FILE_NAME; + string value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillOnce(Return(E_OK)); + int32_t ret = CloudDiskRdbUtils::GetString(key, value, resultSet); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "GetString End"; +} + +/** + * @tc.name: GetStringTest002 + * @tc.desc: Verify the GetString function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetStringTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetString Start"; + try { + const string key = ""; + string value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillOnce(Return(E_OK)); + int32_t ret = CloudDiskRdbUtils::GetString(key, value, resultSet); + EXPECT_EQ(ret, E_OK); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetString ERROR"; + } + GTEST_LOG_(INFO) << "GetString End"; +} + +/** + * @tc.name: GetStringTest003 + * @tc.desc: Verify the GetString function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetStringTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetString Start"; + try { + const string key = FileColumn::FILE_NAME; + string value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::GetString(key, value, resultSet); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetString ERROR"; + } + GTEST_LOG_(INFO) << "GetString End"; +} + +/** + * @tc.name: GetStringTest004 + * @tc.desc: Verify the GetString function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetStringTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetString Start"; + try { + const string key = FileColumn::FILE_NAME; + string value; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::GetString(key, value, resultSet); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetString ERROR"; + } + GTEST_LOG_(INFO) << "GetString End"; +} + +/** + * @tc.name: GetStringTest005 + * @tc.desc: Verify the GetString function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, GetStringTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetString Start"; + try { + const string key = FileColumn::FILE_NAME; + string value; + std::shared_ptr resultSet = nullptr; + + int32_t ret = CloudDiskRdbUtils::GetString(key, value, resultSet); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetString ERROR"; + } + GTEST_LOG_(INFO) << "GetString End"; +} + +/** + * @tc.name: ResultSetToFileInfoTest001 + * @tc.desc: Verify the ResultSetToFileInfo function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, ResultSetToFileInfoTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ResultSetToFileInfo Start"; + try { + CloudDiskFileInfo info; + std::shared_ptr resultSet = nullptr; + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfo(resultSet, info); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ResultSetToFileInfo ERROR"; + } + GTEST_LOG_(INFO) << "ResultSetToFileInfo End"; +} + +/** + * @tc.name: ResultSetToFileInfoTest002 + * @tc.desc: Verify the ResultSetToFileInfo function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, ResultSetToFileInfoTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ResultSetToFileInfo Start"; + try { + CloudDiskFileInfo info; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GoToNextRow()).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfo(std::move(resultSet), info); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ResultSetToFileInfo ERROR"; + } + GTEST_LOG_(INFO) << "ResultSetToFileInfo End"; +} + +/** + * @tc.name: ResultSetToFileInfoTest003 + * @tc.desc: Verify the ResultSetToFileInfo function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, ResultSetToFileInfoTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ResultSetToFileInfo Start"; + try { + CloudDiskFileInfo info; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GoToNextRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetRow(_)).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfo(std::move(resultSet), info); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ResultSetToFileInfo ERROR"; + } + GTEST_LOG_(INFO) << "ResultSetToFileInfo End"; +} + +/** + * @tc.name: ResultSetToFileInfoTest004 + * @tc.desc: Verify the ResultSetToFileInfo function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, ResultSetToFileInfoTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ResultSetToFileInfo Start"; + CloudDiskFileInfo info; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GoToNextRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSet, GetRow(_)).WillOnce(Return(E_OK)); + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfo(std::move(resultSet), info); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "ResultSetToFileInfo End"; +} + +/** + * @tc.name: ResultSetToFileInfosTest001 + * @tc.desc: Verify the ResultSetToFileInfos function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, ResultSetToFileInfosTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ResultSetToFileInfos Start"; + try { + vector infos; + std::shared_ptr resultSet = nullptr; + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfos(resultSet, infos); + EXPECT_EQ(ret, E_RDB); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ResultSetToFileInfos ERROR"; + } + GTEST_LOG_(INFO) << "ResultSetToFileInfos End"; +} + +/** + * @tc.name: ResultSetToFileInfosTest002 + * @tc.desc: Verify the ResultSetToFileInfos function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, ResultSetToFileInfosTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ResultSetToFileInfos Start"; + vector infos; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GoToNextRow()).WillOnce(Return(E_RDB)); + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfos(std::move(resultSet), infos); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "ResultSetToFileInfos End"; +} + +/** + * @tc.name: ResultSetToFileInfosTest003 + * @tc.desc: Verify the ResultSetToFileInfos function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskRdbUtilsTest, ResultSetToFileInfosTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ResultSetToFileInfos Start"; + vector infos; + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*resultSet, GoToNextRow()) + .Times(2) + .WillOnce(Return(E_OK)) + .WillOnce(Return(E_RDB)); + EXPECT_CALL(*resultSet, GetColumnIndex(_, _)).Times(2).WillRepeatedly(Return(E_OK)); + int32_t ret = CloudDiskRdbUtils::ResultSetToFileInfos(std::move(resultSet), infos); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "ResultSetToFileInfos End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/clouddisk_database/clouddisk_rdbstore_test.cpp b/cloud_file/test/unittests/clouddisk_database/clouddisk_rdbstore_test.cpp new file mode 100644 index 0000000..1de2b26 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/clouddisk_rdbstore_test.cpp @@ -0,0 +1,4341 @@ +/* +* Copyright (C) 2024 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 "cloud_file_utils.h" +#include "cloud_status.h" +#include "clouddisk_rdb_utils.h" +#include "clouddisk_rdbstore.h" +#include "dfs_error.h" +#include "rdb_assistant.h" +#include "result_set_mock.h" +#include +#include +#include +#include "transaction_mock.cpp" + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace NativeRdb; + +static const string BUNDLE_NAME = "com.ohos.photos"; +static const int32_t USER_ID = 100; +class CloudDiskRdbStoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr clouddiskrdbStore_ = nullptr; + static inline shared_ptr insMock = nullptr; +}; + +void CloudDiskRdbStoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + insMock = make_shared(); + Assistant::ins = insMock; + clouddiskrdbStore_ = make_shared(BUNDLE_NAME, USER_ID); +} + +void CloudDiskRdbStoreTest::TearDownTestCase(void) +{ + Assistant::ins = nullptr; + insMock = nullptr; + clouddiskrdbStore_ = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDiskRdbStoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDiskRdbStoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: ReBuildDatabase + * @tc.desc: Verify the CloudDiskRdbStore::ReBuildDatabase function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, ReBuildDatabaseTest1, TestSize.Level1) +{ + string databasePath = "/data"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*insMock, DeleteRdbStore(_)).WillOnce(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->ReBuildDatabase(databasePath); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: ReBuildDatabase + * @tc.desc: Verify the CloudDiskRdbStore::ReBuildDatabase function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, ReBuildDatabaseTest2, TestSize.Level1) +{ + string databasePath = "/data"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*insMock, DeleteRdbStore(_)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, GetRdbStore(_, _, _, _)).WillOnce(Return(nullptr)); + + int32_t ret = clouddiskrdbStore_->ReBuildDatabase(databasePath); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: ReBuildDatabase + * @tc.desc: Verify the CloudDiskRdbStore::ReBuildDatabase function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, ReBuildDatabaseTest3, TestSize.Level1) +{ + string databasePath = "/data"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*insMock, DeleteRdbStore(_)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, GetRdbStore(_, _, _, _)).WillOnce(Return(rdb)); + + int32_t ret = clouddiskrdbStore_->ReBuildDatabase(databasePath); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: RdbInit + * @tc.desc: Verify the CloudDiskRdbStore::RdbInit function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RdbInitTest1, TestSize.Level1) +{ + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*insMock, GetRdbStore(_, _, _, _)).WillOnce(Return(nullptr)); + + int32_t ret = clouddiskrdbStore_->RdbInit(); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: RdbInit + * @tc.desc: Verify the CloudDiskRdbStore::RdbInit function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RdbInitTest2, TestSize.Level1) +{ + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*insMock, GetRdbStore(_, _, _, _)).WillOnce(Return(rdb)); + + int32_t ret = clouddiskrdbStore_->RdbInit(); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: LookUp + * @tc.desc: Verify the CloudDiskRdbStore::LookUp function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LookUpTest1, TestSize.Level1) +{ + const std::string parentCloudId = ""; + const std::string fileName = "test"; + CloudDiskFileInfo info; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->LookUp(parentCloudId, fileName, info); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: LookUp + * @tc.desc: Verify the CloudDiskRdbStore::LookUp function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LookUpTest2, TestSize.Level1) +{ + const std::string parentCloudId = "100"; + const std::string fileName = ""; + CloudDiskFileInfo info; + info.name = "mock"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->LookUp(parentCloudId, fileName, info); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: LookUp + * @tc.desc: Verify the CloudDiskRdbStore::LookUp function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LookUpTest3, TestSize.Level1) +{ + const std::string parentCloudId = "rootId"; + const std::string fileName = "test"; + CloudDiskFileInfo info; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->LookUp(parentCloudId, fileName, info); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: LookUp + * @tc.desc: Verify the CloudDiskRdbStore::LookUp function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LookUpTest4, TestSize.Level1) +{ + const std::string parentCloudId = "rootId"; + const std::string fileName = "test"; + CloudDiskFileInfo info; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->LookUp(parentCloudId, fileName, info); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetAttrTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + CloudDiskFileInfo info; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetAttr(cloudId, info); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetAttrTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + CloudDiskFileInfo info; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetAttr(cloudId, info); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetAttrTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + CloudDiskFileInfo info; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetAttr(cloudId, info); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetAttrTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + CloudDiskFileInfo info; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetAttr(cloudId, info); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: SetAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetAttrTest1, TestSize.Level1) +{ + const std::string fileName = "Test"; + const std::string parentCloudId = "100"; + const std::string cloudId = ""; + const unsigned long long size = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->SetAttr(fileName, parentCloudId, cloudId, size); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: SetAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetAttrTest2, TestSize.Level1) +{ + const std::string fileName = "Test"; + const std::string parentCloudId = "100"; + const std::string cloudId = "rootId"; + const unsigned long long size = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->SetAttr(fileName, parentCloudId, cloudId, size); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: SetAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetAttrTest3, TestSize.Level1) +{ + const std::string fileName = "mock"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const unsigned long long size = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->SetAttr(fileName, parentCloudId, cloudId, size); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: SetAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetAttrTest4, TestSize.Level1) +{ + const std::string fileName = "mock"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const unsigned long long size = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->SetAttr(fileName, parentCloudId, cloudId, size); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: SetAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetAttrTest5, TestSize.Level1) +{ + const std::string fileName = "test"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const unsigned long long size = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->SetAttr(fileName, parentCloudId, cloudId, size); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: ReadDir + * @tc.desc: Verify the CloudDiskRdbStore::ReadDir function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, ReadDirTest1, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + vector infos; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->ReadDir(cloudId, infos); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: Create + * @tc.desc: Verify the CloudDiskRdbStore::Create function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateTest1, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string parentCloudId = "100"; + const std::string fileName = ""; + bool noNeedUpload = false; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->Create(cloudId, parentCloudId, fileName, noNeedUpload); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: Create + * @tc.desc: Verify the CloudDiskRdbStore::Create function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string parentCloudId = "100"; + const std::string fileName = "<|>"; + bool noNeedUpload = false; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->Create(cloudId, parentCloudId, fileName, noNeedUpload); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: Create + * @tc.desc: Verify the CloudDiskRdbStore::Create function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateTest3, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string parentCloudId = "100"; + const std::string fileName = " test"; + bool noNeedUpload = false; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->Create(cloudId, parentCloudId, fileName, noNeedUpload); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: Create + * @tc.desc: Verify the CloudDiskRdbStore::Create function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateTest4, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string parentCloudId = ""; + const std::string fileName = "test"; + bool noNeedUpload = false; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->Create(cloudId, parentCloudId, fileName, noNeedUpload); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: Create + * @tc.desc: Verify the CloudDiskRdbStore::Create function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateTest5, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string parentCloudId = "100"; + const std::string fileName = "test"; + bool noNeedUpload = false; + clouddiskrdbStore_->userId_ = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->Create(cloudId, parentCloudId, fileName, noNeedUpload); + EXPECT_EQ(ret, E_PATH); +} + +/** + * @tc.name: Create + * @tc.desc: Verify the CloudDiskRdbStore::Create function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateTest6, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string parentCloudId = "100"; + const std::string fileName = "test"; + bool noNeedUpload = true; + clouddiskrdbStore_->userId_ = 1; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->Create(cloudId, parentCloudId, fileName, noNeedUpload); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: Create + * @tc.desc: Verify the CloudDiskRdbStore::Create function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateTest7, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string parentCloudId = "100"; + const std::string fileName = "mock"; + bool noNeedUpload = true; + clouddiskrdbStore_->userId_ = 1; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->Create(cloudId, parentCloudId, fileName, noNeedUpload); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: Create + * @tc.desc: Verify the CloudDiskRdbStore::Create function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateTest8, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string parentCloudId = "100"; + const std::string fileName = "test"; + bool noNeedUpload = true; + clouddiskrdbStore_->userId_ = 1; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->Create(cloudId, parentCloudId, fileName, noNeedUpload); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: MkDir + * @tc.desc: Verify the CloudDiskRdbStore::MkDir function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, MkDirTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string parentCloudId = "100"; + const std::string directoryName = ""; + bool noNeedUpload = false; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->MkDir(cloudId, parentCloudId, directoryName, noNeedUpload); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: MkDir + * @tc.desc: Verify the CloudDiskRdbStore::MkDir function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, MkDirTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string parentCloudId = "100"; + const std::string directoryName = ".trash"; + bool noNeedUpload = false; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->MkDir(cloudId, parentCloudId, directoryName, noNeedUpload); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: MkDir + * @tc.desc: Verify the CloudDiskRdbStore::MkDir function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, MkDirTest3, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string parentCloudId = ""; + const std::string directoryName = "test"; + bool noNeedUpload = false; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->MkDir(cloudId, parentCloudId, directoryName, noNeedUpload); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: MkDir + * @tc.desc: Verify the CloudDiskRdbStore::MkDir function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, MkDirTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string parentCloudId = "100"; + const std::string directoryName = "mock"; + bool noNeedUpload = false; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->MkDir(cloudId, parentCloudId, directoryName, noNeedUpload); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: MkDir + * @tc.desc: Verify the CloudDiskRdbStore::MkDir function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, MkDirTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string parentCloudId = "100"; + const std::string directoryName = "mock"; + bool noNeedUpload = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->MkDir(cloudId, parentCloudId, directoryName, noNeedUpload); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: MkDir + * @tc.desc: Verify the CloudDiskRdbStore::MkDir function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, MkDirTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string parentCloudId = "100"; + const std::string directoryName = "test"; + bool noNeedUpload = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->MkDir(cloudId, parentCloudId, directoryName, noNeedUpload); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: Write + * @tc.desc: Verify the CloudDiskRdbStore::Write function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, WriteTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string parentCloudId = "100"; + const std::string fileName = "file"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Write(fileName, parentCloudId, cloudId); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: Write + * @tc.desc: Verify the CloudDiskRdbStore::Write function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, WriteTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string fileName = "file"; + const std::string parentCloudId = "rootId"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Write(fileName, parentCloudId, cloudId); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: Write + * @tc.desc: Verify the CloudDiskRdbStore::Write function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, WriteTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string fileName = "file"; + const std::string parentCloudId = "rootId"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->userId_ = 0; + + int32_t ret = clouddiskrdbStore_->Write(fileName, parentCloudId, cloudId); + EXPECT_EQ(ret, E_PATH); +} + +/** + * @tc.name: Write + * @tc.desc: Verify the CloudDiskRdbStore::Write function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, WriteTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string fileName = "mock"; + const std::string parentCloudId = "rootId"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->userId_ = 1; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->Write(fileName, parentCloudId, cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: Write + * @tc.desc: Verify the CloudDiskRdbStore::Write function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, WriteTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string fileName = "mock"; + const std::string parentCloudId = "rootId"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->userId_ = 1; + std::shared_ptr rset = std::make_shared(); + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->Write(fileName, parentCloudId, cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: Write + * @tc.desc: Verify the CloudDiskRdbStore::Write function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, WriteTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string fileName = "mock"; + const std::string parentCloudId = "rootId"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->userId_ = 1; + std::shared_ptr rset = std::make_shared(); + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->Write(fileName, parentCloudId, cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: LocationSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::LocationSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LocationSetXattrTest1, TestSize.Level1) +{ + const std::string name = "test"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const std::string value = "4"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->LocationSetXattr(name, parentCloudId, cloudId, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: LocationSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::LocationSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LocationSetXattrTest2, TestSize.Level1) +{ + const std::string name = "mock"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const std::string value = "1"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->LocationSetXattr(name, parentCloudId, cloudId, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: LocationSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::LocationSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LocationSetXattrTest3, TestSize.Level1) +{ + const std::string name = "mock"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const std::string value = "1"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->LocationSetXattr(name, parentCloudId, cloudId, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: LocationSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::LocationSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LocationSetXattrTest4, TestSize.Level1) +{ + const std::string name = "test"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const std::string value = "1"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->LocationSetXattr(name, parentCloudId, cloudId, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: HasTHMSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::HasTHMSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HasTHMSetXattrTest1, TestSize.Level1) +{ + const std::string name = "test"; + const std::string key = "100"; + const std::string cloudId = "100"; + const std::string value = "test"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->HasTHMSetXattr(name, key, cloudId, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: HasTHMSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::HasTHMSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HasTHMSetXattrTest2, TestSize.Level1) +{ + const std::string name = "test"; + const std::string key = "100"; + const std::string cloudId = "100"; + const std::string value = "2"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->HasTHMSetXattr(name, key, cloudId, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: HasTHMSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::HasTHMSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HasTHMSetXattrTest3, TestSize.Level1) +{ + const std::string name = "test"; + const std::string key = CLOUD_HAS_LCD; + const std::string cloudId = "100"; + const std::string value = "0"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->HasTHMSetXattr(name, key, cloudId, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: HasTHMSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::HasTHMSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HasTHMSetXattrTest4, TestSize.Level1) +{ + const std::string name = "test"; + const std::string key = CLOUD_HAS_THM; + const std::string cloudId = "100"; + const std::string value = "0"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->HasTHMSetXattr(name, key, cloudId, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: HasTHMSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::HasTHMSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HasTHMSetXattrTest5, TestSize.Level1) +{ + const std::string name = "test"; + const std::string key = CLOUD_HAS_LCD; + const std::string cloudId = "100"; + const std::string value = "1"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->HasTHMSetXattr(name, key, cloudId, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: HasTHMSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::HasTHMSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HasTHMSetXattrTest6, TestSize.Level1) +{ + const std::string name = "test"; + const std::string key = CLOUD_HAS_THM; + const std::string cloudId = "100"; + const std::string value = "1"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->HasTHMSetXattr(name, key, cloudId, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: HasTHMSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::HasTHMSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HasTHMSetXattrTest7, TestSize.Level1) +{ + const std::string name = "test"; + const std::string key = CLOUD_HAS_THM; + const std::string cloudId = "100"; + const std::string value = "1"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->HasTHMSetXattr(name, key, cloudId, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetRowId + * @tc.desc: Verify the CloudDiskRdbStore::GetRowId function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRowIdTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId = 100; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetRowId(cloudId, rowId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetRowId + * @tc.desc: Verify the CloudDiskRdbStore::GetRowId function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRowIdTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId = 100; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetRowId(cloudId, rowId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetRowId + * @tc.desc: Verify the CloudDiskRdbStore::GetRowId function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRowIdTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId = 100; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetRowId(cloudId, rowId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetParentCloudIdTest + * @tc.desc: Verify the CloudDiskRdbStore::GetParentCloudIdTest function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentCloudIdTestTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string parentCloudId = "mock"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetParentCloudId(cloudId, parentCloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetParentCloudIdTest + * @tc.desc: Verify the CloudDiskRdbStore::GetParentCloudIdTest function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentCloudIdTestTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string parentCloudId = "mock"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetParentCloudId(cloudId, parentCloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetParentCloudIdTest + * @tc.desc: Verify the CloudDiskRdbStore::GetParentCloudIdTest function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentCloudIdTestTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string parentCloudId = "mock"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetParentCloudId(cloudId, parentCloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetParentCloudIdTest + * @tc.desc: Verify the CloudDiskRdbStore::GetParentCloudIdTest function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentCloudIdTestTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string parentCloudId = "test"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetParentCloudId(cloudId, parentCloudId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetSourcePath + * @tc.desc: Verify the CloudDiskRdbStore::GetSourcePath function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetSourcePathTest1, TestSize.Level1) +{ + const std::string attr = R"({"srcPath": "/data/service"})"; + const std::string parentCloudId = "100"; + std::string sourcePath = "/data"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetSourcePath(attr, parentCloudId, sourcePath); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetSourcePath + * @tc.desc: Verify the CloudDiskRdbStore::GetSourcePath function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetSourcePathTest2, TestSize.Level1) +{ + const std::string attr = R"({"srcPath": 100})"; + const std::string parentCloudId = "100"; + std::string sourcePath = "/data"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetSourcePath(attr, parentCloudId, sourcePath); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetSourcePath + * @tc.desc: Verify the CloudDiskRdbStore::GetSourcePath function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetSourcePathTest3, TestSize.Level1) +{ + const std::string attr = ""; + const std::string parentCloudId = "100"; + std::string sourcePath = "/data"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetSourcePath(attr, parentCloudId, sourcePath); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetSourcePath + * @tc.desc: Verify the CloudDiskRdbStore::GetSourcePath function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetSourcePathTest4, TestSize.Level1) +{ + const std::string attr = ""; + const std::string parentCloudId = ""; + std::string sourcePath = "/data"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetSourcePath(attr, parentCloudId, sourcePath); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetSourcePath + * @tc.desc: Verify the CloudDiskRdbStore::GetSourcePath function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetSourcePathTest5, TestSize.Level1) +{ + const std::string attr = ""; + const std::string parentCloudId = "100"; + std::string sourcePath = "/data"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetSourcePath(attr, parentCloudId, sourcePath); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: SourcePathSetValue + * @tc.desc: Verify the CloudDiskRdbStore::SourcePathSetValue function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SourcePathSetValueTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string attr = ""; + ValuesBucket setXattr; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->SourcePathSetValue(cloudId, attr, setXattr); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: SourcePathSetValue + * @tc.desc: Verify the CloudDiskRdbStore::SourcePathSetValue function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SourcePathSetValueTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string attr = ""; + ValuesBucket setXattr; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->SourcePathSetValue(cloudId, attr, setXattr); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: SourcePathSetValue + * @tc.desc: Verify the CloudDiskRdbStore::SourcePathSetValue function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SourcePathSetValueTest3, TestSize.Level1) +{ + const std::string cloudId = "test"; + const std::string attr = ""; + ValuesBucket setXattr; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->SourcePathSetValue(cloudId, attr, setXattr); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: RecycleSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::RecycleSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RecycleSetXattrTest1, TestSize.Level1) +{ + const std::string name = "test"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const std::string value = "notnum"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->RecycleSetXattr(name, parentCloudId, cloudId, value); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: RecycleSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::RecycleSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RecycleSetXattrTest2, TestSize.Level1) +{ + const std::string name = "test"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const std::string value = "0"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->RecycleSetXattr(name, parentCloudId, cloudId, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: RecycleSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::RecycleSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RecycleSetXattrTest3, TestSize.Level1) +{ + const std::string name = "test"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const std::string value = "1"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->RecycleSetXattr(name, parentCloudId, cloudId, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: RecycleSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::RecycleSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RecycleSetXattrTest4, TestSize.Level1) +{ + const std::string name = "test"; + const std::string parentCloudId = "100"; + const std::string cloudId = "100"; + const std::string value = "-1"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->RecycleSetXattr(name, parentCloudId, cloudId, value); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: CheckIsConflict + * @tc.desc: Verify the CloudDiskRdbStore::CheckIsConflict function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CheckIsConflictTest1, TestSize.Level1) +{ + const std::string name = "mock"; + const std::string parentCloudId = "100"; + std::string newName = "test1"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->CheckIsConflict(name, parentCloudId, newName); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: CheckIsConflict + * @tc.desc: Verify the CloudDiskRdbStore::CheckIsConflict function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CheckIsConflictTest2, TestSize.Level1) +{ + const std::string name = "test"; + const std::string parentCloudId = "100"; + std::string newName = "test1"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->CheckIsConflict(name, parentCloudId, newName); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: RestoreUpdateRdb + * @tc.desc: Verify the CloudDiskRdbStore::RestoreUpdateRdb function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RestoreUpdateRdbTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + const struct RestoreInfo restoreInfo; + ValuesBucket setXattr; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->RestoreUpdateRdb(cloudId, restoreInfo, setXattr); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: RestoreUpdateRdb + * @tc.desc: Verify the CloudDiskRdbStore::RestoreUpdateRdb function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RestoreUpdateRdbTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + const struct RestoreInfo restoreInfo; + ValuesBucket setXattr; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->RestoreUpdateRdb(cloudId, restoreInfo, setXattr); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: RestoreUpdateRdb + * @tc.desc: Verify the CloudDiskRdbStore::RestoreUpdateRdb function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RestoreUpdateRdbTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + const struct RestoreInfo restoreInfo; + ValuesBucket setXattr; + restoreInfo.parentCloudId == "mock"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->RestoreUpdateRdb(cloudId, restoreInfo, setXattr); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: HandleRestoreXattr + * @tc.desc: Verify the CloudDiskRdbStore::HandleRestoreXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HandleRestoreXattrTest1, TestSize.Level1) +{ + const std::string name = ""; + const std::string parentCloudId = ""; + const std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->HandleRestoreXattr(name, parentCloudId, cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: HandleRestoreXattr + * @tc.desc: Verify the CloudDiskRdbStore::HandleRestoreXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HandleRestoreXattrTest2, TestSize.Level1) +{ + const std::string name = ""; + const std::string parentCloudId = ""; + const std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))) + .WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->HandleRestoreXattr(name, parentCloudId, cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: HandleRestoreXattr + * @tc.desc: Verify the CloudDiskRdbStore::HandleRestoreXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HandleRestoreXattrTest3, TestSize.Level1) +{ + const std::string name = ""; + const std::string parentCloudId = ""; + const std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))) + .WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->HandleRestoreXattr(name, parentCloudId, cloudId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: HandleRecycleXattr + * @tc.desc: Verify the CloudDiskRdbStore::HandleRecycleXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HandleRecycleXattrTest1, TestSize.Level1) +{ + const std::string name = ""; + const std::string parentCloudId = ""; + const std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->HandleRecycleXattr(name, parentCloudId, cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: HandleRecycleXattr + * @tc.desc: Verify the CloudDiskRdbStore::HandleRecycleXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HandleRecycleXattrTest2, TestSize.Level1) +{ + const std::string name = ""; + const std::string parentCloudId = ""; + const std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = "rootId"; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(1), Return(E_OK))); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->HandleRecycleXattr(name, parentCloudId, cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: HandleRecycleXattr + * @tc.desc: Verify the CloudDiskRdbStore::HandleRecycleXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HandleRecycleXattrTest3, TestSize.Level1) +{ + const std::string name = ""; + const std::string parentCloudId = "mock"; + const std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = "rootId"; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(0), Return(E_OK))); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->HandleRecycleXattr(name, parentCloudId, cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: HandleRecycleXattr + * @tc.desc: Verify the CloudDiskRdbStore::HandleRecycleXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, HandleRecycleXattrTest4, TestSize.Level1) +{ + const std::string name = ""; + const std::string parentCloudId = ""; + const std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = "rootId"; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(1), Return(E_OK))); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->HandleRecycleXattr(name, parentCloudId, cloudId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetRecycleInfo + * @tc.desc: Verify the CloudDiskRdbStore::GetRecycleInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRecycleInfoTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId; + int32_t position; + std::string attr; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetRecycleInfo(transaction, cloudId, rowId, position, attr); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetRecycleInfo + * @tc.desc: Verify the CloudDiskRdbStore::GetRecycleInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRecycleInfoTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId; + int32_t position; + std::string attr; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetRecycleInfo(transaction, cloudId, rowId, position, attr); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetRecycleInfo + * @tc.desc: Verify the CloudDiskRdbStore::GetRecycleInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRecycleInfoTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId; + int32_t position; + std::string attr; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetRecycleInfo(transaction, cloudId, rowId, position, attr); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetRecycleInfo + * @tc.desc: Verify the CloudDiskRdbStore::GetRecycleInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRecycleInfoTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId; + int32_t position; + std::string attr; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetRecycleInfo(transaction, cloudId, rowId, position, attr); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetRecycleInfo + * @tc.desc: Verify the CloudDiskRdbStore::GetRecycleInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRecycleInfoTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId; + int32_t position; + std::string attr; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetRecycleInfo(transaction, cloudId, rowId, position, attr); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetRecycleInfo + * @tc.desc: Verify the CloudDiskRdbStore::GetRecycleInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetRecycleInfoTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + int64_t rowId; + int32_t position; + std::string attr; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + auto transaction = make_shared(); + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*transaction, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetRecycleInfo(transaction, cloudId, rowId, position, attr); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: FavoriteSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteSetXattrTest1, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string value = "notnum"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->FavoriteSetXattr(cloudId, value); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: FavoriteSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteSetXattrTest2, TestSize.Level1) +{ + const std::string cloudId = "root"; + const std::string value = "2"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->FavoriteSetXattr(cloudId, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: FavoriteSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteSetXattrTest3, TestSize.Level1) +{ + const std::string cloudId = "root"; + const std::string value = "0"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, Update(_, _, _, _, An &>())).WillOnce(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->FavoriteSetXattr(cloudId, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: FavoriteSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteSetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteSetXattrTest4, TestSize.Level1) +{ + const std::string cloudId = "root"; + const std::string value = "1"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, Update(_, _, _, _, An &>())).WillOnce(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->FavoriteSetXattr(cloudId, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: LocationGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::LocationGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LocationGetXattrTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + const std::string name = "test"; + const std::string parentCloudId = "rootId"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->LocationGetXattr(name, key, value, parentCloudId); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: LocationGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::LocationGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LocationGetXattrTest2, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = CLOUD_FILE_LOCATION; + std::string value = ""; + const std::string name = "mock"; + const std::string parentCloudId = "rootId"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->LocationGetXattr(name, key, value, parentCloudId); + EXPECT_EQ(ret, ENOENT); +} + +/** + * @tc.name: LocationGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::LocationGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, LocationGetXattrTest3, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = CLOUD_FILE_LOCATION; + std::string value = ""; + const std::string name = "test"; + const std::string parentCloudId = "rootId"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->LocationGetXattr(name, key, value, parentCloudId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: FavoriteGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteGetXattrTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->FavoriteGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: FavoriteGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteGetXattrTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->FavoriteGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: FavoriteGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteGetXattrTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FILE_STATUS_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->FavoriteGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: FavoriteGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteGetXattrTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->FavoriteGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: FavoriteGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteGetXattrTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->FavoriteGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: FavoriteGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FavoriteGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FavoriteGetXattrTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->FavoriteGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: FileStatusGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FileStatusGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FileStatusGetXattrTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = IS_FILE_STATUS_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->FileStatusGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: FileStatusGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FileStatusGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FileStatusGetXattrTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string key = IS_FILE_STATUS_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->FileStatusGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: FileStatusGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FileStatusGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FileStatusGetXattrTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->FileStatusGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: FileStatusGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FileStatusGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FileStatusGetXattrTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FILE_STATUS_XATTR; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->FileStatusGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: FileStatusGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FileStatusGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FileStatusGetXattrTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FILE_STATUS_XATTR; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->FileStatusGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: FileStatusGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FileStatusGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FileStatusGetXattrTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FILE_STATUS_XATTR; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->FileStatusGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: FileStatusGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::FileStatusGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, FileStatusGetXattrTest7, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FILE_STATUS_XATTR; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->FileStatusGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: TimeRecycledGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::TimeRecycledGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, TimeRecycledGetXattrTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = CLOUD_TIME_RECYCLED; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->TimeRecycledGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: TimeRecycledGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::TimeRecycledGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, TimeRecycledGetXattrTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string key = CLOUD_TIME_RECYCLED; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->TimeRecycledGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: TimeRecycledGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::TimeRecycledGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, TimeRecycledGetXattrTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->TimeRecycledGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: TimeRecycledGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::TimeRecycledGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, TimeRecycledGetXattrTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = CLOUD_TIME_RECYCLED; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->TimeRecycledGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: TimeRecycledGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::TimeRecycledGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, TimeRecycledGetXattrTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = CLOUD_TIME_RECYCLED; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->TimeRecycledGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: TimeRecycledGetXattr + * @tc.desc: Verify the CloudDiskRdbStore::TimeRecycledGetXattr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, TimeRecycledGetXattrTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = CLOUD_TIME_RECYCLED; + std::string value = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->TimeRecycledGetXattr(cloudId, key, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = "100"; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + const std::string key = "100"; + std::string value = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = ""; + std::string value = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = "100"; + std::string value = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = "100"; + std::string value = "100"; + std::string mockValue = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(mockValue), Return(E_OK))); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = "100"; + std::string value = "100"; + std::string mockValue = "invalid"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(mockValue), Return(E_OK))); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest7, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = "test"; + std::string value = "100"; + std::string mockValue = R"({"key": "/data/service"})"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(mockValue), Return(E_OK))); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest8, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = "key"; + std::string value = "100"; + std::string mockValue = R"({"key": 123})"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(mockValue), Return(E_OK))); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttrValue + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrValueTest9, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = "key"; + std::string value = "100"; + std::string mockValue = R"({"key": "/data/service"})"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(mockValue), Return(E_OK))); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetExtAttrValue(cloudId, key, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetExtAttr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + std::string value = ""; + int32_t pos = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetExtAttr(cloudId, value, pos); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetExtAttr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrTest2, TestSize.Level1) +{ + const std::string cloudId = "rootId"; + std::string value = ""; + int32_t pos = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetExtAttr(cloudId, value, pos); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetExtAttr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string value = "mock"; + int32_t pos = 0; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetExtAttr(cloudId, value, pos); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string value = ""; + int32_t pos = 0; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetExtAttr(cloudId, value, pos); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string value = "mock"; + int32_t pos = 0; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetExtAttr(cloudId, value, pos); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string value = ""; + int32_t pos = -1; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetExtAttr(cloudId, value, pos); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetExtAttr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrTest7, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string value = ""; + int32_t pos = -1; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetExtAttr(cloudId, value, pos); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetExtAttr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, GetExtAttrTest8, TestSize.Level1) +{ + const std::string cloudId = "100"; + std::string value = ""; + int32_t pos = 1; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetExtAttr(cloudId, value, pos); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetXAttrTest1, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = CLOUD_FILE_LOCATION; + std::string value = ""; + CacheNode node; + node.fileName = "test"; + node.parentCloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetXAttr(cloudId, key, value); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetXAttrTest2, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = IS_FAVORITE_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetXAttr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetXAttrTest3, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = IS_FILE_STATUS_XATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetXAttr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetXAttrTest4, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = CLOUD_EXT_ATTR; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetXAttr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetXAttrTest5, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = CLOUD_TIME_RECYCLED; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetXAttr(cloudId, key, value); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::GetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetXAttrTest6, TestSize.Level1) +{ + const std::string cloudId = ""; + const std::string key = CLOUD_HAS_THM; + std::string value = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetXAttr(cloudId, key, value); + EXPECT_EQ(ret, ENOSYS); +} + +/** + * @tc.name: ExtAttributeSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, ExtAttributeSetXattrTest1, TestSize.Level1) +{ + const std::string cloudId = "cloudId"; + const std::string key = "key1"; + const std::string value = "value1"; + std::string xattrList = ""; + int32_t pos = 0; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(xattrList), Return(E_OK))); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(pos), Return(E_OK))); + + int32_t ret = clouddiskrdbStore_->ExtAttributeSetXattr(cloudId, value, key); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: ExtAttributeSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, ExtAttributeSetXattrTest2, TestSize.Level1) +{ + const std::string cloudId = "cloudId"; + const std::string key = "key1"; + const std::string value = "value1"; + std::string xattrList = "{\"key2\":\"value2\"}";; + int32_t pos = 0; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(xattrList), Return(E_OK))); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(pos), Return(E_OK))); + + int32_t ret = clouddiskrdbStore_->ExtAttributeSetXattr(cloudId, value, key); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: ExtAttributeSetXattr + * @tc.desc: Verify the CloudDiskRdbStore::ExtAttributeSetXattr function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, ExtAttributeSetXattrTest3, TestSize.Level1) +{ + const std::string cloudId = "cloudId"; + const std::string key = "key1"; + const std::string value = "value1"; + std::string xattrList = "{\"key1\":\"value1\"}";; + int32_t pos = 1; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + auto transaction = make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Update(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(xattrList), Return(E_OK))); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>(pos), Return(E_OK))); + + int32_t ret = clouddiskrdbStore_->ExtAttributeSetXattr(cloudId, value, key); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: SetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetXAttrTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = CLOUD_FILE_LOCATION; + const std::string value = "notnum"; + const std::string name = "test"; + const std::string parentCloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->SetXAttr(cloudId, key, value, name, parentCloudId); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: SetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetXAttrTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = CLOUD_CLOUD_RECYCLE_XATTR; + const std::string value = "notnum"; + const std::string name = "test"; + const std::string parentCloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->SetXAttr(cloudId, key, value, name, parentCloudId); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: SetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetXAttrTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = IS_FAVORITE_XATTR; + const std::string value = "notnum"; + const std::string name = "test"; + const std::string parentCloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->SetXAttr(cloudId, key, value, name, parentCloudId); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: SetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetXAttrTest4, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = CLOUD_EXT_ATTR; + const std::string value = "notnum"; + const std::string name = "test"; + const std::string parentCloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->SetXAttr(cloudId, key, value, name, parentCloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: SetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetXAttrTest5, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = CLOUD_HAS_THM; + const std::string value = "notnum"; + const std::string name = "test"; + const std::string parentCloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->SetXAttr(cloudId, key, value, name, parentCloudId); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: SetXAttr + * @tc.desc: Verify the CloudDiskRdbStore::SetXAttr function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, SetXAttrTest6, TestSize.Level1) +{ + const std::string cloudId = "100"; + const std::string key = CLOUD_CLOUD_ID_XATTR; + const std::string value = "notnum"; + const std::string name = "test"; + const std::string parentCloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->SetXAttr(cloudId, key, value, name, parentCloudId); + EXPECT_EQ(ret, ENOSYS); +} + +/** + * @tc.name: Rename + * @tc.desc: Verify the CloudDiskRdbStore::Rename function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RenameTest1, TestSize.Level1) +{ + const std::string oldParentCloudId = "100"; + const std::string oldFileName = "test"; + const std::string newParentCloudId = "100"; + const std::string newFileName = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Rename(oldParentCloudId, oldFileName, newParentCloudId, newFileName); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: Rename + * @tc.desc: Verify the CloudDiskRdbStore::Rename function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RenameTest2, TestSize.Level1) +{ + const std::string oldParentCloudId = ""; + const std::string oldFileName = "test"; + const std::string newParentCloudId = "100"; + const std::string newFileName = "newFileName"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Rename(oldParentCloudId, oldFileName, newParentCloudId, newFileName); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: Rename + * @tc.desc: Verify the CloudDiskRdbStore::Rename function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RenameTest3, TestSize.Level1) +{ + const std::string oldParentCloudId = "100"; + const std::string oldFileName = ""; + const std::string newParentCloudId = "100"; + const std::string newFileName = "newFileName"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Rename(oldParentCloudId, oldFileName, newParentCloudId, newFileName); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: Rename + * @tc.desc: Verify the CloudDiskRdbStore::Rename function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RenameTest4, TestSize.Level1) +{ + const std::string oldParentCloudId = "100"; + const std::string oldFileName = "test"; + const std::string newParentCloudId = ""; + const std::string newFileName = "newFileName"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Rename(oldParentCloudId, oldFileName, newParentCloudId, newFileName); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: Rename + * @tc.desc: Verify the CloudDiskRdbStore::Rename function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RenameTest5, TestSize.Level1) +{ + const std::string oldParentCloudId = "10"; + const std::string oldFileName = "mock"; + const std::string newParentCloudId = "100"; + const std::string newFileName = "newFileName"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Rename(oldParentCloudId, oldFileName, newParentCloudId, newFileName); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: Rename + * @tc.desc: Verify the CloudDiskRdbStore::Rename function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RenameTest6, TestSize.Level1) +{ + const std::string oldParentCloudId = "10"; + const std::string oldFileName = "oldFileName"; + const std::string newParentCloudId = "100"; + const std::string newFileName = ".."; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Rename(oldParentCloudId, oldFileName, newParentCloudId, newFileName); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: Rename + * @tc.desc: Verify the CloudDiskRdbStore::Rename function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RenameTest7, TestSize.Level1) +{ + const std::string oldParentCloudId = "100"; + const std::string oldFileName = "oldFileName"; + const std::string newParentCloudId = "100"; + const std::string newFileName = "mock"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Rename(oldParentCloudId, oldFileName, newParentCloudId, newFileName); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: Rename + * @tc.desc: Verify the CloudDiskRdbStore::Rename function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, RenameTest8, TestSize.Level1) +{ + const std::string oldParentCloudId = "10"; + const std::string oldFileName = "oldFileName"; + const std::string newParentCloudId = "100"; + const std::string newFileName = "mock"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Rename(oldParentCloudId, oldFileName, newParentCloudId, newFileName); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: GetHasChild + * @tc.desc: Verify the CloudDiskRdbStore::GetHasChild function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetHasChildTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + bool hasChild = true; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + int32_t ret = clouddiskrdbStore_->GetHasChild(cloudId, hasChild); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetHasChild + * @tc.desc: Verify the CloudDiskRdbStore::GetHasChild function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetHasChildTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + bool hasChild = true; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + int32_t ret = clouddiskrdbStore_->GetHasChild(cloudId, hasChild); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetHasChild + * @tc.desc: Verify the CloudDiskRdbStore::GetHasChild function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetHasChildTest3, TestSize.Level1) +{ + const std::string cloudId = "100"; + bool hasChild = true; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + int32_t ret = clouddiskrdbStore_->GetHasChild(cloudId, hasChild); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: UnlinkSynced + * @tc.desc: Verify the CloudDiskRdbStore::UnlinkSynced function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, UnlinkSyncedTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, Update(_, _, _, _, An &>())).WillOnce(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->UnlinkSynced(cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: UnlinkSynced + * @tc.desc: Verify the CloudDiskRdbStore::UnlinkSynced function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, UnlinkSyncedTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, Update(_, _, _, _, An &>())).WillOnce(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->UnlinkSynced(cloudId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: UnlinkLocal + * @tc.desc: Verify the CloudDiskRdbStore::UnlinkLocal function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, UnlinkLocalTest1, TestSize.Level1) +{ + const std::string cloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, Delete(_, _, _, An &>())).WillOnce(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->UnlinkLocal(cloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: UnlinkLocal + * @tc.desc: Verify the CloudDiskRdbStore::UnlinkLocal function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, UnlinkLocalTest2, TestSize.Level1) +{ + const std::string cloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, Delete(_, _, _, An &>())).WillOnce(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->UnlinkLocal(cloudId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: Unlink + * @tc.desc: Verify the CloudDiskRdbStore::Unlink function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, UnlinkTest1, TestSize.Level1) +{ + std::string cloudId = ""; + const int32_t noUpload = 0; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Unlink(cloudId, noUpload); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: Unlink + * @tc.desc: Verify the CloudDiskRdbStore::Unlink function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, UnlinkTest2, TestSize.Level1) +{ + const int32_t noUpload = 1; + std::string cloudId = "rootId"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->Unlink(cloudId, noUpload); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: Unlink + * @tc.desc: Verify the CloudDiskRdbStore::Unlink function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, UnlinkTest3, TestSize.Level1) +{ + const int32_t noUpload = 1; + std::string cloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, Delete(_, _, _, An &>())).WillOnce(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->Unlink(cloudId, noUpload); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: Unlink + * @tc.desc: Verify the CloudDiskRdbStore::Unlink function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, UnlinkTest4, TestSize.Level1) +{ + const int32_t noUpload = 0; + std::string cloudId = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, Update(_, _, _, _, An &>())).WillOnce(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->Unlink(cloudId, noUpload); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetDirtyType + * @tc.desc: Verify the CloudDiskRdbStore::GetDirtyType function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetDirtyTypeTest1, TestSize.Level1) +{ + int32_t dirtyType = 0; + std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetDirtyType(cloudId, dirtyType); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetDirtyType + * @tc.desc: Verify the CloudDiskRdbStore::GetDirtyType function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetDirtyTypeTest2, TestSize.Level1) +{ + int32_t dirtyType = 0; + std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetDirtyType(cloudId, dirtyType); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetDirtyType + * @tc.desc: Verify the CloudDiskRdbStore::GetDirtyType function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetDirtyTypeTest3, TestSize.Level1) +{ + int32_t dirtyType = -1; + std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetDirtyType(cloudId, dirtyType); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetDirtyType + * @tc.desc: Verify the CloudDiskRdbStore::GetDirtyType function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetDirtyTypeTest4, TestSize.Level1) +{ + int32_t dirtyType = 1; + std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetDirtyType(cloudId, dirtyType); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetCurNode + * @tc.desc: Verify the CloudDiskRdbStore::GetCurNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetCurNodeTest1, TestSize.Level1) +{ + CacheNode curNode; + std::string cloudId = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + int32_t ret = clouddiskrdbStore_->GetCurNode(cloudId, curNode); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetCurNode + * @tc.desc: Verify the CloudDiskRdbStore::GetCurNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetCurNodeTest2, TestSize.Level1) +{ + CacheNode curNode; + std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetCurNode(cloudId, curNode); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetCurNode + * @tc.desc: Verify the CloudDiskRdbStore::GetCurNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetCurNodeTest3, TestSize.Level1) +{ + CacheNode curNode; + std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetCurNode(cloudId, curNode); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetCurNode + * @tc.desc: Verify the CloudDiskRdbStore::GetCurNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetCurNodeTest4, TestSize.Level1) +{ + CacheNode curNode; + std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetCurNode(cloudId, curNode); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetCurNode + * @tc.desc: Verify the CloudDiskRdbStore::GetCurNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetCurNodeTest5, TestSize.Level1) +{ + CacheNode curNode; + std::string cloudId = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetCurNode(cloudId, curNode); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetParentNode + * @tc.desc: Verify the CloudDiskRdbStore::GetParentNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentNodeTest1, TestSize.Level1) +{ + const std::string parentCloudId = ""; + std::string nextCloudId = "100"; + std::string fileName = "test"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetParentNode(parentCloudId, nextCloudId, fileName); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetParentNode + * @tc.desc: Verify the CloudDiskRdbStore::GetParentNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentNodeTest2, TestSize.Level1) +{ + const std::string parentCloudId = "100"; + std::string nextCloudId = "100"; + std::string fileName = "test"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetParentNode(parentCloudId, nextCloudId, fileName); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetParentNode + * @tc.desc: Verify the CloudDiskRdbStore::GetParentNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentNodeTest3, TestSize.Level1) +{ + const std::string parentCloudId = "100"; + std::string nextCloudId = "100"; + std::string fileName = "test"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetParentNode(parentCloudId, nextCloudId, fileName); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetParentNode + * @tc.desc: Verify the CloudDiskRdbStore::GetParentNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentNodeTest4, TestSize.Level1) +{ + const std::string parentCloudId = "100"; + std::string nextCloudId = "100"; + std::string fileName = "test"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->GetParentNode(parentCloudId, nextCloudId, fileName); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetParentNode + * @tc.desc: Verify the CloudDiskRdbStore::GetParentNode function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetParentNodeTest5, TestSize.Level1) +{ + const std::string parentCloudId = "100"; + std::string nextCloudId = "100"; + std::string fileName = "test"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetParentNode(parentCloudId, nextCloudId, fileName); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetUriFromDB + * @tc.desc: Verify the CloudDiskRdbStore::GetUriFromDB function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetUriFromDBTest1, TestSize.Level1) +{ + const std::string parentCloudId = ""; + std::string uri = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetUriFromDB(parentCloudId, uri); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetUriFromDB + * @tc.desc: Verify the CloudDiskRdbStore::GetUriFromDB function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetUriFromDBTest2, TestSize.Level1) +{ + const std::string parentCloudId = "rootId"; + std::string uri = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->GetUriFromDB(parentCloudId, uri); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetUriFromDB + * @tc.desc: Verify the CloudDiskRdbStore::GetUriFromDB function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetUriFromDBTest3, TestSize.Level1) +{ + const std::string parentCloudId = "100"; + std::string uri = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetUriFromDB(parentCloudId, uri); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetUriFromDB + * @tc.desc: Verify the CloudDiskRdbStore::GetUriFromDB function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetUriFromDBTest4, TestSize.Level1) +{ + const std::string parentCloudId = "100"; + std::string nextCloudId = "cloudid"; + std::string uri = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillOnce(Return(E_OK)).WillRepeatedly(Return(E_RDB)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetUriFromDB(parentCloudId, uri); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetUriFromDB + * @tc.desc: Verify the CloudDiskRdbStore::GetUriFromDB function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetUriFromDBTest5, TestSize.Level1) +{ + const std::string parentCloudId = "100"; + std::string nextCloudId = "cloudid"; + std::string uri = "100"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetRow(_)).WillRepeatedly(Return(E_OK)); + + int32_t ret = clouddiskrdbStore_->GetUriFromDB(parentCloudId, uri); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetNotifyUri + * @tc.desc: Verify the CloudDiskRdbStore::GetNotifyUri function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetNotifyUriTest1, TestSize.Level1) +{ + CacheNode cacheNode; + std::string uri = "100"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = ""; + int32_t ret = clouddiskrdbStore_->GetNotifyUri(cacheNode, uri); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetNotifyUri + * @tc.desc: Verify the CloudDiskRdbStore::GetNotifyUri function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetNotifyUriTest2, TestSize.Level1) +{ + CacheNode cacheNode; + std::string uri = "test"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = "rootId"; + int32_t ret = clouddiskrdbStore_->GetNotifyUri(cacheNode, uri); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetNotifyUri + * @tc.desc: Verify the CloudDiskRdbStore::GetNotifyUri function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetNotifyUriTest3, TestSize.Level1) +{ + CacheNode cacheNode; + std::string uri = "mock"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = "rootId"; + int32_t ret = clouddiskrdbStore_->GetNotifyUri(cacheNode, uri); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetNotifyUri + * @tc.desc: Verify the CloudDiskRdbStore::GetNotifyUri function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetNotifyUriTest4, TestSize.Level1) +{ + CacheNode cacheNode; + cacheNode.parentCloudId = "root"; + std::string uri = "mock"; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = "rootId"; + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->GetNotifyUri(cacheNode, uri); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetNotifyData + * @tc.desc: Verify the CloudDiskRdbStore::GetNotifyData function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetNotifyDataTest1, TestSize.Level1) +{ + CacheNode cacheNode; + NotifyData notifyData; + notifyData.uri = "mock"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = ""; + + int32_t ret = clouddiskrdbStore_->GetNotifyData(cacheNode, notifyData); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: GetNotifyData + * @tc.desc: Verify the CloudDiskRdbStore::GetNotifyData function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, GetNotifyDataTest2, TestSize.Level1) +{ + CacheNode cacheNode; + NotifyData notifyData; + notifyData.uri = "mock"; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = "rootId"; + + int32_t ret = clouddiskrdbStore_->GetNotifyData(cacheNode, notifyData); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: CheckRootIdValid + * @tc.desc: Verify the CloudDiskRdbStore::CheckRootIdValid function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CheckRootIdValidTest1, TestSize.Level1) +{ + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = "rootId"; + + int32_t ret = clouddiskrdbStore_->CheckRootIdValid(); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: CheckRootIdValid + * @tc.desc: Verify the CloudDiskDataCallBack::CheckRootIdValid function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, CheckRootIdValidTest2, TestSize.Level1) +{ + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + clouddiskrdbStore_->rootId_ = ""; + + int32_t ret = clouddiskrdbStore_->CheckRootIdValid(); + EXPECT_EQ(ret, E_INVAL_ARG); +} + +/** + * @tc.name: OnCreate + * @tc.desc: Verify the CloudDiskDataCallBack::OnCreate function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, OnCreateTest1, TestSize.Level1) +{ + RdbStoreMock store; + RdbStoreMock* rdb = &store; + CloudDiskDataCallBack CloudDiskDataCallBack; + EXPECT_CALL(*rdb, ExecuteSql(_, _)).WillRepeatedly(Return(E_RDB)); + + int32_t ret = CloudDiskDataCallBack.OnCreate(store); + EXPECT_EQ(ret, NativeRdb::E_ERROR); +} + +/** + * @tc.name: OnCreate + * @tc.desc: Verify the CloudDiskDataCallBack::OnCreate function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, OnCreateTest2, TestSize.Level1) +{ + RdbStoreMock store; + RdbStoreMock* rdb = &store; + CloudDiskDataCallBack CloudDiskDataCallBack; + EXPECT_CALL(*rdb, ExecuteSql(_, _)).WillRepeatedly(Return(E_OK)); + + int32_t ret = CloudDiskDataCallBack.OnCreate(store); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: OnUpgrade + * @tc.desc: Verify the CloudDiskDataCallBack::OnUpgrade function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, OnUpgradeTest1, TestSize.Level1) +{ + RdbStoreMock store; + int32_t oldVersion = 13; + int32_t newVersion = 14; + CloudDiskDataCallBack CloudDiskDataCallBack; + int32_t ret = CloudDiskDataCallBack.OnUpgrade(store, oldVersion, newVersion); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: OnUpgrade + * @tc.desc: Verify the CloudDiskDataCallBack::OnUpgrade function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskRdbStoreTest, OnUpgradeTest2, TestSize.Level1) +{ + RdbStoreMock store; + int32_t oldVersion = 8; + int32_t newVersion = 14; + CloudDiskDataCallBack CloudDiskDataCallBack; + int32_t ret = CloudDiskDataCallBack.OnUpgrade(store, oldVersion, newVersion); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: CreateDentryFile + * @tc.desc: Verify the CloudDiskRdbStore::CreateDentryFile function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateDentryFileTest1, TestSize.Level1) +{ + MetaBase metaBase; + metaBase.name = "mock"; + std::string destParentCloudId = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->CreateDentryFile(metaBase, destParentCloudId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: CreateDentryFile + * @tc.desc: Verify the CloudDiskRdbStore::CreateDentryFile function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, CreateDentryFileTest2, TestSize.Level1) +{ + MetaBase metaBase; + std::string destParentCloudId = ""; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + + int32_t ret = clouddiskrdbStore_->CreateDentryFile(metaBase, destParentCloudId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: InsertCopyData + * @tc.desc: Verify the CloudDiskRdbStore::InsertCopyData function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, InsertCopyDataTest1, TestSize.Level1) +{ + std::string srcCloudId = ""; + std::string destCloudId = ""; + std::string destParentCloudId = ""; + auto rdb = make_shared(); + auto transaction = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rset, GetColumnIndex(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->InsertCopyData(srcCloudId, destCloudId, destParentCloudId, rset); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: InsertCopyData + * @tc.desc: Verify the CloudDiskRdbStore::InsertCopyData function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, InsertCopyDataTest2, TestSize.Level1) +{ + std::string srcCloudId = ""; + std::string destCloudId = ""; + std::string destParentCloudId = ""; + auto rdb = make_shared(); + auto transaction = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rset, GetColumnIndex(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(DoAll(SetArgReferee<1>("mock"), Return(E_OK))); + + int32_t ret = clouddiskrdbStore_->InsertCopyData(srcCloudId, destCloudId, destParentCloudId, rset); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: InsertCopyData + * @tc.desc: Verify the CloudDiskRdbStore::InsertCopyData function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, InsertCopyDataTest3, TestSize.Level1) +{ + std::string srcCloudId = ""; + std::string destCloudId = ""; + std::string destParentCloudId = ""; + auto rdb = make_shared(); + auto transaction = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rset, GetColumnIndex(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->InsertCopyData(srcCloudId, destCloudId, destParentCloudId, rset); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: CopyFile + * @tc.desc: Verify the CloudDiskRdbStore::CopyFile function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, CopyFileTest1, TestSize.Level1) +{ + std::string srcCloudId = ""; + std::string destCloudId = ""; + std::string bundleName = "com.ohos.photos"; + const int userId = 100; + std::string destPath = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(nullptr))); + + int32_t ret = clouddiskrdbStore_->CopyFile(srcCloudId, destCloudId, + bundleName, userId, destPath); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: CopyFile + * @tc.desc: Verify the CloudDiskRdbStore::CopyFile function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, CopyFileTest2, TestSize.Level1) +{ + std::string srcCloudId = ""; + std::string destCloudId = ""; + std::string bundleName = "com.ohos.photos"; + const int userId = 100; + std::string destPath = ""; + bool preCount = true; + auto rdb = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_RDB)); + + int32_t ret = clouddiskrdbStore_->CopyFile(srcCloudId, destCloudId, + bundleName, userId, destPath); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: CopyFile + * @tc.desc: Verify the CloudDiskRdbStore::CopyFile function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, CopyFileTest3, TestSize.Level1) +{ + std::string srcCloudId = ""; + std::string destCloudId = ""; + std::string bundleName = "com.ohos.photos"; + const int userId = 100; + std::string destPath = ""; + bool preCount = true; + auto rdb = make_shared(); + auto transaction = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetColumnIndex(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_RDB, 0))); + + int32_t ret = clouddiskrdbStore_->CopyFile(srcCloudId, destCloudId, + bundleName, userId, destPath); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: CopyFile + * @tc.desc: Verify the CloudDiskRdbStore::CopyFile function + * @tc.type: FUNC + */ +HWTEST_F(CloudDiskRdbStoreTest, CopyFileTest4, TestSize.Level1) +{ + std::string srcCloudId = ""; + std::string destCloudId = ""; + std::string bundleName = "com.ohos.photos"; + const int userId = 100; + std::string destPath = ""; + bool preCount = true; + auto rdb = make_shared(); + auto transaction = make_shared(); + clouddiskrdbStore_->rdbStore_ = rdb; + std::shared_ptr rset = std::make_shared(); + EXPECT_CALL(*rdb, QueryByStep(An(), + An &>(), preCount)).WillOnce(Return(ByMove(rset))); + EXPECT_CALL(*rdb, CreateTransaction(_)).WillOnce(Return(std::make_pair(E_OK, transaction))); + EXPECT_CALL(*rset, GoToNextRow()).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetColumnIndex(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetLong(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetInt(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*rset, GetString(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*transaction, Insert(_, _, _)).WillOnce(Return(std::make_pair(E_OK, 0))); + + int32_t ret = clouddiskrdbStore_->CopyFile(srcCloudId, destCloudId, + bundleName, userId, destPath); + EXPECT_EQ(ret, E_OK); +} +} // namespace OHOS::FileManagement::CloudDisk::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/clouddisk_sync_helper_test.cpp b/cloud_file/test/unittests/clouddisk_database/clouddisk_sync_helper_test.cpp new file mode 100644 index 0000000..d07b498 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/clouddisk_sync_helper_test.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "clouddisk_sync_helper.h" +#include "utils_log.h" +#include "dfs_error.h" +#include "common_timer_errors.h" + +namespace OHOS { +namespace FileManagement::CloudDisk { +namespace Test { +using namespace testing::ext; +using namespace std; + +constexpr int32_t MIN_USER_ID = 100; + +class CloudDiskSyncHelperTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudDiskSyncHelperTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudDiskSyncHelperTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudDiskSyncHelperTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudDiskSyncHelperTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: RegisterTriggerSyncTest001 + * @tc.desc: Verify the RegisterTriggerSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskSyncHelperTest, RegisterTriggerSyncTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterTriggerSync Start"; + string bundleName = ""; + int32_t userId = 0; + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName, userId); + GTEST_LOG_(INFO) << "RegisterTriggerSync End"; +} + +/** + * @tc.name: RegisterTriggerSyncTest002 + * @tc.desc: Verify the RegisterTriggerSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskSyncHelperTest, RegisterTriggerSyncTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterTriggerSync Start"; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName, userId); + GTEST_LOG_(INFO) << "RegisterTriggerSync End"; +} + +/** + * @tc.name: UnregisterRepeatingTriggerSyncTest001 + * @tc.desc: Verify the UnregisterRepeatingTriggerSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskSyncHelperTest, UnregisterRepeatingTriggerSyncTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterRepeatingTriggerSync Start"; + string bundleName = ""; + int32_t userId = 0; + CloudDiskSyncHelper::GetInstance().UnregisterRepeatingTriggerSync(bundleName, userId); + GTEST_LOG_(INFO) << "UnregisterRepeatingTriggerSync End"; +} + +/** + * @tc.name: UnregisterRepeatingTriggerSyncTest002 + * @tc.desc: Verify the UnregisterRepeatingTriggerSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskSyncHelperTest, UnregisterRepeatingTriggerSyncTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterRepeatingTriggerSync Start"; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + CloudDiskSyncHelper::GetInstance().UnregisterRepeatingTriggerSync(bundleName, userId); + GTEST_LOG_(INFO) << "UnregisterRepeatingTriggerSync End"; +} + +/** + * @tc.name: OnTriggerSyncCallbackTest001 + * @tc.desc: Verify the OnTriggerSyncCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskSyncHelperTest, OnTriggerSyncCallbackTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnTriggerSyncCallback Start"; + string bundleName = ""; + int32_t userId = 0; + CloudDiskSyncHelper::GetInstance().OnTriggerSyncCallback(bundleName, userId); + GTEST_LOG_(INFO) << "OnTriggerSyncCallback End"; +} + +/** + * @tc.name: OnTriggerSyncCallbackTest002 + * @tc.desc: Verify the OnTriggerSyncCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDiskSyncHelperTest, OnTriggerSyncCallbackTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnTriggerSyncCallback Start"; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + CloudDiskSyncHelper::GetInstance().OnTriggerSyncCallback(bundleName, userId); + GTEST_LOG_(INFO) << "OnTriggerSyncCallback End"; +} +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/include/clouddisk_rdbstore_mock.h b/cloud_file/test/unittests/clouddisk_database/include/clouddisk_rdbstore_mock.h new file mode 100644 index 0000000..e9ed69a --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/include/clouddisk_rdbstore_mock.h @@ -0,0 +1,210 @@ +/* + * 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 OHOS_CLOUDDISK_RDBSTORE_MOCK_H +#define OHOS_CLOUDDISK_RDBSTORE_MOCK_H + +#include "abs_rdb_predicates.h" +#include "rdb_helper.h" +#include "result_set.h" +#include "value_object.h" +#include "values_bucket.h" + +#include +#include + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace NativeRdb; +class RdbStoreMock final : public NativeRdb::RdbStore { +public: + MOCK_METHOD3(Insert, int(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues)); + MOCK_METHOD3(BatchInsert, + int(int64_t &outInsertNum, + const std::string &table, + const std::vector &initialBatchValues)); + MOCK_METHOD3(Replace, int(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues)); + MOCK_METHOD4(InsertWithConflictResolution, + int(int64_t &outRowId, + const std::string &table, + const ValuesBucket &initialValues, + ConflictResolution conflictResolution)); + MOCK_METHOD5(Update, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &whereArgs)); + MOCK_METHOD5(Update, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &bindArgs)); + + MOCK_METHOD6(UpdateWithConflictResolution, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &whereArgs, + ConflictResolution conflictResolution)); + + MOCK_METHOD6(UpdateWithConflictResolution, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &bindArgs, + ConflictResolution conflictResolution)); + + MOCK_METHOD4(Delete, + int(int &deletedRows, + const std::string &table, + const std::string &whereClause, + const std::vector &whereArgs)); + + MOCK_METHOD4(Delete, + int(int &deletedRows, + const std::string &table, + const std::string &whereClause, + const std::vector &bindArgs)); + + MOCK_METHOD2(ExecuteSql, int(const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteAndGetLong, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteAndGetString, + int(std::string &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteForLastInsertedRowId, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteForChangedRowCount, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD2(Backup, int(const std::string &databasePath, const std::vector &destEncryptKey)); + + MOCK_METHOD3(Attach, + int(const std::string &alias, const std::string &pathName, const std::vector destEncryptKey)); + + MOCK_METHOD2(Count, int(int64_t &outValue, const AbsRdbPredicates &predicates)); + MOCK_METHOD2(Query, + std::shared_ptr(const AbsRdbPredicates &predicates, + const std::vector &columns)); + + MOCK_METHOD11(Query, + std::shared_ptr(int &errCode, + bool distinct, + const std::string &table, + const std::vector &columns, + const std::string &whereClause, + const std::vector &bindArgs, + const std::string &groupBy, + const std::string &indexName, + const std::string &orderBy, + const int &limit, + const int &offset)); + MOCK_METHOD2(QuerySql, + std::shared_ptr(const std::string &sql, + const std::vector &selectionArgs)); + MOCK_METHOD2(QuerySql, + std::shared_ptr(const std::string &sql, + const std::vector &bindArgs)); + MOCK_METHOD2(QueryByStep, + std::shared_ptr(const std::string &sql, const std::vector &selectionArgs)); + MOCK_METHOD3(QueryByStep, + std::shared_ptr(const std::string &sql, const std::vector &bindArgs, + bool preCount)); + + MOCK_METHOD3(QueryByStep, + std::shared_ptr(const AbsRdbPredicates &predicates, + const std::vector &columns, bool preCount)); + + MOCK_METHOD4(RemoteQuery, + std::shared_ptr(const std::string &device, + const AbsRdbPredicates &predicates, + const std::vector &columns, + int &errCode)); + + MOCK_METHOD3(GetModifyTime, ModifyTime(const std::string &table, const std::string &columnName, + std::vector &keys)); + + MOCK_METHOD3(SetDistributedTables, int(const std::vector &tables, int32_t type, + const DistributedRdb::DistributedConfig &distributedConfig)); + MOCK_METHOD3(ObtainDistributedTableName, + std::string(const std::string &device, const std::string &table, int &errCode)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncBrief& async)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncDetail& async)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const std::vector& tables, const AsyncDetail& async)); + MOCK_METHOD2(Subscribe, int(const SubscribeOption &option, RdbStoreObserver *observer)); + MOCK_METHOD2(UnSubscribe, int(const SubscribeOption &option, RdbStoreObserver *observer)); + MOCK_METHOD1(RegisterAutoSyncCallback, int(std::shared_ptr syncObserver)); + MOCK_METHOD1(UnregisterAutoSyncCallback, int(std::shared_ptr syncObserver)); + MOCK_METHOD2(CleanDirtyData, int(const std::string &table, uint64_t cursor)); + MOCK_METHOD1(Notify, int(const std::string &event)); + MOCK_METHOD2(DropDeviceData, bool(const std::vector &devices, const DropOption &option)); + MOCK_METHOD3(Update, int(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates)); + MOCK_METHOD2(Delete, int(int &deletedRows, const AbsRdbPredicates &predicates)); + MOCK_METHOD1(GetVersion, int(int &version)); + MOCK_METHOD1(SetVersion, int(int version)); + MOCK_METHOD0(BeginTransaction, int()); + MOCK_METHOD0(RollBack, int()); + MOCK_METHOD0(Commit, int()); + MOCK_METHOD0(IsInTransaction, bool()); + MOCK_METHOD0(GetPath, std::string()); + MOCK_METHOD0(IsHoldingConnection, bool()); + MOCK_CONST_METHOD0(IsOpen, bool()); + MOCK_CONST_METHOD0(IsReadOnly, bool()); + MOCK_CONST_METHOD0(IsMemoryRdb, bool()); + MOCK_METHOD2(Restore, int(const std::string &backupPath, const std::vector &newKey)); + MOCK_METHOD1(GetRebuilt, int(RebuiltType &rebuilt)); + MOCK_METHOD1(CreateTransaction, std::pair>(int32_t type)); +}; + +class transactionMock final : public NativeRdb::Transaction { +public: + MOCK_METHOD0(Commit, int32_t()); + MOCK_METHOD0(Rollback, int32_t()); + MOCK_METHOD0(Close, int32_t()); + MOCK_METHOD3(Insert, std::pair(const std::string &table, + const Row &row, + Resolution resolution)); + MOCK_METHOD2(BatchInsert, std::pair(const std::string &table, const Rows &rows)); + MOCK_METHOD2(BatchInsert, std::pair(const std::string &table, const RefRows &rows)); + MOCK_METHOD3(BatchInsertWithConflictResolution, std::pair(const std::string &table, + const RefRows &rows, Resolution resolution)); + MOCK_METHOD5(Update, std::pair(const std::string &table, + const Row &row, + const std::string &where, + const Values &args, + Resolution resolution)); + MOCK_METHOD3(Update, std::pair(const Row &row, + const AbsRdbPredicates &predicates, + Resolution resolution)); + MOCK_METHOD3(Delete, std::pair(const std::string &table, + const std::string &whereClause, + const Values &args)); + MOCK_METHOD1(Delete, std::pair(const AbsRdbPredicates &predicates)); + MOCK_METHOD3(QueryByStep, std::shared_ptr(const std::string &sql, const Values &args, bool preCount)); + MOCK_METHOD3(QueryByStep, std::shared_ptr(const AbsRdbPredicates &predicates, + const Fields &columns, bool preCount)); + MOCK_METHOD2(Execute, std::pair(const std::string &sql, const Values &args)); +}; +} // namespace OHOS::FileManagement::CloudSync::Test +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/include/clouddisk_resultset_mock.h b/cloud_file/test/unittests/clouddisk_database/include/clouddisk_resultset_mock.h new file mode 100644 index 0000000..bcd2506 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/include/clouddisk_resultset_mock.h @@ -0,0 +1,68 @@ +/* + * 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 OHOS_CLOUD_DISK_CLOUDDISK_RESULTSET_MOCK_H +#define OHOS_CLOUD_DISK_CLOUDDISK_RESULTSET_MOCK_H + +#include "result_set.h" + +#include +#include +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace NativeRdb; +class ResultSetMock : public ResultSet { +public: + ~ResultSetMock() {} + MOCK_METHOD1(GetAllColumnNames, int(std::vector &)); + MOCK_METHOD1(GetColumnCount, int(int &)); + MOCK_METHOD2(GetColumnType, int(int, ColumnType &)); + MOCK_METHOD2(GetColumnIndex, int(const std::string &, int &)); + MOCK_METHOD2(GetColumnName, int(int, std::string &)); + MOCK_METHOD1(GetRowCount, int(int &)); + MOCK_METHOD1(GoTo, int(int)); + MOCK_METHOD1(GoToRow, int(int)); + MOCK_METHOD0(GoToFirstRow, int()); + MOCK_METHOD0(GoToLastRow, int()); + MOCK_METHOD0(GoToNextRow, int()); + MOCK_METHOD0(GoToPreviousRow, int()); + MOCK_METHOD1(IsEnded, int(bool &)); + MOCK_METHOD1(IsAtLastRow, int(bool &)); + MOCK_METHOD2(GetBlob, int(int, std::vector &)); + MOCK_METHOD2(GetString, int(int, std::string &)); + MOCK_METHOD2(GetInt, int(int, int &)); + MOCK_METHOD2(GetLong, int(int, int64_t &)); + MOCK_METHOD2(GetDouble, int(int, double &)); + MOCK_METHOD2(IsColumnNull, int(int, bool &)); + MOCK_METHOD0(Close, int()); + MOCK_METHOD1(GetRow, int(RowEntity &)); + MOCK_METHOD2(ResultSetToFileInfo, int(shared_ptr, CloudDiskFileInfo &)); + MOCK_METHOD2(ResultSetToFileInfos, int(shared_ptr, vector &)); + + MOCK_CONST_METHOD0(IsClosed, bool()); + MOCK_CONST_METHOD1(GetRowIndex, int(int &)); + MOCK_CONST_METHOD1(IsStarted, int(bool &)); + MOCK_CONST_METHOD1(IsAtFirstRow, int(bool &)); + + MOCK_METHOD2(GetAsset, int(int32_t, ValueObject::Asset &)); + MOCK_METHOD2(GetAssets, int(int32_t, ValueObject::Assets &)); + MOCK_METHOD2(Get, int(int32_t, ValueObject &)); + MOCK_METHOD1(GetModifyTime, int(std::string &)); + MOCK_METHOD2(GetSize, int(int32_t, size_t &)); +}; +} // namespace OHOS::FileManagement::CloudSync::Test +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/include/result_set_mock.h b/cloud_file/test/unittests/clouddisk_database/include/result_set_mock.h new file mode 100644 index 0000000..d67af10 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/include/result_set_mock.h @@ -0,0 +1,66 @@ +/* + * 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 OHOS_CLOUD_DISK_DATABASE_RESULT_SET_MOCK_H +#define OHOS_CLOUD_DISK_DATABASE_RESULT_SET_MOCK_H + +#include "result_set.h" + +#include +#include +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace NativeRdb; +class ResultSetMock : public ResultSet { +public: + ~ResultSetMock() {} + MOCK_METHOD1(GetAllColumnNames, int(std::vector &)); + MOCK_METHOD1(GetColumnCount, int(int &)); + MOCK_METHOD2(GetColumnType, int(int, ColumnType &)); + MOCK_METHOD2(GetColumnIndex, int(const std::string &, int &)); + MOCK_METHOD2(GetColumnName, int(int, std::string &)); + MOCK_METHOD1(GetRowCount, int(int &)); + MOCK_METHOD1(GoTo, int(int)); + MOCK_METHOD1(GoToRow, int(int)); + MOCK_METHOD0(GoToFirstRow, int()); + MOCK_METHOD0(GoToLastRow, int()); + MOCK_METHOD0(GoToNextRow, int()); + MOCK_METHOD0(GoToPreviousRow, int()); + MOCK_METHOD1(IsEnded, int(bool &)); + MOCK_METHOD1(IsAtLastRow, int(bool &)); + MOCK_METHOD2(GetBlob, int(int, std::vector &)); + MOCK_METHOD2(GetString, int(int, std::string &)); + MOCK_METHOD2(GetInt, int(int, int &)); + MOCK_METHOD2(GetLong, int(int, int64_t &)); + MOCK_METHOD2(GetDouble, int(int, double &)); + MOCK_METHOD2(IsColumnNull, int(int, bool &)); + MOCK_METHOD0(Close, int()); + MOCK_METHOD1(GetRow, int(RowEntity &)); + + MOCK_CONST_METHOD0(IsClosed, bool()); + MOCK_CONST_METHOD1(GetRowIndex, int(int &)); + MOCK_CONST_METHOD1(IsStarted, int(bool &)); + MOCK_CONST_METHOD1(IsAtFirstRow, int(bool &)); + + MOCK_METHOD2(GetAsset, int(int32_t, ValueObject::Asset &)); + MOCK_METHOD2(GetAssets, int(int32_t, ValueObject::Assets &)); + MOCK_METHOD2(Get, int(int32_t, ValueObject &)); + MOCK_METHOD1(GetModifyTime, int(std::string &)); + MOCK_METHOD2(GetSize, int(int32_t, size_t &)); +}; +} // namespace OHOS::FileManagement::CloudDisk::Test +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_notify_utils_mock.cpp b/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_notify_utils_mock.cpp new file mode 100644 index 0000000..fc0e8dd --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_notify_utils_mock.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2024 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 "clouddisk_notify_utils.h" +#include "clouddisk_rdb_utils.h" +#include "file_column.h" +#include "cloud_pref_impl.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudDisk { +const uint32_t MAX_QUERY_TIMES = 1024; +const string BUNDLENAME_FLAG = ""; +const string CLOUDDISK_URI_PREFIX = "file:///data/storage/el2/cloud"; +const string BACKFLASH = "/"; +const int32_t MOCKUSERID = 10; +const int32_t CloudDiskNotifyUtils::maxCacheCnt_; +list> CloudDiskNotifyUtils::cacheList_; +unordered_map>::iterator> CloudDiskNotifyUtils::cacheMap_; +mutex CloudDiskNotifyUtils::cacheMutex_; + +static bool isRoot(const fuse_ino_t &ino) +{ + return ino == FUSE_ROOT_ID; +} + +static int32_t GetUriRecursively(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + shared_ptr inoPtr, string &uri) +{ + string bundleName = inoPtr->bundleName; + string realPrefix = CLOUDDISK_URI_PREFIX; + realPrefix.replace(realPrefix.find(BUNDLENAME_FLAG), BUNDLENAME_FLAG.length(), bundleName); + uint32_t queryTimes = 0; + while (!isRoot(inoPtr->parent)) { + inoPtr = func(data, inoPtr->parent); + if (!inoPtr || inoPtr->fileName.empty()) { + break; + } + uri = inoPtr->fileName + BACKFLASH + uri; + queryTimes++; + if (uri.length() > PATH_MAX || queryTimes > MAX_QUERY_TIMES) { + return E_INVAL_ARG; + } + } + uri = realPrefix + BACKFLASH + uri; + LOGD("GetUriRecursively uri: %{public}s", GetAnonyString(uri).c_str()); + return E_OK; +} + +int32_t CloudDiskNotifyUtils::GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + const fuse_ino_t &ino, NotifyData ¬ifyData) +{ + if (data->userId == MOCKUSERID) { + LOGI("AAA"); + return E_INVAL_ARG; + } + return E_OK; +} + +int32_t CloudDiskNotifyUtils::GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + const fuse_ino_t &parent, const string &name, NotifyData ¬ifyData) +{ + if (data->userId == MOCKUSERID || name == "mock") { + return E_INVAL_ARG; + } + return E_OK; +} + +int32_t CloudDiskNotifyUtils::GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + shared_ptr inoPtr, NotifyData ¬ifyData) +{ + if (data->userId == MOCKUSERID) { + return E_INVAL_ARG; + } + return E_OK; +} + +int32_t CloudDiskNotifyUtils::GetNotifyData(CloudDiskFuseData* data, FindCloudDiskInodeFunc func, + shared_ptr pInoPtr, const string &name, NotifyData ¬ifyData) +{ + if (data->userId == MOCKUSERID || name == "mock") { + return E_INVAL_ARG; + } + return E_OK; +} + +int32_t CloudDiskNotifyUtils::GetCacheNode(const string &cloudId, CacheNode &cacheNode) +{ + lock_guard lock(cacheMutex_); + auto it = cacheMap_.find(cloudId); + if (it == cacheMap_.end()) { + LOGI("Not fount in cache, id: %{public}s", cloudId.c_str()); + return E_INVAL_ARG; + } + cacheList_.splice(cacheList_.begin(), cacheList_, it->second); + cacheNode = it->second->second; + return E_OK; +} + +void CloudDiskNotifyUtils::PutCacheNode(const string &cloudId, const CacheNode &cacheNode) +{ + if (cacheNode.isDir != TYPE_DIR_STR) { + return; + } + lock_guard lock(cacheMutex_); + auto it = cacheMap_.find(cloudId); + if (it != cacheMap_.end()) { + LOGD("update cache name: %{public}s", GetAnonyString(cacheNode.fileName).c_str()); + it->second->second = cacheNode; + cacheList_.splice(cacheList_.begin(), cacheList_, it->second); + return; + } + if (cacheMap_.size() == maxCacheCnt_) { + LOGI("upto max, delete last one"); + string deleteCloudId = cacheList_.back().first; + cacheList_.pop_back(); + cacheMap_.erase(deleteCloudId); + } + LOGD("insert to cache name: %{public}s", GetAnonyString(cacheNode.fileName).c_str()); + cacheList_.emplace_front(cloudId, cacheNode); + cacheMap_[cloudId] = cacheList_.begin(); +} + +int32_t CloudDiskNotifyUtils::GetUriFromCache(const string &bundleName, + const string &rootId, + const CacheNode &cacheNode, + string &uri) +{ + if (uri == "mock") { + return E_RDB; + } + return E_OK; +} +} // namespace OHOS::FileManagement::CloudDisk \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_rdb_transaction_mock.cpp b/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_rdb_transaction_mock.cpp new file mode 100644 index 0000000..4d220ef --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_rdb_transaction_mock.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2024 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 "clouddisk_rdb_transaction.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; + +constexpr int32_t E_HAS_DB_ERROR = -222; +constexpr int32_t E_OK = 0; + +constexpr int RDB_TRANSACTION_WAIT_MS = 1000; +constexpr int32_t MAX_TRY_TIMES = 5; +constexpr int32_t TRANSACTION_WAIT_INTERVAL = 50; // in milliseconds. + +TransactionOperations::TransactionOperations( + const shared_ptr &rdbStore) : rdbStore_(rdbStore) {} + +TransactionOperations::~TransactionOperations() +{ + if (isStart && !isFinish) { + LOGI("TransactionOperations::RollBack"); + TransactionRollback(); + } +} + +std::pair> TransactionOperations::Start( + NativeRdb::Transaction::TransactionType type) +{ + auto [errCode, transaction] = rdbStore_->CreateTransaction(type); + return make_pair(errCode, transaction); +} + +void TransactionOperations::Finish() +{ +} + +int32_t TransactionOperations::BeginTransaction( + NativeRdb::Transaction::TransactionType type) +{ + return E_OK; +} + +int32_t TransactionOperations::TransactionCommit() +{ + return E_OK; +} + +int32_t TransactionOperations::TransactionRollback() +{ + return E_OK; +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_rdb_utils_mock.cpp b/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_rdb_utils_mock.cpp new file mode 100644 index 0000000..36170a9 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/mock/clouddisk_rdb_utils_mock.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2024 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. + */ + +#define FUSE_USE_VERSION 34 + +#include "clouddisk_rdb_utils.h" + +#include + +#include "utils_log.h" +#include "dfs_error.h" +#include "clouddisk_db_const.h" +#include "file_column.h" +#include "result_set.h" + +namespace OHOS::FileManagement::CloudDisk { +using namespace std; +using namespace NativeRdb; + +static const int32_t LOCAL_ID_OFFSET = 100; + +int32_t CloudDiskRdbUtils::GetInt(const string &key, int32_t &val, + const shared_ptr resultSet) +{ + if (val == -1) { + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskRdbUtils::GetLong(const string &key, int64_t &val, + const shared_ptr resultSet) +{ + return E_OK; +} + +int32_t CloudDiskRdbUtils::GetString(const string &key, string &val, + const shared_ptr resultSet) +{ + if (val == "mock") { + return E_RDB; + } + return E_OK; +} + +static void FillFileInfo(const RowEntity &rowEntity, CloudDiskFileInfo &info) +{ + rowEntity.Get(FileColumn::FILE_NAME).GetString(info.name); + rowEntity.Get(FileColumn::CLOUD_ID).GetString(info.cloudId); + rowEntity.Get(FileColumn::PARENT_CLOUD_ID).GetString(info.parentCloudId); + int32_t int_variable; + rowEntity.Get(FileColumn::POSITION).GetInt(int_variable); + info.location = static_cast(int_variable); + int64_t long_variable; + rowEntity.Get(FileColumn::FILE_SIZE).GetLong(long_variable); + info.size = static_cast(long_variable); + rowEntity.Get(FileColumn::FILE_TIME_ADDED).GetLong(long_variable); + info.atime = static_cast(long_variable); + rowEntity.Get(FileColumn::META_TIME_EDITED).GetLong(long_variable); + info.ctime = static_cast(long_variable); + rowEntity.Get(FileColumn::FILE_TIME_EDITED).GetLong(long_variable); + info.mtime = static_cast(long_variable); + rowEntity.Get(FileColumn::IS_DIRECTORY).GetInt(int_variable); + info.IsDirectory = (int_variable == DIRECTORY); + rowEntity.Get(FileColumn::ROW_ID).GetLong(long_variable); + info.localId = static_cast(long_variable) + LOCAL_ID_OFFSET; +} + +int32_t CloudDiskRdbUtils::ResultSetToFileInfo(const shared_ptr resultSet, + CloudDiskFileInfo &info) +{ + if (info.name == "mock") { + return E_RDB; + } + return E_OK; +} + +size_t CloudDiskRdbUtils::FuseDentryAlignSize(const char *name) +{ + return fuse_add_direntry({}, nullptr, 0, name, nullptr, 0); +} + +int32_t CloudDiskRdbUtils::ResultSetToFileInfos(const shared_ptr resultSet, + vector &infos) +{ + if (infos.empty()) { + return E_RDB; + } + return E_OK; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/mock/meta_file_clouddisk_mock.cpp b/cloud_file/test/unittests/clouddisk_database/mock/meta_file_clouddisk_mock.cpp new file mode 100644 index 0000000..8d18ad3 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/mock/meta_file_clouddisk_mock.cpp @@ -0,0 +1,580 @@ +/* + * Copyright (c) 2024 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 "meta_file.h" + +#include +#include +#include +#include +#include + +#include "cloud_file_utils.h" +#include "dfs_error.h" +#include "file_utils.h" +#include "securec.h" +#include "string_ex.h" +#include "sys/xattr.h" +#include "utils_directory.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +constexpr uint32_t DENTRYGROUP_SIZE = 4096; +constexpr uint32_t DENTRY_NAME_LEN = 8; +constexpr uint32_t DENTRY_RESERVED_LENGTH = 4; +constexpr uint32_t DENTRY_PER_GROUP = 52; +constexpr uint32_t DENTRY_BITMAP_LENGTH = 7; +constexpr uint32_t DENTRY_GROUP_RESERVED = 32; +constexpr uint32_t CLOUD_RECORD_ID_LEN = 33; +constexpr uint32_t DENTRYGROUP_HEADER = 4096; +constexpr uint32_t MAX_BUCKET_LEVEL = 63; +constexpr uint32_t BUCKET_BLOCKS = 2; +constexpr uint32_t BITS_PER_BYTE = 8; +constexpr uint32_t HMDFS_SLOT_LEN_BITS = 3; +constexpr uint64_t DELTA = 0x9E3779B9; /* Hashing code copied from f2fs */ +constexpr uint64_t HMDFS_HASH_COL_BIT = (0x1ULL) << 63; +constexpr uint32_t FILE_TYPE_OFFSET = 2; + +#pragma pack(push, 1) +struct HmdfsDentry { + uint32_t hash{0}; + uint16_t mode{0}; + uint16_t namelen{0}; + uint64_t size{0}; + uint64_t mtime{0}; + uint64_t atime{0}; + uint8_t recordId[CLOUD_RECORD_ID_LEN]{0}; +}; + +struct HmdfsDentryGroup { + uint8_t dentryVersion; + uint8_t bitmap[DENTRY_BITMAP_LENGTH]; + struct HmdfsDentry nsl[DENTRY_PER_GROUP]; + uint8_t fileName[DENTRY_PER_GROUP][DENTRY_NAME_LEN]; + uint8_t reserved[DENTRY_GROUP_RESERVED]; +}; +#pragma pack(pop) + +void MetaHelper::SetFileType(struct HmdfsDentry *de, uint8_t fileType) +{ +} + +void MetaHelper::SetPosition(struct HmdfsDentry *de, uint8_t position) +{ +} + +uint8_t MetaHelper::GetFileType(const struct HmdfsDentry *de) +{ + return 0; +} + +uint8_t MetaHelper::GetPosition(const struct HmdfsDentry *de) +{ + return 0; +} + +static std::string GetCloudDiskDentryFileByPath(uint32_t userId, const std::string &bundleName, + const std::string &cloudId) +{ + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + + "/hmdfs/cloud/data/" + bundleName + "/" + + std::to_string(CloudDisk::CloudFileUtils::GetBucketId(cloudId)) + "/"; + std::string dentryFileName = MetaFileMgr::GetInstance().CloudIdToRecordId(cloudId); + Storage::DistributedFile::Utils::ForceCreateDirectory(cacheDir, STAT_MODE_DIR); + return cacheDir + dentryFileName; +} + +CloudDiskMetaFile::CloudDiskMetaFile(uint32_t userId, const std::string &bundleName, const std::string &cloudId) +{ +} + +std::string CloudDiskMetaFile::GetDentryFilePath() +{ + return cacheFile_; +} + +int32_t CloudDiskMetaFile::DoLookupAndUpdate(const std::string &name, CloudDiskMetaFileCallBack callback) +{ + if (name == "mock") { + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoLookupAndCreate(const std::string &name, CloudDiskMetaFileCallBack metaFileCallBack) +{ + if (name == "mock") { + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoChildUpdate(const std::string &name, CloudDiskMetaFileCallBack callback) +{ + if (name == "mock") { + return E_RDB; + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoLookupAndRemove(MetaBase &metaBase) +{ + /* lookup and remove in parent */ + int32_t ret = DoLookup(metaBase); + if (ret == E_OK) { + ret = DoRemove(metaBase); + if (ret != E_OK) { + LOGE("remove dentry file failed, ret %{public}d", ret); + return ret; + } + return E_OK; + } + return E_OK; +} + +CloudDiskMetaFile::~CloudDiskMetaFile() +{ +} + +static bool IsDotDotdot(const std::string &name) +{ + return name == "." || name == ".."; +} + +static void Str2HashBuf(const char *msg, size_t len, uint32_t *buf, int num) +{ + uint32_t pad = static_cast(len) | (static_cast(len) << 8); + pad |= pad << 16; /* hash pad length 16 */ + + uint32_t val = pad; + len = std::min(len, static_cast(num * sizeof(int))); + for (uint32_t i = 0; i < len; i++) { + if ((i % sizeof(int)) == 0) { + val = pad; + } + uint8_t c = static_cast(tolower(msg[i])); + val = c + (val << 8); /* hash shift size 8 */ + if ((i % 4) == 3) { /* msg size 4, shift when 3 */ + *buf++ = val; + val = pad; + num--; + } + } + if (--num >= 0) { + *buf++ = val; + } + while (--num >= 0) { + *buf++ = pad; + } +} + +static void TeaTransform(uint32_t buf[4], uint32_t const in[]) __attribute__((no_sanitize("unsigned-integer-overflow"))) +{ + int n = 16; /* transform total rounds 16 */ + uint32_t a = in[0]; /* transform input pos 0 */ + uint32_t b = in[1]; /* transform input pos 1 */ + uint32_t c = in[2]; /* transform input pos 2 */ + uint32_t d = in[3]; /* transform input pos 3 */ + uint32_t b0 = buf[0]; /* buf pos 0 */ + uint32_t b1 = buf[1]; /* buf pos 1 */ + uint32_t sum = 0; + + do { + sum += DELTA; + b0 += ((b1 << 4) + a) ^ (b1 + sum) ^ ((b1 >> 5) + b); /* tea transform width 4 and 5 */ + b1 += ((b0 << 4) + c) ^ (b0 + sum) ^ ((b0 >> 5) + d); /* tea transform width 4 and 5 */ + } while (--n); + + buf[0] += b0; + buf[1] += b1; +} + +static uint32_t DentryHash(const std::string &name) +{ + if (IsDotDotdot(name)) { + return 0; + } + + constexpr int inLen = 8; /* hash input buf size 8 */ + constexpr int bufLen = 4; /* hash output buf size 4 */ + uint32_t in[inLen]; + uint32_t buf[bufLen]; + auto len = name.length(); + constexpr decltype(len) hashWidth = 16; /* hash operation width 4 */ + const char *p = name.c_str(); + + buf[0] = 0x67452301; /* hash magic 1 */ + buf[1] = 0xefcdab89; /* hash magic 2 */ + buf[2] = 0x98badcfe; /* hash magic 3 */ + buf[3] = 0x10325476; /* hash magic 4 */ + + bool loopFlag = true; + while (loopFlag) { + Str2HashBuf(p, len, in, bufLen); + TeaTransform(buf, in); + + if (len <= hashWidth) { + break; + } + + p += hashWidth; + len -= hashWidth; + }; + uint32_t hash = buf[0]; + uint32_t hmdfsHash = hash & ~HMDFS_HASH_COL_BIT; + + return hmdfsHash; +} + +static inline uint32_t GetDentrySlots(size_t nameLen) +{ + return static_cast((nameLen + BITS_PER_BYTE - 1) >> HMDFS_SLOT_LEN_BITS); +} + +static inline off_t GetDentryGroupPos(size_t bidx) +{ + return bidx * DENTRYGROUP_SIZE + DENTRYGROUP_HEADER; +} + +static inline uint64_t GetDentryGroupCnt(uint64_t size) +{ + return (size >= DENTRYGROUP_HEADER) ? ((size - DENTRYGROUP_HEADER) / DENTRYGROUP_SIZE) : 0; +} + +static uint32_t GetOverallBucket(uint32_t level) +{ + if (level >= MAX_BUCKET_LEVEL) { + LOGD("level = %{public}d overflow", level); + return 0; + } + uint64_t buckets = (1ULL << (level + 1)) - 1; + return static_cast(buckets); +} + +static size_t GetDcacheFileSize(uint32_t level) +{ + size_t buckets = GetOverallBucket(level); + return buckets * DENTRYGROUP_SIZE * BUCKET_BLOCKS + DENTRYGROUP_HEADER; +} + +static uint32_t GetBucketaddr(uint32_t level, uint32_t buckoffset) +{ + if (level >= MAX_BUCKET_LEVEL) { + return 0; + } + + uint64_t curLevelMaxBucks = (1ULL << level); + if (buckoffset >= curLevelMaxBucks) { + return 0; + } + + return static_cast(curLevelMaxBucks) + buckoffset - 1; +} + +static uint32_t GetBucketByLevel(uint32_t level) +{ + if (level >= MAX_BUCKET_LEVEL) { + LOGD("level = %{public}d overflow", level); + return 0; + } + + uint64_t buckets = (1ULL << level); + return static_cast(buckets); +} + +static uint32_t RoomForFilename(const uint8_t bitmap[], size_t slots, uint32_t maxSlots) +{ + uint32_t bitStart = 0; + bool loopFlag = true; + while (loopFlag) { + uint32_t zeroStart = BitOps::FindNextZeroBit(bitmap, maxSlots, bitStart); + if (zeroStart >= maxSlots) { + return maxSlots; + } + + uint32_t zeroEnd = BitOps::FindNextBit(bitmap, maxSlots, zeroStart); + if (zeroEnd - zeroStart >= slots) { + return zeroStart; + } + + bitStart = zeroEnd + 1; + if (zeroEnd + 1 >= maxSlots) { + return maxSlots; + } + } + return 0; +} + +static void UpdateDentry(HmdfsDentryGroup &d, const MetaBase &base, uint32_t nameHash, uint32_t bitPos) +{ + HmdfsDentry *de; + const std::string name = base.name; + uint32_t slots = GetDentrySlots(name.length()); + + de = &d.nsl[bitPos]; + de->hash = nameHash; + de->namelen = name.length(); + auto ret = memcpy_s(d.fileName[bitPos], slots * DENTRY_NAME_LEN, name.c_str(), name.length()); + if (ret != 0) { + LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", slots * DENTRY_NAME_LEN, name.length()); + } + de->atime = base.atime; + de->mtime = base.mtime; + de->size = base.size; + de->mode = base.mode; + MetaHelper::SetPosition(de, base.position); + MetaHelper::SetFileType(de, base.fileType); + (void) memset_s(de->recordId, CLOUD_RECORD_ID_LEN, 0, CLOUD_RECORD_ID_LEN); + ret = memcpy_s(de->recordId, CLOUD_RECORD_ID_LEN, base.cloudId.c_str(), base.cloudId.length()); + if (ret != 0) { + LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", CLOUD_RECORD_ID_LEN, base.cloudId.length()); + } + + for (uint32_t i = 0; i < slots; i++) { + BitOps::SetBit(bitPos + i, d.bitmap); + if (i) { + (de + i)->namelen = 0; + } + } +} + +int32_t CloudDiskMetaFile::HandleFileByFd(unsigned long &endBlock, uint32_t &level) +{ + return E_OK; +} + +static unsigned long GetBidxFromLevel(uint32_t level, uint32_t namehash) +{ + uint32_t bucket = GetBucketByLevel(level); + if (bucket == 0) { + return 0; + } + return BUCKET_BLOCKS * GetBucketaddr(level, namehash % bucket); +} + +int32_t CloudDiskMetaFile::DoCreate(const MetaBase &base) +{ + return E_OK; +} + +struct DcacheLookupCtx { + int fd{-1}; + std::string name{}; + uint32_t hash{0}; + uint32_t bidx{0}; + std::unique_ptr page{nullptr}; +}; + +static void InitDcacheLookupCtx(DcacheLookupCtx *ctx, const MetaBase &base, int fd) +{ + ctx->fd = fd; + ctx->name = base.name; + ctx->bidx = 0; + ctx->page = nullptr; + ctx->hash = DentryHash(ctx->name); +} + +static std::unique_ptr FindDentryPage(uint64_t index, DcacheLookupCtx *ctx) +{ + auto dentryBlk = std::make_unique(); + + off_t pos = GetDentryGroupPos(index); + ssize_t size = FileUtils::ReadFile(ctx->fd, pos, DENTRYGROUP_SIZE, dentryBlk.get()); + if (size != DENTRYGROUP_SIZE) { + return nullptr; + } + return dentryBlk; +} + +static HmdfsDentry *FindInBlock(HmdfsDentryGroup &dentryBlk, uint32_t namehash, const std::string &name) +{ + int maxLen = 0; + uint32_t bitPos = 0; + HmdfsDentry *de = nullptr; + + while (bitPos < DENTRY_PER_GROUP) { + if (!BitOps::TestBit(bitPos, dentryBlk.bitmap)) { + bitPos++; + maxLen++; + continue; + } + de = &dentryBlk.nsl[bitPos]; + if (!de->namelen) { + bitPos++; + continue; + } + + if (de->hash == namehash && de->namelen == name.length() && + !memcmp(name.c_str(), dentryBlk.fileName[bitPos], de->namelen)) { + return de; + } + maxLen = 0; + bitPos += GetDentrySlots(de->namelen); + } + + return nullptr; +} + +static HmdfsDentry *InLevel(uint32_t level, DcacheLookupCtx *ctx) + __attribute__((no_sanitize("unsigned-integer-overflow"))) +{ + HmdfsDentry *de = nullptr; + + uint32_t nbucket = GetBucketByLevel(level); + if (nbucket == 0) { + return de; + } + + uint32_t bidx = GetBucketaddr(level, ctx->hash % nbucket) * BUCKET_BLOCKS; + uint32_t endBlock = bidx + BUCKET_BLOCKS; + + for (; bidx < endBlock; bidx++) { + auto dentryBlk = FindDentryPage(bidx, ctx); + if (dentryBlk == nullptr) { + break; + } + + de = FindInBlock(*dentryBlk, ctx->hash, ctx->name); + if (de != nullptr) { + ctx->page = std::move(dentryBlk); + break; + } + } + ctx->bidx = bidx; + return de; +} + +static HmdfsDentry *FindDentry(DcacheLookupCtx *ctx) +{ + for (uint32_t level = 0; level < MAX_BUCKET_LEVEL; level++) { + HmdfsDentry *de = InLevel(level, ctx); + if (de != nullptr) { + return de; + } + } + return nullptr; +} + +int32_t CloudDiskMetaFile::DoRemove(const MetaBase &base) +{ + return E_OK; +} + +int32_t CloudDiskMetaFile::DoLookup(MetaBase &base) +{ + if (base.name == "mock") { + return EINVAL; + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoUpdate(const MetaBase &base) +{ + return E_OK; +} + +int32_t CloudDiskMetaFile::DoRename(MetaBase &metaBase, const std::string &newName, + std::shared_ptr newMetaFile) +{ + if (newName == "mock") { + return EINVAL; + } + return E_OK; +} + +static int32_t DecodeDentrys(const HmdfsDentryGroup &dentryGroup, std::vector &bases) +{ + return 0; +} + +int32_t CloudDiskMetaFile::LoadChildren(std::vector &bases) +{ + return E_OK; +} + +void MetaFileMgr::Clear(uint32_t userId, const std::string &bundleName, + const std::string &cloudId) +{ + std::lock_guard lock(cloudDiskMutex_); + MetaFileKey key(userId, cloudId + bundleName); + cloudDiskMetaFile_.erase(key); + cloudDiskMetaFileList_.remove_if([key](CloudDiskMetaFileListEle &item) { return item.first == key; }); +} + +void MetaFileMgr::CloudDiskClearAll() +{ + std::lock_guard lock(cloudDiskMutex_); + cloudDiskMetaFile_.clear(); + cloudDiskMetaFileList_.clear(); +} + +std::shared_ptr MetaFileMgr::GetCloudDiskMetaFile(uint32_t userId, const std::string &bundleName, + const std::string &cloudId) +{ + std::shared_ptr mFile = nullptr; + std::lock_guard lock(cloudDiskMutex_); + MetaFileKey key(userId, cloudId + bundleName); + auto it = cloudDiskMetaFile_.find(key); + if (it != cloudDiskMetaFile_.end()) { + cloudDiskMetaFileList_.splice(cloudDiskMetaFileList_.begin(), cloudDiskMetaFileList_, it->second); + mFile = it->second->second; + } else { + if (cloudDiskMetaFile_.size() == MAX_META_FILE_NUM) { + auto deleteKey = cloudDiskMetaFileList_.back().first; + cloudDiskMetaFile_.erase(deleteKey); + cloudDiskMetaFileList_.pop_back(); + } + mFile = std::make_shared(userId, bundleName, cloudId); + cloudDiskMetaFileList_.emplace_front(key, mFile); + cloudDiskMetaFile_[key] = cloudDiskMetaFileList_.begin(); + } + return mFile; +} + +int32_t MetaFileMgr::CreateRecycleDentry(uint32_t userId, const std::string &bundleName) +{ + if (bundleName != "com.ohos.photos") { + return EINVAL; + } + return E_OK; +} + +int32_t MetaFileMgr::MoveIntoRecycleDentryfile(uint32_t userId, const std::string &bundleName, const std::string &name, + const std::string &parentCloudId, int64_t rowId) +{ + if (parentCloudId == "mock") { + return E_RDB; + } + return E_OK; +} + +int32_t MetaFileMgr::RemoveFromRecycleDentryfile(uint32_t userId, const std::string &bundleName, + const struct RestoreInfo &restoreInfo) +{ + if (restoreInfo.parentCloudId == "mock") { + return E_RDB; + } + return E_OK; +} + +int32_t MetaFileMgr::GetNewName(std::shared_ptr metaFile, const std::string &oldName, + std::string &newName) +{ + return E_OK; +} +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/mock/rdb_assistant.h b/cloud_file/test/unittests/clouddisk_database/mock/rdb_assistant.h new file mode 100644 index 0000000..9bdcf8d --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/mock/rdb_assistant.h @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_SYNC_SA_RDB_STORE_MOCK_H +#define OHOS_CLOUD_SYNC_SA_RDB_STORE_MOCK_H + +#include "abs_rdb_predicates.h" +#include "rdb_helper.h" +#include "result_set.h" +#include "value_object.h" +#include "values_bucket.h" + +#include +#include + +namespace OHOS::FileManagement::CloudDisk { +using namespace std; +using namespace NativeRdb; + + +class RdbStoreMock final : public NativeRdb::RdbStore { +public: + MOCK_METHOD3(Insert, int(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues)); + MOCK_METHOD3(BatchInsert, + int(int64_t &outInsertNum, + const std::string &table, + const std::vector &initialBatchValues)); + MOCK_METHOD3(Replace, int(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues)); + MOCK_METHOD4(InsertWithConflictResolution, + int(int64_t &outRowId, + const std::string &table, + const ValuesBucket &initialValues, + ConflictResolution conflictResolution)); + MOCK_METHOD5(Update, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &whereArgs)); + MOCK_METHOD5(Update, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &bindArgs)); + + MOCK_METHOD6(UpdateWithConflictResolution, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &whereArgs, + ConflictResolution conflictResolution)); + + MOCK_METHOD6(UpdateWithConflictResolution, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &bindArgs, + ConflictResolution conflictResolution)); + + MOCK_METHOD4(Delete, + int(int &deletedRows, + const std::string &table, + const std::string &whereClause, + const std::vector &whereArgs)); + + MOCK_METHOD4(Delete, + int(int &deletedRows, + const std::string &table, + const std::string &whereClause, + const std::vector &bindArgs)); + + MOCK_METHOD2(ExecuteSql, int(const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteAndGetLong, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteAndGetString, + int(std::string &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteForLastInsertedRowId, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteForChangedRowCount, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD2(Backup, int(const std::string &databasePath, const std::vector &destEncryptKey)); + + MOCK_METHOD3(Attach, + int(const std::string &alias, const std::string &pathName, const std::vector destEncryptKey)); + + MOCK_METHOD2(Count, int(int64_t &outValue, const AbsRdbPredicates &predicates)); + MOCK_METHOD2(Query, + std::shared_ptr(const AbsRdbPredicates &predicates, + const std::vector &columns)); + MOCK_METHOD11(Query, + std::shared_ptr(int &errCode, + bool distinct, + const std::string &table, + const std::vector &columns, + const std::string &whereClause, + const std::vector &bindArgs, + const std::string &groupBy, + const std::string &indexName, + const std::string &orderBy, + const int &limit, + const int &offset)); + MOCK_METHOD2(QuerySql, + std::shared_ptr(const std::string &sql, + const std::vector &selectionArgs)); + MOCK_METHOD2(QuerySql, + std::shared_ptr(const std::string &sql, + const std::vector &bindArgs)); + MOCK_METHOD2(QueryByStep, + std::shared_ptr(const std::string &sql, const std::vector &selectionArgs)); + MOCK_METHOD3(QueryByStep, + std::shared_ptr(const std::string &sql, const std::vector &bindArgs, + bool preCount)); + + MOCK_METHOD3(QueryByStep, + std::shared_ptr(const AbsRdbPredicates &predicates, + const std::vector &columns, bool preCount)); + + MOCK_METHOD4(RemoteQuery, + std::shared_ptr(const std::string &device, + const AbsRdbPredicates &predicates, + const std::vector &columns, + int &errCode)); + + MOCK_METHOD3(GetModifyTime, ModifyTime(const std::string &table, const std::string &columnName, + std::vector &keys)); + + MOCK_METHOD3(SetDistributedTables, int(const std::vector &tables, int32_t type, + const DistributedRdb::DistributedConfig &distributedConfig)); + MOCK_METHOD3(ObtainDistributedTableName, + std::string(const std::string &device, const std::string &table, int &errCode)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncBrief& async)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncDetail& async)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const std::vector& tables, const AsyncDetail& async)); + MOCK_METHOD2(Subscribe, int(const SubscribeOption &option, RdbStoreObserver *observer)); + MOCK_METHOD2(UnSubscribe, int(const SubscribeOption &option, RdbStoreObserver *observer)); + MOCK_METHOD1(RegisterAutoSyncCallback, int(std::shared_ptr syncObserver)); + MOCK_METHOD1(UnregisterAutoSyncCallback, int(std::shared_ptr syncObserver)); + MOCK_METHOD2(CleanDirtyData, int(const std::string &table, uint64_t cursor)); + MOCK_METHOD1(Notify, int(const std::string &event)); + MOCK_METHOD2(DropDeviceData, bool(const std::vector &devices, const DropOption &option)); + MOCK_METHOD3(Update, int(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates)); + MOCK_METHOD2(Delete, int(int &deletedRows, const AbsRdbPredicates &predicates)); + MOCK_METHOD1(GetVersion, int(int &version)); + MOCK_METHOD1(SetVersion, int(int version)); + MOCK_METHOD0(BeginTransaction, int()); + MOCK_METHOD0(RollBack, int()); + MOCK_METHOD0(Commit, int()); + MOCK_METHOD0(IsInTransaction, bool()); + MOCK_METHOD0(GetPath, std::string()); + MOCK_METHOD0(IsHoldingConnection, bool()); + MOCK_CONST_METHOD0(IsOpen, bool()); + MOCK_CONST_METHOD0(IsReadOnly, bool()); + MOCK_CONST_METHOD0(IsMemoryRdb, bool()); + MOCK_METHOD2(Restore, int(const std::string &backupPath, const std::vector &newKey)); + MOCK_METHOD1(GetRebuilt, int(RebuiltType &rebuilt)); + MOCK_METHOD1(CreateTransaction, std::pair>(int32_t type)); +}; + +class AbsSharedResultSetMock : public AbsSharedResultSet { +public: + ~AbsSharedResultSetMock() {} + MOCK_METHOD1(GetAllColumnNames, int(std::vector &)); + MOCK_METHOD1(GetColumnCount, int(int &)); + MOCK_METHOD2(GetColumnType, int(int, ColumnType &)); + MOCK_METHOD2(GetColumnIndex, int(const std::string &, int &)); + MOCK_METHOD2(GetColumnName, int(int, std::string &)); + MOCK_METHOD1(GetRowCount, int(int &)); + MOCK_METHOD1(GoTo, int(int)); + MOCK_METHOD1(GoToRow, int(int)); + MOCK_METHOD0(GoToFirstRow, int()); + MOCK_METHOD0(GoToLastRow, int()); + MOCK_METHOD0(GoToNextRow, int()); + MOCK_METHOD0(GoToPreviousRow, int()); + MOCK_METHOD1(IsEnded, int(bool &)); + MOCK_METHOD1(IsAtLastRow, int(bool &)); + MOCK_METHOD2(GetBlob, int(int, std::vector &)); + MOCK_METHOD2(GetString, int(int, std::string &)); + MOCK_METHOD2(GetInt, int(int, int &)); + MOCK_METHOD2(GetLong, int(int, int64_t &)); + MOCK_METHOD2(GetDouble, int(int, double &)); + MOCK_METHOD2(IsColumnNull, int(int, bool &)); + MOCK_METHOD0(Close, int()); + MOCK_METHOD1(GetRow, int(RowEntity &)); + + MOCK_CONST_METHOD0(IsClosed, bool()); + MOCK_CONST_METHOD1(GetRowIndex, int(int &)); + MOCK_CONST_METHOD1(IsStarted, int(bool &)); + MOCK_CONST_METHOD1(IsAtFirstRow, int(bool &)); + + MOCK_METHOD2(GetAsset, int(int32_t, ValueObject::Asset &)); + MOCK_METHOD2(GetAssets, int(int32_t, ValueObject::Assets &)); + MOCK_METHOD2(Get, int(int32_t, ValueObject &)); + MOCK_METHOD1(GetModifyTime, int(std::string &)); + MOCK_METHOD2(GetSize, int(int32_t, size_t &)); +}; + +class Assistant { +public: + static inline std::shared_ptr ins = nullptr; +public: + virtual ~Assistant() = default; + virtual shared_ptr GetRdbStore(const RdbStoreConfig &, int, RdbOpenCallback &, int &) = 0; + virtual int DeleteRdbStore(const std::string &) = 0; + virtual std::string GetDefaultDatabasePath(const std::string &, const std::string &, int &) = 0; +}; + +class AssistantMock : public Assistant { +public: + MOCK_METHOD4(GetRdbStore, shared_ptr(const RdbStoreConfig &, int, RdbOpenCallback &, int &)); + MOCK_METHOD1(DeleteRdbStore, int(const std::string &)); + MOCK_METHOD3(GetDefaultDatabasePath, std::string(const std::string &, const std::string &, int &)); +}; +} // namespace OHOS::FileManagement::CloudSync::Test +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/mock/rdb_mock.cpp b/cloud_file/test/unittests/clouddisk_database/mock/rdb_mock.cpp new file mode 100644 index 0000000..432644f --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/mock/rdb_mock.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 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 "rdb_assistant.h" +#include "rdb_sql_utils.h" +#include "clouddisk_rdbstore.h" +#include "clouddisk_rdb_transaction.h" + +using namespace OHOS::FileManagement::CloudDisk; + +std::shared_ptr RdbHelper::GetRdbStore( + const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode) +{ + return Assistant::ins->GetRdbStore(config, version, openCallback, errCode); +} + +int RdbHelper::DeleteRdbStore(const std::string &dbFileName, bool shouldClose) +{ + return Assistant::ins->DeleteRdbStore(dbFileName); +} + +std::string RdbSqlUtils::GetDefaultDatabasePath(const std::string &baseDir, const std::string &name, int &errorCode) +{ + return Assistant::ins->GetDefaultDatabasePath(baseDir, name, errorCode); +} \ No newline at end of file diff --git a/cloud_file/test/unittests/clouddisk_database/mock/transaction_mock.cpp b/cloud_file/test/unittests/clouddisk_database/mock/transaction_mock.cpp new file mode 100644 index 0000000..bb56613 --- /dev/null +++ b/cloud_file/test/unittests/clouddisk_database/mock/transaction_mock.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024 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 +#include "transaction.h" + +namespace OHOS::FileManagement::CloudDisk { +using namespace NativeRdb; +class TransactionMock : public NativeRdb::Transaction { +public: + MOCK_METHOD3(Update, std::pair(const Row &row, const AbsRdbPredicates &predicates, + Resolution resolution)); + MOCK_METHOD5(Update, std::pair(const std::string &table, const Row &row, + const std::string &where, const Values &args, Resolution resolution)); + MOCK_METHOD3(Insert, std::pair(const std::string &table, const Row &row, + Resolution resolution)); + MOCK_METHOD0(Commit, int32_t()); + MOCK_METHOD0(Rollback, int32_t()); + MOCK_METHOD0(Close, int32_t()); + MOCK_METHOD2(BatchInsert, std::pair(const std::string &table, const Rows &rows)); + MOCK_METHOD2(BatchInsert, std::pair(const std::string &table, const RefRows &rows)); + MOCK_METHOD3(BatchInsertWithConflictResolution, std::pair(const std::string &table, + const RefRows &rows, Resolution resolution)); + MOCK_METHOD3(Delete, std::pair(const std::string &table, const std::string &whereClause, + const Values &args)); + MOCK_METHOD1(Delete, std::pair(const AbsRdbPredicates &predicates)); + MOCK_METHOD3(QueryByStep, std::shared_ptr(const std::string &sql, const Values &args, bool preCount)); + MOCK_METHOD3(QueryByStep, std::shared_ptr(const AbsRdbPredicates &predicates, const Fields &columns, + bool preCount)); + MOCK_METHOD2(Execute, std::pair(const std::string &sql, const Values &args)); +}; +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_api/BUILD.gn b/cloud_file/test/unittests/cloudsync_api/BUILD.gn new file mode 100644 index 0000000..79542b7 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/BUILD.gn @@ -0,0 +1,19 @@ +# 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. +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +group("cloudsync_api_test") { + testonly = true + deps = [ "cloudsync_impl:cloudsync_impl_test" ] +} diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/BUILD.gn b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/BUILD.gn new file mode 100644 index 0000000..885fe4e --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/BUILD.gn @@ -0,0 +1,559 @@ +# 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. +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("cloud_sync_callback_client_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "cloud_sync_callback_client_test.cpp" ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/utils/log/include", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_callback_stub_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "cloud_sync_callback_stub_test.cpp" ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/utils/log/include", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_manager_impl_test") { + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp", + "cloud_sync_manager_impl_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/test/mock/ipc", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/utils/log/include", + "${cloud_file_path}/utils/system/include", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloudsync_sa_static", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + "json:nlohmann_json_static", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004310", + "LOG_TAG=\"CLOUD_SYNC_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_manager_impl_unnomal_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "cloud_sync_manager_impl_unnomal_test.cpp" ] + + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/test/mock/ipc", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/utils/log/include", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloudsync_sa_static", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "cloud_sync_manager_test.cpp" ] + + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_service_proxy_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "cloud_sync_service_proxy_test.cpp" ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/utils/log/include", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_download_callback_client_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "cloud_download_callback_client_test.cpp" ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/utils/log/include", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("cloud_download_callback_stub_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_callback_stub.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_optimize_callback_stub.cpp", + "../../../mock/cloud_download_uri_manager_hook.cpp", + "cloud_download_callback_stub_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${cloud_file_path}/utils/log/include", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ + "private=public", + "protected=public", + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("cloud_download_uri_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_download_uri_manager.cpp", + "cloud_download_uri_manager_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_common_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "cloud_sync_common_test.cpp", + "file_hook/parcel.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_asset_manager_impl_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager_impl.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp", + "cloud_sync_asset_manager_impl_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/utils/log/include", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_asset_manager_impl_unnomal_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_asset_manager_impl.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp", + "cloud_sync_asset_manager_impl_unnomal_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_asset_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_asset_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "cloud_sync_asset_manager_test.cpp" ] + + include_dirs = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_asset_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("download_asset_callback_client_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_client.cpp", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp", + "download_asset_callback_client_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("download_asset_callback_stub_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/download_asset_callback_stub.cpp", + "../../../mock/cloud_download_uri_manager_hook.cpp", + "download_asset_callback_stub_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/interfaces/inner_api/native/cloudsync_kit_inner", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + ] + + defines = [ + "private=public", + "protected=public", + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_TEST\"", + ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_service_proxy_lite_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/test/mock/system_ability_manager_client_mock.cpp", + "cloud_sync_service_proxy_lite_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner_lite/src", + "${cloud_file_path}/utils/log/include", + "${cloud_file_path}/test/mock", + ] + + deps = [ + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner_lite", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + "samgr:samgr_proxy", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +group("cloudsync_impl_test") { + testonly = true + + deps = [ + ":cloud_download_callback_client_test", + ":cloud_download_callback_stub_test", + ":cloud_download_uri_manager_test", + ":cloud_sync_asset_manager_impl_test", + ":cloud_sync_asset_manager_impl_unnomal_test", + ":cloud_sync_asset_manager_test", + ":cloud_sync_callback_client_test", + ":cloud_sync_callback_stub_test", + ":cloud_sync_common_test", + ":cloud_sync_manager_impl_test", + ":cloud_sync_manager_impl_unnomal_test", + ":cloud_sync_manager_test", + ":download_asset_callback_client_test", + ":download_asset_callback_stub_test", + ] +} diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_callback_client_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_callback_client_test.cpp new file mode 100644 index 0000000..b5a6946 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_callback_client_test.cpp @@ -0,0 +1,110 @@ +/* + * 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 +#include + +#include "cloud_download_callback_client.h" +#include "dfs_error.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace std; + +class CloudDownloadCallbackClientTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +class MockCloudDownloadCallback final : public CloudDownloadCallback { +public: + void OnDownloadProcess(const DownloadProgressObj &progress) + { + return; + } +}; + +void CloudDownloadCallbackClientTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudDownloadCallbackClientTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudDownloadCallbackClientTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudDownloadCallbackClientTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: OnDownloadProcessTest001 + * @tc.desc: Verify the OnDownloadProcess function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadCallbackClientTest, OnDownloadProcessTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnDownloadProcess Start"; + try { + DownloadProgressObj progress; + std::shared_ptr callback = nullptr; + CloudDownloadCallbackClient cloudCallback(callback); + cloudCallback.OnDownloadProcess(progress); + EXPECT_TRUE(true); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnDownloadProcess ERROR"; + } + GTEST_LOG_(INFO) << "OnDownloadProcess End"; +} + +/** + * @tc.name: OnDownloadProcessTest002 + * @tc.desc: Verify the OnDownloadProcess function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadCallbackClientTest, OnDownloadProcessTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnDownloadProcess Start"; + try { + DownloadProgressObj progress; + std::shared_ptr callback = std::make_shared(); + CloudDownloadCallbackClient cloudCallback(callback); + cloudCallback.OnDownloadProcess(progress); + EXPECT_TRUE(true); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnDownloadProcess ERROR"; + } + GTEST_LOG_(INFO) << "OnDownloadProcess End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_callback_stub_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_callback_stub_test.cpp new file mode 100644 index 0000000..06c241b --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_callback_stub_test.cpp @@ -0,0 +1,215 @@ +/* + * 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 +#include + +#include "cloud_download_callback_stub.h" +#include "cloud_download_uri_manager.h" +#include "i_cloud_download_callback_mock.h" +#include "dfs_error.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudDownloadCallbackStubMock : public CloudDownloadCallbackStub { +public: + CloudDownloadCallbackStubMock() {} + void OnDownloadProcess(const DownloadProgressObj& progress) override + {} +}; + +class CloudDownloadCallbackStubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr cloudDownloadCallbackStub_; +}; + +void CloudDownloadCallbackStubTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudDownloadCallbackStubTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudDownloadCallbackStubTest::SetUp(void) +{ + cloudDownloadCallbackStub_ = std::make_shared(); + std::cout << "SetUp" << std::endl; +} + +void CloudDownloadCallbackStubTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: OnRemoteRequestTest001 + * @tc.desc: Verify the OnRemoteRequest function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadCallbackStubTest, OnRemoteRequestTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequest Start"; + try { + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_EQ(E_SERVICE_DESCRIPTOR_IS_EMPTY, cloudDownloadCallbackStub_->OnRemoteRequest( + ICloudDownloadCallback::SERVICE_CMD_ON_PROCESS, data, reply, option)); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnRemoteRequest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequest End"; +} + +/** + * @tc.name: OnRemoteRequestTest002 + * @tc.desc: Verify the OnRemoteRequest function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadCallbackStubTest, OnRemoteRequestTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequest Start"; + try { + uint32_t code = 100; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_TRUE(data.WriteInterfaceToken(ICloudDownloadCallback::GetDescriptor())); + int32_t ret = cloudDownloadCallbackStub_->OnRemoteRequest(code, data, reply, option); + EXPECT_NE(E_OK, ret); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnRemoteRequest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequest End"; +} + +/** + * @tc.name: OnRemoteRequestTest003 + * @tc.desc: Verify the OnRemoteRequest function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudDownloadCallbackStubTest, OnRemoteRequestTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequest Start"; + try { + uint32_t code = ICloudDownloadCallback::SERVICE_CMD_ON_PROCESS; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_TRUE(data.WriteInterfaceToken(ICloudDownloadCallback::GetDescriptor())); + int32_t ret = cloudDownloadCallbackStub_->OnRemoteRequest(code, data, reply, option); + EXPECT_NE(E_OK, ret); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnRemoteRequest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequest End"; +} + +/** + * @tc.name: HandleOnProcessTest001 + * @tc.desc: Verify the HandleOnProcess function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadCallbackStubTest, HandleOnProcessTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOnProcess Start"; + try { + MessageParcel data; + MessageParcel reply; + DownloadProgressObj progress; + progress.path = "/data"; + bool prog = data.WriteParcelable(&progress); + EXPECT_TRUE(prog); + int ret = cloudDownloadCallbackStub_->HandleOnProcess(data, reply); + EXPECT_EQ(E_OK, ret); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOnProcess ERROR"; + } + GTEST_LOG_(INFO) << "HandleOnProcess End"; +} + +/** + * @tc.name: HandleOnProcessTest002 + * @tc.desc: Verify the HandleOnProcess function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadCallbackStubTest, HandleOnProcessTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOnProcess Start"; + try { + MessageParcel data; + MessageParcel reply; + DownloadProgressObj progress; + progress.path = ""; + bool prog = data.WriteParcelable(&progress); + EXPECT_TRUE(prog); + int32_t ret = cloudDownloadCallbackStub_->HandleOnProcess(data, reply); + EXPECT_EQ(E_OK, ret); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOnProcess ERROR"; + } + GTEST_LOG_(INFO) << "HandleOnProcess End"; +} + +/** + * @tc.name: HandleOnProcessTest003 + * @tc.desc: Verify the HandleOnProcess function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadCallbackStubTest, HandleOnProcessTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOnProcess Start"; + try { + MessageParcel data; + MessageParcel reply; + DownloadProgressObj progress; + progress.path = "/data"; + progress.state = DownloadProgressObj::STOPPED; + bool prog = data.WriteParcelable(&progress); + EXPECT_TRUE(prog); + cloudDownloadCallbackStub_->HandleOnProcess(data, reply); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOnProcess ERROR"; + } + GTEST_LOG_(INFO) << "HandleOnProcess End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync { +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_uri_manager_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_uri_manager_test.cpp new file mode 100644 index 0000000..46bdd9c --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_download_uri_manager_test.cpp @@ -0,0 +1,241 @@ +/* + * 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 +#include + +#include "cloud_download_uri_manager.h" +#include "dfs_error.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudDownloadUriManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudDownloadUriManagerTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudDownloadUriManagerTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudDownloadUriManagerTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudDownloadUriManagerTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: GetInstanceTest + * @tc.desc: Verify the GetInstance function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadUriManagerTest, GetInstanceTest, TestSize.Level1) +{ + try { + CloudDownloadUriManager::GetInstance(); + } catch (...) { + EXPECT_TRUE(false); + } +} + +/** + * @tc.name: AddPathToUriTest001 + * @tc.desc: Verify the AddPathToUri function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadUriManagerTest, AddPathToUriTest001, TestSize.Level1) +{ + const std::string path = "file://data/file"; + const std::string uri = "file://data/file/test"; + CloudDownloadUriManager mUriMgr; + mUriMgr.AddPathToUri(path, uri); + EXPECT_EQ(mUriMgr.pathUriMap_[path], uri); +} + +/** + * @tc.name: AddPathToUriTest002 + * @tc.desc: Verify the AddPathToUri function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudDownloadUriManagerTest, AddPathToUriTest002, TestSize.Level1) +{ + const std::string path = "file://data/file"; + const std::string uri = "file://data/file/test"; + CloudDownloadUriManager mUriMgr; + mUriMgr.pathUriMap_[path] = uri; + auto ret = mUriMgr.AddPathToUri(path, uri); + EXPECT_EQ(ret, E_STOP); +} + +/** + * @tc.name: RemoveUriTest001 + * @tc.desc: Verify the RemoveUri function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadUriManagerTest, RemoveUriTest001, TestSize.Level1) +{ + const std::string path = "file://data/file"; + const std::string uri = "file://data/file/test1"; + CloudDownloadUriManager mUriMgr; + mUriMgr.AddPathToUri(path, uri); + EXPECT_EQ(mUriMgr.pathUriMap_[path], uri); + mUriMgr.RemoveUri(path); + auto ret = mUriMgr.pathUriMap_.find(path); + EXPECT_EQ(ret, mUriMgr.pathUriMap_.end()); +} + +/** + * @tc.name: RemoveUriTest002 + * @tc.desc: Verify the RemoveUri function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudDownloadUriManagerTest, RemoveUriTest002, TestSize.Level1) +{ + const std::string path = "file://data/file"; + CloudDownloadUriManager mUriMgr; + mUriMgr.RemoveUri(path); + auto ret = mUriMgr.pathUriMap_.find(path); + EXPECT_EQ(ret, mUriMgr.pathUriMap_.end()); +} + +/** + * @tc.name: RemoveUriTest003 + * @tc.desc: Verify the RemoveUri function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudDownloadUriManagerTest, RemoveUriTest003, TestSize.Level1) +{ + int64_t downloadId = 3; + const std::string path = "file://data/file"; + CloudDownloadUriManager mUriMgr; + (mUriMgr.downloadIdPathMap_)[3].push_back(path); + (mUriMgr.pathUriMap_)[path] = "test2"; + mUriMgr.RemoveUri(downloadId); + auto ret1 = mUriMgr.pathUriMap_.find(path); + EXPECT_EQ(ret1, mUriMgr.pathUriMap_.end()); + auto ret2 = mUriMgr.downloadIdPathMap_.find(downloadId); + EXPECT_EQ(ret2, mUriMgr.downloadIdPathMap_.end()); +} + +/** + * @tc.name: GetUriTest001 + * @tc.desc: Verify the GetUri function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadUriManagerTest, GetUriTest001, TestSize.Level1) +{ + const std::string path = ""; + const std::string uri = ""; + CloudDownloadUriManager mUriMgr; + string uriStr = mUriMgr.GetUri(path); + EXPECT_EQ(uriStr, uri); +} + +/** + * @tc.name: GetUriTest002 + * @tc.desc: Verify the GetUri function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadUriManagerTest, GetUriTest002, TestSize.Level1) +{ + const std::string path = "file://data/file"; + const std::string uri = "file://data/file/test2"; + CloudDownloadUriManager mUriMgr; + mUriMgr.AddPathToUri(path, uri); + EXPECT_EQ(mUriMgr.pathUriMap_[path], uri); + string uriStr = mUriMgr.GetUri(path); + EXPECT_EQ(uriStr, uri); +} + +/** + * @tc.name: CheckDownloadIdPathMap001 + * @tc.desc: Verify the CheckDownloadIdPathMap function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadUriManagerTest, CheckDownloadIdPathMap001, TestSize.Level1) +{ + int64_t downloadId = 1; + const std::string path = "file://data/file"; + CloudDownloadUriManager mUriMgr; + (mUriMgr.downloadIdPathMap_)[1].push_back(path); + mUriMgr.CheckDownloadIdPathMap(downloadId); + auto ret = mUriMgr.downloadIdPathMap_.find(downloadId); + EXPECT_EQ(ret, mUriMgr.downloadIdPathMap_.end()); +} + +/** + * @tc.name: CheckDownloadIdPathMap002 + * @tc.desc: Verify the CheckDownloadIdPathMap function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadUriManagerTest, CheckDownloadIdPathMap002, TestSize.Level1) +{ + int64_t downloadId = 1; + const std::string path = "fild://data/file"; + CloudDownloadUriManager mUriMgr; + (mUriMgr.downloadIdPathMap_)[1].push_back(path); + (mUriMgr.pathUriMap_)[path] = "test2"; + mUriMgr.CheckDownloadIdPathMap(downloadId); + auto ret1 = mUriMgr.downloadIdPathMap_.find(downloadId); + EXPECT_NE(ret1, mUriMgr.downloadIdPathMap_.end()); + auto ret2 = mUriMgr.pathUriMap_.find(path); + EXPECT_NE(ret2, mUriMgr.pathUriMap_.end()); +} + +/** + * @tc.name: AddDownloadIdToPathTest + * @tc.desc: Verify the AddDownloadIdToPath function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDownloadUriManagerTest, AddDownloadIdToPathTest, TestSize.Level1) +{ + std::vector pathVec = {"file://data/file"}; + int64_t downloadId = 0; + CloudDownloadUriManager mUriMgr; + auto ret = mUriMgr.AddDownloadIdToPath(downloadId, pathVec); + EXPECT_EQ(ret, E_OK); +} +} // namespace Test +} // namespace FileManagement::CloudSync { +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_impl_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_impl_test.cpp new file mode 100644 index 0000000..c8b05dc --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_impl_test.cpp @@ -0,0 +1,170 @@ +/* + * 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 "cloud_sync_asset_manager_impl.h" +#include "service_proxy.h" +#include "dfs_error.h" +#include "utils_log.h" + +#include +#include + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudSyncAssetManagerImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudSyncAssetManagerImplTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncAssetManagerImplTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncAssetManagerImplTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncAssetManagerImplTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/* + * @tc.name: SetDeathRecipientTest + * @tc.desc: Verify the SetDeathRecipient function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncAssetManagerImplTest, SetDeathRecipientTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + CloudSyncAssetManagerImpl::GetInstance().SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetDeathRecipientTest FAILED"; + } + GTEST_LOG_(INFO) << "SetDeathRecipientTest End"; +} + +/* + * @tc.name: UploadAssetTest + * @tc.desc: Verify the UploadAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncAssetManagerImplTest, UploadAssetTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UploadAssetTest Start"; + try { + int32_t userId = 100; + std::string request = ""; + std::string result = ""; + int32_t res = CloudSyncAssetManagerImpl::GetInstance().UploadAsset(userId, request, result); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UploadAsseteTest FAILED"; + } + GTEST_LOG_(INFO) << "UploadAssetTest End"; +} + +/* + * @tc.name: DownloadFileTest001 + * @tc.desc: Verify the DownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncAssetManagerImplTest, DownloadFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFileTest Start"; + try { + int32_t userId = 100; + std::string bundleName = "com.ohos.photos"; + AssetInfo assetInfo; + int32_t res = CloudSyncAssetManagerImpl::GetInstance().DownloadFile(userId, bundleName, assetInfo); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DownloadFileTest FAILED"; + } + GTEST_LOG_(INFO) << "DownloadFileTest End"; +} + +/* + * @tc.name: DownloadFilesTest + * @tc.desc: Verify the DownloadFiles function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncAssetManagerImplTest, DownloadFilesTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFilesTest Start"; + try { + int32_t userId = 100; + std::string bundleName = "com.ohos.photos"; + std::vector assetInfo; + std::vector assetResultMap; + int32_t res = CloudSyncAssetManagerImpl::GetInstance().DownloadFiles(userId, + bundleName, assetInfo, assetResultMap); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DownloadFilesTest FAILED"; + } + GTEST_LOG_(INFO) << "DownloadFilesTest End"; +} + +/* + * @tc.name: DeleteAssetTest + * @tc.desc: Verify the DeleteAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncAssetManagerImplTest, DeleteAssetTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeleteAssetTest Start"; + try { + int32_t userId = 100; + std::string uri = "uri"; + int32_t res = CloudSyncAssetManagerImpl::GetInstance().DeleteAsset(userId, uri); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DeleteAssetTest FAILED"; + } + GTEST_LOG_(INFO) << "DeleteAssetTest End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_impl_unnomal_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_impl_unnomal_test.cpp new file mode 100644 index 0000000..7724d1e --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_impl_unnomal_test.cpp @@ -0,0 +1,93 @@ +/* + * 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 +#include + +#include "cloud_sync_asset_manager_impl.h" +#include "service_proxy.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudSyncAssetManagerImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudSyncAssetManagerImplTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncAssetManagerImplTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncAssetManagerImplTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncAssetManagerImplTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: UploadAssetTest + * @tc.desc: Verify the UploadAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncAssetManagerImplTest, UploadAssetTest, TestSize.Level1) +{ + CloudSyncAssetManagerImpl assetManager; + int32_t userId = 100; + std::string request = "sample_request"; + std::string result; + int32_t ret = assetManager.UploadAsset(userId, request, result); + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +/** + * @tc.name: DownloadFileTest + * @tc.desc: Verify the DownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncAssetManagerImplTest, DownloadFileTest, TestSize.Level1) +{ + CloudSyncAssetManagerImpl assetManager; + int32_t userId = 100; + std::string request = "sample_request"; + AssetInfo assetInfo; + int32_t ret = assetManager.DownloadFile(userId, request, assetInfo); + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_test.cpp new file mode 100644 index 0000000..2721f19 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_asset_manager_test.cpp @@ -0,0 +1,74 @@ +/* + * 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 + +#include "cloud_sync_asset_manager_impl.h" +#include "cloud_sync_asset_manager.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing::ext; +using namespace testing; +using namespace std; + +class CloudSyncAssetManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudSyncAssetManagerTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncAssetManagerTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncAssetManagerTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncAssetManagerTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: GetInstanceTest + * @tc.desc: Verify the GetInstance function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(CloudSyncAssetManagerTest, GetInstanceTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest Begin"; + try { + CloudSyncAssetManager::GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest ERROR"; + } + + GTEST_LOG_(INFO) << "GetInstanceTest End"; +} + +} // namespace OHOS::FileManagement::CloudSync::Test diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_callback_client_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_callback_client_test.cpp new file mode 100644 index 0000000..0eeee38 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_callback_client_test.cpp @@ -0,0 +1,99 @@ +/* + * 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 +#include + +#include "cloud_sync_constants.h" +#include "dfs_error.h" +#include "cloud_sync_callback_client.h" +#include "service_callback_mock.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace std; + +class CloudSyncCallbackTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + sptr callbackClient_; + void InitCloudSyncCallback(); +}; + +class CloudSyncCallbackDerived : public CloudSyncCallback { +public: + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override + { + GTEST_LOG_(INFO) << "OnSyncStateChanged SUCCESS"; + } +}; + +void CloudSyncCallbackTest::InitCloudSyncCallback(void) +{ + shared_ptr callback = make_shared(); + callbackClient_ = new CloudSyncCallbackClient(callback); +} + +void CloudSyncCallbackTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncCallbackTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncCallbackTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncCallbackTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: OnSyncStateChangedTest + * @tc.desc: Verify the OnSyncStateChanged function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCallbackTest, OnSyncStateChangedTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnSyncStateChanged start"; + try { + InitCloudSyncCallback(); + callbackClient_->OnSyncStateChanged(CloudSyncState::COMPLETED, ErrorType::NO_ERROR); + EXPECT_TRUE(true); + callbackClient_->callback_ = nullptr; + callbackClient_->OnSyncStateChanged(CloudSyncState::COMPLETED, ErrorType::NO_ERROR); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnSyncStateChanged FAILED"; + } + GTEST_LOG_(INFO) << "OnSyncStateChanged end"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync { +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_callback_stub_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_callback_stub_test.cpp new file mode 100644 index 0000000..d8572a8 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_callback_stub_test.cpp @@ -0,0 +1,156 @@ +/* + * 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 +#include + +#include "cloud_sync_callback_stub.h" +#include "cloud_sync_constants.h" +#include "service_callback_mock.h" +#include "i_cloud_sync_callback.h" +#include "dfs_error.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MockCallback final : public CloudSyncCallbackStub { +public: + MOCK_METHOD2(OnSyncStateChanged, void(CloudSyncState state, ErrorType error)); +}; + +class CloudSyncCallbackStubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudSyncCallbackStubTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncCallbackStubTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncCallbackStubTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncCallbackStubTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: HandleOnSyncStateChangedTest001 + * @tc.desc: Verify the HandleOnSyncStateChanged function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCallbackStubTest, HandleOnSyncStateChangedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOnSyncStateChangedTest001 Start"; + try { + MockCallback callback; + EXPECT_CALL(callback, OnSyncStateChanged(_, _)).WillOnce(Return()); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncCallback::GetDescriptor())); + + const string bundleName = "com.ohos.photos"; + EXPECT_TRUE(data.WriteInt32(static_cast((CloudSyncState)0))); + EXPECT_TRUE(data.WriteInt32(static_cast((ErrorType)0))); + + EXPECT_EQ(E_OK, callback.OnRemoteRequest( + ICloudSyncCallback::SERVICE_CMD_ON_SYNC_STATE_CHANGED, data, reply, option)); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOnSyncStateChangedTest001 ERROR"; + } + GTEST_LOG_(INFO) << "HandleOnSyncStateChangedTest001 End"; +} + + +/** + * @tc.name: HandleOnSyncStateChangedTest002 + * @tc.desc: Verify the HandleOnSyncStateChanged function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCallbackStubTest, HandleOnSyncStateChangedTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOnSyncStateChangedTest002 Start"; + try { + MockCallback callback; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + const string bundleName = "com.ohos.photos"; + EXPECT_TRUE(data.WriteInt32(static_cast((CloudSyncState)0))); + EXPECT_TRUE(data.WriteInt32(static_cast((ErrorType)0))); + + EXPECT_NE(E_OK, callback.OnRemoteRequest( + ICloudSyncCallback::SERVICE_CMD_ON_SYNC_STATE_CHANGED, data, reply, option)); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOnSyncStateChangedTest002 ERROR"; + } + GTEST_LOG_(INFO) << "HandleOnSyncStateChangedTest002 End"; +} + +/** + * @tc.name: HandleOnSyncStateChangedTest003 + * @tc.desc: Verify the HandleOnSyncStateChanged function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCallbackStubTest, HandleOnSyncStateChangedTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOnSyncStateChangedTest003 Start"; + try { + MockCallback callback; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncCallback::GetDescriptor())); + callback.opToInterfaceMap_.clear(); + + const string bundleName = "com.ohos.photos"; + EXPECT_TRUE(data.WriteInt32(static_cast((CloudSyncState)0))); + EXPECT_TRUE(data.WriteInt32(static_cast((ErrorType)0))); + + EXPECT_NE(E_OK, callback.OnRemoteRequest( + ICloudSyncCallback::SERVICE_CMD_ON_SYNC_STATE_CHANGED, data, reply, option)); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOnSyncStateChangedTest003 ERROR"; + } + GTEST_LOG_(INFO) << "HandleOnSyncStateChangedTest003 End"; +} +} // namespace Test +} // namespace FileManagement::CloudSync { +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_common_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_common_test.cpp new file mode 100644 index 0000000..c872ce3 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_common_test.cpp @@ -0,0 +1,655 @@ +/* + * 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 +#include + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "iservice_registry.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace testing; +using namespace std; + +class CloudSyncCommonTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudSyncCommonTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncCommonTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncCommonTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncCommonTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/* + * @tc.name: Marshalling + * @tc.desc: Verify the Marshalling function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Marshalling, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Marshalling Start"; + try { + SwitchDataObj switchDataObj; + Parcel parcel; + string strSwitchData = "continue"; + bool boolSwitchData = false; + switchDataObj.switchData.insert({strSwitchData, boolSwitchData}); + auto res = switchDataObj.Marshalling(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Marshalling FAILED"; + } + GTEST_LOG_(INFO) << "Marshalling End"; +} + +/* + * @tc.name: Marshalling001 + * @tc.desc: Verify the Marshalling001 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Marshalling001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Marshalling001 Start"; + try { + SwitchDataObj switchDataObj; + Parcel parcel; + + auto res = switchDataObj.Marshalling(parcel); + EXPECT_TRUE(!res); + + string strSwitchData = "continue"; + bool boolSwitchData = true; + switchDataObj.switchData.insert({strSwitchData, boolSwitchData}); + res = switchDataObj.Marshalling(parcel); + EXPECT_TRUE(res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Marshalling001 FAILED"; + } + GTEST_LOG_(INFO) << "Marshalling001 End"; +} + +/* + * @tc.name: Marshalling002 + * @tc.desc: Verify the Marshalling002 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Marshalling002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Marshalling002 Start"; + try { + SwitchDataObj switchDataObj; + Parcel parcel; + + string strSwitchData = "strSwitchData"; + bool boolSwitchData = false; + switchDataObj.switchData.insert({strSwitchData, boolSwitchData}); + auto res = switchDataObj.Marshalling(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Marshalling002 FAILED"; + } + GTEST_LOG_(INFO) << "Marshalling002 End"; +} + +/* + * @tc.name: Marshalling003 + * @tc.desc: Verify the Marshalling003 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Marshalling003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Marshalling003 Start"; + try { + DownloadProgressObj downloadProgressObj; + Parcel parcel; + downloadProgressObj.path = "continue"; + downloadProgressObj.state = downloadProgressObj.RUNNING; + downloadProgressObj.downloadedSize = 1; + downloadProgressObj.totalSize = 1; + auto res = downloadProgressObj.Marshalling(parcel); + EXPECT_TRUE(!res); + + downloadProgressObj.path = "continue"; + downloadProgressObj.state = downloadProgressObj.RUNNING; + downloadProgressObj.downloadedSize = 1; + downloadProgressObj.totalSize = 0; + res = downloadProgressObj.Marshalling(parcel); + EXPECT_TRUE(!res); + + downloadProgressObj.path = "continue"; + downloadProgressObj.state = downloadProgressObj.RUNNING; + downloadProgressObj.downloadedSize = 0; + downloadProgressObj.totalSize = 0; + res = downloadProgressObj.Marshalling(parcel); + EXPECT_TRUE(!res); + + downloadProgressObj.path = "continue"; + downloadProgressObj.state = downloadProgressObj.STOPPED; + downloadProgressObj.downloadedSize = 0; + downloadProgressObj.totalSize = 0; + res = downloadProgressObj.Marshalling(parcel); + EXPECT_TRUE(!res); + + downloadProgressObj.path = "path"; + downloadProgressObj.state = downloadProgressObj.STOPPED; + downloadProgressObj.downloadedSize = 0; + downloadProgressObj.totalSize = 0; + res = downloadProgressObj.Marshalling(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Marshalling003 FAILED"; + } + GTEST_LOG_(INFO) << "Marshalling003 End"; +} + +/* + * @tc.name: Marshalling004 + * @tc.desc: Verify the Marshalling004 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Marshalling004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Marshalling004 Start"; + try { + CleanOptions cleanOptions; + Parcel parcel; + + auto res = cleanOptions.Marshalling(parcel); + EXPECT_TRUE(!res); + + string strActionsData = "continue"; + int32_t intActionsData = 1; + cleanOptions.appActionsData.insert({strActionsData, intActionsData}); + res = cleanOptions.Marshalling(parcel); + EXPECT_TRUE(res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Marshalling004 FAILED"; + } + GTEST_LOG_(INFO) << "Marshalling004 End"; +} + +/* + * @tc.name: Marshalling005 + * @tc.desc: Verify the Marshalling005 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Marshalling005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Marshalling005 Start"; + try { + CleanOptions cleanOptions; + Parcel parcel; + string strActionsData = "strActionsData"; + int32_t intActionsData = 0; + cleanOptions.appActionsData.insert({strActionsData, intActionsData}); + auto res = cleanOptions.Marshalling(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Marshalling005 FAILED"; + } + GTEST_LOG_(INFO) << "Marshalling005 End"; +} + +/* + * @tc.name: Marshalling006 + * @tc.desc: Verify the Marshalling006 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Marshalling006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Marshalling006 Start"; + try { + CleanOptions cleanOptions; + Parcel parcel; + + auto res = cleanOptions.Marshalling(parcel); + EXPECT_TRUE(!res); + + string strActionsData = "continue"; + int32_t intActionsData = 0; + cleanOptions.appActionsData.insert({strActionsData, intActionsData}); + res = cleanOptions.Marshalling(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Marshalling006 FAILED"; + } + GTEST_LOG_(INFO) << "Marshalling006 End"; +} + +/* + * @tc.name: Unmarshalling001 + * @tc.desc: Verify the Unmarshalling001 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Unmarshalling001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Unmarshalling001 Start"; + try { + auto switchDataObj = make_shared(); + Parcel parcel; + auto res = switchDataObj->Unmarshalling(parcel); + EXPECT_TRUE(res == nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Unmarshalling001 FAILED"; + } + GTEST_LOG_(INFO) << "Unmarshalling001 End"; +} + +/* + * @tc.name: Unmarshalling002 + * @tc.desc: Verify the Unmarshalling002 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Unmarshalling002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Unmarshalling002 Start"; + try { + auto downloadProgressObj = make_shared(); + Parcel parcel; + auto res = downloadProgressObj->Unmarshalling(parcel); + EXPECT_TRUE(res == nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Unmarshalling002 FAILED"; + } + GTEST_LOG_(INFO) << "Unmarshalling002 End"; +} + +/* + * @tc.name: Unmarshalling003 + * @tc.desc: Verify the Unmarshalling003 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Unmarshalling003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Unmarshalling003 Start"; + try { + auto cleanOptions = make_shared(); + Parcel parcel; + auto res = cleanOptions->Unmarshalling(parcel); + EXPECT_TRUE(res == nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Unmarshalling003 FAILED"; + } + GTEST_LOG_(INFO) << "Unmarshalling003 End"; +} + +/* + * @tc.name: ReadFromParcel001 + * @tc.desc: Verify the ReadFromParcel001 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, ReadFromParcel001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFromParcel001 Start"; + try { + SwitchDataObj switchDataObj; + Parcel parcel; + parcel.dataSize_ = 0; + auto res = switchDataObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFromParcel001 FAILED"; + } + GTEST_LOG_(INFO) << "ReadFromParcel001 End"; +} + +/* + * @tc.name: ReadFromParcel002 + * @tc.desc: Verify the ReadFromParcel002 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, ReadFromParcel002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFromParcel002 Start"; + try { + SwitchDataObj switchDataObj; + Parcel parcel; + parcel.dataSize_ = 1025; + auto res = switchDataObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFromParcel002 FAILED"; + } + GTEST_LOG_(INFO) << "ReadFromParcel002 End"; +} + +/* + * @tc.name: ReadFromParcel003 + * @tc.desc: Verify the ReadFromParcel003 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, ReadFromParcel003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFromParcel003 Start"; + try { + SwitchDataObj switchDataObj; + Parcel parcel; + parcel.dataSize_ = 3; + auto res = switchDataObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + parcel.data_ = new uint8_t(); + parcel.writable_ = 0; + res = switchDataObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + parcel.writable_ = 1; + res = switchDataObj.ReadFromParcel(parcel); + EXPECT_TRUE(res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFromParcel003 FAILED"; + } + GTEST_LOG_(INFO) << "ReadFromParcel003 End"; +} + +/* + * @tc.name: ReadFromParcel004 + * @tc.desc: Verify the ReadFromParcel004 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, ReadFromParcel004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFromParcel004 Start"; + try { + CleanOptions cleanOptions; + Parcel parcel; + parcel.dataSize_ = 0; + auto res = cleanOptions.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFromParcel004 FAILED"; + } + GTEST_LOG_(INFO) << "ReadFromParcel004 End"; +} + +/* + * @tc.name: ReadFromParcel005 + * @tc.desc: Verify the ReadFromParcel005 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, ReadFromParcel005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFromParcel005 Start"; + try { + CleanOptions cleanOptions; + Parcel parcel; + parcel.dataSize_ = 1025; + auto res = cleanOptions.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFromParcel005 FAILED"; + } + GTEST_LOG_(INFO) << "ReadFromParcel005 End"; +} + +/* + * @tc.name: ReadFromParcel006 + * @tc.desc: Verify the ReadFromParcel006 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, ReadFromParcel006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFromParcel006 Start"; + try { + CleanOptions cleanOptions; + Parcel parcel; + parcel.dataSize_ = 3; + auto res = cleanOptions.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + parcel.data_ = new uint8_t(); + parcel.readCursor_ = 0; + res = cleanOptions.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + parcel.readCursor_ = 1; + res = cleanOptions.ReadFromParcel(parcel); + EXPECT_TRUE(res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFromParcel006 FAILED"; + } + GTEST_LOG_(INFO) << "ReadFromParcel006 End"; +} + +/* + * @tc.name: ReadFromParcel007 + * @tc.desc: Verify the ReadFromParcel007 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, ReadFromParcel007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFromParcel007 Start"; + try { + DownloadProgressObj downloadProgressObj; + Parcel parcel; + auto res = downloadProgressObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + parcel.data_ = new uint8_t(); + parcel.readCursor_ = 0; + res = downloadProgressObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + parcel.readCursor_ = 1; + res = downloadProgressObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + downloadProgressObj.downloadedSize = 0; + res = downloadProgressObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + downloadProgressObj.downloadedSize = 1; + downloadProgressObj.totalSize = 0; + res = downloadProgressObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + + downloadProgressObj.totalSize = 1; + res = downloadProgressObj.ReadFromParcel(parcel); + EXPECT_TRUE(!res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFromParcel007 FAILED"; + } + GTEST_LOG_(INFO) << "ReadFromParcel007 End"; +} + +/* + * @tc.name: to_string + * @tc.desc: Verify the to_string function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, to_string, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "to_string Start"; + try { + DownloadProgressObj downloadProgressObj; + auto res = downloadProgressObj.to_string(); + std::string expectStr = + "DownloadProgressObj [path: ******** state: 0 downloaded: 0 total: 0 downloadErrorType: 0 " + "downloadId: 0 batchState: 0 batchDownloadSize: 0 batchTotalSize: 0 " + "batchSuccNum: 0 batchFailNum: 0 batchTotalNum: 0]"; + EXPECT_EQ(res, expectStr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " to_string FAILED"; + } + GTEST_LOG_(INFO) << "to_string End"; +} + +/* + * @tc.name: ReadFromParcel00 + * @tc.desc: Verify the ReadFromParcel00 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, ReadFromParcel00, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFromParcel00 Start"; + try { + AssetInfoObj assetInfo; + Parcel parcel; + auto res = assetInfo.ReadFromParcel(parcel); + EXPECT_TRUE(res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFromParcel00 FAILED"; + } + GTEST_LOG_(INFO) << "ReadFromParcel00 End"; +} + +/* + * @tc.name: Marshalling007 + * @tc.desc: Verify the Marshalling007 function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Marshalling007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Marshalling007 Start"; + try { + AssetInfoObj assetInfo; + Parcel parcel; + auto res = assetInfo.Marshalling(parcel); + EXPECT_TRUE(res); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Marshalling007 FAILED"; + } + GTEST_LOG_(INFO) << "Marshalling007 End"; +} + +/* + * @tc.name: Unmarshalling + * @tc.desc: Verify the Unmarshalling function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, Unmarshalling, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Unmarshalling Start"; + try { + auto assetInfo = make_shared(); + Parcel parcel; + auto res = assetInfo->Unmarshalling(parcel); + EXPECT_TRUE(res != nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Unmarshalling FAILED"; + } + GTEST_LOG_(INFO) << "Unmarshalling End"; +} + +/* + * @tc.name: Unmarshalling + * @tc.desc: Verify the Unmarshalling function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, UnmarshallingTest1, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnmarshallingTest1 Start"; + try { + auto Info = make_shared(); + Parcel parcel; + auto res = Info->Unmarshalling(parcel); + EXPECT_TRUE(res != nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " UnmarshallingTest1 FAILED"; + } + GTEST_LOG_(INFO) << "UnmarshallingTest1 End"; +} + +/* + * @tc.name: Unmarshalling + * @tc.desc: Verify the Unmarshalling function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncCommonTest, UnmarshallingTest2, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnmarshallingTest2 Start"; + try { + auto Info = make_shared(); + Parcel parcel; + auto res = Info->Unmarshalling(parcel); + EXPECT_TRUE(res != nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " UnmarshallingTest2 FAILED"; + } + GTEST_LOG_(INFO) << "UnmarshallingTest2 End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_impl_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_impl_test.cpp new file mode 100644 index 0000000..c0bb917 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_impl_test.cpp @@ -0,0 +1,850 @@ +/* + * 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 +#include +#include +#include +#include + +#include "cloud_sync_manager_impl.h" +#include "service_proxy.h" +#include "dfs_error.h" +#include "i_cloud_sync_service_mock.h" +#include "iservice_registry.h" +#include "service_callback_mock.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +namespace fs = std::filesystem; +using namespace testing::ext; +using namespace testing; +using namespace std; +constexpr int32_t MAX_DENTRY_FILE_SIZE = 500; +constexpr int32_t MAX_FILE_CACHE_NUM = 400; +static const int32_t CLEAN_FILE_MAX_SIZE = 200; + +class CloudSyncManagerImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr managePtr_ = nullptr; +}; + +class CloudSyncCallbackDerived : public CloudSyncCallback { +public: + void OnSyncStateChanged(CloudSyncState state, ErrorType error) + { + std::cout << "OnSyncStateChanged" << std::endl; + } +}; + +class CloudDownloadCallbackDerived : public CloudDownloadCallback { +public: + void OnDownloadProcess(const DownloadProgressObj& progress) + { + std::cout << "OnDownloadProcess" << std::endl; + } +}; + +void CloudSyncManagerImplTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncManagerImplTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncManagerImplTest::SetUp(void) +{ + managePtr_ = make_shared(); + std::cout << "SetUp" << std::endl; +} + +void CloudSyncManagerImplTest::TearDown(void) +{ + managePtr_ = nullptr; + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: RegisterCallbackTest002 + * @tc.desc: Verify the RegisterCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, RegisterCallbackTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterCallbackTest Start"; + try { + shared_ptr callback = make_shared(); + int32_t res = CloudSyncManagerImpl::GetInstance().RegisterCallback(callback); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "RegisterCallbackTest End"; +} + +/* + * @tc.name: UnRegisterCallbackTest001 + * @tc.desc: Verify the UnRegisterCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, UnRegisterCallbackTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnRegisterCallbackTest Start"; + try { + string bundleName = "com.ohos.photos"; + int32_t res = CloudSyncManagerImpl::GetInstance().UnRegisterCallback(bundleName); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnRegisterCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "UnRegisterCallbackTest End"; +} + +/** + * @tc.name: StartSyncTest001 + * @tc.desc: Verify the StartSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, StartSyncTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartSyncTest Start"; + try { + string bundleName = "com.ohos.photos"; + int32_t res = CloudSyncManagerImpl::GetInstance().StartSync(bundleName); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartSyncTest FAILED"; + } + GTEST_LOG_(INFO) << "StartSyncTest End"; +} + +/** + * @tc.name: StartSyncTest003 + * @tc.desc: Verify the StartSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, StartSyncTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartSyncTest Start"; + try { + bool forceFlag = true; + shared_ptr callback = make_shared(); + string bundleName = "com.ohos.photos"; + int32_t res = CloudSyncManagerImpl::GetInstance().StartSync(forceFlag, callback); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartSyncTest FAILED"; + } + GTEST_LOG_(INFO) << "StartSyncTest End"; +} + +/** + * @tc.name: GetSyncTimeTest001 + * @tc.desc: Verify the GetSyncTime function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, GetSyncTimeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSyncTimeTest Start"; + try { + int64_t syncTime = 0; + string bundleName = "com.ohos.photos"; + int32_t res = CloudSyncManagerImpl::GetInstance().GetSyncTime(syncTime, bundleName); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetSyncTimeTest FAILED"; + } + GTEST_LOG_(INFO) << "GetSyncTimeTest End"; +} + +/** + * @tc.name: TriggerSyncTest002 + * @tc.desc: Verify the TriggerSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, TriggerSyncTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TriggerSyncTest Start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + int32_t res = CloudSyncManagerImpl::GetInstance().TriggerSync(bundleName, userId); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TriggerSyncTest FAILED"; + } + GTEST_LOG_(INFO) << "TriggerSyncTest End"; +} + +/* + * @tc.name: StopSyncTest + * @tc.desc: Verify the StopSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, StopSyncTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopSyncTest Start"; + try { + string bundleName = "com.ohos.photos"; + int res = CloudSyncManagerImpl::GetInstance().StopSync(bundleName); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StopSyncTest FAILED"; + } + GTEST_LOG_(INFO) << "StopSyncTest End"; +} + +/* + * @tc.name: ChangeAppSwitchTest + * @tc.desc: Verify the ChangeAppSwitch function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, ChangeAppSwitchTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChangeAppSwitchTest Start"; + try { + std::string accoutId = "accoutId"; + std::string bundleName = "bundleName"; + bool status = true; + auto res = CloudSyncManagerImpl::GetInstance().ChangeAppSwitch(accoutId, bundleName, status); + EXPECT_EQ(res, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ChangeAppSwitchTest FAILED"; + } + GTEST_LOG_(INFO) << "ChangeAppSwitchTest End"; +} + +/* + * @tc.name: NotifyEventChangeTest + * @tc.desc: Verify the NotifyEventChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, NotifyEventChangeTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyEventChangeTest Start"; + try { + int32_t userId = 100; + std::string eventId = "eventId"; + std::string extraData = "extraData"; + auto res = CloudSyncManagerImpl::GetInstance().NotifyEventChange(userId, eventId, extraData); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "NotifyEventChangeTest FAILED"; + } + GTEST_LOG_(INFO) << "NotifyEventChangeTest End"; +} + +/* + * @tc.name: StartDownloadFileTest + * @tc.desc: Verify the StartDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, StartDownloadFileTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string uri = "uri"; + auto res = CloudSyncManagerImpl::GetInstance().StartDownloadFile(uri); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StartDownloadFileTest FAILED"; + } + GTEST_LOG_(INFO) << "StartDownloadFileTest End"; +} + +/* + * @tc.name: StartFileCacheTest + * @tc.desc: Verify the StartFileCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, StartFileCacheTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFileCacheTest Start"; + try { + std::string uri = "uri"; + auto res = CloudSyncManagerImpl::GetInstance().StartFileCache(uri); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFileCacheTest FAILED"; + } + GTEST_LOG_(INFO) << "StartFileCacheTest End"; +} + +/* + * @tc.name: StopDownloadFileTest + * @tc.desc: Verify the StopDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, StopDownloadFileTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string uri = "uri"; + auto res = CloudSyncManagerImpl::GetInstance().StopDownloadFile(uri); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StopDownloadFileTest FAILED"; + } + GTEST_LOG_(INFO) << "StopDownloadFileTest End"; +} + +/* + * @tc.name: UnregisterDownloadFileCallbackTest + * @tc.desc: Verify the UnregisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, UnregisterDownloadFileCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallbackTest Start"; + try { + auto res = CloudSyncManagerImpl::GetInstance().UnregisterDownloadFileCallback(); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " UnregisterDownloadFileCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallbackTest End"; +} + +/* + * @tc.name: EnableCloudTest + * @tc.desc: Verify the EnableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, EnableCloudTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string accoutId = "accoutId"; + SwitchDataObj switchData; + auto res = CloudSyncManagerImpl::GetInstance().EnableCloud(accoutId, switchData); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " EnableCloudTest FAILED"; + } + GTEST_LOG_(INFO) << "EnableCloudTest End"; +} + +/* + * @tc.name: DisableCloudTest + * @tc.desc: Verify the DisableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, DisableCloudTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string accoutId = "accoutId"; + auto res = CloudSyncManagerImpl::GetInstance().DisableCloud(accoutId); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " DisableCloudTest FAILED"; + } + GTEST_LOG_(INFO) << "DisableCloudTest End"; +} + +/* + * @tc.name: CleanTest + * @tc.desc: Verify the Clean function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, CleanTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string accoutId = "accoutId"; + CleanOptions cleanOptions; + auto res = CloudSyncManagerImpl::GetInstance().Clean(accoutId, cleanOptions); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CleanTest FAILED"; + } + GTEST_LOG_(INFO) << "CleanTest End"; +} + +/* + * @tc.name: CleanCacheTest + * @tc.desc: Verify the CleanCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, CleanCacheTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CleanCacheTest Start"; + try { + string uri = "uri"; + auto res = CloudSyncManagerImpl::GetInstance().CleanCache(uri); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CleanCacheTest FAILED"; + } + GTEST_LOG_(INFO) << "CleanCacheTest End"; +} + +HWTEST_F(CloudSyncManagerImplTest, BatchCleanFileTest1, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchCleanFileTest1 Start"; + try { + CleanFileInfo cleanFileInfo; + std::vector fileInfo; + fileInfo.emplace_back(cleanFileInfo); + std::vector failCloudId; + auto res = CloudSyncManagerImpl::GetInstance().BatchCleanFile(fileInfo, failCloudId); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BatchCleanFileTest1 FAILED"; + } + GTEST_LOG_(INFO) << "BatchCleanFileTest1 End"; +} + +HWTEST_F(CloudSyncManagerImplTest, ResetCursorTest, TestSize.Level1) +{ + string bundleName = "com.ohos.photos"; + int res = CloudSyncManagerImpl::GetInstance().ResetCursor(bundleName); + EXPECT_EQ(res, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncManagerImplTest, StartFileCacheTest003, TestSize.Level1) +{ + std::vector uriVec = {"uri"}; + int64_t downloadId = 0; + int32_t res = CloudSyncManagerImpl::GetInstance().StartFileCache(uriVec, downloadId); + EXPECT_EQ(res, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncManagerImplTest, StopFileCacheTest, TestSize.Level1) +{ + int64_t downloadId = 0; + bool needClean = true; + int32_t res = CloudSyncManagerImpl::GetInstance().StopFileCache(downloadId, needClean); + EXPECT_EQ(res, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncManagerImplTest, DownloadThumbTest, TestSize.Level1) +{ + int32_t res = CloudSyncManagerImpl::GetInstance().DownloadThumb(); + EXPECT_EQ(res, E_PERMISSION_DENIED); +} + +/* + * @tc.name: BatchDentryFileInsertTest + * @tc.desc: Verify the BatchDentryFileInsert function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, BatchDentryFileInsertTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchDentryFileInsertTest002 Start"; + try { + std::vector fileInfo(MAX_DENTRY_FILE_SIZE - 1); + std::vector failCloudId; + int32_t result = CloudSyncManagerImpl::GetInstance().BatchDentryFileInsert(fileInfo, failCloudId); + + EXPECT_EQ(result, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " BatchDentryFileInsertTest002 FAILED"; + } + GTEST_LOG_(INFO) << "BatchDentryFileInsertTest002 End"; +} + +/** + * @tc.name: StopFileCache + * @tc.desc: Verify the StopFileCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH +**/ +HWTEST_F(CloudSyncManagerImplTest, StopFileCacheTest1, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopFileCacheTest1 Start"; + try { + CloudSyncManagerImpl &cloudSyncManagerImpl = CloudSyncManagerImpl::GetInstance(); + int64_t downloadId = 1; + bool needClean = true; + int32_t timeout = 10; + + int32_t result = cloudSyncManagerImpl.StopFileCache(downloadId, needClean, timeout); + + EXPECT_EQ(result, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StopFileCacheTest1 FAILED"; + } + GTEST_LOG_(INFO) << "StopFileCacheTest1 End"; +} + +/** + * @tc.name: RegisterCallbackTest001 + * @tc.desc: Verify the RegisterCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, RegisterCallbackTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterCallbackTest Start"; + try { + auto callback = nullptr; + int32_t res = CloudSyncManagerImpl::GetInstance().RegisterCallback(callback); + EXPECT_EQ(res, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "RegisterCallbackTest End"; +} + +/** + * @tc.name: StartSyncTest002 + * @tc.desc: Verify the StartSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, StartSyncTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartSyncTest Start"; + try { + bool forceFlag = true; + string bundleName = "com.ohos.photos"; + int32_t res = CloudSyncManagerImpl::GetInstance().StartSync(forceFlag, nullptr); + EXPECT_EQ(res, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartSyncTest FAILED"; + } + GTEST_LOG_(INFO) << "StartSyncTest End"; +} + +/** + * @tc.name: TriggerSyncTest001 + * @tc.desc: Verify the TriggerSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, TriggerSyncTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TriggerSyncTest Start"; + try { + string bundleName = ""; + int32_t userId = 0; + int32_t res = CloudSyncManagerImpl::GetInstance().TriggerSync(bundleName, userId); + EXPECT_EQ(res, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TriggerSyncTest FAILED"; + } + GTEST_LOG_(INFO) << "TriggerSyncTest End"; +} + +/* + * @tc.name: NotifyDataChangeTest + * @tc.desc: Verify the NotifyDataChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, NotifyDataChangeTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string accoutId = "accoutId"; + std::string bundleName = "bundleName"; + auto res = CloudSyncManagerImpl::GetInstance().NotifyDataChange(accoutId, bundleName); + EXPECT_EQ(res, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " NotifyDataChangeTest FAILED"; + } + GTEST_LOG_(INFO) << "NotifyDataChangeTest End"; +} + +/* + * @tc.name: RegisterDownloadFileCallbackTest + * @tc.desc: Verify the UnregisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, RegisterDownloadFileCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadFileCallbackTest Start"; + try { + shared_ptr downloadCallback = make_shared(); + auto res = CloudSyncManagerImpl::GetInstance().RegisterDownloadFileCallback(downloadCallback); + EXPECT_EQ(res, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RegisterDownloadFileCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "RegisterDownloadFileCallbackTest End"; +} + +/* + * @tc.name: SetDeathRecipientTest + * @tc.desc: Verify the SetDeathRecipient function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, SetDeathRecipientTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetDeathRecipientTest Start"; + try { + auto CloudSyncServiceProxy = ServiceProxy::GetInstance(); + CloudSyncManagerImpl::GetInstance().SetDeathRecipient(CloudSyncServiceProxy->AsObject()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetDeathRecipientTest FAILED"; + } + GTEST_LOG_(INFO) << "SetDeathRecipientTest End"; +} + +HWTEST_F(CloudSyncManagerImplTest, BatchCleanFileTest2, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchCleanFileTest2 Start"; + try { + CleanFileInfo cleanFileInfo; + std::vector fileInfo; + for (int i = 0; i < CLEAN_FILE_MAX_SIZE + 1; i++) { + cleanFileInfo.cloudId = to_string(i); + fileInfo.emplace_back(cleanFileInfo); + } + std::vector failCloudId; + auto res = CloudSyncManagerImpl::GetInstance().BatchCleanFile(fileInfo, failCloudId); + EXPECT_EQ(res, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BatchCleanFileTest2 FAILED"; + } + GTEST_LOG_(INFO) << "BatchCleanFileTest2 End"; +} + +HWTEST_F(CloudSyncManagerImplTest, StartFileCacheTest001, TestSize.Level1) +{ + std::vector uriVec; + int64_t downloadId = 0; + int32_t res = CloudSyncManagerImpl::GetInstance().StartFileCache(uriVec, downloadId); + EXPECT_EQ(res, E_INVAL_ARG); +} + +HWTEST_F(CloudSyncManagerImplTest, StartFileCacheTest002, TestSize.Level1) +{ + std::vector uriVec(MAX_FILE_CACHE_NUM + 1, "uri"); + int64_t downloadId = 0; + int32_t res = CloudSyncManagerImpl::GetInstance().StartFileCache(uriVec, downloadId); + EXPECT_EQ(res, E_EXCEED_MAX_SIZE); +} + +HWTEST_F(CloudSyncManagerImplTest, ResetProxyCallbackTest, TestSize.Level1) +{ + uint32_t retryCount = 3; + string bundleName = "testBundle"; + auto res = CloudSyncManagerImpl::GetInstance().ResetProxyCallback(retryCount, bundleName); + EXPECT_EQ(res, true); +} + +/* + * @tc.name: BatchDentryFileInsertTest + * @tc.desc: Verify the BatchDentryFileInsert function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, BatchDentryFileInsertTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchDentryFileInsertTest001 Start"; + try { + std::vector fileInfo(MAX_DENTRY_FILE_SIZE + 1); + std::vector failCloudId; + int32_t result = CloudSyncManagerImpl::GetInstance().BatchDentryFileInsert(fileInfo, failCloudId); + + EXPECT_EQ(result, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " BatchDentryFileInsertTest001 FAILED"; + } + GTEST_LOG_(INFO) << "BatchDentryFileInsertTest001 End"; +} + + /* + * @tc.name: OnAddSystemAbilityTest + * @tc.desc: Verify the OnAddSystemAbility function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, OnAddSystemAbilityTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest001 Start"; + try { + string bundleName = "testbundleName"; + CloudSyncManagerImpl::SystemAbilityStatusChange statusChange(bundleName); + int32_t systemAbilityId = 1; + std::string deviceId = "testDeviceId"; + + EXPECT_NO_THROW(statusChange.OnAddSystemAbility(systemAbilityId, deviceId)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnAddSystemAbilityTest001 FAILED"; + } + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest001 End"; +} + + /* + * @tc.name: CleanGalleryDentryFile + * @tc.desc: Verify the CleanGalleryDentryFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, CleanGalleryDentryFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CleanGalleryDentryFileTest001 Start"; + try { + managePtr_->CleanGalleryDentryFile(); + + EXPECT_FALSE(fs::exists("/storage/media/cloud/files/Photo")); + EXPECT_FALSE(fs::exists("/storage/media/cloud/files/.thumbs/Photo")); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CleanGalleryDentryFileTest001 FAILED"; + } + GTEST_LOG_(INFO) << "CleanGalleryDentryFileTest001 End"; +} + + /* + * @tc.name: CleanGalleryDentryFile + * @tc.desc: Verify the CleanGalleryDentryFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, CleanGalleryDentryFileTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CleanGalleryDentryFileTest002 Start"; + try { + fs::remove_all("/storage/media/cloud/files/Photo"); + fs::remove_all("/storage/media/cloud/files/.thumbs/Photo"); + + managePtr_->CleanGalleryDentryFile(); + + EXPECT_FALSE(fs::exists("/storage/media/cloud/files/Photo")); + EXPECT_FALSE(fs::exists("/storage/media/cloud/files/.thumbs/Photo")); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CleanGalleryDentryFileTest002 FAILED"; + } + GTEST_LOG_(INFO) << "CleanGalleryDentryFileTest002 End"; +} + + /* + * @tc.name: ResetProxyCallback + * @tc.desc: Verify the ResetProxyCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, ResetProxyCallbackTest1, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CleanGalleryDentryFileTest002 Start"; + try { + CloudSyncManagerImpl cloudSyncManagerImpl; + + EXPECT_TRUE(cloudSyncManagerImpl.ResetProxyCallback(1, "testBundle")); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CleanGalleryDentryFileTest002 FAILED"; + } + GTEST_LOG_(INFO) << "CleanGalleryDentryFileTest002 End"; +} + + /* + * @tc.name: ResetProxyCallback + * @tc.desc: Verify the ResetProxyCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, ResetProxyCallbackTest2, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ResetProxyCallbackTest2 Start"; + try { + CloudSyncManagerImpl cloudSyncManagerImpl; + ServiceProxy::GetInstance(); + + EXPECT_TRUE(cloudSyncManagerImpl.ResetProxyCallback(1, "testBundle")); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ResetProxyCallbackTest2 FAILED"; + } + GTEST_LOG_(INFO) << "ResetProxyCallbackTest2 End"; +} + + /* + * @tc.name: SubscribeListener + * @tc.desc: Verify the SubscribeListener function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerImplTest, SubscribeListenerTest1, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SubscribeListenerTest1 Start"; + try { + CloudSyncManagerImpl cloudSyncManagerImpl; + cloudSyncManagerImpl.SubscribeListener("testBundleName"); + + EXPECT_EQ(cloudSyncManagerImpl.listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SubscribeListenerTest1 FAILED"; + } + GTEST_LOG_(INFO) << "SubscribeListenerTest1 End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_impl_unnomal_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_impl_unnomal_test.cpp new file mode 100644 index 0000000..a43679a --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_impl_unnomal_test.cpp @@ -0,0 +1,300 @@ +/* + * 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 +#include + +#include "cloud_sync_manager_impl.h" +#include "service_proxy.h" +#include "dfs_error.h" +#include "i_cloud_sync_service_mock.h" +#include "iservice_registry.h" +#include "service_callback_mock.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace testing; +using namespace std; + +class CloudSyncManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr managePtr_; +}; + +class CloudSyncCallbackDerived : public CloudSyncCallback { +public: + void OnSyncStateChanged(CloudSyncState state, ErrorType error) + { + std::cout << "OnSyncStateChanged" << std::endl; + } +}; + +void CloudSyncManagerTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncManagerTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncManagerTest::SetUp(void) +{ + managePtr_ = make_shared(); + std::cout << "SetUp" << std::endl; +} + +void CloudSyncManagerTest::TearDown(void) +{ + managePtr_ = nullptr; + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: RegisterCallbackTest + * @tc.desc: Verify the RegisterCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, RegisterCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterCallbackTest Start"; + try { + shared_ptr callback = make_shared(); + auto res = managePtr_->RegisterCallback(callback); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RegisterCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "RegisterCallbackTest End"; +} + +/** + * @tc.name: StartSyncTest + * @tc.desc: Verify the StartSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, StartSyncTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartSyncTest Start"; + try { + bool forceFlag = false; + shared_ptr callback = make_shared(); + auto res = managePtr_->StartSync(); + EXPECT_EQ(res, E_PERMISSION_DENIED); + res = managePtr_->StartSync(forceFlag, callback); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StartSyncTest FAILED"; + } + GTEST_LOG_(INFO) << "StartSyncTest End"; +} + +/* + * @tc.name: StopSyncTest + * @tc.desc: Verify the StopSync function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, StopSyncTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopSyncTest Start"; + try { + int res = managePtr_->StopSync(); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StopSyncTest FAILED"; + } + GTEST_LOG_(INFO) << "StopSyncTest End"; +} + +/* + * @tc.name: ChangeAppSwitchTest + * @tc.desc: Verify the ChangeAppSwitch function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, ChangeAppSwitchTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChangeAppSwitchTest Start"; + try { + std::string accoutId = "accoutId"; + std::string bundleName = "bundleName"; + bool status = true; + auto res = managePtr_->ChangeAppSwitch(accoutId, bundleName, status); + EXPECT_EQ(res, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ChangeAppSwitchTest FAILED"; + } + GTEST_LOG_(INFO) << "ChangeAppSwitchTest End"; +} + +/* + * @tc.name: NotifyDataChangeTest + * @tc.desc: Verify the NotifyDataChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, NotifyDataChangeTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string accoutId = "accoutId"; + std::string bundleName = "bundleName"; + auto res = managePtr_->NotifyDataChange(accoutId, bundleName); + EXPECT_EQ(res, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " NotifyDataChangeTest FAILED"; + } + GTEST_LOG_(INFO) << "NotifyDataChangeTest End"; +} + +/* + * @tc.name: StartDownloadFileTest + * @tc.desc: Verify the StartDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, StartDownloadFileTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string uri = "uri"; + auto res = managePtr_->StartDownloadFile(uri); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StartDownloadFileTest FAILED"; + } + GTEST_LOG_(INFO) << "StartDownloadFileTest End"; +} + +/* + * @tc.name: StopDownloadFileTest + * @tc.desc: Verify the StopDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, StopDownloadFileTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string uri = "uri"; + auto res = managePtr_->StopDownloadFile(uri); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StopDownloadFileTest FAILED"; + } + GTEST_LOG_(INFO) << "StopDownloadFileTest End"; +} + +/* + * @tc.name: RegisterDownloadFileCallbackTest + * @tc.desc: Verify the UnregisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, RegisterDownloadFileCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + auto res = managePtr_->UnregisterDownloadFileCallback(); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RegisterDownloadFileCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "RegisterDownloadFileCallbackTest End"; +} + +/* + * @tc.name: EnableCloudTest + * @tc.desc: Verify the EnableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, EnableCloudTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string accoutId = "accoutId"; + SwitchDataObj switchData; + auto res = managePtr_->EnableCloud(accoutId, switchData); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " EnableCloudTest FAILED"; + } + GTEST_LOG_(INFO) << "EnableCloudTest End"; +} + +/* + * @tc.name: DisableCloudTest + * @tc.desc: Verify the DisableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, DisableCloudTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string accoutId = "accoutId"; + auto res = managePtr_->DisableCloud(accoutId); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " DisableCloudTest FAILED"; + } + GTEST_LOG_(INFO) << "DisableCloudTest End"; +} + +/* + * @tc.name: CleanTest + * @tc.desc: Verify the Clean function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncManagerTest, CleanTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChangeTest Start"; + try { + std::string accoutId = "accoutId"; + CleanOptions cleanOptions; + auto res = managePtr_->Clean(accoutId, cleanOptions); + EXPECT_EQ(res, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CleanTest FAILED"; + } + GTEST_LOG_(INFO) << "CleanTest End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_test.cpp new file mode 100644 index 0000000..f64f16f --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_manager_test.cpp @@ -0,0 +1,73 @@ +/* + * 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 + +#include "cloud_sync_manager_impl.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing::ext; +using namespace testing; +using namespace std; + +class CloudSyncManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudSyncManagerTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncManagerTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncManagerTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncManagerTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: GetInstanceTest + * @tc.desc: Verify the GetInstance function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(CloudSyncManagerTest, GetInstanceTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest Begin"; + try { + CloudSyncManager::GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest ERROR"; + } + + GTEST_LOG_(INFO) << "GetInstanceTest End"; +} + +} // namespace OHOS::FileManagement::CloudSync::Test diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_service_proxy_lite_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_service_proxy_lite_test.cpp new file mode 100644 index 0000000..a8fa533 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_service_proxy_lite_test.cpp @@ -0,0 +1,232 @@ +/* + * 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 +#include +#define protect public +#include "cloud_sync_service_proxy.h" +#include "dfs_error.h" +#include "i_cloud_download_callback_mock.h" +#include "i_cloud_sync_service_mock.h" +#include "service_callback_mock.h" + +#include "peer_holder.h" +#include "if_system_ability_manager.h" +#include "system_ability_manager_client_mock.h" +#include "if_system_ability_manager_mock.h" +#include "cloud_sync_service_proxy_lite.cpp" + +#undef protect +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace testing; +using namespace std; + +static const int64_t FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID = 5204; + +class CloudSyncServiceProxyLiteTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + shared_ptr proxy_ = nullptr; + sptr mock_ = nullptr; + sptr remote_ = nullptr; + sptr download_ = nullptr; + static inline shared_ptr smc_ = nullptr; + static inline shared_ptr samgr = make_shared(); +}; + +void CloudSyncServiceProxyLiteTest::SetUpTestCase(void) +{ + smc_ = make_shared(); + SystemAbilityManagerClientMock::smc = smc_; + SystemAbilityManagerClient::GetInstance().systemAbilityManager_ = sptr(samgr.get()); + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncServiceProxyLiteTest::TearDownTestCase(void) +{ + SystemAbilityManagerClientMock::smc = nullptr; + smc_ = nullptr; + samgr = nullptr; + SystemAbilityManagerClient::GetInstance().systemAbilityManager_ = nullptr; + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncServiceProxyLiteTest::SetUp(void) +{ + mock_ = sptr(new CloudSyncServiceMock()); + proxy_ = make_shared(mock_); + remote_ = sptr(new CloudSyncCallbackMock()); + download_ = sptr(new CloudDownloadCallbackMock()); + std::cout << "SetUp" << std::endl; +} + +void CloudSyncServiceProxyLiteTest::TearDown(void) +{ + proxy_ = nullptr; + mock_ = nullptr; + remote_ = nullptr; + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: TriggerSyncInnerInner001 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyLiteTest, TriggerSyncInner001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TriggerSyncInner Start"; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->TriggerSyncInner(bundleName, userId); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "TriggerSyncInner End"; +} + +/** + * @tc.name: TriggerSyncInner002 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyLiteTest, TriggerSyncInner002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TriggerSyncInner Start"; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->TriggerSyncInner(bundleName, userId); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "TriggerSyncInner End"; +} + +/** + * @tc.name: OnLoadSystemAbilityTest001 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyLiteTest, OnLoadSystemAbilityTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnLoadSystemAbilityTest001 Start"; + + sptr remoteObject = sptr(new CloudSyncServiceMock()); + int32_t systemAbilityId = FILEMANAGEMENT_CLOUD_SYNC_SERVICE_SA_ID; + sptr callback = + new CloudSyncServiceProxy::ServiceProxyLoadCallback(); + callback->OnLoadSystemAbilitySuccess(systemAbilityId, remoteObject); + callback->OnLoadSystemAbilitySuccess(systemAbilityId, remoteObject); + EXPECT_TRUE(callback->isLoadSuccess_.load()); + + GTEST_LOG_(INFO) << "OnLoadSystemAbilityTest001 End"; +} + +/** + * @tc.name: OnLoadSystemAbilityTest001 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyLiteTest, GetInstanceTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest001 Start"; + try { + auto CloudSyncServiceProxy = CloudSyncServiceProxy::GetInstance(); + EXPECT_NE(CloudSyncServiceProxy, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetInstanceTest001 End"; +} + +/** + * @tc.name: GetInstanceTest002 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyLiteTest, GetInstanceTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest002 Start"; + EXPECT_CALL(*smc_, GetSystemAbilityManager()).WillOnce(Return(nullptr)); + shared_ptr proxy_ = make_shared(nullptr); + proxy_->serviceProxy_ = nullptr; + auto ret = proxy_->GetInstance(); + EXPECT_TRUE(ret == nullptr); + GTEST_LOG_(INFO) << "GetInstanceTest002 End"; +} + +/** + * @tc.name: GetInstanceTest003 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyLiteTest, GetInstanceTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest003 Start"; + try { + auto sysAbilityManager = sptr(new ISystemAbilityManagerMock()); + EXPECT_CALL(*smc_, GetSystemAbilityManager()).WillOnce(Return(sysAbilityManager)); + EXPECT_CALL(*sysAbilityManager, LoadSystemAbility(An(), An&>())) + .WillOnce(Return(E_PERMISSION)); + shared_ptr proxy_ = make_shared(nullptr); + proxy_->serviceProxy_ = nullptr; + auto ret = proxy_->GetInstance(); + EXPECT_TRUE(ret == nullptr); + } catch (...) { + GTEST_LOG_(ERROR) << "GetInstanceTest003 occurs an exception."; + } + GTEST_LOG_(INFO) << "GetInstanceTest003 End"; +} + +/** + * @tc.name: GetInstanceTest004 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyLiteTest, GetInstanceTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest004 Start"; + try { + auto sysAbilityManager = sptr(new ISystemAbilityManagerMock()); + EXPECT_CALL(*smc_, GetSystemAbilityManager()).WillOnce(Return(sysAbilityManager)); + EXPECT_CALL(*sysAbilityManager, LoadSystemAbility(An(), An&>())) + .WillOnce(Return(ERR_OK)); + shared_ptr proxy_ = make_shared(nullptr); + proxy_->serviceProxy_ = nullptr; + auto ret = proxy_->GetInstance(); + EXPECT_TRUE(ret == nullptr); + } catch (...) { + GTEST_LOG_(ERROR) << "GetInstanceTest004 occurs an exception."; + } + GTEST_LOG_(INFO) << "GetInstanceTest004 End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync { +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_service_proxy_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_service_proxy_test.cpp new file mode 100644 index 0000000..2675969 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/cloud_sync_service_proxy_test.cpp @@ -0,0 +1,1111 @@ +/* + * 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 +#include + +#include "cloud_sync_service_proxy.h" +#include "dfs_error.h" +#include "i_cloud_download_callback_mock.h" +#include "i_cloud_sync_service_mock.h" +#include "service_callback_mock.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace testing; +using namespace std; + +class CloudSyncServiceProxyTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + shared_ptr proxy_ = nullptr; + sptr mock_ = nullptr; + sptr remote_ = nullptr; + sptr download_ = nullptr; +}; + +void CloudSyncServiceProxyTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncServiceProxyTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncServiceProxyTest::SetUp(void) +{ + mock_ = sptr(new CloudSyncServiceMock()); + proxy_ = make_shared(mock_); + remote_ = sptr(new CloudSyncCallbackMock()); + download_ = sptr(new CloudDownloadCallbackMock()); + std::cout << "SetUp" << std::endl; +} + +void CloudSyncServiceProxyTest::TearDown(void) +{ + proxy_ = nullptr; + mock_ = nullptr; + remote_ = nullptr; + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: UnRegisterCallbackInner001 + * @tc.desc: Verify the UnRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudSyncServiceProxyTest, UnRegisterCallbackInner001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnRegisterCallbackInner Start"; + string bundleName = "com.ohos.photos"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int result = proxy_->UnRegisterCallbackInner(bundleName); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "UnRegisterCallbackInner End"; +} + +/** + * @tc.name: UnRegisterCallbackInner002 + * @tc.desc: Verify the RRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudSyncServiceProxyTest, UnRegisterCallbackInner002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnRegisterCallbackInner Start"; + string bundleName = "com.ohos.photos"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int result = proxy_->UnRegisterCallbackInner(bundleName); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "UnRegisterCallbackInner End"; +} + + +/** + * @tc.name: RegisterCallbackInner001 + * @tc.desc: Verify the RegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterCallbackInner001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterCallbackInner Start"; + string bundleName = "com.ohos.photos"; + + int result = proxy_->RegisterCallbackInner(nullptr, bundleName); + EXPECT_EQ(result, E_INVAL_ARG); + GTEST_LOG_(INFO) << "RegisterCallbackInner End"; +} + +/** + * @tc.name: RegisterCallbackInner002 + * @tc.desc: Verify the RegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterCallbackInner002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterCallbackInner Start"; + string bundleName = "com.ohos.photos"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->RegisterCallbackInner(remote_, bundleName); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "RegisterCallbackInner End"; +} + +/** + * @tc.name: RegisterCallbackInner003 + * @tc.desc: Verify the RegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterCallbackInner003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterCallbackInner Start"; + string bundleName = "com.ohos.photos"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->RegisterCallbackInner(remote_, bundleName); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "RegisterCallbackInner End"; +} + +/** + * @tc.name: StartSyncInner001 + * @tc.desc: Verify the StartSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StartSyncInner001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartSyncInner Start"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + bool forceFlag = true; + int result = proxy_->StartSyncInner(forceFlag); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "StartSyncInner End"; +} + +/** + * @tc.name: StartSyncInner002 + * @tc.desc: Verify the StartSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StartSyncInner002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartSyncInner Start"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Invoke(mock_.GetRefPtr(), &CloudSyncServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); + + bool forceFlag = true; + int result = proxy_->StartSyncInner(forceFlag); + EXPECT_EQ(result, E_OK); + + result = proxy_->StartSyncInner(forceFlag); + EXPECT_NE(result, E_OK); + GTEST_LOG_(INFO) << "StartSyncInner End"; +} + +/** + * @tc.name: TriggerSyncInnerInner001 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, TriggerSyncInner001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TriggerSyncInner Start"; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->TriggerSyncInner(bundleName, userId); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "TriggerSyncInner End"; +} + +/** + * @tc.name: TriggerSyncInner002 + * @tc.desc: Verify the TriggerSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, TriggerSyncInner002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TriggerSyncInner Start"; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->TriggerSyncInner(bundleName, userId); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "TriggerSyncInner End"; +} + +/** + * @tc.name: GetSyncTimeInner001 + * @tc.desc: Verify the GetSyncTimeInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, GetSyncTimeInner001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSyncTimeInner Start"; + string bundleName = "com.ohos.photos"; + int64_t syncTime = 0; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->GetSyncTimeInner(syncTime, bundleName); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "GetSyncTimeInner End"; +} + +/** + * @tc.name: GetSyncTimeInner002 + * @tc.desc: Verify the GetSyncTimeInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, GetSyncTimeInner002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSyncTimeInner Start"; + string bundleName = "com.ohos.photos"; + int64_t syncTime = 0; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->GetSyncTimeInner(syncTime, bundleName); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "GetSyncTimeInner End"; +} + +/** + * @tc.name: BatchDentryFileInsert001 + * @tc.desc: Verify the BatchCleanFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, BatchDentryFileInsert001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchDentryFileInsert001 Start"; + std::vector fileInfoObj; + std::vector failCloudId; + int ret = proxy_->BatchDentryFileInsert(fileInfoObj, failCloudId); + EXPECT_EQ(ret, E_INVAL_ARG); + GTEST_LOG_(INFO) << "BatchDentryFileInsert001 End"; +} + +/** + * @tc.name: BatchDentryFileInsert002 + * @tc.desc: Verify the BatchCleanFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, BatchDentryFileInsert002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchDentryFileInsert002 Start"; + DentryFileInfo obj; + std::vector fileInfoObj; + fileInfoObj.push_back(obj); + std::vector failCloudId; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int ret = proxy_->BatchDentryFileInsert(fileInfoObj, failCloudId); + EXPECT_EQ(ret, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "BatchDentryFileInsert002 End"; +} + +/** + * @tc.name: BatchDentryFileInsert003 + * @tc.desc: Verify the BatchCleanFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, BatchDentryFileInsert003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchDentryFileInsert003 Start"; + DentryFileInfo obj; + std::vector fileInfoObj; + fileInfoObj.push_back(obj); + std::vector failCloudId; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int ret = proxy_->BatchDentryFileInsert(fileInfoObj, failCloudId); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "BatchDentryFileInsert003 End"; +} + +/** + * @tc.name: CleanCacheInner001 + * @tc.desc: Verify the CleanCacheInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, CleanCacheInner001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CleanCacheInner Start"; + string uri = ""; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->CleanCacheInner(uri); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "CleanCacheInner End"; +} + +/** + * @tc.name: CleanCacheInner002 + * @tc.desc: Verify the CleanCacheInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, CleanCacheInner002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CleanCacheInner Start"; + string uri = ""; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->CleanCacheInner(uri); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "CleanCacheInner End"; +} + +/** + * @tc.name: StopSyncInner001 + * @tc.desc: Verify the StopSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StopSyncInner001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopSyncInner Start"; + string bundleName = "com.ohos.photos"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->StopSyncInner(bundleName); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "StopSyncInner End"; +} + +/** + * @tc.name: StopSyncInner002 + * @tc.desc: Verify the StopSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StopSyncInner002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopSyncInner Start"; + string bundleName = "com.ohos.photos"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->StopSyncInner(bundleName); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "StopSyncInner End"; +} + +/** + * @tc.name: ChangeAppSwitch001 + * @tc.desc: Verify the ChangeAppSwitch function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, ChangeAppSwitch001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChangeAppSwitch Start"; + string accoutId = "100"; + string bundleName = "com.ohos.photos"; + bool status = true; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->ChangeAppSwitch(accoutId, bundleName, status); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "ChangeAppSwitch End"; +} + +/** + * @tc.name: ChangeAppSwitch002 + * @tc.desc: Verify the ChangeAppSwitch function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, ChangeAppSwitch002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChangeAppSwitch Start"; + string accoutId = "100"; + string bundleName = "com.ohos.photos"; + bool status = true; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->ChangeAppSwitch(accoutId, bundleName, status); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "ChangeAppSwitch End"; +} + +/** + * @tc.name: Clean001 + * @tc.desc: Verify the Clean function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, Clean001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Clean Start"; + string accoutId = "100"; + CleanOptions cleanOptions; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->Clean(accoutId, cleanOptions); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "Clean End"; +} + +/** + * @tc.name: Clean002 + * @tc.desc: Verify the Clean function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, Clean002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Clean Start"; + string accoutId = "100"; + CleanOptions cleanOptions; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->Clean(accoutId, cleanOptions); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "Clean End"; +} + +/** + * @tc.name: EnableCloud001 + * @tc.desc: Verify the EnableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, EnableCloud001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnableCloud Start"; + string accoutId = "100"; + SwitchDataObj switchData; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->EnableCloud(accoutId, switchData); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "EnableCloud End"; +} + +/** + * @tc.name: EnableCloud002 + * @tc.desc: Verify the EnableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, EnableCloud002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnableCloud Start"; + string accoutId = "100"; + SwitchDataObj switchData; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->EnableCloud(accoutId, switchData); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "EnableCloud End"; +} + +/** + * @tc.name: DisableCloud001 + * @tc.desc: Verify the DisableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DisableCloud001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DisableCloud Start"; + string accoutId = "100"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->DisableCloud(accoutId); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "DisableCloud End"; +} + +/** + * @tc.name: DisableCloud002 + * @tc.desc: Verify the DisableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DisableCloud002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DisableCloud Start"; + string accoutId = "100"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->DisableCloud(accoutId); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "DisableCloud End"; +} + +/** + * @tc.name: NotifyDataChange001 + * @tc.desc: Verify the NotifyDataChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, NotifyDataChange001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChange Start"; + string accoutId = "100"; + string bundleName = "com.ohos.photos"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->NotifyDataChange(accoutId, bundleName); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "NotifyDataChange End"; +} + +/** + * @tc.name: NotifyDataChange002 + * @tc.desc: Verify the NotifyDataChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, NotifyDataChange002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyDataChange Start"; + string accoutId = "100"; + string bundleName = "com.ohos.photos"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->NotifyDataChange(accoutId, bundleName); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "NotifyDataChange End"; +} + +/** + * @tc.name: NotifyEventChange001 + * @tc.desc: Verify the NotifyEventChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, NotifyEventChange001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyEventChange Start"; + int32_t userId = 100; + string eventId = ""; + string extraData = ""; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->NotifyEventChange(userId, eventId, extraData); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "NotifyEventChange End"; +} + +/** + * @tc.name: NotifyEventChange002 + * @tc.desc: Verify the NotifyEventChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, NotifyEventChange002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyEventChange Start"; + int32_t userId = 100; + string eventId = ""; + string extraData = ""; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->NotifyEventChange(userId, eventId, extraData); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "NotifyEventChange End"; +} + +/** + * @tc.name: StartDownloadFile001 + * @tc.desc: Verify the StartDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StartDownloadFile001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartDownloadFile Start"; + string uri = "file://media"; + int result = proxy_->StartDownloadFile(uri); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "StartDownloadFile End"; +} + +/** + * @tc.name: StartDownloadFile002 + * @tc.desc: Verify the StartDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StartDownloadFile002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartDownloadFile Start"; + string uri = ""; + int result = proxy_->StartDownloadFile(uri); + EXPECT_EQ(result, E_INVAL_ARG); + GTEST_LOG_(INFO) << "StartDownloadFile End"; +} + +/** + * @tc.name: StartFileCache001 + * @tc.desc: Verify the StartFileCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StartFileCache001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFileCache Start"; + string uri = "file://media"; + std::vector uriVec; + uriVec.push_back(uri); + int64_t downloadId = 0; + int result = proxy_->StartFileCache(uriVec, downloadId); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "StartFileCache End"; +} + +/** + * @tc.name: StartFileCache002 + * @tc.desc: Verify the StartFileCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StartFileCache002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFileCache Start"; + string uri = ""; + std::vector uriVec; + uriVec.push_back(uri); + int64_t downloadId = 0; + int result = proxy_->StartFileCache(uriVec, downloadId); + EXPECT_EQ(result, E_INVAL_ARG); + GTEST_LOG_(INFO) << "StartFileCache End"; +} + +/** + * @tc.name: StopDownloadFile001 + * @tc.desc: Verify the StopDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StopDownloadFile001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopDownloadFile Start"; + string uri = "file://media"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->StopDownloadFile(uri); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "StopDownloadFile End"; +} + +/** + * @tc.name: StopDownloadFile002 + * @tc.desc: Verify the StopDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StopDownloadFile002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopDownloadFile Start"; + string uri = "file://media"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->StopDownloadFile(uri); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "StopDownloadFile End"; +} + +/** + * @tc.name: StopDownloadFile003 + * @tc.desc: Verify the StopDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, StopDownloadFile003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopDownloadFile Start"; + string uri = ""; + + int result = proxy_->StopDownloadFile(uri); + EXPECT_EQ(result, E_INVAL_ARG); + GTEST_LOG_(INFO) << "StopDownloadFile End"; +} + +/** + * @tc.name: UploadAsset001 + * @tc.desc: Verify the UploadAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, UploadAsset001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UploadAsset001 Start"; + int32_t userId = 100; + string request = "test_request"; + string result; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int ret = proxy_->UploadAsset(userId, request, result); + EXPECT_EQ(ret, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "UploadAsset001 End"; +} + +/** + * @tc.name: UploadAsset002 + * @tc.desc: Verify the UploadAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, UploadAsset002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UploadAsset002 Start"; + int32_t userId = 100; + string request = "test_request"; + string result; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int ret = proxy_->UploadAsset(userId, request, result); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "UploadAsset002 End"; +} + +/** + * @tc.name: DownloadFile001 + * @tc.desc: Verify the DownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DownloadFile001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFile001 Start"; + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + AssetInfoObj assetInfoObj; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int ret = proxy_->DownloadFile(userId, bundleName, assetInfoObj); + EXPECT_EQ(ret, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "DownloadFile001 End"; +} + +/** + * @tc.name: DownloadFile002 + * @tc.desc: Verify the DownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DownloadFile002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFile002 Start"; + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + AssetInfoObj assetInfoObj; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int ret = proxy_->DownloadFile(userId, bundleName, assetInfoObj); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "DownloadFile002 End"; +} + +/** + * @tc.name: DownloadFiles001 + * @tc.desc: Verify the DownloadFiles function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DownloadFiles001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFiles001 Start"; + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + std::vector assetInfoObj; + std::vector assetResultMap; + int ret = proxy_->DownloadFiles(userId, bundleName, assetInfoObj, assetResultMap); + EXPECT_EQ(ret, E_INVAL_ARG); + GTEST_LOG_(INFO) << "DownloadFiles001 End"; +} + +/** + * @tc.name: DownloadFiles002 + * @tc.desc: Verify the DownloadFiles function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DownloadFiles002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFiles002 Start"; + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + AssetInfoObj obj; + std::vector assetInfoObj; + assetInfoObj.push_back(obj); + std::vector assetResultMap; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int ret = proxy_->DownloadFiles(userId, bundleName, assetInfoObj, assetResultMap); + EXPECT_EQ(ret, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "DownloadFiles002 End"; +} + +/** + * @tc.name: DownloadFiles003 + * @tc.desc: Verify the DownloadFiles function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DownloadFiles003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFiles002 Start"; + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + AssetInfoObj obj; + std::vector assetInfoObj; + assetInfoObj.push_back(obj); + std::vector assetResultMap; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int ret = proxy_->DownloadFiles(userId, bundleName, assetInfoObj, assetResultMap); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "DownloadFiles002 End"; +} + +/** + * @tc.name: DownloadAsset001 + * @tc.desc: Verify the DownloadAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DownloadAsset001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadAsset001 Start"; + uint64_t taskId = 100; + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + string networkId = ""; + AssetInfoObj assetInfoObj; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int ret = proxy_->DownloadAsset(taskId, userId, bundleName, networkId, assetInfoObj); + EXPECT_EQ(ret, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "DownloadAsset001 End"; +} + +/** + * @tc.name: DownloadAsset002 + * @tc.desc: Verify the DownloadAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DownloadAsset002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadAsset002 Start"; + uint64_t taskId = 100; + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + string networkId = ""; + AssetInfoObj assetInfoObj; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int ret = proxy_->DownloadAsset(taskId, userId, bundleName, networkId, assetInfoObj); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "DownloadAsset002 End"; +} + +/** + * @tc.name: RegisterDownloadAssetCallback001 + * @tc.desc: Verify the RegisterDownloadAssetCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterDownloadAssetCallback001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback Start"; + + int ret = proxy_->RegisterDownloadAssetCallback(nullptr); + EXPECT_EQ(ret, E_INVAL_ARG); + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback End"; +} + +/** + * @tc.name: RegisterDownloadAssetCallback002 + * @tc.desc: Verify the RegisterDownloadAssetCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterDownloadAssetCallback002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback Start"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int ret = proxy_->RegisterDownloadAssetCallback(remote_); + EXPECT_EQ(ret, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback End"; +} + +/** + * @tc.name: RegisterDownloadAssetCallback003 + * @tc.desc: Verify the RegisterDownloadAssetCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterDownloadAssetCallback003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback Start"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int ret = proxy_->RegisterDownloadAssetCallback(remote_); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback End"; +} + +/** + * @tc.name: DeleteAsset001 + * @tc.desc: Verify the DeleteAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DeleteAsset001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeleteAsset001 Start"; + int32_t userId = 100; + string uri = "file://media"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int ret = proxy_->DeleteAsset(userId, uri); + EXPECT_EQ(ret, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "DeleteAsset001 End"; +} + +/** + * @tc.name: DeleteAsset002 + * @tc.desc: Verify the DeleteAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, DeleteAsset002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeleteAsset002 Start"; + int32_t userId = 100; + string uri = "file://media"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int ret = proxy_->DeleteAsset(userId, uri); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "DeleteAsset002 End"; +} + +/** + * @tc.name: RegisterDownloadFileCallback001 + * @tc.desc: Verify the RegisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterDownloadFileCallback001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback Start"; + string bundleName = "com.ohos.photos"; + + int result = proxy_->RegisterDownloadFileCallback(nullptr); + EXPECT_EQ(result, E_INVAL_ARG); + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback End"; +} + +/** + * @tc.name: RegisterDownloadFileCallback002 + * @tc.desc: Verify the RegisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterDownloadFileCallback002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback Start"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + + int result = proxy_->RegisterDownloadFileCallback(remote_); + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback End"; +} + +/** + * @tc.name: RegisterDownloadFileCallback003 + * @tc.desc: Verify the RegisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, RegisterDownloadFileCallback003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback Start"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + + int result = proxy_->RegisterDownloadFileCallback(remote_); + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback End"; +} + +/** + * @tc.name: UnregisterDownloadFileCallback001 + * @tc.desc: Verify the UnegisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudSyncServiceProxyTest, UnregisterDownloadFileCallback001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallback Start"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int result = proxy_->UnregisterDownloadFileCallback(); + + EXPECT_EQ(result, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallback End"; +} + +/** + * @tc.name: UnregisterDownloadFileCallback002 + * @tc.desc: Verify the UnegisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(CloudSyncServiceProxyTest, UnregisterDownloadFileCallback002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallback Start"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int result = proxy_->UnregisterDownloadFileCallback(); + + EXPECT_EQ(result, E_OK); + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallback End"; +} + +/** + * @tc.name: BatchCleanFile001 + * @tc.desc: Verify the BatchCleanFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, BatchCleanFile001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchCleanFile001 Start"; + std::vector fileInfoObj; + std::vector failCloudId; + int ret = proxy_->BatchCleanFile(fileInfoObj, failCloudId); + EXPECT_EQ(ret, E_INVAL_ARG); + GTEST_LOG_(INFO) << "BatchCleanFile001 End"; +} + +/** + * @tc.name: DeleteFilesInner002 + * @tc.desc: Verify the BatchCleanFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, BatchCleanFile002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchCleanFile002 Start"; + CleanFileInfo obj; + std::vector fileInfoObj; + fileInfoObj.push_back(obj); + std::vector failCloudId; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + int ret = proxy_->BatchCleanFile(fileInfoObj, failCloudId); + EXPECT_EQ(ret, E_BROKEN_IPC); + GTEST_LOG_(INFO) << "DownloadFiles002 End"; +} + +/** + * @tc.name: BatchCleanFile003 + * @tc.desc: Verify the BatchCleanFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceProxyTest, BatchCleanFile003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BatchCleanFile003 Start"; + CleanFileInfo obj; + std::vector fileInfoObj; + fileInfoObj.push_back(obj); + std::vector failCloudId; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + int ret = proxy_->BatchCleanFile(fileInfoObj, failCloudId); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "DeleteFilesInner003 End"; +} +} // namespace Test +} // namespace FileManagement::CloudSync { +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/download_asset_callback_client_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/download_asset_callback_client_test.cpp new file mode 100644 index 0000000..4891d19 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/download_asset_callback_client_test.cpp @@ -0,0 +1,149 @@ +/* + * 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 +#include + +#include "download_asset_callback_client.h" +#include "asset_callback_mock.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace std; + +class DownloadAssetCallbackClientTest : public testing::Test { +public: + using TaskId = uint64_t; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DownloadAssetCallbackClientTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void DownloadAssetCallbackClientTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void DownloadAssetCallbackClientTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void DownloadAssetCallbackClientTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: OnFinishedTest001 + * @tc.desc: Verify the OnFinished function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(DownloadAssetCallbackClientTest, OnFinishedTest001, TestSize.Level1) +{ + DownloadAssetCallbackClient client; + TaskId taskId = 1; + std::string uri = "file://data/file/test"; + int32_t result = 0; + auto callback = [](const std::string &uri, const int32_t result) { + EXPECT_EQ(uri, "file://data/file/test"); + EXPECT_EQ(result, 0); + }; + client.GetDownloadTaskCallback(taskId) = callback; + + client.OnFinished(taskId, uri, result); + + EXPECT_EQ(client.GetDownloadTaskCallback(taskId), nullptr); +} + + /** + * @tc.name: OnFinishedTest002 + * @tc.desc: Verify the OnFinished function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(DownloadAssetCallbackClientTest, OnFinishedTest002, TestSize.Level1) +{ + DownloadAssetCallbackClient client; + TaskId taskId = 1; + std::string uri = "file://data/file/test"; + int32_t result = 0; + + client.OnFinished(taskId, uri, result); + + EXPECT_EQ(client.GetDownloadTaskCallback(taskId), nullptr); +} + + /** + * @tc.name: RemoveDownloadTaskCallbackTest001 + * @tc.desc: Verify the OnFinished function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(DownloadAssetCallbackClientTest, RemoveDownloadTaskCallbackTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RemoveDownloadTaskCallbackTest001 Start"; + try { + DownloadAssetCallbackClient client; + TaskId taskId = 1; + CloudSyncAssetManager::ResultCallback callback; + client.callbackListMap_.Insert(taskId, callback); + client.RemoveDownloadTaskCallback(taskId); + + EXPECT_FALSE(client.callbackListMap_.Find(taskId, callback)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RemoveDownloadTaskCallbackTest001 ERROR"; + } + GTEST_LOG_(INFO) << "RemoveDownloadTaskCallbackTest001 End"; +} + + /** + * @tc.name: GetDownloadTaskCallbackTest001 + * @tc.desc: Verify the GetDownloadTaskCallback function + * @tc.type: FUNC + * @tc.require: issuesI91IOG + */ +HWTEST_F(DownloadAssetCallbackClientTest, GetDownloadTaskCallbackTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetDownloadTaskCallbackTest001 Start"; + try { + DownloadAssetCallbackClient downloadAssetCallbackClient; + TaskId taskId = 1; + CloudSyncAssetManager::ResultCallback callback = [](const std::string &, int32_t) {}; + auto result = downloadAssetCallbackClient.GetDownloadTaskCallback(taskId); + + EXPECT_TRUE(result == nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetDownloadTaskCallbackTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetDownloadTaskCallbackTest001 End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/download_asset_callback_stub_test.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/download_asset_callback_stub_test.cpp new file mode 100644 index 0000000..6337be3 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/download_asset_callback_stub_test.cpp @@ -0,0 +1,161 @@ +/* + * 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 +#include + +#include "download_asset_callback_stub.h" +#include "cloud_download_uri_manager.h" +#include "asset_callback_mock.h" +#include "dfs_error.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class DownloadAssetCallbackStubMock : public DownloadAssetCallbackStub { +public: + DownloadAssetCallbackStubMock() {} + void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) override + {} +}; + +class DownloadAssetCallbackStubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr downloadAssetCallbackStub_; +}; + +void DownloadAssetCallbackStubTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void DownloadAssetCallbackStubTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void DownloadAssetCallbackStubTest::SetUp(void) +{ + downloadAssetCallbackStub_ = std::make_shared(); + std::cout << "SetUp" << std::endl; +} + +void DownloadAssetCallbackStubTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: OnRemoteRequestTest001 + * @tc.desc: Verify the OnRemoteRequest function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(DownloadAssetCallbackStubTest, OnRemoteRequestTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequest Start"; + try { + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_EQ(E_SERVICE_DESCRIPTOR_IS_EMPTY, downloadAssetCallbackStub_->OnRemoteRequest( + IDownloadAssetCallback::SERVICE_CMD_ON_DOWNLOAD_FINSHED, data, reply, option)); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnRemoteRequest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequest End"; +} + +/** + * @tc.name: OnRemoteRequestTest002 + * @tc.desc: Verify the OnRemoteRequest function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(DownloadAssetCallbackStubTest, OnRemoteRequestTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequest Start"; + try { + uint32_t code = 100; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_TRUE(data.WriteInterfaceToken(IDownloadAssetCallback::GetDescriptor())); + int32_t ret = downloadAssetCallbackStub_->OnRemoteRequest(code, data, reply, option); + EXPECT_NE(E_OK, ret); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnRemoteRequest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequest End"; +} + +/** + * @tc.name: OnRemoteRequestTest003 + * @tc.desc: Verify the OnRemoteRequest function. + * @tc.type: FUNC + * @tc.require: issueI7UYAL + */ +HWTEST_F(DownloadAssetCallbackStubTest, OnRemoteRequestTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequest Start"; + try { + uint32_t code = IDownloadAssetCallback::SERVICE_CMD_ON_DOWNLOAD_FINSHED; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_TRUE(data.WriteInterfaceToken(IDownloadAssetCallback::GetDescriptor())); + int32_t ret = downloadAssetCallbackStub_->OnRemoteRequest(code, data, reply, option); + EXPECT_EQ(E_OK, ret); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnRemoteRequest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequest End"; +} + +/** + * @tc.name: HandleOnFinishedTest001 + * @tc.desc: Verify the HandleOnFinished function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(DownloadAssetCallbackStubTest, HandleOnFinishedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOnFinished Start"; + try { + MessageParcel data; + MessageParcel reply; + int ret = downloadAssetCallbackStub_->HandleOnFinished(data, reply); + EXPECT_EQ(E_OK, ret); + } catch(...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOnFinished ERROR"; + } + GTEST_LOG_(INFO) << "HandleOnFinished End"; +} + +} // namespace Test +} // namespace FileManagement::CloudSync { +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/file_hook/parcel.cpp b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/file_hook/parcel.cpp new file mode 100644 index 0000000..12bc1ef --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/file_hook/parcel.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2022-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 "parcel.h" + +namespace OHOS { +using namespace std; +bool Parcel::WriteInt32(int32_t value) +{ + if (value == 0) { + return false; + } + return true; +} + +bool Parcel::WriteUint32(uint32_t value) +{ + if (value == 0) { + return false; + } + return true; +} + +bool Parcel::WriteInt64(int64_t value) +{ + if (value == 0) { + return false; + } + return true; +} + +bool Parcel::WriteString(const std::string &value) +{ + if (value == "continue") { + return true; + } + return false; +} + +bool Parcel::WriteBool(bool value) +{ + if (value == false) { + return false; + } + return true; +} + +bool Parcel::WriteParcelable(const Parcelable *) +{ + return true; +} + +bool Parcel::ReadInt32(int32_t &value) +{ + value = Parcel::readCursor_; + if (Parcel::readCursor_ == 0) { + return false; + } + return true; +} + +bool Parcel::ReadUint32(uint32_t &value) +{ + value = Parcel::dataSize_; + if (Parcel::dataSize_ == 0) { + return false; + } + return true; +} + +bool Parcel::ReadInt64(int64_t &value) +{ + if (value == 0) { + return false; + } + return true; +} + +bool Parcel::ReadString(string &value) +{ + if (Parcel::data_ == nullptr) { + return false; + } + return true; +} + +bool Parcel::ReadBool(bool &value) +{ + value = Parcel::writable_; + if (value == false) { + return false; + } + return true; +} +} // namespace OHOS::FileManagement::Backup diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/asset_callback_mock.h b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/asset_callback_mock.h new file mode 100644 index 0000000..3c23733 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/asset_callback_mock.h @@ -0,0 +1,47 @@ +/* +* 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 MOCK_I_CLOUD_SYNC_CALLBACK_H +#define MOCK_I_CLOUD_SYNC_CALLBACK_H + + +#include + +#include "i_download_asset_callback.h" +#include "iremote_stub.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudSync { + +class DownloadAssetCallbackMock : public IRemoteStub { +public: + int code_; + DownloadAssetCallbackMock() : code_(0) {} + virtual ~DownloadAssetCallbackMock() {} + + MOCK_METHOD4(SendRequest, int(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)); + + int32_t InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + code_ = code; + return E_OK; + } + + void OnFinished(const TaskId taskId, const std::string &uri, const int32_t result) override {} +}; + +} // namespace OHOS::FileManagement::CloudSync + +#endif // MOCK_I_CLOUD_SYNC_CALLBACK_H diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/i_cloud_download_callback_mock.h b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/i_cloud_download_callback_mock.h new file mode 100644 index 0000000..e066f20 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/i_cloud_download_callback_mock.h @@ -0,0 +1,48 @@ +/* +* 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 MOCK_I_CLOUD_DOWNLOAD_CALLBACK_H +#define MOCK_I_CLOUD_DOWNLOAD_CALLBACK_H + + +#include + +#include "i_cloud_download_callback.h" +#include "iremote_stub.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudSync { + +class CloudDownloadCallbackMock : public IRemoteStub { +public: + int code_; + CloudDownloadCallbackMock() : code_(0) {} + virtual ~CloudDownloadCallbackMock() {} + + MOCK_METHOD4(SendRequest, int(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)); + + int32_t InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + code_ = code; + return E_OK; + } + + void OnDownloadProcess(const DownloadProgressObj& progress) override + {} +}; + +} // namespace OHOS::FileManagement::CloudSync + +#endif // MOCK_I_CLOUD_DOWNLOAD_CALLBACK_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/i_cloud_sync_service_mock.h b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/i_cloud_sync_service_mock.h new file mode 100644 index 0000000..12ea434 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/i_cloud_sync_service_mock.h @@ -0,0 +1,228 @@ +/* + * 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 MOCK_I_CLOUD_SYNC_SERVICE_H +#define MOCK_I_CLOUD_SYNC_SERVICE_H + +#include "icloud_sync_service.h" + +#include +#include + +#include "iremote_broker.h" +#include "cloud_sync_constants.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudSync { +class CloudSyncServiceMock : public IRemoteStub { +public: + int code_; + CloudSyncServiceMock() : code_(0) {} + virtual ~CloudSyncServiceMock() {} + + MOCK_METHOD4(SendRequest, int(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)); + + int32_t InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + code_ = code; + reply.WriteInt32(E_OK); + return E_OK; + } + + int32_t UnRegisterCallbackInner(const std::string &bundleName = "") override + { + return E_OK; + } + + int32_t UnRegisterFileSyncCallbackInner(const std::string &bundleName = "") override + { + return E_OK; + } + + int32_t RegisterCallbackInner(const sptr &remoteObject, const std::string &bundleName = "") override + { + return E_OK; + } + + int32_t RegisterFileSyncCallbackInner(const sptr &remoteObject, + const std::string &bundleName = "") override + { + return E_OK; + } + + int32_t StartSyncInner(bool forceFlag, const std::string &bundleName = "") override + { + return E_OK; + } + + int32_t StartFileSyncInner(bool forceFlag, const std::string &bundleName = "") override + { + return E_OK; + } + + int32_t TriggerSyncInner(const std::string &bundleName, int32_t userId) override + { + return E_OK; + } + + int32_t StopSyncInner(const std::string &bundleName = "", bool forceFlag = false) override + { + return E_OK; + } + + int32_t StopFileSyncInner(const std::string &bundleName = "", bool forceFlag = false) override + { + return E_OK; + } + + int32_t ResetCursor(const std::string &bundleName = "") override + { + return E_OK; + } + + int32_t ChangeAppSwitch(const std::string &accoutId, const std::string &bundleName, bool status) override + { + return E_OK; + } + + int32_t Clean(const std::string &accountId, const CleanOptions &cleanOptions) override + { + return E_OK; + } + + int32_t NotifyDataChange(const std::string &accoutId, const std::string &bundleName) override + { + return E_OK; + } + int32_t NotifyEventChange(int32_t userId, const std::string &eventId, const std::string &extraData) override + { + return E_OK; + } + int32_t EnableCloud(const std::string &accoutId, const SwitchDataObj &switchData) override + { + return E_OK; + } + int32_t DisableCloud(const std::string &accoutId) override + { + return E_OK; + } + int32_t StartDownloadFile(const std::string &path) + { + return E_OK; + } + int32_t StartFileCache(const std::vector &pathVec, int64_t &downloadId, + int32_t fieldkey, + bool isCallbackValid, + const sptr &downloadCallback, + int32_t timeout = -1) + { + return E_OK; + } + int32_t StopDownloadFile(const std::string &path, bool needClean = false) + { + return E_OK; + } + int32_t StopFileCache(int64_t downloadId, bool needClean = false, int32_t timeout = -1) + { + return E_OK; + } + int32_t RegisterDownloadFileCallback(const sptr &downloadCallback) + { + return E_OK; + } + int32_t RegisterFileCacheCallback(const sptr &downloadCallback) + { + return E_OK; + } + int32_t UnregisterDownloadFileCallback() + { + return E_OK; + } + int32_t UnregisterFileCacheCallback() + { + return E_OK; + } + int32_t UploadAsset(const int32_t userId, const std::string &request, std::string &result) + { + return E_OK; + } + int32_t DownloadFile(const int32_t userId, const std::string &bundleName, const AssetInfoObj &assetInfoObj) + { + return E_OK; + } + int32_t DownloadFiles(const int32_t userId, + const std::string &bundleName, + const std::vector &assetInfoObj, + std::vector &assetResultMap) + { + return E_OK; + } + int32_t DeleteAsset(const int32_t userId, const std::string &uri) + { + return E_OK; + } + int32_t GetSyncTimeInner(int64_t &syncTime, const std::string &bundleName = "") + { + return E_OK; + } + + int32_t BatchDentryFileInsert(const std::vector &fileInfo, + std::vector &failCloudId) + { + return E_OK; + } + + int32_t CleanCacheInner(const std::string &uri) + { + return E_OK; + } + + int32_t OptimizeStorage(const OptimizeSpaceOptions &optimizeOptions, bool isCallbackValid, + const sptr &optimizeCallback) + { + return E_OK; + } + + int32_t StopOptimizeStorage() + { + return E_OK; + } + + int32_t DownloadAsset(const uint64_t taskId, + const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + const AssetInfoObj &assetInfoObj) + { + return E_OK; + } + int32_t RegisterDownloadAssetCallback(const sptr &remoteObject) + { + return E_OK; + } + + int32_t DownloadThumb() + { + return E_OK; + } + int32_t BatchCleanFile(const std::vector &fileInfo, std::vector &failCloudId) + { + return E_OK; + } +}; + +} // namespace OHOS::FileManagement::CloudSync + +#endif // MOCK_I_CLOUD_SYNC_SERVICE_H diff --git a/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/service_callback_mock.h b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/service_callback_mock.h new file mode 100644 index 0000000..1ab3509 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_api/cloudsync_impl/include/service_callback_mock.h @@ -0,0 +1,47 @@ +/* +* 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 MOCK_I_CLOUD_SYNC_CALLBACK_H +#define MOCK_I_CLOUD_SYNC_CALLBACK_H + + +#include + +#include "i_cloud_sync_callback.h" +#include "iremote_stub.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudSync { + +class CloudSyncCallbackMock : public IRemoteStub { +public: + int code_; + CloudSyncCallbackMock() : code_(0) {} + virtual ~CloudSyncCallbackMock() {} + + MOCK_METHOD4(SendRequest, int(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)); + + int32_t InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + code_ = code; + return E_OK; + } + + void OnSyncStateChanged(CloudSyncState state, ErrorType error) override {} +}; + +} // namespace OHOS::FileManagement::CloudSync + +#endif // MOCK_I_CLOUD_SYNC_CALLBACK_H diff --git a/cloud_file/test/unittests/cloudsync_sa/BUILD.gn b/cloud_file/test/unittests/cloudsync_sa/BUILD.gn new file mode 100644 index 0000000..ab20c52 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/BUILD.gn @@ -0,0 +1,27 @@ +# Copyright (C) 2023-2024 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. +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +group("cloudsync_sa_test") { + testonly = true + deps = [ + "cycle_task:cloudsync_sa_cycle_task_test", + "dentry:cloudsync_sa_dentry_test", + "ipc:cloudsync_sa_ipc_test", + "log:cloudsync_sa_log_test", + "sync_rule:cloudsync_sa_sync_rule_test", + "system:utils_system_src_test", + "transport:cloudsync_sa_transport_test", + ] +} diff --git a/cloud_file/test/unittests/cloudsync_sa/cycle_task/BUILD.gn b/cloud_file/test/unittests/cloudsync_sa/cycle_task/BUILD.gn new file mode 100644 index 0000000..9969b1c --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/cycle_task/BUILD.gn @@ -0,0 +1,95 @@ +# Copyright (C) 2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("cloud_sync_service_cycle_task_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp", + "${cloud_file_path}/test/mock/cloud_file_kit_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/parameters.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/cycle_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/cycle_task_runner.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/database_backup_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/save_subscription_task.cpp", + "cloud_sync_service_cycle_task_test.cpp", + ] + + include_dirs = [ + "${clouddisk_database_path}/include", + "${cloud_file_path}/test/mock", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/cycle_task", + "${services_path}/cloudsyncservice/include/cycle_task/tasks", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "cloud_file:cloudsync_kit_inner", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gtest", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_single", + "libfuse:libfuse", + "os_account:os_account_innerkits", + "preferences:native_preferences", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "protected=public", + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_TEST\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +group("cloudsync_sa_cycle_task_test") { + testonly = true + deps = [ ":cloud_sync_service_cycle_task_test" ] +} diff --git a/cloud_file/test/unittests/cloudsync_sa/cycle_task/cloud_sync_service_cycle_task_test.cpp b/cloud_file/test/unittests/cloudsync_sa/cycle_task/cloud_sync_service_cycle_task_test.cpp new file mode 100644 index 0000000..9057432 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/cycle_task/cloud_sync_service_cycle_task_test.cpp @@ -0,0 +1,580 @@ +/* + * Copyright (c) 2024 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 + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "cycle_task.h" +#include "cycle_task_runner.h" +#include "tasks/database_backup_task.h" +#include "tasks/optimize_cache_task.h" +#include "tasks/optimize_storage_task.h" +#include "tasks/periodic_check_task.h" +#include "tasks/save_subscription_task.h" +#include "tasks/report_statistics_task.h" +#include "utils_log.h" +#include "cloud_file_kit_mock.cpp" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace std; +using namespace testing; + +std::shared_ptr g_dataSyncManagerPtr_; + +class SubCycleTask : public CycleTask { +public: + SubCycleTask(std::string taskName, + std::set bundleNames, + int32_t intervalTime, + std::shared_ptr dataSyncManager) + :CycleTask(taskName, bundleNames, intervalTime, dataSyncManager) + {} + int32_t RunTaskForBundle(int32_t userId, std::string bundleName) override + { + return 0; + } +}; + +class CloudSyncServiceCycleTaskTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr ability = make_shared(); +}; + +void CloudSyncServiceCycleTaskTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; + if (g_dataSyncManagerPtr_ == nullptr) { + g_dataSyncManagerPtr_ = make_shared(); + } +} + +void CloudSyncServiceCycleTaskTest::TearDownTestCase(void) +{ + ability = nullptr; + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncServiceCycleTaskTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncServiceCycleTaskTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: RunTaskForBundleTest001 + * @tc.desc: Verify the RunTaskForBundle function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest001 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + EXPECT_NE(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest001 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest001 end"; +} + +/** + * @tc.name: RunTaskForBundleTest002 + * @tc.desc: Verify the RunTaskForBundle function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest002 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + EXPECT_NE(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest002 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest002 end"; +} + +/** + * @tc.name: RunTaskForBundleTest003 + * @tc.desc: Verify the RunTaskForBundle function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest003 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + EXPECT_NE(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest003 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest003 end"; +} + +/** + * @tc.name: RunTaskForBundleTest004 + * @tc.desc: Verify the RunTaskForBundle function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest004 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest004 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest004 end"; +} + +/** + * @tc.name: RunTaskForBundleTest005 + * @tc.desc: Verify the RunTaskForBundle function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest005 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + EXPECT_NE(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest005 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest005 end"; +} + +/** + * @tc.name: InitTasksTest001 + * @tc.desc: Verify the InitTasks function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, InitTasksTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitTasksTest001 start"; + try { + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr taskRunner = make_shared(g_dataSyncManagerPtr_); + taskRunner->InitTasks(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitTasksTest001 FAILED"; + } + GTEST_LOG_(INFO) << "InitTasksTest001 end"; +} + +/** + * @tc.name: StartTaskTest001 + * @tc.desc: Verify the StartTask function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, StartTaskTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartTaskTest001 start"; + try { + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr taskRunner = make_shared(g_dataSyncManagerPtr_); + GTEST_LOG_(INFO) << "StartTaskTest001 userId_:" << taskRunner->userId_; + taskRunner->StartTask(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartTaskTest001 FAILED"; + } + GTEST_LOG_(INFO) << "StartTaskTest001 end"; +} + +/** + * @tc.name: SetRunableBundleNamesTest001 + * @tc.desc: Verify the SetRunableBundleNames function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, SetRunableBundleNamesTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetRunableBundleNamesTest001 start"; + try { + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr taskRunner = make_shared(g_dataSyncManagerPtr_); + taskRunner->SetRunableBundleNames(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetRunableBundleNamesTest001 FAILED"; + } + GTEST_LOG_(INFO) << "SetRunableBundleNamesTest001 end"; +} + +/* + * @tc.name: RunTaskForBundlTest + * @tc.desc: Verify the RunTaskForBundl function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest006 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest006 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest006 end"; +} + + /* + * @tc.name: CleanCacheTest + * @tc.desc: Verify the CleanCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest007 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + CloudFile::CloudFileKit::instance_ = ability.get(); + EXPECT_NE(g_dataSyncManagerPtr_, nullptr); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest007 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest007 end"; +} + + /* + * @tc.name: CleanCacheTest + * @tc.desc: Verify the CleanCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest008 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + CloudFile::CloudFileKit::instance_ = ability.get(); + EXPECT_CALL(*ability, GetAppConfigParams(_, _, _)).WillOnce(Return(E_OK)); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest008 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest008 end"; +} + + /* + * @tc.name: CleanCacheTest + * @tc.desc: Verify the CleanCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskForBundleTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskForBundleTest009 start"; + try { + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + CloudFile::CloudFileKit::instance_ = ability.get(); + shared_ptr task = make_shared(g_dataSyncManagerPtr_); + int32_t ret = task->RunTaskForBundle(userId, bundleName); + + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskForBundleTest009 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskForBundleTest009 end"; +} + +/* + * @tc.name: CycleTaskRunnerTest + * @tc.desc: Verify the CycleTaskRunner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, CycleTaskRunnerTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CycleTaskRunnerTest001 start"; + try { + shared_ptr dataSyncManager = nullptr; + CycleTaskRunner cycleTaskRunner(dataSyncManager); + auto res = cycleTaskRunner.dataSyncManager_; + EXPECT_EQ(res, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CycleTaskRunnerTest001 FAILED"; + } + GTEST_LOG_(INFO) << "CycleTaskRunnerTest001 end"; +} + + /* + * @tc.name: SetLastRunTimeTest001 + * @tc.desc: Verify the SetLastRunTime function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, SetLastRunTimeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetLastRunTimeTest001 start"; + try { + std::string taskName; + std::set bundleNames; + int32_t intervalTime = 0; + std::shared_ptr dataSyncManager = nullptr; + + CycleTask *sycTask = new SubCycleTask(taskName, bundleNames, intervalTime, dataSyncManager); + + std::time_t time = std::time(nullptr); + sycTask->SetLastRunTime(time); + EXPECT_EQ(sycTask->cloudPrefImpl_, nullptr); + delete sycTask; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetLastRunTimeTest001 FAILED"; + } + GTEST_LOG_(INFO) << "SetLastRunTimeTest001 end"; +} + + /* + * @tc.name: SetLastRunTimeTest002 + * @tc.desc: Verify the SetLastRunTime function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, SetLastRunTimeTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetLastRunTimeTest002 start"; + try { + std::string taskName; + std::set bundleNames; + int32_t intervalTime = 0; + std::shared_ptr dataSyncManager = nullptr; + + CycleTask *sycTask = new SubCycleTask(taskName, bundleNames, intervalTime, dataSyncManager); + + sycTask->cloudPrefImpl_ = std::make_unique(""); + std::time_t time = std::time(nullptr); + sycTask->SetLastRunTime(time); + EXPECT_NE(sycTask->cloudPrefImpl_, nullptr); + delete sycTask; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetLastRunTimeTest002 FAILED"; + } + GTEST_LOG_(INFO) << "SetLastRunTimeTest002 end"; +} + + /* + * @tc.name: GetLastRunTimeTest001 + * @tc.desc: Verify the GetLastRunTime function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, GetLastRunTimeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLastRunTimeTest001 start"; + try { + std::string taskName; + std::set bundleNames; + int32_t intervalTime = 0; + std::shared_ptr dataSyncManager = nullptr; + + CycleTask *sycTask = new SubCycleTask(taskName, bundleNames, intervalTime, dataSyncManager); + + std::time_t time = std::time(nullptr); + sycTask->GetLastRunTime(time); + EXPECT_EQ(sycTask->cloudPrefImpl_, nullptr); + delete sycTask; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetLastRunTimeTest001 FAILED"; + } + GTEST_LOG_(INFO) << "GetLastRunTimeTest001 end"; +} + + /* + * @tc.name: GetLastRunTimeTest002 + * @tc.desc: Verify the GetLastRunTime function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, GetLastRunTimeTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLastRunTimeTest002 start"; + try { + std::string taskName; + std::set bundleNames; + int32_t intervalTime = 0; + std::shared_ptr dataSyncManager = nullptr; + + CycleTask *sycTask = new SubCycleTask(taskName, bundleNames, intervalTime, dataSyncManager); + + sycTask->cloudPrefImpl_ = std::make_unique(""); + std::time_t time = std::time(nullptr); + sycTask->GetLastRunTime(time); + EXPECT_NE(sycTask->cloudPrefImpl_, nullptr); + delete sycTask; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetLastRunTimeTest002 FAILED"; + } + GTEST_LOG_(INFO) << "GetLastRunTimeTest002 end"; +} + + /* + * @tc.name: IsEligibleToRunTest001 + * @tc.desc: Verify the IsEligibleToRun function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, IsEligibleToRunTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsEligibleToRunTest001 start"; + try { + std::string taskName; + std::set bundleNames; + int32_t intervalTime = 0; + std::shared_ptr dataSyncManager = nullptr; + CycleTask *sycTask = new SubCycleTask(taskName, bundleNames, intervalTime, dataSyncManager); + + std::time_t currentTime = std::time(nullptr); + std::string bundleName; + bool res = sycTask->IsEligibleToRun(currentTime, bundleName); + EXPECT_EQ(res, true); + delete sycTask; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsEligibleToRunTest001 FAILED"; + } + GTEST_LOG_(INFO) << "IsEligibleToRunTest001 end"; +} + + /* + * @tc.name: IsEligibleToRunTest002 + * @tc.desc: Verify the IsEligibleToRun function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, IsEligibleToRunTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsEligibleToRunTest002 start"; + try { + std::string taskName; + std::set bundleNames = {"test"}; + int32_t intervalTime = 0; + std::shared_ptr dataSyncManager = nullptr; + CycleTask *sycTask = new SubCycleTask(taskName, bundleNames, intervalTime, dataSyncManager); + + std::time_t currentTime = std::time(nullptr); + std::string bundleName = ""; + bool res = sycTask->IsEligibleToRun(currentTime, bundleName); + EXPECT_EQ(res, false); + delete sycTask; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsEligibleToRunTest002 FAILED"; + } + GTEST_LOG_(INFO) << "IsEligibleToRunTest002 end"; +} + + /* + * @tc.name: RunTaskTest001 + * @tc.desc: Verify the RunTask function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceCycleTaskTest, RunTaskTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RunTaskTest001 start"; + try { + std::string taskName; + std::set bundleNames = {"test"}; + int32_t intervalTime = 0; + std::shared_ptr dataSyncManager = nullptr; + CycleTask *sycTask = new SubCycleTask(taskName, bundleNames, intervalTime, dataSyncManager); + + int32_t userId = 0; + sycTask->RunTask(userId); + EXPECT_EQ(sycTask->runnableBundleNames_, nullptr); + delete sycTask; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RunTaskTest001 FAILED"; + } + GTEST_LOG_(INFO) << "RunTaskTest001 end"; +} +} +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/dentry/BUILD.gn b/cloud_file/test/unittests/cloudsync_sa/dentry/BUILD.gn new file mode 100644 index 0000000..354eb25 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/dentry/BUILD.gn @@ -0,0 +1,119 @@ +# 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("dentry_meta_file_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "./mock/base_interface_lib_mock.cpp", + "dentry_meta_file_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/test/unittests/cloudsync_sa/dentry/mock/", + "${utils_path}/dentry/include", + ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + ] + + external_deps = [ + "c_utils:utils", + "googletest:gmock_main", + "googletest:gtest_main", + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + use_exceptions = true +} + +ohos_unittest("dentry_file_utils_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "dentry_file_utils_test.cpp" ] + + include_dirs = [ "${utils_path}/dentry/include" ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + ] + + external_deps = [ + "c_utils:utils", + "googletest:gmock_main", + "googletest:gtest_main" + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + use_exceptions = true +} + +ohos_unittest("dentry_meta_file_clouddisk_test") { + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = "cloud_file/cloud_file" + + sources = [ + "./mock/base_interface_lib_mock.cpp", + "dentry_meta_file_clouddisk_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/test/unittests/cloudsync_sa/dentry/mock/", + "${utils_path}/dentry/include", + ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "c_utils:utils", + "googletest:gmock_main", + "googletest:gtest_main" + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + use_exceptions = true +} + +group("cloudsync_sa_dentry_test") { + testonly = true + deps = [ + ":dentry_file_utils_test", + ":dentry_meta_file_clouddisk_test", + ":dentry_meta_file_test", + ] +} diff --git a/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_file_utils_test.cpp b/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_file_utils_test.cpp new file mode 100644 index 0000000..e70e1d7 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_file_utils_test.cpp @@ -0,0 +1,199 @@ +/* + * 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 +#include +#include + +#include "directory_ex.h" +#include "file_utils.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FileUtilsTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void FileUtilsTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void FileUtilsTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void FileUtilsTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FileUtilsTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: ReadFileTest001 + * @tc.desc: Verify the ReadFile function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(FileUtilsTest, ReadFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFileTest001 Begin"; + try { + int fd = -1; + off_t offset = 0; + size_t size = 1024; + void *data = nullptr; + int ret = FileUtils::ReadFile(fd, offset, size, data); + EXPECT_EQ(ret, -1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFileTest001 ERROR"; + } + + GTEST_LOG_(INFO) << "ReadFileTest001 End"; +} + +/** + * @tc.name: ReadFileTest002 + * @tc.desc: Verify the ReadFile function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(FileUtilsTest, ReadFileTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFileTest002 Begin"; + try { + int fd = 1; + off_t offset = 1; + size_t size = 5; + void *data = new int8_t; + int ret = FileUtils::ReadFile(fd, offset, size, data); + EXPECT_EQ(ret, -29); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ReadFileTest002 ERROR"; + } + + GTEST_LOG_(INFO) << "ReadFileTest002 End"; +} + +/** + * @tc.name: ReadFileTest003 + * @tc.desc: Verify the ReadFile function + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(FileUtilsTest, ReadFileTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ReadFileTest003 Start"; + try { + auto data = make_shared(1); + int64_t ret = FileUtils::ReadFile(-1, 0, 0, data.get()); + EXPECT_EQ(ret, -1); + ret = FileUtils::ReadFile(0, -1, 0, data.get()); + EXPECT_EQ(ret, -1); + ret = FileUtils::ReadFile(0, 0, 0, nullptr); + EXPECT_EQ(ret, -1); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " ReadFileTest003 ERROR"; + } + GTEST_LOG_(INFO) << "ReadFileTest003 End"; +} + +/** + * @tc.name: WriteFileTest001 + * @tc.desc: Verify the WriteFile function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(FileUtilsTest, WriteFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteFileTest001 Begin"; + try { + int fd = -1; + void *data = nullptr; + off_t offset = 0; + size_t size = 1024; + int ret = FileUtils::WriteFile(fd, data, offset, size); + EXPECT_EQ(ret, -1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " WriteFileTest001 ERROR"; + } + + GTEST_LOG_(INFO) << "WriteFileTest001 End"; +} + +/** + * @tc.name: WriteFileTest002 + * @tc.desc: Verify the ReadFile function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(FileUtilsTest, WriteFileTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteFileTest002 Begin"; + try { + int fd = 0; + const void* data = "data"; + off_t offset = 0; + size_t size = 5; + int ret = FileUtils::WriteFile(fd, data, offset, size); + EXPECT_EQ(ret, -29); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " WriteFileTest002 ERROR"; + } + + GTEST_LOG_(INFO) << "WriteFileTest002 End"; +} + +/** + * @tc.name: WriteFileTest003 + * @tc.desc: Verify the WriteFile function + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(FileUtilsTest, WriteFileTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WriteFileTest003 Start"; + try { + auto data = make_shared(1); + int64_t ret = FileUtils::WriteFile(-1, data.get(), 0, 1); + EXPECT_EQ(ret, -1); + ret = FileUtils::WriteFile(0, nullptr, 0, 0); + EXPECT_EQ(ret, -1); + ret = FileUtils::WriteFile(0, data.get(), -1, 1); + EXPECT_EQ(ret, -1); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " WriteFileTest003 ERROR"; + } + GTEST_LOG_(INFO) << "WriteFileTest003 End"; +} +} // namespace OHOS::FileManagement::CloudSync::Test diff --git a/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_meta_file_clouddisk_test.cpp b/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_meta_file_clouddisk_test.cpp new file mode 100644 index 0000000..2653c86 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_meta_file_clouddisk_test.cpp @@ -0,0 +1,624 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "directory_ex.h" +#include "meta_file.h" +#include "dfs_error.h" +#include "base_interface_lib_mock.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +constexpr uint32_t TEST_USER_ID = 201; +constexpr uint64_t TEST_ISIZE = 1024; + +class CloudDiskDentryMetaFileTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void CloudDiskDentryMetaFileTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudDiskDentryMetaFileTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDiskDentryMetaFileTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDiskDentryMetaFileTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: CloudDiskMetaFileHandleFileByFd001 + * @tc.desc: Verify the MetaFile::HandleFileByFd function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskMetaFileHandleFileByFd001, TestSize.Level1) +{ + MetaFile mFile(TEST_USER_ID, "/"); + unsigned long endBlock = 0; + uint32_t level = 0; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: CloudDiskMetaFileHandleFileByFd002 + * @tc.desc: Verify the MetaFile::HandleFileByFd function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskMetaFileHandleFileByFd002, TestSize.Level1) +{ + uint32_t userId = 100; + CloudDiskMetaFile mFile(userId, "/", "id1"); + unsigned long endBlock = 0; + uint32_t level = 64; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: CloudDiskMetaFileHandleFileByFd003 + * @tc.desc: Verify the MetaFile::HandleFileByFd function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskMetaFileHandleFileByFd003, TestSize.Level1) +{ + uint32_t userId = 100; + CloudDiskMetaFile mFile(userId, "/", "id1"); + unsigned long endBlock = 0; + uint32_t level = 0; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: CloudDiskMetaFileDoChildUpdateTest + * @tc.desc: Verify the CloudDiskMetaFile::DoChildUpdate function + * @tc.type: FUNC + * @tc.require: SR000HRKKC + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskMetaFileDoChildUpdateTest, TestSize.Level1) +{ + CloudDiskMetaFile mFile(TEST_USER_ID, "/", "id1"); + string name = ""; + CloudDiskMetaFile::CloudDiskMetaFileCallBack callback; + int ret = mFile.DoChildUpdate(name, callback); + EXPECT_EQ(ret, 2); +} + +/** + * @tc.name: DoLookupAndRemoveTest + * @tc.desc: Verify the CloudDiskMetaFile::DoLookupAndRemove function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskDentryMetaFileTest, DoLookupAndRemoveTest, TestSize.Level1) +{ + CloudDiskMetaFile mFile(100, "com.ohos.photos", "rootId"); + MetaBase mBase1(".trash", "rootId"); + int ret = mFile.DoLookupAndRemove(mBase1); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: CloudDiskDentryFileCreateTest + * @tc.desc: Verify the CloudDiskMetaFile::DoCreate function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskDentryFileCreateTest, TestSize.Level1) +{ + std::string cacheDir = + "/data/service/el2/" + std::to_string(TEST_USER_ID) + "/hmdfs/cache/cloud_cache/dentry_cache/cloud/"; + ForceRemoveDirectory(cacheDir); + + string CloudId = ""; + CloudDiskMetaFile mFile(TEST_USER_ID, "/", "id1"); + MetaBase mBase1("file1", "id1"); + mBase1.size = TEST_ISIZE; + int ret = mFile.DoCreate(mBase1); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: CloudDiskMetaFileLookupTest + * @tc.desc: Verify the CloudDiskMetaFile::DoLookup function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskMetaFileLookupTest, TestSize.Level1) +{ + CloudDiskMetaFile mFile(TEST_USER_ID, "/", "id1"); + MetaBase mBase1("file1"); + int ret = mFile.DoCreate(mBase1); + ret = mFile.DoLookup(mBase1); + EXPECT_EQ(ret, 0); + EXPECT_EQ(mBase1.size, TEST_ISIZE); +} + +/** + * @tc.name: CloudDiskMetaFileUpdateTest + * @tc.desc: Verify the CloudDiskMetaFile::DoUpdate function + * @tc.type: FUNC + * @tc.require: SR000HRKKC + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskMetaFileUpdateTest, TestSize.Level1) +{ + CloudDiskMetaFile mFile(TEST_USER_ID, "/", "id1"); + MetaBase mBase1("file1", "id1"); + mBase1.size = 0; + int ret = mFile.DoCreate(mBase1); + ret = mFile.DoUpdate(mBase1); + EXPECT_EQ(ret, 0); + MetaBase mBase2("file1", "id1"); + ret = mFile.DoLookup(mBase2); + EXPECT_EQ(ret, 0); + EXPECT_EQ(mBase2.size, 0); +} + +/** + * @tc.name: CloudDiskMetaFileRemoveTest + * @tc.desc: Verify the CloudDiskMetaFile::DoRemove function + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskMetaFileRemoveTest, TestSize.Level1) +{ + CloudDiskMetaFile mFile(TEST_USER_ID, "/", "id1"); + MetaBase mBase1("file1", "id1"); + int ret = mFile.DoCreate(mBase1); + ret = mFile.DoRemove(mBase1); + EXPECT_EQ(ret, 0); + MetaBase mBase2("file1", "id1"); + ret = mFile.DoLookup(mBase2); + EXPECT_EQ(ret, ENOENT); +} + +/** + * @tc.name:LoadChildrenTest + * @tc.desc: Verify the CloudDiskMetaFile::LoadChildren function + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(CloudDiskDentryMetaFileTest, LoadChildrenTest, TestSize.Level1) +{ + CloudDiskMetaFile mFile(100, "/", "id1"); + MetaBase mBase1("file1", "id1"); + std::vector bases; + bases.push_back(mBase1); + int32_t ret = mFile.LoadChildren(bases); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: CloudDiskMetaFileMgrTest001 + * @tc.desc: Verify the MetaFileMgr + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CloudDiskMetaFileMgrTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudDiskMetaFileMgrTest001 Start"; + try { + auto m = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(TEST_USER_ID, "/o/p/q/r/s/t", "id1"); + EXPECT_NE(m, nullptr); + m = nullptr; + MetaFileMgr::GetInstance().CloudDiskClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "CloudDiskMetaFileMgrTest001 ERROR"; + } + GTEST_LOG_(INFO) << "CloudDiskMetaFileMgrTest001 End"; +} + +/** + * @tc.name: CreateRecycleDentryTest001 + * @tc.desc: Verify the CreateRecycleDentry + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(CloudDiskDentryMetaFileTest, CreateRecycleDentryTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateRecycleDentryTest001 Start"; + try { + uint32_t userId = 100; + string bundleName = "com.ohos.photos"; + int32_t ret = MetaFileMgr::GetInstance().CreateRecycleDentry(userId, bundleName); + EXPECT_EQ(ret, 0); + MetaFileMgr::GetInstance().CloudDiskClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "CreateRecycleDentryTest001 ERROR"; + } + GTEST_LOG_(INFO) << "CreateRecycleDentryTest001 End"; +} + +/** + * @tc.name: MoveIntoRecycleDentryfileTest001 + * @tc.desc: Verify the MoveIntoRecycleDentryfile + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(CloudDiskDentryMetaFileTest, MoveIntoRecycleDentryfileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MoveIntoRecycleDentryfileTest001 Start"; + try { + uint32_t userId = 100; + string bundleName = "com.ohos.photos"; + string name = ".trash"; + string parentCloudId = "rootId"; + int64_t rowId = 0; + int32_t ret = MetaFileMgr::GetInstance().MoveIntoRecycleDentryfile(userId, bundleName, + name, parentCloudId, rowId); + EXPECT_EQ(ret, 0); + MetaFileMgr::GetInstance().CloudDiskClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "MoveIntoRecycleDentryfileTest001 ERROR"; + } + GTEST_LOG_(INFO) << "MoveIntoRecycleDentryfileTest001 End"; +} + +/** + * @tc.name: RemoveFromRecycleDentryfileTest001 + * @tc.desc: Verify the RemoveFromRecycleDentryfile + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(CloudDiskDentryMetaFileTest, RemoveFromRecycleDentryfileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RemoveFromRecycleDentryfileTest001 Start"; + try { + uint32_t userId = 100; + string bundleName = "com.ohos.photos"; + string name = ".trash"; + string parentCloudId = "rootId"; + int64_t rowId = 0; + struct RestoreInfo restoreInfo = {name, parentCloudId, name, rowId}; + int32_t ret = MetaFileMgr::GetInstance().RemoveFromRecycleDentryfile(userId, bundleName, restoreInfo); + EXPECT_EQ(ret, 0); + MetaFileMgr::GetInstance().CloudDiskClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "RemoveFromRecycleDentryfileTest001 ERROR"; + } + GTEST_LOG_(INFO) << "RemoveFromRecycleDentryfileTest001 End"; +} + + +HWTEST_F(CloudDiskDentryMetaFileTest, DfsService_GetDentryFilePath_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DfsService_GetDentryFilePath_001 Start"; + try { + CloudDiskMetaFile mFile(100, "/", "id1"); + string cacheFilePath = mFile.GetDentryFilePath(); + EXPECT_EQ((cacheFilePath != ""), true); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DfsService_GetDentryFilePath_001 ERROR"; + } + GTEST_LOG_(INFO) << "DfsService_GetDentryFilePath_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DfsService_DoLookupAndUpdate_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DfsService_DoLookupAndUpdate_001 Start"; + try { + string fileName = "testLongLongfileName"; + string cloudId = "testLongLongfileName"; + uint64_t size = 0x6b6b6b6b00000000; + MetaBase metaBase(fileName, cloudId); + metaBase.size = size; + auto callback = [&metaBase] (MetaBase &m) { + m.size = metaBase.size; + }; + + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(TEST_USER_ID, "/o/p/q/r/s/t", "id1"); + int32_t ret = metaFile->DoLookupAndUpdate(fileName, callback); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DfsService_DoLookupAndUpdate_001 ERROR"; + } + GTEST_LOG_(INFO) << "DfsService_DoLookupAndUpdate_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DfsService_DoChildUpdate_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DfsService_DoChildUpdate_001 Start"; + try { + string name = "testName"; + CloudDiskMetaFile mFile(100, "/", "id1"); + CloudDiskMetaFile::CloudDiskMetaFileCallBack updateFunc; + + int32_t ret = mFile.DoChildUpdate(name, updateFunc); + EXPECT_EQ(ret, E_INVAL_ARG); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DfsService_DoChildUpdate_001 ERROR"; + } + GTEST_LOG_(INFO) << "DfsService_DoChildUpdate_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DfsService_DoLookupAndRemove_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DfsService_DoLookupAndRemove_001 Start"; + try { + CloudDiskMetaFile mFile(100, "com.ohos.photos", "rootId"); + MetaBase mBase1(".trash", "rootId"); + + int32_t ret = mFile.DoLookupAndRemove(mBase1); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DfsService_DoLookupAndRemove_001 ERROR"; + } + GTEST_LOG_(INFO) << "DfsService_DoLookupAndRemove_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoCreate_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoCreate_001 Start"; + try { + CloudDiskMetaFile mFile(100, "", ""); + MetaBase mBase1("file1", "id1"); + int32_t ret = mFile.DoCreate(mBase1); + EXPECT_EQ(ret, E_EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoCreate_001 ERROR"; + } + GTEST_LOG_(INFO) << "DoCreate_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoRemove_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoRemove_001 Start"; + try { + CloudDiskMetaFile mFile(100, "", ""); + MetaBase mBase1("file1", "id1"); + int32_t ret = mFile.DoRemove(mBase1); + EXPECT_EQ(ret, E_EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoRemove_001 ERROR"; + } + GTEST_LOG_(INFO) << "DoRemove_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoLookup_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoLookup_001 Start"; + try { + CloudDiskMetaFile mFile(100, "", ""); + MetaBase mBase1("file1", "id1"); + int32_t ret = mFile.DoLookup(mBase1); + EXPECT_EQ(ret, E_EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoLookup_001 ERROR"; + } + GTEST_LOG_(INFO) << "DoLookup_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoUpdate_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoUpdate_001 Start"; + try { + CloudDiskMetaFile mFile(100, "", ""); + MetaBase mBase1("file1", "id1"); + int32_t ret = mFile.DoUpdate(mBase1); + EXPECT_EQ(ret, E_EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoUpdate_001 ERROR"; + } + GTEST_LOG_(INFO) << "DoUpdate_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, LoadChildren_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LoadChildren_001 Start"; + try { + CloudDiskMetaFile mFile(100, "", ""); + MetaBase mBase1("file1", "id1"); + std::vector bases; + bases.push_back(mBase1); + int32_t ret = mFile.LoadChildren(bases); + EXPECT_EQ(ret, E_EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "LoadChildren_001 ERROR"; + } + GTEST_LOG_(INFO) << "LoadChildren_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoLookupAndUpdate_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoLookupAndUpdate_002 Start"; + try { + string fileName = ""; + string cloudId = "id1"; + uint64_t size = 0x6b6b6b6b00000000; + MetaBase metaBase(fileName, cloudId); + metaBase.size = size; + auto callback = [&metaBase] (MetaBase &m) { + m.size = metaBase.size; + }; + + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(100, "/o/p/q/r/s/t", "id1"); + int32_t ret = metaFile->DoLookupAndUpdate(fileName, callback); + EXPECT_EQ(ret, E_SUCCESS); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoLookupAndUpdate_002 ERROR"; + } + GTEST_LOG_(INFO) << "DoLookupAndUpdate_002 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoLookupAndUpdate_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoLookupAndUpdate_003 Start"; + try { + uint64_t size = 0x6b6b6b6b000000ff; + CloudDiskMetaFile mFile(100, "", ""); + MetaBase metaBase("file1", "id1"); + metaBase.size = size; + auto callback = [&metaBase] (MetaBase &m) { + m.size = metaBase.size; + }; + + int32_t ret = mFile.DoUpdate(metaBase); + EXPECT_EQ(ret, E_EINVAL); + ret = mFile.DoLookupAndUpdate("file1", callback); + EXPECT_EQ(ret, E_EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoLookupAndUpdate_003 ERROR"; + } + GTEST_LOG_(INFO) << "DoLookupAndUpdate_003 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoLookupAndUpdate_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoLookupAndUpdate_004 Start"; + try { + uint64_t size = 0x6b6b6b6b0000006f; + CloudDiskMetaFile mFile(100, "/", "id1"); + MetaBase metaBase("file1", "id1"); + metaBase.size = size; + auto callback = [&metaBase] (MetaBase &m) { + m.size = metaBase.size; + }; + + int32_t ret = mFile.DoLookupAndUpdate("file1", callback); + EXPECT_EQ(ret, E_SUCCESS); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoLookupAndUpdate_004 ERROR"; + } + GTEST_LOG_(INFO) << "DoLookupAndUpdate_004 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoRename_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoRename_001 Start"; + try { + CloudDiskMetaFile mFile(100, "", ""); + MetaBase mBase1("file1", "id1"); + std::shared_ptr newMetaFile = + make_shared(TEST_USER_ID, "/", "id1"); + + int ret = mFile.DoCreate(mBase1); + ret = mFile.DoRename(mBase1, "id2", newMetaFile); + EXPECT_EQ(ret, EINVAL); + MetaBase mBase2("id2"); + ret = mFile.DoLookup(mBase2); + EXPECT_EQ(ret, E_EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoRename_001 ERROR"; + } + GTEST_LOG_(INFO) << "DoRename_001 End"; +} + +HWTEST_F(CloudDiskDentryMetaFileTest, DoRename_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoRename_002 Start"; + try { + CloudDiskMetaFile mFile(100, "", ""); + MetaBase mBase1("file1", "id1"); + std::shared_ptr newMetaFile = + make_shared(TEST_USER_ID, "", ""); + + int ret = mFile.DoCreate(mBase1); + ret = mFile.DoRename(mBase1, "id2", newMetaFile); + EXPECT_EQ(ret, E_EINVAL); + MetaBase mBase2("id2"); + ret = mFile.DoLookup(mBase2); + EXPECT_EQ(ret, E_EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DoRename_002 ERROR"; + } + GTEST_LOG_(INFO) << "DoRename_002 End"; +} + +/** + * @tc.name: RemoveFromRecycleDentryfileTest001 + * @tc.desc: Verify the DoLookupAndCreate + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(CloudDiskDentryMetaFileTest, DfsService_DoLookupAndCreate_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DfsService_DoLookupAndUpdate_001 Start"; + try { + string fileName = "testLongLongfileName"; + string cloudId = "testLongLongfileName"; + uint64_t size = 0x6b6b6b6b00000000; + MetaBase metaBase(fileName, cloudId); + metaBase.size = size; + auto callback = [&metaBase] (MetaBase &m) { + m.size = metaBase.size; + }; + + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(TEST_USER_ID, "/o/p/q/r/s/t", "id1"); + int32_t ret = metaFile->DoLookupAndCreate(fileName, callback); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "DfsService_DoLookupAndUpdate_001 ERROR"; + } + GTEST_LOG_(INFO) << "DfsService_DoLookupAndUpdate_001 End"; +} + +/** + * @tc.name: GetNewNameTest + * @tc.desc: Verify the GetNewName function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudDiskDentryMetaFileTest, GetNewNameTest, TestSize.Level1) +{ + std::shared_ptr metaFile = std::make_shared(1, "bundleName", "cloudId"); + std::string oldName = "test.txt"; + std::string newName; + std::vector metaBases; + int32_t ret = MetaFileMgr::GetInstance().GetNewName(metaFile, oldName, newName); + + EXPECT_EQ(ret, 0); +} + +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_meta_file_test.cpp b/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_meta_file_test.cpp new file mode 100644 index 0000000..64a3bcf --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/dentry/dentry_meta_file_test.cpp @@ -0,0 +1,671 @@ + /* + * 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 +#include + +#include "directory_ex.h" +#include "meta_file.h" +#include "base_interface_lib_mock.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +constexpr uint32_t TEST_USER_ID = 201; +constexpr uint64_t TEST_ISIZE = 1024; +const string TEST_PATH = "/data/service/el2/100/hmdfs/cache/account_cache/dentry_cache/cloud/"; + +class DentryMetaFileTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +public: + static inline shared_ptr interfaceLibMock_ = nullptr; +}; + +void DentryMetaFileTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + interfaceLibMock_ = make_shared(); + InterfaceLibMock::baseInterfaceLib_ = interfaceLibMock_; +} + +void DentryMetaFileTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + InterfaceLibMock::baseInterfaceLib_ = nullptr; + interfaceLibMock_ = nullptr; +} + +void DentryMetaFileTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void DentryMetaFileTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: MetaFileHandleFileByFd001 + * @tc.desc: Verify the MetaFile::HandleFileByFd function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(DentryMetaFileTest, MetaFileHandleFileByFd001, TestSize.Level1) +{ + MetaFile mFile(TEST_USER_ID, "/"); + unsigned long endBlock = 0; + uint32_t level = 0; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: MetaFileHandleFileByFd002 + * @tc.desc: Verify the MetaFile::HandleFileByFd function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(DentryMetaFileTest, MetaFileHandleFileByFd002, TestSize.Level1) +{ + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + unsigned long endBlock = 0; + uint32_t level = 64; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: MetaFileHandleFileByFd003 + * @tc.desc: Verify the MetaFile::HandleFileByFd function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(DentryMetaFileTest, MetaFileHandleFileByFd003, TestSize.Level1) +{ + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + unsigned long endBlock = 0; + uint32_t level = 0; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, 0); +} + +/** + * @tc.name: MetaFileCreate001 + * @tc.desc: Verify the MetaFile::DoCreate function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(DentryMetaFileTest, MetaFileCreate001, TestSize.Level1) +{ + uint32_t userId = 100; + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cache/cloud_cache/dentry_cache/cloud/"; + ForceRemoveDirectory(cacheDir); + + MetaFile mFile(userId, "/"); + MetaBase mBase1("file1", "id1"); + mBase1.size = TEST_ISIZE; + int ret = mFile.DoCreate(mBase1); + EXPECT_EQ(ret, 0); + MetaBase mBase2("file2", "id2"); + mBase2.size = TEST_ISIZE; + ret = mFile.DoCreate(mBase2); + EXPECT_EQ(ret, 0); + MetaFile mFile2(userId, "/a/b"); + MetaBase mBase3("file3", "id3"); + ret = mFile2.DoCreate(mBase3); +} + +/** + * @tc.name: MetaFileCreate002 + * @tc.desc: Verify the MetaFile::DoCreate function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(DentryMetaFileTest, MetaFileCreate002, TestSize.Level1) +{ + MetaFile mFile(TEST_USER_ID, "/"); + MetaBase mBase1("file1", "id1"); + int ret = mFile.DoCreate(mBase1); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: MetaFileLookup001 + * @tc.desc: Verify the MetaFile::DoLookup function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(DentryMetaFileTest, MetaFileLookup001, TestSize.Level1) +{ + MetaFile mFile(TEST_USER_ID, "/"); + MetaBase mBase1("file1"); + int ret = mFile.DoLookup(mBase1); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: MetaFileLookup002 + * @tc.desc: Verify the MetaFile::DoLookup002 function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(DentryMetaFileTest, MetaFileLookup, TestSize.Level1) +{ + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + MetaBase mBase1("file1"); + int ret = mFile.DoLookup(mBase1); + EXPECT_EQ(ret, 0); + EXPECT_EQ(mBase1.size, TEST_ISIZE); +} + +/** + * @tc.name: MetaFileUpdate001 + * @tc.desc: Verify the MetaFile::DoUpdate function + * @tc.type: FUNC + * @tc.require: SR000HRKKC + */ +HWTEST_F(DentryMetaFileTest, MetaFileUpdate001, TestSize.Level1) +{ + MetaFile mFile(TEST_USER_ID, "/"); + MetaBase mBase1("file1", "id11"); + int ret = mFile.DoUpdate(mBase1); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: MetaFileUpdate + * @tc.desc: Verify the MetaFile::DoUpdate function + * @tc.type: FUNC + * @tc.require: SR000HRKKC + */ +HWTEST_F(DentryMetaFileTest, MetaFileUpdate, TestSize.Level1) +{ + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + MetaBase mBase1("file1", "id11"); + mBase1.size = 0; + int ret = mFile.DoUpdate(mBase1); + EXPECT_EQ(ret, 0); + MetaBase mBase2("file1"); + ret = mFile.DoLookup(mBase2); + EXPECT_EQ(ret, 0); + EXPECT_EQ(mBase2.size, 0); +} + +/** + * @tc.name: MetaFileRename + * @tc.desc: Verify the MetaFile::DoRename function + * @tc.type: FUNC + * @tc.require: SR000HRKKC + */ +HWTEST_F(DentryMetaFileTest, MetaFileRename, TestSize.Level1) +{ + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + MetaBase mBase1("file2"); + int ret = mFile.DoRename(mBase1, "file4"); + EXPECT_EQ(ret, 0); + MetaBase mBase2("file4"); + ret = mFile.DoLookup(mBase2); + EXPECT_EQ(ret, 0); + EXPECT_EQ(mBase2.size, TEST_ISIZE); +} + +/** + * @tc.name: MetaFileRemove001 + * @tc.desc: Verify the MetaFile::DoRemove function + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(DentryMetaFileTest, MetaFileRemove001, TestSize.Level1) +{ + MetaFile mFile(TEST_USER_ID, "/"); + MetaBase mBase1("file1"); + int ret = mFile.DoRemove(mBase1); + EXPECT_EQ(ret, EINVAL); +} + +/** + * @tc.name: LoadChildren001 + * @tc.desc: Verify the LoadChildren + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(DentryMetaFileTest, LoadChildren001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LoadChildren001 Start"; + try { + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + std::vector bases; + int ret = mFile.LoadChildren(bases); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "LoadChildren001 ERROR"; + } + GTEST_LOG_(INFO) << "LoadChildren001 End"; +} + +/** + * @tc.name: LoadChildren002 + * @tc.desc: Verify the LoadChildren + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(DentryMetaFileTest, LoadChildren002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LoadChildren002 Start"; + try { + MetaFile mFile(TEST_USER_ID, "/"); + std::vector bases; + int ret = mFile.LoadChildren(bases); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "LoadChildren002 ERROR"; + } + GTEST_LOG_(INFO) << "LoadChildren002 End"; +} + +/** + * @tc.name: MetaFileMgr001 + * @tc.desc: Verify the MetaFileMgr + * @tc.type: FUNC + * @tc.require: SR000HRKJB + */ +HWTEST_F(DentryMetaFileTest, MetaFileMgr001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MetaFileMgr001 Start"; + try { + uint32_t userId = 100; + auto m = MetaFileMgr::GetInstance().GetMetaFile(userId, "/o/p/q/r/s/t"); + MetaBase mBase1("file1", "file1"); + EXPECT_EQ(m->DoCreate(mBase1), 0); + m = nullptr; + MetaFileMgr::GetInstance().ClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " MetaFileMgr001 ERROR"; + } + GTEST_LOG_(INFO) << "MetaFileMgr001 End"; +} + +/** + * @tc.name: MetaFileMgr002 + * @tc.desc: Verify the MetaFileMgr + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(DentryMetaFileTest, MetaFileMgr002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MetaFileMgr002 Start"; + try { + uint32_t userId = 100; + auto m = MetaFileMgr::GetInstance().GetMetaFile(userId, "/o/p/q/r/s/t"); + MetaBase mBase1("testLongLongfileName", "testLongLongfileName"); + EXPECT_EQ(m->DoCreate(mBase1), 0); + m = nullptr; + MetaFileMgr::GetInstance().ClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " MetaFileMgr002 ERROR"; + } + GTEST_LOG_(INFO) << "MetaFileMgr002 End"; +} + +/** + * @tc.name: MetaFileMgr003 + * @tc.desc: Verify the MetaFileMgr + * @tc.type: FUNC + * @tc.require: issueIBLAKM + */ +HWTEST_F(DentryMetaFileTest, MetaFileMgr003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "MetaFileMgr003 Start"; + try { + uint32_t userId = 100; + for (int i = 0; i < MAX_META_FILE_NUM; i++) { + auto m = MetaFileMgr::GetInstance().GetMetaFile(userId, to_string(i)); + } + auto m = MetaFileMgr::GetInstance().GetMetaFile(userId, "/o/p/q/r/s/t"); + auto checkSize = MetaFileMgr::GetInstance().CheckMetaFileSize(); + m = nullptr; + MetaFileMgr::GetInstance().ClearAll(); + EXPECT_EQ(checkSize, MAX_META_FILE_NUM); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " MetaFileMgr003 ERROR"; + } + GTEST_LOG_(INFO) << "MetaFileMgr003 End"; +} + +/** + * @tc.name:RecordIdToCloudId001 + * @tc.desc: Verify the RecordIdToCloudId + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(DentryMetaFileTest, RecordIdToCloudId001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RecordIdToCloudId001 Start"; + try { + std::string hexStr = ""; + string ret = MetaFileMgr::GetInstance().RecordIdToCloudId(hexStr); + EXPECT_EQ(ret, ""); + MetaFileMgr::GetInstance().ClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "RecordIdToCloudId001 ERROR"; + } + GTEST_LOG_(INFO) << "RecordIdToCloudId001 End"; +} + +/** + * @tc.name:RecordIdToCloudId002 + * @tc.desc: Verify the RecordIdToCloudId + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(DentryMetaFileTest, RecordIdToCloudId002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RecordIdToCloudId002 Start"; + try { + std::string hexStr = "test"; + string ret = MetaFileMgr::GetInstance().RecordIdToCloudId(hexStr); + EXPECT_EQ(ret, ""); + MetaFileMgr::GetInstance().ClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "RecordIdToCloudId002 ERROR"; + } + GTEST_LOG_(INFO) << "RecordIdToCloudId002 End"; +} + +/** + * @tc.name: GetParentDir001 + * @tc.desc: Verify the GetParentDir + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(DentryMetaFileTest, GetParentDir001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetParentDir001 Start"; + try { + string str = MetaFile::GetParentDir(""); + EXPECT_EQ(str, ""); + str = MetaFile::GetParentDir("/"); + EXPECT_EQ(str, ""); + str = MetaFile::GetParentDir("abc"); + EXPECT_EQ(str, "/"); + str = MetaFile::GetParentDir("/abc"); + EXPECT_EQ(str, "/"); + str = MetaFile::GetParentDir("/abc/def"); + EXPECT_EQ(str, "/abc"); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " GetParentDir001 ERROR"; + } + GTEST_LOG_(INFO) << "GetParentDir001 End"; +} + +/** + * @tc.name: GetFileName001 + * @tc.desc: Verify the GetFileName + * @tc.type: FUNC + * @tc.require: issueI7SP3A + */ +HWTEST_F(DentryMetaFileTest, GetFileName001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFileName001 Start"; + try { + string str = MetaFile::GetFileName(""); + EXPECT_EQ(str, ""); + str = MetaFile::GetFileName("/"); + EXPECT_EQ(str, ""); + str = MetaFile::GetFileName("abc"); + EXPECT_EQ(str, ""); + str = MetaFile::GetFileName("/abc/def"); + EXPECT_EQ(str, "def"); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " GetFileName001 ERROR"; + } + GTEST_LOG_(INFO) << "GetFileName001 End"; +} + +HWTEST_F(DentryMetaFileTest, HandleFileByFd_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleFileByFd_001 Start"; + try { + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + unsigned long endBlock = 0; + uint32_t level = MAX_BUCKET_LEVEL; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " HandleFileByFd_001 ERROR"; + } + GTEST_LOG_(INFO) << "HandleFileByFd_001 End"; +} + +HWTEST_F(DentryMetaFileTest, HandleFileByFd_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleFileByFd_002 Start"; + try { + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + unsigned long endBlock = DENTRY_PER_GROUP; + uint32_t level = MAX_BUCKET_LEVEL; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " HandleFileByFd_002 ERROR"; + } + GTEST_LOG_(INFO) << "HandleFileByFd_002 End"; +} + +HWTEST_F(DentryMetaFileTest, HandleFileByFd_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleFileByFd_003 Start"; + try { + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + unsigned long endBlock = -100; + uint32_t level = MAX_BUCKET_LEVEL; + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " HandleFileByFd_003 ERROR"; + } + GTEST_LOG_(INFO) << "HandleFileByFd_003 End"; +} + +HWTEST_F(DentryMetaFileTest, GetDentryfileName_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetDentryfileName_001 Start"; + try { + uint32_t userId = 100; + EXPECT_CALL(*interfaceLibMock_, GetDentryfileName(_, _)).WillOnce(Return("/")); + MetaFile mFile(userId, "/"); + + string path = "/test/"; + bool caseSense = true; + EXPECT_TRUE(true); + EXPECT_EQ(interfaceLibMock_->GetDentryfileName(path, caseSense), "/"); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " GetDentryfileName_001 ERROR"; + } + GTEST_LOG_(INFO) << "GetDentryfileName_001 End"; +} + +HWTEST_F(DentryMetaFileTest, GetOverallBucket_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetOverallBucket_001 Start"; + try { + uint32_t userId = 100; + MetaFile mFile(userId, "/"); + unsigned long endBlock = -100; + uint32_t level = MAX_BUCKET_LEVEL; + + EXPECT_CALL(*interfaceLibMock_, GetOverallBucket(_)).WillOnce(Return(E_SUCCESS)); + int ret = mFile.HandleFileByFd(endBlock, level); + EXPECT_EQ(ret, 0); + EXPECT_EQ(interfaceLibMock_->GetOverallBucket(MAX_BUCKET_LEVEL), E_SUCCESS); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " GetOverallBucket_001 ERROR"; + } + GTEST_LOG_(INFO) << "GetOverallBucket_001 End"; +} + +HWTEST_F(DentryMetaFileTest, GetBucketaddr_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetBucketaddr_001 Start"; + try { + EXPECT_CALL(*interfaceLibMock_, GetBucketaddr(_, _)).WillOnce(Return(E_SUCCESS)); + uint32_t userId = 100; + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cache/cloud_cache/dentry_cache/cloud/"; + ForceRemoveDirectory(cacheDir); + + MetaFile mFile(userId, "/"); + MetaBase mBase1("file1", "id1"); + mBase1.size = TEST_ISIZE; + int ret = mFile.DoCreate(mBase1); + EXPECT_EQ(ret, E_SUCCESS); + EXPECT_EQ(interfaceLibMock_->GetBucketaddr(MAX_BUCKET_LEVEL, MAX_BUCKET_LEVEL), E_SUCCESS); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " GetBucketaddr_001 ERROR"; + } + GTEST_LOG_(INFO) << "GetBucketaddr_001 End"; +} + +HWTEST_F(DentryMetaFileTest, GetBucketaddr_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetBucketaddr_002 Start"; + try { + EXPECT_CALL(*interfaceLibMock_, GetBucketaddr(Eq(E_SUCCESS), _)).WillOnce(Return(E_FAIL)); + uint32_t userId = 100; + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cache/cloud_cache/dentry_cache/cloud/"; + ForceRemoveDirectory(cacheDir); + + MetaFile mFile(userId, "/"); + MetaBase mBase1("file1", "id1"); + mBase1.size = TEST_ISIZE; + int ret = mFile.DoCreate(mBase1); + EXPECT_EQ(ret, E_SUCCESS); + EXPECT_EQ(interfaceLibMock_->GetBucketaddr(E_SUCCESS, MAX_BUCKET_LEVEL), E_FAIL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " GetBucketaddr_002 ERROR"; + } + GTEST_LOG_(INFO) << "GetBucketaddr_002 End"; +} + +HWTEST_F(DentryMetaFileTest, GetBucketByLevel_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetBucketByLevel_001 Start"; + try { + EXPECT_CALL(*interfaceLibMock_, GetBucketByLevel(_)).WillOnce(Return(E_SUCCESS)); + uint32_t userId = 100; + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cache/cloud_cache/dentry_cache/cloud/"; + ForceRemoveDirectory(cacheDir); + + MetaFile mFile(userId, "/"); + MetaBase mBase1("file1", "id1"); + mBase1.size = TEST_ISIZE; + int ret = mFile.DoCreate(mBase1); + EXPECT_EQ(ret, E_SUCCESS); + EXPECT_EQ(interfaceLibMock_->GetBucketByLevel(E_SUCCESS), E_SUCCESS); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " GetBucketByLevel_001 ERROR"; + } + GTEST_LOG_(INFO) << "GetBucketByLevel_001 End"; +} + +HWTEST_F(DentryMetaFileTest, RoomForFilename_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RoomForFilename_001 Start"; + try { + EXPECT_CALL(*interfaceLibMock_, FindNextZeroBit(_, _, _)).WillOnce(Return(DENTRY_PER_GROUP)); + uint32_t userId = 100; + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cache/cloud_cache/dentry_cache/cloud/"; + ForceRemoveDirectory(cacheDir); + + MetaFile mFile(userId, "/"); + MetaBase mBase1("file1", "id1"); + mBase1.size = TEST_ISIZE; + int ret = mFile.DoCreate(mBase1); + uint8_t addr[] = {0}; + uint32_t maxSlots = DENTRY_PER_GROUP; + uint32_t start = DENTRY_PER_GROUP; + EXPECT_EQ(interfaceLibMock_->FindNextZeroBit(addr, maxSlots, start), DENTRY_PER_GROUP); + EXPECT_EQ(ret, E_SUCCESS); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " RoomForFilename_001 ERROR"; + } + GTEST_LOG_(INFO) << "RoomForFilename_001 End"; +} + +HWTEST_F(DentryMetaFileTest, RoomForFilename_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RoomForFilename_002 Start"; + try { + EXPECT_CALL(*interfaceLibMock_, FindNextZeroBit(_, _, _)).WillOnce(Return(DENTRY_PER_GROUP)); + EXPECT_CALL(*interfaceLibMock_, FindNextBit(_, _, _)).WillOnce(Return(MAX_BUCKET_LEVEL)); + uint32_t userId = 100; + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cache/cloud_cache/dentry_cache/cloud/"; + ForceRemoveDirectory(cacheDir); + + MetaFile mFile(userId, "/"); + MetaBase mBase1("file1", "id1"); + mBase1.size = TEST_ISIZE; + int ret = mFile.DoCreate(mBase1); + uint8_t addr[] = {0}; + uint32_t maxSlots = DENTRY_PER_GROUP; + uint32_t start = DENTRY_PER_GROUP; + EXPECT_EQ(ret, E_SUCCESS); + EXPECT_EQ(interfaceLibMock_->FindNextZeroBit(addr, maxSlots, start), DENTRY_PER_GROUP); + EXPECT_EQ(interfaceLibMock_->FindNextBit(addr, maxSlots, start), MAX_BUCKET_LEVEL); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " RoomForFilename_002 ERROR"; + } + GTEST_LOG_(INFO) << "RoomForFilename_002 End"; +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/dentry/mock/base_interface_lib_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/dentry/mock/base_interface_lib_mock.cpp new file mode 100644 index 0000000..f4d30bc --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/dentry/mock/base_interface_lib_mock.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2024 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 "base_interface_lib_mock.h" + +namespace OHOS { +namespace FileManagement { +string GetDentryfileByPath(uint32_t userId, const string &path, bool caseSense) +{ + if (BaseInterfaceLib::baseInterfaceLib_ == nullptr) { + if (path == "") { + caseSense = true; + return ""; + } + caseSense = false; + return ""; + } + + return BaseInterfaceLib::baseInterfaceLib_->GetDentryfileByPath(userId, path, caseSense); +} + +string GetDentryfileName(const std::string &path, bool caseSense) +{ + if (BaseInterfaceLib::baseInterfaceLib_ == nullptr) { + return ""; + } + + return BaseInterfaceLib::baseInterfaceLib_->GetDentryfileName(path, caseSense); +} + +uint32_t GetOverallBucket(uint32_t level) +{ + if (BaseInterfaceLib::baseInterfaceLib_ == nullptr) { + if (level >= MAX_BUCKET_LEVEL) { + return E_SUCCESS; + } + return E_SUCCESS; + } + + return BaseInterfaceLib::baseInterfaceLib_->GetOverallBucket(level); +} + +uint32_t GetBucketaddr(uint32_t level, uint32_t buckoffset) +{ + if (BaseInterfaceLib::baseInterfaceLib_ == nullptr) { + if (level >= MAX_BUCKET_LEVEL) { + return E_SUCCESS; + } + + uint64_t curLevelMaxBucks = level; + if (buckoffset >= curLevelMaxBucks) { + return E_FAIL; + } + + return MAX_BUCKET_LEVEL; + } + + return BaseInterfaceLib::baseInterfaceLib_->GetBucketaddr(level, buckoffset); +} + +uint32_t GetBucketByLevel(uint32_t level) +{ + if (BaseInterfaceLib::baseInterfaceLib_ == nullptr) { + if (level >= MAX_BUCKET_LEVEL) { + return E_SUCCESS; + } else { + return MAX_BUCKET_LEVEL; + } + } + + return BaseInterfaceLib::baseInterfaceLib_->GetBucketByLevel(level); +} + +uint32_t RoomForFilename(const uint8_t bitmap[], size_t slots, uint32_t maxSlots) +{ + if (BaseInterfaceLib::baseInterfaceLib_ == nullptr) { + if (maxSlots == E_SUCCESS) { + return E_SUCCESS; + } else { + return MAX_BUCKET_LEVEL; + } + } + + return BaseInterfaceLib::baseInterfaceLib_->RoomForFilename(bitmap, slots, maxSlots); +} + +uint32_t FindNextZeroBit(const uint8_t addr[], uint32_t maxSlots, uint32_t start) +{ + if (BaseInterfaceLib::baseInterfaceLib_ == nullptr) { + if (maxSlots == DENTRY_PER_GROUP) { + return DENTRY_PER_GROUP; + } else { + return MAX_BUCKET_LEVEL; + } + } + + return BaseInterfaceLib::baseInterfaceLib_->FindNextZeroBit(addr, maxSlots, start); +} + +uint32_t FindNextBit(const uint8_t addr[], uint32_t maxSlots, uint32_t start) +{ + if (BaseInterfaceLib::baseInterfaceLib_ == nullptr) { + if (maxSlots == DENTRY_PER_GROUP) { + return DENTRY_PER_GROUP; + } else { + return MAX_BUCKET_LEVEL; + } + } + + return BaseInterfaceLib::baseInterfaceLib_->FindNextBit(addr, maxSlots, start); +} + +int32_t DoLookup(MetaBase &base) +{ + return E_SUCCESS; +} + +int32_t DoCreate(const MetaBase &base) +{ + return E_SUCCESS; +} + +int32_t DoLookupAndRemove(MetaBase &metaBase) +{ + return E_SUCCESS; +} +} // FileManagement +} // OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/dentry/mock/base_interface_lib_mock.h b/cloud_file/test/unittests/cloudsync_sa/dentry/mock/base_interface_lib_mock.h new file mode 100644 index 0000000..a0dc41d --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/dentry/mock/base_interface_lib_mock.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2024 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 BASE_INTERFACE_LIB_MOCK_H +#define BASE_INTERFACE_LIB_MOCK_H + +#include +#include +#include "meta_file.h" + +namespace OHOS { +namespace FileManagement { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class BaseInterfaceLib { +public: + virtual ~BaseInterfaceLib() = default; + virtual string GetDentryfileByPath(uint32_t userId, const string &path, bool caseSense) = 0; + virtual string GetDentryfileName(const std::string &path, bool caseSense) = 0; + virtual uint32_t GetOverallBucket(uint32_t level) = 0; + virtual uint32_t GetBucketaddr(uint32_t level, uint32_t buckoffset) = 0; + virtual uint32_t GetBucketByLevel(uint32_t level) = 0; + virtual uint32_t RoomForFilename(const uint8_t bitmap[], size_t slots, uint32_t maxSlots) = 0; + virtual uint32_t FindNextZeroBit(const uint8_t addr[], uint32_t maxSlots, uint32_t start) = 0; + virtual uint32_t FindNextBit(const uint8_t addr[], uint32_t maxSlots, uint32_t start) = 0; + virtual int32_t DoLookup(MetaBase &base) = 0; + virtual int32_t DoCreate(const MetaBase &base) = 0; + virtual int32_t DoLookupAndRemove(MetaBase &metaBase) = 0; +public: + static inline shared_ptr baseInterfaceLib_ = nullptr; +}; + +class InterfaceLibMock : public BaseInterfaceLib { +public: + MOCK_METHOD3(GetDentryfileByPath, string(uint32_t userId, const string &path, bool caseSense)); + MOCK_METHOD2(GetDentryfileName, string(const string &path, bool caseSense)); + MOCK_METHOD1(GetOverallBucket, uint32_t(uint32_t level)); + MOCK_METHOD2(GetBucketaddr, uint32_t(uint32_t level, uint32_t buckoffset)); + MOCK_METHOD1(GetBucketByLevel, uint32_t(uint32_t level)); + MOCK_METHOD3(RoomForFilename, uint32_t(const uint8_t bitmap[], size_t slots, uint32_t maxSlot)); + MOCK_METHOD3(FindNextZeroBit, uint32_t(const uint8_t addr[], uint32_t maxSlots, uint32_t start)); + MOCK_METHOD3(FindNextBit, uint32_t(const uint8_t addr[], uint32_t maxSlots, uint32_t start)); + MOCK_METHOD1(DoLookup, int32_t(MetaBase &base)); + MOCK_METHOD1(DoCreate, int32_t(const MetaBase &base)); + MOCK_METHOD1(DoLookupAndRemove, int32_t(MetaBase &metaBase)); +}; + +enum ErrStatus { + E_FAIL = -1, + E_SUCCESS = 0, + E_EINVAL = 22, + DENTRY_PER_GROUP = 60, + MAX_BUCKET_LEVEL = 63 +}; +} // FileManagement +} // OHOS +#endif // BASE_INTERFACE_LIB_MOCK_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/ipc/BUILD.gn b/cloud_file/test/unittests/cloudsync_sa/ipc/BUILD.gn new file mode 100644 index 0000000..b40200a --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/ipc/BUILD.gn @@ -0,0 +1,260 @@ +# Copyright (C) 2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("cloud_sync_service_stub_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.cpp", + "${services_path}/cloudsyncservice/src/ipc/cloud_sync_service_stub.cpp", + "cloud_sync_service_stub_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${services_path}/cloudsyncservice/include", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("cloud_sync_service_test") { + module_out_path = "cloud_file/cloud_file" + public_configs = + [ "${services_path}/cloudsyncservice:cloud_sync_service_public_config" ] + sources = [ + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/battery_status_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/cloud_status_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/network_status_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/parameters.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/cycle_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/cycle_task_runner.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/database_backup_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp", + "${services_path}/cloudsyncservice/src/cycle_task/tasks/save_subscription_task.cpp", + "${services_path}/cloudsyncservice/src/ipc/cloud_sync_service.cpp", + "${services_path}/cloudsyncservice/src/ipc/download_asset_callback_manager.cpp", + "${services_path}/cloudsyncservice/src/ipc/download_asset_callback_proxy.cpp", + "${services_path}/cloudsyncservice/src/sync_rule/battery_status_listener.cpp", + "${services_path}/cloudsyncservice/src/sync_rule/package_status_listener.cpp", + "${services_path}/cloudsyncservice/src/sync_rule/screen_status_listener.cpp", + "${services_path}/cloudsyncservice/src/sync_rule/user_status_listener.cpp", + "cloud_sync_service_test.cpp", + ] + + include_dirs = [ + "${clouddisk_database_path}/include", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "${services_path}/cloudsyncservice/include/ipc", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/cycle_task", + "${services_path}/cloudsyncservice/include/cycle_task/tasks", + "${services_path}/cloudsyncservice/include/transport", + "${services_path}/cloudsyncservice/include/transport/softbus", + "${services_path}/cloudsyncservice/include/sync_rule", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + ] + + transport = [ + "${services_path}/cloudsyncservice/src/transport/file_transfer_manager.cpp", + "${services_path}/cloudsyncservice/src/transport/message_handler.cpp", + "${services_path}/cloudsyncservice/src/transport/softbus/session_manager.cpp", + "${services_path}/cloudsyncservice/src/transport/softbus/softbus_adapter.cpp", + "${services_path}/cloudsyncservice/src/transport/softbus/softbus_session.cpp", + ] + + sources += transport + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloud_sync_service_stub", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "e2fsprogs:libext2_uuid", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "cloud_file:cloudsync_kit_inner", + "dsoftbus:softbus_client", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_single", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "power_manager:powermgr_client", + "preferences:native_preferences", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_TEST\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +ohos_unittest("download_asset_callback_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${services_path}/cloudsyncservice/src/ipc/download_asset_callback_manager.cpp", + "download_asset_callback_manager_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_single", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("download_asset_callback_proxy_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${services_path}/cloudsyncservice/src/ipc/download_asset_callback_proxy.cpp", + "download_asset_callback_proxy_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_single", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +group("cloudsync_sa_ipc_test") { + testonly = true + deps = [ + ":cloud_sync_service_test", + ":download_asset_callback_manager_test", + ":download_asset_callback_proxy_test", + ] +} diff --git a/cloud_file/test/unittests/cloudsync_sa/ipc/cloud_sync_service_stub_test.cpp b/cloud_file/test/unittests/cloudsync_sa/ipc/cloud_sync_service_stub_test.cpp new file mode 100644 index 0000000..caac446 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/ipc/cloud_sync_service_stub_test.cpp @@ -0,0 +1,2099 @@ +/* + * 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 +#include + +#include "cloud_file_sync_service_interface_code.h" +#include "cloud_sync_service_stub.h" +#include "dfsu_access_token_helper_mock.h" +#include "i_cloud_sync_service.h" +#include "service_callback_mock.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MockService final : public CloudSyncServiceStub { +public: + MOCK_METHOD2(RegisterCallbackInner, + int32_t(const sptr &remoteObject, const std::string &bundleName)); + MOCK_METHOD2(RegisterFileSyncCallbackInner, + int32_t(const sptr &remoteObject, const std::string &bundleName)); + MOCK_METHOD1(UnRegisterCallbackInner, int32_t(const std::string &bundleName)); + MOCK_METHOD1(UnRegisterFileSyncCallbackInner, int32_t(const std::string &bundleName)); + MOCK_METHOD2(StartSyncInner, int32_t(bool forceFlag, const std::string &bundleName)); + MOCK_METHOD2(StartFileSyncInner, int32_t(bool forceFlag, const std::string &bundleName)); + MOCK_METHOD2(TriggerSyncInner, int32_t(const std::string &bundleName, const int32_t &userId)); + MOCK_METHOD2(StopSyncInner, int32_t(const std::string &bundleName, bool forceFlag)); + MOCK_METHOD2(StopFileSyncInner, int32_t(const std::string &bundleName, bool forceFlag)); + MOCK_METHOD1(ResetCursor, int32_t(const std::string &bundleName)); + MOCK_METHOD3(ChangeAppSwitch, int32_t(const std::string &accoutId, const std::string &bundleName, bool status)); + MOCK_METHOD2(Clean, int32_t(const std::string &accountId, const CleanOptions &cleanOptions)); + MOCK_METHOD2(NotifyDataChange, int32_t(const std::string &accoutId, const std::string &bundleName)); + MOCK_METHOD3(NotifyEventChange, int32_t(int32_t userId, const std::string &eventId, const std::string &extraData)); + MOCK_METHOD2(EnableCloud, int32_t(const std::string &accoutId, const SwitchDataObj &switchData)); + MOCK_METHOD1(DisableCloud, int32_t(const std::string &accoutId)); + MOCK_METHOD1(StartDownloadFile, int32_t(const std::string &path)); + MOCK_METHOD6(StartFileCache, int32_t(const std::vector &pathVec, int64_t &downloadId, + std::bitset fieldkey, + bool isCallbackValid, + const sptr &downloadCallback, + int32_t timeout)); + MOCK_METHOD2(StopDownloadFile, int32_t(const std::string &path, bool needClean)); + MOCK_METHOD3(StopFileCache, int32_t(int64_t downloadId, bool needClean, int32_t timeout)); + MOCK_METHOD1(RegisterDownloadFileCallback, int32_t(const sptr &downloadCallback)); + MOCK_METHOD1(RegisterFileCacheCallback, int32_t(const sptr &downloadCallback)); + MOCK_METHOD0(UnregisterDownloadFileCallback, int32_t()); + MOCK_METHOD0(UnregisterFileCacheCallback, int32_t()); + MOCK_METHOD3(UploadAsset, int32_t(const int32_t userId, const std::string &request, std::string &result)); + MOCK_METHOD3(DownloadFile, + int32_t(const int32_t userId, const std::string &bundleName, AssetInfoObj &assetInfoObj)); + MOCK_METHOD4(DownloadFiles, + int32_t(const int32_t userId, + const std::string &bundleName, + const std::vector &assetInfoObj, + std::vector &assetResultMap)); + MOCK_METHOD5(DownloadAsset, + int32_t(const uint64_t taskId, + const int32_t userId, + const std::string &bundleName, + const std::string &networkId, + AssetInfoObj &assetInfoObj)); + MOCK_METHOD1(RegisterDownloadAssetCallback, int32_t(const sptr &remoteObject)); + MOCK_METHOD2(DeleteAsset, int32_t(const int32_t userId, const std::string &uri)); + MOCK_METHOD2(GetSyncTimeInner, int32_t(int64_t &syncTime, const std::string &bundleName)); + MOCK_METHOD1(CleanCacheInner, int32_t(const std::string &uri)); + MOCK_METHOD0(DownloadThumb, int32_t()); + MOCK_METHOD2(BatchCleanFile, int32_t(const std::vector &fileInfo, + std::vector &failCloudId)); + MOCK_METHOD3(OptimizeStorage, int32_t(const OptimizeSpaceOptions &optimizeOptions, bool isCallbackValid, + const sptr &optimizeCallback)); + MOCK_METHOD2(BatchDentryFileInsert, int32_t(const std::vector &fileInfo, + std::vector &failCloudId)); + MOCK_METHOD0(StopOptimizeStorage, int32_t()); +}; + +class CloudSyncServiceStubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr dfsuAccessToken_ = nullptr; +}; + +void CloudSyncServiceStubTest::SetUpTestCase(void) +{ + dfsuAccessToken_ = make_shared(); + DfsuAccessTokenMock::dfsuAccessToken = dfsuAccessToken_; + std::cout << "SetUpTestCase" << std::endl; +} + +void CloudSyncServiceStubTest::TearDownTestCase(void) +{ + DfsuAccessTokenMock::dfsuAccessToken = nullptr; + dfsuAccessToken_ = nullptr; + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncServiceStubTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncServiceStubTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: HandleOptimizeStorageTest001 + * @tc.desc: Verify the HandleOptimizeStorage function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleOptimizeStorageTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOptimizeStorage Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t res = service.HandleOptimizeStorage(data, reply); + EXPECT_EQ(res, E_PERMISSION_DENIED); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOptimizeStorage ERROR"; + } + GTEST_LOG_(INFO) << "HandleOptimizeStorage End"; +} + +/** + * @tc.name: HandleOptimizeStorageTest002 + * @tc.desc: Verify the HandleOptimizeStorage function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleOptimizeStorageTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOptimizeStorage Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t res = service.HandleOptimizeStorage(data, reply); + EXPECT_EQ(res, E_PERMISSION_SYSTEM); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOptimizeStorage ERROR"; + } + GTEST_LOG_(INFO) << "HandleOptimizeStorage End"; +} + +/** + * @tc.name: HandleOptimizeStorageTest003 + * @tc.desc: Verify the HandleOptimizeStorage function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleOptimizeStorageTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleOptimizeStorage Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + int32_t res = service.HandleOptimizeStorage(data, reply); + EXPECT_EQ(res, E_INVAL_ARG); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleOptimizeStorage ERROR"; + } + GTEST_LOG_(INFO) << "HandleOptimizeStorage End"; +} + +/** + * @tc.name: HandleEnableCloudTest003 + * @tc.desc: Verify the HandleEnableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleEnableCloudTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleEnableCloud Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + int32_t res = service.HandleEnableCloud(data, reply); + EXPECT_EQ(res, E_INVAL_ARG); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleEnableCloud ERROR"; + } + GTEST_LOG_(INFO) << "HandleEnableCloud End"; +} + +/** + * @tc.name: HandleStartFileCacheTest003 + * @tc.desc: Verify the HandleStartFileCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleStartFileCacheTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleStartFileCache Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + data.writable_ = true; + + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + EXPECT_CALL(*dfsuAccessToken_, CheckUriPermission(_)).WillOnce(Return(false)); + int32_t res = service.HandleStartFileCache(data, reply); + EXPECT_EQ(res, E_OK); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleStartFileCache ERROR"; + } + GTEST_LOG_(INFO) << "HandleStartFileCache End"; +} + +/** + * @tc.name: HandleDownloadThumbTest001 + * @tc.desc: Verify the HandleDownloadThumb function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadThumbTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleDownloadThumb Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t res = service.HandleDownloadThumb(data, reply); + EXPECT_EQ(res, E_PERMISSION_SYSTEM); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleDownloadThumb ERROR"; + } + GTEST_LOG_(INFO) << "HandleDownloadThumb End"; +} + +/** + * @tc.name: HandleDownloadThumbTest002 + * @tc.desc: Verify the HandleDownloadThumb function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadThumbTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleDownloadThumb Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t res = service.HandleDownloadThumb(data, reply); + EXPECT_EQ(res, E_PERMISSION_DENIED); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleDownloadThumb ERROR"; + } + GTEST_LOG_(INFO) << "HandleDownloadThumb End"; +} + +/** + * @tc.name: HandleDownloadThumbTest003 + * @tc.desc: Verify the HandleDownloadThumb function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadThumbTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleDownloadThumb Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + int32_t res = service.HandleDownloadThumb(data, reply); + EXPECT_EQ(res, E_OK); + + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleDownloadThumb ERROR"; + } + GTEST_LOG_(INFO) << "HandleDownloadThumb End"; +} + +/** + * @tc.name: HandleUnRegisterCallbackInnerTest + * @tc.desc: Verify the HandleUnRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleUnRegisterCallbackInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleUnRegisterCallbackInner Start"; + try { + string bundleName = ""; + MockService service; + EXPECT_CALL(service, UnRegisterCallbackInner(bundleName)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + sptr remote = sptr(new CloudSyncCallbackMock()); + EXPECT_TRUE(data.WriteRemoteObject(remote->AsObject().GetRefPtr())); + + EXPECT_TRUE(data.WriteString(bundleName)); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_UNREGISTER_CALLBACK), + data, reply, option)); + remote = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleUnRegisterCallbackInner ERROR"; + } + GTEST_LOG_(INFO) << "HandleUnRegisterCallbackInner End"; +} + +/** + * @tc.name: HandleRegisterCallbackInnerTest + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterCallbackInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleRegisterCallbackInner Start"; + try { + string bundleName = ""; + MockService service; + EXPECT_CALL(service, RegisterCallbackInner(_, bundleName)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + sptr remote = sptr(new CloudSyncCallbackMock()); + EXPECT_TRUE(data.WriteRemoteObject(remote->AsObject().GetRefPtr())); + + EXPECT_TRUE(data.WriteString(bundleName)); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_REGISTER_CALLBACK), + data, reply, option)); + remote = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleRegisterCallbackInner ERROR"; + } + GTEST_LOG_(INFO) << "HandleRegisterCallbackInner End"; +} + +/** + * @tc.name: HandleStartSyncInnerTest + * @tc.desc: Verify the HandleStartSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleStartSyncInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleStartSyncInner Start"; + try { + string bundleName = ""; + MockService service; + EXPECT_CALL(service, StartSyncInner(_, bundleName)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + bool forceFlag = true; + EXPECT_TRUE(data.WriteBool(forceFlag)); + + EXPECT_TRUE(data.WriteString(bundleName)); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_START_SYNC), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleStartSyncInner ERROR"; + } + GTEST_LOG_(INFO) << "HandleStartSyncInner End"; +} + +/** + * @tc.name: HandleTriggerSyncInnerTest + * @tc.desc: Verify the HandleStartSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleTriggerSyncInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleTriggerSyncInner Start"; + try { + MockService service; + EXPECT_CALL(service, TriggerSyncInner(_, _)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_TRIGGER_SYNC), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleTriggerSyncInner ERROR"; + } + GTEST_LOG_(INFO) << "HandleTriggerSyncInner End"; +} + +/** + * @tc.name: HandleStopSyncInnerTest + * @tc.desc: Verify the HandleStopSyncInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleStopSyncInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleStopSyncInner Start"; + try { + string bundleName = ""; + bool forceFlag = false; + MockService service; + EXPECT_CALL(service, StopSyncInner(bundleName, forceFlag)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_TRUE(data.WriteString(bundleName)); + + EXPECT_TRUE(data.WriteBool(forceFlag)); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_STOP_SYNC), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleStopSyncInner ERROR"; + } + GTEST_LOG_(INFO) << "HandleStopSyncInner End"; +} + +/** + * @tc.name: HandleChangeAppSwitchTest + * @tc.desc: Verify the HandleChangeAppSwitch function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleChangeAppSwitchTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleChangeAppSwitch Start"; + try { + MockService service; + EXPECT_CALL(service, ChangeAppSwitch(_, _, _)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_CHANGE_APP_SWITCH), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleChangeAppSwitch ERROR"; + } + GTEST_LOG_(INFO) << "HandleChangeAppSwitch End"; +} + +/** + * @tc.name: HandleCleanTest + * @tc.desc: Verify the HandleClean function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleCleandTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleClean Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_INVAL_ARG, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_CLEAN), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleClean ERROR"; + } + GTEST_LOG_(INFO) << "HandleClean End"; +} + +/** + * @tc.name: HandleNotifyDataChangeTest + * @tc.desc: Verify the HandleNotifyDataChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyDataChangeTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleNotifyDataChange Start"; + try { + MockService service; + EXPECT_CALL(service, NotifyDataChange(_, _)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_NOTIFY_DATA_CHANGE), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleNotifyDataChange ERROR"; + } + GTEST_LOG_(INFO) << "HandleNotifyDataChange End"; +} + +/** + * @tc.name: HandleNotifyEventChangeTest + * @tc.desc: Verify the HandleNotifyEventChange function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyEventChangeTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleNotifyEventChange Start"; + try { + MockService service; + EXPECT_CALL(service, NotifyEventChange(_, _, _)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_NOTIFY_EVENT_CHANGE), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleNotifyEventChange ERROR"; + } + GTEST_LOG_(INFO) << "HandleNotifyEventChange End"; +} + +/** + * @tc.name: HandleDisableCloudTest + * @tc.desc: Verify the HandleDisableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDisableCloudTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleStopSyncInner Start"; + try { + MockService service; + EXPECT_CALL(service, DisableCloud(_)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DISABLE_CLOUD), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleDisableCloud ERROR"; + } + GTEST_LOG_(INFO) << "HandleDisableCloud End"; +} + +/** + * @tc.name: HandleEnableCloudTest + * @tc.desc: Verify the HandleEnableCloud function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleEnableCloudTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleEnableCloudFile Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_INVAL_ARG, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_ENABLE_CLOUD), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleEnableCloud ERROR"; + } + GTEST_LOG_(INFO) << "HandleEnableCloud End"; +} + +/** + * @tc.name: HandleStartDownloadFileTest + * @tc.desc: Verify the HandleStartDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleStartDownloadFileTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleStartDownloadFile Start"; + try { + MockService service; + EXPECT_CALL(service, StartDownloadFile(_)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_START_DOWNLOAD_FILE), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleStartDownloadFile ERROR"; + } + GTEST_LOG_(INFO) << "HandleStartDownloadFile End"; +} + +/** + * @tc.name: HandleStopDownloadFileTest + * @tc.desc: Verify the HandleStopDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleStopDownloadFileTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleStopDownloadFile Start"; + try { + MockService service; + EXPECT_CALL(service, StopDownloadFile(_, _)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_STOP_DOWNLOAD_FILE), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleStopDownloadFile ERROR"; + } + GTEST_LOG_(INFO) << "HandleStopDownloadFile End"; +} + +/** + * @tc.name: HandleRegisterDownloadFileCallbackTest + * @tc.desc: Verify the HandleRegisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterDownloadFileCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleRegisterDownloadFileCallback Start"; + try { + MockService service; + EXPECT_CALL(service, RegisterDownloadFileCallback(_)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast( + CloudFileSyncServiceInterfaceCode::SERVICE_CMD_REGISTER_DOWNLOAD_FILE_CALLBACK), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleRegisterDownloadFileCallback ERROR"; + } + GTEST_LOG_(INFO) << "HandleRegisterDownloadFileCallback End"; +} + +/** + * @tc.name: HandleUnregisterDownloadFileCallbackTest + * @tc.desc: Verify the HandleUnregisterDownloadFileCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleUnregisterDownloadFileCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleUnregisterDownloadFileCallback Start"; + try { + MockService service; + EXPECT_CALL(service, UnregisterDownloadFileCallback()).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast( + CloudFileSyncServiceInterfaceCode::SERVICE_CMD_UNREGISTER_DOWNLOAD_FILE_CALLBACK), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleUnregisterDownloadFileCallback ERROR"; + } + GTEST_LOG_(INFO) << "HandleUnregisterDownloadFileCallback End"; +} + +/** + * @tc.name: HandleUploadAssetTest + * @tc.desc: Verify the HandleUploadAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleUploadAssetTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleUploadAsset Start"; + try { + MockService service; + EXPECT_CALL(service, UploadAsset(_, _, _)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_UPLOAD_ASSET), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleUploadAsset ERROR"; + } + GTEST_LOG_(INFO) << "HandleUploadAsset End"; +} + +/** + * @tc.name: HandleDownloadFileTest + * @tc.desc: Verify the HandleDownloadFile function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadFileTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleDownloadFile Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_INVAL_ARG, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DOWNLOAD_FILE), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleDownloadFile ERROR"; + } + GTEST_LOG_(INFO) << "HandleDownloadFile End"; +} + +/** + * @tc.name: HandleDownloadAssetTest + * @tc.desc: Verify the HandleDownloadAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadAssetTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleDownloadAsset Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_INVAL_ARG, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DOWNLOAD_ASSET), data, + reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleDownloadAsset ERROR"; + } + GTEST_LOG_(INFO) << "HandleDownloadAsset End"; +} + +/** + * @tc.name: HandleRegisterDownloadAssetCallbackTest + * @tc.desc: Verify the HandleRegisterDownloadAssetCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterDownloadAssetCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleRegisterDownloadAssetCallback Start"; + try { + MockService service; + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_REGISTER_DOWNLOAD_ASSET_CALLBACK), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " HandleRegisterDownloadAssetCallback ERROR"; + } + GTEST_LOG_(INFO) << "HandleRegisterDownloadAssetCallback End"; +} + +/** + * @tc.name: HandleDeleteAssetTest + * @tc.desc: Verify the HandleDeleteAsset function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDeleteAssetTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleDeleteAsset Start"; + try { + MockService service; + EXPECT_CALL(service, DeleteAsset(_, _)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_DELETE_ASSET), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "HandleDeleteAsset ERROR"; + } + GTEST_LOG_(INFO) << "HandleDeleteAsset End"; +} + +/** + * @tc.name: HandleGetSyncTimeTest + * @tc.desc: Verify the HandleGetSyncTime function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleGetSyncTimeTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleGetSyncTime Start"; + try { + string bundleName = ""; + MockService service; + EXPECT_CALL(service, GetSyncTimeInner(_, bundleName)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_TRUE(data.WriteString(bundleName)); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_GET_SYNC_TIME), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "HandleGetSyncTime ERROR"; + } + GTEST_LOG_(INFO) << "HandleGetSyncTime End"; +} + +/** + * @tc.name: HandleCleanCacheTest + * @tc.desc: Verify the HandleCleanCache function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleCleanCacheTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleCleanCache Start"; + try { + MockService service; + EXPECT_CALL(service, CleanCacheInner(_)).WillOnce(Return(E_OK)); + MessageParcel data; + MessageParcel reply; + MessageOption option; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_TRUE(data.WriteInterfaceToken(ICloudSyncService::GetDescriptor())); + + EXPECT_EQ(E_OK, service.OnRemoteRequest( + static_cast(CloudFileSyncServiceInterfaceCode::SERVICE_CMD_CLEAN_CACHE), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "HandleCleanCache ERROR"; + } + GTEST_LOG_(INFO) << "HandleCleanCache End"; +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadAssetTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleDownloadAsset(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadAssetTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleDownloadAsset(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleUnRegisterCallbackInnerTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleUnRegisterCallbackInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleUnRegisterCallbackInnerTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleUnRegisterCallbackInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterCallbackInnerTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleRegisterCallbackInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterCallbackInnerTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleRegisterCallbackInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartSyncInnerTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStartSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartSyncInnerTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStartSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleTriggerSyncInnerTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleTriggerSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleTriggerSyncInnerTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleTriggerSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopSyncInnerTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStopSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopSyncInnerTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStopSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleResetCursorTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleResetCursor(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleResetCursorTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleResetCursor(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleResetCursorTest003, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillRepeatedly(Return(true)); + int32_t ret = service.HandleResetCursor(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleChangeAppSwitchTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleChangeAppSwitch(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleChangeAppSwitchTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleChangeAppSwitch(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleCleanTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleClean(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleCleanTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillRepeatedly (Return(false)); + int32_t ret = service.HandleClean(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyDataChangeTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleNotifyDataChange(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyDataChangeTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleNotifyDataChange(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyEventChangeTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleNotifyEventChange(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyEventChangeTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleNotifyEventChange(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleEnableCloudTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleEnableCloud(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleEnableCloudTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleEnableCloud(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDisableCloudTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleDisableCloud(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDisableCloudTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleDisableCloud(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartDownloadFileTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStartDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartDownloadFileTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStartDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartFileCacheTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStartFileCache(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartFileCacheTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStartFileCache(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopDownloadFileTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStopDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopDownloadFileTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStopDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopFileCacheTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStopFileCache(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopFileCacheTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStopFileCache(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopFileCacheTest003, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillRepeatedly(Return(true)); + int32_t ret = service.HandleStopFileCache(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterDownloadFileCallbackTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleRegisterDownloadFileCallback(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleUnregisterDownloadFileCallbackTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleUnregisterDownloadFileCallback(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleUploadAssetTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleUploadAsset(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleUploadAssetTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleUploadAsset(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadFileTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadFileTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadFilesTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleDownloadFiles(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadFilesTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleDownloadFiles(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadFilesTest003, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + int32_t ret = service.HandleDownloadFiles(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterDownloadAssetCallbackTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleRegisterDownloadAssetCallback(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterDownloadAssetCallbackTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleRegisterDownloadAssetCallback(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDeleteAssetTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleDeleteAsset(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDeleteAssetTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleDeleteAsset(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleGetSyncTimeTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleGetSyncTime(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleGetSyncTimeTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleGetSyncTime(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleBatchDentryFileInsert001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleBatchDentryFileInsert(data, reply);\ + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleBatchDentryFileInsert002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleBatchDentryFileInsert(data, reply); + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleBatchDentryFileInsert003, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + int32_t ret = service.HandleBatchDentryFileInsert(data, reply); + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleCleanCacheTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleCleanCache(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleCleanCacheTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleCleanCache(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleBatchCleanFileTest001, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleBatchCleanFile(data, reply);\ + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleBatchCleanFileTest002, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleBatchCleanFile(data, reply); + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleBatchCleanFileTest003, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + int32_t ret = service.HandleBatchCleanFile(data, reply); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: HandleDownloadAssetTest1 + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadAssetTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleDownloadAsset(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +/** + * @tc.name: HandleDownloadAssetTest2 + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleDownloadAssetTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleDownloadAsset(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +/** + * @tc.name: HandleUnRegisterCallbackInnerTest1 + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleUnRegisterCallbackInnerTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleUnRegisterCallbackInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +/** + * @tc.name: HandleUnRegisterCallbackInnerTest2 + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleUnRegisterCallbackInnerTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleUnRegisterCallbackInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +/** + * @tc.name: HandleRegisterCallbackInnerTest1 + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterCallbackInnerTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleRegisterCallbackInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +/** + * @tc.name: HandleRegisterCallbackInnerTest2 + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleRegisterCallbackInnerTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleRegisterCallbackInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +/** + * @tc.name: HandleStartSyncInnerTest1 + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleStartSyncInnerTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStartSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +/** + * @tc.name: HandleStartSyncInnerTest2 + * @tc.desc: Verify the HandleRegisterCallbackInner function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceStubTest, HandleStartSyncInnerTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStartSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleTriggerSyncInnerTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleTriggerSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleTriggerSyncInnerTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleTriggerSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopSyncInnerTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStopSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopSyncInnerTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStopSyncInner(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleResetCursorTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleResetCursor(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleResetCursorTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleResetCursor(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleResetCursorTest3, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillRepeatedly(Return(true)); + int32_t ret = service.HandleResetCursor(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleChangeAppSwitchTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleChangeAppSwitch(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleChangeAppSwitchTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleChangeAppSwitch(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleCleanTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleClean(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleCleanTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillRepeatedly(Return(false)); + int32_t ret = service.HandleClean(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyDataChangeTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleNotifyDataChange(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyDataChangeTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleNotifyDataChange(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyEventChangeTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleNotifyEventChange(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleNotifyEventChangeTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleNotifyEventChange(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleEnableCloudTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleEnableCloud(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleEnableCloudTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleEnableCloud(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDisableCloudTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleDisableCloud(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleDisableCloudTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleDisableCloud(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartDownloadFileTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStartDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartDownloadFileTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStartDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartFileCacheTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStartFileCache(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStartFileCacheTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStartFileCache(data, reply); + + EXPECT_EQ(ret, E_OK); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopDownloadFileTest1, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(false)); + int32_t ret = service.HandleStopDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_DENIED); +} + +HWTEST_F(CloudSyncServiceStubTest, HandleStopDownloadFileTest2, TestSize.Level1) +{ + MockService service; + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*dfsuAccessToken_, CheckCallerPermission(_)).WillOnce(Return(true)); + EXPECT_CALL(*dfsuAccessToken_, IsSystemApp()).WillOnce(Return(false)); + int32_t ret = service.HandleStopDownloadFile(data, reply); + + EXPECT_EQ(ret, E_PERMISSION_SYSTEM); +} + +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_sa/ipc/cloud_sync_service_test.cpp b/cloud_file/test/unittests/cloudsync_sa/ipc/cloud_sync_service_test.cpp new file mode 100644 index 0000000..f76babe --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/ipc/cloud_sync_service_test.cpp @@ -0,0 +1,773 @@ +/* + * 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 + +#include "cloud_sync_service.h" +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "service_callback_mock.h" +#include "utils_log.h" +#include "i_cloud_download_callback_mock.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace std; + +std::shared_ptr g_servicePtr_; + +class CloudSyncServiceTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudSyncServiceTest::SetUpTestCase(void) +{ + if (g_servicePtr_ == nullptr) { + int32_t saId = 5204; + g_servicePtr_ = std::make_shared(saId); + ASSERT_TRUE(g_servicePtr_ != nullptr) << "SystemAbility failed"; + } + std::cout << "SetUpTestCase" << std::endl; + g_servicePtr_->dataSyncManager_ = make_shared(); +} + +void CloudSyncServiceTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void CloudSyncServiceTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void CloudSyncServiceTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name:UnRegisterCallbackInnerTest + * @tc.desc:Verify the UnRegisterCallbackInner function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, UnRegisterCallbackInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnRegisterCallbackInner Start"; + try { + std::string bundleName = ""; + int ret = g_servicePtr_->UnRegisterCallbackInner(bundleName); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnRegisterCallbackInner FAILED"; + } + GTEST_LOG_(INFO) << "UnRegisterCallbackInner End"; +} + +/** + * @tc.name:RegisterCallbackInnerTest001 + * @tc.desc:Verify the RegisterCallbackInner function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, RegisterCallbackInnerTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterCallbackInner start"; + try { + std::string bundleName = ""; + sptr callback = sptr(new CloudSyncCallbackMock()); + int ret = g_servicePtr_->RegisterCallbackInner(callback, bundleName); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterCallbackInner FAILED"; + } + GTEST_LOG_(INFO) << "RegisterCallbackInner end"; +} + +/** + * @tc.name:RegisterCallbackInnerTest002 + * @tc.desc:Verify the RegisterCallbackInner function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, RegisterCallbackInnerTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterCallbackInner error branch start"; + try { + std::string bundleName = "com.ohos.photos"; + sptr callback = nullptr; + int ret = g_servicePtr_->RegisterCallbackInner(callback, bundleName); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterCallbackInner error branch FAILED"; + } + GTEST_LOG_(INFO) << "RegisterCallbackInner error branch end"; +} + +/** + * @tc.name:TriggerSyncInnerTest + * @tc.desc:Verify the TriggerSyncInner function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, TriggerSyncInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TriggerSyncInner start"; + try { + std::string bundleName = "com.ohos.photos"; + int32_t userId = 0; + int ret = g_servicePtr_->TriggerSyncInner(bundleName, userId); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "TriggerSyncInner FAILED"; + } + GTEST_LOG_(INFO) << "TriggerSyncInner end"; +} + +/** + * @tc.name:StopSyncInnerTest + * @tc.desc:Verify the StopSyncInner function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, StopSyncInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopSyncInner Start"; + try { + std::string bundleName = ""; + int ret = g_servicePtr_->StopSyncInner(bundleName); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StopSyncInner FAILED"; + } + GTEST_LOG_(INFO) << "StopSyncInner End"; +} + +/** + * @tc.name:CleanCacheInnerTest + * @tc.desc:Verify the CleanCacheInner function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, CleanCacheInnerTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CleanCacheInner Start"; + try { + std::string uri = ""; + int ret = g_servicePtr_->CleanCacheInner(uri); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CleanCacheInner FAILED"; + } + GTEST_LOG_(INFO) << "CleanCacheInner End"; +} + +/** + * @tc.name:EnableCloudTest + * @tc.desc:Verify the EnableCloud function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, EnableCloudTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnableCloud start"; + try { + std::string accountId = "testId"; + SwitchDataObj switchData; + int ret = g_servicePtr_->EnableCloud(accountId, switchData); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "EnableCloud FAILED"; + } + GTEST_LOG_(INFO) << "EnableCloud end"; +} + +/** + * @tc.name:CleanTest + * @tc.desc:Verify the Clean function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, CleanTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DisableCloud start"; + try { + std::string accountId = "testId"; + CleanOptions cleanOptions; + int ret = g_servicePtr_->Clean(accountId, cleanOptions); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "Clean FAILED"; + } + GTEST_LOG_(INFO) << "Clean end"; +} + +/** + * @tc.name:StopDownloadFileTest + * @tc.desc:Verify the StopDownloadFile function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, StopDownloadFileTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopDownloadFile start"; + try { + std::string path; + bool needClean = false; + int ret = g_servicePtr_->StopDownloadFile(path, needClean); + EXPECT_EQ(E_PERMISSION_DENIED, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StopDownloadFile FAILED"; + } + GTEST_LOG_(INFO) << "StopDownloadFile end"; +} + +/** + * @tc.name:RegisterDownloadFileCallbackTest + * @tc.desc:Verify the RegisterDownloadFileCallback function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, RegisterDownloadFileCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback start"; + try { + sptr downloadCallback = sptr(new CloudDownloadCallbackMock()); + int ret = g_servicePtr_->RegisterDownloadFileCallback(downloadCallback); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback FAILED"; + } + GTEST_LOG_(INFO) << "RegisterDownloadFileCallback end"; +} + +/** + * @tc.name:UnregisterDownloadFileCallbackTest + * @tc.desc:Verify the UnregisterDownloadFileCallback function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, UnregisterDownloadFileCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallback start"; + try { + int ret = g_servicePtr_->UnregisterDownloadFileCallback(); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallback FAILED"; + } + GTEST_LOG_(INFO) << "UnregisterDownloadFileCallback end"; +} + +/** + * @tc.name:UploadAssetTest + * @tc.desc:Verify the UploadAsset function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, UploadAssetTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UploadAsset start"; + try { + int32_t userId = 100; + std::string request = "testReq"; + std::string result = "expRes"; + int ret = g_servicePtr_->UploadAsset(userId, request, result); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UploadAsset FAILED"; + } + GTEST_LOG_(INFO) << "UploadAsset end"; +} + +/** + * @tc.name:DownloadFileTest001 + * @tc.desc:Verify the DownloadFile function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, DownloadFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFileTest001 start"; + try { + int32_t userId = 100; + std::string bundleName = "com.ohos.photos"; + std::string uri = "file://com.hmos.notepad/data/storage/el2/distributedfiles/dir/1.txt"; + AssetInfoObj assetInfoObj; + assetInfoObj.uri = uri; + int ret = g_servicePtr_->DownloadFile(userId, bundleName, assetInfoObj); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DownloadFileTest001 FAILED"; + } + GTEST_LOG_(INFO) << "DownloadFileTest001 end"; +} + +/** + * @tc.name:DownloadAssetTest001 + * @tc.desc:Verify the DownloadAsset function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, DownloadAssetTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadAssetTest001 start"; + try { + uint64_t taskId = 100; + int32_t userId = 100; + std::string bundleName = "com.ohos.photos"; + std::string networkId = "0.0.0.0"; + std::string uri = "file://com.hmos.notepad/data/storage/el2/distributedfiles/dir/1.txt"; + AssetInfoObj assetInfoObj; + assetInfoObj.uri = uri; + int ret = g_servicePtr_->DownloadAsset(taskId, userId, bundleName, networkId, assetInfoObj); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DownloadAssetTest001 FAILED"; + } + GTEST_LOG_(INFO) << "DownloadAssetTest001 end"; +} + +/** + * @tc.name:DownloadAssetTest002 + * @tc.desc:Verify the DownloadAsset function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, DownloadAssetTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadAssetTest002 start"; + try { + uint64_t taskId = 100; + int32_t userId = 100; + std::string bundleName = "com.ohos.photos"; + std::string networkId = "edge2cloud"; + AssetInfoObj assetInfoObj; + int ret = g_servicePtr_->DownloadAsset(taskId, userId, bundleName, networkId, assetInfoObj); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DownloadAssetTest002 FAILED"; + } + GTEST_LOG_(INFO) << "DownloadAssetTest002 end"; +} + +/** + * @tc.name:RegisterDownloadAssetCallbackTest + * @tc.desc:Verify the RegisterDownloadAssetCallback function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, RegisterDownloadAssetCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback start"; + try { + sptr callback = sptr(new CloudSyncCallbackMock()); + int ret = g_servicePtr_->RegisterDownloadAssetCallback(callback); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback FAILED"; + } + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback end"; +} + +/** + * @tc.name:RegisterDownloadAssetCallbackTest002 + * @tc.desc:Verify theRegisterDownloadAssetCallback function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, RegisterDownloadAssetCallbackTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback error branch start"; + try { + sptr callback = nullptr; + int ret = g_servicePtr_->RegisterDownloadAssetCallback(callback); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback error branch FAILED"; + } + GTEST_LOG_(INFO) << "RegisterDownloadAssetCallback error branch end"; +} + +/** + * @tc.name:DeleteAssetTest001 + * @tc.desc:Verify the DeleteAsset function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, DeleteAssetTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeleteAssetTest001 start"; + try { + int32_t userId = 100; + std::string uri = ""; + int ret = g_servicePtr_->DeleteAsset(userId, uri); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DeleteAssetTest001 FAILED"; + } + GTEST_LOG_(INFO) << "DeleteAssetTest001 end"; +} + +/** + * @tc.name:DeleteAssetTest002 + * @tc.desc:Verify the DeleteAsset function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, DeleteAssetTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeleteAssetTest002 start"; + try { + int32_t userId = 100; + std::string uri = "file://com.hmos.notepad/data/storage/el2/distributedfiles/dir/1.txt"; + int ret = g_servicePtr_->DeleteAsset(userId, uri); + EXPECT_EQ(ret, E_PERMISSION_DENIED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DeleteAssetTest002 FAILED"; + } + GTEST_LOG_(INFO) << "DeleteAssetTest002 end"; +} + +/** + * @tc.name:GetHmdfsPathTest001 + * @tc.desc:Verify the GetHmdfsPath function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, GetHmdfsPathTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetHmdfsPathTest001 start"; + try { + std::string uri = ""; + int32_t userId = 100; + std::string ret = g_servicePtr_->GetHmdfsPath(uri, userId); + EXPECT_EQ(ret, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetHmdfsPathTest001 FAILED"; + } + GTEST_LOG_(INFO) << "GetHmdfsPathTest001 end"; +} + +/** + * @tc.name:GetHmdfsPathTest002 + * @tc.desc:Verify the GetHmdfsPath function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, GetHmdfsPathTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetHmdfsPathTest002 start"; + try { + std::string uri = "invaild_uri"; + int32_t userId = 100; + std::string ret = g_servicePtr_->GetHmdfsPath(uri, userId); + EXPECT_EQ(ret, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetHmdfsPathTest002 FAILED"; + } + GTEST_LOG_(INFO) << "GetHmdfsPathTest002 end"; +} + +/** + * @tc.name:GetHmdfsPathTest003 + * @tc.desc:Verify the GetHmdfsPath function. + * @tc.type:FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, GetHmdfsPathTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetHmdfsPathTest003 start"; + try { + std::string uri = "file://com.hmos.notepad/data/storage/el2/distributedfiles/dir/1.txt"; + int32_t userId = 100; + std::string ret = g_servicePtr_->GetHmdfsPath(uri, userId); + std::string out = "/mnt/hmdfs/100/account/device_view/local/data/com.hmos.notepad/dir/1.txt"; + EXPECT_EQ(ret, out); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetHmdfsPathTest003 FAILED"; + } + GTEST_LOG_(INFO) << "GetHmdfsPathTest003 end"; +} + +/** + * @tc.name: OnStopTest + * @tc.desc: Verify the OnStop function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, OnStopTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnStop start"; + try { + g_servicePtr_->OnStop(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnStop FAILED"; + } + GTEST_LOG_(INFO) << "OnStop end"; +} + +/** + * @tc.name: OnAddSystemAbilityTest + * @tc.desc: Verify the OnAddSystemAbility function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, OnAddSystemAbilityTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnAddSystemAbility start"; + try { + int32_t systemAbilityId = 100; + std::string deviceId = ""; + g_servicePtr_->OnAddSystemAbility(systemAbilityId, deviceId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnAddSystemAbility FAILED"; + } + GTEST_LOG_(INFO) << "OnAddSystemAbility end"; +} + +/** + * @tc.name: LoadRemoteSATest + * @tc.desc: Verify the LoadRemoteSA function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudSyncServiceTest, LoadRemoteSATest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "LoadRemoteSA start"; + try { + std::string deviceId = ""; + int ret = g_servicePtr_->LoadRemoteSA(deviceId); + EXPECT_EQ(ret, E_SA_LOAD_FAILED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "LoadRemoteSA FAILED"; + } + GTEST_LOG_(INFO) << "LoadRemoteSA end"; +} + +/** + * @tc.name:SetDeathRecipientTest001 + * @tc.desc:Verify the SetDeathRecipient function. + * @tc.type:FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, SetDeathRecipientTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetDeathRecipientTest001 start"; + try { + EXPECT_NE(g_servicePtr_, nullptr); + sptr callback = sptr(new CloudSyncCallbackMock()); + g_servicePtr_->SetDeathRecipient(callback); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetDeathRecipientTest001 failed"; + } + GTEST_LOG_(INFO) << "SetDeathRecipientTest001 end"; +} + +/** + * @tc.name: OnStartTest001 + * @tc.desc: Verify the OnStart function. + * @tc.type: FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, OnStartTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnStartTest001 start"; + try { + EXPECT_NE(g_servicePtr_, nullptr); + SystemAbilityOnDemandReason startReason; + g_servicePtr_->OnStart(startReason); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnStartTest001 failed"; + } + GTEST_LOG_(INFO) << "OnStartTest001 end"; +} + +/** + * @tc.name: OnActiveTest001 + * @tc.desc: Verify the OnActive function. + * @tc.type: FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, OnActiveTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnActiveTest001 start"; + try { + EXPECT_NE(g_servicePtr_, nullptr); + SystemAbilityOnDemandReason startReason; + g_servicePtr_->OnActive(startReason); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnActiveTest001 failed"; + } + GTEST_LOG_(INFO) << "OnActiveTest001 end"; +} + +/** + * @tc.name: HandleStartReasonTest001 + * @tc.desc: Verify the HandleStartReason function. + * @tc.type: FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, HandleStartReasonTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleStartReasonTest001 start"; + try { + EXPECT_NE(g_servicePtr_, nullptr); + SystemAbilityOnDemandReason startReason; + g_servicePtr_->HandleStartReason(startReason); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "HandleStartReason failed"; + } + GTEST_LOG_(INFO) << "HandleStartReasonTest001 end"; +} + +/** + * @tc.name: PreInitTest001 + * @tc.desc: Verify the PreInit function. + * @tc.type: FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, PreInitTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PreInitTest001 start"; + try { + EXPECT_NE(g_servicePtr_, nullptr); + g_servicePtr_->PreInit(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PreInitTest001 failed"; + } + GTEST_LOG_(INFO) << "PreInitTest001 end"; +} + +/** + * @tc.name: InitTest001 + * @tc.desc: Verify the Init function. + * @tc.type: FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, InitTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitTest001 start"; + try { + EXPECT_NE(g_servicePtr_, nullptr); + g_servicePtr_->Init(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitTest001 failed"; + } + GTEST_LOG_(INFO) << "InitTest001 end"; +} + +/** + * @tc.name: GetBundleNameUserInfoTest001 + * @tc.desc: Verify the GetBundleNameUserInfo function. + * @tc.type: FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, GetBundleNameUserInfoTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetBundleNameUserInfoTest001 start"; + try { + EXPECT_NE(g_servicePtr_, nullptr); + BundleNameUserInfo userInfo; + int32_t ret = g_servicePtr_->GetBundleNameUserInfo(userInfo); + EXPECT_EQ(ret, E_INVAL_ARG); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetBundleNameUserInfoTest001 failed"; + } + GTEST_LOG_(INFO) << "GetBundleNameUserInfoTest001 end"; +} + +/** + * @tc.name: GetBundleNameUserInfoTest002 + * @tc.desc: Verify the GetBundleNameUserInfo function. + * @tc.type: FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, GetBundleNameUserInfoTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetBundleNameUserInfoTest002 start"; + try { + EXPECT_NE(g_servicePtr_, nullptr); + std::vector uriVec = {""}; + BundleNameUserInfo userInfo; + g_servicePtr_->GetBundleNameUserInfo(uriVec, userInfo); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetBundleNameUserInfoTest002 failed"; + } + GTEST_LOG_(INFO) << "GetBundleNameUserInfoTest002 end"; +} + +/** + * @tc.name: OnLoadSACompleteForRemoteTest001 + * @tc.desc: Verify the OnLoadSACompleteForRemote function. + * @tc.type: FUNC + * @tc.require: IB3SLT + */ +HWTEST_F(CloudSyncServiceTest, OnLoadSACompleteForRemoteTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnLoadSACompleteForRemoteTest001 start"; + try { + sptr callback = sptr(new CloudSyncCallbackMock()); + CloudSyncService::LoadRemoteSACallback callBack; + callBack.OnLoadSACompleteForRemote("test", 0, callback); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnLoadSACompleteForRemoteTest001 failed"; + } + GTEST_LOG_(INFO) << "OnLoadSACompleteForRemoteTest001 end"; +} +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_sa/ipc/download_asset_callback_manager_test.cpp b/cloud_file/test/unittests/cloudsync_sa/ipc/download_asset_callback_manager_test.cpp new file mode 100644 index 0000000..7d09b1d --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/ipc/download_asset_callback_manager_test.cpp @@ -0,0 +1,118 @@ +/* + * 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 +#include + +#include "download_asset_callback_manager.h" +#include "dfs_error.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace std; + +class DownloadAssetCallbackManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DownloadAssetCallbackManagerTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void DownloadAssetCallbackManagerTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void DownloadAssetCallbackManagerTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void DownloadAssetCallbackManagerTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: AddCallbackTest001 + * @tc.desc: Verify the AddCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(DownloadAssetCallbackManagerTest, AddCallbackTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AddCallbackTest Start"; + try { + DownloadAssetCallbackManager callbackManager; + callbackManager.AddCallback(nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AddCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "AddCallbackTest End"; +} + +/** + * @tc.name: AddCallbackTest002 + * @tc.desc: Verify the AddCallback function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(DownloadAssetCallbackManagerTest, AddCallbackTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AddCallbackTest Start"; + try { + DownloadAssetCallbackManager callbackManager; + sptr callback; + callbackManager.AddCallback(callback); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AddCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "AddCallbackTest End"; +} + +/** + * @tc.name: OnDownloadFinshedTest001 + * @tc.desc: Verify the OnDownloadFinshed function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(DownloadAssetCallbackManagerTest, OnDownloadFinshedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnDownloadFinshedTest Start"; + try { + uint64_t taskId = 100; + std::string uri = ""; + int32_t result = 1; + DownloadAssetCallbackManager callbackManager; + callbackManager.OnDownloadFinshed(taskId, uri, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnDownloadFinshedTest FAILED"; + } + GTEST_LOG_(INFO) << "OnDownloadFinshedTest End"; +} +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/ipc/download_asset_callback_proxy_test.cpp b/cloud_file/test/unittests/cloudsync_sa/ipc/download_asset_callback_proxy_test.cpp new file mode 100644 index 0000000..e752c14 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/ipc/download_asset_callback_proxy_test.cpp @@ -0,0 +1,108 @@ +/* + * 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 +#include + +#include "download_asset_callback_proxy.h" +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "asset_callback_mock.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing::ext; +using namespace testing; +using namespace std; + +class DownloadAssetCallbackProxyTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + shared_ptr proxy_ = nullptr; + sptr mock_ = nullptr; +}; + +void DownloadAssetCallbackProxyTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void DownloadAssetCallbackProxyTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void DownloadAssetCallbackProxyTest::SetUp(void) +{ + mock_ = sptr(new DownloadAssetCallbackMock()); + proxy_ = make_shared(mock_); + std::cout << "SetUp" << std::endl; +} + +void DownloadAssetCallbackProxyTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: OnFinishedTest + * @tc.desc: Verify the OnFinished function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(DownloadAssetCallbackProxyTest, OnFinishedTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnFinished Start"; + try { + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(E_OK)); + DownloadAssetCallback::TaskId taskId = 1; + std::string uri = "uri"; + int32_t result = 0; + proxy_->OnFinished(taskId, uri, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnFinished ERROR"; + } + GTEST_LOG_(INFO) << "OnFinished End"; +} + +/** + * @tc.name: OnFinishedTest002 + * @tc.desc: Verify the OnFinished function. + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(DownloadAssetCallbackProxyTest, OnFinishedTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnFinishedTest002 Start"; + try { + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).Times(1).WillOnce(Return(-1)); + DownloadAssetCallback::TaskId taskId = 1; + std::string uri = "uri"; + int32_t result = 0; + proxy_->OnFinished(taskId, uri, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnFinishedTest002 ERROR"; + } + GTEST_LOG_(INFO) << "OnFinishedTest002 End"; +} +} // namespace Test +} // namespace FileManagement::CloudSync +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_sa/log/BUILD.gn b/cloud_file/test/unittests/cloudsync_sa/log/BUILD.gn new file mode 100644 index 0000000..a2ba1bd --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/log/BUILD.gn @@ -0,0 +1,67 @@ +# 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("dfs_error_test") { + module_out_path = "cloud_file/cloud_file" + sources = [ "dfs_error_test.cpp" ] + + include_dirs = [ "${utils_path}/log/include" ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "hilog:libhilog", + "googletest:gmock_main", + "googletest:gtest_main", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("utils_log_test") { + module_out_path = "cloud_file/cloud_file" + sources = [ "utils_log_test.cpp" ] + + include_dirs = [ "${utils_path}/log/include" ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "hilog:libhilog", + "googletest:gmock_main", + "googletest:gtest_main" + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +group("cloudsync_sa_log_test") { + testonly = true + deps = [ + ":dfs_error_test", + ":utils_log_test", + ] +} diff --git a/cloud_file/test/unittests/cloudsync_sa/log/dfs_error_test.cpp b/cloud_file/test/unittests/cloudsync_sa/log/dfs_error_test.cpp new file mode 100644 index 0000000..1323a55 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/log/dfs_error_test.cpp @@ -0,0 +1,74 @@ +/* + * 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 + +#include "dfs_error.h" + +namespace OHOS::FileManagement::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class DfsErrorTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void DfsErrorTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void DfsErrorTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void DfsErrorTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void DfsErrorTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: Convert2JsErrNumTest + * @tc.desc: Verify the Convert2JsErrNum function + * @tc.type: FUNC + * @tc.require: SR000HRKKAs + */ +HWTEST_F(DfsErrorTest, Convert2JsErrNumTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Convert2JsErrNumTest Start"; + try { + int32_t errNum = -1; + int32_t ret = Convert2JsErrNum(errNum); + EXPECT_EQ(ret, errNum); + errNum = E_PERMISSION_DENIED; + ret = Convert2JsErrNum(errNum); + EXPECT_EQ(ret, E_PERMISSION); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "Convert2JsErrNumTest FAILED"; + } + GTEST_LOG_(INFO) << "Convert2JsErrNumTest End"; +} +} // namespace OHOS::FileManagement::Test diff --git a/cloud_file/test/unittests/cloudsync_sa/log/utils_log_test.cpp b/cloud_file/test/unittests/cloudsync_sa/log/utils_log_test.cpp new file mode 100644 index 0000000..c8860de --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/log/utils_log_test.cpp @@ -0,0 +1,76 @@ +/* + * 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 + +#include "utils_log.h" + +namespace OHOS::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class UtilsLogTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void UtilsLogTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void UtilsLogTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void UtilsLogTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void UtilsLogTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetFileNameFromFullPathTest + * @tc.desc: Verify the GetFileNameFromFullPath function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(UtilsLogTest, GetFileNameFromFullPathTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFileNameFromFullPathTest Start"; + try { + const char *str1 = "test_path"; + std::string out = ""; + std::string ret = GetFileNameFromFullPath(str1); + EXPECT_STREQ(ret.c_str(), out.c_str()); + const char *str2 = "test_path/1.txt"; + out = "1.txt"; + ret = GetFileNameFromFullPath(str2); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetFileNameFromFullPathTest FAILED"; + } + GTEST_LOG_(INFO) << "GetFileNameFromFullPathTest End"; +} +} // namespace OHOS::Test diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/abs_shared_result_set_mock.h b/cloud_file/test/unittests/cloudsync_sa/mock/abs_shared_result_set_mock.h new file mode 100644 index 0000000..db90826 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/abs_shared_result_set_mock.h @@ -0,0 +1,66 @@ +/* + * 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 OHOS_CLOUD_SYNC_SA_ABS_SHARED_RESULT_SET_MOCK_H +#define OHOS_CLOUD_SYNC_SA_ABS_SHARED_RESULT_SET_MOCK_H + +#include "abs_shared_result_set.h" + +#include +#include +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace NativeRdb; +class AbsSharedResultSetMock : public AbsSharedResultSet { +public: + ~AbsSharedResultSetMock() {} + MOCK_METHOD1(GetAllColumnNames, int(std::vector &)); + MOCK_METHOD1(GetColumnCount, int(int &)); + MOCK_METHOD2(GetColumnType, int(int, ColumnType &)); + MOCK_METHOD2(GetColumnIndex, int(const std::string &, int &)); + MOCK_METHOD2(GetColumnName, int(int, std::string &)); + MOCK_METHOD1(GetRowCount, int(int &)); + MOCK_METHOD1(GoTo, int(int)); + MOCK_METHOD1(GoToRow, int(int)); + MOCK_METHOD0(GoToFirstRow, int()); + MOCK_METHOD0(GoToLastRow, int()); + MOCK_METHOD0(GoToNextRow, int()); + MOCK_METHOD0(GoToPreviousRow, int()); + MOCK_METHOD1(IsEnded, int(bool &)); + MOCK_METHOD1(IsAtLastRow, int(bool &)); + MOCK_METHOD2(GetBlob, int(int, std::vector &)); + MOCK_METHOD2(GetString, int(int, std::string &)); + MOCK_METHOD2(GetInt, int(int, int &)); + MOCK_METHOD2(GetLong, int(int, int64_t &)); + MOCK_METHOD2(GetDouble, int(int, double &)); + MOCK_METHOD2(IsColumnNull, int(int, bool &)); + MOCK_METHOD0(Close, int()); + MOCK_METHOD1(GetRow, int(RowEntity &)); + + MOCK_CONST_METHOD0(IsClosed, bool()); + MOCK_CONST_METHOD1(GetRowIndex, int(int &)); + MOCK_CONST_METHOD1(IsStarted, int(bool &)); + MOCK_CONST_METHOD1(IsAtFirstRow, int(bool &)); + + MOCK_METHOD2(GetAsset, int(int32_t, ValueObject::Asset &)); + MOCK_METHOD2(GetAssets, int(int32_t, ValueObject::Assets &)); + MOCK_METHOD2(Get, int(int32_t, ValueObject &)); + MOCK_METHOD1(GetModifyTime, int(std::string &)); + MOCK_METHOD2(GetSize, int(int32_t, size_t &)); +}; +} +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/battery_status_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/battery_status_mock.cpp new file mode 100644 index 0000000..71e1fd9 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/battery_status_mock.cpp @@ -0,0 +1,56 @@ +/* + * 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 "battery_status.h" + +namespace OHOS::FileManagement::CloudSync { +constexpr int32_t DEFAULT_BATTERY_CAPCITY = 100; + +void BatteryStatus::SetChargingStatus(bool status) +{ +} + +void BatteryStatus::GetInitChargingStatus() +{ +} + +int32_t BatteryStatus::GetCapacity() +{ + int32_t capacity = DEFAULT_BATTERY_CAPCITY; + return capacity; +} + +bool BatteryStatus::IsAllowUpload(bool forceFlag) +{ + return true; +} + +bool BatteryStatus::IsBatteryCapcityOkay() +{ + if (level_ == LEVEL_TOO_LOW) { + return false; + } + return true; +} + +BatteryStatus::CapacityLevel BatteryStatus::GetCapacityLevel() +{ + return level_; +} + +bool BatteryStatus::IsCharging() +{ + return true; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.cpp new file mode 100644 index 0000000..3852af9 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.cpp @@ -0,0 +1,137 @@ +/* + * 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 "cloud_file_utils.h" +#include +#include +#include +#include +#include +#include +#include "utils_log.h" +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +namespace { + static const string LOCAL_PATH_DATA_SERVICE_EL2 = "/data/service/el2/"; + static const string LOCAL_PATH_HMDFS_CLOUD_DATA = "/hmdfs/cloud/data/"; + static const string CLOUD_FILE_CLOUD_ID_XATTR = "user.cloud.cloudid"; + static const uint32_t CLOUD_ID_MIN_SIZE = 3; + static const uint32_t CLOUD_ID_BUCKET_MID_TIMES = 2; + static const uint32_t CLOUD_ID_BUCKET_MAX_SIZE = 32; + static const int64_t SECOND_TO_MILLISECOND = 1e3; + static const int64_t MILLISECOND_TO_NANOSECOND = 1e6; + static const uint64_t DELTA_DISK = 0x9E3779B9; + static const uint64_t HMDFS_HASH_COL_BIT_DISK = (0x1ULL) << 63; +} + +constexpr unsigned HMDFS_IOC = 0xf2; +constexpr unsigned WRITEOPEN_CMD = 0x02; +#define HMDFS_IOC_GET_WRITEOPEN_CNT _IOR(HMDFS_IOC, WRITEOPEN_CMD, uint32_t) +const string CloudFileUtils::TMP_SUFFIX = ".temp.download"; + +bool CloudFileUtils::IsDotDotdot(const std::string &name) +{ + return name == "." || name == ".."; +} + +void CloudFileUtils::Str2HashBuf(const char *msg, size_t len, uint32_t *buf, int num) +{ +} + +void CloudFileUtils::TeaTransform(uint32_t buf[4], uint32_t const in[]) +{ +} + +uint32_t CloudFileUtils::DentryHash(const std::string &inputStr) +{ + return -1; +} + +uint32_t CloudFileUtils::GetBucketId(string cloudId) +{ + return 0; +} + +int64_t CloudFileUtils::Timespec2Milliseconds(const struct timespec &time) +{ + return 0; +} + +string CloudFileUtils::GetLocalBucketPath(string cloudId, string bundleName, int32_t userId) +{ + return ""; +} + +string CloudFileUtils::GetLocalFilePath(string cloudId, string bundleName, int32_t userId) +{ + if (userId == 0) { + return "mock"; + } + return "/data"; +} + +string CloudFileUtils::GetPathWithoutTmp(const string &path) +{ + return ""; +} + +bool CloudFileUtils::EndsWith(const string &fullString, const string &ending) +{ + return false; +} + +string CloudFileUtils::GetCloudId(const string &path) +{ + return ""; +} + +bool CloudFileUtils::CheckIsCloud(const string &key) +{ + return key == CLOUD_CLOUD_ID_XATTR; +} + +bool CloudFileUtils::CheckIsCloudLocation(const string &key) +{ + return key == CLOUD_FILE_LOCATION; +} + +bool CloudFileUtils::CheckIsHmdfsPermission(const string &key) +{ + return key == HMDFS_PERMISSION_XATTR; +} + +bool CloudFileUtils::CheckIsCloudRecycle(const string &key) +{ + return key == CLOUD_CLOUD_RECYCLE_XATTR; +} + +bool CloudFileUtils::CheckIsFavorite(const string &key) +{ + return key == IS_FAVORITE_XATTR; +} + +bool CloudFileUtils::CheckFileStatus(const string &key) +{ + return key == IS_FILE_STATUS_XATTR; +} + +bool CloudFileUtils::LocalWriteOpen(const string &dfsPath) +{ + return false; +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.h b/cloud_file/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.h new file mode 100644 index 0000000..c5f4145 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/cloud_file_utils_mock.h @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. All rights reserved. + * 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 CLOUD_FILE_DAEMON_CLOUD_FILE_UTILS_MOCK_H +#define CLOUD_FILE_DAEMON_CLOUD_FILE_UTILS_MOCK_H + +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { + +extern int g_getCloudIdFlag; +} +} +} +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/cloud_pref_impl_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/cloud_pref_impl_mock.cpp new file mode 100644 index 0000000..688bedd --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/cloud_pref_impl_mock.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. All rights reserved. + * 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 "cloud_pref_impl.h" +#include +#include +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +CloudPrefImpl::CloudPrefImpl(const int32_t userId, const std::string& bundleName, const std::string& tableName) +{ +} + +CloudPrefImpl::CloudPrefImpl(const std::string& fileName) +{ +} + +void CloudPrefImpl::SetString(const std::string& key, const std::string& value) +{ +} + +void CloudPrefImpl::GetString(const std::string& key, std::string &value) +{ +} + +void CloudPrefImpl::SetLong(const std::string& key, const int64_t value) +{ +} + +void CloudPrefImpl::GetLong(const std::string& key, int64_t &value) +{ +} + +void CloudPrefImpl::SetInt(const std::string& key, const int value) +{ +} + +void CloudPrefImpl::GetInt(const std::string& key, int32_t &value) +{ +} + +void CloudPrefImpl::SetBool(const std::string& key, const bool& value) +{ +} + +void CloudPrefImpl::GetBool(const std::string& key, bool& value) +{ +} + +void CloudPrefImpl::Clear() +{ +} + +void CloudPrefImpl::Delete(const std::string& key) +{ +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/cloud_status_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/cloud_status_mock.cpp new file mode 100644 index 0000000..26e66be --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/cloud_status_mock.cpp @@ -0,0 +1,40 @@ +/* + * 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 "cloud_status.h" + +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudSync { +int32_t CloudStatus::GetCurrentCloudInfo(const std::string &bundleName, const int32_t userId) +{ + return E_OK; +} + +bool CloudStatus::IsCloudStatusOkay(const std::string &bundleName, const int32_t userId) +{ + return true; +} + +int32_t CloudStatus::ChangeAppSwitch(const std::string &bundleName, const int32_t userId, bool appSwitchStatus) +{ + return E_OK; +} + +bool CloudStatus::IsAccountIdChanged(const std::string &accountId) +{ + return false; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_interface.h b/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_interface.h new file mode 100644 index 0000000..cf42a1d --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_interface.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_INTERFACE_H +#define OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_INTERFACE_H + +#include + +namespace OHOS { +namespace AAFwk { +class IDataAbilityObserver : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.DataAbilityObserver"); + + enum { + TRANS_HEAD, + DATA_ABILITY_OBSERVER_CHANGE = TRANS_HEAD, + DATA_ABILITY_OBSERVER_CHANGE_EXT, + DATA_ABILITY_OBSERVER_CHANGE_PREFERENCES, + TRANS_BUTT, + }; + + /** + * @brief Called back to notify that the data being observed has changed. + * + * @param uri Indicates the path of the data to operate. + */ + virtual void OnChange() = 0; + + /** + * @brief Called back to notify that the data being observed has changed. + * + * @param changeInfo Indicates the info of the data to operate. + */ + virtual void OnChangePreferences(const std::string &key) + { + return; + } +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_INTERFACE_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp new file mode 100644 index 0000000..00f12bc --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2024 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 "data_ability_observer_stub.h" + +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "ipc_skeleton.h" +#include "common_utils.h" +#include "string_ex.h" + +namespace OHOS { +namespace AAFwk { + +const DataAbilityObserverStub::RequestFuncType DataAbilityObserverStub::HANDLES[TRANS_BUTT] = { + &DataAbilityObserverStub::OnChangeInner, + &DataAbilityObserverStub::OnChangeExtInner, + &DataAbilityObserverStub::OnChangePreferencesInner, +}; + +DataAbilityObserverStub::DataAbilityObserverStub() {} + +DataAbilityObserverStub::~DataAbilityObserverStub() {} + +int DataAbilityObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + TAG_LOGD(AAFwkTag::DBOBSMGR, "code: %{public}d, flags: %{public}d, callingPid:%{public}d", code, option.GetFlags(), + IPCSkeleton::GetCallingPid()); + std::u16string descriptor = DataAbilityObserverStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + TAG_LOGE(AAFwkTag::DBOBSMGR, + "local descriptor is not equal to remote, descriptor: %{public}s, remoteDescriptor: %{public}s", + CommonUtils::Anonymous(Str16ToStr8(descriptor)).c_str(), + CommonUtils::Anonymous(Str16ToStr8(remoteDescriptor)).c_str()); + return ERR_INVALID_STATE; + } + + if (code < TRANS_HEAD || code >= TRANS_BUTT || HANDLES[code] == nullptr) { + TAG_LOGE(AAFwkTag::DBOBSMGR, "not support code:%u, BUTT:%d", code, TRANS_BUTT); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return (this->*HANDLES[code])(data, reply); +} + +/** + * @brief Called back to notify that the data being observed has changed. + * + * @return Returns 0 on success, others on failure. + */ +int32_t DataAbilityObserverStub::OnChangeInner(MessageParcel &data, MessageParcel &reply) +{ + OnChange(); + return ERR_NONE; +} + +/** + * @brief Called back to notify that the data being observed has changed. + * + * @return Returns 0 on success, others on failure. + */ +int32_t DataAbilityObserverStub::OnChangeExtInner(MessageParcel &data, MessageParcel &reply) +{ + ChangeInfo changeInfo; + if (!ChangeInfo::Unmarshalling(changeInfo, data)) { + return IPC_STUB_INVALID_DATA_ERR; + } + OnChangeExt(changeInfo); + return ERR_NONE; +} + +/** + * @brief Called back to notify that the data being observed has changed. + * + * @return Returns 0 on success, others on failure. + */ +int32_t DataAbilityObserverStub::OnChangePreferencesInner(MessageParcel &data, MessageParcel &reply) +{ + std::string key = data.ReadString(); + if (key.empty()) { + return IPC_STUB_INVALID_DATA_ERR; + } + OnChangePreferences(key); + return ERR_NONE; +} + +void DataObsCallbackRecipient::OnRemoteDied(const wptr &remote) +{ + if (handler_) { + handler_(remote); + } +} + +DataObsCallbackRecipient::DataObsCallbackRecipient(RemoteDiedHandler handler) : handler_(handler) {} + +DataObsCallbackRecipient::~DataObsCallbackRecipient() {} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.h b/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.h new file mode 100644 index 0000000..5227c35 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_STUB_H +#define OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_STUB_H + +#include +#include + +#include "data_ability_observer_interface.h" +#include "nocopyable.h" + +#include +#include + +namespace OHOS { +namespace AAFwk { +class DataAbilityObserverStub : public IRemoteStub { +public: + DataAbilityObserverStub(); + virtual ~DataAbilityObserverStub(); + + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + /** + * @brief Called back to notify that the data being observed has changed. + * + */ + int32_t OnChangeInner(MessageParcel &data, MessageParcel &reply); + + /** + * @brief Called back to notify that the data being observed has changed. + * + */ + int32_t OnChangeExtInner(MessageParcel &data, MessageParcel &reply); + + /** + * @brief Called back to notify that the data being observed has changed. + * + */ + int32_t OnChangePreferencesInner(MessageParcel &data, MessageParcel &reply); + + using RequestFuncType = int (DataAbilityObserverStub::*)(MessageParcel &data, MessageParcel &reply); + static const RequestFuncType HANDLES[TRANS_BUTT]; + + DISALLOW_COPY_AND_MOVE(DataAbilityObserverStub); +}; + +/** + * @class DataObsCallbackRecipient + * DataObsCallbackRecipient notices IRemoteBroker died. + */ +class DataObsCallbackRecipient : public IRemoteObject::DeathRecipient { +public: + using RemoteDiedHandler = std::function &)>; + explicit DataObsCallbackRecipient(RemoteDiedHandler handler); + virtual ~DataObsCallbackRecipient(); + virtual void OnRemoteDied(const wptr &remote); + +private: + RemoteDiedHandler handler_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_STUB_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/datashare_errno.h b/cloud_file/test/unittests/cloudsync_sa/mock/datashare_errno.h new file mode 100644 index 0000000..ec16b08 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/datashare_errno.h @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2024 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 DATASHARE_ERRNO_H +#define DATASHARE_ERRNO_H + +namespace OHOS { +namespace DataShare { + +/** +* @brief The base code of the exception error code. +*/ +constexpr int E_BASE = 1000; + +/** +* @brief The error code for common exceptions. +*/ +constexpr int E_ERROR = (E_BASE + 1); + +/** +* @brief The error code for register exceptions. +*/ +constexpr int E_REGISTERED_REPEATED = (E_BASE + 2); + + +/** +* @brief The error code for register exceptions. +*/ +constexpr int E_UNREGISTERED_EMPTY = (E_BASE + 3); + +/** +* @brief The error code for invalid statement. +*/ +constexpr int E_INVALID_STATEMENT = (E_BASE + 7); + +/** +* @brief The error code for invalid column index. +*/ +constexpr int E_INVALID_COLUMN_INDEX = (E_BASE + 8); + +/** +* @brief The error code for invalid object type. +*/ +constexpr int E_INVALID_OBJECT_TYPE = (E_BASE + 20); + +/** +* @brief The error code for invalid parcel. +*/ +constexpr int E_INVALID_PARCEL = (E_BASE + 42); + +/** +* @brief The version is smaller than exist. +*/ +constexpr int E_VERSION_NOT_NEWER = (E_BASE + 45); + +/** +* @brief Cannot find the template +*/ +constexpr int E_TEMPLATE_NOT_EXIST = (E_BASE + 46); + +/** +* @brief Cannot find the subscriber +*/ +constexpr int E_SUBSCRIBER_NOT_EXIST = (E_BASE + 47); + +/** +* @brief Cannot find the uri +*/ +constexpr int E_URI_NOT_EXIST = (E_BASE + 48); + +/** +* @brief Cannot find the bundleName +*/ +constexpr int E_BUNDLE_NAME_NOT_EXIST = (E_BASE + 49); + +/** +* @brief BMS not ready +*/ +constexpr int E_BMS_NOT_READY = (E_BASE + 50); + +/** +* @brief metaData not exists +*/ +constexpr int E_METADATA_NOT_EXISTS = (E_BASE + 51); +/** +* @brief silent proxy is disable +*/ +constexpr int E_SILENT_PROXY_DISABLE = (E_BASE + 52); +/** +* @brief token is empty +*/ +constexpr int E_TOKEN_EMPTY = (E_BASE + 53); +/** +* @brief ext uri is empty +*/ +constexpr int E_EXT_URI_INVALID = (E_BASE + 54); +/** +* @brief DataShare not ready +*/ +constexpr int E_DATA_SHARE_NOT_READY = (E_BASE + 55); +} // namespace DataShare +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/datashare_helper.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/datashare_helper.cpp new file mode 100644 index 0000000..fe284e1 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/datashare_helper.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2024 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 "datashare_helper.h" +#include "datashare_result_set.h" + +namespace OHOS { +namespace DataShare { +std::shared_ptr DataShareHelper::instance_; +DataSharePredicates *DataSharePredicates::EqualTo(const std::string &field, const std::string &value) +{ + return this; +} + +std::shared_ptr DataShareHelper::Creator( + const std::string &strUri, const CreateOptions &options, const std::string &bundleName) +{ + if (instance_ != nullptr) { + return instance_; + } + instance_ = std::make_shared(); + return instance_; +} + +std::shared_ptr DataShareHelper::Query(Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError *businessError) +{ + if (resultSet_ != nullptr) { + return resultSet_; + } + resultSet_ = std::make_shared(); + return resultSet_; +} + +void DataShareHelper::RegisterObserver(const Uri &uri, const sptr &dataObserver) +{ + return; +} + +void DataShareHelper::UnregisterObserver(const Uri &uri, const sptr &dataObserver) +{ + return; +} + +bool DataShareHelper::Release() +{ + return true; +} +} // namespace OHOS +} // namespace DataShare \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/datashare_helper.h b/cloud_file/test/unittests/cloudsync_sa/mock/datashare_helper.h new file mode 100644 index 0000000..25ad85e --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/datashare_helper.h @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2024 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 DATASHARE_HELPER_H +#define DATASHARE_HELPER_H + +#include +#include + +#include "data_ability_observer_interface.h" +#include "datashare_result_set.h" +#include "uri.h" + +namespace OHOS { +namespace DataShare { +constexpr int32_t E_OK = 0; + +struct CreateOptions { + /** Specifies whether the {@link DataShareHelper} in proxy mode. */ + bool isProxy_ = true; + /** Specifies the System token. */ + sptr token_; + /** Specifies whether use options to create DataShareHelper. */ + bool enabled_ = false; +}; + +class DataSharePredicates { +public: + DataSharePredicates *EqualTo(const std::string &field, const std::string &value); +}; +class DatashareBusinessError {}; + +class DataShareHelper { +public: + DataShareHelper() = default; + ~DataShareHelper() = default; + static std::shared_ptr Creator( + const std::string &strUri, const CreateOptions &options, const std::string &bundleName = "com.ohos.photos"); + std::shared_ptr Query(Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError *businessError = nullptr); + + static void RegisterObserver(const Uri &uri, const sptr &dataObserver); + static void UnregisterObserver(const Uri &uri, const sptr &dataObserver); + static bool Release(); + +private: + static std::shared_ptr instance_; + std::shared_ptr resultSet_; +}; + + +} // namespace OHOS +} // namespace DataShare +#endif // DATASHARE_HELPER_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/datashare_result_set.h b/cloud_file/test/unittests/cloudsync_sa/mock/datashare_result_set.h new file mode 100644 index 0000000..0bf4b76 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/datashare_result_set.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 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 DATASHARE_RESULT_SET_H +#define DATASHARE_RESULT_SET_H + +namespace OHOS { +namespace DataShare { +class DataShareResultSet { +public: + static int GetColumnIndex(const std::string &columnName, int &columnIndex) + { + return 0; + } + static int GetString(int columnIndex, std::string &value) + { + return 0; + } + static int GetLong(int columnIndex, int64_t &value) + { + return 0; + } + static int GetInt(int columnIndex, int &value) + { + return 0; + } + static int GoToFirstRow() + { + return 0; + } + static int GoToNextRow() + { + return 0; + } + static int Close() + { + return 0; + } +}; + +} +} +#endif // DATASHARE_RESULT_SET_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.cpp new file mode 100644 index 0000000..11095fb --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.cpp @@ -0,0 +1,60 @@ +/* + * 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 "dfsu_access_token_helper_mock.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement { +using namespace std; +bool DfsuAccessTokenHelper::CheckCallerPermission(const std::string &permissionName) +{ + return FileManagement::CloudSync::DfsuAccessToken::dfsuAccessToken->CheckCallerPermission(permissionName); +} + +bool DfsuAccessTokenHelper::CheckPermission(uint32_t tokenId, const std::string &permissionName) +{ + return FileManagement::CloudSync::DfsuAccessToken::dfsuAccessToken->CheckPermission(tokenId, permissionName); +} + +int32_t DfsuAccessTokenHelper::GetCallerBundleName(std::string &bundleName) +{ + return FileManagement::CloudSync::DfsuAccessToken::dfsuAccessToken->GetCallerBundleName(bundleName); +} + +int32_t DfsuAccessTokenHelper::GetBundleNameByToken(uint32_t tokenId, std::string &bundleName) +{ + return FileManagement::CloudSync::DfsuAccessToken::dfsuAccessToken->GetBundleNameByToken(tokenId, bundleName); +} +bool DfsuAccessTokenHelper::IsSystemApp() +{ + return FileManagement::CloudSync::DfsuAccessToken::dfsuAccessToken->IsSystemApp(); +} + +int32_t DfsuAccessTokenHelper::GetUserId() +{ + return FileManagement::CloudSync::DfsuAccessToken::dfsuAccessToken->GetUserId(); +} + +int32_t DfsuAccessTokenHelper::GetPid() +{ + return FileManagement::CloudSync::DfsuAccessToken::dfsuAccessToken->GetPid(); +} + +bool DfsuAccessTokenHelper::CheckUriPermission(const std::string &uri) +{ + return FileManagement::CloudSync::DfsuAccessToken::dfsuAccessToken->CheckUriPermission(uri); +} + +} // namespace OHOS::FileManagement \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.h b/cloud_file/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.h new file mode 100644 index 0000000..10995d3 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/dfsu_access_token_helper_mock.h @@ -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. + */ + +#ifndef DFSU_ACCESS_TOKEN_HELPER_MOCK +#define DFSU_ACCESS_TOKEN_HELPER_MOCK + +#include +#include "dfsu_access_token_helper.h" +#include + +namespace OHOS::FileManagement::CloudSync { + +class DfsuAccessToken { +public: + virtual bool CheckCallerPermission(const std::string &permissionName); + virtual int32_t GetCallerBundleName(std::string &bundleName); + virtual bool CheckPermission(uint32_t tokenId, const std::string &permissionName); + virtual bool CheckUriPermission(const std::string &uri); + virtual int32_t GetBundleNameByToken(uint32_t tokenId, std::string &bundleName); + virtual bool IsSystemApp(); + virtual int32_t GetUserId(); + virtual int32_t GetPid(); + +public: + DfsuAccessToken() = default; + virtual ~DfsuAccessToken() = default; + static inline std::shared_ptr dfsuAccessToken = nullptr; +}; + +class DfsuAccessTokenMock : public DfsuAccessToken { +public: + MOCK_METHOD1(CheckCallerPermission, bool(const std::string &permissionName)); + MOCK_METHOD1(GetCallerBundleName, int32_t(std::string &bundleName)); + MOCK_METHOD2(CheckPermission, bool(uint32_t tokenId, const std::string &permissionName)); + MOCK_METHOD1(CheckUriPermission, bool(const std::string &uri)); + MOCK_METHOD2(GetBundleNameByToken, int32_t(uint32_t tokenId, std::string &bundleName)); + MOCK_METHOD0(IsSystemApp, bool()); + MOCK_METHOD0(GetUserId, int32_t()); + MOCK_METHOD0(GetPid, int32_t()); +}; + +} +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/network_set_manager_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/network_set_manager_mock.cpp new file mode 100644 index 0000000..0b1304d --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/network_set_manager_mock.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2024 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 "network_set_manager.h" + +#include "accesstoken_kit.h" +#include "cloud_file_kit.h" +#include "datashare_errno.h" +#include "datashare_result_set.h" +#include "dfs_error.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "parameters.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +const std::string QUERY_URI = "datashareproxy://"; +const std::string PHOTO_NET_CONT = "datashare://kernel/linux/common_modules/cloud_filecom.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; +const std::string SWITCH_STATUS_KEY = "useMobileNetworkData"; +const std::string CLOUDDRIVE_KEY = "persist.kernel.bundle_name.clouddrive"; +const std::string PHOTOS_BUNDLE_NAME = "com.ohos.photos"; +const std::string BUNDLE_NAME_KEY = "key"; +const std::string BUNDLE_NAME_VALUE = "value"; +const std::int32_t MOCK_USER_ID = 1; +auto clouddriveBundleName = system::GetParameter(CLOUDDRIVE_KEY, ""); +auto photoQueryUri = PHOTO_NET_CONT + "&key=photo_network_connection_status"; +auto queryUri = QUERY_URI + clouddriveBundleName + "/cloud_sp?key=" + SWITCH_STATUS_KEY; +DataShare::CreateOptions options; + +int32_t NetworkSetManager::QueryCellularConnect(int32_t userId, const std::string &bundleName) +{ + return E_OK; +} + +int32_t NetworkSetManager::QueryNetConnect(int32_t userId, const std::string &bundleName) +{ + return E_OK; +} + +void NetworkSetManager::GetCellularConnect(const std::string &bundleName, const int32_t userId) +{ +} + +void NetworkSetManager::GetNetConnect(const std::string &bundleName, const int32_t userId) +{ +} + +bool NetworkSetManager::GetConfigParams(const std::string &bundleName, int32_t userId) +{ + return true; +} + +void NetworkSetManager::UnregisterObserver(const std::string &bundleName, const int32_t userId, const int32_t type) +{ +} + +void NetworkSetManager::RegisterObserver(const std::string &bundleName, const int32_t userId, const int32_t type) +{ +} + +void MobileNetworkObserver::OnChange() +{ +} + +bool NetworkSetManager::IsAllowCellularConnect(const std::string &bundleName, const int32_t userId) +{ + if (userId == MOCK_USER_ID) { + return true; + } + return false; +} + +bool NetworkSetManager::IsAllowNetConnect(const std::string &bundleName, const int32_t userId) +{ + if (userId == MOCK_USER_ID) { + return true; + } + return false; +} + +void NetworkSetManager::InitNetworkSetManager(const std::string &bundleName, const int32_t userId) +{ +} + +void NetworkSetManager::InitDataSyncManager(std::shared_ptr dataSyncManager) +{ +} + +void NetworkSetManager::NetWorkChangeStopUploadTask() +{ +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/network_status_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/network_status_mock.cpp new file mode 100644 index 0000000..d92482a --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/network_status_mock.cpp @@ -0,0 +1,73 @@ +/* + * 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 "network_status.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement::CloudSync { +using namespace CloudFile; + +int32_t NetworkStatus::RegisterNetConnCallback(std::shared_ptr dataSyncManager) +{ + return E_OK; +} + +int32_t NetworkStatus::GetDefaultNet() +{ + return E_OK; +} + +void NetworkStatus::SetNetConnStatus(NetManagerStandard::NetAllCapabilities &netAllCap) +{ +} + +int32_t NetworkStatus::GetAndRegisterNetwork(std::shared_ptr dataSyncManager) +{ + int32_t res = GetDefaultNet(); + if (res != E_OK) { + return res; + } + + return RegisterNetConnCallback(dataSyncManager); +} + +void NetworkStatus::InitNetwork(std::shared_ptr dataSyncManager) +{ +} + +void NetworkStatus::SetNetConnStatus(NetworkStatus::NetConnStatus netStatus) +{ + return; +} + +bool NetworkStatus::CheckMobileNetwork(const std::string &bundleName, const int32_t userId) +{ + return true; +} + +bool NetworkStatus::CheckNetwork(const std::string &bundleName, const int32_t userId) +{ + return true; +} + +NetworkStatus::NetConnStatus NetworkStatus::GetNetConnStatus() +{ + return NetworkStatus::NetConnStatus::WIFI_CONNECT; +} + +void NetworkStatus::NetWorkChangeStopUploadTask() +{ +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/parameter.h b/cloud_file/test/unittests/cloudsync_sa/mock/parameter.h new file mode 100644 index 0000000..eccf5c0 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/parameter.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2024 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 STARTUP_SYSPARAM_PARAMETER_API_H +#define STARTUP_SYSPARAM_PARAMETER_API_H +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +int WaitParameter(const char *key, const char *value, int timeout); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // STARTUP_SYSPARAM_PARAMETER_API_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/parameters.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/parameters.cpp new file mode 100644 index 0000000..568b24e --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/parameters.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 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 "parameters.h" +#include "parameter.h" + +int WaitParameter(const char *key, const char *value, int timeout) +{ + return 0; +} + +namespace OHOS { +namespace system { +/* + * Returns true if the system parameter `key` has the value "1", "y", "yes", "on", or "true", + * false for "0", "n", "no", "off", or "false", or `def` otherwise. + */ +bool GetBoolParameter(const std::string &key, bool def) +{ + return true; +} + +std::string GetParameter(const std::string &key, const std::string &def) +{ + return ""; +} + +bool SetParameter(const std::string& key, const std::string& value) +{ + return true; +} +} // namespace system +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/parameters.h b/cloud_file/test/unittests/cloudsync_sa/mock/parameters.h new file mode 100644 index 0000000..a7bdda6 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/parameters.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2024 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 SYSTEM_PARAMETERS_H +#define SYSTEM_PARAMETERS_H + +#include +#include + +namespace OHOS { +namespace system { +/* + * Returns true if the system parameter `key` has the value "1", "y", "yes", "on", or "true", + * false for "0", "n", "no", "off", or "false", or `def` otherwise. + */ +bool GetBoolParameter(const std::string &key, bool def); +std::string GetParameter(const std::string &key, const std::string &def); +bool SetParameter(const std::string& key, const std::string& value); +} // namespace system +} // namespace OHOS + +#endif // SYSTEM_PARAMETERS_H \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/rdb_store_mock.h b/cloud_file/test/unittests/cloudsync_sa/mock/rdb_store_mock.h new file mode 100644 index 0000000..cc99c01 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/rdb_store_mock.h @@ -0,0 +1,178 @@ +/* + * 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 OHOS_CLOUD_SYNC_SA_RDB_STORE_MOCK_H +#define OHOS_CLOUD_SYNC_SA_RDB_STORE_MOCK_H + +#include "abs_rdb_predicates.h" +#include "rdb_helper.h" +#include "result_set.h" +#include "value_object.h" +#include "values_bucket.h" + +#include +#include + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace NativeRdb; +class RdbStoreMock final : public NativeRdb::RdbStore { +public: + MOCK_METHOD3(Insert, int(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues)); + MOCK_METHOD3(BatchInsert, + int(int64_t &outInsertNum, + const std::string &table, + const std::vector &initialBatchValues)); + MOCK_METHOD3(Replace, int(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues)); + MOCK_METHOD4(InsertWithConflictResolution, + int(int64_t &outRowId, + const std::string &table, + const ValuesBucket &initialValues, + ConflictResolution conflictResolution)); + MOCK_METHOD5(Update, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &whereArgs)); + MOCK_METHOD5(Update, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &bindArgs)); + + MOCK_METHOD6(UpdateWithConflictResolution, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &whereArgs, + ConflictResolution conflictResolution)); + + MOCK_METHOD6(UpdateWithConflictResolution, + int(int &changedRows, + const std::string &table, + const ValuesBucket &values, + const std::string &whereClause, + const std::vector &bindArgs, + ConflictResolution conflictResolution)); + + MOCK_METHOD4(Delete, + int(int &deletedRows, + const std::string &table, + const std::string &whereClause, + const std::vector &whereArgs)); + + MOCK_METHOD4(Delete, + int(int &deletedRows, + const std::string &table, + const std::string &whereClause, + const std::vector &bindArgs)); + + MOCK_METHOD2(ExecuteSql, int(const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteAndGetLong, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteAndGetString, + int(std::string &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteForLastInsertedRowId, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD3(ExecuteForChangedRowCount, + int(int64_t &outValue, const std::string &sql, const std::vector &bindArgs)); + + MOCK_METHOD2(Backup, int(const std::string &databasePath, const std::vector &destEncryptKey)); + + MOCK_METHOD3(Attach, + int(const std::string &alias, const std::string &pathName, const std::vector destEncryptKey)); + + MOCK_METHOD2(Count, int(int64_t &outValue, const AbsRdbPredicates &predicates)); + MOCK_METHOD2(Query, + std::shared_ptr(const AbsRdbPredicates &predicates, + const std::vector &columns)); + MOCK_METHOD11(Query, + std::shared_ptr(int &errCode, + bool distinct, + const std::string &table, + const std::vector &columns, + const std::string &whereClause, + const std::vector &bindArgs, + const std::string &groupBy, + const std::string &indexName, + const std::string &orderBy, + const int &limit, + const int &offset)); + MOCK_METHOD2(QuerySql, + std::shared_ptr(const std::string &sql, + const std::vector &selectionArgs)); + MOCK_METHOD2(QuerySql, + std::shared_ptr(const std::string &sql, + const std::vector &bindArgs)); + MOCK_METHOD2(QueryByStep, + std::shared_ptr(const std::string &sql, const std::vector &selectionArgs)); + MOCK_METHOD3(QueryByStep, + std::shared_ptr(const std::string &sql, const std::vector &bindArgs, + bool preCount)); + + MOCK_METHOD3(QueryByStep, + std::shared_ptr(const AbsRdbPredicates &predicates, + const std::vector &columns, bool preCount)); + + MOCK_METHOD4(RemoteQuery, + std::shared_ptr(const std::string &device, + const AbsRdbPredicates &predicates, + const std::vector &columns, + int &errCode)); + + MOCK_METHOD3(GetModifyTime, ModifyTime(const std::string &table, const std::string &columnName, + std::vector &keys)); + + MOCK_METHOD3(SetDistributedTables, int(const std::vector &tables, int32_t type, + const DistributedRdb::DistributedConfig &distributedConfig)); + MOCK_METHOD3(ObtainDistributedTableName, + std::string(const std::string &device, const std::string &table, int &errCode)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncBrief& async)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncDetail& async)); + MOCK_METHOD3(Sync, int(const SyncOption &option, const std::vector& tables, const AsyncDetail& async)); + MOCK_METHOD2(Subscribe, int(const SubscribeOption &option, RdbStoreObserver *observer)); + MOCK_METHOD2(UnSubscribe, int(const SubscribeOption &option, RdbStoreObserver *observer)); + MOCK_METHOD1(RegisterAutoSyncCallback, int(std::shared_ptr syncObserver)); + MOCK_METHOD1(UnregisterAutoSyncCallback, int(std::shared_ptr syncObserver)); + MOCK_METHOD2(CleanDirtyData, int(const std::string &table, uint64_t cursor)); + MOCK_METHOD1(Notify, int(const std::string &event)); + MOCK_METHOD2(DropDeviceData, bool(const std::vector &devices, const DropOption &option)); + MOCK_METHOD3(Update, int(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates)); + MOCK_METHOD2(Delete, int(int &deletedRows, const AbsRdbPredicates &predicates)); + MOCK_METHOD1(GetVersion, int(int &version)); + MOCK_METHOD1(SetVersion, int(int version)); + MOCK_METHOD0(BeginTransaction, int()); + MOCK_METHOD0(RollBack, int()); + MOCK_METHOD0(Commit, int()); + MOCK_METHOD0(IsInTransaction, bool()); + MOCK_METHOD0(GetPath, std::string()); + MOCK_METHOD0(IsHoldingConnection, bool()); + MOCK_CONST_METHOD0(IsOpen, bool()); + MOCK_CONST_METHOD0(IsReadOnly, bool()); + MOCK_CONST_METHOD0(IsMemoryRdb, bool()); + MOCK_METHOD2(Restore, int(const std::string &backupPath, const std::vector &newKey)); + MOCK_METHOD1(GetRebuilt, int(RebuiltType &rebuilt)); +}; +} // namespace OHOS::FileManagement::CloudSync::Test +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/result_set_mock.h b/cloud_file/test/unittests/cloudsync_sa/mock/result_set_mock.h new file mode 100644 index 0000000..380a372 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/result_set_mock.h @@ -0,0 +1,66 @@ +/* + * 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 OHOS_CLOUD_SYNC_SA_RESULT_SET_MOCK_H +#define OHOS_CLOUD_SYNC_SA_RESULT_SET_MOCK_H + +#include "result_set.h" + +#include +#include +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace NativeRdb; +class ResultSetMock : public ResultSet { +public: + ~ResultSetMock() {} + MOCK_METHOD1(GetAllColumnNames, int(std::vector &)); + MOCK_METHOD1(GetColumnCount, int(int &)); + MOCK_METHOD2(GetColumnType, int(int, ColumnType &)); + MOCK_METHOD2(GetColumnIndex, int(const std::string &, int &)); + MOCK_METHOD2(GetColumnName, int(int, std::string &)); + MOCK_METHOD1(GetRowCount, int(int &)); + MOCK_METHOD1(GoTo, int(int)); + MOCK_METHOD1(GoToRow, int(int)); + MOCK_METHOD0(GoToFirstRow, int()); + MOCK_METHOD0(GoToLastRow, int()); + MOCK_METHOD0(GoToNextRow, int()); + MOCK_METHOD0(GoToPreviousRow, int()); + MOCK_METHOD1(IsEnded, int(bool &)); + MOCK_METHOD1(IsAtLastRow, int(bool &)); + MOCK_METHOD2(GetBlob, int(int, std::vector &)); + MOCK_METHOD2(GetString, int(int, std::string &)); + MOCK_METHOD2(GetInt, int(int, int &)); + MOCK_METHOD2(GetLong, int(int, int64_t &)); + MOCK_METHOD2(GetDouble, int(int, double &)); + MOCK_METHOD2(IsColumnNull, int(int, bool &)); + MOCK_METHOD0(Close, int()); + MOCK_METHOD1(GetRow, int(RowEntity &)); + + MOCK_CONST_METHOD0(IsClosed, bool()); + MOCK_CONST_METHOD1(GetRowIndex, int(int &)); + MOCK_CONST_METHOD1(IsStarted, int(bool &)); + MOCK_CONST_METHOD1(IsAtFirstRow, int(bool &)); + + MOCK_METHOD2(GetAsset, int(int32_t, ValueObject::Asset &)); + MOCK_METHOD2(GetAssets, int(int32_t, ValueObject::Assets &)); + MOCK_METHOD2(Get, int(int32_t, ValueObject &)); + MOCK_METHOD1(GetModifyTime, int(std::string &)); + MOCK_METHOD2(GetSize, int(int32_t, size_t &)); +}; +} // namespace OHOS::FileManagement::CloudSync::Test +#endif \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/sync_state_manager_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/sync_state_manager_mock.cpp new file mode 100644 index 0000000..ba79860 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/sync_state_manager_mock.cpp @@ -0,0 +1,51 @@ +/* + * 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 "sync_state_manager.h" + +#include + +#include + +namespace OHOS::FileManagement::CloudSync { + +Action SyncStateManager::UpdateSyncState(SyncState newState) +{ + return nextAction_; +} + +bool SyncStateManager::CheckAndSetPending(bool forceFlag, SyncTriggerType triggerType) +{ + GTEST_LOG_(INFO) << "CheckAndSetPending Start"; + return forceFlag; +} + +bool SyncStateManager::GetStopSyncFlag() +{ + return stopSyncFlag_; +} + +void SyncStateManager::SetStopSyncFlag() {} + +SyncState SyncStateManager::GetSyncState() const +{ + return state_; +} + +bool SyncStateManager::GetForceFlag() const +{ + return isForceSync_; +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/mock/task_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/mock/task_mock.cpp new file mode 100644 index 0000000..b22fbbb --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/mock/task_mock.cpp @@ -0,0 +1,131 @@ +/* + * 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 "task.h" + +#include +#include +#include + +#include "sdk_helper.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { +using namespace std; + +/* task runner */ +TaskRunner::TaskRunner(function callback) : callback_(callback) {} + +TaskRunner::~TaskRunner() {} + +int32_t TaskRunner::GenerateTaskId() +{ + return currentId_.fetch_add(1); +} + +int32_t TaskRunner::AddTask(shared_ptr t) +{ + return E_OK; +} + +int32_t TaskRunner::StartTask(shared_ptr t, TaskAction action) +{ + GTEST_LOG_(INFO) << "StartTask Start"; + return E_OK; +} + +int32_t TaskRunner::CommitTask(shared_ptr t) +{ + GTEST_LOG_(INFO) << "CommitTask Start"; + return E_OK; +} + +void TaskRunner::CompleteTask(int32_t id) {} + +bool TaskRunner::ReleaseTask() +{ + return false; +} + +void TaskRunner::SetStopFlag(std::shared_ptr stopFlag) +{ +} + +void TaskRunner::Reset() +{ + currentId_.store(0); +} + +void TaskRunner::SetCommitFunc(function, shared_ptr)> func) {} + +void TaskRunner::CommitDummyTask() {} + +void TaskRunner::CompleteDummyTask() {} + +/* TaskManager */ +TaskManager::TaskManager() {} + +TaskManager::~TaskManager() {} + +shared_ptr TaskManager::AllocRunner(int32_t userId, + const std::string &bundleName, + function callback) +{ + string key = GetKey(userId, bundleName); + unique_lock wlock(mapMutex_); + if (map_.find(key) == map_.end()) { + auto runner = make_shared(callback); + InitRunner(*runner); + map_.insert({key, runner}); + } + return map_[key]; +} + +void TaskManager::ReleaseRunner(int32_t userId, const std::string &bundleName) +{ + string key = GetKey(userId, bundleName); + unique_lock wlock(mapMutex_); + map_.erase(key); +} + +shared_ptr TaskManager::GetRunner(int32_t userId, const std::string &bundleName) +{ + string key = GetKey(userId, bundleName); + shared_lock rlock(mapMutex_); + if (map_.find(key) == map_.end()) { + return nullptr; + } + return map_[key]; +} + +void TaskManager::InitRunner(TaskRunner &runner) +{ + runner.SetCommitFunc(bind(&TaskManager::CommitTask, this, placeholders::_1, placeholders::_2)); +} + +int32_t TaskManager::CommitTask(shared_ptr runner, shared_ptr t) +{ + GTEST_LOG_(INFO) << "CommitTask Start"; + return E_OK; +} + +string TaskManager::GetKey(int32_t userId, const string &bundleName) +{ + return to_string(userId) + bundleName; +} +} // namespace CloudSync +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/BUILD.gn b/cloud_file/test/unittests/cloudsync_sa/sync_rule/BUILD.gn new file mode 100644 index 0000000..272fcff --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/BUILD.gn @@ -0,0 +1,593 @@ +# Copyright (C) 2023-2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("battery_status_listener_test") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = true + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp", + "battery_status_listener_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${utils_path}/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004310", + "LOG_TAG=\"CLOUD_SYNC_TEST\"", + ] + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +ohos_unittest("net_conn_callback_observer_test") { + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/services/cloudsyncservice/src/sync_rule/net_conn_callback_observer.cpp", + "net_conn_callback_observer_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${utils_path}/log/include", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("network_status_test") { + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/data_sync_manager.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/net_conn_callback_observer.cpp", + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp", + "${cloud_file_path}/test/mock/net_conn_client_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/network_set_manager_mock.cpp", + "network_status_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner", + "${cloud_file_path}/test/mock/", + "${innerkits_native_path}/cloud_file_kit_inner", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${utils_path}/log/include", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ "private=public" ] + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +ohos_unittest("cloud_status_test") { + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp", + "${cloud_file_path}/test/mock/cloud_file_kit_mock.cpp", + "${cloud_file_path}/utils/log/src/dfs_error.cpp", + "cloud_status_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner", + "${services_path}/cloudsyncservice/include", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/test/mock", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("battery_status_test") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = true + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp", + "${cloud_file_path}/test/mock/battersrvclient_mock.cpp", + "battery_status_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner", + "${utils_path}/log/include", + "${cloud_file_path}/test/mock", + ] + + deps = [ + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "power_manager:powermgr_client", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004310", + "LOG_TAG=\"CLOUD_SYNC_TEST\"", + ] + + if (cloudsync_service_power) { + external_deps += [ "battery_manager:batterysrv_client" ] + + defines += [ "SUPPORT_POWER" ] + } + + use_exceptions = true +} + +ohos_unittest("network_set_manager_test") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = true + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/datashare_helper.cpp", + "network_set_manager_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock", + "${innerkits_native_path}/cloud_file_kit_inner", + "${innerkits_native_path}/cloudsync_kit_inner", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${utils_path}/log/include", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "access_token:libtokenid_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "ipc:ipc_single", + "safwk:system_ability_fwk", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("system_load_test") { + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/system_load.cpp", + "system_load_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${utils_path}/log/include", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", + "cloud_file:cloudsync_kit_inner", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "resource_schedule_service:ressched_client", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ "private=public" ] + + use_exceptions = true +} + +ohos_unittest("screen_status_listener_test") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = true + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp", + "screen_status_listener_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${utils_path}/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:want", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "googletest:gmock", + "googletest:gtest", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004310", + "LOG_TAG=\"CLOUD_SYNC_TEST\"", + ] + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +ohos_unittest("user_status_listener_test") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = true + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/services/cloudsyncservice/src/sync_rule/user_status_listener.cpp", + "user_status_listener_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${services_path}/cloudsyncservice/include/transport/softbus", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${utils_path}/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:want", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gtest", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004310", + "LOG_TAG=\"CLOUD_SYNC_TEST\"", + ] + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +ohos_unittest("package_status_listener_test") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = true + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + module_out_path = "cloud_file/cloud_file" + sources = [ + "${cloud_file_path}/services/cloudsyncservice/src/sync_rule/package_status_listener.cpp", + "package_status_listener_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${innerkits_native_path}/cloudsync_kit_inner", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${services_path}/cloudsyncservice/include/sync_rule", + "${utils_path}/log/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${services_path}/cloudsyncservice:cloudsync_sa_static", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:want", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "googletest:gmock", + "googletest:gtest", + "hilog:libhilog", + "hisysevent:libhisysevent", + "init:libbegetutil", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004310", + "LOG_TAG=\"CLOUD_SYNC_TEST\"", + ] + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +group("cloudsync_sa_sync_rule_test") { + testonly = true + deps = [ + ":battery_status_listener_test", + ":battery_status_test", + ":cloud_status_test", + ":network_set_manager_test", + ":network_status_test", + ":package_status_listener_test", + ":screen_status_listener_test", + ":system_load_test", + ":user_status_listener_test", + ] +} diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/battery_status_listener_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/battery_status_listener_test.cpp new file mode 100644 index 0000000..b22a67e --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/battery_status_listener_test.cpp @@ -0,0 +1,226 @@ +/* + * 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 +#include + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "battery_status.h" +#include "battery_status_listener.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace CloudFile; +using Want = OHOS::AAFwk::Want; + +class BatteryStatusListenerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void BatteryStatusListenerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void BatteryStatusListenerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void BatteryStatusListenerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void BatteryStatusListenerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: StopTest + * @tc.desc: Verify the Stop function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusListenerTest, StopTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopTest Start"; + try { + auto dataSyncManager = std::make_shared(); + auto batteryStatusListener = std::make_shared(dataSyncManager); + batteryStatusListener->Start(); + batteryStatusListener->Stop(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StopTest FAILED"; + } + GTEST_LOG_(INFO) << "StopTest End"; +} + +/** + * @tc.name: OnStatusAbnormalTest + * @tc.desc: Verify the OnStatusAbnormal function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusListenerTest, OnStatusAbnormalTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnStatusAbnormalTest Start"; + try { + auto dataSyncManager = std::make_shared(); + auto batteryStatusListener = std::make_shared(dataSyncManager); + batteryStatusListener->OnStatusAbnormal(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnStatusAbnormalTest FAILED"; + } + GTEST_LOG_(INFO) << "OnStatusAbnormalTest End"; +} + +/** + * @tc.name: OnReceiveEventTest + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest001 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_OKAY); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto batteryStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + batteryStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnReceiveEventTest001 FAILED"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest001 End"; +} + +/** + * @tc.name: OnReceiveEventTest + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest002 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto batteryStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + batteryStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnReceiveEventTest002 FAILED"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest002 End"; +} + +/** + * @tc.name: OnReceiveEventTest + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest003 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto batteryStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + batteryStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnReceiveEventTest003 FAILED"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest003 End"; +} + +/** + * @tc.name: OnReceiveEventTest + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest004 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto batteryStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + batteryStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnReceiveEventTest004 FAILED"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest004 End"; +} + +/** + * @tc.name: OnPowerConnectedTest001 + * @tc.desc: Verify the OnPowerConnected function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(BatteryStatusListenerTest, OnPowerConnectedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnPowerConnectedTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto batteryStatusListener = std::make_shared(dataSyncManager); + batteryStatusListener->OnPowerConnected(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnPowerConnectedTest001 failed"; + } + GTEST_LOG_(INFO) << "OnPowerConnectedTest001 end"; +} +} // namespace OHOS::FileManagement::CloudSync::Test diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/battery_status_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/battery_status_test.cpp new file mode 100644 index 0000000..0c8526d --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/battery_status_test.cpp @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2024 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 +#include +#include "battersrvclient_mock.h" +#include "battery_status.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +constexpr int32_t STOP_CAPACITY_LIMIT = 10; +constexpr int32_t PAUSE_CAPACITY_LIMIT = 15; + +class BatteryStatusMock final : public BatteryStatus { +public: + BatteryStatusMock() : BatteryStatus() {} + MOCK_METHOD0(GetCapacity, int32_t()); +}; + +class BatteryStatusTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + shared_ptr batteryStatus_ = nullptr; + static inline shared_ptr dfsBatterySrvClient_ = nullptr; +}; + +void BatteryStatusTest::SetUpTestCase(void) +{ + dfsBatterySrvClient_ = make_shared(); + BatterySrvClientMock::dfsBatterySrvClient = dfsBatterySrvClient_; + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void BatteryStatusTest::TearDownTestCase(void) +{ + BatterySrvClientMock::dfsBatterySrvClient = nullptr; + dfsBatterySrvClient_ = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void BatteryStatusTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + batteryStatus_ = make_shared(); +} + +void BatteryStatusTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; + batteryStatus_ = nullptr; +} + +/** + * @tc.name: IsAllowUploadTest001 + * @tc.desc: Verify the IsAllowUpload function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsAllowUploadTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsAllowUploadTest001 Start"; + try { + batteryStatus_->SetChargingStatus(true); + bool ret = batteryStatus_->IsAllowUpload(true); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsAllowUploadTest001 FAILED"; + } + GTEST_LOG_(INFO) << "IsAllowUploadTest001 End"; +} + +/** + * @tc.name: IsAllowUploadTest002 + * @tc.desc: Verify the IsAllowUpload function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsAllowUploadTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsAllowUploadTest002 Start"; + try { + batteryStatus_->SetChargingStatus(false); + bool ret = batteryStatus_->IsAllowUpload(true); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsAllowUploadTest002 FAILED"; + } + GTEST_LOG_(INFO) << "IsAllowUploadTest002 End"; +} + +/** + * @tc.name: IsAllowUploadTest003 + * @tc.desc: Verify the IsAllowUpload function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsAllowUploadTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsAllowUploadTest003 Start"; + EXPECT_CALL(*dfsBatterySrvClient_, GetCapacity()).WillOnce(Return(STOP_CAPACITY_LIMIT - 1)); + batteryStatus_->SetChargingStatus(false); + bool ret = batteryStatus_->IsAllowUpload(false); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "IsAllowUploadTest003 End"; +} + +/** + * @tc.name: IsAllowUploadTest004 + * @tc.desc: Verify the IsAllowUpload function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsAllowUploadTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsAllowUploadTest004 Start"; + EXPECT_CALL(*dfsBatterySrvClient_, GetCapacity()).WillOnce(Return(PAUSE_CAPACITY_LIMIT - 1)); + batteryStatus_->SetChargingStatus(false); + bool ret = batteryStatus_->IsAllowUpload(false); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "IsAllowUploadTest004 End"; +} + +/** + * @tc.name: IsAllowUploadTest005 + * @tc.desc: Verify the IsAllowUpload function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsAllowUploadTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsAllowUploadTest005 Start"; + EXPECT_CALL(*dfsBatterySrvClient_, GetCapacity()).WillOnce(Return(PAUSE_CAPACITY_LIMIT - 1)); + batteryStatus_->SetChargingStatus(false); + bool ret = batteryStatus_->IsAllowUpload(true); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "IsAllowUploadTest005 End"; +} + +/** + * @tc.name: IsAllowUploadTest006 + * @tc.desc: Verify the IsAllowUpload function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsAllowUploadTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsAllowUploadTest006 Start"; + EXPECT_CALL(*dfsBatterySrvClient_, GetCapacity()).WillOnce(Return(PAUSE_CAPACITY_LIMIT + 1)); + batteryStatus_->SetChargingStatus(false); + bool ret = batteryStatus_->IsAllowUpload(true); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "IsAllowUploadTest006 End"; +} + +/** + * @tc.name: IsBatteryCapcityOkayTest001 + * @tc.desc: Verify the IsBatteryCapcityOkay function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsBatteryCapcityOkayTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest001 Start"; + try { + batteryStatus_->SetChargingStatus(true); + bool ret = batteryStatus_->IsBatteryCapcityOkay(); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest001 FAILED"; + } + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest001 End"; +} + +/** + * @tc.name: IsBatteryCapcityOkayTest002 + * @tc.desc: Verify the IsBatteryCapcityOkay function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsBatteryCapcityOkayTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest Start"; + try { + EXPECT_CALL(*dfsBatterySrvClient_, GetCapacity()).WillOnce(Return(STOP_CAPACITY_LIMIT + 1)); + batteryStatus_->SetChargingStatus(false); + bool ret = batteryStatus_->IsBatteryCapcityOkay(); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest002 FAILED"; + } + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest002 End"; +} + +/** + * @tc.name: IsBatteryCapcityOkayTest003 + * @tc.desc: Verify the IsBatteryCapcityOkay function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(BatteryStatusTest, IsBatteryCapcityOkayTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest003 Start"; + try { + EXPECT_CALL(*dfsBatterySrvClient_, GetCapacity()).WillOnce(Return(STOP_CAPACITY_LIMIT - 1)); + batteryStatus_->SetChargingStatus(false); + bool ret = batteryStatus_->IsBatteryCapcityOkay(); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest003 FAILED"; + } + GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest003 End"; +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/cloud_status_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/cloud_status_test.cpp new file mode 100644 index 0000000..9b9e183 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/cloud_status_test.cpp @@ -0,0 +1,214 @@ +/* + * 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 +#include + +#include "cloud_status.h" +#include "dfs_error.h" +#include "cloud_file_kit_mock.cpp" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CloudStatusTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr ability = make_shared(); +}; +void CloudStatusTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudStatusTest::TearDownTestCase(void) +{ + ability = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudStatusTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudStatusTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetCurrentCloudInfo001 + * @tc.desc: Verify the CloudStatus::GetCurrentCloudInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, GetCurrentCloudInfo001, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "ohos.com.test"; + const int32_t userId = 1; + auto ret = cloudStatus.GetCurrentCloudInfo(bundleName, userId); + EXPECT_EQ(ret, E_NULLPTR); +} + +/** + * @tc.name: GetCurrentCloudInfo002 + * @tc.desc: Verify the CloudStatus::GetCurrentCloudInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, GetCurrentCloudInfo002, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "ohos.com.test"; + const int32_t userId = 1; + CloudFile::CloudFileKit::instance_ = ability.get(); + EXPECT_CALL(*ability, GetCloudUserInfo(_, _)).WillOnce(Return(E_RDB)).WillRepeatedly(Return(E_OK)); + auto ret = cloudStatus.GetCurrentCloudInfo(bundleName, userId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: GetCurrentCloudInfo003 + * @tc.desc: Verify the CloudStatus::GetCurrentCloudInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, GetCurrentCloudInfo003, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "ohos.com.test"; + const int32_t userId = 1; + CloudFile::CloudFileKit::instance_ = ability.get(); + EXPECT_CALL(*ability, GetAppSwitchStatus(_, _, _)).WillOnce(Return(E_RDB)).WillRepeatedly(Return(E_OK)); + auto ret = cloudStatus.GetCurrentCloudInfo(bundleName, userId); + EXPECT_EQ(ret, E_RDB); +} + +/** + * @tc.name: IsCloudStatusOkay001 + * @tc.desc: Verify the CloudStatus::IsCloudStatusOkay function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, IsCloudStatusOkay001, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "ohos.com.demo"; + const int32_t userId = -1; + auto ret = cloudStatus.IsCloudStatusOkay(bundleName, userId); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: IsCloudStatusOkay002 + * @tc.desc: Verify the CloudStatus::IsCloudStatusOkay function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, IsCloudStatusOkay002, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "ohos.com.demo1"; + const int32_t userId = 1; + auto ret = cloudStatus.IsCloudStatusOkay(bundleName, userId); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: ChangeAppSwitch001 + * @tc.desc: Verify the CloudStatus::ChangeAppSwitch function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, ChangeAppSwitch001, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "ohos.com.demo2"; + const int32_t userId = -1; + bool appSwitchStatus = true; + auto ret = cloudStatus.ChangeAppSwitch(bundleName, userId, appSwitchStatus); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: ChangeAppSwitch002 + * @tc.desc: Verify the CloudStatus::ChangeAppSwitch function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, ChangeAppSwitch002, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "ohos.com.demo3"; + const int32_t userId = 1; + bool appSwitchStatus = true; + auto ret = cloudStatus.ChangeAppSwitch(bundleName, userId, appSwitchStatus); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: ChangeAppSwitch003 + * @tc.desc: Verify the CloudStatus::ChangeAppSwitch function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, ChangeAppSwitch003, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "ohos.com.demo3"; + const int32_t userId = 1; + bool appSwitchStatus = true; + cloudStatus.appSwitches_.clear(); + auto ret = cloudStatus.ChangeAppSwitch(bundleName, userId, appSwitchStatus); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: IsAccountIdChanged001 + * @tc.desc: Verify the CloudStatus::IsAccountIdChanged function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, IsAccountIdChanged001, TestSize.Level1) +{ + CloudStatus cloudStatus; + std::string accountId = "IsAccountIdChanged"; + cloudStatus.userInfo_.accountId = "CloudStatusTest"; + auto ret = cloudStatus.IsAccountIdChanged(accountId); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: IsAccountIdChanged002 + * @tc.desc: Verify the CloudStatus::IsAccountIdChanged function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, IsAccountIdChanged002, TestSize.Level1) +{ + CloudStatus cloudStatus; + std::string accountId = "IsAccountIdChanged"; + cloudStatus.userInfo_.accountId = ""; + auto ret = cloudStatus.IsAccountIdChanged(accountId); + EXPECT_EQ(ret, false); +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/net_conn_callback_observer_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/net_conn_callback_observer_test.cpp new file mode 100644 index 0000000..66f3c68 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/net_conn_callback_observer_test.cpp @@ -0,0 +1,152 @@ +/* + * 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 +#include + +#include "dfs_error.h" +#include "net_conn_callback_observer.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class NetConnCallbackObserverTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr oberverPtr_; +}; +void NetConnCallbackObserverTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void NetConnCallbackObserverTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void NetConnCallbackObserverTest::SetUp(void) +{ + if (oberverPtr_ == nullptr) { + auto dataSyncManager = std::make_shared(); + oberverPtr_ = make_shared(dataSyncManager); + ASSERT_TRUE(oberverPtr_ != nullptr) << "CallbackObserver failed"; + } + GTEST_LOG_(INFO) << "SetUp"; +} + +void NetConnCallbackObserverTest::TearDown(void) +{ + oberverPtr_ = nullptr; + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: NetAvailableTest + * @tc.desc: Verify the NetAvailable function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetConnCallbackObserverTest, NetAvailable, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NetAvailable Start"; + sptr netHandle = sptr(new NetManagerStandard::NetHandle()); + int res = oberverPtr_->NetAvailable(netHandle); + EXPECT_EQ(res, E_OK); + GTEST_LOG_(INFO) << "NetAvailable End"; +} + +/** + * @tc.name: NetCapabilitiesChangeTest + * @tc.desc: Verify the NetCapabilitiesChange function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetConnCallbackObserverTest, NetCapabilitiesChange, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NetCapabilitiesChange Start"; + sptr netHandle = sptr(new NetManagerStandard::NetHandle()); + sptr netAllCap = sptr(new NetManagerStandard::NetAllCapabilities()); + int res = oberverPtr_->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(res, E_OK); + GTEST_LOG_(INFO) << "NetCapabilitiesChange End"; +} + +/** + * @tc.name: NetConnectionPropertiesChangeTest + * @tc.desc: Verify the NetConnectionPropertiesChange function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetConnCallbackObserverTest, NetConnectionPropertiesChange, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NetConnectionPropertiesChange Start"; + sptr netHandle = sptr(new NetManagerStandard::NetHandle()); + sptr info = sptr(new NetManagerStandard::NetLinkInfo()); + int res = oberverPtr_->NetConnectionPropertiesChange(netHandle, info); + EXPECT_EQ(res, E_OK); + GTEST_LOG_(INFO) << "NetConnectionPropertiesChange End"; +} + +/** + * @tc.name: NetLostTest + * @tc.desc: Verify the NetLost function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetConnCallbackObserverTest, NetLost, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NetLost Start"; + sptr netHandle = sptr(new NetManagerStandard::NetHandle()); + int res = oberverPtr_->NetLost(netHandle); + EXPECT_EQ(res, E_OK); + GTEST_LOG_(INFO) << "NetLost End"; +} + +/** + * @tc.name: NetUnavailableTest + * @tc.desc: Verify the NetUnavailable function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetConnCallbackObserverTest, NetUnavailable, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NetUnavailable Start"; + int res = oberverPtr_->NetUnavailable(); + EXPECT_EQ(res, E_OK); + GTEST_LOG_(INFO) << "NetUnavailable End"; +} + +/** + * @tc.name: NetBlockStatusChangeTest + * @tc.desc: Verify the NetBlockStatusChange function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetConnCallbackObserverTest, NetBlockStatusChange, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NetBlockStatusChange Start"; + sptr netHandle = sptr(new NetManagerStandard::NetHandle()); + bool blocked = true; + int res = oberverPtr_->NetBlockStatusChange(netHandle, blocked); + EXPECT_EQ(res, E_OK); + GTEST_LOG_(INFO) << "NetBlockStatusChange End"; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/network_set_manager_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/network_set_manager_test.cpp new file mode 100644 index 0000000..b2f61a9 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/network_set_manager_test.cpp @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2024 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 +#include +#include +#include + +#include "network_set_manager.h" +#include "data_ability_observer_stub.h" +#include "accesstoken_kit.h" +#include "cloud_file_kit.h" +#include "datashare_errno.h" +#include "datashare_result_set.h" +#include "dfs_error.h" +#include "ipc_skeleton.h" +#include "parameters.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace CloudFile; + +class NetworkSetManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr networkSetManager_ = nullptr; +}; + +void NetworkSetManagerTest::SetUpTestCase(void) +{ + networkSetManager_ = make_shared(); + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void NetworkSetManagerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void NetworkSetManagerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void NetworkSetManagerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: QueryCellularConnectTest001 + * @tc.desc: Verify the QueryCellularConnect function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, QueryCellularConnectTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryCellularConnectTest Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + + int32_t ret = networkSetManager_->QueryCellularConnect(userId, bundleName); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "QueryCellularConnectTest FAILED"; + } + GTEST_LOG_(INFO) << "QueryCellularConnectTest End"; +} + +/** + * @tc.name: QueryNetConnectTest001 + * @tc.desc: Verify the QueryNetConnect function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, QueryNetConnectTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryNetConnectTest Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + + int32_t ret = networkSetManager_->QueryNetConnect(userId, bundleName); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "QueryNetConnectTest FAILED"; + } + GTEST_LOG_(INFO) << "QueryNetConnectTest End"; +} + +/** + * @tc.name: GetNetConnectTest001 + * @tc.desc: Verify the GetNetConnect function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, GetNetConnectTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNetConnectTest Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + + networkSetManager_->GetNetConnect(bundleName, userId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetNetConnectTest FAILED"; + } + GTEST_LOG_(INFO) << "GetNetConnectTest End"; +} + +/** + * @tc.name: UnregisterObserverTest001 + * @tc.desc: Verify the UnregisterObserver function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, UnregisterObserverTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterObserverTest Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + int32_t type = NetworkSetManager::CELLULARCONNECT; + + networkSetManager_->UnregisterObserver(bundleName, userId, type); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnregisterObserverTest FAILED"; + } + GTEST_LOG_(INFO) << "UnregisterObserverTest End"; +} + +/** + * @tc.name: UnregisterObserverTest002 + * @tc.desc: Verify the UnregisterObserver function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, UnregisterObserverTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterObserverTest Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + int32_t type = NetworkSetManager::NETCONNECT; + + networkSetManager_->UnregisterObserver(bundleName, userId, type); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UnregisterObserverTest FAILED"; + } + GTEST_LOG_(INFO) << "UnregisterObserverTest End"; +} + +/** + * @tc.name: RegisterObserverTest001 + * @tc.desc: Verify the RegisterObserver function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, RegisterObserverTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterObserverTest Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + int32_t type = NetworkSetManager::CELLULARCONNECT; + + networkSetManager_->RegisterObserver(bundleName, userId, type); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterObserverTest FAILED"; + } + GTEST_LOG_(INFO) << "RegisterObserverTest End"; +} + +/** + * @tc.name: GetCellularConnectTest + * @tc.desc: Verify the GetCellularConnect function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, GetCellularConnectTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCellularConnectTest Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + + (networkSetManager_->cellularNetMap_).Insert(std::to_string(userId) + "/" + bundleName, true); + networkSetManager_->dataSyncManager_ = std::make_shared(); + networkSetManager_->GetCellularConnect(bundleName, userId); + EXPECT_NE(networkSetManager_->netStatus_, NetworkSetManager::NetConnStatus::WIFI_CONNECT); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetCellularConnectTest FAILED"; + } + GTEST_LOG_(INFO) << "GetCellularConnectTest End"; +} + +/** + * @tc.name: OnChangeTest001 + * @tc.desc: Verify the OnChange function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, OnChangeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnChangeTest Start"; + try { + std::string bundleName; + int32_t userId = 0; + int32_t type = 0; + MobileNetworkObserver mobile(bundleName, userId, type); + mobile.observerCallback_ = [] () {}; + mobile.type_ = 0; + + mobile.OnChange(); + EXPECT_NE(mobile.observerCallback_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnChange FAILED"; + } + GTEST_LOG_(INFO) << "OnChange End"; +} + +/** + * @tc.name: OnChangeTest002 + * @tc.desc: Verify the OnChange function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkSetManagerTest, OnChangeTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnChangeTest Start"; + try { + std::string bundleName; + int32_t userId = 0; + int32_t type = -1; + MobileNetworkObserver mobile(bundleName, userId, type); + + mobile.OnChange(); + EXPECT_EQ(mobile.observerCallback_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnChange FAILED"; + } + GTEST_LOG_(INFO) << "OnChange End"; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/network_status_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/network_status_test.cpp new file mode 100644 index 0000000..67f9c88 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/network_status_test.cpp @@ -0,0 +1,443 @@ +/* + * 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 +#include +#include +#include + +#include "dfs_error.h" +#include "net_conn_client.h" +#include "parameter.h" +#include "net_conn_callback_observer.h" +#include "network_status.h" +#include "utils_log.h" +#include "net_conn_client_mock.h" +#include "net_handle.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace CloudFile; + +class NetworkStatusTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr dfsNetConnClient_ = nullptr; +}; +void NetworkStatusTest::SetUpTestCase(void) +{ + dfsNetConnClient_ = make_shared(); + NetConnClientMock::dfsNetConnClient = dfsNetConnClient_; + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void NetworkStatusTest::TearDownTestCase(void) +{ + NetConnClientMock::dfsNetConnClient = nullptr; + dfsNetConnClient_ = nullptr; + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void NetworkStatusTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void NetworkStatusTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: RegisterNetConnCallbackTest + * @tc.desc: Verify the RegisterNetConnCallback function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, RegisterNetConnCallbackTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterNetConnCallbackTest Start"; + try { + auto dataSyncManager = std::make_shared(); + int32_t ret = NetworkStatus::RegisterNetConnCallback(dataSyncManager); + EXPECT_EQ(ret, E_GET_NETWORK_MANAGER_FAILED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RegisterNetConnCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "RegisterNetConnCallbackTest End"; +} + +/** + * @tc.name: GetDefaultNetTest001 + * @tc.desc: Verify the GetDefaultNet function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, GetDefaultNetTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetDefaultNetTest001 Start"; + EXPECT_CALL(*dfsNetConnClient_, GetDefaultNet(_)).WillOnce(Return(E_GET_NETWORK_MANAGER_FAILED)); + NetworkStatus netStatus; + int32_t ret = netStatus.GetDefaultNet(); + EXPECT_EQ(ret, E_GET_NETWORK_MANAGER_FAILED); + GTEST_LOG_(INFO) << "GetDefaultNetTest001 End"; +} + +/** + * @tc.name: GetDefaultNetTest002 + * @tc.desc: Verify the GetDefaultNet function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, GetDefaultNetTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetDefaultNetTest002 Start"; + EXPECT_CALL(*dfsNetConnClient_, GetDefaultNet(_)).WillOnce(Return(NetManagerStandard::NETMANAGER_SUCCESS)); + NetworkStatus netStatus; + int32_t ret = netStatus.GetDefaultNet(); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "GetDefaultNetTest002 End"; +} + +/** + * @tc.name: SetNetConnStatusTest001 + * @tc.desc: Verify the SetNetConnStatus function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, SetNetConnStatusTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 Start"; + try { + NetManagerStandard::NetAllCapabilities netAllCap; + NetworkStatus::SetNetConnStatus(netAllCap); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetNetConnStatusTest001 FAILED"; + } + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 End"; +} + +/** + * @tc.name: SetNetConnStatusTest002 + * @tc.desc: Verify the SetNetConnStatus function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, SetNetConnStatusTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 Start"; + try { + NetManagerStandard::NetAllCapabilities netAllCap; + netAllCap.netCaps_.insert(NetManagerStandard::NetCap::NET_CAPABILITY_INTERNET); + NetworkStatus::SetNetConnStatus(netAllCap); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetNetConnStatusTest001 FAILED"; + } + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 End"; +} + +/** + * @tc.name: SetNetConnStatusTest003 + * @tc.desc: Verify the SetNetConnStatus function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, SetNetConnStatusTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 Start"; + try { + NetManagerStandard::NetAllCapabilities netAllCap; + netAllCap.netCaps_.insert(NetManagerStandard::NetCap::NET_CAPABILITY_INTERNET); + netAllCap.bearerTypes_.insert(NetManagerStandard::BEARER_ETHERNET); + NetworkStatus::SetNetConnStatus(netAllCap); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetNetConnStatusTest001 FAILED"; + } + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 End"; +} + +/** + * @tc.name: SetNetConnStatusTest004 + * @tc.desc: Verify the SetNetConnStatus function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, SetNetConnStatusTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 Start"; + try { + NetManagerStandard::NetAllCapabilities netAllCap; + netAllCap.netCaps_.insert(NetManagerStandard::NetCap::NET_CAPABILITY_INTERNET); + netAllCap.bearerTypes_.insert(NetManagerStandard::BEARER_WIFI); + NetworkStatus::SetNetConnStatus(netAllCap); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetNetConnStatusTest001 FAILED"; + } + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 End"; +} + +/** + * @tc.name: SetNetConnStatusTest005 + * @tc.desc: Verify the SetNetConnStatus function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, SetNetConnStatusTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 Start"; + try { + NetManagerStandard::NetAllCapabilities netAllCap; + netAllCap.netCaps_.insert(NetManagerStandard::NetCap::NET_CAPABILITY_INTERNET); + netAllCap.bearerTypes_.insert(NetManagerStandard::BEARER_CELLULAR); + NetworkStatus::SetNetConnStatus(netAllCap); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetNetConnStatusTest001 FAILED"; + } + GTEST_LOG_(INFO) << "SetNetConnStatusTest001 End"; +} + +/** + * @tc.name: GetAndRegisterNetworkTest + * @tc.desc: Verify the GetAndRegisterNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, GetAndRegisterNetworkTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAndRegisterNetworkTest Start"; + try { + EXPECT_CALL(*dfsNetConnClient_, GetDefaultNet(_)).WillOnce(Return(E_OK)); + auto dataSyncManager = std::make_shared(); + int32_t ret = NetworkStatus::GetAndRegisterNetwork(dataSyncManager); + EXPECT_EQ(ret, E_GET_NETWORK_MANAGER_FAILED); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetAndRegisterNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "GetAndRegisterNetworkTest End"; +} + +/** + * @tc.name: InitNetworkTest + * @tc.desc: Verify the InitNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, InitNetworkTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitNetworkTest Start"; + try { + EXPECT_CALL(*dfsNetConnClient_, GetDefaultNet(_)).WillOnce(Return(E_OK)).WillRepeatedly(Return(E_OK)); + auto dataSyncManager = std::make_shared(); + NetworkStatus::InitNetwork(dataSyncManager); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " InitNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "InitNetworkTest End"; +} + +/** + * @tc.name: CheckMobileNetworkTest001 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest Start"; + try { + NetworkStatus networkStatus; + string bundleName = ""; + int32_t userId = 100; + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest End"; +} + +/** + * @tc.name: CheckMobileNetworkTest002 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.photos"; + int32_t userId = 1; + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest End"; +} + +/** + * @tc.name: CheckMobileNetworkTest003 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + networkStatus.SetNetConnStatus(NetworkStatus::WIFI_CONNECT); + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest End"; +} + +/** + * @tc.name: CheckMobileNetworkTest004 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + networkStatus.SetNetConnStatus(NetworkStatus::NO_NETWORK); + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest End"; +} + +/** + * @tc.name: CheckNetworkTest001 + * @tc.desc: Verify the CheckNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckNetworkTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckNetworkTest Start"; + try { + NetworkStatus networkStatus; + string bundleName = ""; + int32_t userId = 100; + bool ret = networkStatus.CheckNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "CheckNetworkTest End"; +} + +/** + * @tc.name: CheckNetworkTest002 + * @tc.desc: Verify the CheckNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckNetworkTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckNetworkTest Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.photos"; + int32_t userId = 1; + bool ret = networkStatus.CheckNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "CheckNetworkTest End"; +} + +/** + * @tc.name: CheckNetworkTest003 + * @tc.desc: Verify the CheckNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckNetworkTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckNetworkTest Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + bool ret = networkStatus.CheckNetwork(bundleName, userId); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckNetworkTest FAILED"; + } + GTEST_LOG_(INFO) << "CheckNetworkTest End"; +} + +/** + * @tc.name: OnNetworkAvailTest001 + * @tc.desc: Verify the OnNetworkAvail function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, OnNetworkAvailTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnNetworkAvailTest Start"; + try { + NetworkStatus networkStatus; + networkStatus.SetNetConnStatus(NetworkStatus::WIFI_CONNECT); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnNetworkAvailTest FAILED"; + } + GTEST_LOG_(INFO) << "OnNetworkAvailTest End"; +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/package_status_listener_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/package_status_listener_test.cpp new file mode 100644 index 0000000..843f7b7 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/package_status_listener_test.cpp @@ -0,0 +1,384 @@ +/* + * Copyright (c) 2025 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 +#include + +#include "cloud_status.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "package_status_listener.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace CloudFile; +using Want = OHOS::AAFwk::Want; + +constexpr int32_t USER_ID = 101; + +class PackageStatusListenerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void PackageStatusListenerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void PackageStatusListenerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void PackageStatusListenerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void PackageStatusListenerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: StopTest + * @tc.desc: Verify the Stop function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(PackageStatusListenerTest, StopTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopTest Start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + packageStatusListener->Start(); + packageStatusListener->Stop(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " StopTest FAILED"; + } + GTEST_LOG_(INFO) << "StopTest End"; +} + +/** + * @tc.name: OnReceiveEventTest + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(PackageStatusListenerTest, OnReceiveEventTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest001 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + packageStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " OnReceiveEventTest001 FAILED"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest001 End"; +} + +/** + * @tc.name: RemovedCleanTest001 + * @tc.desc: Verify the RemovedClean function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, RemovedCleanTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RemovedCleanTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = "Test"; + const int32_t userId = USER_ID; + packageStatusListener->RemovedClean(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RemovedCleanTest001 failed"; + } + GTEST_LOG_(INFO) << "RemovedCleanTest001 end"; +} + +/** + * @tc.name: RemovedCleanTest002 + * @tc.desc: Verify the RemovedClean function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, RemovedCleanTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RemovedCleanTest002 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = ""; + const int32_t userId = USER_ID; + packageStatusListener->RemovedClean(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RemovedCleanTest002 failed"; + } + GTEST_LOG_(INFO) << "RemovedCleanTest002 end"; +} + +/** + * @tc.name: RemovedCleanTest003 + * @tc.desc: Verify the RemovedClean function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, RemovedCleanTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RemovedCleanTest003 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = "Test"; + const int32_t userId = -1; + packageStatusListener->RemovedClean(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RemovedCleanTest003 failed"; + } + GTEST_LOG_(INFO) << "RemovedCleanTest003 end"; +} + +/** + * @tc.name: RemovedCleanTest004 + * @tc.desc: Verify the RemovedClean function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, RemovedCleanTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RemovedCleanTest004 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = ""; + const int32_t userId = -1; + packageStatusListener->RemovedClean(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RemovedCleanTest004 failed"; + } + GTEST_LOG_(INFO) << "RemovedCleanTest004 end"; +} + +/** + * @tc.name: RemovedCleanTest005 + * @tc.desc: Verify the RemovedClean function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, RemovedCleanTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RemovedCleanTest005 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = "Test"; + const int32_t userId = 0; + packageStatusListener->RemovedClean(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RemovedCleanTest005 failed"; + } + GTEST_LOG_(INFO) << "RemovedCleanTest005 end"; +} + +/** + * @tc.name: RemovedCleanTest006 + * @tc.desc: Verify the RemovedClean function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, RemovedCleanTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RemovedCleanTest006 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = ""; + const int32_t userId = 0; + packageStatusListener->RemovedClean(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " RemovedCleanTest006 failed"; + } + GTEST_LOG_(INFO) << "RemovedCleanTest006 end"; +} + +/** + * @tc.name: IsCloudSyncOnTest001 + * @tc.desc: Verify the IsCloudSyncOn function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, IsCloudSyncOnTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsCloudSyncOnTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = "Test"; + const int32_t userId = USER_ID; + packageStatusListener->IsCloudSyncOn(userId, bundleName); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsCloudSyncOnTest001 failed"; + } + GTEST_LOG_(INFO) << "IsCloudSyncOnTest001 end"; +} + +/** + * @tc.name: IsCloudSyncOnTest002 + * @tc.desc: Verify the IsCloudSyncOn function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, IsCloudSyncOnTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsCloudSyncOnTest002 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = ""; + const int32_t userId = USER_ID; + packageStatusListener->IsCloudSyncOn(userId, bundleName); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsCloudSyncOnTest002 failed"; + } + GTEST_LOG_(INFO) << "IsCloudSyncOnTest002 end"; +} + +/** + * @tc.name: IsCloudSyncOnTest003 + * @tc.desc: Verify the IsCloudSyncOn function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, IsCloudSyncOnTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsCloudSyncOnTest003 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = "Test"; + const int32_t userId = -1; + packageStatusListener->IsCloudSyncOn(userId, bundleName); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsCloudSyncOnTest003 failed"; + } + GTEST_LOG_(INFO) << "IsCloudSyncOnTest003 end"; +} + +/** + * @tc.name: IsCloudSyncOnTest004 + * @tc.desc: Verify the IsCloudSyncOn function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, IsCloudSyncOnTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsCloudSyncOnTest004 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = ""; + const int32_t userId = -1; + packageStatusListener->IsCloudSyncOn(userId, bundleName); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsCloudSyncOnTest004 failed"; + } + GTEST_LOG_(INFO) << "IsCloudSyncOnTest004 end"; +} + +/** + * @tc.name: IsCloudSyncOnTest005 + * @tc.desc: Verify the IsCloudSyncOn function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, IsCloudSyncOnTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsCloudSyncOnTest005 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = "Test"; + const int32_t userId = 0; + packageStatusListener->IsCloudSyncOn(userId, bundleName); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsCloudSyncOnTest005 failed"; + } + GTEST_LOG_(INFO) << "IsCloudSyncOnTest005 end"; +} + +/** + * @tc.name: IsCloudSyncOnTest006 + * @tc.desc: Verify the IsCloudSyncOn function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(PackageStatusListenerTest, IsCloudSyncOnTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsCloudSyncOnTest006 start"; + try { + auto dataSyncManager = std::make_shared(); + auto packageStatusListener = std::make_shared(dataSyncManager); + const std::string bundleName = ""; + const int32_t userId = 0; + packageStatusListener->IsCloudSyncOn(userId, bundleName); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsCloudSyncOnTest006 failed"; + } + GTEST_LOG_(INFO) << "IsCloudSyncOnTest006 end"; +} +} // namespace OHOS::FileManagement::CloudSync::Test diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/screen_status_listener_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/screen_status_listener_test.cpp new file mode 100644 index 0000000..1d39d28 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/screen_status_listener_test.cpp @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "screen_status_listener.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace CloudFile; +using Want = OHOS::AAFwk::Want; + +class ScreenStatusListenerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void ScreenStatusListenerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void ScreenStatusListenerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void ScreenStatusListenerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void ScreenStatusListenerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: StopTest001 + * @tc.desc: Verify the Stop function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(ScreenStatusListenerTest, StopTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto screenStatusListener = std::make_shared(dataSyncManager); + screenStatusListener->Start(); + EXPECT_NE(screenStatusListener->commonEventSubscriber_, nullptr); + screenStatusListener->Stop(); + EXPECT_EQ(screenStatusListener->commonEventSubscriber_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StopTest001 failed"; + } + GTEST_LOG_(INFO) << "StopTest001 end"; +} + +/** + * @tc.name: ScreenOffTest001 + * @tc.desc: Verify the ScreenOff function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(ScreenStatusListenerTest, ScreenOffTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ScreenOffTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto screenStatusListener = std::make_shared(dataSyncManager); + screenStatusListener->ScreenOff(); + EXPECT_NE(screenStatusListener->dataSyncManager_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ScreenOffTest001 failed"; + } + GTEST_LOG_(INFO) << "ScreenOffTest001 end"; +} + +/** + * @tc.name: OnReceiveEventTest001 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(ScreenStatusListenerTest, OnReceiveEventTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest001 start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_OKAY); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto screenStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + screenStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_NE(subscriber->listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest001 failed"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest001 end"; +} + +/** + * @tc.name: OnReceiveEventTest002 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(ScreenStatusListenerTest, OnReceiveEventTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest002 start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto screenStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + screenStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_NE(subscriber->listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest002 failed"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest002 end"; +} + +/** + * @tc.name: OnReceiveEventTest003 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(ScreenStatusListenerTest, OnReceiveEventTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest003 start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto screenStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + screenStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_NE(subscriber->listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest003 failed"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest003 end"; +} + +/** + * @tc.name: OnReceiveEventTest004 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: IB3SWZ + */ +HWTEST_F(ScreenStatusListenerTest, OnReceiveEventTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest004 start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto screenStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + screenStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_NE(subscriber->listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest004 failed"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest004 end"; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/system_load_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/system_load_test.cpp new file mode 100644 index 0000000..e37255c --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/system_load_test.cpp @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "system_load.h" +#include "dfs_error.h" +#include "parameters.h" +#include "utils_log.h" +#include "res_sched_client.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class SytemLoadTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + shared_ptr SystemLoadStatus_ = nullptr; + shared_ptr SystemLoadListener_ = nullptr; +}; + +void SytemLoadTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void SytemLoadTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void SytemLoadTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + SystemLoadStatus_ = make_shared(); + SystemLoadListener_ = make_shared(); +} + +void SytemLoadTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; + SystemLoadStatus_ = nullptr; + SystemLoadListener_ = nullptr; +} + +/** + * @tc.name: RegisterSystemloadCallbackTest + * @tc.desc: Verify the RegisterSystemloadCallback function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, RegisterSystemloadCallbackTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterSystemloadCallbackTest Start"; + try { + std::shared_ptr dataSyncManager; + SystemLoadStatus_->RegisterSystemloadCallback(dataSyncManager); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterSystemloadCallbackTest FAILED"; + } + GTEST_LOG_(INFO) << "RegisterSystemloadCallbackTest End"; +} + +/** + * @tc.name: OnSystemloadLevelTest001 + * @tc.desc: Verify the OnSystemloadLevel function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, OnSystemloadLevelTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnSystemloadLevelTest001 Start"; + try { + int32_t level = 10; + SystemLoadListener_->OnSystemloadLevel(level); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnSystemloadLevelTest001 FAILED"; + } + GTEST_LOG_(INFO) << "OnSystemloadLevelTest001 End"; +} + +/** + * @tc.name: OnSystemloadLevelTest002 + * @tc.desc: Verify the OnSystemloadLevel function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, OnSystemloadLevelTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnSystemloadLevelTest001 Start"; + try { + int32_t level = 1; + std::shared_ptr dataSyncManager; + SystemLoadListener_->dataSyncManager_ = make_shared(); + SystemLoadListener_->OnSystemloadLevel(level); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnSystemloadLevelTest001 FAILED"; + } + GTEST_LOG_(INFO) << "OnSystemloadLevelTest001 End"; +} + +/** + * @tc.name: OnSystemloadLevelTest003 + * @tc.desc: Verify the OnSystemloadLevel function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, OnSystemloadLevelTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnSystemloadLevelTest003 Start"; + try { + int32_t level = 1; + system::SetParameter(TEMPERATURE_SYSPARAM_SYNC, "true"); + auto dataSyncManager = std::make_shared(); + SystemLoadListener_->SetDataSycner(dataSyncManager); + SystemLoadListener_->OnSystemloadLevel(level); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnSystemloadLevelTest003 FAILED"; + } + GTEST_LOG_(INFO) << "OnSystemloadLevelTest003 End"; +} + +/** + * @tc.name: OnSystemloadLevelTest004 + * @tc.desc: Verify the OnSystemloadLevel function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, OnSystemloadLevelTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnSystemloadLevelTest004 Start"; + try { + int32_t level = 1; + system::SetParameter(TEMPERATURE_SYSPARAM_THUMB, "true"); + auto dataSyncManager = std::make_shared(); + SystemLoadListener_->SetDataSycner(dataSyncManager); + SystemLoadListener_->OnSystemloadLevel(level); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnSystemloadLevelTest004 FAILED"; + } + GTEST_LOG_(INFO) << "OnSystemloadLevelTest004 End"; +} + +/** + * @tc.name: IsLoadStatusUnderHotTest001 + * @tc.desc: Verify the IsLoadStatusUnderHot function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, IsLoadStatusUnderHotTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 Start"; + try { + SystemLoadStatus_->Setload(10); + bool ret = SystemLoadStatus_->IsLoadStatusUnderHot(); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 FAILED"; + } + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 End"; +} + +/** + * @tc.name: IsLoadStatusUnderHotTest002 + * @tc.desc: Verify the IsLoadStatusUnderHot function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, IsLoadStatusUnderHotTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 Start"; + try { + SystemLoadStatus_->Setload(10); + bool ret = SystemLoadStatus_->IsLoadStatusUnderHot(); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 FAILED"; + } + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 End"; +} + +/** + * @tc.name: IsLoadStatusUnderHotTest003 + * @tc.desc: Verify the IsLoadStatusUnderHot function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, IsLoadStatusUnderHotTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 Start"; + try { + SystemLoadStatus_->Setload(1); + bool ret = SystemLoadStatus_->IsLoadStatusUnderHot(); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 FAILED"; + } + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest001 End"; +} + +/** + * @tc.name: IsLoadStatusUnderHotTest004 + * @tc.desc: Verify the IsLoadStatusUnderHot function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, IsLoadStatusUnderHotTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest004 Start"; + SystemLoadStatus_->Setload(10); + STOPPED_TYPE process = STOPPED_IN_THUMB; + bool ret = SystemLoadStatus_->IsLoadStatusUnderHot(process); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest004 End"; +} + +/** + * @tc.name: IsLoadStatusUnderHotTest005 + * @tc.desc: Verify the IsLoadStatusUnderHot function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(SytemLoadTest, IsLoadStatusUnderHotTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest005 Start"; + SystemLoadStatus_->Setload(10); + STOPPED_TYPE process = STOPPED_IN_SYNC; + bool ret = SystemLoadStatus_->IsLoadStatusUnderHot(process); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "IsLoadStatusUnderHotTest005 End"; +} + +HWTEST_F(SytemLoadTest, IsLoadStatusUnderNormalTest001, TestSize.Level1) +{ + SystemLoadStatus_->Setload(SYSTEMLOADLEVEL_NORMAL); + bool ret = SystemLoadStatus_->IsLoadStatusUnderNormal(STOPPED_TYPE::STOPPED_IN_SYNC); + EXPECT_TRUE(ret); +} + +HWTEST_F(SytemLoadTest, IsLoadStatusUnderNormalTest002, TestSize.Level1) +{ + SystemLoadStatus_->Setload(SYSTEMLOADLEVEL_NORMAL + 1); + bool ret = SystemLoadStatus_->IsLoadStatusUnderNormal(STOPPED_TYPE::STOPPED_IN_SYNC); + EXPECT_FALSE(ret); +} + +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/sync_rule/user_status_listener_test.cpp b/cloud_file/test/unittests/cloudsync_sa/sync_rule/user_status_listener_test.cpp new file mode 100644 index 0000000..6602a1e --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/sync_rule/user_status_listener_test.cpp @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "session_manager.h" +#include "user_status_listener.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace CloudFile; +using Want = OHOS::AAFwk::Want; + +class UserStatusListenerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void UserStatusListenerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void UserStatusListenerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void UserStatusListenerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void UserStatusListenerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: StopTest001 + * @tc.desc: Verify the Stop function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(UserStatusListenerTest, StopTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StopTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto userStatusListener = std::make_shared(dataSyncManager); + userStatusListener->Start(); + EXPECT_NE(userStatusListener->commonEventSubscriber_, nullptr); + userStatusListener->Stop(); + EXPECT_EQ(userStatusListener->commonEventSubscriber_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StopTest001 failed"; + } + GTEST_LOG_(INFO) << "StopTest001 end"; +} + +/** + * @tc.name: AddObserverTest001 + * @tc.desc: Verify the AddObserver function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(UserStatusListenerTest, AddObserverTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AddObserverTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto userStatusListener = std::make_shared(dataSyncManager); + auto sessionManager = make_shared(); + sessionManager->Init(); + userStatusListener->AddObserver(sessionManager); + EXPECT_NE(userStatusListener->observers_.size(), 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AddObserverTest001 failed"; + } + GTEST_LOG_(INFO) << "AddObserverTest001 end"; +} + +/** + * @tc.name: NotifyUserUnlockedTest001 + * @tc.desc: Verify the NotifyUserUnlocked function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(UserStatusListenerTest, NotifyUserUnlockedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NotifyUserUnlockedTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto userStatusListener = std::make_shared(dataSyncManager); + userStatusListener->NotifyUserUnlocked(); + EXPECT_EQ(userStatusListener->observers_.size(), 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "NotifyUserUnlockedTest001 failed"; + } + GTEST_LOG_(INFO) << "NotifyUserUnlockedTest001 end"; +} + +/** + * @tc.name: DoCleanVideoCacheTest001 + * @tc.desc: Verify the DoCleanVideoCache function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(UserStatusListenerTest, DoCleanVideoCacheTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DoCleanVideoCacheTest001 start"; + try { + auto dataSyncManager = std::make_shared(); + auto userStatusListener = std::make_shared(dataSyncManager); + userStatusListener->DoCleanVideoCache(); + EXPECT_NE(userStatusListener->dataSyncManager_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DoCleanVideoCacheTest001 failed"; + } + GTEST_LOG_(INFO) << "DoCleanVideoCacheTest001 end"; +} + +/** + * @tc.name: OnReceiveEventTest001 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(UserStatusListenerTest, OnReceiveEventTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest001 start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_OKAY); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto userStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + userStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_NE(subscriber->listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest001 failed"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest001 end"; +} + +/** + * @tc.name: OnReceiveEventTest002 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(UserStatusListenerTest, OnReceiveEventTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest002 start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto userStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + userStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_NE(subscriber->listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest002 failed"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest002 end"; +} + +/** + * @tc.name: OnReceiveEventTest003 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(UserStatusListenerTest, OnReceiveEventTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest003 start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto userStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + userStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_NE(subscriber->listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest003 failed"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest003 end"; +} + +/** + * @tc.name: OnReceiveEventTest004 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(UserStatusListenerTest, OnReceiveEventTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest004 start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); + EventFwk::CommonEventData eventData(want); + auto dataSyncManager = std::make_shared(); + auto userStatusListener = std::make_shared(dataSyncManager); + auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), + userStatusListener); + subscriber->OnReceiveEvent(eventData); + EXPECT_NE(subscriber->listener_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest004 failed"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest004 end"; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/system/BUILD.gn b/cloud_file/test/unittests/cloudsync_sa/system/BUILD.gn new file mode 100644 index 0000000..11c00e1 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/system/BUILD.gn @@ -0,0 +1,137 @@ +# 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("dfsu_fd_guard_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${utils_path}/system/src/dfsu_fd_guard.cpp", + "dfsu_fd_guard_test.cpp", + ] + + include_dirs = [ + "${utils_path}/system/include", + "${utils_path}/log/include", + ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + use_exceptions = true +} + +ohos_unittest("dfsu_access_token_helper_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${utils_path}/system/src/dfsu_access_token_helper.cpp", + "dfsu_access_token_helper_test.cpp", + "reimplement/accesstoken_kit.cpp", + "reimplement/accesstoken_kit_mock.cpp", + "reimplement/ipc_skeleton.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/test/unittests/cloudsync_sa/system/reimplement", + "${utils_path}/system/include", + "${utils_path}/log/include", + ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "preferences:native_preferences", + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + use_exceptions = true +} + +ohos_unittest("dfsu_mount_argument_descriptors_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${utils_path}/system/src/dfsu_mount_argument_descriptors.cpp", + "dfsu_mount_argument_descriptors_test.cpp", + ] + + include_dirs = [ + "${utils_path}/system/include", + "${utils_path}/log/include", + ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + use_exceptions = true +} +group("utils_system_src_test") { + testonly = true + deps = [ + ":dfsu_access_token_helper_test", + ":dfsu_fd_guard_test", + ":dfsu_mount_argument_descriptors_test", + ] +} diff --git a/cloud_file/test/unittests/cloudsync_sa/system/dfsu_access_token_helper_test.cpp b/cloud_file/test/unittests/cloudsync_sa/system/dfsu_access_token_helper_test.cpp new file mode 100644 index 0000000..32a1e38 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/system/dfsu_access_token_helper_test.cpp @@ -0,0 +1,211 @@ +/* + * 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 +#include +#include + +#include "dfsu_access_token_helper.h" +#include "tokenInfo.h" + +namespace OHOS::FileManagement::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +class DfsuAccessTokenHelperTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DfsuAccessTokenHelperTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void DfsuAccessTokenHelperTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void DfsuAccessTokenHelperTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void DfsuAccessTokenHelperTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: CheckCallerPermissionTest + * @tc.desc: Verify the CheckCallerPermission function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuAccessTokenHelperTest, CheckCallerPermissionTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckCallerPermissionTest Begin"; + try { + DfsuAccessTokenHelper dfsuAccessTokenHelper; + string permissionName = "permissionName"; + TokenInfo tokenInfo; + tokenInfo.SetTokenId(0); + auto res = dfsuAccessTokenHelper.CheckCallerPermission(permissionName); + EXPECT_FALSE(res == true); + tokenInfo.SetTokenId(2); + res = dfsuAccessTokenHelper.CheckCallerPermission(permissionName); + EXPECT_TRUE(res == true); + tokenInfo.SetTokenId(3); + res = dfsuAccessTokenHelper.CheckCallerPermission(permissionName); + EXPECT_TRUE(res == false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CheckCallerPermissionTest ERROR"; + } + + GTEST_LOG_(INFO) << "CheckCallerPermissionTest End"; +} + +/** + * @tc.name: CheckPermissionTest + * @tc.desc: Verify the CheckPermission function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuAccessTokenHelperTest, CheckPermissionTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckPermissionTest Begin"; + try { + DfsuAccessTokenHelper dfsuAccessTokenHelper; + uint32_t tokenId = 0; + string permissionName = "permissionName"; + auto res = dfsuAccessTokenHelper.CheckPermission(tokenId, permissionName); + EXPECT_FALSE(res); + res = dfsuAccessTokenHelper.CheckPermission(tokenId, permissionName); + EXPECT_FALSE(res); + tokenId = 1; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CheckPermissionTest ERROR"; + } + + GTEST_LOG_(INFO) << "CheckPermissionTest End"; +} + +/** + * @tc.name: GetCallerBundleNameTest + * @tc.desc: Verify the GetCallerBundleName function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuAccessTokenHelperTest, GetCallerBundleNameTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCallerBundleNameTest Begin"; + try { + DfsuAccessTokenHelper dfsuAccessTokenHelper; + string bundleName = "bundleName"; + auto res = dfsuAccessTokenHelper.GetCallerBundleName(bundleName); + EXPECT_EQ(res, 9); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetCallerBundleNameTest ERROR"; + } + + GTEST_LOG_(INFO) << "GetCallerBundleNameTest End"; +} + +/** + * @tc.name: GetBundleNameByTokenTest + * @tc.desc: Verify the GetBundleNameByToken function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuAccessTokenHelperTest, GetBundleNameByTokenTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetBundleNameByTokenTest Begin"; + try { + DfsuAccessTokenHelper dfsuAccessTokenHelper; + uint32_t tokenId = 0; + string bundleName = "bundleName"; + auto res = dfsuAccessTokenHelper.GetBundleNameByToken(tokenId, bundleName); + EXPECT_EQ(res, 9); + tokenId = 1; + res = dfsuAccessTokenHelper.GetBundleNameByToken(tokenId, bundleName); + EXPECT_EQ(res, 0); + tokenId = 2; + res = dfsuAccessTokenHelper.GetBundleNameByToken(tokenId, bundleName); + EXPECT_EQ(res, 9); + tokenId = 3; + res = dfsuAccessTokenHelper.GetBundleNameByToken(tokenId, bundleName); + EXPECT_EQ(res, 9); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetBundleNameByTokenTest ERROR"; + } + + GTEST_LOG_(INFO) << "GetBundleNameByTokenTest End"; +} + +/** + * @tc.name: IsSystemAppTest + * @tc.desc: Verify the IsSystemApp function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuAccessTokenHelperTest, IsSystemAppTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsSystemAppTest Begin"; + try { + DfsuAccessTokenHelper dfsuAccessTokenHelper; + TokenInfo tokenInfo; + tokenInfo.SetTokenId(1); + auto res = dfsuAccessTokenHelper.IsSystemApp(); + EXPECT_TRUE(res); + tokenInfo.SetTokenId(0); + res = dfsuAccessTokenHelper.IsSystemApp(); + EXPECT_TRUE(res == false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsSystemAppTest ERROR"; + } + + GTEST_LOG_(INFO) << "IsSystemAppTest End"; +} + +/** + * @tc.name: GetUserIdTest + * @tc.desc: Verify the GetUserId function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuAccessTokenHelperTest, GetUserIdTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetUserIdTest Begin"; + try { + DfsuAccessTokenHelper dfsuAccessTokenHelper; + auto res = dfsuAccessTokenHelper.GetUserId(); + EXPECT_EQ(res, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetUserIdTest ERROR"; + } + + GTEST_LOG_(INFO) << "GetUserIdTest End"; +} +} // namespace OHOS::FileManagement::Test diff --git a/cloud_file/test/unittests/cloudsync_sa/system/dfsu_fd_guard_test.cpp b/cloud_file/test/unittests/cloudsync_sa/system/dfsu_fd_guard_test.cpp new file mode 100644 index 0000000..445a0a3 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/system/dfsu_fd_guard_test.cpp @@ -0,0 +1,146 @@ +/* + * 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 +#include +#include + +#include "dfsu_fd_guard.h" + +namespace OHOS::Storage::DistributedFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +class DfsuFdGuardTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DfsuFdGuardTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void DfsuFdGuardTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void DfsuFdGuardTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void DfsuFdGuardTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetFDTest001 + * @tc.desc: Verify the GetFD function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuFdGuardTest, GetFDTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFDTest001 Begin"; + try { + int fd = 0; + bool autoClose = true; + DfsuFDGuard dfsuFDGuard(fd, autoClose); + auto ret = dfsuFDGuard.GetFD(); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetFDTest001 ERROR"; + } + + GTEST_LOG_(INFO) << "GetFDTest001 End"; +} + +/** + * @tc.name: GetFDTest002 + * @tc.desc: Verify the GetFD function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuFdGuardTest, GetFDTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFDTest002 Begin"; + try { + int fd = 0; + bool autoClose = true; + DfsuFDGuard dfsuFDGuard(fd, autoClose); + if (dfsuFDGuard.GetFD()) { + EXPECT_TRUE(true); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetFDTest002 ERROR"; + } + + GTEST_LOG_(INFO) << "GetFDTest002 End"; +} + +/** + * @tc.name: SetFDTest001 + * @tc.desc: Verify the SetFD function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuFdGuardTest, SetFDTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetFDTest001 Begin"; + try { + int fd = 1; + bool autoClose = true; + DfsuFDGuard dfsuFDGuard(fd, autoClose); + dfsuFDGuard.SetFD(fd, autoClose); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetFDTest001 ERROR"; + } + + GTEST_LOG_(INFO) << "SetFDTest001 End"; +} + +/** + * @tc.name: SetFDTest002 + * @tc.desc: Verify the SetFD function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(DfsuFdGuardTest, SetFDTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetFDTest002 Begin"; + try { + int fd = 1; + bool autoClose = true; + DfsuFDGuard dfsuFDGuard(fd, autoClose); + dfsuFDGuard.ClearFD(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetFDTest002 ERROR"; + } + + GTEST_LOG_(INFO) << "SetFDTest002 End"; +} +} // namespace OHOS::Storage::DistributedFile::Test diff --git a/cloud_file/test/unittests/cloudsync_sa/system/dfsu_mount_argument_descriptors_test.cpp b/cloud_file/test/unittests/cloudsync_sa/system/dfsu_mount_argument_descriptors_test.cpp new file mode 100644 index 0000000..c6760b8 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/system/dfsu_mount_argument_descriptors_test.cpp @@ -0,0 +1,302 @@ +/* + * 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 +#include +#include +#include + +#include "dfsu_mount_argument_descriptors.h" + +namespace OHOS::Storage::DistributedFile::Utils::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +class MountArgumentTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + shared_ptr mountArgument_ = nullptr; +}; + +void MountArgumentTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void MountArgumentTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void MountArgumentTest::SetUp(void) +{ + mountArgument_ = make_shared(); + GTEST_LOG_(INFO) << "SetUp"; +} + +void MountArgumentTest::TearDown(void) +{ + mountArgument_ = nullptr; + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetFullSrcTest + * @tc.desc: Verify the GetFullSrc function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, GetFullSrcTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFullSrcTest Begin"; + try { + std::string out = "/data/service/el2/0/hmdfs/"; + std::string ret = mountArgument_->GetFullSrc(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetFullSrcTest ERROR"; + } + GTEST_LOG_(INFO) << "GetFullSrcTest End"; +} + +/** + * @tc.name: GetFullDstTest + * @tc.desc: Verify the GetFullDst function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, GetFullDstTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFullDstTest Begin"; + try { + std::string out = "/mnt/hmdfs/0/"; + std::string ret = mountArgument_->GetFullDst(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetFullDstTest ERROR"; + } + GTEST_LOG_(INFO) << "GetFullDstTest End"; +} + +/** + * @tc.name: GetCachePathTest + * @tc.desc: Verify the GetCachePath function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, GetCachePathTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCachePathTest Begin"; + try { + std::string out = "/data/service/el2/0/hmdfs//cache/"; + std::string ret = mountArgument_->GetCachePath(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetCachePathTest ERROR"; + } + GTEST_LOG_(INFO) << "GetCachePathTest End"; +} + +/** + * @tc.name: GetCtrlPathTest + * @tc.desc: Verify the GetCtrlPath function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, GetCtrlPathTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetCtrlPathTest Begin"; + try { + std::string out = "/sys/fs/hmdfs/18446744073709551615/cmd"; + std::string ret = mountArgument_->GetCtrlPath(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetCtrlPathTest ERROR"; + } + GTEST_LOG_(INFO) << "GetCtrlPathTest End"; +} + +/** + * @tc.name: OptionsToStringTest001 + * @tc.desc: Verify the OptionsToString function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, OptionsToStringTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OptionsToStringTest001 Begin"; + try { + std::string out = "local_dst=/mnt/hmdfs/0/"; + std::string ret = mountArgument_->OptionsToString(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OptionsToStringTest001 ERROR"; + } + GTEST_LOG_(INFO) << "OptionsToStringTest001 End"; +} + +/** + * @tc.name: OptionsToStringTest002 + * @tc.desc: Verify the OptionsToString function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, OptionsToStringTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OptionsToStringTest002 Begin"; + try { + std::string out = "local_dst=/mnt/hmdfs/0/,cache_dir=/data/service/el2/0/hmdfs//cache/"; + mountArgument_->useCache_ = true; + std::string ret = mountArgument_->OptionsToString(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OptionsToStringTest002 ERROR"; + } + GTEST_LOG_(INFO) << "OptionsToStringTest002 End"; +} + +/** + * @tc.name: OptionsToStringTest003 + * @tc.desc: Verify the OptionsToString function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, OptionsToStringTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OptionsToStringTest003 Begin"; + try { + std::string out = "local_dst=/mnt/hmdfs/0/,sensitive"; + mountArgument_->caseSensitive_ = true; + std::string ret = mountArgument_->OptionsToString(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OptionsToStringTest003 ERROR"; + } + GTEST_LOG_(INFO) << "OptionsToStringTest003 End"; +} + +/** + * @tc.name: OptionsToStringTest004 + * @tc.desc: Verify the OptionsToString function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, OptionsToStringTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OptionsToStringTest004 Begin"; + try { + std::string out = "local_dst=/mnt/hmdfs/0/,merge"; + mountArgument_->enableMergeView_ = true; + std::string ret = mountArgument_->OptionsToString(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OptionsToStringTest004 ERROR"; + } + GTEST_LOG_(INFO) << "OptionsToStringTest004 End"; +} + +/** + * @tc.name: OptionsToStringTest005 + * @tc.desc: Verify the OptionsToString function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, OptionsToStringTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OptionsToStringTest005 Begin"; + try { + std::string out = "local_dst=/mnt/hmdfs/0/,fixupownership"; + mountArgument_->enableFixupOwnerShip_ = true; + std::string ret = mountArgument_->OptionsToString(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OptionsToStringTest005 ERROR"; + } + GTEST_LOG_(INFO) << "OptionsToStringTest005 End"; +} + +/** + * @tc.name: OptionsToStringTest006 + * @tc.desc: Verify the OptionsToString function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, OptionsToStringTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OptionsToStringTest006 Begin"; + try { + std::string out = "local_dst=/mnt/hmdfs/0/,no_offline_stash"; + mountArgument_->enableOfflineStash_ = false; + std::string ret = mountArgument_->OptionsToString(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OptionsToStringTest006 ERROR"; + } + GTEST_LOG_(INFO) << "OptionsToStringTest006 End"; +} + +/** + * @tc.name: OptionsToStringTest007 + * @tc.desc: Verify the OptionsToString function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, OptionsToStringTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OptionsToStringTest006 Begin"; + try { + std::string out = "local_dst=/mnt/hmdfs/0/,external_fs"; + mountArgument_->externalFS_ = true; + std::string ret = mountArgument_->OptionsToString(); + EXPECT_STREQ(ret.c_str(), out.c_str()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OptionsToStringTest007 ERROR"; + } + GTEST_LOG_(INFO) << "OptionsToStringTest007 End"; +} + +/** + * @tc.name: GetFlagsTest + * @tc.desc: Verify the GetFlags function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(MountArgumentTest, GetFlagsTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFlagsTest Begin"; + try { + auto ret = mountArgument_->GetFlags(); + EXPECT_EQ(ret, MS_NODEV); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetFlagsTest ERROR"; + } + GTEST_LOG_(INFO) << "GetFlagsTest End"; +} +} // namespace OHOS::Storage::DistributedFile::Utils::Test diff --git a/cloud_file/test/unittests/cloudsync_sa/system/reimplement/accesstoken_kit.cpp b/cloud_file/test/unittests/cloudsync_sa/system/reimplement/accesstoken_kit.cpp new file mode 100644 index 0000000..0b6ddc5 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/system/reimplement/accesstoken_kit.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2022 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 "accesstoken_kit.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#ifdef BUNDLE_PERMISSION_DEF_LIST + +int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + if (tokenID == 0) { + return PermissionState::PERMISSION_DENIED; + } else { + return 0; + } +} + +ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) +{ + switch (tokenID) { + case TOKEN_HAP: { + return TOKEN_HAP; + } + case TOKEN_NATIVE: { + return TOKEN_NATIVE; + } + case TOKEN_SHELL: { + return TOKEN_SHELL; + } + default: { + return TOKEN_INVALID; + } + } +} +#else +int AccessTokenKit::GetReqPermissions(AccessTokenID tokenID, std::vector& reqPermList, + bool isSystemGrant) +{ + return 0; +} + +int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + if (tokenID == 0) { + return PermissionState::PERMISSION_DENIED; + } else { + return 0; + } +} + +ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) +{ +#ifdef BUNDLE_FRAMEWORK_SYSTEM_APP_FALSE + switch (tokenID) { + case TOKEN_HAP: { + return TOKEN_HAP; + } + case TOKEN_NATIVE: { + return TOKEN_NATIVE; + } + case TOKEN_SHELL: { + return TOKEN_SHELL; + } + default: { + return TOKEN_INVALID; + } + } +#else + switch (tokenID) { + case TOKEN_HAP: { + return TOKEN_HAP; + } + case TOKEN_NATIVE: { + return TOKEN_NATIVE; + } + case TOKEN_SHELL: { + return TOKEN_SHELL; + } + default: { + return TOKEN_INVALID; + } + } +#endif +} +#endif + +int AccessTokenKit::VerifyAccessToken( + AccessTokenID callerTokenID, AccessTokenID firstTokenID, const std::string& permissionName) +{ + return 0; +} +int AccessTokenKit::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo &nativeTokenInfo) +{ + if (tokenID == TOKEN_SHELL) { + return TOKEN_NATIVE; + } else { + nativeTokenInfo.processName = "foundation"; + return 0; + } +} +} +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/system/reimplement/accesstoken_kit_mock.cpp b/cloud_file/test/unittests/cloudsync_sa/system/reimplement/accesstoken_kit_mock.cpp new file mode 100644 index 0000000..569e51d --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/system/reimplement/accesstoken_kit_mock.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2022-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 "accesstoken_kit.h" + +namespace OHOS::Security::AccessToken { +ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) +{ + return TOKEN_HAP; +} + +int AccessTokenKit::GetHapTokenInfo(AccessTokenID callerToken, HapTokenInfo &hapTokenInfoRes) +{ + hapTokenInfoRes.bundleName = "com.example.app2backup"; + return 1; +} + +} // namespace OHOS::Security::AccessToken diff --git a/cloud_file/test/unittests/cloudsync_sa/system/reimplement/ipc_skeleton.cpp b/cloud_file/test/unittests/cloudsync_sa/system/reimplement/ipc_skeleton.cpp new file mode 100644 index 0000000..e0c9164 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/system/reimplement/ipc_skeleton.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2021 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 "ipc_skeleton.h" + +#include +#include + +#include "access_token_adapter.h" +#include "accesstoken_kit.h" +#include "iosfwd" +#include "ipc_process_skeleton.h" +#include "ipc_thread_skeleton.h" +#include "ipc_types.h" +#include "iremote_invoker.h" +#include "iremote_object.h" +#include "refbase.h" +#include "string" +#include "tokenInfo.h" +#include "unistd.h" +#include "utils_log.h" + +int32_t TokenInfo::tokenid; + +namespace OHOS { +using namespace Security::AccessToken; +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif + +pid_t IPCSkeleton::GetCallingUid() +{ + return 0; +} + +uint32_t IPCSkeleton::GetCallingTokenID() +{ + int ret = 0; + switch (TokenInfo::GetTokenId()) { + case TOKEN_HAP: { + ret = TOKEN_HAP; + break; + } + case TOKEN_NATIVE: { + ret = TOKEN_NATIVE; + break; + } + case TOKEN_SHELL: { + ret = TOKEN_NATIVE; + break; + } + default: { + ret = -1; + break; + } + } + return ret; +} + +uint64_t IPCSkeleton::GetCallingFullTokenID() +{ + IRemoteInvoker *invoker = IPCThreadSkeleton::GetActiveInvoker(); + if (invoker != nullptr) { + return invoker->GetCallerTokenID(); + } + return GetSelfTokenID(); +} + +uint64_t IPCSkeleton::GetSelfTokenID() +{ + IRemoteInvoker *invoker = IPCThreadSkeleton::GetDefaultInvoker(); + if (invoker != nullptr) { + return invoker->GetSelfTokenID(); + } + return 0; +} +} // namespace OHOS diff --git a/cloud_file/test/unittests/cloudsync_sa/system/reimplement/tokenInfo.h b/cloud_file/test/unittests/cloudsync_sa/system/reimplement/tokenInfo.h new file mode 100644 index 0000000..2ab1b82 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/system/reimplement/tokenInfo.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 TOKEN_INFO_H +#define TOKEN_INFO_H + +#include + +class TokenInfo { +public: + static int32_t tokenid; + static int32_t GetTokenId() + { + return tokenid; + } + static void SetTokenId(int32_t tokenId) + { + tokenid = tokenId; + } +}; + +#endif // TOKEN_INFO_H diff --git a/cloud_file/test/unittests/cloudsync_sa/transport/BUILD.gn b/cloud_file/test/unittests/cloudsync_sa/transport/BUILD.gn new file mode 100644 index 0000000..295567c --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/transport/BUILD.gn @@ -0,0 +1,182 @@ +# Copyright (C) 2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("cloud_sync_service_transport_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp", + "${cloud_file_path}/test/mock/cloudsyncservice/transport/softbus_adapter_mock.cpp", + "${cloud_file_path}/test/mock/cloudsyncservice/transport/softbus_session_mock.cpp", + "${cloud_file_path}/test/mock/socket_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/parameters.cpp", + "${services_path}/cloudsyncservice/src/ipc/download_asset_callback_manager.cpp", + "${services_path}/cloudsyncservice/src/ipc/download_asset_callback_proxy.cpp", + "${services_path}/cloudsyncservice/src/transport/file_transfer_manager.cpp", + "${services_path}/cloudsyncservice/src/transport/message_handler.cpp", + "${services_path}/cloudsyncservice/src/transport/softbus/session_manager.cpp", + "file_transfer_manager_test.cpp", + "message_handler_test.cpp", + "softbus/session_manager_test.cpp", + ] + + include_dirs = [ + "${clouddisk_database_path}/include", + "${cloud_file_path}/test/mock", + "${cloud_file_path}/test/mock/cloudsyncservice/transport", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/transport", + "${services_path}/cloudsyncservice/include/transport/softbus", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${innerkits_native_path}/cloudsync_kit_inner", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "cloud_file:cloudsync_kit_inner", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gtest", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_single", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_TEST\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +ohos_unittest("cloud_sync_service_transport_softbus_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/src/cloud_sync_common.cpp", + "${cloud_file_path}/test/mock/socket_mock.cpp", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/parameters.cpp", + "${services_path}/cloudsyncservice/src/ipc/download_asset_callback_manager.cpp", + "${services_path}/cloudsyncservice/src/ipc/download_asset_callback_proxy.cpp", + "${services_path}/cloudsyncservice/src/transport/file_transfer_manager.cpp", + "${services_path}/cloudsyncservice/src/transport/message_handler.cpp", + "${services_path}/cloudsyncservice/src/transport/softbus/session_manager.cpp", + "${services_path}/cloudsyncservice/src/transport/softbus/softbus_adapter.cpp", + "${services_path}/cloudsyncservice/src/transport/softbus/softbus_session.cpp", + "softbus/softbus_adapter_test.cpp", + "softbus/softbus_session_test.cpp", + ] + + include_dirs = [ + "${clouddisk_database_path}/include", + "${cloud_file_path}/test/mock", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/test/unittests/cloudsync_sa/mock/", + "${services_path}/cloudsyncservice/include", + "${services_path}/cloudsyncservice/include/transport", + "${services_path}/cloudsyncservice/include/transport/softbus", + "${services_path}/cloudfiledaemon/include/cloud_disk", + "${innerkits_native_path}/cloudsync_kit_inner", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "app_file_service:sandbox_helper_native", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "cloud_file:cloudsync_kit_inner", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gtest", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "ipc:ipc_single", + "libfuse:libfuse", + "netmanager_base:net_conn_manager_if", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "protected=public", + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_TEST\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + if (cloudsync_service_resource_schedule) { + external_deps += [ "resource_schedule_service:ressched_client" ] + defines += [ "CLOUDSYNC_SERVICE_RESOURCE_SCHEDULE" ] + } + use_exceptions = true +} + +group("cloudsync_sa_transport_test") { + testonly = true + deps = [ + ":cloud_sync_service_transport_manager_test", + ":cloud_sync_service_transport_softbus_test", + ] +} diff --git a/cloud_file/test/unittests/cloudsync_sa/transport/file_transfer_manager_test.cpp b/cloud_file/test/unittests/cloudsync_sa/transport/file_transfer_manager_test.cpp new file mode 100644 index 0000000..3dd3ff0 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/transport/file_transfer_manager_test.cpp @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "file_transfer_manager.h" +#include "softbus_adapter_mock.h" +#include "softbus_session_mock.h" +#include "session_manager.h" +#include "socket_mock.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class FileTransferManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void FileTransferManagerTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void FileTransferManagerTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void FileTransferManagerTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void FileTransferManagerTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: InitTest001 + * @tc.desc: Verify the Init function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(FileTransferManagerTest, InitTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitTest001 start"; + try { + auto sessionManager = make_shared(); + auto fileTransferManager = make_shared(sessionManager); + fileTransferManager->Init(); + fileTransferManager->OnSessionClosed(); + EXPECT_NE(fileTransferManager->sessionManager_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitTest001 failed"; + } + GTEST_LOG_(INFO) << "InitTest001 end"; +} + +/** + * @tc.name: DownloadFileFromRemoteDeviceTest001 + * @tc.desc: Verify the DownloadFileFromRemoteDevice function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(FileTransferManagerTest, DownloadFileFromRemoteDeviceTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DownloadFileFromRemoteDeviceTest001 start"; + try { + auto sessionManager = make_shared(); + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto fileTransferManager = make_shared(sessionManager); + fileTransferManager->DownloadFileFromRemoteDevice(peerNetworkId, 0, 0, "data/test"); + EXPECT_NE(fileTransferManager->sessionManager_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "DownloadFileFromRemoteDeviceTest001 failed"; + } + GTEST_LOG_(INFO) << "DownloadFileFromRemoteDeviceTest001 end"; +} + +/** + * @tc.name: OnMessageHandleTest001 + * @tc.desc: Verify the OnMessageHandle function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(FileTransferManagerTest, OnMessageHandleTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnMessageHandleTest001 start"; + try { + auto sessionManager = make_shared(); + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto fileTransferManager = make_shared(sessionManager); + fileTransferManager->OnMessageHandle(peerNetworkId, 0, data, sizeof(data)); + EXPECT_NE(fileTransferManager->sessionManager_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnMessageHandleTest001 failed"; + } + GTEST_LOG_(INFO) << "OnMessageHandleTest001 end"; +} + +/** + * @tc.name: HandleDownloadFileRequestTest001 + * @tc.desc: Verify the HandleDownloadFileRequest function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(FileTransferManagerTest, HandleDownloadFileRequestTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleDownloadFileRequestTest001 start"; + try { + auto sessionManager = make_shared(); + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto fileTransferManager = make_shared(sessionManager); + + MessageInputInfo msgInputInfo = {}; + msgInputInfo.userId = 100; + msgInputInfo.taskId = 100; + msgInputInfo.uri = "data/test"; + MessageHandler msgHandle(msgInputInfo); + fileTransferManager->HandleDownloadFileRequest(msgHandle, peerNetworkId, 0); + fileTransferManager->HandleDownloadFileResponse(msgHandle); + fileTransferManager->HandleRecvFileFinished(); + EXPECT_NE(fileTransferManager->sessionManager_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "HandleDownloadFileRequestTest001 failed"; + } + GTEST_LOG_(INFO) << "HandleDownloadFileRequestTest001 end"; +} + +/** + * @tc.name: IsFileExistsTest001 + * @tc.desc: Verify the IsFileExists function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(FileTransferManagerTest, IsFileExistsTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsFileExistsTest001 start"; + try { + auto sessionManager = make_shared(); + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto fileTransferManager = make_shared(sessionManager); + EXPECT_TRUE(fileTransferManager->IsFileExists("data/errorPath") == false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsFileExistsTest001 failed"; + } + GTEST_LOG_(INFO) << "IsFileExistsTest001 end"; +} + +/** + * @tc.name: AddTransTaskTest001 + * @tc.desc: Verify the AddTransTask function + * @tc.type: FUNC + * @tc.require: IB3T5H + */ +HWTEST_F(FileTransferManagerTest, AddTransTaskTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AddTransTaskTest001 start"; + try { + auto sessionManager = make_shared(); + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto fileTransferManager = make_shared(sessionManager); + fileTransferManager->AddTransTask("data/test", 0, 100); + fileTransferManager->FinishTransTask("data/test", 0); + fileTransferManager->RemoveTransTask(100); + EXPECT_NE(fileTransferManager->sessionManager_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "AddTransTaskTest001 failed"; + } + GTEST_LOG_(INFO) << "AddTransTaskTest001 end"; +} +} // namespace Test +} // namespace CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/transport/message_handler_test.cpp b/cloud_file/test/unittests/cloudsync_sa/transport/message_handler_test.cpp new file mode 100644 index 0000000..6c2c83c --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/transport/message_handler_test.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "message_handler.h" +#include "socket_mock.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MessageHandlerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void MessageHandlerTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void MessageHandlerTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void MessageHandlerTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void MessageHandlerTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: GetDataTest001 + * @tc.desc: Verify the MessageHandler function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(MessageHandlerTest, GetDataTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetDataTest001 start"; + try { + MessageInputInfo inputInfo; + inputInfo.srcNetworkId = "srcNetworkId"; + inputInfo.dstNetworkId = "dstNetworkId"; + inputInfo.uri = "uritest"; + inputInfo.msgType = MSG_DOWNLOAD_FILE_REQ; + inputInfo.errorCode = 1; + inputInfo.userId = 100; + inputInfo.taskId = 100; + auto messageHandler = make_shared(inputInfo); + EXPECT_TRUE(messageHandler); + + EXPECT_EQ(messageHandler->GetMsgType(), MSG_DOWNLOAD_FILE_REQ); + EXPECT_EQ(messageHandler->GetSrcNetworkId(), "srcNetworkId"); + EXPECT_EQ(messageHandler->GetDstNetworkId(), "dstNetworkId"); + EXPECT_EQ(messageHandler->GetUri(), "uritest"); + EXPECT_EQ(messageHandler->GetErrorCode(), 1); + EXPECT_EQ(messageHandler->GetUserId(), 100); + EXPECT_EQ(messageHandler->GetTaskId(), 100); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetDataTest001 failed"; + } + GTEST_LOG_(INFO) << "GetDataTest001 end"; +} + +/** + * @tc.name: AddTransTaskTest001 + * @tc.desc: Verify the PackData function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(MessageHandlerTest, PackDataTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PackDataTest001 start"; + try { + MessageInputInfo inputInfo; + inputInfo.srcNetworkId = "srcNetworkId"; + inputInfo.dstNetworkId = "dstNetworkId"; + inputInfo.uri = "uritest"; + inputInfo.msgType = MSG_DOWNLOAD_FILE_REQ; + inputInfo.errorCode = 1; + inputInfo.userId = 100; + inputInfo.taskId = 100; + auto messageHandler = make_shared(inputInfo); + EXPECT_TRUE(messageHandler); + cout << "messageHandler->GetDataSize():" << messageHandler->GetDataSize() << endl; + auto dataSubPtr = std::make_unique(messageHandler->GetDataSize()); + EXPECT_TRUE(messageHandler->PackData(dataSubPtr.get(), messageHandler->GetDataSize())); + + MessageHandler msgHandleSub; + EXPECT_TRUE(msgHandleSub.UnPackData(dataSubPtr.get(), messageHandler->GetDataSize())); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PackDataTest001 FAILED"; + } + GTEST_LOG_(INFO) << "PackDataTest001 end"; +} +} // namespace Test +} // namespace CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/transport/softbus/session_manager_test.cpp b/cloud_file/test/unittests/cloudsync_sa/transport/softbus/session_manager_test.cpp new file mode 100644 index 0000000..9940651 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/transport/softbus/session_manager_test.cpp @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "file_transfer_manager.h" +#include "softbus_adapter_mock.h" +#include "softbus_session_mock.h" +#include "session_manager.h" +#include "socket_mock.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class SessionManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static inline std::shared_ptr softbusAdapterMock_ = nullptr; + static inline std::shared_ptr softbusSessionMock_ = nullptr; +}; + +void SessionManagerTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; +} + +void SessionManagerTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; +} + +void SessionManagerTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; + softbusAdapterMock_ = std::make_shared(); + ISoftbusAdapterMock::iSoftbusAdapterMock_ = softbusAdapterMock_; + + softbusSessionMock_ = std::make_shared(); + ISoftbusSessionMock::iSoftbusSessionMock_ = softbusSessionMock_; +} + +void SessionManagerTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; + ISoftbusAdapterMock::iSoftbusAdapterMock_ = nullptr; + softbusAdapterMock_ = nullptr; + + ISoftbusSessionMock::iSoftbusSessionMock_ = nullptr; + softbusSessionMock_ = nullptr; +} + +/** + * @tc.name: InitTest001 + * @tc.desc: Verify the Init function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SessionManagerTest, InitTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitTest001 start"; + try { + auto sessionManager = make_shared(); + EXPECT_NE(sessionManager, nullptr); + EXPECT_CALL(*softbusAdapterMock_, CreateSessionServer(_, _)).WillOnce(Return(-1)); + sessionManager->Init(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitTest001 failed"; + } + GTEST_LOG_(INFO) << "InitTest001 end"; +} + +/** + * @tc.name: SendDataTest001 + * @tc.desc: Verify the SendData function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SessionManagerTest, SendDataTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SendDataTest001 start"; + try { + auto sessionManager = make_shared(); + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + EXPECT_CALL(*softbusSessionMock_, Start()).WillOnce(Return(0)); + int32_t ret = sessionManager->SendData(peerNetworkId, data, sizeof(data)); + EXPECT_EQ(ret, 0); + sessionManager->ReleaseSession(SoftbusSession::TYPE_BYTES, peerNetworkId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SendDataTest001 failed"; + } + GTEST_LOG_(INFO) << "SendDataTest001 end"; +} + +/** + * @tc.name: SendDataTest001 + * @tc.desc: Verify the SendFile function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SessionManagerTest, SendFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SendFileTest001 start"; + try { + auto sessionManager = make_shared(); + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto session = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(session != nullptr); + + EXPECT_CALL(*softbusSessionMock_, Start()).WillOnce(Return(0)); + EXPECT_CALL(*softbusSessionMock_, SendFile(_, _)).WillOnce(Return(0)); + int32_t ret = sessionManager->SendFile(peerNetworkId, {"data/test"}, {"data/test"}); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SendFileTest001 failed"; + } + GTEST_LOG_(INFO) << "SendFileTest001 end"; +} + +/** + * @tc.name: OnSessionOpenedTest001 + * @tc.desc: Verify the OnSessionOpened function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SessionManagerTest, OnSessionOpenedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnSessionOpenedTest001 start"; + try { + auto sessionManager = make_shared(); + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto session = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(session != nullptr); + int sessionId = session->GetSessionId(); + sessionManager->OnSessionOpened(sessionId, -1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnSessionOpenedTest001 failed"; + } + GTEST_LOG_(INFO) << "OnSessionOpenedTest001 end"; +} + +/** + * @tc.name: OnSessionClosedTest001 + * @tc.desc: Verify the OnSessionClosed function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SessionManagerTest, OnSessionClosedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnSessionClosedTest001 start"; + try { + auto sessionManager = make_shared(); + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto session = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(session != nullptr); + int sessionId = session->GetSessionId(); + sessionManager->OnSessionClosed(sessionId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnSessionClosedTest001 failed"; + } + GTEST_LOG_(INFO) << "OnSessionClosedTest001 end"; +} + +/** + * @tc.name: OnDataReceivedTest001 + * @tc.desc: Verify the OnDataReceived function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SessionManagerTest, OnDataReceivedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnDataReceivedTest001 start"; + try { + auto sessionManager = make_shared(); + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto session = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(session != nullptr); + int sessionId = session->GetSessionId(); + sessionManager->OnDataReceived(peerNetworkId, sessionId, data, sizeof(data)); + EXPECT_EQ(sessionManager->dataHandler_, nullptr); + auto fileTransferManager = make_shared(sessionManager); + sessionManager->RegisterDataHandler(fileTransferManager); + sessionManager->OnDataReceived(peerNetworkId, sessionId, data, sizeof(data)); + EXPECT_NE(sessionManager->dataHandler_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnDataReceivedTest001 failed"; + } + GTEST_LOG_(INFO) << "OnDataReceivedTest001 end"; +} + +/** + * @tc.name: OnFileReceivedTest001 + * @tc.desc: Verify the OnFileReceived function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SessionManagerTest, OnFileReceivedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnFileReceivedTest001 start"; + try { + auto sessionManager = make_shared(); + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + sessionManager->OnFileReceived(peerNetworkId, "data/test", 0); + EXPECT_EQ(sessionManager->dataHandler_, nullptr); + auto fileTransferManager = make_shared(sessionManager); + sessionManager->RegisterDataHandler(fileTransferManager); + sessionManager->OnFileReceived(peerNetworkId, "data/test", 0); + EXPECT_NE(sessionManager->dataHandler_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnFileReceivedTest001 failed"; + } + GTEST_LOG_(INFO) << "OnFileReceivedTest001 end"; +} + +/** + * @tc.name: OnUserUnlockedTest001 + * @tc.desc: Verify the OnUserUnlocked function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SessionManagerTest, OnUserUnlockedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnUserUnlockedTest001 start"; + try { + auto sessionManager = make_shared(); + sessionManager->OnUserUnlocked(); + EXPECT_EQ(sessionManager->dataHandler_, nullptr); + auto fileTransferManager = make_shared(sessionManager); + sessionManager->RegisterDataHandler(fileTransferManager); + sessionManager->OnUserUnlocked(); + EXPECT_NE(sessionManager->dataHandler_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnUserUnlockedTest001 failed"; + } + GTEST_LOG_(INFO) << "OnUserUnlockedTest001 end"; +} + +HWTEST_F(SessionManagerTest, OnUserUnlockedTest002, TestSize.Level1) +{ + auto sessionManager = make_shared(); + sessionManager->SetFileRecvListenerFlag_ = false; + sessionManager->OnUserUnlocked(); + EXPECT_FALSE(sessionManager->SetFileRecvListenerFlag_); +} + +HWTEST_F(SessionManagerTest, SendFileTest002, TestSize.Level1) +{ + auto sessionManager = make_shared(); + string peerNetworkId = "test peerNetworkId"; + EXPECT_CALL(*softbusSessionMock_, Start()).WillOnce(Return(1)); + + int32_t ret = sessionManager->SendFile(peerNetworkId, {"data/test"}, {"data/test"}); + EXPECT_EQ(ret, E_CREATE_SESSION); +} + +HWTEST_F(SessionManagerTest, OnSessionClosedTest, TestSize.Level1) +{ + auto sessionManager = make_shared(); + + auto type = SoftbusSession::TYPE_BYTES; + string peerNetworkId = "test peerNetworkId"; + sessionManager->ReleaseSession(type, peerNetworkId); + + int32_t socket = 1; + sessionManager->dataHandler_ = make_shared(nullptr); + sessionManager->OnSessionClosed(socket); + EXPECT_NE(sessionManager->dataHandler_, nullptr); +} + +HWTEST_F(SessionManagerTest, GetSendSessionTest, TestSize.Level1) +{ + auto type = SoftbusSession::TYPE_BYTES; + string peerNetworkId = "test peerNetworkId"; + auto sessionManager = make_shared(); + + auto res = sessionManager->GetSendSession(type, peerNetworkId); + EXPECT_EQ(res, nullptr); +} +} // namespace Test +} // namespace CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/transport/softbus/softbus_adapter_test.cpp b/cloud_file/test/unittests/cloudsync_sa/transport/softbus/softbus_adapter_test.cpp new file mode 100644 index 0000000..25380d4 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/transport/softbus/softbus_adapter_test.cpp @@ -0,0 +1,487 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "softbus_adapter.h" +#include "session_manager.h" +#include "softbus_session.h" +#include "socket_mock.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class SoftbusAdapterTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr socketMock_ = nullptr; +}; + +void SoftbusAdapterTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; + socketMock_ = make_shared(); + Storage::DistributedFile::SocketMock::dfsSocket = socketMock_; +} + +void SoftbusAdapterTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; + Storage::DistributedFile::SocketMock::dfsSocket = nullptr; + socketMock_ = nullptr; +} + +void SoftbusAdapterTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void SoftbusAdapterTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: CreateSessionServerTest001 + * @tc.desc: Verify the CreateSessionServer function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, CreateSessionServerTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateSessionServerTest001 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char packageName[] = "com.example.test"; + char sessionName[] = "testSession"; + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(-1)); + int32_t result = adapter.CreateSessionServer(packageName, sessionName); + EXPECT_EQ(result, ERR_BAD_VALUE); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CreateSessionServerTest001 failed"; + } + GTEST_LOG_(INFO) << "CreateSessionServerTest001 end"; +} + +/** + * @tc.name: CreateSessionServerTest002 + * @tc.desc: Verify the CreateSessionServer function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, CreateSessionServerTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateSessionServerTest002 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char packageName[] = "com.example.test"; + char sessionName[] = "testSession"; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Listen(_, _, _, _)).WillOnce(Return(0)); + int32_t result = adapter.CreateSessionServer(packageName, sessionName); + EXPECT_EQ(result, E_OK); + adapter.RemoveSessionServer(packageName, sessionName); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CreateSessionServerTest002 failed"; + } + GTEST_LOG_(INFO) << "CreateSessionServerTest002 end"; +} + +/** + * @tc.name: CreateSessionServerTest003 + * @tc.desc: Verify the CreateSessionServer function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, CreateSessionServerTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CreateSessionServerTest003 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char packageName[] = "com.example.test"; + char sessionName[] = "testSession"; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Listen(_, _, _, _)).WillOnce(Return(1)); + int32_t result = adapter.CreateSessionServer(packageName, sessionName); + EXPECT_EQ(result, 1); + adapter.RemoveSessionServer(packageName, sessionName); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CreateSessionServerTest003 failed"; + } + GTEST_LOG_(INFO) << "CreateSessionServerTest003 end"; +} + +/** + * @tc.name: OpenSessionByP2PTest001 + * @tc.desc: Verify the OpenSessionByP2P function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, OpenSessionByP2PTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenSessionByP2PTest001 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char sessionName[] = "testSession"; + char peerNetworkId[] = "test peerNetworkId"; + char groupId[] = "test"; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(-1)); + int socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, true); + EXPECT_EQ(socketFd, ERR_BAD_VALUE); + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(0)); + socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, true); + EXPECT_EQ(socketFd, 1); + CloseSession(socketFd); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenSessionByP2PTest001 failed"; + } + GTEST_LOG_(INFO) << "OpenSessionByP2PTest001 end"; +} + +/** + * @tc.name: OpenSessionByP2PTest002 + * @tc.desc: Verify the OpenSessionByP2P function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, OpenSessionByP2PTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OpenSessionByP2PTest002 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char sessionName[] = "testSession"; + char peerNetworkId[] = "test peerNetworkId"; + char groupId[] = "test"; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(-1)); + int socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, false); + EXPECT_EQ(socketFd, ERR_BAD_VALUE); + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(0)); + socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, false); + EXPECT_EQ(socketFd, 1); + CloseSession(socketFd); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OpenSessionByP2PTest002 failed"; + } + GTEST_LOG_(INFO) << "OpenSessionByP2PTest002 end"; +} + +/** + * @tc.name: EventTest001 + * @tc.desc: Verify the OpenSessionByP2P function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, EventTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EventTest001 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char sessionName[] = "testSession"; + char peerNetworkId[] = "test peerNetworkId"; + char groupId[] = "test"; + PeerSocketInfo info; + info.name = sessionName; + info.networkId = peerNetworkId; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(0)); + int socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, false); + // OnBind + SoftbusAdapter::OnBind(socketFd, info); + // OnShutdown + SoftbusAdapter::OnShutdown(socketFd, SHUTDOWN_REASON_UNKNOWN); + // OnBytes + char data[] = "test data"; + SoftbusAdapter::OnBytes(socketFd, data, sizeof(data)); + // OnFile + FileEvent event; + event.type = FileEventType::FILE_EVENT_RECV_UPDATE_PATH; + SoftbusAdapter::OnFile(socketFd, &event); + // OnReceiveFileProcess + int32_t result = SoftbusAdapter::OnReceiveFileProcess(socketFd, "", 0, 0); + EXPECT_EQ(result, 0); + // OnReceiveFileFinished + SoftbusAdapter::OnReceiveFileFinished(socketFd, "", 0); + // GetRecvPath + EXPECT_EQ(SoftbusAdapter::GetRecvPath(), "/mnt/hmdfs/100/account/device_view/local/data/"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "EventTest001 failed"; + } + GTEST_LOG_(INFO) << "EventTest001 end"; +} + +/** + * @tc.name: SendBytesTest001 + * @tc.desc: Verify the OpenSessionByP2P function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, SendBytesTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SendBytesTest001 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char sessionName[] = "testSession"; + char peerNetworkId[] = "test peerNetworkId"; + char groupId[] = "test"; + char data[] = "test data"; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(0)); + int socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, false); + int result = adapter.SendBytes(socketFd, data, sizeof(data)); + EXPECT_NE(result, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SendBytesTest001 failed"; + } + GTEST_LOG_(INFO) << "SendBytesTest001 end"; +} + +/** + * @tc.name: SendBytesTest001 + * @tc.desc: Verify the OpenSessionByP2P function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, SendFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SendFileTest001 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char sessionName[] = "testSession"; + char peerNetworkId[] = "test peerNetworkId"; + char groupId[] = "test"; + char data[] = "test data"; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(0)); + int socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, false); + int result = adapter.SendFile(socketFd, {"data/test"}, {"data/test"}); + EXPECT_EQ(result, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SendFileTest001 failed"; + } + GTEST_LOG_(INFO) << "SendFileTest001 end"; +} + +/** + * @tc.name: GetSessionNameTest001 + * @tc.desc: Verify the OpenSessionByP2P function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, GetSessionNameTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSessionNameTest001 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char sessionName[] = "testSession"; + char peerNetworkId[] = "test peerNetworkId"; + char groupId[] = "test"; + char data[] = "test data"; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(0)); + int socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, false); + + EXPECT_EQ(adapter.GetSessionNameFromMap(socketFd), "testSession"); + EXPECT_EQ(adapter.GetPeerNetworkId(socketFd), "test peerNetworkId"); + EXPECT_EQ(adapter.GetSocketNameFromMap("testSession"), -1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetSessionNameTest001 failed"; + } + GTEST_LOG_(INFO) << "GetSessionNameTest001 end"; +} + +/** + * @tc.name: RegisterSessionTest001 + * @tc.desc: Verify the OpenSessionByP2P function + * @tc.type: FUNC + * @tc.require: IB3T80 + */ +HWTEST_F(SoftbusAdapterTest, RegisterSessionTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterSessionTest001 start"; + try { + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + char sessionName[] = "testSession"; + char peerNetworkId[] = "test peerNetworkId"; + char groupId[] = "test"; + char data[] = "test data"; + + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(0)); + int socketFd = adapter.OpenSessionByP2P(sessionName, peerNetworkId, groupId, false); + + adapter.RegisterSessionListener(sessionName, nullptr); + adapter.UnRegisterSessionListener(sessionName); + EXPECT_EQ(adapter.IsSessionOpened(socketFd), true); + + adapter.AcceptSesion(socketFd, sessionName, peerNetworkId); + adapter.RemoveSesion(socketFd); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterSessionTest001 failed"; + } + GTEST_LOG_(INFO) << "RegisterSessionTest001 end"; +} + +HWTEST_F(SoftbusAdapterTest, RemoveSessionServerTest001, TestSize.Level1) +{ + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + + char packageName[] = ""; + char sessionName[] = ""; + + int32_t res = adapter.RemoveSessionServer(packageName, sessionName); + EXPECT_EQ(res, E_OK); +} + +HWTEST_F(SoftbusAdapterTest, OnBindTest001, TestSize.Level1) +{ + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + + int socket = 1; + char sessionName[] = ""; + char peerNetworkId[] = "test peerNetworkId"; + PeerSocketInfo info; + info.name = sessionName; + info.networkId = peerNetworkId; + + adapter.OnBind(socket, info); + EXPECT_EQ(info.name, sessionName); + + auto ptr = std::make_shared(); + (adapter.listeners_)["socket"] = ptr; + char socket2[] = "socket"; + info.name = socket2; + adapter.OnBind(socket, info); + EXPECT_NE(adapter.listeners_.count("socket"), 0); +} + +HWTEST_F(SoftbusAdapterTest, OnShutdownTest, TestSize.Level1) +{ + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + + int32_t socket = 0; + ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; + adapter.OnShutdown(socket, reason); + + (adapter.sessionNameMap_)[0] = "test"; + auto ptr = std::make_shared(); + (adapter.listeners_)["test"] = ptr; + adapter.OnShutdown(socket, reason); + EXPECT_NE(adapter.listeners_.count("test"), 0); +} + +HWTEST_F(SoftbusAdapterTest, OnBytesTest, TestSize.Level1) +{ + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + + int socket = 0; + unsigned int dataLen = 1; + adapter.OnBytes(socket, nullptr, dataLen); + + (adapter.sessionNameMap_)[0] = "test"; + adapter.OnBytes(socket, nullptr, dataLen); + + (adapter.networkIdMap_)[0] = "test"; + auto ptr = std::make_shared(); + (adapter.listeners_)["test"] = ptr; + adapter.OnBytes(socket, nullptr, dataLen); + + EXPECT_NE(adapter.listeners_.count("test"), 0); +} + +HWTEST_F(SoftbusAdapterTest, OnReceiveFileFinishedTest, TestSize.Level1) +{ + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + + int sessionId = -1; + char *files = nullptr; + int fileCnt = 1; + adapter.OnReceiveFileFinished(sessionId, files, fileCnt); + + (adapter.sessionNameMap_)[-1] = "test1"; + adapter.OnReceiveFileFinished(sessionId, files, fileCnt); + + (adapter.networkIdMap_)[-1] = "test2"; + auto ptr = std::make_shared(); + (adapter.listeners_)["test1"] = ptr; + adapter.OnReceiveFileFinished(sessionId, files, fileCnt); + + EXPECT_NE(adapter.listeners_.count("test1"), 0); +} + +HWTEST_F(SoftbusAdapterTest, OpenSessionTest, TestSize.Level1) +{ + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + + TransDataType dataType = TransDataType::DATA_TYPE_MESSAGE; + char sessionName[] = ""; + char peerDeviceId[] = ""; + char groupId[] = ""; + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(1)); + + auto res = adapter.OpenSession(sessionName, peerDeviceId, groupId, dataType); + EXPECT_EQ(res, 1); +} + +HWTEST_F(SoftbusAdapterTest, GetPeerNetworkIdTest, TestSize.Level1) +{ + SoftbusAdapter& adapter = SoftbusAdapter::GetInstance(); + + TransDataType dataType = TransDataType::DATA_TYPE_MESSAGE; + char sessionName[] = ""; + char peerDeviceId[] = ""; + char groupId[] = ""; + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + EXPECT_CALL(*socketMock_, Bind(_, _, _, _)).WillOnce(Return(1)); + + auto res = adapter.OpenSession(sessionName, peerDeviceId, groupId, dataType); + EXPECT_EQ(res, 1); +} +} // namespace Test +} // namespace CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/cloudsync_sa/transport/softbus/softbus_session_test.cpp b/cloud_file/test/unittests/cloudsync_sa/transport/softbus/softbus_session_test.cpp new file mode 100644 index 0000000..ca2f2d3 --- /dev/null +++ b/cloud_file/test/unittests/cloudsync_sa/transport/softbus/softbus_session_test.cpp @@ -0,0 +1,273 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "cloud_sync_common.h" +#include "dfs_error.h" +#include "softbus_adapter.h" +#include "softbus_session.h" +#include "socket_mock.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement::CloudSync { +namespace Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +constexpr int32_t HEAD_SIZE = 3; +constexpr int32_t END_SIZE = 3; +constexpr const char *REPLACE_CHAIN = "***"; +constexpr const char *DEFAULT_ANONYMOUS = "******"; + +class SoftbusSessionTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr socketMock_ = nullptr; +}; + +void SoftbusSessionTest::SetUpTestCase(void) +{ + std::cout << "SetUpTestCase" << std::endl; + socketMock_ = make_shared(); + Storage::DistributedFile::SocketMock::dfsSocket = socketMock_; +} + +void SoftbusSessionTest::TearDownTestCase(void) +{ + std::cout << "TearDownTestCase" << std::endl; + Storage::DistributedFile::SocketMock::dfsSocket = nullptr; + socketMock_ = nullptr; +} + +void SoftbusSessionTest::SetUp(void) +{ + std::cout << "SetUp" << std::endl; +} + +void SoftbusSessionTest::TearDown(void) +{ + std::cout << "TearDown" << std::endl; +} + +/** + * @tc.name: StartTest001 + * @tc.desc: Verify the Start function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SoftbusSessionTest, StartTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartTest001 start"; + try { + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(softbusSession != nullptr); + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(-1)); + int32_t result = softbusSession->Start(); + EXPECT_NE(result, 0); + result = softbusSession->Stop(); + EXPECT_EQ(result, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartTest001 failed"; + } + GTEST_LOG_(INFO) << "StartTest001 end"; +} + +/** + * @tc.name: SendDataTest001 + * @tc.desc: Verify the SendData function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SoftbusSessionTest, SendDataTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SendDataTest001 start"; + try { + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(softbusSession != nullptr); + int32_t result = softbusSession->SendData(data, sizeof(data)); + EXPECT_NE(result, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SendDataTest001 failed"; + } + GTEST_LOG_(INFO) << "SendDataTest001 end"; +} + +/** + * @tc.name: SendFileTest001 + * @tc.desc: Verify the SendFile function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SoftbusSessionTest, SendFileTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SendFileTest001 start"; + try { + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(softbusSession != nullptr); + int32_t result = softbusSession->SendFile({"data/test"}, {"data/test"}); + EXPECT_EQ(result, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SendFileTest001 failed"; + } + GTEST_LOG_(INFO) << "SendFileTest001 end"; +} + +/** + * @tc.name: ToBeAnonymousTest001 + * @tc.desc: Verify the ToBeAnonymous function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SoftbusSessionTest, ToBeAnonymousTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToBeAnonymousTest001 start"; + try { + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(softbusSession != nullptr); + SoftbusSession::DataType dataType = softbusSession->GetDataType(); + EXPECT_TRUE(dataType == SoftbusSession::TYPE_BYTES); + string deviceId = softbusSession->GetPeerDeviceId(); + EXPECT_TRUE(deviceId == "test peerNetworkId"); + EXPECT_EQ(softbusSession->ToBeAnonymous(deviceId), "tes***kId"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToBeAnonymousTest001 failed"; + } + GTEST_LOG_(INFO) << "ToBeAnonymousTest001 end"; +} + +/** + * @tc.name: WaitSessionOpenedTest001 + * @tc.desc: Verify the WaitSessionOpened function + * @tc.type: FUNC + * @tc.require: IB3T9R + */ +HWTEST_F(SoftbusSessionTest, WaitSessionOpenedTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "WaitSessionOpenedTest001 start"; + try { + char data[] = "test data"; + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + EXPECT_TRUE(softbusSession != nullptr); + int32_t sessionId = softbusSession->GetSessionId(); + SoftbusAdapter::GetInstance().AcceptSesion(sessionId, "test session", peerNetworkId); + int32_t result = softbusSession->WaitSessionOpened(sessionId); + EXPECT_EQ(result, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "WaitSessionOpenedTest001 failed"; + } + GTEST_LOG_(INFO) << "WaitSessionOpenedTest001 end"; +} + +HWTEST_F(SoftbusSessionTest, StartTest002, TestSize.Level1) +{ + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + softbusSession->sessionId_ = 0; + auto res = softbusSession->Start(); + EXPECT_EQ(res, E_OK); +} + +HWTEST_F(SoftbusSessionTest, StartTest003, TestSize.Level1) +{ + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + EXPECT_CALL(*socketMock_, Socket(_)).WillOnce(Return(1)); + auto res = softbusSession->Start(); + EXPECT_EQ(res, E_OK); +} + +HWTEST_F(SoftbusSessionTest, WaitSessionOpenedTest002, TestSize.Level1) +{ + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + int sessionId = 0; + auto res = softbusSession->WaitSessionOpened(sessionId); + EXPECT_EQ(res, E_WAIT_SESSION_OPENED); +} + +HWTEST_F(SoftbusSessionTest, WaitSessionOpenedTest003, TestSize.Level1) +{ + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + int sessionId = 0; + SoftbusAdapter::GetInstance().AcceptSesion(sessionId, "", ""); + auto res = softbusSession->WaitSessionOpened(sessionId); + EXPECT_EQ(res, E_OK); +} + +HWTEST_F(SoftbusSessionTest, ToBeAnonymousTest002, TestSize.Level1) +{ + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + + std::string name = ""; + auto res = softbusSession->ToBeAnonymous(name); + EXPECT_EQ(res, DEFAULT_ANONYMOUS); +} + +HWTEST_F(SoftbusSessionTest, ToBeAnonymousTest003, TestSize.Level1) +{ + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + + std::string name = "test"; + auto res = softbusSession->ToBeAnonymous(name); + EXPECT_EQ(res, (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN)); +} + +HWTEST_F(SoftbusSessionTest, ToBeAnonymousTest004, TestSize.Level1) +{ + string peerNetworkId = "test peerNetworkId"; + auto type = SoftbusSession::TYPE_BYTES; + auto softbusSession = make_shared(peerNetworkId, "test session", type); + + std::string name = "test name"; + auto res = softbusSession->ToBeAnonymous(name); + EXPECT_EQ(res, (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN + name.substr(name.length() - END_SIZE, END_SIZE))); +} +} // namespace Test +} // namespace CloudSync +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/resource/cloud_disk_data_handler_test.txt b/cloud_file/test/unittests/resource/cloud_disk_data_handler_test.txt new file mode 100644 index 0000000..4b01280 --- /dev/null +++ b/cloud_file/test/unittests/resource/cloud_disk_data_handler_test.txt @@ -0,0 +1,15 @@ +/* + * 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. + */ + cloud_disk_data_handler_test.txt \ No newline at end of file diff --git a/cloud_file/test/unittests/resource/cloud_disk_data_handler_test1.txt b/cloud_file/test/unittests/resource/cloud_disk_data_handler_test1.txt new file mode 100644 index 0000000..83f35d1 --- /dev/null +++ b/cloud_file/test/unittests/resource/cloud_disk_data_handler_test1.txt @@ -0,0 +1,15 @@ +/* + * 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. + */ + cloud_disk_data_handler_test1.txt \ No newline at end of file diff --git a/cloud_file/test/unittests/resource/ohos_test.xml b/cloud_file/test/unittests/resource/ohos_test.xml new file mode 100644 index 0000000..648f860 --- /dev/null +++ b/cloud_file/test/unittests/resource/ohos_test.xml @@ -0,0 +1,23 @@ + + + + + + + + \ No newline at end of file diff --git a/cloud_file/test/unittests/services_daemon/BUILD.gn b/cloud_file/test/unittests/services_daemon/BUILD.gn new file mode 100644 index 0000000..3b3459f --- /dev/null +++ b/cloud_file/test/unittests/services_daemon/BUILD.gn @@ -0,0 +1,309 @@ +# Copyright (C) 2023-2024 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. + +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("fuse_manager_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp", + "${cloud_file_path}/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp", + "fuse_manager_test.cpp", + "mock/libfuse_mock.cpp", + "mock/system_function_mock.cpp", + ] + cloud_disk = [ + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp", + "${cloud_file_path}/services/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status.cpp", + ] + + sources += cloud_disk + + include_dirs = [ + "${cloud_file_path}/services/cloudfiledaemon/include", + "${cloud_file_path}/services/cloudfiledaemon/include/fuse_manager", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${clouddisk_database_path}/include", + "${cloud_file_path}/test/unittests/services_daemon/mock", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CloudFileDaemon\"", + "strdup=StrdupMock", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_unittest("cloud_daemon_statistic_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp", + "cloud_daemon_statistic_test.cpp", + ] + + cloud_disk = [ + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp", + ] + + sources += cloud_disk + + include_dirs = [ + "${cloud_file_path}/services/cloudfiledaemon/include", + "${cloud_file_path}/services/cloudfiledaemon/include/fuse_manager", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${clouddisk_database_path}/include", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CloudFileDaemon\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_unittest("cloud_daemon_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp", + "${cloud_file_path}/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp", + "${cloud_file_path}/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp", + "${cloud_file_path}/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp", + "cloud_daemon_test.cpp", + "mock/system_function_mock.cpp", + ] + + cloud_disk = [ + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp", + "${cloud_file_path}/services/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp", + ] + + sources += cloud_disk + + include_dirs = [ + "${cloud_file_path}/services/cloudfiledaemon/include", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + "${clouddisk_database_path}/include", + "${cloud_file_path}/test/unittests/services_daemon/mock", + "${cloud_file_path}/services/cloudfiledaemon/include/fuse_manager", + "${cloud_file_path}/interfaces/inner_api/native", + "${cloud_file_path}/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics", + "${utils_path}/cloud_disk/include", + "${utils_path}/dentry/include", + "${utils_path}/log/include", + "${utils_path}/system/include", + "${innerkits_native_path}/cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${services_path}/cloudfiledaemon/include/fuse_manager/", + "${services_path}/cloudfiledaemon/include/ipc/", + "${services_path}/cloudsyncservice/include/data_sync/", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit_core", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (cloudsync_service_media_library) { + external_deps += [ "media_library:media_library" ] + } + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CloudFileDaemon\"", + "access=AccessMock", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} + +ohos_unittest("cloud_daemon_stub_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp", + "cloud_daemon_stub_test.cpp", + ] + + include_dirs = [ + "${cloud_file_path}/services/cloudfiledaemon/include", + "${services_path}/cloudsyncservice/include/data_sync/", + "${cloud_file_path}/adapter/cloud_adapter_example/include", + ] + + deps = [ + "${innerkits_native_path}/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "libfuse:libfuse", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CloudFileDaemon\"", + ] + + use_exceptions = true + part_name = "cloud_file" + subsystem_name = "kernel" +} + +group("services_daemon_test") { + testonly = true + + deps = [ + ":cloud_daemon_statistic_test", + ":cloud_daemon_stub_test", + ":cloud_daemon_test", + ":fuse_manager_test", + ] +} diff --git a/cloud_file/test/unittests/services_daemon/cloud_daemon_statistic_test.cpp b/cloud_file/test/unittests/services_daemon/cloud_daemon_statistic_test.cpp new file mode 100644 index 0000000..1c61c97 --- /dev/null +++ b/cloud_file/test/unittests/services_daemon/cloud_daemon_statistic_test.cpp @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2024 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 "cloud_daemon_statistic.h" + +#include +#include + +namespace OHOS::FileManagement::CloudFile::test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +#define MODEL_TIME 20240710 +#define MODEL_TYPE 1 +#define MODEL_SIZE 12 + +class CloudDaemonStatisticTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudDaemonStatisticTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudDaemonStatisticTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDaemonStatisticTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDaemonStatisticTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +HWTEST_F(CloudDaemonStatisticTest, CloudDaemonStatisticTest_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_001 Start"; + try { + CloudDaemonStatistic::GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_001 ERROR"; + } + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_001 End"; +} + +HWTEST_F(CloudDaemonStatisticTest, CloudDaemonStatisticTest_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_002 Start"; + try { + CloudDaemonStatistic::GetInstance().UpdateStatData(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_002 ERROR"; + } + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_002 End"; +} + +HWTEST_F(CloudDaemonStatisticTest, CloudDaemonStatisticTest_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_003 Start"; + CloudDaemonStatistic cds; + try { + cds.UpdateOpenSizeStat(MODEL_SIZE); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_003 ERROR"; + } + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_003 End"; +} + +HWTEST_F(CloudDaemonStatisticTest, CloudDaemonStatisticTest_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_004 Start"; + CloudDaemonStatistic cds; + try { + cds.UpdateReadSizeStat(MODEL_SIZE); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_004 ERROR"; + } + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_004 End"; +} + +HWTEST_F(CloudDaemonStatisticTest, CloudDaemonStatisticTest_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_005 Start"; + CloudDaemonStatistic cds; + try { + cds.UpdateReadTimeStat(MODEL_TYPE, MODEL_TIME); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_005 ERROR"; + } + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_005 End"; +} + +HWTEST_F(CloudDaemonStatisticTest, CloudDaemonStatisticTest_006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_006 Start"; + CloudDaemonStatistic cds; + try { + cds.UpdateStatData(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_006 ERROR"; + } + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_006 End"; +} + +HWTEST_F(CloudDaemonStatisticTest, CloudDaemonStatisticTest_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_007 Start"; + CloudDaemonStatistic &readStat = CloudDaemonStatistic::GetInstance(); + try { + readStat.UpdateOpenTimeStat(MODEL_TYPE, MODEL_TIME); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_007 ERROR"; + } + GTEST_LOG_(INFO) << "CloudDaemonStatisticTest_007 End"; +} +} \ No newline at end of file diff --git a/cloud_file/test/unittests/services_daemon/cloud_daemon_stub_test.cpp b/cloud_file/test/unittests/services_daemon/cloud_daemon_stub_test.cpp new file mode 100644 index 0000000..a1d7a00 --- /dev/null +++ b/cloud_file/test/unittests/services_daemon/cloud_daemon_stub_test.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2023-2024 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 "cloud_file_daemon_interface_code.h" +#include "ipc/cloud_daemon_stub.h" +#include "utils_log.h" + +#include +#include + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class MockCloudDaemonStub : public CloudDaemonStub { +public: + MOCK_METHOD3(StartFuse, int32_t(int32_t userId, int32_t deviceFd, const std::string &path)); +}; + +class CloudDaemonStubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr cloudDaemonStub_; +}; + +void CloudDaemonStubTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudDaemonStubTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDaemonStubTest::SetUp(void) +{ + cloudDaemonStub_ = std::make_shared(); + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDaemonStubTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: OnRemoteRequestTest001 + * @tc.desc: Verify the OnRemoteRequest function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonStubTest, OnRemoteRequestTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequestTest Start"; + try { + MessageParcel data; + MessageParcel reply; + MessageOption option; + int ret = cloudDaemonStub_->OnRemoteRequest( + static_cast(CloudFileDaemonInterfaceCode::CLOUD_DAEMON_CMD_START_FUSE), data, reply, option); + EXPECT_EQ(ret, ICloudDaemon::CLOUD_DAEMON_DESCRIPTOR_IS_EMPTY); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnRemoteRequestTest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequestTest End"; +} + +/** + * @tc.name: OnRemoteRequestTest002 + * @tc.desc: Verify the OnRemoteRequest function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonStubTest, OnRemoteRequestTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequestTest Start"; + try { + int32_t code = 1000; + MessageParcel data; + EXPECT_TRUE(data.WriteInterfaceToken(ICloudDaemon::GetDescriptor())); + MessageParcel reply; + MessageOption option; + int ret = cloudDaemonStub_->OnRemoteRequest(code, data, reply, option); + EXPECT_NE(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnRemoteRequestTest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequestTest End"; +} + +/** + * @tc.name: OnRemoteRequestTest003 + * @tc.desc: Verify the OnRemoteRequest function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonStubTest, OnRemoteRequestTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequestTest Start"; + try { + MessageParcel data; + EXPECT_TRUE(data.WriteInterfaceToken(ICloudDaemon::GetDescriptor())); + MessageParcel reply; + MessageOption option; + int ret = cloudDaemonStub_->OnRemoteRequest( + static_cast(CloudFileDaemonInterfaceCode::CLOUD_DAEMON_CMD_START_FUSE), data, reply, option); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnRemoteRequestTest ERROR"; + } + GTEST_LOG_(INFO) << "OnRemoteRequestTest End"; +} + +/** + * @tc.name: HandleStartFuseInnerTest001 + * @tc.desc: Verify the HandleStartFuseInner function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(CloudDaemonStubTest, HandleStartFuseInnerTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "HandleStartFuseInnerTest start"; + try { + MessageParcel data; + MessageParcel reply; + int ret = cloudDaemonStub_->HandleStartFuseInner(data, reply); + EXPECT_EQ(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "HandleStartFuseInnerTest failed"; + } + GTEST_LOG_(INFO) << "HandleStartFuseInnerTest end"; +} + +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/services_daemon/cloud_daemon_test.cpp b/cloud_file/test/unittests/services_daemon/cloud_daemon_test.cpp new file mode 100644 index 0000000..4d71cdb --- /dev/null +++ b/cloud_file/test/unittests/services_daemon/cloud_daemon_test.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2023-2024 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 +#include + +#include "dfs_error.h" +#include "fuse_assistant.h" +#include "fuse_manager/fuse_manager.h" +#include "ipc/cloud_daemon.h" +#include "iremote_object.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +constexpr int32_t USER_ID = 100; +constexpr int32_t DEV_FD = 10; + +class CloudDaemonTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr cloudDaemon_; + static inline shared_ptr insMock_ = nullptr; +}; + +void CloudDaemonTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudDaemonTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDaemonTest::SetUp(void) +{ + int32_t saID = FILEMANAGEMENT_CLOUD_DAEMON_SERVICE_SA_ID; + bool runOnCreate = true; + insMock_ = make_shared(); + FuseAssistantMock::ins = insMock_; + cloudDaemon_ = std::make_shared(saID, runOnCreate); + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDaemonTest::TearDown(void) +{ + FuseAssistantMock::ins = nullptr; + insMock_ = nullptr; + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: OnStopTest + * @tc.desc: Verify the OnStop function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonTest, OnStopTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnStop Start"; + try { + cloudDaemon_->state_ = ServiceRunningState::STATE_NOT_START; + cloudDaemon_->registerToService_ = false; + cloudDaemon_->OnStop(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnStop ERROR"; + } + GTEST_LOG_(INFO) << "OnStop End"; +} + +/** + * @tc.name: OnStartTest1 + * @tc.desc: Verify the OnStart function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonTest, OnStartTest1, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnStart1 Start"; + try { + cloudDaemon_->state_ = ServiceRunningState::STATE_RUNNING; + cloudDaemon_->OnStart(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnStart1 ERROR"; + } + GTEST_LOG_(INFO) << "OnStart1 End"; +} + +/** + * @tc.name: OnStartTest2 + * @tc.desc: Verify the OnStart function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudDaemonTest, OnStartTest2, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnStart2 Start"; + try { + cloudDaemon_->state_ = ServiceRunningState::STATE_NOT_START; + cloudDaemon_->registerToService_ = true; + cloudDaemon_->OnStart(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnStart2 ERROR"; + } + GTEST_LOG_(INFO) << "OnStart2 End"; +} + +/** + * @tc.name: StartFuseTest001 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(CloudDaemonTest, StartFuseTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest001 start"; + std::cout << "StartFuseTest001 Start" << std::endl; + try { + const char* path = "/cloud/test"; + int32_t ret = cloudDaemon_->StartFuse(USER_ID, DEV_FD, path); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest001 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest001 end"; +} + +/** + * @tc.name: StartFuseTest002 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(CloudDaemonTest, StartFuseTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest002 start"; + try { + std::string path = "/cloud/test"; + EXPECT_CALL(*insMock_, mkdir(_, _)).WillRepeatedly(Return(-1)); + int32_t ret = cloudDaemon_->StartFuse(USER_ID, DEV_FD, path); + EXPECT_EQ(ret, E_PATH); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest002 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest002 end"; +} + +/** + * @tc.name: StartFuseTest003 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(CloudDaemonTest, StartFuseTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest003 start"; + try { + std::string path = "/cloud/test"; + EXPECT_CALL(*insMock_, mkdir(_, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(*insMock_, chmod(_, _)).WillRepeatedly(Return(-1)); + int32_t ret = cloudDaemon_->StartFuse(USER_ID, DEV_FD, path); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest003 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest003 end"; +} + +/** + * @tc.name: StartFuseTest004 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(CloudDaemonTest, StartFuseTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest004 start"; + try { + std::string path = "/cloud/test"; + EXPECT_CALL(*insMock_, mkdir(_, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(*insMock_, chown(_, _, _)).WillRepeatedly(Return(-1)); + int32_t ret = cloudDaemon_->StartFuse(USER_ID, DEV_FD, path); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest004 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest004 end"; +} + +/** + * @tc.name: StartFuseTest007 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(CloudDaemonTest, StartFuseTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest007 start"; + try { + std::string path = "/cloud_fuse/test"; + EXPECT_CALL(*insMock_, mkdir(_, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(*insMock_, HandleStartMove(_)).WillRepeatedly(Return()); + int32_t ret = cloudDaemon_->StartFuse(USER_ID, DEV_FD, path); + EXPECT_EQ(ret, E_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest007 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest007 end"; +} + +/** + * @tc.name: OnAddSystemAbilityTest001 + * @tc.desc: Verify the OnStart function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(CloudDaemonTest, OnAddSystemAbility001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnAddSystemAbility001 start"; + try { + const int32_t systemAbilityId = 100; + const std::string deviceId = "device_test"; + cloudDaemon_->OnAddSystemAbility(systemAbilityId, deviceId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest001 failed"; + } + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest001 end"; +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/services_daemon/fuse_manager_test.cpp b/cloud_file/test/unittests/services_daemon/fuse_manager_test.cpp new file mode 100644 index 0000000..109421c --- /dev/null +++ b/cloud_file/test/unittests/services_daemon/fuse_manager_test.cpp @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2023-2024 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 +#include +#include +#include +#include + +#include "dfs_error.h" +#include "fuse_assistant.h" +#include "fuse_manager/fuse_manager.h" +#include "fuse_i.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +constexpr int32_t USER_ID = 100; +class FuseManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr fuseManager_; + static inline shared_ptr insMock_ = nullptr; +}; + +void FuseManagerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void FuseManagerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void FuseManagerTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + insMock_ = make_shared(); + FuseAssistantMock::ins = insMock_; + fuseManager_ = std::make_shared(); +} + +void FuseManagerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; + FuseAssistantMock::ins = nullptr; + insMock_ = nullptr; +} + +/** + * @tc.name: GetInstanceTest + * @tc.desc: Verify the GetInstance function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(FuseManagerTest, GetInstanceTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest start"; + try { + FuseManager::GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest failed"; + } + GTEST_LOG_(INFO) << "GetInstanceTest end"; +} + +/** + * @tc.name: StartFuseTest001 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest001 start"; + try { + std::unique_ptr fs = std::make_unique(); + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*insMock_, fuse_session_new(_, _, _, _)).WillOnce(Return(fs.get())); + EXPECT_CALL(*insMock_, fuse_session_destroy(fs.get())).WillOnce(Return()); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/data/100/cloud_fuse"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest001 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest001 end"; +} + +/** + * @tc.name: StartFuseTest002 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest002 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(-1)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/data/100/cloud_fuse"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest002 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest002 end"; +} + +/** + * @tc.name: StartFuseTest003 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest003 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*insMock_, fuse_session_new(_, _, _, _)).WillOnce(Return(nullptr)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/data/100/cloud_fuse"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest003 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest003 end"; +} + +/** + * @tc.name: StartFuseTest004 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest004 start"; + try { + std::unique_ptr fs = std::make_unique(); + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*insMock_, fuse_session_new(_, _, _, _)).WillOnce(Return(fs.get())); + EXPECT_CALL(*insMock_, fuse_session_destroy(fs.get())).WillOnce(Return()); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/data/100/cloud"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest004 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest004 end"; +} + +/** + * @tc.name: StartFuseTest005 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest005 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(-1)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/data/100/cloud"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest005 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest005 end"; +} + +/** + * @tc.name: StartFuseTest006 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest006 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*insMock_, fuse_session_new(_, _, _, _)).WillOnce(Return(nullptr)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/data/100/cloud"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest006 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest006 end"; +} + +/** + * @tc.name: StartFuseTest007 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest007 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/invalid/data/100/cloud_fuse"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest007 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest007 end"; +} + +/** + * @tc.name: StartFuseTest008 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest008 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/other/100/cloud_fuse"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest008 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest008 end"; +} + +/** + * @tc.name: StartFuseTest009 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest009 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/data/abcd/cloud_fuse"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest009 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest009 end"; +} + +/** + * @tc.name: StartFuseTest010 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest010 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "/mnt/data/100/invalid_suffix"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest010 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest010 end"; +} + +/** + * @tc.name: StartFuseTest011 + * @tc.desc: Verify the StartFuse function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(FuseManagerTest, StartFuseTest011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StartFuseTest011 start"; + try { + EXPECT_CALL(*insMock_, fuse_opt_add_arg(_, _)).WillOnce(Return(0)); + int32_t devFd = open("/dev/fuse", O_RDWR); + string path = "\0"; + int ret = fuseManager_->StartFuse(USER_ID, devFd, path); + close(devFd); + EXPECT_EQ(ret, -EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StartFuseTest011 failed"; + } + GTEST_LOG_(INFO) << "StartFuseTest011 end"; +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/services_daemon/mock/fuse_assistant.h b/cloud_file/test/unittests/services_daemon/mock/fuse_assistant.h new file mode 100644 index 0000000..9153952 --- /dev/null +++ b/cloud_file/test/unittests/services_daemon/mock/fuse_assistant.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2024 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 TEST_UNITTESTS_CLOUD_FILE_FUSEASSISTANT_H +#define TEST_UNITTESTS_CLOUD_FILE_FUSEASSISTANT_H +#ifndef FUSE_USE_VERSION +#define FUSE_USE_VERSION 30 +#endif + +#include +#include +#include +#include + +namespace OHOS::FileManagement::CloudFile { +class FuseAssistant { +public: + virtual ~FuseAssistant() = default; + virtual int fuse_opt_add_arg(struct fuse_args *args, const char *arg) = 0; + virtual struct fuse_session* fuse_session_new(struct fuse_args *args, const struct fuse_lowlevel_ops *op, + size_t opSize, void *userData) = 0; + virtual void fuse_session_destroy(struct fuse_session *se) = 0; + virtual int mkdir(const char* path, mode_t mode) = 0; + virtual int chown(const char *path, uid_t owner, gid_t group) = 0; + virtual int chmod(const char *path, mode_t mode) = 0; + virtual void HandleStartMove(int32_t userId) = 0; + static inline std::shared_ptr ins = nullptr; +}; + +class FuseAssistantMock : public FuseAssistant { +public: + MOCK_METHOD2(fuse_opt_add_arg, int(struct fuse_args *args, const char *arg)); + MOCK_METHOD4(fuse_session_new, struct fuse_session*(struct fuse_args *args, const struct fuse_lowlevel_ops *op, + size_t opSize, void *userData)); + MOCK_METHOD1(fuse_session_destroy, void(struct fuse_session *se)); + MOCK_METHOD2(mkdir, int(const char* path, mode_t mode)); + MOCK_METHOD3(chown, int(const char * path, uid_t owner, gid_t group)); + MOCK_METHOD2(chmod, int(const char * path, mode_t mode)); + MOCK_METHOD1(HandleStartMove, void(int32_t userId)); +}; +} // namespace OHOS::FileManagement::CloudDisk +#endif // TEST_UNITTESTS_CLOUD_FILE_FUSEASSISTANT_H \ No newline at end of file diff --git a/cloud_file/test/unittests/services_daemon/mock/libfuse_mock.cpp b/cloud_file/test/unittests/services_daemon/mock/libfuse_mock.cpp new file mode 100644 index 0000000..cd70166 --- /dev/null +++ b/cloud_file/test/unittests/services_daemon/mock/libfuse_mock.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2024 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 "file_operations_base.h" +#include "fuse_assistant.h" + +using namespace OHOS::FileManagement::CloudFile; +int fuse_opt_add_arg(struct fuse_args *args, const char *arg) +{ + return FuseAssistant::ins->fuse_opt_add_arg(args, arg); +} + +struct fuse_session* fuse_session_new(struct fuse_args *args, const struct fuse_lowlevel_ops *op, + size_t opSize, void *userData) +{ + return FuseAssistant::ins->fuse_session_new(args, op, opSize, userData); +} + +void fuse_session_destroy(struct fuse_session *se) +{ + FuseAssistant::ins->fuse_session_destroy(se); +} + +void HandleStartMove(int32_t userId) +{ + FuseAssistant::ins->HandleStartMove(userId); +} diff --git a/cloud_file/test/unittests/services_daemon/mock/system_function_mock.cpp b/cloud_file/test/unittests/services_daemon/mock/system_function_mock.cpp new file mode 100644 index 0000000..4c18857 --- /dev/null +++ b/cloud_file/test/unittests/services_daemon/mock/system_function_mock.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2024 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 +#include +#include +#include + +#include "file_operations_base.h" +#include "fuse_assistant.h" +#include "securec.h" + +using namespace OHOS::FileManagement::CloudFile; + +int mkdir(const char *path, mode_t mode) +{ + return FuseAssistant::ins->mkdir(path, mode); +} + +int chown(const char *path, uid_t owner, gid_t group) +{ + return FuseAssistant::ins->chown(path, owner, group); +} + +int chmod(const char *path, mode_t mode) +{ + return FuseAssistant::ins->chmod(path, mode); +} + +int AccessMock(const char *name, int type) +{ + if (name == nullptr) { + return 0; + } + const char *dentryPath = "/data/service/el2/100/hmdfs/cache/account_cache/dentry_cache/cloud"; + if (strcmp(name, dentryPath) == 0) { + return -1; + } + return 0; +} + +char* StrdupMock(const char *path) +{ + const char *str1 = "/mnt/data/234/cloud"; + const char *str2 = "/mnt/data/234/cloud_fuse"; + if (path == nullptr) { + return nullptr; + } + if (strcmp(path, str1) == 0 || strcmp(path, str2) == 0) { + return nullptr; + } + size_t len = strlen(path); + if (len <= 0) { + return nullptr; + } + char* dstStr = static_cast(malloc(len + 1)); + if (dstStr == nullptr) { + return nullptr; + } + if (memcpy_s(dstStr, len + 1, path, len + 1) != 0) { + free(dstStr); + dstStr = nullptr; + return nullptr; + } + return dstStr; +} \ No newline at end of file diff --git a/cloud_file/test/unittests/utils/BUILD.gn b/cloud_file/test/unittests/utils/BUILD.gn new file mode 100644 index 0000000..031151c --- /dev/null +++ b/cloud_file/test/unittests/utils/BUILD.gn @@ -0,0 +1,214 @@ +# Copyright (C) 2023-2024 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. +import("//build/test.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +ohos_unittest("cloud_pref_impl_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ + "${cloud_file_path}/utils/preference/src/cloud_pref_impl.cpp", + "./preference/cloud_pref_impl_test.cpp", + ] + + include_dirs = [ + "${services_path}/cloudsyncservice/include/ipc", + "${cloud_file_path}/test/unittests/cloudsync_api/cloudsync_impl/include", + "${cloud_file_path}/frameworks/native/cloudsync_kit_inner/include", + "${cloud_file_path}/utils/dentry/include", + "${cloud_file_path}/utils/log/include", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "cloud_file:cloudsync_kit_inner", + "hilog:libhilog", + "ipc:ipc_single", + "preferences:native_preferences", + ] + + defines = [ "private=public" ] + + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"UTILS\"", + ] + + use_exceptions = true +} + +ohos_unittest("utils_directory_test") { + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${cloud_file_path}/cfi_blocklist.txt" + } + + module_out_path = "cloud_file/cloud_file" + + sources = [ "./system/utils_directory_test.cpp" ] + + include_dirs = [ + "${utils_path}/system/include", + "${utils_path}/log/include", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + "json:nlohmann_json_static", + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + use_exceptions = true +} + +ohos_unittest("cloud_file_utils_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "./cloud_disk/cloud_file_utils_test.cpp" ] + + include_dirs = [ + "${utils_path}/cloud_disk/include", + "${utils_path}/log/include", + ] + + deps = [ + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "image_framework:image_native", + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + use_exceptions = true +} + +ohos_unittest("plugin_loader_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "./load/plugin_loader_test.cpp" ] + + include_dirs = [ + "${utils_path}/load/include", + "${utils_path}/load/src", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "c_utils:utils", + "hilog:libhilog", + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"UTILS\"", + ] + + use_exceptions = true +} + +ohos_unittest("async_work_test") { + module_out_path = "cloud_file/cloud_file" + + sources = [ "./work/async_work_test.cpp" ] + + include_dirs = [ + "${utils_path}/work/include", + "${utils_path}/work/src", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "c_utils:utils", + "device_manager:devicemanagersdk", + "ffrt:libffrt", + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "napi:ace_napi", + "preferences:native_preferences", + ] + + defines = [ "private=public" ] + defines += [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"UTILS\"", + ] + + use_exceptions = true +} + +group("utils_test") { + testonly = true + + deps = [ + ":async_work_test", + ":cloud_file_utils_test", + ":cloud_pref_impl_test", + ":plugin_loader_test", + ":utils_directory_test", + ] +} diff --git a/cloud_file/test/unittests/utils/cloud_disk/cloud_file_utils_test.cpp b/cloud_file/test/unittests/utils/cloud_disk/cloud_file_utils_test.cpp new file mode 100644 index 0000000..9a0928d --- /dev/null +++ b/cloud_file/test/unittests/utils/cloud_disk/cloud_file_utils_test.cpp @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "cloud_file_utils.h" + +namespace OHOS::FileManagement::CloudDisk::Test { +using namespace std; +using namespace OHOS; +using namespace testing::ext; + +class CloudFileUtilsTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CloudFileUtilsTest::SetUpTestCase(void) {} + +void CloudFileUtilsTest::TearDownTestCase(void) {} + +void CloudFileUtilsTest::SetUp(void) {} + +void CloudFileUtilsTest::TearDown(void) {} + +/** + * @tc.name: DfsService_CloudDisk_GetCloudId_001 + * @tc.desc: Verify the sub function. + * @tc.type: FUNC + * @tc.require: issueNumber + */ +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_GetCloudId_001, TestSize.Level1) +{ + string cloudId = CloudFileUtils::GetCloudId(""); + EXPECT_EQ((cloudId == ""), true); + + cloudId = CloudFileUtils::GetCloudId("test"); + EXPECT_EQ((cloudId == ""), true); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_GetLocalBucketPath_002, TestSize.Level1) +{ + string cloudId; + string bundleName; + int32_t userId = -1; + string bucketPath = CloudFileUtils::GetLocalBucketPath(cloudId, bundleName, userId); + EXPECT_EQ((cloudId == ""), true); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_GetLocalBucketPath_003, TestSize.Level1) +{ + string cloudId = "testId"; + string bundleName = "testBundleName"; + int32_t userId = -1; + string bucketPath = CloudFileUtils::GetLocalBucketPath(cloudId, bundleName, userId); + EXPECT_EQ((cloudId == ""), false); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_CheckIsCloud_004, TestSize.Level1) +{ + string key; + EXPECT_EQ(CloudFileUtils::CheckIsCloud(key), false); + + key = CLOUD_CLOUD_ID_XATTR; + EXPECT_EQ(CloudFileUtils::CheckIsCloud(key), true); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_CheckIsCloudLocation_005, TestSize.Level1) +{ + string key; + EXPECT_EQ(CloudFileUtils::CheckIsCloudLocation(key), false); + + key = CLOUD_FILE_LOCATION; + EXPECT_EQ(CloudFileUtils::CheckIsCloudLocation(key), true); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_CheckIsHmdfsPermission_006, TestSize.Level1) +{ + string key; + EXPECT_EQ(CloudFileUtils::CheckIsHmdfsPermission(key), false); + + key = HMDFS_PERMISSION_XATTR; + EXPECT_EQ(CloudFileUtils::CheckIsHmdfsPermission(key), true); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_GetLocalFilePath_007, TestSize.Level1) +{ + string cloudId; + string bundleName; + int32_t userId = 0; + string ret = CloudFileUtils::GetLocalFilePath(cloudId, bundleName, userId); + EXPECT_EQ((ret == ""), false); + + userId = -1; + ret = CloudFileUtils::GetLocalFilePath(cloudId, bundleName, userId); + EXPECT_EQ((ret == ""), false); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_GetPathWithoutTmp_008, TestSize.Level1) +{ + string path; + string ret = CloudFileUtils::GetPathWithoutTmp(path); + EXPECT_EQ(ret, path); + + path = "path/test"; + ret = CloudFileUtils::GetPathWithoutTmp(path); + EXPECT_EQ(ret, path); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_LocalWriteOpen_009, TestSize.Level1) +{ + string dfsPath; + EXPECT_EQ(CloudFileUtils::LocalWriteOpen(dfsPath), false); + + dfsPath = "testPath"; + EXPECT_EQ(CloudFileUtils::LocalWriteOpen(dfsPath), false); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_EndsWith_010, TestSize.Level1) +{ + string fullString; + string ending; + EXPECT_EQ(CloudFileUtils::EndsWith(fullString, ending), true); + + fullString = "testPath"; + EXPECT_EQ(CloudFileUtils::EndsWith(fullString, ending), true); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_EndsWith_011, TestSize.Level1) +{ + string fullString = "testPath"; + string ending = "test@@text##"; + EXPECT_EQ(CloudFileUtils::EndsWith(fullString, ending), false); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_DentryHash_012, TestSize.Level1) +{ + try { + string inputStr = "."; + EXPECT_EQ(CloudFileUtils::DentryHash(inputStr), 0); + + inputStr = ".."; + EXPECT_EQ(CloudFileUtils::DentryHash(inputStr), 0); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " DfsService_CloudDisk_DentryHash_012 ERROR"; + } +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_LocalWriteOpen_013, TestSize.Level1) +{ + string dfsPath = "./"; + EXPECT_EQ(CloudFileUtils::LocalWriteOpen(dfsPath), false); + + dfsPath = "testPath"; + EXPECT_EQ(CloudFileUtils::LocalWriteOpen(dfsPath), false); +} + +HWTEST_F(CloudFileUtilsTest, DfsService_CloudDisk_GetCloudId_014, TestSize.Level1) +{ + string dfsPath = "/data/service/el1/public/cloudfile"; + string cloudId = CloudFileUtils::GetCloudId(dfsPath); + EXPECT_EQ((cloudId == ""), true); + + dfsPath = "/data/service/el1/public/cloudfile/cloud_data_statistic"; + cloudId = CloudFileUtils::GetCloudId(dfsPath); + EXPECT_EQ((cloudId == ""), true); +} +} // OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/utils/load/plugin_loader_test.cpp b/cloud_file/test/unittests/utils/load/plugin_loader_test.cpp new file mode 100644 index 0000000..1e743ee --- /dev/null +++ b/cloud_file/test/unittests/utils/load/plugin_loader_test.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "plugin_loader.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace std; +using namespace OHOS; +using namespace testing::ext; + +class PluginLoaderTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void PluginLoaderTest::SetUpTestCase(void) {} + +void PluginLoaderTest::TearDownTestCase(void) {} + +void PluginLoaderTest::SetUp(void) {} + +void PluginLoaderTest::TearDown(void) {} + +HWTEST_F(PluginLoaderTest, PluginLoaderTest_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PluginLoaderTest_001 Start"; + try { + PluginLoader pluginLoader; + pluginLoader.GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PluginLoaderTest_001 ERROR"; + } + GTEST_LOG_(INFO) << "PluginLoaderTest_001 End"; +} + +HWTEST_F(PluginLoaderTest, PluginLoaderTest_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PluginLoaderTest_003 Start"; + try { + PluginLoader pluginLoader; + bool isSupportCloudSync = false; + pluginLoader.LoadCloudKitPlugin(isSupportCloudSync); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PluginLoaderTest_003 ERROR"; + } + GTEST_LOG_(INFO) << "PluginLoaderTest_003 End"; +} + +HWTEST_F(PluginLoaderTest, PluginLoaderTest_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PluginLoaderTest_004 Start"; + try { + PluginLoader::GetInstance().LoadCloudKitPlugin(true); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PluginLoaderTest_004 ERROR"; + } + GTEST_LOG_(INFO) << "PluginLoaderTest_004 End"; +} + +HWTEST_F(PluginLoaderTest, PluginLoaderTest_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "PluginLoaderTest_005 Start"; + try { + PluginLoader::GetInstance().LoadCloudKitPlugin(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "PluginLoaderTest_005 ERROR"; + } + GTEST_LOG_(INFO) << "PluginLoaderTest_005 End"; +} +} // OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/utils/preference/cloud_pref_impl_test.cpp b/cloud_file/test/unittests/utils/preference/cloud_pref_impl_test.cpp new file mode 100644 index 0000000..1fd235a --- /dev/null +++ b/cloud_file/test/unittests/utils/preference/cloud_pref_impl_test.cpp @@ -0,0 +1,924 @@ +/* + * 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 +#include + +#include "cloud_pref_impl.h" +#include +#include +#include "utils_log.h" + +#define USERID 100 +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace NativePreferences; + +class PreferencesMock : public Preferences { +public: + MOCK_METHOD2(Get, PreferencesValue(const std::string &key, const PreferencesValue &defValue)); + MOCK_METHOD2(Put, int(const std::string &key, const PreferencesValue &value)); + MOCK_METHOD2(GetInt, int(const std::string &key, const int &defValue)); + MOCK_METHOD2(GetString, std::string(const std::string &key, const std::string &defValue)); + MOCK_METHOD2(GetBool, bool(const std::string &key, const bool &defValue)); + MOCK_METHOD2(GetFloat, float(const std::string &key, const float &defValue)); + MOCK_METHOD2(GetDouble, double(const std::string &key, const double &defValue)); + MOCK_METHOD2(GetLong, int64_t(const std::string &key, const int64_t &defValue)); + MOCK_METHOD0(GetAll, std::map()); + MOCK_METHOD1(HasKey, bool(const std::string &key)); + MOCK_METHOD2(PutInt, int(const std::string &key, int value)); + MOCK_METHOD2(PutString, int(const std::string &key, const std::string &value)); + MOCK_METHOD2(PutBool, int(const std::string &key, bool value)); + MOCK_METHOD2(PutLong, int(const std::string &key, int64_t value)); + MOCK_METHOD2(PutFloat, int(const std::string &key, float value)); + MOCK_METHOD2(PutDouble, int(const std::string &key, double value)); + MOCK_METHOD1(Delete, int(const std::string &key)); + MOCK_METHOD0(Clear, int()); + MOCK_METHOD0(Flush, void()); + MOCK_METHOD0(FlushSync, int()); + MOCK_METHOD2(RegisterObserver, int(std::shared_ptr preferencesObserver, RegisterMode mode)); + MOCK_METHOD2(UnRegisterObserver, int(std::shared_ptr preferencesObserver, RegisterMode mode)); +}; + +class CloudPrefImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + int32_t userId_; + std::string fileName_; + std::shared_ptr cloudPtr_; + static inline std::shared_ptr preferencesMock_; +}; + +void CloudPrefImplTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudPrefImplTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudPrefImplTest::SetUp(void) +{ + userId_ = USERID; + fileName_ = "test"; + cloudPtr_ = std::make_shared(fileName_); + if (cloudPtr_ == nullptr) { + GTEST_LOG_(INFO) << "cloudPtr_ == nullptr"; + } + + preferencesMock_ = std::make_shared(); + if (preferencesMock_ == nullptr) { + GTEST_LOG_(INFO) << "preferencesMock_ == nullptr"; + } + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudPrefImplTest::TearDown(void) +{ + if (cloudPtr_ != nullptr) { + cloudPtr_ = nullptr; + } + + if (preferencesMock_ != nullptr) { + preferencesMock_ = nullptr; + } + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: CloudPrefImplTest001 + * @tc.desc: Verify the CloudPrefImpl function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, CloudPrefImpTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudPrefImpTest001 Start"; + try { + CloudPrefImpl cloudPreImpl(""); + EXPECT_EQ(cloudPreImpl.pref_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CloudPrefImpTest001 ERROR"; + } + GTEST_LOG_(INFO) << "CloudPrefImpTest001 End"; +} + +/** + * @tc.name: CloudPrefImplTest002 + * @tc.desc: Verify the CloudPrefImpl function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, CloudPrefImpTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudPrefImpTest002 Start"; + try { + CloudPrefImpl cloudPreImpl(fileName_); + EXPECT_NE(cloudPreImpl.pref_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CloudPrefImpTest002 ERROR"; + } + GTEST_LOG_(INFO) << "CloudPrefImpTest002 End"; +} + +/** + * @tc.name: CloudPrefImplTest003 + * @tc.desc: Verify the CloudPrefImpl function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, CloudPrefImplTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudPrefImplTest003 Start"; + try { + const std::string bundleName = ""; + std::string fileDir = "/data/service/el1/public/cloudfile/"; + std::string tableName = "testTable"; + EXPECT_EQ(access(fileDir.c_str(), F_OK), 0); + CloudPrefImpl cloudPreImpl(userId_, bundleName, tableName); + EXPECT_NE(cloudPreImpl.pref_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CloudPrefImplTest003 ERROR"; + } + GTEST_LOG_(INFO) << "CloudPrefImplTest003 End"; +} + +/** + * @tc.name: SetStringTest + * @tc.desc: Verify the SetString function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, SetStringTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetStringTest Start"; + try { + EXPECT_NE(cloudPtr_->pref_, nullptr); + std::string key; + std::string value; + cloudPtr_->SetString(key, value); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetStringTest ERROR"; + } + GTEST_LOG_(INFO) << "SetStringTest End"; +} + +/** + * @tc.name: GetStringTest + * @tc.desc: Verify the GetString function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, GetStringTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetStringTest Start"; + try { + EXPECT_NE(cloudPtr_->pref_, nullptr); + std::string key; + std::string value; + cloudPtr_->GetString(key, value); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetStringTest ERROR"; + } + GTEST_LOG_(INFO) << "GetStringTest End"; +} + +/** + * @tc.name: SetIntTest + * @tc.desc: Verify the SetInt function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, SetIntTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetIntTest Start"; + try { + EXPECT_NE(cloudPtr_->pref_, nullptr); + std::string key; + int value = 0; + cloudPtr_->SetInt(key, value); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetIntTest ERROR"; + } + GTEST_LOG_(INFO) << "SetIntTest End"; +} + +/** + * @tc.name: GetIntTest + * @tc.desc: Verify the GetInt function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, GetIntTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetIntTest Start"; + try { + EXPECT_NE(cloudPtr_->pref_, nullptr); + std::string key; + int32_t value = 0; + cloudPtr_->GetInt(key, value); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetIntTest ERROR"; + } + GTEST_LOG_(INFO) << "GetIntTest End"; +} + +/** + * @tc.name: ClearTest + * @tc.desc: Verify the Clear function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, ClearTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ClearTest Start"; + try { + EXPECT_NE(cloudPtr_->pref_, nullptr); + cloudPtr_->Clear(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ClearTest ERROR"; + } + GTEST_LOG_(INFO) << "ClearTest End"; +} + +/** + * @tc.name: DeleteTest + * @tc.desc: Verify the Delete function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, DeleteTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeleteTest Start"; + try { + EXPECT_NE(cloudPtr_->pref_, nullptr); + std::string key; + cloudPtr_->Delete(key); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " DeleteTest ERROR"; + } + GTEST_LOG_(INFO) << "DeleteTest End"; +} + +HWTEST_F(CloudPrefImplTest, CloudPrefImpl_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudPrefImpl_001 Start"; + try { + int32_t userId = 100; + string bundleName = "testBundle"; + string tableName = "testTable"; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + EXPECT_NE(cloudPrefImpl.pref_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CloudPrefImpl_001 ERROR"; + } + GTEST_LOG_(INFO) << "CloudPrefImpl_001 End"; +} + +HWTEST_F(CloudPrefImplTest, CloudPrefImpl_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudPrefImpl_002 Start"; + try { + int32_t userId = -1; + string bundleName = "testBundle"; + string tableName = "testTable"; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + EXPECT_NE(cloudPrefImpl.pref_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CloudPrefImpl_002 ERROR"; + } + GTEST_LOG_(INFO) << "CloudPrefImpl_002 End"; +} + +HWTEST_F(CloudPrefImplTest, CloudPrefImpl_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudPrefImpl_003 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = "testTable"; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + EXPECT_NE(cloudPrefImpl.pref_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CloudPrefImpl_003 ERROR"; + } + GTEST_LOG_(INFO) << "CloudPrefImpl_003 End"; +} + +HWTEST_F(CloudPrefImplTest, CloudPrefImpl_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudPrefImpl_004 Start"; + try { + int32_t userId = 123; + string bundleName = "test_key"; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + EXPECT_EQ(cloudPrefImpl.pref_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " CloudPrefImpl_004 ERROR"; + } + GTEST_LOG_(INFO) << "CloudPrefImpl_004 End"; +} + +HWTEST_F(CloudPrefImplTest, SetString_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetString_001 Start"; + try { + PreferencesMock preferencesMock; + string key = ""; + string value = "test_value"; + EXPECT_CALL(preferencesMock, PutString(_, _)).WillOnce(Return(X_OK)); + EXPECT_CALL(preferencesMock, FlushSync()).WillOnce(Return(X_OK)); + + EXPECT_EQ(preferencesMock.PutString(key, value), X_OK); + EXPECT_EQ(preferencesMock.FlushSync(), X_OK); + cloudPtr_->SetString(key, value); + cloudPtr_->GetString(key, value); + EXPECT_EQ(key, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetString_001 ERROR"; + } + GTEST_LOG_(INFO) << "SetString_001 End"; +} + +HWTEST_F(CloudPrefImplTest, SetString_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetString_002 Start"; + try { + int32_t userId = 100; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + string value = ""; + cloudPrefImpl.SetString(key, value); + cloudPrefImpl.GetString(key, value); + EXPECT_EQ(key, "test_key"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetString_002 ERROR"; + } + GTEST_LOG_(INFO) << "SetString_002 End"; +} + +HWTEST_F(CloudPrefImplTest, SetString_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetString_003 Start"; + try { + int32_t userId = 100; + string bundleName = "test_key"; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + string value = "test_value"; + cloudPrefImpl.SetString(key, value); + cloudPrefImpl.GetString(key, value); + EXPECT_EQ(value, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetString_003 ERROR"; + } + GTEST_LOG_(INFO) << "SetString_003 End"; +} + +HWTEST_F(CloudPrefImplTest, SetString_004, TestSize.Level1) +{ + string key = ""; + string value = "test_value"; + + EXPECT_CALL(*preferencesMock_, PutString(_, _)).WillOnce(Return(X_OK)); + EXPECT_CALL(*preferencesMock_, FlushSync()).WillOnce(Return(X_OK)); + + cloudPtr_->SetString(key, value); + EXPECT_EQ(key, ""); + EXPECT_EQ(preferencesMock_->PutString(key, value), X_OK); + EXPECT_EQ(preferencesMock_->FlushSync(), X_OK); +} + +HWTEST_F(CloudPrefImplTest, SetLong_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetLong_001 Start"; + try { + int32_t userId = 100; + string bundleName = "test_key"; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + int64_t value = -1;; + cloudPrefImpl.SetLong(key, value); + cloudPrefImpl.GetLong(key, value); + EXPECT_EQ(key, "test_key"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetLong_001 ERROR"; + } + GTEST_LOG_(INFO) << "SetLong_001 End"; +} + +HWTEST_F(CloudPrefImplTest, SetLong_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetLong_002 Start"; + try { + int32_t userId = 100; + string bundleName = "test_key"; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + int64_t value = 89; + cloudPrefImpl.SetLong(key, value); + cloudPrefImpl.GetLong(key, value); + EXPECT_EQ(key, "test_key"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetLong_002 ERROR"; + } + GTEST_LOG_(INFO) << "SetLong_002 End"; +} + +HWTEST_F(CloudPrefImplTest, SetLong_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetLong_003 Start"; + try { + int32_t userId = 100; + string bundleName = "test_key"; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = ""; + int64_t value = -1; + cloudPrefImpl.SetLong(key, value); + cloudPrefImpl.GetLong(key, value); + EXPECT_EQ(key, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetLong_003 ERROR"; + } + GTEST_LOG_(INFO) << "SetLong_003 End"; +} + +HWTEST_F(CloudPrefImplTest, SetLong_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetLong_004 Start"; + try { + int32_t userId = 100; + string bundleName = "test_key"; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = ""; + int64_t value = 89; + cloudPrefImpl.SetLong(key, value); + cloudPrefImpl.GetLong(key, value); + EXPECT_EQ(key, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetLong_004 ERROR"; + } + GTEST_LOG_(INFO) << "SetLong_004 End"; +} + +HWTEST_F(CloudPrefImplTest, SetInt_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetInt_001 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + int value = 1; + cloudPrefImpl.SetInt(key, value); + cloudPrefImpl.GetInt(key, value); + EXPECT_EQ(key, "test_key"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetInt_001 ERROR"; + } + GTEST_LOG_(INFO) << "SetInt_001 End"; +} + +HWTEST_F(CloudPrefImplTest, SetInt_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetInt_002 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = ""; + int value = 0; + cloudPrefImpl.SetInt(key, value); + cloudPrefImpl.GetInt(key, value); + EXPECT_EQ(key, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetInt_002 ERROR"; + } + GTEST_LOG_(INFO) << "SetInt_002 End"; +} + +HWTEST_F(CloudPrefImplTest, SetInt_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetInt_003 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + int value = 0x7fffffff; + cloudPrefImpl.SetInt(key, value); + cloudPrefImpl.GetInt(key, value); + EXPECT_EQ(key, "test_key"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetInt_003 ERROR"; + } + GTEST_LOG_(INFO) << "SetInt_003 End"; +} + +HWTEST_F(CloudPrefImplTest, SetInt_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetInt_004 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + int value = 0xffffffff; + cloudPrefImpl.SetInt(key, value); + cloudPrefImpl.GetInt(key, value); + EXPECT_EQ(key, "test_key"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetInt_004 ERROR"; + } + GTEST_LOG_(INFO) << "SetInt_004 End"; +} + +HWTEST_F(CloudPrefImplTest, SetBool_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetBool_001 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + bool value = true; + cloudPrefImpl.SetBool(key, value); + cloudPrefImpl.GetBool(key, value); + EXPECT_FALSE(value); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetBool_001 ERROR"; + } + GTEST_LOG_(INFO) << "SetBool_001 End"; +} + +HWTEST_F(CloudPrefImplTest, SetBool_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetBool_002 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + bool value = false; + cloudPrefImpl.SetBool(key, value); + cloudPrefImpl.GetBool(key, value); + EXPECT_FALSE(value); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetBool_002 ERROR"; + } + GTEST_LOG_(INFO) << "SetBool_002 End"; +} + +HWTEST_F(CloudPrefImplTest, SetBool_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetBool_003 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + bool value = true; + cloudPrefImpl.SetBool(key, value); + cloudPrefImpl.GetBool(key, value); + EXPECT_FALSE(value); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetBool_003 ERROR"; + } + GTEST_LOG_(INFO) << "SetBool_003 End"; +} + +HWTEST_F(CloudPrefImplTest, SetBool_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetBool_004 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + bool value = false; + cloudPrefImpl.SetBool(key, value); + cloudPrefImpl.GetBool(key, value); + EXPECT_FALSE(value); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SetBool_004 ERROR"; + } + GTEST_LOG_(INFO) << "SetBool_004 End"; +} + +HWTEST_F(CloudPrefImplTest, Delete_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "Delete_001 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "test_key"; + cloudPrefImpl.Delete(key); + EXPECT_EQ(key, "test_key"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Delete_001 ERROR"; + } + GTEST_LOG_(INFO) << "Delete_001 End"; +} + +HWTEST_F(CloudPrefImplTest, Delete_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "Delete_001 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = ""; + cloudPrefImpl.Delete(key); + EXPECT_EQ(key, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Delete_002 ERROR"; + } + GTEST_LOG_(INFO) << "Delete_002 End"; +} + +HWTEST_F(CloudPrefImplTest, Delete_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Delete_003 Start"; + try { + int32_t userId = 123; + string bundleName = ""; + string tableName = ""; + CloudPrefImpl cloudPrefImpl(userId, bundleName, tableName); + + string key = "/"; + cloudPrefImpl.Delete(key); + EXPECT_EQ(key, "/"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " Delete_003 ERROR"; + } + GTEST_LOG_(INFO) << "Delete_003 End"; +} + +/** + * @tc.name: SetStringTest001 + * @tc.desc: Verify the SetString function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, SetStringTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetStringTest001 Start"; + std::string key; + std::string value; + cloudPtr_->pref_ = nullptr; + cloudPtr_->SetString(key, value); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "SetStringTest001 End"; +} + +/** + * @tc.name: GetStringTest001 + * @tc.desc: Verify the GetString function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, GetStringTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetStringTest001 Start"; + std::string key; + std::string value; + cloudPtr_->pref_ = nullptr; + cloudPtr_->GetString(key, value); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "GetStringTest001 End"; +} + +/** + * @tc.name: SetLongTest001 + * @tc.desc: Verify the SetLong function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, SetLongTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetLongTest001 Start"; + std::string key; + int64_t value = 0; + cloudPtr_->pref_ = nullptr; + cloudPtr_->SetLong(key, value); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "SetLongTest001 End"; +} + +/** + * @tc.name: GetLongTest001 + * @tc.desc: Verify the GetLong function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, GetLongTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLongTest001 Start"; + std::string key; + int64_t value = 0; + cloudPtr_->pref_ = nullptr; + cloudPtr_->GetLong(key, value); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "GetLongTest001 End"; +} + +/** + * @tc.name: SetIntTest001 + * @tc.desc: Verify the SetInt function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, SetIntTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetIntTest001 Start"; + std::string key; + int value = 0; + cloudPtr_->pref_ = nullptr; + cloudPtr_->SetInt(key, value); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "SetIntTest001 End"; +} + +/** + * @tc.name: GetIntTest001 + * @tc.desc: Verify the GetInt function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, GetIntTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetIntTest001 Start"; + std::string key; + int32_t value = 0; + cloudPtr_->pref_ = nullptr; + cloudPtr_->GetInt(key, value); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "GetIntTest001 End"; +} + +/** + * @tc.name: SetBoolTest001 + * @tc.desc: Verify the SetBool function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, SetBoolTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetBoolTest001 Start"; + std::string key; + bool value = true; + cloudPtr_->pref_ = nullptr; + cloudPtr_->SetBool(key, value); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "SetBoolTest001 End"; +} + +/** + * @tc.name: GetBoolTest001 + * @tc.desc: Verify the GetBool function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, GetBoolTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetBoolTest001 Start"; + std::string key; + bool value = true; + cloudPtr_->pref_ = nullptr; + cloudPtr_->GetBool(key, value); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "GetBoolTest001 End"; +} + +/** + * @tc.name: ClearTest001 + * @tc.desc: Verify the Clear function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, ClearTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ClearTest001 Start"; + cloudPtr_->pref_ = nullptr; + cloudPtr_->Clear(); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "ClearTest001 End"; +} + +/** + * @tc.name: DeleteTest001 + * @tc.desc: Verify the Delete function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(CloudPrefImplTest, DeleteTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeleteTest001 Start"; + cloudPtr_->pref_ = nullptr; + std::string key; + cloudPtr_->Delete(key); + EXPECT_EQ(cloudPtr_->pref_, nullptr); + + GTEST_LOG_(INFO) << "DeleteTest001 End"; +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/cloud_file/test/unittests/utils/system/utils_directory_test.cpp b/cloud_file/test/unittests/utils/system/utils_directory_test.cpp new file mode 100644 index 0000000..d087220 --- /dev/null +++ b/cloud_file/test/unittests/utils/system/utils_directory_test.cpp @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2023-2025 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 "utils_directory.h" + +#include +#include +#include +#include +#include +#include + +#include "directory_ex.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +namespace Utils { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class UtilsDirectoryTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void UtilsDirectoryTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void UtilsDirectoryTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void UtilsDirectoryTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void UtilsDirectoryTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: ForceCreateDirectoryTest001 + * @tc.desc: Verify the ForceCreateDirectory function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, ForceCreateDirectoryTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForceCreateDirectoryTest001 Start"; + try { + string path = "/data/tdd"; + ForceCreateDirectory(path); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << " ForceCreateDirectoryTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ForceCreateDirectoryTest001 End"; +} + +/** + * @tc.name: ForceCreateDirectoryTest002 + * @tc.desc: Verify the ForceCreateDirectoryTest002 function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, ForceCreateDirectoryTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForceCreateDirectoryTest002 Start"; + try { + string path = "/data/tdd"; + mode_t mode = (S_IRWXU | S_IRWXG | S_IRWXO); // 00777 + ForceCreateDirectory(path, mode); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ForceCreateDirectoryTest002 ERROR"; + } + GTEST_LOG_(INFO) << "ForceCreateDirectoryTest002 End"; +} + +/** + * @tc.name: ForceCreateDirectoryTest003 + * @tc.desc: Verify the ForceCreateDirectoryTest003 function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, ForceCreateDirectoryTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForceCreateDirectoryTest003 Start"; + try { + string path = "/data/tdd"; + mode_t mode = (S_IRWXU | S_IRWXG | S_IRWXO); + uid_t uid = UID_ROOT; + gid_t gid = 0; // root + ForceCreateDirectory(path, mode, uid, gid); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ForceCreateDirectoryTest003 ERROR"; + } + GTEST_LOG_(INFO) << "ForceCreateDirectoryTest003 End"; +} + +/** + * @tc.name: ForceRemoveDirectoryTest001 + * @tc.desc: Verify the ForceRemoveDirectory function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, ForceRemoveDirectoryTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForceRemoveDirectory001 Start"; + try { + string path = "/data/tdd"; + ForceRemoveDirectory(path); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ForceRemoveDirectoryTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ForceRemoveDirectoryTest001 End"; +} + +/** + * @tc.name: ForceRemoveDirectoryDeepFirstTest001Test001 + * @tc.desc: Verify the ForceRemoveDirectoryDeepFirst function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, ForceRemoveDirectoryDeepFirstTest001Test001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ForceRemoveDirectoryDeepFirstTest001Test001 Start"; + try { + string path = "/data/tdd"; + ForceRemoveDirectory(path); + EXPECT_FALSE(ForceRemoveDirectoryDeepFirst(path)); + + mode_t mode = (S_IRWXU | S_IRWXG | S_IRWXO); + uid_t uid = UID_ROOT; + gid_t gid = 0; // root + ForceCreateDirectory(path, mode, uid, gid); + + string subPath = path + "/sub"; + ForceCreateDirectory(path, mode, uid, gid); + + string fileStr = path + "/test.txt"; + int32_t fd = open(fileStr.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) << "ForceIsFolderTest001 Create File Failed!"; + close(fd); + + EXPECT_TRUE(ForceRemoveDirectoryDeepFirst(path)); + EXPECT_NE(access(fileStr.c_str(), F_OK), 0); + EXPECT_NE(access(subPath.c_str(), F_OK), 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ForceRemoveDirectoryDeepFirstTest001Test001 ERROR"; + } + GTEST_LOG_(INFO) << "ForceRemoveDirectoryDeepFirstTest001Test001 End"; +} + +/** + * @tc.name: IsFolderTest001 + * @tc.desc: Verify the IsFolder & IsFile function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, IsFolderTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsFolderTest001 Start"; + try { + string path; + EXPECT_FALSE(IsFolder(path)); + + path = "/data/tdd"; + ForceRemoveDirectory(path); + EXPECT_FALSE(IsFolder(path)); + + mode_t mode = (S_IRWXU | S_IRWXG | S_IRWXO); + uid_t uid = UID_ROOT; + gid_t gid = 0; // root + ForceCreateDirectory(path, mode, uid, gid); + EXPECT_TRUE(IsFolder(path)); + + string fileStr = path + "/test.txt"; + int32_t fd = open(fileStr.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) << "IsFolderTest001 Create File Failed!"; + close(fd); + EXPECT_TRUE(IsFile(fileStr)); + + auto ret = unlink(fileStr.c_str()); + ASSERT_TRUE(ret != -1) << "Failed to delete file in IsFolderTest001! " << errno; + ForceRemoveDirectory(path); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsFolderTest001 ERROR"; + } + GTEST_LOG_(INFO) << "IsFolderTest001 End"; +} + +/** + * @tc.name: GetFilePathTest001 + * @tc.desc: Verify the GetFilePath function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, GetFilePathTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetFilePathTest001 Start"; + try { + string path = "/data/tdd"; + ForceRemoveDirectory(path); + + mode_t mode = (S_IRWXU | S_IRWXG | S_IRWXO); + uid_t uid = UID_ROOT; + gid_t gid = 0; // root + ForceCreateDirectory(path, mode, uid, gid); + + string subPath = path + "/sub"; + ForceCreateDirectory(subPath, mode, uid, gid); + + string fileStr1 = path + "/test.txt"; + string fileStr2 = subPath + "/1.txt"; + string fileStr3 = subPath + "/2.txt"; + int32_t fd = open(fileStr1.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) << "GetFilePathTest001 Create fileStr1 Failed!"; + close(fd); + fd = open(fileStr2.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) << "GetFilePathTest001 Create fileStr2 Failed!"; + close(fd); + fd = open(fileStr3.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) << "GetFilePathTest001 Create fileStr3 Failed!"; + close(fd); + + auto rlt = GetFilePath(fileStr1); + std::vector ept; + ept.emplace_back(fileStr1); + EXPECT_EQ(rlt, ept); + + rlt.clear(); + rlt = GetFilePath(path); + EXPECT_EQ(rlt.size(), 3); + + EXPECT_NE(find(rlt.begin(), rlt.end(), fileStr1), rlt.end()); + EXPECT_NE(find(rlt.begin(), rlt.end(), fileStr2), rlt.end()); + EXPECT_NE(find(rlt.begin(), rlt.end(), fileStr3), rlt.end()); + EXPECT_TRUE(ForceRemoveDirectoryDeepFirst(path)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetFilePathTest001 ERROR"; + } + GTEST_LOG_(INFO) << "GetFilePathTest001 End"; +} + +/** + * @tc.name: ChangeOwnerRecursiveTest001 + * @tc.desc: Verify the ChangeOwnerRecursive function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, ChangeOwnerRecursiveTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChangeOwnerRecursiveTest001 Start"; + try { + string path = "/data/tdd"; + ForceRemoveDirectory(path); + + mode_t mode = (S_IRWXU | S_IRWXG | S_IRWXO); + uid_t uid = UID_ROOT; + gid_t gid = 0; // root + ForceCreateDirectory(path, mode, uid, gid); + + string subPath = path + "/sub"; + ForceCreateDirectory(subPath, mode, uid, gid); + + string fileStr = path + "/test.txt"; + int32_t fd = open(fileStr.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) << "ChangeOwnerRecursiveTest001 Create fileStr Failed!"; + close(fd); + + EXPECT_EQ(ChangeOwnerRecursive(fileStr, UID_SYSTEM, 1), -1); + EXPECT_EQ(ChangeOwnerRecursive(path, UID_SYSTEM, 1), 0); + EXPECT_TRUE(ForceRemoveDirectoryDeepFirst(path)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " ChangeOwnerRecursiveTest001 ERROR"; + } + GTEST_LOG_(INFO) << "ChangeOwnerRecursiveTest001 End"; +} + +/** + * @tc.name: IsInt32Test001 + * @tc.desc: Verify the IsInt32 function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, IsInt32Test001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsInt32Test001 Start"; + try { + nlohmann::json jsonObj; + string key = "test"; + EXPECT_EQ(IsInt32(jsonObj, key), false); + + jsonObj["test"] = 20; + EXPECT_EQ(IsInt32(jsonObj, key), true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsInt32Test001 ERROR"; + } + GTEST_LOG_(INFO) << "IsInt32Test001 End"; +} + +/** + * @tc.name: SysEventWriteTest001 + * @tc.desc: Verify the SysEventWrite function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(UtilsDirectoryTest, SysEventWriteTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SysEventWriteTest001 Start"; + try { + string uid; + SysEventWrite(uid); + uid = "test"; + SysEventWrite(uid); + SysEventFileParse(1000); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " SysEventWriteTest001 ERROR"; + } + GTEST_LOG_(INFO) << "SysEventWriteTest001 End"; +} +} // namespace Utils +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/test/unittests/utils/work/async_work_test.cpp b/cloud_file/test/unittests/utils/work/async_work_test.cpp new file mode 100644 index 0000000..7a7bcad --- /dev/null +++ b/cloud_file/test/unittests/utils/work/async_work_test.cpp @@ -0,0 +1,83 @@ +/* + * 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 +#include +#include +#include + +#include "async_work.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class AsyncWorkTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AsyncWorkTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void AsyncWorkTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void AsyncWorkTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void AsyncWorkTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: GetPromiseOrCallBackWorkTest001 + * @tc.desc: Verify the ForceCreateDirectory function + * @tc.type: FUNC + * @tc.require: I6H5MH + */ +HWTEST_F(AsyncWorkTest, GetPromiseOrCallBackWorkTest001, TestSize.Level1) +{ + napi_env env = nullptr; + napi_callback_info info = nullptr; + LibN::NFuncArg funcArg(env, info); + + std::unique_ptr asyncWork = LibN::GetPromiseOrCallBackWork(env, funcArg, 1); + EXPECT_NE(asyncWork, nullptr); +} + +HWTEST_F(AsyncWorkTest, GetPromiseOrCallBackWorkTest002, TestSize.Level1) +{ + napi_env env = nullptr; + napi_callback_info info = nullptr; + LibN::NFuncArg funcArg(env, info); + + std::unique_ptr asyncWork = LibN::GetPromiseOrCallBackWork(env, funcArg, 0); + EXPECT_EQ(asyncWork, nullptr); +} + +} \ No newline at end of file diff --git a/cloud_file/utils/BUILD.gn b/cloud_file/utils/BUILD.gn new file mode 100755 index 0000000..4f9d0c2 --- /dev/null +++ b/cloud_file/utils/BUILD.gn @@ -0,0 +1,275 @@ +# Copyright (c) 2021 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. + +import("//build/ohos.gni") +import("//kernel/linux/common_modules/cloud_file/cloud_file.gni") + +config("compiler_configs") { + visibility = [ ":*" ] + visibility += [ + "${cloud_file_path}/services/*", + "${cloud_file_path}/test/moduletest/*", + ] + + cflags = [ + "-Wall", + "-Werror", + "-Wdate-time", + "-Wfloat-equal", + "-Wshadow", + "-Wformat=2", + "-ffunction-sections", + "-Os", + ] + configs = [ "//build/config/compiler:exceptions" ] + + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Os", + ] + + defines = [ + "LOG_DOMAIN=0xD001600", + "LOG_LEVEL=INFO", + ] +} + +config("utils_public_config") { + include_dirs = [ + "inner_api", + "load/include", + "log/include", + "work/include", + "system/include", + ] +} + +config("optimize-size") { + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-Oz", + ] + cflags_cc = [ + "-fvisibility-inlines-hidden", + "-Oz", + ] +} + +ohos_shared_library("libdistributedfileutils") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + sources = [ + "cloud_disk/src/cloud_file_utils.cpp", + "dfx/src/xcollie_helper.cpp", + "ffrt/src/ffrt_timer.cpp", + "load/src/plugin_loader.cpp", + "log/src/dfs_error.cpp", + "log/src/utils_log.cpp", + "preference/src/cloud_pref_impl.cpp", + "system/src/dfsu_access_token_helper.cpp", + "system/src/dfsu_fd_guard.cpp", + "system/src/dfsu_memory_guard.cpp", + "system/src/dfsu_mount_argument_descriptors.cpp", + "system/src/dfsu_timer.cpp", + "system/src/sys_utils.cpp", + "system/src/utils_directory.cpp", + "work/src/async_work.cpp", + ] + + configs += [ "//build/config/compiler:exceptions" ] + public_configs = [ ":utils_public_config" ] + + cflags = [ + "-D_FORTIFY_SOURCE=2", + ] + + defines = [ + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"distributedfile_utils\"", + ] + + if (use_musl) { + if (musl_use_jemalloc && musl_use_jemalloc_dfx_intf) { + defines += [ "CONFIG_USE_JEMALLOC_DFX_INTF" ] + } + } + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "c_utils:utils", + "device_manager:devicemanagersdk", + "ffrt:libffrt", + "file_api:filemgmt_libhilog", + "file_api:filemgmt_libn", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "json:nlohmann_json_static", + "napi:ace_napi", + "preferences:native_preferences", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + part_name = "cloud_file" + innerapi_tags = [ "platformsdk" ] + subsystem_name = "kernel" +} + +config("dentry_public_config") { + include_dirs = [ + "dentry/include", + "inner_api", + "system/include", + ] +} + +ohos_shared_library("libdistributedfiledentry") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + + sources = [ + "dentry/src/file_utils.cpp", + "dentry/src/meta_file.cpp", + "dentry/src/meta_file_clouddisk.cpp", + "system/src/utils_directory.cpp", + ] + + public_configs = [ ":dentry_public_config" ] + + cflags = [ + "-D_FORTIFY_SOURCE=2", + ] + + deps = [ "${utils_path}:libdistributedfileutils" ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "hilog:libhilog", + "hisysevent:libhisysevent", + "json:nlohmann_json_static", + ] + + defines = [ + "LOG_DOMAIN=0xD004307", + "LOG_TAG=\"CLOUDSYNC_SA\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + part_name = "cloud_file" + subsystem_name = "kernel" +} + +config("utils_lite_public_config") { + include_dirs = [ + "dentry/include", + "inner_api", + "load/include", + "log/include", + "system/include", + ] +} + +ohos_shared_library("libdistributedfileutils_lite") { + branch_protector_ret = "pac_ret" + configs = [ ":optimize-size" ] + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + + sources = [ + "cloud_disk/src/cloud_file_utils.cpp", + "dentry/src/file_utils.cpp", + "dentry/src/meta_file.cpp", + "dentry/src/meta_file_clouddisk.cpp", + "dfx/src/xcollie_helper.cpp", + "ffrt/src/ffrt_timer.cpp", + "load/src/plugin_loader.cpp", + "log/src/dfs_error.cpp", + "log/src/utils_log.cpp", + "system/src/dfsu_memory_guard.cpp", + "system/src/utils_directory.cpp", + ] + + configs += [ "//build/config/compiler:exceptions" ] + public_configs = [ ":utils_lite_public_config" ] + + cflags = [ + "-D_FORTIFY_SOURCE=2", + ] + + defines = [ + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CloudFileDaemon\"", + ] + + deps = [] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "json:nlohmann_json_static", + ] + + if (use_musl) { + if (musl_use_jemalloc && musl_use_jemalloc_dfx_intf) { + defines += [ "CONFIG_USE_JEMALLOC_DFX_INTF" ] + } + } + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + part_name = "cloud_file" + innerapi_tags = [ "platformsdk" ] + subsystem_name = "kernel" +} diff --git a/cloud_file/utils/cloud_disk/src/cloud_file_utils.cpp b/cloud_file/utils/cloud_disk/src/cloud_file_utils.cpp new file mode 100644 index 0000000..ce1d29c --- /dev/null +++ b/cloud_file/utils/cloud_disk/src/cloud_file_utils.cpp @@ -0,0 +1,351 @@ +/* + * 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 "cloud_file_utils.h" +#include +#include +#include +#include +#include +#include +#include "utils_log.h" +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +using namespace std; +namespace { + static const string LOCAL_PATH_DATA_SERVICE_EL2 = "/data/service/el2/"; + static const string LOCAL_PATH_HMDFS_CLOUD_DATA = "/hmdfs/cloud/data/"; + static const string LOCAL_PATH_HMDFS_CLOUD_CACHE = "/hmdfs/cache/cloud_cache"; + static const string CLOUDDISK_CACHE_DIR = "/disk_drivekit_cache/"; + static const string CLOUD_FILE_CLOUD_ID_XATTR = "user.cloud.cloudid"; + static const uint32_t CLOUD_ID_MIN_SIZE = 3; + static const uint32_t CLOUD_ID_BUCKET_MID_TIMES = 2; + static const uint32_t CLOUD_ID_BUCKET_MAX_SIZE = 32; + static const int64_t SECOND_TO_MILLISECOND = 1e3; + static const int64_t MILLISECOND_TO_NANOSECOND = 1e6; + static const uint64_t DELTA_DISK = 0x9E3779B9; + static const uint64_t HMDFS_HASH_COL_BIT_DISK = (0x1ULL) << 63; +} + +constexpr unsigned HMDFS_IOC = 0xf2; +constexpr unsigned WRITEOPEN_CMD = 0x02; +constexpr unsigned CLOUD_ENABLE_CMD = 0x0b; +#define HMDFS_IOC_GET_WRITEOPEN_CNT _IOR(HMDFS_IOC, WRITEOPEN_CMD, uint32_t) +#define HMDFS_IOC_SET_CLOUD_GENERATION _IOR(HMDFS_IOC, CLOUD_ENABLE_CMD, uint32_t) +const string CloudFileUtils::TMP_SUFFIX = ".temp.download"; + +bool CloudFileUtils::IsDotDotdot(const std::string &name) +{ + return name == "." || name == ".."; +} + +void CloudFileUtils::Str2HashBuf(const char *msg, size_t len, uint32_t *buf, int num) +{ + const int32_t shift8 = 8; + const int32_t shift16 = 16; + const int32_t three = 3; + const int32_t mod = 4; + uint32_t pad = static_cast(len) | (static_cast(len) << shift8); + pad |= pad << shift16; + + uint32_t val = pad; + len = std::min(len, static_cast(num * sizeof(int))); + for (uint32_t i = 0; i < len; i++) { + if ((i % sizeof(int)) == 0) { + val = pad; + } + uint8_t c = static_cast(tolower(msg[i])); + val = c + (val << shift8); + if ((i % mod) == three) { + *buf++ = val; + val = pad; + num--; + } + } + if (--num >= 0) { + *buf++ = val; + } + while (--num >= 0) { + *buf++ = pad; + } +} + +void CloudFileUtils::TeaTransform(uint32_t buf[4], uint32_t const in[]) __attribute__((no_sanitize( + "unsigned-integer-overflow"))) +{ + int n = 16; + uint32_t a = in[0]; + uint32_t b = in[1]; + uint32_t c = in[2]; + uint32_t d = in[3]; + uint32_t b0 = buf[0]; + uint32_t b1 = buf[1]; + uint32_t sum = 0; + const int32_t LEFT_SHIFT = 4; + const int32_t RIGHT_SHIFT = 5; + do { + sum += DELTA_DISK; + b0 += ((b1 << LEFT_SHIFT) + a) ^ (b1 + sum) ^ ((b1 >> RIGHT_SHIFT) + b); + b1 += ((b0 << LEFT_SHIFT) + c) ^ (b0 + sum) ^ ((b0 >> RIGHT_SHIFT) + d); + } while (--n); + + buf[0] += b0; + buf[1] += b1; +} + +uint32_t CloudFileUtils::DentryHash(const std::string &inputStr) +{ + if (IsDotDotdot(inputStr)) { + return 0; + } + constexpr int inLen = 8; + constexpr int bufLen = 4; + uint32_t in[inLen]; + uint32_t buf[bufLen] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476}; + auto len = inputStr.length(); + constexpr decltype(len) hashWidth = 16; + const char *p = inputStr.c_str(); + + bool loopFlag = true; + while (loopFlag) { + Str2HashBuf(p, len, in, bufLen); + TeaTransform(buf, in); + + if (len <= hashWidth) { + break; + } + p += hashWidth; + len -= hashWidth; + }; + uint32_t hash = buf[0]; + uint32_t hmdfsHash = hash & ~HMDFS_HASH_COL_BIT_DISK; + return hmdfsHash; +} + +uint32_t CloudFileUtils::GetBucketId(string cloudId) +{ + size_t size = cloudId.size(); + if (size < CLOUD_ID_MIN_SIZE) { + return 0; + } + + char first = cloudId[0]; + char last = cloudId[size - 1]; + char middle = cloudId[size / CLOUD_ID_BUCKET_MID_TIMES]; + return (first + last + middle) % CLOUD_ID_BUCKET_MAX_SIZE; +} + +int64_t CloudFileUtils::Timespec2Milliseconds(const struct timespec &time) +{ + return time.tv_sec * SECOND_TO_MILLISECOND + time.tv_nsec / MILLISECOND_TO_NANOSECOND; +} + +string CloudFileUtils::GetLocalBucketPath(string cloudId, string bundleName, int32_t userId) +{ + string baseDir = LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + + LOCAL_PATH_HMDFS_CLOUD_DATA + bundleName + "/"; + uint32_t bucketId = GetBucketId(cloudId); + string bucketPath = baseDir + to_string(bucketId); + return bucketPath; +} + +string CloudFileUtils::GetLocalDKCachePath(string cloudId, string bundleName, int32_t userId) +{ + string baseDir = LOCAL_PATH_DATA_SERVICE_EL2 + to_string(userId) + LOCAL_PATH_HMDFS_CLOUD_CACHE + + CLOUDDISK_CACHE_DIR + bundleName + "/"; + uint32_t bucketId = GetBucketId(cloudId); + string cachePath = baseDir + to_string(bucketId) + "/" + cloudId; + return cachePath; +} + +string CloudFileUtils::GetLocalFilePath(string cloudId, string bundleName, int32_t userId) +{ + return GetLocalBucketPath(cloudId, bundleName, userId) + "/" + cloudId; +} + +string CloudFileUtils::GetPathWithoutTmp(const string &path) +{ + string ret = path; + if (EndsWith(path, TMP_SUFFIX)) { + ret = path.substr(0, path.length() - TMP_SUFFIX.length()); + } + return ret; +} + +bool CloudFileUtils::EndsWith(const string &fullString, const string &ending) +{ + if (fullString.length() >= ending.length()) { + return (!fullString.compare(fullString.length() - ending.length(), + ending.length(), + ending)); + } + return false; +} + +string CloudFileUtils::GetCloudId(const string &path) +{ + auto idSize = getxattr(path.c_str(), CLOUD_FILE_CLOUD_ID_XATTR.c_str(), nullptr, 0); + if (idSize <= 0) { + return ""; + } + char cloudId[idSize + 1]; + idSize = getxattr(path.c_str(), CLOUD_FILE_CLOUD_ID_XATTR.c_str(), cloudId, idSize); + if (idSize <= 0) { + return ""; + } + return string(cloudId); +} + +bool CloudFileUtils::CheckIsCloud(const string &key) +{ + return key == CLOUD_CLOUD_ID_XATTR; +} + +bool CloudFileUtils::CheckIsCloudLocation(const string &key) +{ + return key == CLOUD_FILE_LOCATION; +} + +bool CloudFileUtils::CheckIsHmdfsPermission(const string &key) +{ + return key == HMDFS_PERMISSION_XATTR; +} + +bool CloudFileUtils::CheckIsCloudRecycle(const string &key) +{ + return key == CLOUD_CLOUD_RECYCLE_XATTR; +} + +bool CloudFileUtils::CheckIsFavorite(const string &key) +{ + return key == IS_FAVORITE_XATTR; +} + +bool CloudFileUtils::CheckIsTimeRecycled(const string &key) +{ + return key == CLOUD_TIME_RECYCLED; +} + +bool CloudFileUtils::CheckIsHasLCD(const string &key) +{ + return key == CLOUD_HAS_LCD; +} + +bool CloudFileUtils::CheckIsHasTHM(const string &key) +{ + return key == CLOUD_HAS_THM; +} + +bool CloudFileUtils::CheckFileStatus(const string &key) +{ + return key == IS_FILE_STATUS_XATTR; +} + +bool CloudFileUtils::CheckIsRecyclePath(const string &key) +{ + return key == CLOUD_RECYCLE_PATH; +} + +bool CloudFileUtils::LocalWriteOpen(const string &dfsPath) +{ + unique_ptr absPath = make_unique(PATH_MAX + 1); + if (realpath(dfsPath.c_str(), absPath.get()) == nullptr) { + return false; + } + string realPath = absPath.get(); + char resolvedPath[PATH_MAX] = {'\0'}; + char *realPaths = realpath(realPath.c_str(), resolvedPath); + if (realPaths == NULL) { + LOGE("realpath failed"); + return false; + } + std::FILE *file = fopen(realPaths, "r"); + if (file == nullptr) { + LOGE("fopen failed, errno:%{public}d", errno); + return false; + } + int fd = fileno(file); + if (fd < 0) { + LOGE("get fd failed, errno:%{public}d", errno); + return false; + } + uint32_t writeOpenCnt = 0; + int ret = ioctl(fd, HMDFS_IOC_GET_WRITEOPEN_CNT, &writeOpenCnt); + if (ret < 0) { + LOGE("ioctl failed, errno:%{public}d", errno); + if (fclose(file)) { + LOGE("fclose failed, errno:%{public}d", errno); + } + return false; + } + + if (fclose(file)) { + LOGE("fclose failed, errno:%{public}d", errno); + return false; + } + return writeOpenCnt != 0; +} + +bool CloudFileUtils::ClearCache(const string &dfsPath) +{ + auto resolvedPath = realpath(dfsPath.c_str(), NULL); + if (resolvedPath == NULL) { + LOGE("realpath failed"); + return false; + } + std::FILE *file = fopen(resolvedPath, "r"); + free(resolvedPath); + if (file == nullptr) { + LOGE("fopen failed, errno:%{public}d", errno); + return false; + } + int fd = fileno(file); + if (fd < 0) { + LOGE("get fd failed, errno:%{public}d", errno); + return false; + } + int ret = ioctl(fd, HMDFS_IOC_SET_CLOUD_GENERATION); + if (ret < 0) { + LOGE("ioctl failed, errno:%{public}d", errno); + if (fclose(file)) { + LOGE("fclose failed, errno:%{public}d", errno); + } + return false; + } + if (fclose(file)) { + LOGE("fclose failed, errno:%{public}d", errno); + return false; + } + return true; +} + +string CloudFileUtils::GetRealPath(const string &path) +{ + filesystem::path tempPath(path); + filesystem::path realPath{}; + for (const auto& component : tempPath) { + if (component == ".") { + continue; + } else if (component == "..") { + realPath = realPath.parent_path(); + } else { + realPath /= component; + } + } + return realPath.string(); +} +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/utils/dentry/include/file_utils.h b/cloud_file/utils/dentry/include/file_utils.h new file mode 100644 index 0000000..02225da --- /dev/null +++ b/cloud_file/utils/dentry/include/file_utils.h @@ -0,0 +1,35 @@ +/* + * 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 OHOS_FILEMGMT_DENTRY_FILE_UTILS_H +#define OHOS_FILEMGMT_DENTRY_FILE_UTILS_H + +#include +#include + +namespace OHOS { +namespace FileManagement { +class FileUtils { +public: + FileUtils() = delete; + ~FileUtils() = delete; + + static int64_t ReadFile(int fd, off_t offset, size_t size, void *data); + static int64_t WriteFile(int fd, const void *data, off_t offset, size_t size); +}; +} // namespace FileManagement +} // namespace OHOS + +#endif diff --git a/cloud_file/utils/dentry/include/meta_file.h b/cloud_file/utils/dentry/include/meta_file.h new file mode 100644 index 0000000..efad14b --- /dev/null +++ b/cloud_file/utils/dentry/include/meta_file.h @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2023-2024 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 OHOS_FILEMGMT_DENTRY_META_FILE_H +#define OHOS_FILEMGMT_DENTRY_META_FILE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "unique_fd.h" + +namespace OHOS { +namespace FileManagement { + +const std::string RECYCLE_NAME = ".trash"; +const std::string RECYCLE_CLOUD_ID = ".trash"; +const std::string ROOT_CLOUD_ID = "rootId"; +const unsigned int STAT_MODE_DIR = 0771; +constexpr int32_t LOCAL = 1; +constexpr uint32_t MAX_META_FILE_NUM = 100; +constexpr uint32_t MAX_CLOUDDISK_META_FILE_NUM = 150; + +struct MetaBase; +struct RestoreInfo; +class MetaFile { +public: + MetaFile() = delete; + ~MetaFile(); + using CloudDiskMetaFileCallBack = std::function; + explicit MetaFile(uint32_t userId, const std::string &path); + explicit MetaFile(uint32_t userId, const std::string &bundleName, const std::string &parentCloudId); + int32_t DoLookupAndUpdate(const std::string &name, CloudDiskMetaFileCallBack updateFunc); + int32_t DoLookupAndRemove(MetaBase &metaBase); + int32_t DoCreate(const MetaBase &base); + int32_t HandleFileByFd(unsigned long &endBlock, uint32_t &level); + int32_t DoRemove(const MetaBase &base); + int32_t DoUpdate(const MetaBase &base); + int32_t DoRename(const MetaBase &oldBase, const std::string &newName); + int32_t DoRename(MetaBase &metaBase, const std::string &newName, std::shared_ptr newMetaFile); + int32_t DoLookup(MetaBase &base); + int32_t LoadChildren(std::vector &bases); + + static std::string GetParentDir(const std::string &path); + static std::string GetFileName(const std::string &path); + +private: + std::mutex mtx_{}; + std::string path_{}; + std::string cacheFile_{}; + std::string bundleName_{}; + std::string cloudId_{}; + std::string name_{}; + UniqueFd fd_{}; + uint32_t userId_{}; + std::shared_ptr parentMetaFile_{nullptr}; +}; + +class CloudDiskMetaFile { +public: + CloudDiskMetaFile() = delete; + ~CloudDiskMetaFile(); + using CloudDiskMetaFileCallBack = std::function; + explicit CloudDiskMetaFile(uint32_t userId, const std::string &bundleName, const std::string &cloudId); + + int32_t DoLookupAndCreate(const std::string &name, CloudDiskMetaFileCallBack metaFileCallBack); + int32_t DoLookupAndUpdate(const std::string &name, CloudDiskMetaFileCallBack updateFunc); + int32_t DoChildUpdate(const std::string &name, CloudDiskMetaFileCallBack updateFunc); + int32_t DoLookupAndRemove(MetaBase &metaBase); + int32_t DoCreate(const MetaBase &base); + int32_t HandleFileByFd(unsigned long &endBlock, uint32_t &level); + int32_t DoRemove(const MetaBase &base); + int32_t DoUpdate(const MetaBase &base); + int32_t DoRename(MetaBase &metaBase, const std::string &newName, + std::shared_ptr newMetaFile); + int32_t DoLookup(MetaBase &base); + int32_t LoadChildren(std::vector &bases); + std::string GetDentryFilePath(); + +private: + int32_t GetCreateInfo(const MetaBase &base, uint32_t &bitPos, uint32_t &namehash, + unsigned long &bidx, struct HmdfsDentryGroup &dentryBlk); + std::mutex mtx_{}; + std::string path_{}; + std::string cacheFile_{}; + std::string bundleName_{}; + std::string cloudId_{}; + std::string name_{}; + UniqueFd fd_{}; + uint32_t userId_{}; + std::shared_ptr parentMetaFile_{nullptr}; +}; + +enum { + NEED_UPLOAD = 0, + NO_UPLOAD, +}; + +enum { + FILE_TYPE_CONTENT = 0, + FILE_TYPE_THUMBNAIL, + FILE_TYPE_LCD, +}; + +enum { + POSITION_UNKNOWN = 0, + POSITION_LOCAL = 0x01, + POSITION_CLOUD = 0x02, + POSITION_LOCAL_AND_CLOUD = POSITION_LOCAL | POSITION_CLOUD, +}; + +typedef std::pair MetaFileKey; +typedef std::pair> CloudDiskMetaFileListEle; +typedef std::pair> MetaFileListEle; + +class MetaFileMgr { +public: + static MetaFileMgr& GetInstance(); + /* recordId is hex string of 256 bits, convert to u8 cloudId[32] to kernel */ + static std::string RecordIdToCloudId(const std::string hexStr); + static std::string CloudIdToRecordId(const std::string cloudId); + std::shared_ptr GetMetaFile(uint32_t userId, const std::string &path); + std::shared_ptr GetCloudDiskMetaFile(uint32_t userId, const std::string &bundleName, + const std::string &cloudId); + void ClearAll(); + void CloudDiskClearAll(); + void Clear(uint32_t userId, const std::string &bundleName, const std::string &cloudId); + int32_t CreateRecycleDentry(uint32_t userId, const std::string &bundleName); + int32_t MoveIntoRecycleDentryfile(uint32_t userId, const std::string &bundleName, + const std::string &name, const std::string &parentCloudId, int64_t rowId); + int32_t RemoveFromRecycleDentryfile(uint32_t userId, const std::string &bundleName, + const struct RestoreInfo &restoreinfo); + int32_t GetNewName(std::shared_ptr metaFile, + const std::string &oldName, std::string &newName); + int32_t CheckMetaFileSize(); +private: + MetaFileMgr() = default; + ~MetaFileMgr() = default; + MetaFileMgr(const MetaFileMgr &m) = delete; + const MetaFileMgr &operator=(const MetaFileMgr &m) = delete; + + std::recursive_mutex mtx_{}; + std::mutex cloudDiskMutex_{}; + std::list metaFileList_; + std::map::iterator> metaFiles_; + std::list cloudDiskMetaFileList_; + std::map::iterator> cloudDiskMetaFile_; +}; + +struct MetaBase { + MetaBase(const std::string &name) : name(name) {} + MetaBase(const std::string &name, const std::string &cloudId) : name(name), cloudId(cloudId) {} + MetaBase() = default; + inline bool operator!=(const MetaBase &other) const + { + return !operator==(other); + } + inline bool operator==(const MetaBase &other) const + { + return other.cloudId == cloudId && other.name == name && other.size == size; + } + uint64_t atime{0}; + uint64_t mtime{0}; + uint64_t size{0}; + uint32_t mode{S_IFREG}; + uint8_t position{POSITION_LOCAL}; + uint8_t fileType{FILE_TYPE_CONTENT}; + uint8_t noUpload{NEED_UPLOAD}; + std::string name{}; + std::string cloudId{}; + off_t nextOff{0}; +}; + +struct BitOps { + static const uint8_t BIT_PER_BYTE = 8; + static int TestBit(uint32_t nr, const uint8_t addr[]) + { + return 1 & (addr[nr / BIT_PER_BYTE] >> (nr & (BIT_PER_BYTE - 1))); + } + + static void ClearBit(uint32_t nr, uint8_t addr[]) + { + addr[nr / BIT_PER_BYTE] &= ~(1UL << ((nr) % BIT_PER_BYTE)); + } + + static void SetBit(uint32_t nr, uint8_t addr[]) + { + addr[nr / BIT_PER_BYTE] |= (1UL << ((nr) % BIT_PER_BYTE)); + } + + static uint32_t FindNextBit(const uint8_t addr[], uint32_t maxSlots, uint32_t start) + { + while (start < maxSlots) { + if (BitOps::TestBit(start, addr)) { + return start; + } + start++; + } + return maxSlots; + } + + static uint32_t FindNextZeroBit(const uint8_t addr[], uint32_t maxSlots, uint32_t start) + { + while (start < maxSlots) { + if (!BitOps::TestBit(start, addr)) { + return start; + } + start++; + } + return maxSlots; + } +}; + +struct MetaHelper { + static void SetFileType(struct HmdfsDentry *de, uint8_t fileType); + static void SetPosition(struct HmdfsDentry *de, uint8_t position); + static void SetNoUpload(struct HmdfsDentry *de, uint8_t noUpload); + static uint8_t GetFileType(const struct HmdfsDentry *de); + static uint8_t GetPosition(const struct HmdfsDentry *de); + static uint8_t GetNoUpload(const struct HmdfsDentry *de); +}; + +struct RestoreInfo { + std::string oldName; + std::string parentCloudId; + std::string newName; + int64_t rowId = 0; +}; +} // namespace FileManagement +} // namespace OHOS + +#endif // META_FILE_H diff --git a/cloud_file/utils/dentry/src/file_utils.cpp b/cloud_file/utils/dentry/src/file_utils.cpp new file mode 100644 index 0000000..e6a6864 --- /dev/null +++ b/cloud_file/utils/dentry/src/file_utils.cpp @@ -0,0 +1,83 @@ +/* + * 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 "file_utils.h" + +#include +#include +#include +#include + +#include "dfs_error.h" +#include "utils_log.h" +#include "xcollie_helper.h" + +namespace OHOS { +namespace FileManagement { +int64_t FileUtils::ReadFile(int fd, off_t offset, size_t size, void *data) +{ + if ((fd < 0) || (offset < 0) || (size < 0) || (data == nullptr)) { + LOGE("invalid params, fd %{public}d, offset %{public}d, size %{public}zu, or buf is null", fd, + static_cast(offset), size); + return -1; + } + + off_t err = lseek(fd, offset, SEEK_SET); + if (err < 0) { + return -errno; + } + + size_t readLen = 0; + while (readLen < size) { + ssize_t ret = read(fd, data, size - readLen); + if (ret < 0) { + LOGE("read failed, errno %{public}d, fd=%{public}d", errno, fd); + return ret; + } else if (ret == 0) { + break; + } + readLen += static_cast(ret); + } + + return readLen; +} + +int64_t FileUtils::WriteFile(int fd, const void *data, off_t offset, size_t size) +{ + if ((fd < 0) || (offset < 0) || (size < 0) || (data == nullptr)) { + LOGE("invalid params, fd %{public}d, offset %{public}d, size %{public}zu, or buf is null", fd, + static_cast(offset), size); + return -1; + } + + off_t err = lseek(fd, offset, SEEK_SET); + if (err < 0) { + return -errno; + } + + size_t writeLen = 0; + while (writeLen < size) { + ssize_t ret = write(fd, data, size - writeLen); + if (ret <= 0) { + LOGE("write failed, errno %{public}d, fd=%{public}d", errno, fd); + return ret; + } + writeLen += static_cast(ret); + } + + return writeLen; +} +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/utils/dentry/src/meta_file.cpp b/cloud_file/utils/dentry/src/meta_file.cpp new file mode 100644 index 0000000..0820e0f --- /dev/null +++ b/cloud_file/utils/dentry/src/meta_file.cpp @@ -0,0 +1,743 @@ +/* + * 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 "meta_file.h" + +#include +#include +#include +#include +#include + +#include "cloud_file_utils.h" +#include "dfs_error.h" +#include "directory_ex.h" +#include "file_utils.h" +#include "securec.h" +#include "string_ex.h" +#include "sys/xattr.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +constexpr uint32_t DENTRYGROUP_SIZE = 4096; +constexpr uint32_t DENTRY_NAME_LEN = 8; +constexpr uint32_t DENTRY_RESERVED_LENGTH = 3; +constexpr uint32_t DENTRY_PER_GROUP = 60; +constexpr uint32_t DENTRY_BITMAP_LENGTH = 8; +constexpr uint32_t DENTRY_GROUP_RESERVED = 7; +constexpr uint32_t CLOUD_RECORD_ID_LEN = 33; +constexpr uint32_t DENTRYGROUP_HEADER = 4096; +constexpr uint32_t MAX_BUCKET_LEVEL = 63; +constexpr uint32_t BUCKET_BLOCKS = 2; +constexpr uint32_t BITS_PER_BYTE = 8; +constexpr uint32_t HMDFS_SLOT_LEN_BITS = 3; +constexpr uint32_t DIR_SIZE = 4096; + +#pragma pack(push, 1) +struct HmdfsDentry { + uint32_t hash{0}; + uint16_t mode{0}; + uint16_t namelen{0}; + uint64_t size{0}; + uint64_t mtime{0}; + uint8_t recordId[CLOUD_RECORD_ID_LEN]{0}; + /* reserved bytes for long term extend, total 60 bytes */ + union { + struct { + uint8_t fileType : 2; + }; + uint8_t reserved[DENTRY_RESERVED_LENGTH]; + }; +}; + +struct HmdfsDentryGroup { + uint8_t dentryVersion; + uint8_t bitmap[DENTRY_BITMAP_LENGTH]; + HmdfsDentry nsl[DENTRY_PER_GROUP]; + uint8_t fileName[DENTRY_PER_GROUP][DENTRY_NAME_LEN]; + uint8_t reserved[DENTRY_GROUP_RESERVED]; +}; +static_assert(sizeof(HmdfsDentryGroup) == DENTRYGROUP_SIZE); + +struct HmdfsDcacheHeader { + uint64_t dcacheCrtime{0}; + uint64_t dcacheCrtimeNsec{0}; + + uint64_t dentryCtime{0}; + uint64_t dentryCtimeNsec{0}; + + uint64_t dentryCount{0}; +}; +#pragma pack(pop) + +static uint64_t PathHash(const std::string &path, bool caseSense) +{ + uint64_t res = 0; + const char *kp = path.c_str(); + + while (*kp) { + char c = *kp; + if (!caseSense) { + c = tolower(c); + } + res = (res << 5) - res + static_cast(c); /* hash shift width 5 */ + kp++; + } + return res; +} + +static std::string GetDentryfileName(const std::string &path, bool caseSense) +{ + // path should be like "/", "/dir/", "/dir/dir/" ... + constexpr uint32_t fileNameLen = 32; + char buf[fileNameLen + 1] = {0}; + uint64_t fileHash = PathHash(path, caseSense); + int ret = snprintf_s(buf, fileNameLen + 1, fileNameLen, "cloud_%016llx", fileHash); + if (ret < 0) { + LOGE("filename failer fileHash ret :%{public}d", ret); + } + return buf; +} + +static std::string GetDentryfileByPath(uint32_t userId, const std::string &path, bool caseSense = false) +{ + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cache/account_cache/dentry_cache/cloud/"; + std::string dentryFileName = GetDentryfileName(path, caseSense); + + return cacheDir + dentryFileName; +} + +std::string MetaFile::GetParentDir(const std::string &path) +{ + if ((path == "/") || (path == "")) { + return ""; + } + + auto pos = path.find_last_of('/'); + if ((pos == std::string::npos) || (pos == 0)) { + return "/"; + } + + return path.substr(0, pos); +} + +std::string MetaFile::GetFileName(const std::string &path) +{ + if ((path == "/") || (path == "")) { + return ""; + } + + auto pos = path.find_last_of('/'); + if (pos == std::string::npos) { + return ""; + } + + return path.substr(pos + 1); +} + +static std::shared_ptr GetParentMetaFile(uint32_t userId, const std::string &path) +{ + std::string parentPath = MetaFile::GetParentDir(path); + if (parentPath == "") { + return nullptr; + } + + return MetaFileMgr::GetInstance().GetMetaFile(userId, parentPath); +} + +MetaFile::MetaFile(uint32_t userId, const std::string &path) +{ + path_ = path; + cacheFile_ = GetDentryfileByPath(userId, path); + fd_ = UniqueFd{open(cacheFile_.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)}; + if (fd_ < 0) { + LOGE("fd=%{public}d, errno :%{public}d", fd_.Get(), errno); + return; + } + + int ret = fsetxattr(fd_, "user.hmdfs_cache", path.c_str(), path.size(), 0); + if (ret != 0) { + LOGE("setxattr failed, errno %{public}d, cacheFile_ %s", errno, GetAnonyString(cacheFile_).c_str()); + } + + /* lookup and create in parent */ + parentMetaFile_ = GetParentMetaFile(userId, path); + std::string dirName = GetFileName(path); + if ((parentMetaFile_ == nullptr) || (dirName == "")) { + return; + } + MetaBase m(dirName, std::to_string(PathHash(path, false)) + std::to_string(std::time(nullptr))); + ret = parentMetaFile_->DoLookup(m); + if (ret != E_OK) { + m.mode = S_IFDIR; + m.size = DIR_SIZE; + ret = parentMetaFile_->DoCreate(m); + if (ret != E_OK) { + LOGE("create parent failed, ret %{public}d", ret); + } + } +} + +MetaFile::~MetaFile() +{ +} + +static inline uint32_t GetDentrySlots(size_t nameLen) +{ + return static_cast((nameLen + BITS_PER_BYTE - 1) >> HMDFS_SLOT_LEN_BITS); +} + +static inline off_t GetDentryGroupPos(size_t bidx) +{ + return bidx * DENTRYGROUP_SIZE + DENTRYGROUP_HEADER; +} + +static inline uint64_t GetDentryGroupCnt(uint64_t size) +{ + return (size >= DENTRYGROUP_HEADER) ? ((size - DENTRYGROUP_HEADER) / DENTRYGROUP_SIZE) : 0; +} + +static uint32_t GetOverallBucket(uint32_t level) +{ + if (level >= MAX_BUCKET_LEVEL) { + LOGI("level = %{public}d overflow", level); + return 0; + } + uint64_t buckets = (1ULL << (level + 1)) - 1; + return static_cast(buckets); +} + +static size_t GetDcacheFileSize(uint32_t level) +{ + size_t buckets = GetOverallBucket(level); + return buckets * DENTRYGROUP_SIZE * BUCKET_BLOCKS + DENTRYGROUP_HEADER; +} + +static uint32_t GetBucketaddr(uint32_t level, uint32_t buckoffset) +{ + if (level >= MAX_BUCKET_LEVEL) { + return 0; + } + + uint64_t curLevelMaxBucks = (1ULL << level); + if (buckoffset >= curLevelMaxBucks) { + return 0; + } + + return static_cast(curLevelMaxBucks) + buckoffset - 1; +} + +static uint32_t GetBucketByLevel(uint32_t level) +{ + if (level >= MAX_BUCKET_LEVEL) { + LOGI("level = %{public}d overflow", level); + return 0; + } + + uint64_t buckets = (1ULL << level); + return static_cast(buckets); +} + +static uint32_t RoomForFilename(const uint8_t bitmap[], size_t slots, uint32_t maxSlots) +{ + uint32_t bitStart = 0; + + while (1) { + uint32_t zeroStart = BitOps::FindNextZeroBit(bitmap, maxSlots, bitStart); + if (zeroStart >= maxSlots) { + return maxSlots; + } + + uint32_t zeroEnd = BitOps::FindNextBit(bitmap, maxSlots, zeroStart); + if (zeroEnd - zeroStart >= slots) { + return zeroStart; + } + + bitStart = zeroEnd + 1; + if (zeroEnd + 1 >= maxSlots) { + return maxSlots; + } + } + return 0; +} + +static bool UpdateDentry(HmdfsDentryGroup &d, const MetaBase &base, uint32_t nameHash, uint32_t bitPos) +{ + HmdfsDentry *de; + const std::string name = base.name; + uint32_t slots = GetDentrySlots(name.length()); + + de = &d.nsl[bitPos]; + de->hash = nameHash; + de->namelen = name.length(); + errno_t ret = memcpy_s(d.fileName[bitPos], slots * DENTRY_NAME_LEN, name.c_str(), name.length()); + if (ret != EOK) { + LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", slots * DENTRY_NAME_LEN, name.length()); + return false; + } + de->mtime = base.mtime; + de->fileType = base.fileType; + de->size = base.size; + de->mode = base.mode; + ret = memcpy_s(de->recordId, CLOUD_RECORD_ID_LEN, base.cloudId.c_str(), base.cloudId.length()); + if (ret != EOK) { + LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", CLOUD_RECORD_ID_LEN, base.cloudId.length()); + return false; + } + + for (uint32_t i = 0; i < slots; i++) { + BitOps::SetBit(bitPos + i, d.bitmap); + if (i) { + (de + i)->namelen = 0; + } + } + return true; +} + +int32_t MetaFile::HandleFileByFd(unsigned long &endBlock, uint32_t &level) +{ + struct stat fileStat; + int err = fstat(fd_, &fileStat); + if (err < 0) { + return EINVAL; + } + if ((endBlock > GetDentryGroupCnt(fileStat.st_size)) && + ftruncate(fd_, GetDcacheFileSize(level))) { + return ENOENT; + } + return E_OK; +} + +int32_t MetaFile::DoCreate(const MetaBase &base) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + off_t pos = 0; + uint32_t level = 0; + uint32_t bitPos = 0; + unsigned long bidx; + HmdfsDentryGroup dentryBlk = {0}; + + std::unique_lock lock(mtx_); + uint32_t namehash = CloudDisk::CloudFileUtils::DentryHash(base.name); + + bool found = false; + while (!found) { + if (level == MAX_BUCKET_LEVEL) { + return ENOSPC; + } + bidx = BUCKET_BLOCKS * GetBucketaddr(level, namehash % GetBucketByLevel(level)); + unsigned long endBlock = bidx + BUCKET_BLOCKS; + + int32_t ret = MetaFile::HandleFileByFd(endBlock, level); + if (ret != E_OK) { + return ret; + } + + for (; bidx < endBlock; bidx++) { + pos = GetDentryGroupPos(bidx); + if (FileUtils::ReadFile(fd_, pos, DENTRYGROUP_SIZE, &dentryBlk) != DENTRYGROUP_SIZE) { + return ENOENT; + } + bitPos = RoomForFilename(dentryBlk.bitmap, GetDentrySlots(base.name.length()), DENTRY_PER_GROUP); + if (bitPos < DENTRY_PER_GROUP) { + found = true; + break; + } + } + ++level; + } + + pos = GetDentryGroupPos(bidx); + if (!UpdateDentry(dentryBlk, base, namehash, bitPos)) { + LOGI("UpdateDentry fail, stop write."); + return EINVAL; + } + int size = FileUtils::WriteFile(fd_, &dentryBlk, pos, DENTRYGROUP_SIZE); + if (size != DENTRYGROUP_SIZE) { + LOGI("WriteFile failed, size %{public}d != %{public}d", size, DENTRYGROUP_SIZE); + return EINVAL; + } + + return E_OK; +} + +struct DcacheLookupCtx { + int fd{-1}; + std::string name{}; + uint32_t hash{0}; + uint32_t bidx{0}; + std::unique_ptr page{nullptr}; +}; + +static void InitDcacheLookupCtx(DcacheLookupCtx *ctx, const MetaBase &base, int fd) +{ + ctx->fd = fd; + ctx->name = base.name; + ctx->bidx = 0; + ctx->page = nullptr; + ctx->hash = CloudDisk::CloudFileUtils::DentryHash(ctx->name); +} + +static std::unique_ptr FindDentryPage(uint64_t index, DcacheLookupCtx *ctx) +{ + auto dentryBlk = std::make_unique(); + + off_t pos = GetDentryGroupPos(index); + ssize_t size = FileUtils::ReadFile(ctx->fd, pos, DENTRYGROUP_SIZE, dentryBlk.get()); + if (size != DENTRYGROUP_SIZE) { + return nullptr; + } + return dentryBlk; +} + +static HmdfsDentry *FindInBlock(HmdfsDentryGroup &dentryBlk, uint32_t namehash, const std::string &name) +{ + int maxLen = 0; + uint32_t bitPos = 0; + HmdfsDentry *de = nullptr; + + while (bitPos < DENTRY_PER_GROUP) { + if (!BitOps::TestBit(bitPos, dentryBlk.bitmap)) { + bitPos++; + maxLen++; + continue; + } + de = &dentryBlk.nsl[bitPos]; + if (!de->namelen) { + bitPos++; + continue; + } + + if (de->hash == namehash && de->namelen == name.length() && + !memcmp(name.c_str(), dentryBlk.fileName[bitPos], de->namelen)) { + return de; + } + maxLen = 0; + bitPos += GetDentrySlots(de->namelen); + } + + return nullptr; +} + +static HmdfsDentry *InLevel(uint32_t level, DcacheLookupCtx *ctx) + __attribute__((no_sanitize("unsigned-integer-overflow"))) +{ + HmdfsDentry *de = nullptr; + + uint32_t nbucket = GetBucketByLevel(level); + if (!nbucket) { + return de; + } + + uint32_t bidx = GetBucketaddr(level, ctx->hash % nbucket) * BUCKET_BLOCKS; + uint32_t endBlock = bidx + BUCKET_BLOCKS; + + for (; bidx < endBlock; bidx++) { + auto dentryBlk = FindDentryPage(bidx, ctx); + if (dentryBlk == nullptr) { + break; + } + + de = FindInBlock(*dentryBlk, ctx->hash, ctx->name); + if (de != nullptr) { + ctx->page = std::move(dentryBlk); + break; + } + } + ctx->bidx = bidx; + return de; +} + +static uint32_t GetMaxLevel(int32_t fd) +{ + struct stat st; + if (fstat(fd, &st) == -1) { + return MAX_BUCKET_LEVEL; + } + uint32_t blkNum = static_cast(st.st_size) / DENTRYGROUP_SIZE + 1; + uint32_t maxLevel = 0; + blkNum >>= 1; + while (blkNum > 1) { + blkNum >>= 1; + maxLevel++; + } + return maxLevel; +} + +static HmdfsDentry *FindDentry(DcacheLookupCtx *ctx) +{ + uint32_t maxLevel = GetMaxLevel(ctx->fd); + for (uint32_t level = 0; level < maxLevel; level++) { + HmdfsDentry *de = InLevel(level, ctx); + if (de != nullptr) { + return de; + } + } + return nullptr; +} + +int32_t MetaFile::DoRemove(const MetaBase &base) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::unique_lock lock(mtx_); + DcacheLookupCtx ctx; + InitDcacheLookupCtx(&ctx, base, fd_); + HmdfsDentry *de = FindDentry(&ctx); + if (de == nullptr) { + LOGE("find dentry failed"); + return ENOENT; + } + + uint32_t bitPos = (de - ctx.page->nsl); + uint32_t slots = GetDentrySlots(de->namelen); + for (uint32_t i = 0; i < slots; i++) { + BitOps::ClearBit(bitPos + i, ctx.page->bitmap); + } + + off_t ipos = GetDentryGroupPos(ctx.bidx); + ssize_t size = FileUtils::WriteFile(fd_, ctx.page.get(), ipos, sizeof(HmdfsDentryGroup)); + if (size != sizeof(HmdfsDentryGroup)) { + LOGE("WriteFile failed!, ret = %{public}zd", size); + return EIO; + } + + return E_OK; +} + +int32_t MetaFile::DoLookup(MetaBase &base) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::unique_lock lock(mtx_); + struct DcacheLookupCtx ctx; + InitDcacheLookupCtx(&ctx, base, fd_); + struct HmdfsDentry *de = FindDentry(&ctx); + if (de == nullptr) { + LOGD("find dentry failed"); + return ENOENT; + } + + base.size = de->size; + base.mtime = de->mtime; + base.mode = de->mode; + base.fileType = de->fileType; + base.cloudId = std::string(reinterpret_cast(de->recordId), CLOUD_RECORD_ID_LEN - 1); + + return E_OK; +} + +int32_t MetaFile::DoUpdate(const MetaBase &base) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::unique_lock lock(mtx_); + struct DcacheLookupCtx ctx; + InitDcacheLookupCtx(&ctx, base, fd_); + struct HmdfsDentry *de = FindDentry(&ctx); + if (de == nullptr) { + LOGI("find dentry failed"); + return ENOENT; + } + + de->mtime = base.mtime; + de->size = base.size; + de->mode = base.mode; + de->fileType = base.fileType; + if (memcpy_s(de->recordId, CLOUD_RECORD_ID_LEN, base.cloudId.c_str(), base.cloudId.length())) { + LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", CLOUD_RECORD_ID_LEN, base.cloudId.length()); + } + + off_t ipos = GetDentryGroupPos(ctx.bidx); + ssize_t size = FileUtils::WriteFile(fd_, ctx.page.get(), ipos, sizeof(struct HmdfsDentryGroup)); + if (size != sizeof(struct HmdfsDentryGroup)) { + LOGI("write failed, ret = %{public}zd", size); + return EIO; + } + return E_OK; +} + +int32_t MetaFile::DoRename(const MetaBase &oldBase, const std::string &newName) +{ + MetaBase base{oldBase.name}; + int32_t ret = DoLookup(base); + if (ret) { + LOGE("ret = %{public}d, lookup %s failed", ret, GetAnonyString(base.name).c_str()); + return ret; + } + + base.name = newName; + ret = DoCreate(base); + if (ret) { + LOGE("ret = %{public}d, create %s failed", ret, GetAnonyString(base.name).c_str()); + return ret; + } + + base.name = oldBase.name; + ret = DoRemove(oldBase); + if (ret) { + LOGE("ret = %{public}d, remove %s failed", ret, GetAnonyString(oldBase.name).c_str()); + base.name = newName; + (void)DoRemove(base); + return ret; + } + + return E_OK; +} + +static int32_t DecodeDentrys(const HmdfsDentryGroup &dentryGroup, std::vector &bases) +{ + for (uint32_t i = 0; i < DENTRY_PER_GROUP; i++) { + int len = dentryGroup.nsl[i].namelen; + if (!BitOps::TestBit(i, dentryGroup.bitmap) || len == 0 || len >= PATH_MAX) { + continue; + } + + std::string name(reinterpret_cast(dentryGroup.fileName[i]), len); + + MetaBase base(name); + base.mode = dentryGroup.nsl[i].mode; + base.mtime = dentryGroup.nsl[i].mtime; + base.size = dentryGroup.nsl[i].size; + base.fileType = dentryGroup.nsl[i].fileType; + base.cloudId = std::string(reinterpret_cast(dentryGroup.nsl[i].recordId), CLOUD_RECORD_ID_LEN); + bases.emplace_back(base); + } + return 0; +} + +int32_t MetaFile::LoadChildren(std::vector &bases) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::lock_guard lock(mtx_); + struct stat fileStat; + int ret = fstat(fd_, &fileStat); + if (ret != E_OK) { + return EINVAL; + } + + uint64_t fileSize = static_cast(fileStat.st_size); + uint64_t groupCnt = GetDentryGroupCnt(fileSize); + HmdfsDentryGroup dentryGroup; + + for (uint64_t i = 1; i < groupCnt + 1; i++) { + uint64_t off = i * sizeof(HmdfsDentryGroup); + FileUtils::ReadFile(fd_, off, sizeof(HmdfsDentryGroup), &dentryGroup); + DecodeDentrys(dentryGroup, bases); + } + return E_OK; +} + +MetaFileMgr& MetaFileMgr::GetInstance() +{ + static MetaFileMgr instance_; + return instance_; +} + +std::shared_ptr MetaFileMgr::GetMetaFile(uint32_t userId, const std::string &path) +{ + std::shared_ptr mFile = nullptr; + std::lock_guard lock(mtx_); + + MetaFileKey key(userId, path); + auto it = metaFiles_.find(key); + if (it != metaFiles_.end()) { + metaFileList_.splice(metaFileList_.begin(), metaFileList_, it->second); + mFile = it->second->second; + } else { + mFile = std::make_shared(userId, path); + while (metaFiles_.size() >= MAX_META_FILE_NUM) { + auto deleteKey = metaFileList_.back().first; + metaFiles_.erase(deleteKey); + metaFileList_.pop_back(); + } + metaFileList_.emplace_front(key, mFile); + metaFiles_[key] = metaFileList_.begin(); + } + return mFile; +} + +int32_t MetaFileMgr::CheckMetaFileSize() +{ + std::lock_guard lock(mtx_); + if (metaFiles_.size() != metaFileList_.size()) { + return -1; + } + return metaFileList_.size(); +} + +void MetaFileMgr::ClearAll() +{ + std::lock_guard lock(mtx_); + metaFiles_.clear(); + metaFileList_.clear(); +} + +std::string MetaFileMgr::RecordIdToCloudId(const std::string hexStr) +{ + std::string result; + constexpr std::size_t offset = 2; + constexpr int changeBase = 16; + for (std::size_t i = 0; i < hexStr.length(); i += offset) { + std::string hexByte = hexStr.substr(i, offset); + char *endPtr; + unsigned long hexValue = std::strtoul(hexByte.c_str(), &endPtr, changeBase); + + if (endPtr != hexByte.c_str() + hexByte.length()) { + LOGE("Invalid hexadecimal string: %{public}s", hexStr.c_str()); + return ""; + } + result += static_cast(hexValue); + } + if (result.size() > CLOUD_RECORD_ID_LEN) { + LOGE("Invalid result length %{public}zu", result.size()); + return ""; + } + + return result; +} + +std::string MetaFileMgr::CloudIdToRecordId(const std::string cloudId) +{ + std::stringstream result; + constexpr int width = 2; + for (std::size_t i = 0; i < cloudId.length(); i++) { + uint8_t u8Byte = cloudId[i]; + result << std::setw(width) << std::setfill('0') << std::hex << static_cast(u8Byte); + } + return result.str(); +} + +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/utils/dentry/src/meta_file_clouddisk.cpp b/cloud_file/utils/dentry/src/meta_file_clouddisk.cpp new file mode 100644 index 0000000..6381662 --- /dev/null +++ b/cloud_file/utils/dentry/src/meta_file_clouddisk.cpp @@ -0,0 +1,843 @@ +/* + * Copyright (c) 2024 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 "meta_file.h" + +#include +#include +#include +#include +#include +#include + +#include "cloud_file_utils.h" +#include "dfs_error.h" +#include "file_utils.h" +#include "securec.h" +#include "string_ex.h" +#include "sys/xattr.h" +#include "utils_directory.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +constexpr uint32_t DENTRYGROUP_SIZE = 4096; +constexpr uint32_t DENTRY_NAME_LEN = 8; +constexpr uint32_t DENTRY_RESERVED_LENGTH = 4; +constexpr uint32_t DENTRY_PER_GROUP = 52; +constexpr uint32_t DENTRY_BITMAP_LENGTH = 7; +constexpr uint32_t DENTRY_GROUP_RESERVED = 32; +constexpr uint32_t CLOUD_RECORD_ID_LEN = 33; +constexpr uint32_t DENTRYGROUP_HEADER = 4096; +constexpr uint32_t MAX_BUCKET_LEVEL = 63; +constexpr uint32_t BUCKET_BLOCKS = 2; +constexpr uint32_t BITS_PER_BYTE = 8; +constexpr uint32_t HMDFS_SLOT_LEN_BITS = 3; +constexpr uint32_t FILE_TYPE_OFFSET = 2; +constexpr uint32_t NO_UPLOAD_OFFSET = 4; + +#pragma pack(push, 1) +struct HmdfsDentry { + uint32_t hash{0}; + uint16_t mode{0}; + uint16_t namelen{0}; + uint64_t size{0}; + uint64_t mtime{0}; + uint64_t atime{0}; + uint8_t recordId[CLOUD_RECORD_ID_LEN]{0}; + uint8_t flags{0}; + /* reserved bytes for long term extend, total 60 bytes */ + uint8_t reserved[DENTRY_RESERVED_LENGTH]; +}; + +struct HmdfsDentryGroup { + uint8_t dentryVersion; + uint8_t bitmap[DENTRY_BITMAP_LENGTH]; + struct HmdfsDentry nsl[DENTRY_PER_GROUP]; + uint8_t fileName[DENTRY_PER_GROUP][DENTRY_NAME_LEN]; + uint8_t reserved[DENTRY_GROUP_RESERVED]; +}; +static_assert(sizeof(HmdfsDentryGroup) == DENTRYGROUP_SIZE); + +struct HmdfsDcacheHeader { + uint64_t dcacheCrtime{0}; + uint64_t dcacheCrtimeNsec{0}; + + uint64_t dentryCtime{0}; + uint64_t dentryCtimeNsec{0}; + + uint64_t dentryCount{0}; +}; +#pragma pack(pop) + +void MetaHelper::SetFileType(struct HmdfsDentry *de, uint8_t fileType) +{ + de->flags &= 0x13; + de->flags |= (fileType << FILE_TYPE_OFFSET); +} + +void MetaHelper::SetPosition(struct HmdfsDentry *de, uint8_t position) +{ + de->flags &= 0xFC; + de->flags |= position; +} + +void MetaHelper::SetNoUpload(struct HmdfsDentry *de, uint8_t noUpload) +{ + de->flags &= 0xEF; + de->flags |= (noUpload << NO_UPLOAD_OFFSET); +} + +uint8_t MetaHelper::GetNoUpload(const struct HmdfsDentry *de) +{ + return (de->flags & 0x10) >> NO_UPLOAD_OFFSET; +} + +uint8_t MetaHelper::GetFileType(const struct HmdfsDentry *de) +{ + return (de->flags & 0xC) >> FILE_TYPE_OFFSET; +} + +uint8_t MetaHelper::GetPosition(const struct HmdfsDentry *de) +{ + return de->flags & 0x3; +} + +static std::string GetCloudDiskDentryFileByPath(uint32_t userId, const std::string &bundleName, + const std::string &cloudId) +{ + std::string cacheDir = + "/data/service/el2/" + std::to_string(userId) + + "/hmdfs/cloud/data/" + bundleName + "/" + + std::to_string(CloudDisk::CloudFileUtils::GetBucketId(cloudId)) + "/"; + std::string dentryFileName = MetaFileMgr::GetInstance().CloudIdToRecordId(cloudId); + Storage::DistributedFile::Utils::ForceCreateDirectory(cacheDir, STAT_MODE_DIR); + return cacheDir + dentryFileName; +} + +CloudDiskMetaFile::CloudDiskMetaFile(uint32_t userId, const std::string &bundleName, const std::string &cloudId) +{ + userId_ = userId; + bundleName_ = bundleName; + cloudId_ = cloudId; + cacheFile_ = GetCloudDiskDentryFileByPath(userId_, bundleName_, cloudId_); + fd_ = UniqueFd{open(cacheFile_.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)}; + LOGD("CloudDiskMetaFile cloudId=%{public}s, path=%{public}s", cloudId_.c_str(), GetAnonyString(cacheFile_).c_str()); + LOGD("CloudDiskMetaFile fd=%{public}d, errno :%{public}d", fd_.Get(), errno); + + HmdfsDcacheHeader header{}; + (void)FileUtils::ReadFile(fd_, 0, sizeof(header), &header); +} + +std::string CloudDiskMetaFile::GetDentryFilePath() +{ + return cacheFile_; +} + +int32_t CloudDiskMetaFile::DoLookupAndCreate(const std::string &name, CloudDiskMetaFileCallBack metaFileCallBack) +{ + MetaBase m(name); + /* lookup and create in parent */ + int32_t ret = DoLookup(m); + if (ret != E_OK) { + metaFileCallBack(m); + ret = DoCreate(m); + if (ret != E_OK) { + LOGE("create dentry file failed, ret %{public}d", ret); + return ret; + } + return ret; + } else { + LOGE("dentry file is not null"); + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoLookupAndUpdate(const std::string &name, CloudDiskMetaFileCallBack callback) +{ + MetaBase m(name); + /* lookup and create in parent */ + int32_t ret = DoLookup(m); + if (ret != E_OK) { + callback(m); + ret = DoCreate(m); + if (ret != E_OK) { + LOGE("create dentry file failed, ret %{public}d", ret); + return ret; + } + return ret; + } else { + callback(m); + ret = DoUpdate(m); + if (ret != E_OK) { + LOGE("update dentry file failed, ret %{public}d", ret); + return ret; + } + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoChildUpdate(const std::string &name, CloudDiskMetaFileCallBack callback) +{ + MetaBase m(name); + /* lookup and update */ + int32_t ret = DoLookup(m); + if (ret != E_OK) { + LOGE("lookup dentry file failed, ret %{public}d", ret); + return ret; + } else { + callback(m); + ret = DoUpdate(m); + if (ret != E_OK) { + LOGE("update dentry file failed, ret %{public}d", ret); + return ret; + } + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoLookupAndRemove(MetaBase &metaBase) +{ + /* lookup and remove in parent */ + int32_t ret = DoLookup(metaBase); + if (ret == E_OK) { + ret = DoRemove(metaBase); + if (ret != E_OK) { + LOGE("remove dentry file failed, ret %{public}d", ret); + return ret; + } + return E_OK; + } + return E_OK; +} + +CloudDiskMetaFile::~CloudDiskMetaFile() +{ +} + +static inline uint32_t GetDentrySlots(size_t nameLen) +{ + return static_cast((nameLen + BITS_PER_BYTE - 1) >> HMDFS_SLOT_LEN_BITS); +} + +static inline off_t GetDentryGroupPos(size_t bidx) +{ + return bidx * DENTRYGROUP_SIZE + DENTRYGROUP_HEADER; +} + +static inline uint64_t GetDentryGroupCnt(uint64_t size) +{ + return (size >= DENTRYGROUP_HEADER) ? ((size - DENTRYGROUP_HEADER) / DENTRYGROUP_SIZE) : 0; +} + +static uint32_t GetOverallBucket(uint32_t level) +{ + if (level >= MAX_BUCKET_LEVEL) { + LOGD("level = %{public}d overflow", level); + return 0; + } + uint64_t buckets = (1ULL << (level + 1)) - 1; + return static_cast(buckets); +} + +static size_t GetDcacheFileSize(uint32_t level) +{ + size_t buckets = GetOverallBucket(level); + return buckets * DENTRYGROUP_SIZE * BUCKET_BLOCKS + DENTRYGROUP_HEADER; +} + +static uint32_t GetBucketaddr(uint32_t level, uint32_t buckoffset) +{ + if (level >= MAX_BUCKET_LEVEL) { + return 0; + } + + uint64_t curLevelMaxBucks = (1ULL << level); + if (buckoffset >= curLevelMaxBucks) { + return 0; + } + + return static_cast(curLevelMaxBucks) + buckoffset - 1; +} + +static uint32_t GetBucketByLevel(uint32_t level) +{ + if (level >= MAX_BUCKET_LEVEL) { + LOGD("level = %{public}d overflow", level); + return 0; + } + + uint64_t buckets = (1ULL << level); + return static_cast(buckets); +} + +static uint32_t RoomForFilename(const uint8_t bitmap[], size_t slots, uint32_t maxSlots) +{ + uint32_t bitStart = 0; + bool loopFlag = true; + while (loopFlag) { + uint32_t zeroStart = BitOps::FindNextZeroBit(bitmap, maxSlots, bitStart); + if (zeroStart >= maxSlots) { + return maxSlots; + } + + uint32_t zeroEnd = BitOps::FindNextBit(bitmap, maxSlots, zeroStart); + if (zeroEnd - zeroStart >= slots) { + return zeroStart; + } + + bitStart = zeroEnd + 1; + if (zeroEnd + 1 >= maxSlots) { + return maxSlots; + } + } + return 0; +} + +static bool UpdateDentry(HmdfsDentryGroup &d, const MetaBase &base, uint32_t nameHash, uint32_t bitPos) +{ + HmdfsDentry *de; + const std::string name = base.name; + uint32_t slots = GetDentrySlots(name.length()); + + de = &d.nsl[bitPos]; + de->hash = nameHash; + de->namelen = name.length(); + auto ret = memcpy_s(d.fileName[bitPos], slots * DENTRY_NAME_LEN, name.c_str(), name.length()); + if (ret != 0) { + LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", slots * DENTRY_NAME_LEN, name.length()); + return false; + } + de->atime = base.atime; + de->mtime = base.mtime; + de->size = base.size; + de->mode = base.mode; + MetaHelper::SetPosition(de, base.position); + MetaHelper::SetFileType(de, base.fileType); + MetaHelper::SetNoUpload(de, base.noUpload); + (void) memset_s(de->recordId, CLOUD_RECORD_ID_LEN, 0, CLOUD_RECORD_ID_LEN); + ret = memcpy_s(de->recordId, CLOUD_RECORD_ID_LEN, base.cloudId.c_str(), base.cloudId.length()); + if (ret != 0) { + LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", CLOUD_RECORD_ID_LEN, base.cloudId.length()); + return false; + } + + for (uint32_t i = 0; i < slots; i++) { + BitOps::SetBit(bitPos + i, d.bitmap); + if (i) { + (de + i)->namelen = 0; + } + } + return true; +} + +int32_t CloudDiskMetaFile::HandleFileByFd(unsigned long &endBlock, uint32_t &level) +{ + struct stat fileStat; + int err = fstat(fd_, &fileStat); + if (err < 0) { + return EINVAL; + } + if ((endBlock > GetDentryGroupCnt(fileStat.st_size)) && + ftruncate(fd_, GetDcacheFileSize(level))) { + return ENOENT; + } + return E_OK; +} + +static unsigned long GetBidxFromLevel(uint32_t level, uint32_t namehash) +{ + uint32_t bucket = GetBucketByLevel(level); + if (bucket == 0) { + return 0; + } + return BUCKET_BLOCKS * GetBucketaddr(level, namehash % bucket); +} + +struct DcacheLookupCtx { + int fd{-1}; + std::string name{}; + uint32_t hash{0}; + uint32_t bidx{0}; + std::unique_ptr page{nullptr}; +}; + +static void InitDcacheLookupCtx(DcacheLookupCtx *ctx, const MetaBase &base, int fd) +{ + ctx->fd = fd; + ctx->name = base.name; + ctx->bidx = 0; + ctx->page = nullptr; + ctx->hash = CloudDisk::CloudFileUtils::DentryHash(ctx->name); +} + +static std::unique_ptr FindDentryPage(uint64_t index, DcacheLookupCtx *ctx) +{ + auto dentryBlk = std::make_unique(); + + off_t pos = GetDentryGroupPos(index); + ssize_t size = FileUtils::ReadFile(ctx->fd, pos, DENTRYGROUP_SIZE, dentryBlk.get()); + if (size != DENTRYGROUP_SIZE) { + return nullptr; + } + return dentryBlk; +} + +static HmdfsDentry *FindInBlock(HmdfsDentryGroup &dentryBlk, uint32_t namehash, const std::string &name) +{ + int maxLen = 0; + uint32_t bitPos = 0; + HmdfsDentry *de = nullptr; + + while (bitPos < DENTRY_PER_GROUP) { + if (!BitOps::TestBit(bitPos, dentryBlk.bitmap)) { + bitPos++; + maxLen++; + continue; + } + de = &dentryBlk.nsl[bitPos]; + if (!de->namelen) { + bitPos++; + continue; + } + + if (de->hash == namehash && de->namelen == name.length() && + !memcmp(name.c_str(), dentryBlk.fileName[bitPos], de->namelen)) { + return de; + } + maxLen = 0; + bitPos += GetDentrySlots(de->namelen); + } + + return nullptr; +} + +static HmdfsDentry *InLevel(uint32_t level, DcacheLookupCtx *ctx) + __attribute__((no_sanitize("unsigned-integer-overflow"))) +{ + HmdfsDentry *de = nullptr; + + uint32_t nbucket = GetBucketByLevel(level); + if (nbucket == 0) { + return de; + } + + uint32_t bidx = GetBucketaddr(level, ctx->hash % nbucket) * BUCKET_BLOCKS; + uint32_t endBlock = bidx + BUCKET_BLOCKS; + + for (; bidx < endBlock; bidx++) { + auto dentryBlk = FindDentryPage(bidx, ctx); + if (dentryBlk == nullptr) { + break; + } + + de = FindInBlock(*dentryBlk, ctx->hash, ctx->name); + if (de != nullptr) { + ctx->page = std::move(dentryBlk); + break; + } + } + ctx->bidx = bidx; + return de; +} + +static HmdfsDentry *FindDentry(DcacheLookupCtx *ctx) +{ + for (uint32_t level = 0; level < MAX_BUCKET_LEVEL; level++) { + HmdfsDentry *de = InLevel(level, ctx); + if (de != nullptr) { + return de; + } + } + return nullptr; +} + +int32_t CloudDiskMetaFile::GetCreateInfo(const MetaBase &base, uint32_t &bitPos, uint32_t &namehash, + unsigned long &bidx, struct HmdfsDentryGroup &dentryBlk) +{ + uint32_t level = 0; + namehash = CloudDisk::CloudFileUtils::DentryHash(base.name); + bool found = false; + while (!found) { + if (level == MAX_BUCKET_LEVEL) { + return ENOSPC; + } + bidx = GetBidxFromLevel(level, namehash); + unsigned long endBlock = bidx + BUCKET_BLOCKS; + int32_t ret = HandleFileByFd(endBlock, level); + if (ret != E_OK) { + return ret; + } + for (; bidx < endBlock; bidx++) { + off_t pos = GetDentryGroupPos(bidx); + if (FileUtils::ReadFile(fd_, pos, DENTRYGROUP_SIZE, &dentryBlk) != DENTRYGROUP_SIZE) { + return ENOENT; + } + bitPos = RoomForFilename(dentryBlk.bitmap, GetDentrySlots(base.name.length()), DENTRY_PER_GROUP); + if (bitPos < DENTRY_PER_GROUP) { + found = true; + break; + } + } + ++level; + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoCreate(const MetaBase &base) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::unique_lock lock(mtx_); + DcacheLookupCtx ctx; + InitDcacheLookupCtx(&ctx, base, fd_); + HmdfsDentry *de = FindDentry(&ctx); + if (de != nullptr) { + LOGE("this name dentry is exist"); + return EEXIST; + } + uint32_t bitPos = 0; + unsigned long bidx = 0; + HmdfsDentryGroup dentryBlk = {0}; + uint32_t namehash = 0; + GetCreateInfo(base, bitPos, namehash, bidx, dentryBlk); + off_t pos = GetDentryGroupPos(bidx); + if (!UpdateDentry(dentryBlk, base, namehash, bitPos)) { + LOGI("UpdateDentry fail, stop write."); + return EINVAL; + } + int size = FileUtils::WriteFile(fd_, &dentryBlk, pos, DENTRYGROUP_SIZE); + if (size != DENTRYGROUP_SIZE) { + LOGD("WriteFile failed, size %{public}d != %{public}d", size, DENTRYGROUP_SIZE); + return EINVAL; + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoRemove(const MetaBase &base) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::unique_lock lock(mtx_); + DcacheLookupCtx ctx; + InitDcacheLookupCtx(&ctx, base, fd_); + HmdfsDentry *de = FindDentry(&ctx); + if (de == nullptr) { + LOGE("find dentry failed"); + return ENOENT; + } + + uint32_t bitPos = (de - ctx.page->nsl); + uint32_t slots = GetDentrySlots(de->namelen); + for (uint32_t i = 0; i < slots; i++) { + BitOps::ClearBit(bitPos + i, ctx.page->bitmap); + } + + off_t ipos = GetDentryGroupPos(ctx.bidx); + ssize_t size = FileUtils::WriteFile(fd_, ctx.page.get(), ipos, sizeof(HmdfsDentryGroup)); + if (size != sizeof(HmdfsDentryGroup)) { + LOGE("WriteFile failed!, ret = %{public}zd", size); + return EIO; + } + + return E_OK; +} + +int32_t CloudDiskMetaFile::DoLookup(MetaBase &base) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::unique_lock lock(mtx_); + struct DcacheLookupCtx ctx; + InitDcacheLookupCtx(&ctx, base, fd_); + struct HmdfsDentry *de = FindDentry(&ctx); + if (de == nullptr) { + LOGD("find dentry failed"); + return ENOENT; + } + + base.size = de->size; + base.atime = de->atime; + base.mtime = de->mtime; + base.mode = de->mode; + base.position = MetaHelper::GetPosition(de); + base.fileType = MetaHelper::GetFileType(de); + base.noUpload = MetaHelper::GetNoUpload(de); + base.cloudId = std::string(reinterpret_cast(de->recordId), CLOUD_RECORD_ID_LEN); + return E_OK; +} + +int32_t CloudDiskMetaFile::DoUpdate(const MetaBase &base) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::unique_lock lock(mtx_); + struct DcacheLookupCtx ctx; + InitDcacheLookupCtx(&ctx, base, fd_); + struct HmdfsDentry *de = FindDentry(&ctx); + if (de == nullptr) { + LOGD("find dentry failed"); + return ENOENT; + } + + de->atime = base.atime; + de->mtime = base.mtime; + de->size = base.size; + de->mode = base.mode; + MetaHelper::SetPosition(de, base.position); + MetaHelper::SetFileType(de, base.fileType); + MetaHelper::SetNoUpload(de, base.noUpload); + auto ret = memcpy_s(de->recordId, CLOUD_RECORD_ID_LEN, base.cloudId.c_str(), base.cloudId.length()); + if (ret != 0) { + LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", CLOUD_RECORD_ID_LEN, base.cloudId.length()); + } + + off_t ipos = GetDentryGroupPos(ctx.bidx); + ssize_t size = FileUtils::WriteFile(fd_, ctx.page.get(), ipos, sizeof(struct HmdfsDentryGroup)); + if (size != sizeof(struct HmdfsDentryGroup)) { + LOGE("write failed, ret = %{public}zd", size); + return EIO; + } + return E_OK; +} + +int32_t CloudDiskMetaFile::DoRename(MetaBase &metaBase, const std::string &newName, + std::shared_ptr newMetaFile) +{ + std::string oldName = metaBase.name; + metaBase.name = newName; + int32_t ret = newMetaFile->DoCreate(metaBase); + if (ret != E_OK) { + LOGE("create dentry failed, ret = %{public}d", ret); + return ret; + } + metaBase.name = oldName; + ret = DoRemove(metaBase); + if (ret != E_OK) { + LOGE("remove dentry failed, ret = %{public}d", ret); + metaBase.name = newName; + (void)newMetaFile->DoRemove(metaBase); + return ret; + } + return E_OK; +} + +static int32_t DecodeDentrys(const HmdfsDentryGroup &dentryGroup, std::vector &bases) +{ + for (uint32_t i = 0; i < DENTRY_PER_GROUP; i++) { + int len = dentryGroup.nsl[i].namelen; + if (!BitOps::TestBit(i, dentryGroup.bitmap) || len == 0 || len >= PATH_MAX) { + continue; + } + + std::string name(reinterpret_cast(dentryGroup.fileName[i]), len); + + MetaBase base(name); + base.mode = dentryGroup.nsl[i].mode; + base.mtime = dentryGroup.nsl[i].mtime; + base.size = dentryGroup.nsl[i].size; + base.position = MetaHelper::GetPosition(&dentryGroup.nsl[i]); + base.fileType = MetaHelper::GetFileType(&dentryGroup.nsl[i]); + base.cloudId = std::string(reinterpret_cast(dentryGroup.nsl[i].recordId), CLOUD_RECORD_ID_LEN); + bases.emplace_back(base); + } + return 0; +} + +int32_t CloudDiskMetaFile::LoadChildren(std::vector &bases) +{ + if (fd_ < 0) { + LOGE("bad metafile fd"); + return EINVAL; + } + + std::lock_guard lock(mtx_); + struct stat fileStat; + int ret = fstat(fd_, &fileStat); + if (ret != E_OK) { + return EINVAL; + } + + uint64_t fileSize = static_cast(fileStat.st_size); + uint64_t groupCnt = GetDentryGroupCnt(fileSize); + HmdfsDentryGroup dentryGroup; + + for (uint64_t i = 1; i < groupCnt + 1; i++) { + uint64_t off = i * sizeof(HmdfsDentryGroup); + FileUtils::ReadFile(fd_, off, sizeof(HmdfsDentryGroup), &dentryGroup); + DecodeDentrys(dentryGroup, bases); + } + return E_OK; +} + +void MetaFileMgr::Clear(uint32_t userId, const std::string &bundleName, + const std::string &cloudId) +{ + std::lock_guard lock(cloudDiskMutex_); + MetaFileKey key(userId, cloudId + bundleName); + cloudDiskMetaFile_.erase(key); + cloudDiskMetaFileList_.remove_if([key](CloudDiskMetaFileListEle &item) { return item.first == key; }); +} + +void MetaFileMgr::CloudDiskClearAll() +{ + std::lock_guard lock(cloudDiskMutex_); + cloudDiskMetaFile_.clear(); + cloudDiskMetaFileList_.clear(); +} + +std::shared_ptr MetaFileMgr::GetCloudDiskMetaFile(uint32_t userId, const std::string &bundleName, + const std::string &cloudId) +{ + std::shared_ptr mFile = nullptr; + std::lock_guard lock(cloudDiskMutex_); + MetaFileKey key(userId, cloudId + bundleName); + auto it = cloudDiskMetaFile_.find(key); + if (it != cloudDiskMetaFile_.end()) { + cloudDiskMetaFileList_.splice(cloudDiskMetaFileList_.begin(), cloudDiskMetaFileList_, it->second); + mFile = it->second->second; + } else { + if (cloudDiskMetaFile_.size() == MAX_CLOUDDISK_META_FILE_NUM) { + auto deleteKey = cloudDiskMetaFileList_.back().first; + cloudDiskMetaFile_.erase(deleteKey); + cloudDiskMetaFileList_.pop_back(); + } + mFile = std::make_shared(userId, bundleName, cloudId); + cloudDiskMetaFileList_.emplace_front(key, mFile); + cloudDiskMetaFile_[key] = cloudDiskMetaFileList_.begin(); + } + return mFile; +} + +int32_t MetaFileMgr::CreateRecycleDentry(uint32_t userId, const std::string &bundleName) +{ + MetaBase metaBase(RECYCLE_NAME); + auto metaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, ROOT_CLOUD_ID); + int32_t ret = metaFile->DoLookup(metaBase); + if (ret != 0) { + metaBase.cloudId = RECYCLE_CLOUD_ID; + metaBase.mode = S_IFDIR | STAT_MODE_DIR; + metaBase.position = static_cast(LOCAL); + ret = metaFile->DoCreate(metaBase); + if (ret != 0) { + return ret; + } + } + return 0; +} + +int32_t MetaFileMgr::MoveIntoRecycleDentryfile(uint32_t userId, const std::string &bundleName, const std::string &name, + const std::string &parentCloudId, int64_t rowId) +{ + MetaBase metaBase(name); + auto srcMetaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, parentCloudId); + auto dstMetaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, RECYCLE_CLOUD_ID); + std::string uniqueName = name + "_" + std::to_string(rowId); + int32_t ret = srcMetaFile->DoLookup(metaBase); + if (ret != E_OK) { + LOGE("lookup src metafile failed, ret = %{public}d", ret); + return ret; + } + metaBase.name = uniqueName; + ret = dstMetaFile->DoCreate(metaBase); + if (ret != E_OK) { + LOGE("lookup and remove dentry failed, ret = %{public}d", ret); + return ret; + } + metaBase.name = name; + ret = srcMetaFile->DoLookupAndRemove(metaBase); + if (ret != E_OK) { + LOGE("lookup and remove dentry failed, ret = %{public}d", ret); + metaBase.name = uniqueName; + (void)dstMetaFile->DoLookupAndRemove(metaBase); + return ret; + } + return E_OK; +} + +int32_t MetaFileMgr::RemoveFromRecycleDentryfile(uint32_t userId, const std::string &bundleName, + const struct RestoreInfo &restoreInfo) +{ + auto srcMetaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, RECYCLE_CLOUD_ID); + auto dstMetaFile = MetaFileMgr::GetInstance().GetCloudDiskMetaFile(userId, bundleName, restoreInfo.parentCloudId); + std::string uniqueName = restoreInfo.oldName + "_" + std::to_string(restoreInfo.rowId); + MetaBase metaBase(uniqueName); + int32_t ret = srcMetaFile->DoLookup(metaBase); + if (ret != E_OK) { + LOGE("lookup and update dentry failed, ret = %{public}d", ret); + return ret; + } + metaBase.name = restoreInfo.newName; + ret = dstMetaFile->DoCreate(metaBase); + if (ret != E_OK) { + LOGE("lookup and remove dentry failed, ret = %{public}d", ret); + return ret; + } + metaBase.name = uniqueName; + ret = srcMetaFile->DoLookupAndRemove(metaBase); + if (ret != E_OK) { + LOGE("lookup and remove dentry failed, ret = %{public}d", ret); + metaBase.name = restoreInfo.newName; + (void)dstMetaFile->DoLookupAndRemove(metaBase); + return ret; + } + return E_OK; +} + +int32_t MetaFileMgr::GetNewName(std::shared_ptr metaFile, const std::string &oldName, + std::string &newName) +{ + std::vector metaBases; + int32_t ret = metaFile->LoadChildren(metaBases); + if (ret != E_OK) { + LOGE("load children dentry fail. ret = %{public}d", ret); + return ret; + } + + size_t lastDot = oldName.rfind('.'); + if (lastDot == std::string::npos) { + lastDot = oldName.length(); + } + std::string name = oldName.substr(0, lastDot); + std::string extension = oldName.substr(lastDot); + int32_t renameTimes = 1; + std::unordered_set fileNames; + for (const MetaBase &meta : metaBases) { + fileNames.insert(meta.name); + } + bool conflict = true; + while (conflict) { + newName = name + "(" + std::to_string(renameTimes) + ")" + extension; + if (fileNames.find(newName) == fileNames.end()) { + conflict = false; + } + renameTimes++; + } + return E_OK; +} +} // namespace FileManagement +} // namespace OHOS diff --git a/cloud_file/utils/dfx/src/xcollie_helper.cpp b/cloud_file/utils/dfx/src/xcollie_helper.cpp new file mode 100644 index 0000000..3c8dd85 --- /dev/null +++ b/cloud_file/utils/dfx/src/xcollie_helper.cpp @@ -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. + */ + +#include "xcollie_helper.h" + +#include "xcollie/xcollie_define.h" +#include "utils_log.h" +#include "dfs_error.h" + +namespace OHOS::FileManagement { +using namespace std; +int XCollieHelper::SetTimer(const std::string &name, uint32_t timeout, XCollieCallback func, void *arg, bool recovery) +{ +#ifdef HICOLLIE_ENABLE + unsigned int flag = HiviewDFX::XCOLLIE_FLAG_LOG | HiviewDFX::XCOLLIE_FLAG_NOOP; + if (recovery) { + flag |= HiviewDFX::XCOLLIE_FLAG_RECOVERY; + } + return HiviewDFX::XCollie::GetInstance().SetTimer(name, timeout, func, arg, flag); +#else + LOGI("XCollie not supported"); + return HiviewDFX::INVALID_ID; +#endif +} +void XCollieHelper::CancelTimer(int id) +{ +#ifdef HICOLLIE_ENABLE + HiviewDFX::XCollie::GetInstance().CancelTimer(id); +#endif +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/utils/ffrt/src/ffrt_timer.cpp b/cloud_file/utils/ffrt/src/ffrt_timer.cpp new file mode 100644 index 0000000..5b0c564 --- /dev/null +++ b/cloud_file/utils/ffrt/src/ffrt_timer.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2024 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 "ffrt_timer.h" + +#include "cloud_file_log.h" + +namespace OHOS::FileManagement::CloudFile { +static constexpr uint32_t TIMER_MAX_INTERVAL_MS = 200; +using namespace std; + +FfrtTimer::FfrtTimer(const std::string &name) : name_(name) {} + +FfrtTimer ::~FfrtTimer() +{ + Stop(); +} + +void FfrtTimer::Start(const TimerCallback &callback, uint32_t interval, uint32_t repatTimes) +{ + unique_lock lock(taskMutex_); + if (running_ == true) { + LOGE("timer may be is running, timerName:%{public}s", name_.c_str()); + return; + } + LOGD("start timer, timerName:%{public}s", name_.c_str()); + running_ = true; + auto task = [this, interval, callback, repatTimes]() { + LOGD("task entering loop"); + uint32_t times = repatTimes; + while (times > 0) { + callback(); + times--; + unique_lock lock(sleepMutex_); + bool stop = + sleepCv_.wait_for(lock, std::chrono::milliseconds(interval), [this]() { return !this->running_; }); + if (stop) { // is stopped + break; + } + } + LOGD("task leaving loop"); + }; + + isJoinable_ = std::make_unique(true); + ffrt::submit(task, {}, {isJoinable_.get()}, ffrt::task_attr().name(name_.c_str())); +} + +void FfrtTimer::Stop() +{ + unique_lock lock(taskMutex_); + if (running_ == false) { + LOGE("timer may be is stopped, timerName:%{public}s", name_.c_str()); + return; + } + + LOGD("stop timer, timerName:%{public}s", name_.c_str()); + { + std::unique_lock lock(sleepMutex_); + running_ = false; + sleepCv_.notify_one(); + } + + if (isJoinable_.get() && *isJoinable_) { + ffrt::wait({isJoinable_.get()}); + *isJoinable_ = false; + } + LOGD("timer is stoped, timerName:%{public}s", name_.c_str()); +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/utils/inner_api/block_object.h b/cloud_file/utils/inner_api/block_object.h new file mode 100644 index 0000000..0510389 --- /dev/null +++ b/cloud_file/utils/inner_api/block_object.h @@ -0,0 +1,66 @@ +/* +* Copyright (c) 2024 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 FILEMANAGEMENT_cloud_file_BLOCK_OBJECT_H +#define FILEMANAGEMENT_cloud_file_BLOCK_OBJECT_H + +#include +#include + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +template +class BlockObject { +public: + explicit BlockObject(uint32_t interval, const T &invalid = T()) : interval_(interval), data_(invalid) + { + } + ~BlockObject() = default; + + void SetValue(T data) + { + std::lock_guard lock(mutex_); + data_ = std::move(data); + isSet_ = true; + cv_.notify_one(); + } + + T GetValue() + { + std::unique_lock lock(mutex_); + cv_.wait_for(lock, std::chrono::milliseconds(interval_), [this]() { return isSet_; }); + isSet_ = false; + T data = std::move(data_); + cv_.notify_one(); + return data; + } + + void SetInterval(uint32_t interval) + { + interval_ = interval; + } + +private: + uint32_t interval_; + bool isSet_ = false; + std::mutex mutex_; + std::condition_variable cv_; + T data_; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // FILEMANAGEMENT_cloud_file_BLOCK_OBJECT_H diff --git a/cloud_file/utils/inner_api/cloud_file_error.h b/cloud_file/utils/inner_api/cloud_file_error.h new file mode 100644 index 0000000..2dfb263 --- /dev/null +++ b/cloud_file/utils/inner_api/cloud_file_error.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_FILE_ERROR_H +#define OHOS_CLOUD_FILE_CLOUD_FILE_ERROR_H + +#include "dfs_error.h" + +#endif // OHOS_CLOUD_FILE_CLOUD_FILE_ERROR_H \ No newline at end of file diff --git a/cloud_file/utils/inner_api/cloud_file_log.h b/cloud_file/utils/inner_api/cloud_file_log.h new file mode 100644 index 0000000..41aba22 --- /dev/null +++ b/cloud_file/utils/inner_api/cloud_file_log.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_FILE_LOG_H +#define OHOS_CLOUD_FILE_CLOUD_FILE_LOG_H + +#include "utils_log.h" + +#endif // OHOS_CLOUD_FILE_CLOUD_FILE_LOG_H \ No newline at end of file diff --git a/cloud_file/utils/inner_api/cloud_file_timer.h b/cloud_file/utils/inner_api/cloud_file_timer.h new file mode 100644 index 0000000..c0a2568 --- /dev/null +++ b/cloud_file/utils/inner_api/cloud_file_timer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_FILE_TIMER_H +#define OHOS_CLOUD_FILE_CLOUD_FILE_TIMER_H + +#include "dfsu_timer.h" + +#endif // OHOS_CLOUD_FILE_CLOUD_FILE_TIMER_H \ No newline at end of file diff --git a/cloud_file/utils/inner_api/cloud_file_utils.h b/cloud_file/utils/inner_api/cloud_file_utils.h new file mode 100644 index 0000000..6ed9172 --- /dev/null +++ b/cloud_file/utils/inner_api/cloud_file_utils.h @@ -0,0 +1,88 @@ +/* + * 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 CLOUD_FILE_DAEMON_CLOUD_FILE_UTILS_H +#define CLOUD_FILE_DAEMON_CLOUD_FILE_UTILS_H + +#include +#include +namespace OHOS { +namespace FileManagement { +namespace CloudDisk { +struct CloudDiskFileInfo { + std::string name; + std::string cloudId; + std::string parentCloudId; + uint32_t location{1}; + uint32_t mode{S_IFREG}; + int64_t localId{0}; + unsigned long long rowId{0}; + unsigned long long size{0}; + unsigned long long atime{0}; + unsigned long long ctime{0}; + unsigned long long mtime{0}; + bool IsDirectory{false}; + off_t nextOff{0}; +}; + +namespace { + static const std::string CLOUD_CLOUD_ID_XATTR = "user.cloud.cloudid"; + static const std::string CLOUD_FILE_LOCATION = "user.cloud.location"; + static const std::string HMDFS_PERMISSION_XATTR = "user.hmdfs.perm"; + static const std::string CLOUD_CLOUD_RECYCLE_XATTR = "user.cloud.recycle"; + static const std::string IS_FAVORITE_XATTR = "user.cloud.favorite"; + static const std::string IS_FILE_STATUS_XATTR = "user.cloud.filestatus"; + static const std::string CLOUD_EXT_ATTR = "extended_attributes"; + static const std::string CLOUD_HAS_LCD = "user.cloud.hasLcdThumbnail"; + static const std::string CLOUD_HAS_THM = "user.cloud.hasThumbnail"; + static const std::string CLOUD_TIME_RECYCLED = "user.cloud.deletetime"; + static const std::string CLOUD_RECYCLE_PATH = "user.cloud.recyclePath"; +} + +class CloudFileUtils final { +public: + static bool CheckIsCloud(const std::string &key); + static bool CheckIsCloudLocation(const std::string &key); + static bool CheckIsHasLCD(const std::string &key); + static bool CheckIsHasTHM(const std::string &key); + static bool CheckIsHmdfsPermission(const std::string &key); + static bool CheckIsCloudRecycle(const std::string &key); + static bool CheckIsFavorite(const std::string &key); + static bool CheckFileStatus(const std::string &key); + static bool CheckIsTimeRecycled(const std::string &key); + static bool CheckIsRecyclePath(const std::string &key); + static std::string GetLocalBucketPath(std::string cloudId, std::string bundleName, + int32_t userId); + static std::string GetLocalDKCachePath(std::string cloudId, std::string bundleName, int32_t userId); + static std::string GetLocalFilePath(std::string cloudId, std::string bundleName, + int32_t userId); + static std::string GetPathWithoutTmp(const std::string &path); + static std::string GetCloudId(const std::string &path); + static std::string GetRealPath(const std::string &path); + static uint32_t GetBucketId(std::string cloudId); + static int64_t Timespec2Milliseconds(const struct timespec &time); + static bool LocalWriteOpen(const std::string &dfsPath); + static bool ClearCache(const std::string &dfsPath); + static uint32_t DentryHash(const std::string &cloudId); + static void TeaTransform(uint32_t buf[4], uint32_t const in[]); + static void Str2HashBuf(const char *msg, size_t len, uint32_t *buf, int num); + static bool IsDotDotdot(const std::string &name); + static const std::string TMP_SUFFIX; +private: + static bool EndsWith(const std::string &fullString, const std::string &ending); +}; +} // namespace CloudDisk +} // namespace FileManagement +} // namespace OHOS +#endif // CLOUD_FILE_DAEMON_CLOUD_FILE_UTILS_H diff --git a/cloud_file/utils/inner_api/cloud_meta_file.h b/cloud_file/utils/inner_api/cloud_meta_file.h new file mode 100644 index 0000000..41d16c9 --- /dev/null +++ b/cloud_file/utils/inner_api/cloud_meta_file.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_CLOUD_META_FILE_H +#define OHOS_CLOUD_FILE_CLOUD_META_FILE_H + +#include "meta_file.h" + +#endif // OHOS_CLOUD_FILE_CLOUD_META_FILE_H \ No newline at end of file diff --git a/cloud_file/utils/inner_api/cloud_pref_impl.h b/cloud_file/utils/inner_api/cloud_pref_impl.h new file mode 100644 index 0000000..2abed43 --- /dev/null +++ b/cloud_file/utils/inner_api/cloud_pref_impl.h @@ -0,0 +1,46 @@ +/* + * 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 OHOS_FILEMGMT_CLOUD_PREF_IMPL_H +#define OHOS_FILEMGMT_CLOUD_PREF_IMPL_H +#include "preferences.h" +#include "preferences_helper.h" + +namespace OHOS::FileManagement::CloudSync { +const static std::string START_CURSOR = "start_cursor"; +const static std::string NEXT_CURSOR = "next_cursor"; +const static std::string TEMP_START_CURSOR = "temp_start_cursor"; +class CloudPrefImpl { +public: + CloudPrefImpl(const std::string& fileName); + CloudPrefImpl(const int32_t userId, const std::string& bundleName, const std::string& tableName); + ~CloudPrefImpl() = default;; + + void SetString(const std::string& key, const std::string& value); + void GetString(const std::string& key, std::string& value); + void SetLong(const std::string& key, const int64_t value); + void GetLong(const std::string& key, int64_t& value); + void SetInt(const std::string& key, const int value); + void GetInt(const std::string& key, int32_t& value); + void SetBool(const std::string& key, const bool& value); + void GetBool(const std::string& key, bool& value); + void Clear(); + void Delete(const std::string& key); + +private: + std::string fileName_; + std::shared_ptr pref_; +}; +} +#endif // OHOS_FILEMGMT_CLOUD_PREF_IMPL_H \ No newline at end of file diff --git a/cloud_file/utils/inner_api/fdsan.h b/cloud_file/utils/inner_api/fdsan.h new file mode 100644 index 0000000..e3ec008 --- /dev/null +++ b/cloud_file/utils/inner_api/fdsan.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2024 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 OHOS_FILEMGMT_FDSAN_H +#define OHOS_FILEMGMT_FDSAN_H + +#include + +struct fdsan_fd { + fdsan_fd() = default; + + explicit fdsan_fd(int fd) + { + reset(fd); + } + + fdsan_fd(const fdsan_fd& copy) = delete; + fdsan_fd(fdsan_fd&& move) + { + *this = std::move(move); + } + + ~fdsan_fd() + { + reset(); + } + + fdsan_fd& operator=(const fdsan_fd& copy) = delete; + fdsan_fd& operator=(fdsan_fd&& move) + { + if (this == &move) { + return *this; + } + reset(); + if (move.fd_ != -1) { + fd_ = move.fd_; + move.fd_ = -1; + // Acquire ownership from the moved-from object. + exchange_tag(fd_, move.tag(), tag()); + } + return *this; + } + + int get() + { + return fd_; + } + + void reset(int new_fd = -1) + { + if (fd_ != -1) { + close(fd_, tag()); + fd_ = -1; + } + if (new_fd != -1) { + fd_ = new_fd; + // Acquire ownership of the presumably unowned fd. + exchange_tag(fd_, 0, tag()); + } + } + + private: + int fd_ = -1; + + // Use the address of object as the file tag + uint64_t tag() + { + return reinterpret_cast(this); + } + + static void exchange_tag(int fd, uint64_t old_tag, uint64_t new_tag) + { + if (&fdsan_exchange_owner_tag) { + fdsan_exchange_owner_tag(fd, old_tag, new_tag); + } + } + + static int close(int fd, uint64_t tag) + { + if (&fdsan_close_with_tag) { + return fdsan_close_with_tag(fd, tag); + } + } +}; +#endif // OHOS_FILEMGMT_FDSAN_H \ No newline at end of file diff --git a/cloud_file/utils/inner_api/ffrt_timer.h b/cloud_file/utils/inner_api/ffrt_timer.h new file mode 100644 index 0000000..f84c090 --- /dev/null +++ b/cloud_file/utils/inner_api/ffrt_timer.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_FFRT_TIMER_H +#define OHOS_CLOUD_FILE_FFRT_TIMER_H + +#include +#include +#include + +#include "ffrt_inner.h" + +namespace OHOS::FileManagement::CloudFile { +using TimerCallback = std::function; +class FfrtTimer { +public: + explicit FfrtTimer(const std::string &name); + ~FfrtTimer(); + + void Start(const TimerCallback &callback, uint32_t interval, uint32_t repatTimes = UINT32_MAX); + void Stop(); + +private: + std::string name_; + ffrt::mutex taskMutex_; + std::atomic_bool running_{false}; + ffrt::mutex sleepMutex_; + ffrt::condition_variable sleepCv_; + std::unique_ptr isJoinable_{nullptr}; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_FFRT_TIMER_H \ No newline at end of file diff --git a/cloud_file/utils/inner_api/visibility.h b/cloud_file/utils/inner_api/visibility.h new file mode 100644 index 0000000..028e0ff --- /dev/null +++ b/cloud_file/utils/inner_api/visibility.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_VISIBILITY_H +#define OHOS_CLOUD_FILE_VISIBILITY_H + +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility ("default"))) +#endif +#ifndef API_LOCAL +#define API_LOCAL __attribute__((visibility ("hidden"))) +#endif + +#endif // OHOS_CLOUD_FILE_VISIBILITY_H \ No newline at end of file diff --git a/cloud_file/utils/inner_api/xcollie_helper.h b/cloud_file/utils/inner_api/xcollie_helper.h new file mode 100644 index 0000000..1d6451c --- /dev/null +++ b/cloud_file/utils/inner_api/xcollie_helper.h @@ -0,0 +1,29 @@ +/* + * 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 OHOS_FILEMGMT_XCOLLIE_HELPER_H +#define OHOS_FILEMGMT_XCOLLIE_HELPER_H + +#include "xcollie/xcollie.h" + +namespace OHOS::FileManagement { +class XCollieHelper { +public: + static int SetTimer(const std::string &name, uint32_t timeout, XCollieCallback func, void *arg, bool recovery); + static void CancelTimer(int id); +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_XCOLLIE_HELPER_H \ No newline at end of file diff --git a/cloud_file/utils/load/include/plugin_loader.h b/cloud_file/utils/load/include/plugin_loader.h new file mode 100644 index 0000000..8c834f4 --- /dev/null +++ b/cloud_file/utils/load/include/plugin_loader.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_FILE_PLUGIN_LOADER_H +#define OHOS_CLOUD_FILE_PLUGIN_LOADER_H + +#include "nocopyable.h" + +namespace OHOS::FileManagement::CloudFile { +class PluginLoader final : public NoCopyable { +public: + ~PluginLoader(); + static PluginLoader &GetInstance(); + void LoadCloudKitPlugin(bool isSupportCloudSync = false); +private: + PluginLoader() = default; + void *cloudKitPulginHandle_ = nullptr; +}; +} // namespace OHOS::FileManagement::CloudFile + +#endif // OHOS_CLOUD_FILE_PLUGIN_LOADER_H \ No newline at end of file diff --git a/cloud_file/utils/load/src/plugin_loader.cpp b/cloud_file/utils/load/src/plugin_loader.cpp new file mode 100644 index 0000000..53d07cf --- /dev/null +++ b/cloud_file/utils/load/src/plugin_loader.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2024 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 "plugin_loader.h" + +#include +#include +#include + +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; + +PluginLoader &PluginLoader::GetInstance() +{ + static PluginLoader instance; + return instance; +} + +PluginLoader::~PluginLoader() +{ + if (cloudKitPulginHandle_ == nullptr) { + return; + } + dlclose(cloudKitPulginHandle_); + LOGI("succ to unload plugin"); + cloudKitPulginHandle_ = nullptr; +} + +string GetPluginPath(const string &pluginFileName) +{ + const string searchDirs[] = {"/system/lib64/", "system/lib/"}; + string pluginFilePath = ""; + for (auto &searchDir : searchDirs) { + std::string tmpPath = searchDir + pluginFileName; + if (access(tmpPath.c_str(), F_OK) == 0) { + pluginFilePath = tmpPath; + break; + } + } + return pluginFilePath; +} + +void PluginLoader::LoadCloudKitPlugin(bool isSupportCloudSync) +{ + std::vector pluginFileNames; + pluginFileNames.emplace_back(isSupportCloudSync ? "libcloudfile_ext.z.so" : "libcloudfile_ext_core.z.so"); + pluginFileNames.emplace_back("libcloud_adapter.z.so"); + for (auto &pluginFileName : pluginFileNames) { + auto pluginFilePath = GetPluginPath(pluginFileName); + if (!pluginFilePath.empty()) { + char resolvedPath[PATH_MAX] = {'\0'}; + if (realpath(pluginFilePath.c_str(), resolvedPath) == nullptr) { + LOGE("realpath failed in line path: %s", pluginFilePath.c_str()); + return; + } + cloudKitPulginHandle_ = dlopen(pluginFilePath.c_str(), RTLD_LAZY); + if (cloudKitPulginHandle_ == nullptr) { + LOGE("dlopen failed, path:%{public}s", pluginFilePath.c_str()); + } else { + LOGI("succ to load plugin, path:%{public}s", pluginFilePath.c_str()); + } + return; + } + } + LOGE("Load CloudKit Plugin failed"); +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/cloud_file/utils/log/include/dfs_error.h b/cloud_file/utils/log/include/dfs_error.h new file mode 100644 index 0000000..6d0a09f --- /dev/null +++ b/cloud_file/utils/log/include/dfs_error.h @@ -0,0 +1,234 @@ +/* + * Copyright (c) 2022-2025 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 OHOS_FILEMGMT_DFS_ERROR_H +#define OHOS_FILEMGMT_DFS_ERROR_H + +#include +#include +#include + +#include "errors.h" + +namespace OHOS::FileManagement { +constexpr int STORAGE_SERVICE_SYS_CAP_TAG = 13600000; +constexpr int FILEIO_SYS_CAP_TAG = 13900000; +constexpr int USER_FILE_MANAGER_SYS_CAP_TAG = 14000000; +constexpr int DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG = 22400000; +constexpr int SOFTBUS_TRANS_FILE_PERMISSION_DENIED = -426114938; +constexpr int SOFTBUS_TRANS_FILE_DISK_QUOTA_EXCEEDED = -426114937; +constexpr int SOFTBUS_TRANS_FILE_NO_MEMORY = -426114936; +constexpr int SOFTBUS_TRANS_FILE_NETWORK_ERROR = -426114935; +constexpr int SOFTBUS_TRANS_FILE_NOT_FOUND = -426114934; +constexpr int SOFTBUS_TRANS_FILE_EXISTED = -426114933; +constexpr int DFS_CANCEL_SUCCESS = 204; + +enum CloudSyncServiceErrCode : ErrCode { + E_OK = 0, + E_SEVICE_DIED, + E_INVAL_ARG, + E_BROKEN_IPC, + E_SA_LOAD_FAILED, + E_SERVICE_DESCRIPTOR_IS_EMPTY, + E_PERMISSION_DENIED, + E_PERMISSION_SYSTEM, + E_GET_PHYSICAL_PATH_FAILED, + E_GET_TOKEN_INFO_ERROR, + E_SYNCER_NUM_OUT_OF_RANGE, + E_SYNC_FAILED_BATTERY_LOW, + E_SYNC_FAILED_BATTERY_TOO_LOW, + E_SYNC_FAILED_NETWORK_NOT_AVAILABLE, + E_GET_NETWORK_MANAGER_FAILED, + E_DELETE_FAILED, + E_NO_SUCH_FILE, + E_RENAME_FAIL, + E_SYSTEM_LOAD_OVER, + E_EXCEED_MAX_SIZE, + E_ILLEGAL_URI, + + /* data syncer */ + E_CLOUD_SDK, + E_RDB, + E_CONTEXT, + E_STOP, + E_PENDING, + E_SCHEDULE, + E_ASYNC_RUN, + E_PATH, + E_DATA, + E_NOTIFY, + E_UNKNOWN, + E_CLOUD_STORAGE_FULL, + E_LOCAL_STORAGE_FULL, + E_BUSINESS_MODE_CHANGED, + E_OSACCOUNT, + E_USER_LOCKED, + E_GET_SIZE_ERROR, + + E_IPC_READ_FAILED, + E_IPC_WRITE_FAILED, + E_SOFTBUS_SESSION_FAILED, + E_GET_DEVICE_ID, + E_GET_USER_ID, + E_NULLPTR, + /* session */ + E_CREATE_SESSION, + E_OPEN_SESSION, + E_WAIT_SESSION_OPENED, + E_FILE_NOT_EXIST, + E_SEND_FILE, + E_MEMORY, + + /* eventhandler */ + E_EVENT_HANDLER, + E_ZIP, + + /* download timeout */ + E_TIMEOUT, + + /* task running */ + E_TASK_RUNNING, + + E_SOURCE_BASIC = 10000, + + E_THM_SOURCE_BASIC = E_SOURCE_BASIC + 1000, + E_THM_SIZE_IS_ZERO = E_THM_SOURCE_BASIC + 201, + E_THM_IS_TOO_LARGE = E_THM_SIZE_IS_ZERO + 1, + + E_LCD_SOURCE_BASIC = E_SOURCE_BASIC + 2000, + E_LCD_SIZE_IS_ZERO = E_LCD_SOURCE_BASIC + 201, + E_LCD_IS_TOO_LARGE = E_LCD_SIZE_IS_ZERO + 1, + + E_CONTENT_SOURCE_BASIC = E_SOURCE_BASIC + 3000, + E_CONTENT_SIZE_IS_ZERO = E_CONTENT_SOURCE_BASIC + 201, + E_CONTENT_COVERT_LIVE_PHOTO = E_CONTENT_SIZE_IS_ZERO + 1, + E_CONTENT_RAW_SIZE_IS_ZERO = E_CONTENT_COVERT_LIVE_PHOTO + 1, + + E_FIELD_BASIC = 20000, + + E_DB_FIELD_BASIC = E_FIELD_BASIC + 1000, + E_DB_SIZE_IS_ZERO = E_DB_FIELD_BASIC + 1, + E_DB_ALBUM_NOT_FOUND = E_DB_SIZE_IS_ZERO + 1, + E_DB_ALBUM_ID_IS_EMPTY = E_DB_ALBUM_NOT_FOUND + 1, + + E_DK_FIELD_BASIC = E_FIELD_BASIC + 2000, + E_DK_NO_ATTRIBUTES = E_DK_FIELD_BASIC + 1, +}; + +enum DFSErrCode { + ERR_OK = 0, + ERR_BAD_VALUE = -1, + + ERR_APPLY_RESULT = 1, + ERR_DLOPEN, + ERR_PUBLISH_STATE, + ERR_ALLCONNECT, + ERR_CHECKOUT_COUNT, + + E_PERM, + E_NOENT, + E_SRCH, + E_INTR, + E_IO, + E_NXIO, + E_2BIG, + E_BADF, + E_CHILD, + E_AGAIN, + E_NOMEM, + E_ACCES, + E_FAULT, + E_BUSY, + E_EXIST, + E_XDEV, + E_NODEV, + E_NOTDIR, + E_ISDIR, + E_INVAL, + E_NFILE, + E_MFILE, + E_TXTBSY, + E_FBIG, + E_NOSPC, + E_SPIPE, + E_ROFS, + E_MLINK, + E_DEADLK, + E_NAMETOOLONG, + E_NOSYS, + E_NOTEMPTY, + E_LOOP, + E_WOULDBLOCK, + E_BADR, + E_UKERR, + E_NETUNREACH, + E_CONNECTION_FAIL, + E_CONNECTION_ABORT, + E_NOTASK, + E_UNCANCELED, + E_CANCELED, +}; + +static inline std::unordered_map softbusErr2ErrCodeTable { + {SOFTBUS_TRANS_FILE_PERMISSION_DENIED, EPERM}, + {SOFTBUS_TRANS_FILE_DISK_QUOTA_EXCEEDED, EIO}, + {SOFTBUS_TRANS_FILE_NO_MEMORY, ENOMEM}, + {SOFTBUS_TRANS_FILE_NETWORK_ERROR, ENETUNREACH}, + {SOFTBUS_TRANS_FILE_NOT_FOUND, ENOENT}, + {SOFTBUS_TRANS_FILE_EXISTED, EEXIST}, + {DFS_CANCEL_SUCCESS, ECANCELED}, +}; + +enum IPCErrCode { + E_DEAD_REPLY = 29189, +}; + +enum JsErrCode { + E_PERMISSION = 201, + E_PERMISSION_SYS = 202, + E_DFS_CANCEL_SUCCESS = 204, + E_PARAMS_ = 401, + E_IPCSS = STORAGE_SERVICE_SYS_CAP_TAG + 1, + E_UNKNOWN_ERR = FILEIO_SYS_CAP_TAG + 42, + E_INVALID_URI = USER_FILE_MANAGER_SYS_CAP_TAG + 2, + E_CLOUD_NOT_READY = DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + 1, + E_NETWORK_ERR = DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + 2, + E_BATTERY_WARNING = DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + 3, + E_EXCEED_MAX_LIMIT = DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + 4, + E_DATABASE_FAILED = DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + 5, + E_OTHER_TASK_RUNNING = DISTRIBUTEDFILE_SERVICE_SYS_CAP_TAG + 6 +}; + +const std::unordered_map errCodeTable { + { E_PERMISSION_DENIED, E_PERMISSION }, + { E_PERMISSION_SYSTEM, E_PERMISSION_SYS }, + { E_INVAL_ARG, E_PARAMS_ }, + { E_BROKEN_IPC, E_IPCSS }, + { E_CLOUD_SDK, E_CLOUD_NOT_READY }, + { E_ILLEGAL_URI, E_INVALID_URI }, + { E_SYNC_FAILED_NETWORK_NOT_AVAILABLE, E_NETWORK_ERR }, + { E_SYNC_FAILED_BATTERY_TOO_LOW, E_BATTERY_WARNING }, + { E_EXCEED_MAX_SIZE, E_EXCEED_MAX_LIMIT }, + { E_RDB, E_IPCSS }, + { E_DEAD_REPLY, E_IPCSS }, + { E_TASK_RUNNING, E_OTHER_TASK_RUNNING}, + { E_SA_LOAD_FAILED, E_IPCSS }, + { E_SYSTEM_LOAD_OVER, E_IPCSS } +}; + +int32_t Convert2JsErrNum(int32_t errNum); +} // namespace OHOS::FileManagement + +#endif // OHOS_FILEMGMT_DFS_ERROR_H \ No newline at end of file diff --git a/cloud_file/utils/log/include/utils_log.h b/cloud_file/utils/log/include/utils_log.h new file mode 100644 index 0000000..8cdcdf0 --- /dev/null +++ b/cloud_file/utils/log/include/utils_log.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 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 UTILS_LOG_H +#define UTILS_LOG_H + +#include + +#include "hilog/log_c.h" +#include "hilog/log_cpp.h" + +namespace OHOS { +#ifndef LOG_DOMAIN +#define LOG_DOMAIN 0xD001600 +#endif + +#ifndef LOG_TAG +#define LOG_TAG "distributedfile" +#endif + +std::string GetFileNameFromFullPath(const char *str); + +#define LOGD(fmt, ...) HILOG_DEBUG(LOG_CORE, "[%{public}s:%{public}d->%{public}s] " fmt, \ + GetFileNameFromFullPath(__FILE__).c_str(), __LINE__, __FUNCTION__, ##__VA_ARGS__) +#define LOGI(fmt, ...) HILOG_INFO(LOG_CORE, "[%{public}s:%{public}d->%{public}s] " fmt, \ + GetFileNameFromFullPath(__FILE__).c_str(), __LINE__, __FUNCTION__, ##__VA_ARGS__) +#define LOGW(fmt, ...) HILOG_WARN(LOG_CORE, "[%{public}s:%{public}d->%{public}s] " fmt, \ + GetFileNameFromFullPath(__FILE__).c_str(), __LINE__, __FUNCTION__, ##__VA_ARGS__) +#define LOGE(fmt, ...) HILOG_ERROR(LOG_CORE, "[%{public}s:%{public}d->%{public}s] " fmt, \ + GetFileNameFromFullPath(__FILE__).c_str(), __LINE__, __FUNCTION__, ##__VA_ARGS__) +#define LOGF(fmt, ...) HILOG_FATAL(LOG_CORE, "[%{public}s:%{public}d->%{public}s] " fmt, \ + GetFileNameFromFullPath(__FILE__).c_str(), __LINE__, __FUNCTION__, ##__VA_ARGS__) + +std::string GetAnonyString(const std::string &value); +} // namespace OHOS +#endif // UTILS_LOG_H \ No newline at end of file diff --git a/cloud_file/utils/log/src/dfs_error.cpp b/cloud_file/utils/log/src/dfs_error.cpp new file mode 100644 index 0000000..7bd27cf --- /dev/null +++ b/cloud_file/utils/log/src/dfs_error.cpp @@ -0,0 +1,27 @@ +/* + * 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 "dfs_error.h" + +namespace OHOS::FileManagement { +int32_t Convert2JsErrNum(int32_t errNum) +{ + if (errCodeTable.find(errNum) != errCodeTable.end()) { + return errCodeTable.at(errNum); + } else { + return errNum; + } +} +} // namespace OHOS::FileManagement diff --git a/cloud_file/utils/log/src/utils_log.cpp b/cloud_file/utils/log/src/utils_log.cpp new file mode 100644 index 0000000..eaea5ac --- /dev/null +++ b/cloud_file/utils/log/src/utils_log.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 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 "utils_log.h" + +namespace OHOS { +std::string GetFileNameFromFullPath(const char *str) +{ + std::string fullPath(str); + size_t pos = fullPath.find_last_of("/"); + return (pos == std::string::npos) ? std::string() : fullPath.substr(pos + 1); +} + +std::string GetAnonyString(const std::string &value) +{ + constexpr size_t INT32_SHORT_ID_LENGTH = 20; + constexpr size_t INT32_PLAINTEXT_LENGTH = 4; + constexpr size_t INT32_MIN_ID_LENGTH = 3; + std::string res; + std::string tmpStr("********"); + size_t strLen = value.length(); + if (strLen < INT32_MIN_ID_LENGTH) { + return tmpStr; + } + + if (strLen <= INT32_SHORT_ID_LENGTH) { + res += value[0]; + res += tmpStr; + res += value[strLen - 1]; + } else { + res.append(value, 0, INT32_PLAINTEXT_LENGTH); + res += tmpStr; + res.append(value, INT32_PLAINTEXT_LENGTH + tmpStr.length(), strLen - INT32_PLAINTEXT_LENGTH - tmpStr.length()); + } + + return res; +} +} // namespace OHOS diff --git a/cloud_file/utils/preference/src/cloud_pref_impl.cpp b/cloud_file/utils/preference/src/cloud_pref_impl.cpp new file mode 100644 index 0000000..43a1e07 --- /dev/null +++ b/cloud_file/utils/preference/src/cloud_pref_impl.cpp @@ -0,0 +1,170 @@ +/* + * 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 "cloud_pref_impl.h" +#include +#include +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +namespace { + static const uint32_t STAT_MODE_DIR = 0771; +} + +CloudPrefImpl::CloudPrefImpl(const int32_t userId, const std::string& bundleName, const std::string& tableName) +{ + /* the file name varies from different userId and bundle name */ + std::string userIdDir = "/data/service/el2/" + std::to_string(userId) + "/hmdfs/cloudfile_manager"; + if (access(userIdDir.c_str(), F_OK) != 0) { + if (mkdir(userIdDir.c_str(), STAT_MODE_DIR) != 0) { + LOGE("CloudPrefImpl: mkdir failed"); + } + } + + std::string bundleDir = userIdDir + "/" + bundleName; + if (access(bundleDir.c_str(), F_OK) != 0) { + if (mkdir(bundleDir.c_str(), STAT_MODE_DIR) != 0) { + LOGE("CloudPrefImpl: mkdir failed"); + } + } + fileName_ = bundleDir + "/" + tableName; + int32_t errCode = 0; + pref_ = NativePreferences::PreferencesHelper::GetPreferences(fileName_, errCode); + if (!pref_) { + LOGE("CloudPrefImpl: Preference get null, errcode: %{public}d", errCode); + } +} + +CloudPrefImpl::CloudPrefImpl(const std::string& fileName) +{ + int32_t errCode = 0; + fileName_ = fileName; + pref_ = NativePreferences::PreferencesHelper::GetPreferences(fileName_, errCode); + if (!pref_) { + LOGE("CloudPrefImpl: Preference get null, errcode: %{public}d", errCode); + } +} + +void CloudPrefImpl::SetString(const std::string& key, const std::string& value) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + pref_->PutString(key, value); + int ret = pref_->FlushSync(); + if (ret) { + LOGE("CloudPrefImpl: SetString has error, ret = %{public}d", ret); + } +} + +void CloudPrefImpl::GetString(const std::string& key, std::string &value) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + value = pref_->GetString(key, ""); +} + +void CloudPrefImpl::SetLong(const std::string& key, const int64_t value) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + pref_->PutLong(key, value); + int ret = pref_->FlushSync(); + if (ret) { + LOGE("CloudPrefImpl: SetLong has error, ret = %{public}d", ret); + } +} + +void CloudPrefImpl::GetLong(const std::string& key, int64_t &value) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + value = pref_->GetLong(key, 0); +} + +void CloudPrefImpl::SetInt(const std::string& key, const int value) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + pref_->PutInt(key, value); + int ret = pref_->FlushSync(); + if (ret) { + LOGE("CloudPrefImpl: SetInt has error, ret = %{public}d", ret); + } +} + +void CloudPrefImpl::GetInt(const std::string& key, int32_t &value) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + value = pref_->GetInt(key, 0); +} + +void CloudPrefImpl::SetBool(const std::string& key, const bool& value) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + pref_->PutBool(key, value); + int ret = pref_->FlushSync(); + if (ret) { + LOGE("CloudPrefImpl: SetBool has error, ret = %{public}d", ret); + } +} + +void CloudPrefImpl::GetBool(const std::string& key, bool& value) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + value = pref_->GetBool(key, false); +} + +void CloudPrefImpl::Clear() +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + pref_->Clear(); + NativePreferences::PreferencesHelper::DeletePreferences(fileName_); +} + +void CloudPrefImpl::Delete(const std::string& key) +{ + if (pref_ == nullptr) { + LOGE("CloudPrefImpl: perf_ is null"); + return; + } + pref_->Delete(key); + int ret = pref_->FlushSync(); + if (ret) { + LOGE("CloudPrefImpl: Delete has error, ret = %{public}d", ret); + } +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfs_daemon_event_dfx.h b/cloud_file/utils/system/include/dfs_daemon_event_dfx.h new file mode 100644 index 0000000..7d4a90c --- /dev/null +++ b/cloud_file/utils/system/include/dfs_daemon_event_dfx.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2024 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 DISTRIBUTEDFILE_DAEMON_EVENT_DFX_H +#define DISTRIBUTEDFILE_DAEMON_EVENT_DFX_H + +#include "hisysevent.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +namespace RadarReporter { +using namespace OHOS::HiviewDFX; +static constexpr int DIST_DATA_MGR_SYS_ID = 0xd; +static constexpr int DFS_ID = 13; +enum BizScene : std::int32_t { + DFX_SET_DFS = 1, +}; + +enum BizStageSetDfs : std::int32_t { + DFX_SET_BIZ_SCENE = 1, + DFX_BUILD__LINK = 2, +}; + +enum StageRes : std::int32_t { + DFX_IDLE = 0, + DFX_SUCCESS = 1, + DFX_FAILED = 2, + DFX_CANCELLED = 3, +}; + +enum BizState : std::int32_t { + DFX_BEGIN = 1, + DFX_END = 2, +}; + +enum ErrorCode : std::int32_t { + DFS_ERROR = (DIST_DATA_MGR_SYS_ID << 21) | (DFS_ID << 16), + PREPARE_COPY_SESSION_ERROR, + COPY_TO_SANDBOX_ERROR, + SEND_FILE_ERROR, + GET_SAME_ACCOUNT_ERROR, + CREAT_SOCKET_ERROR, + BIND_SOCKET_ERROR, + CHECK_URI_PREMISSION_ERROR, + GET_SYSTEM_ABILITY_ERROR, + GET_REMOTE_COPY_INFO_ERROR, + GET_HAP_TOKEN_INFO_ERROR, + CREAT_VALID_PATH_ERROR, + FILE_TRANS_ERROR, + REQUEST_SEND_FILE_ERROR, +}; + +const std::string uriPermMgr = "UriPermMgr"; +const std::string appFileService = "APPFILESERVICE"; +const std::string dSoftBus = "DSOFTBUS"; +const std::string saMgr = "SAMGR"; +const std::string deviceManager = "DeviceManager"; +const std::string accessTokenKit = "AccessTokenKit"; + +static constexpr char DOMAIN[] = "DISTDATAMGR"; +constexpr const char* EVENT_NAME = "DISTRIBUTED_DFS_BEHAVIOR"; +constexpr const char* ORG_PKG = "distributedfile"; +constexpr const char* BIZ_STATE = "BIZ_STATE"; +constexpr const char* ERROR_CODE = "ERROR_CODE"; +constexpr const char* PACKAGE_NAME = "PACKAGE_NAME"; +constexpr const char* CONCURRENT_ID = "CONCURRENT_ID"; +static constexpr HiviewDFX::HiSysEvent::EventType TYPE = HiviewDFX::HiSysEvent::EventType::BEHAVIOR; + +#define RADAR_REPORT(bizScene, bizStage, stageRes, ...) \ +({ \ + HiSysEventWrite(RadarReporter::DOMAIN, RadarReporter::EVENT_NAME, RadarReporter::TYPE, \ + "ORG_PKG", RadarReporter::ORG_PKG, "FUNC", __FUNCTION__, \ + "BIZ_SCENE", bizScene, "BIZ_STAGE", bizStage, "STAGE_RES", stageRes, \ + ##__VA_ARGS__); \ +}) +} // namespace RadarReporter +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif //DISTRIBUTEDFILE_DAEMON_EVENT_DFX_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_access_token_helper.h b/cloud_file/utils/system/include/dfsu_access_token_helper.h new file mode 100644 index 0000000..b0f4c28 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_access_token_helper.h @@ -0,0 +1,41 @@ +/* + * 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 OHOS_FILEMGMT_DFSU_ACCESS_TOKEN_HELPER_H +#define OHOS_FILEMGMT_DFSU_ACCESS_TOKEN_HELPER_H + +#include + +namespace OHOS::FileManagement { +inline const std::string PERM_CLOUD_SYNC_MANAGER = "ohos.permission.CLOUDFILE_SYNC_MANAGER"; +inline const std::string PERM_CLOUD_SYNC = "ohos.permission.CLOUDFILE_SYNC"; +inline const std::string PERM_AUTH_URI = "ohos.permission.PROXY_AUTHORIZATION_URI"; +inline const std::string FILE_ACCESS_MANAGER_PERMISSION = "ohos.permission.FILE_ACCESS_MANAGER"; +inline const std::string PERM_DISTRIBUTED_DATASYNC = "ohos.permission.DISTRIBUTED_DATASYNC"; + +class DfsuAccessTokenHelper final { +public: + static bool CheckCallerPermission(const std::string &permissionName); + static int32_t GetCallerBundleName(std::string &bundleName); + static bool CheckPermission(uint32_t tokenId, const std::string &permissionName); + static bool CheckUriPermission(const std::string &uri); + static int32_t GetBundleNameByToken(uint32_t tokenId, std::string &bundleName); + static bool IsSystemApp(); + static int32_t GetUserId(); + static int32_t GetPid(); +}; +} // namespace OHOS::FileManagement + +#endif // OHOS_FILEMGMT_DFSU_ACCESS_TOKEN_HELPER_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_actor.h b/cloud_file/utils/system/include/dfsu_actor.h new file mode 100644 index 0000000..4e90331 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_actor.h @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2021 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 DFSU_ACTOR_H +#define DFSU_ACTOR_H + +#include +#include +#include +#include + +#include "dfsu_cmd.h" +#include "dfsu_thread_safe_queue.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +constexpr int RETRY_SLEEP_TIME = 1500; +/** + * @brief The Actor Model + * + * @tparam Ctx Context for Commands + */ +template +class DfsuActor { +public: + explicit DfsuActor(Ctx *ctx, uint32_t startCmdTryTimes = 1) : ctx_(ctx), retryTimes_(startCmdTryTimes) {} + virtual ~DfsuActor() {} + + void StartActor() + { + // Always insert cmds b4 starting an actor + StartCtx(); + loop_ = std::thread([this]() { this->Main(); }); + } + + void StopActor() + { + // Always insert cmds b4 starting an actor + StopCtx(); + pendingCmds_.Halt(); + + loop_.join(); + } + + void Recv(std::unique_ptr> pcmd) + { + pendingCmds_.Push(std::move(pcmd)); + } + +protected: + DfsuThreadSafeQueue> pendingCmds_; + + Ctx *ctx_ {nullptr}; + uint32_t retryTimes_ {1}; + std::thread loop_; + + std::list> retryTasks; + +private: + void DelayRetry(std::unique_ptr> cmd) + { + using namespace std::literals::chrono_literals; + std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_SLEEP_TIME)); + pendingCmds_.Push(std::move(cmd)); + } + + void Retry(std::unique_ptr> cmd) + { + pendingCmds_.PushFront(std::move(cmd)); + using namespace std::literals::chrono_literals; + std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_SLEEP_TIME)); + } + + void StartCtx() + { + auto startCmd = std::make_unique>(&Ctx::Start); + startCmd->UpdateOption({.importance_ = CmdImportance::SUBVITAL, .tryTimes_ = retryTimes_}); + pendingCmds_.Push(std::move(startCmd)); + } + + void StopCtx() + { + auto cmd = std::make_unique>(&Ctx::Stop); + cmd->UpdateOption({.importance_ = CmdImportance::VITAL, .tryTimes_ = 1}); + pendingCmds_.Push(std::move(cmd)); + } + + bool IsExistStopTask() + { + bool result = false; + pendingCmds_.ForEach([&result](const std::unique_ptr> &item) { + if (item->option_.importance_ == CmdImportance::VITAL) { + result = true; + } + }); + return result; + } + + bool ExceptionHandler(const DfsuException &e, std::unique_ptr> ¤tCmd) + { + if (e.code() == ERR_UTILS_ACTOR_QUEUE_STOP) { + return false; + } + + const CmdOptions &op = currentCmd->option_; + + if (IsExistStopTask() && (op.tryTimes_ > 0)) { + return true; // exist stop Task, stop retry + } + + if (op.importance_ == CmdImportance::TRIVIAL) { + if (op.tryTimes_) { + retryTasks.emplace_back( + std::async(std::launch::async, &DfsuActor::DelayRetry, this, std::move(currentCmd))); + return true; + } + } else { + if (op.tryTimes_) { + Retry(std::move(currentCmd)); + return true; + } + if (op.importance_ == CmdImportance::VITAL) { + return false; + } + if (op.importance_ == CmdImportance::NORMAL) { + StopCtx(); + StartCtx(); + return true; + } + } + return true; + } + + void Main() + { + while (true) { + std::unique_ptr> currentCmd; + try { + while (true) { + currentCmd = pendingCmds_.WaitAndPop(); + (*currentCmd)(ctx_); + currentCmd.release(); + } + } catch (const DfsuException &e) { + if (ExceptionHandler(e, currentCmd)) { + continue; + } else { + break; + } + } catch (const std::exception &e) { + LOGE("Unexpected Low Level exception"); + } + } + } +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DFSU_ACTOR_H diff --git a/cloud_file/utils/system/include/dfsu_cmd.h b/cloud_file/utils/system/include/dfsu_cmd.h new file mode 100644 index 0000000..dd7b7c0 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_cmd.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 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 DFSU_CMD_H +#define DFSU_CMD_H + +#include + +#include "dfsu_exception.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +enum class CmdImportance { + // If it fails(even has tried multiple times), shutdown the actor. + VITAL, + + SUBVITAL, + // If it fails(even has tried multiple times), reboot the actor. + NORMAL, + + // If it fails(may also try multiple times), just do nothing. + TRIVIAL, +}; + +struct CmdOptions { + CmdImportance importance_ { CmdImportance::TRIVIAL }; + uint32_t tryTimes_ {1}; +}; + +template +class DfsuActor; + +template +class VirtualCmd { + friend class DfsuActor; + +public: + VirtualCmd() = default; + virtual ~VirtualCmd() = default; + virtual void operator()(Ctx *ctx) = 0; + + void UpdateOption(CmdOptions op) + { + option_ = op; + } + +protected: + CmdOptions option_; +}; + +template +class DfsuCmd : public VirtualCmd { + friend class DfsuActor; + +public: + DfsuCmd(void (Ctx::*f)(Args...), Args... args) : f_(f), args_(args...) {} + ~DfsuCmd() override = default; + +private: + void (Ctx::*f_)(Args...); + std::tuple args_; + + void operator()(Ctx *ctx) override + { + if (!VirtualCmd::option_.tryTimes_) { + ThrowException(ERR_UTILS_ACTOR_INVALID_CMD, "Cannot execute a command that has 0 try times"); + } + + VirtualCmd::option_.tryTimes_--; + std::apply(f_, std::tuple_cat(std::make_tuple(ctx), args_)); + } +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DFSU_CMD_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_exception.h b/cloud_file/utils/system/include/dfsu_exception.h new file mode 100644 index 0000000..26c9772 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_exception.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021-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 DFSU_EXCEPTION_H +#define DFSU_EXCEPTION_H + +#include +#include +#include + +#include "utils_log.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +enum { + ERR_DEFAULT, + ERR_UTILS_ACTOR_QUEUE_STOP, + ERR_UTILS_ACTOR_INVALID_CMD, + ERR_NETWORK_AGENT_TEMPLATE_OPEN_SESSION_FAIL, + ERR_SOFTBUS_AGENT_ON_SESSION_OPENED_FAIL, + ERR_DEVICE_CID_UN_INIT, + ERR_DEVICE_EXTRADATA_UN_INIT, + ERR_CONNECT_LINK_TYPE +}; + +class DfsuException : public std::exception { +public: + DfsuException(int code, const std::string &msg) : code_(code), msg_(msg) {}; + + uint32_t code() const noexcept + { + return code_; + } + + virtual const char *what() const noexcept + { + return msg_.c_str(); + } + +private: + int code_ {ERR_DEFAULT}; + std::string msg_; +}; + +#define ThrowException(code, msg) \ + do { \ + std::stringstream __ss; \ + __ss << '[' << (code) << ']' << (msg) << std::endl; \ + LOGE("%{public}s", __ss.str().c_str()); \ + throw DfsuException((code), __ss.str()); \ + } while (0) +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DFSU_EXCEPTION_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_fd_guard.h b/cloud_file/utils/system/include/dfsu_fd_guard.h new file mode 100644 index 0000000..93b9b05 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_fd_guard.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 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 FD_GUARD_H +#define FD_GUARD_H + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class DfsuFDGuard final { +public: + DfsuFDGuard() = default; + explicit DfsuFDGuard(int fd); + DfsuFDGuard(int fd, bool autoClose); + + DfsuFDGuard(const DfsuFDGuard &fdg) = delete; + DfsuFDGuard &operator=(const DfsuFDGuard &fdg) = delete; + + DfsuFDGuard(DfsuFDGuard &&fdg) = delete; + DfsuFDGuard &operator=(DfsuFDGuard &&fdg) = delete; + + operator bool() const; + + ~DfsuFDGuard(); + + int GetFD() const; + void SetFD(int fd, bool autoClose = true); + void ClearFD(); + +private: + int fd_ = -1; + bool autoClose_ = true; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_memory_guard.h b/cloud_file/utils/system/include/dfsu_memory_guard.h new file mode 100644 index 0000000..74d8ee3 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_memory_guard.h @@ -0,0 +1,28 @@ +/* + * 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 OHOS_FILEMGMT_DFSU_MEMORY_GUARD_H +#define OHOS_FILEMGMT_DFSU_MEMORY_GUARD_H + +namespace OHOS::FileManagement::CloudSync { +class DfsuMemoryGuard { +public: + DfsuMemoryGuard(); + ~DfsuMemoryGuard(); +private: +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DFSU_MEMORY_GUARD_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_mount_argument_descriptors.h b/cloud_file/utils/system/include/dfsu_mount_argument_descriptors.h new file mode 100644 index 0000000..87fc9e7 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_mount_argument_descriptors.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 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 DFSU_MOUNT_ARGUMENT_DESCRIPTORS_H +#define DFSU_MOUNT_ARGUMENT_DESCRIPTORS_H + +#include + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +namespace Utils { +struct MountArgument final { + int userId_ { 0 }; + bool accountless_ { false }; + bool needInitDir_ { false }; + bool useCache_ { false }; + bool caseSensitive_ { false }; + bool enableMergeView_ { false }; + bool enableFixupOwnerShip_ { false }; + bool enableOfflineStash_ { true }; + bool externalFS_ { false }; + std::string relativePath_; + + std::string GetFullSrc() const; + std::string GetFullDst() const; + std::string GetCtrlPath() const; + std::string GetCachePath() const; + std::string OptionsToString() const; + unsigned long GetFlags() const; +}; + +class DfsuMountArgumentDescriptors final { +public: + static MountArgument Alpha(int userId, std::string relativePath); +}; +} // namespace Utils +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DFSU_MOUNT_ARGUMENT_DESCRIPTORS_H diff --git a/cloud_file/utils/system/include/dfsu_singleton.h b/cloud_file/utils/system/include/dfsu_singleton.h new file mode 100644 index 0000000..eea5a43 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_singleton.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 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 DFSU_SINGLETON_H +#define DFSU_SINGLETON_H + +#include +#include +#include +#include "nocopyable.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +namespace Utils { +#define DECLARE_SINGLETON(MyClass) \ +public: \ + ~MyClass(); \ + MyClass(const MyClass&) = delete; \ + MyClass& operator=(const MyClass&) = delete; \ + \ +private: \ + friend DfsuSingleton; \ + MyClass(); + +template +class DfsuSingleton : public NoCopyable { +public: + static std::shared_ptr GetInstance(); + +protected: + /** + * @note We depend on the IPC manager to serialize the start and the stop procedure + */ + virtual void StartInstance() = 0; + + /** + * @note Be very careful when freeing memory! Threads may call stop and other member functions simultaneously + */ + virtual void StopInstance() = 0; +}; + +/** + * @brief + * + * @tparam T + * @return T& + * + * @note We use call_once to ensure the atomicity of new() and start() + * @note Memory leaking of T is exactly what we want. Now T will be available along the program's life-time + */ +template +std::shared_ptr DfsuSingleton::GetInstance() +{ + static std::shared_ptr *dummy = nullptr; + static std::once_flag once; + std::call_once(once, []() mutable { + dummy = new std::shared_ptr(new T()); + (*dummy)->StartInstance(); + }); + return *dummy; +} +} // namespace Utils +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DFSU_SINGLETON_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_startable.h b/cloud_file/utils/system/include/dfsu_startable.h new file mode 100644 index 0000000..4a5d6f5 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_startable.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 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 DFSU_STARTABLE_H +#define DFSU_STARTABLE_H + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +class DfsuStartable { +public: + virtual void Start() = 0; + virtual void Stop() = 0; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DFSU_STARTABLE_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_thread.h b/cloud_file/utils/system/include/dfsu_thread.h new file mode 100644 index 0000000..a59e492 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_thread.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 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 DFSU_THREAD_H +#define DFSU_THREAD_H + +#include +#include +#include +#include +#include +#include "utils_log.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +namespace Utils { +class DfsuThread { +public: + DfsuThread() = default; + DfsuThread(const DfsuThread &) = delete; + DfsuThread &operator=(const DfsuThread &) = delete; + + ~DfsuThread() + { + Stop(); + } + + template + bool Run(Fn &&Fx, Args &&...Ax) + { + std::unique_lock lock(threadMutex_); + if (thread_ != nullptr) { + return false; + } + running_ = true; + thread_ = std::make_unique(std::forward(Fx), std::forward(Ax)...); + return true; + } + + bool RunLoop(std::function task, uint64_t interval, uint32_t retryTimes = UINT32_MAX) + { + std::unique_lock lock(threadMutex_); + if (thread_ != nullptr) { + return false; + } + running_ = true; + thread_ = std::make_unique([this, task, interval, retryTimes] { + uint32_t times = retryTimes; + LOGD("DfsThread: entering loop"); + while ((!task()) && (times > 0)) { + times--; + std::unique_lock lock(sleepMutex_); + bool stop = + sleepCv_.wait_for(lock, std::chrono::milliseconds(interval), [this]() { return !this->running_; }); + if (stop) { // is stopped + break; + } + } + LOGD("DfsThread: leaving loop"); + }); + return true; + } + + bool RunLoopFlexible(std::function task, uint64_t interval, uint32_t retryTimes = UINT32_MAX) + { + std::unique_lock lock(threadMutex_); + if (thread_ != nullptr) { + return false; + } + running_ = true; + thread_ = std::make_unique([this, task, interval, retryTimes] { + uint32_t times = retryTimes; + uint64_t duration = interval; + LOGD("DfsThread: entering flexible loop"); + while ((!task(duration)) && (times > 0)) { + times--; + std::unique_lock lock(sleepMutex_); + bool stop = + sleepCv_.wait_for(lock, std::chrono::milliseconds(duration), [this]() { return !this->running_; }); + if (stop) { // is stopped + break; + } + } + LOGD("DfsThread: leaving flexible loop"); + }); + return true; + } + + bool Stop() + { + std::unique_lock lockThread(threadMutex_); + if (thread_ == nullptr) { + return true; + } + { + std::unique_lock lockSleep(sleepMutex_); + running_ = false; + sleepCv_.notify_one(); + } + LOGD("wait thread to stop"); + if (thread_->joinable()) { + thread_->join(); + } + thread_ = nullptr; + return true; + } + + bool operator==(std::thread::id id) + { + if (thread_ == nullptr) { + return false; + } + return thread_->get_id() == id; + } + +private: + std::atomic_bool running_ {false}; + std::mutex threadMutex_ {}; + std::unique_ptr thread_ {nullptr}; + std::mutex sleepMutex_ {}; + std::condition_variable sleepCv_ {}; +}; +} // namespace Utils +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DFSU_THREAD_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_thread_safe_queue.h b/cloud_file/utils/system/include/dfsu_thread_safe_queue.h new file mode 100644 index 0000000..a0ed923 --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_thread_safe_queue.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 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 DFSU_THREAD_SAFE_QUEUE_H +#define DFSU_THREAD_SAFE_QUEUE_H + +#include +#include + +#include "dfsu_exception.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +/** + * @brief A Thread-safe Queue. + * + * Design choices: + * 1) unlimited capacity + * 2) throw exception to indicate failues + * 3) blocking pop interface + * 3) hatlable + * + * @tparam T Any type. Aggregate data type is prefered + * + */ +template +class DfsuThreadSafeQueue { +public: + void Push(std::unique_ptr pt) + { + if (!pt) { + ThrowException(ERR_UTILS_ACTOR_INVALID_CMD, "Push an empty cmd"); + } + std::unique_lock lock(mutex_); + if (!halted) { + queue_.emplace_back(std::move(pt)); + cv_.notify_one(); + } + } + + void PushFront(std::unique_ptr pt) + { + if (!pt) { + ThrowException(ERR_UTILS_ACTOR_INVALID_CMD, "Push an empty cmd"); + } + std::unique_lock lock(mutex_); + if (!halted) { + queue_.emplace_front(std::move(pt)); + cv_.notify_one(); + } + } + + std::unique_ptr WaitAndPop() + { + std::unique_lock lock(mutex_); + cv_.wait(lock, [&] { return !queue_.empty() || halted; }); + if (halted && queue_.empty()) { + ThrowException(ERR_UTILS_ACTOR_QUEUE_STOP, "Queue was halted"); + } + + auto res = std::move(queue_.front()); + queue_.pop_front(); + return std::move(res); + } + + void ForEach(std::function &)> executor) + { + std::unique_lock lock(mutex_); + std::for_each(queue_.begin(), queue_.end(), executor); + } + + void Halt() + { + std::unique_lock lock(mutex_); + halted = true; + cv_.notify_all(); + } + +private: + std::deque> queue_; + std::mutex mutex_; + std::condition_variable cv_; + + bool halted {false}; +}; +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // DFSU_THREAD_SAFE_QUEUE_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/dfsu_timer.h b/cloud_file/utils/system/include/dfsu_timer.h new file mode 100644 index 0000000..d50e0cf --- /dev/null +++ b/cloud_file/utils/system/include/dfsu_timer.h @@ -0,0 +1,36 @@ +/* + * 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 OHOS_FILEMGMT_DFSU_TIMER_H +#define OHOS_FILEMGMT_DFSU_TIMER_H + +#include "nocopyable.h" +#include "timer.h" + +namespace OHOS::FileManagement { +class DfsuTimer final : public NoCopyable { +public: + static DfsuTimer &GetInstance(); + void Register(const Utils::Timer::TimerCallback &callback, uint32_t &outTimerId, uint32_t interval); + void Unregister(uint32_t timerId); + +private: + DfsuTimer(); + ~DfsuTimer(); + std::unique_ptr timer_; +}; +} // namespace OHOS::FileManagement::CloudSync + +#endif // OHOS_FILEMGMT_DFSU_TIMER_H \ No newline at end of file diff --git a/cloud_file/utils/system/include/sys_utils.h b/cloud_file/utils/system/include/sys_utils.h new file mode 100644 index 0000000..a761cb9 --- /dev/null +++ b/cloud_file/utils/system/include/sys_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 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 OHOS_CLOUD_SYNC_SERVICE_SYS_UTILS_H +#define OHOS_CLOUD_SYNC_SERVICE_SYS_UTILS_H + +#include + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { + +enum { + CPU_IDX_0 = 0, + CPU_IDX_1, + CPU_IDX_2, + CPU_IDX_3, + CPU_IDX_4, + CPU_IDX_5, + CPU_IDX_6, + CPU_IDX_7, +}; + +void SlowDown(); +void ResetCpu(); +} +} +} +#endif \ No newline at end of file diff --git a/cloud_file/utils/system/include/utils_directory.h b/cloud_file/utils/system/include/utils_directory.h new file mode 100644 index 0000000..09c65ce --- /dev/null +++ b/cloud_file/utils/system/include/utils_directory.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021-2025 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 UTILS_DIRECTORY_H +#define UTILS_DIRECTORY_H + +#include +#include +#include +#include +#include +#include +#include + +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +namespace Utils { +const std::string ORGPKGNAME = "distributedfile_daemon"; +const std::string SOFTBUSNAME = "dsoftbus"; +const std::string DISTRIBUTEDFILE_CONNECT_BEHAVIOR = "DISTRIBUTEDFILE_DAEMON"; + +enum Uid { + UID_ROOT = 0, + UID_SYSTEM = 1000, + UID_MEDIA_RW = 1023, +}; + +enum class BizScene : int32_t { + DFS_CONNECT = 0x1, +}; + +enum class BizStage : int32_t { + DFS_OPEN_SESSION = 0x1, + DFS_SENDFILE = 0x2 +}; + +enum class StageRes : int32_t { + STAGE_SUCCESS = 0x1, + STAGE_FAIL = 0x2 +}; + +enum class BizState : int32_t { + BIZ_STATE_START = 0x1, + BIZ_STATE_END = 0x2, + BIZ_STATE_CANCEL = 0x3 +}; + +struct RadarInfo { + std::string funcName; + std::string localSessionName; + std::string peerSessionName; + int32_t errCode; + StageRes state; +}; + + +#define DEMO_SYNC_SYS_EVENT(eventName, type, ...) \ + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT, eventName, \ + type, ##__VA_ARGS__) \ + +void SysEventWrite(std::string &uid); +void SysEventFileParse(int64_t maxTime); + +void RadarDotsReportOpenSession(struct RadarInfo &info); +void RadarDotsOpenSession(const std::string funcName, const std::string &sessionName, + const std::string &peerSssionName, int32_t errCode, StageRes state); +void RadarDotsReportSendFile(struct RadarInfo &info); +void RadarDotsSendFile(const std::string funcName, const std::string &sessionName, + const std::string &peerSssionName, int32_t errCode, StageRes state); + +std::string GetAnonyString(const std::string &value); + +void ForceCreateDirectory(const std::string &path); +void ForceCreateDirectory(const std::string &path, mode_t mode); +void ForceCreateDirectory(const std::string &path, mode_t mode, uid_t uid, gid_t gid); + +void ForceRemoveDirectory(const std::string &path); +bool ForceRemoveDirectoryDeepFirst(const std::string& path); +bool IsFile(const std::string &path); +bool IsFolder(const std::string &name); +std::vector GetFilePath(const std::string &name); +int32_t ChangeOwnerRecursive(const std::string &path, uid_t uid, gid_t gid); +bool IsInt32(const nlohmann::json &jsonObj, const std::string &key); +} // namespace Utils +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS +#endif // UTILS_DIRECTORY_H \ No newline at end of file diff --git a/cloud_file/utils/system/src/dfsu_access_token_helper.cpp b/cloud_file/utils/system/src/dfsu_access_token_helper.cpp new file mode 100644 index 0000000..c1bbbae --- /dev/null +++ b/cloud_file/utils/system/src/dfsu_access_token_helper.cpp @@ -0,0 +1,151 @@ +/* + * 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 "accesstoken_kit.h" +#include "dfs_daemon_event_dfx.h" +#include "dfs_error.h" +#include "dfsu_access_token_helper.h" +#include "ipc_skeleton.h" +#include "tokenid_kit.h" +#include "uri_permission_manager_client.h" +#include "uri.h" +#include "utils_log.h" +#include "want.h" + +namespace OHOS::FileManagement { +using namespace std; +using namespace Security::AccessToken; +using namespace Storage::DistributedFile; +constexpr int32_t ROOT_UID = 0; +constexpr int32_t BASE_USER_RANGE = 200000; +bool DfsuAccessTokenHelper::CheckCallerPermission(const std::string &permissionName) +{ + auto tokenId = IPCSkeleton::GetCallingTokenID(); + auto uid = IPCSkeleton::GetCallingUid(); + auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId); + if (tokenType == TOKEN_HAP || tokenType == TOKEN_NATIVE) { + bool isGranted = CheckPermission(tokenId, permissionName); + if (!isGranted) { + LOGE("Token Type is %{public}d", tokenType); + } + return isGranted; + } else if ((tokenType == TOKEN_SHELL) && (uid == ROOT_UID)) { + LOGI("Token type is shell"); + return false; + } else { + LOGE("Unsupported token type:%{public}d", tokenType); + return false; + } +} + +bool DfsuAccessTokenHelper::CheckPermission(uint32_t tokenId, const std::string &permissionName) +{ + int32_t ret = AccessTokenKit::VerifyAccessToken(tokenId, permissionName); + if (ret == PermissionState::PERMISSION_DENIED) { + LOGE("permission %{private}s: PERMISSION_DENIED", permissionName.c_str()); + return false; + } + return true; +} + +int32_t DfsuAccessTokenHelper::GetCallerBundleName(std::string &bundleName) +{ + auto tokenId = IPCSkeleton::GetCallingTokenID(); + return GetBundleNameByToken(tokenId, bundleName); +} + +int32_t DfsuAccessTokenHelper::GetBundleNameByToken(uint32_t tokenId, std::string &bundleName) +{ + int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(tokenId); + switch (tokenType) { + case TOKEN_HAP: { + HapTokenInfo hapInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenId, hapInfo) != 0) { + LOGE("[Permission Check] get hap token info fail"); + return E_GET_TOKEN_INFO_ERROR; + } + if (hapInfo.instIndex != 0) { + LOGE("[Permission Check] APP twin is not supported."); + break; + } + bundleName = hapInfo.bundleName; + break; + } + case TOKEN_NATIVE: + // fall-through + case TOKEN_SHELL: { + NativeTokenInfo tokenInfo; + if (AccessTokenKit::GetNativeTokenInfo(tokenId, tokenInfo) != 0) { + LOGE("[Permission Check] get native token info fail"); + return E_GET_TOKEN_INFO_ERROR; + } + bundleName = tokenInfo.processName; + break; + } + default: { + LOGE("[Permission Check] token type not match"); + return E_GET_TOKEN_INFO_ERROR; + } + } + if (bundleName.empty()) { + LOGE("[Permission Check] package name is empty"); + return E_INVAL_ARG; + } + return E_OK; +} +bool DfsuAccessTokenHelper::IsSystemApp() +{ + auto tokenId = IPCSkeleton::GetCallingTokenID(); + auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId); + if (tokenType == TOKEN_HAP) { + uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID(); + return TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); + } + return true; +} + +int32_t DfsuAccessTokenHelper::GetUserId() +{ + auto uid = IPCSkeleton::GetCallingUid(); + return uid / BASE_USER_RANGE; +} + +int32_t DfsuAccessTokenHelper::GetPid() +{ + auto pid = IPCSkeleton::GetCallingPid(); + return pid; +} + +bool DfsuAccessTokenHelper::CheckUriPermission(const std::string &uriStr) +{ + auto tokenId = IPCSkeleton::GetCallingTokenID(); + string bundleName; + if (GetBundleNameByToken(tokenId, bundleName) != E_OK) { + LOGE("get caller bundle name failed"); + return false; + } + Uri uri(uriStr); + auto &uriPermissionClient = AAFwk::UriPermissionManagerClient::GetInstance(); + if (bundleName != uri.GetAuthority() && + !uriPermissionClient.VerifyUriPermission(uri, AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION, tokenId)) { + RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, + RadarReporter::CHECK_URI_PREMISSION_ERROR, RadarReporter::PACKAGE_NAME, RadarReporter::uriPermMgr); + LOGE("uri permission denied"); + return false; + } + return true; +} +} // namespace OHOS::FileManagement \ No newline at end of file diff --git a/cloud_file/utils/system/src/dfsu_fd_guard.cpp b/cloud_file/utils/system/src/dfsu_fd_guard.cpp new file mode 100644 index 0000000..d41c20e --- /dev/null +++ b/cloud_file/utils/system/src/dfsu_fd_guard.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 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 "dfsu_fd_guard.h" + +#include + +#include "utils_log.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +DfsuFDGuard::DfsuFDGuard(int fd) : fd_(fd) {} + +DfsuFDGuard::DfsuFDGuard(int fd, bool autoClose) : fd_(fd), autoClose_(autoClose) {} + +DfsuFDGuard::~DfsuFDGuard() +{ + if (fd_ >= 0 && autoClose_) { + LOGD("DfsuFDGuard Deconstruction, fd_ = %{public}d", fd_); + close(fd_); + } +} + +DfsuFDGuard::operator bool() const +{ + return fd_ >= 0; +} + +int DfsuFDGuard::GetFD() const +{ + return fd_; +} + +void DfsuFDGuard::SetFD(int fd, bool autoClose) +{ + fd_ = fd; + autoClose_ = autoClose; +} + +void DfsuFDGuard::ClearFD() +{ + fd_ = -1; +} +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS diff --git a/cloud_file/utils/system/src/dfsu_memory_guard.cpp b/cloud_file/utils/system/src/dfsu_memory_guard.cpp new file mode 100644 index 0000000..019a8aa --- /dev/null +++ b/cloud_file/utils/system/src/dfsu_memory_guard.cpp @@ -0,0 +1,42 @@ +/* + * 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 "dfsu_memory_guard.h" + +#include "malloc.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +DfsuMemoryGuard::DfsuMemoryGuard() +{ +#ifdef CONFIG_USE_JEMALLOC_DFX_INTF + int setCacheRet = mallopt(M_SET_THREAD_CACHE, M_THREAD_CACHE_DISABLE); + int setFreeRet = mallopt(M_DELAYED_FREE, M_DELAYED_FREE_DISABLE); + if (setCacheRet != 1 || setFreeRet != 1) { + LOGE("dfs disable tcache and delay free, result[%{public}d, %{public}d]", setCacheRet, setFreeRet); + } +#endif +} + +DfsuMemoryGuard::~DfsuMemoryGuard() +{ +#ifdef CONFIG_USE_JEMALLOC_DFX_INTF + int err = mallopt(M_FLUSH_THREAD_CACHE, 0); + if (err != 1) { + LOGE("dfs flush cache, result: %{public}d", err); + } +#endif +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/utils/system/src/dfsu_mount_argument_descriptors.cpp b/cloud_file/utils/system/src/dfsu_mount_argument_descriptors.cpp new file mode 100644 index 0000000..01c508d --- /dev/null +++ b/cloud_file/utils/system/src/dfsu_mount_argument_descriptors.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2021-2025 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 "dfsu_mount_argument_descriptors.h" + +#include +#include +#include + +#include "dfs_error.h" +#include "utils_log.h" +namespace OHOS { +namespace Storage { +namespace DistributedFile { +namespace Utils { +using namespace std; +namespace { + static const std::string DATA_POINT = "/data/service/el2/"; + static const std::string BASE_MOUNT_POINT = "/mnt/hmdfs/"; + static const std::string SYSFS_HMDFS_PATH = "/sys/fs/hmdfs/"; +} // namespace + +string MountArgument::GetFullSrc() const +{ + stringstream ss; + ss << DATA_POINT << userId_ << "/hmdfs/" << relativePath_; + return ss.str(); +} + +string MountArgument::GetFullDst() const +{ + stringstream ss; + ss << BASE_MOUNT_POINT << userId_ << "/" << relativePath_; + return ss.str(); +} + +string MountArgument::GetCachePath() const +{ + stringstream ss; + ss << DATA_POINT << userId_ << "/hmdfs/" << relativePath_ << "/cache/"; + return ss.str(); +} + +static uint64_t MocklispHash(const string &str) +{ + struct stat statBuf; + auto err = stat(str.c_str(), &statBuf); + if (err != 0) { + LOGE("stat failed %{public}s error, err: %{public}d", GetAnonyString(str).c_str(), err); + return static_cast(FileManagement::ERR_BAD_VALUE); + } + LOGI("statBuf dev id: %{public}lu", static_cast(statBuf.st_dev)); + return statBuf.st_dev; +} + +string MountArgument::GetCtrlPath() const +{ + auto dst = GetFullDst(); + auto res = MocklispHash(dst); + stringstream ss; + ss << SYSFS_HMDFS_PATH << res << "/cmd"; + return ss.str(); +} + +string MountArgument::OptionsToString() const +{ + stringstream ss; + ss << "local_dst=" << GetFullDst(); + if (useCache_) { + ss << ",cache_dir=" << GetCachePath(); + } + if (caseSensitive_) { + ss << ",sensitive"; + } + if (enableMergeView_) { + ss << ",merge"; + } + if (enableFixupOwnerShip_) { + ss << ",fixupownership"; + } + if (!enableOfflineStash_) { + ss << ",no_offline_stash"; + } + if (externalFS_) { + ss << ",external_fs"; + } + return ss.str(); +} + +unsigned long MountArgument::GetFlags() const +{ + return MS_NODEV; +} + +MountArgument DfsuMountArgumentDescriptors::Alpha(int userId, string relativePath) +{ + MountArgument mountArgument = { + .userId_ = userId, + .needInitDir_ = true, + .useCache_ = true, + .enableMergeView_ = true, + .enableFixupOwnerShip_ = false, + .enableOfflineStash_ = true, + .externalFS_ = false, + .relativePath_ = relativePath, + }; + + if (relativePath == "non_account") { + mountArgument.accountless_ = true; + } + return mountArgument; +}; +} // namespace Utils +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS diff --git a/cloud_file/utils/system/src/dfsu_timer.cpp b/cloud_file/utils/system/src/dfsu_timer.cpp new file mode 100644 index 0000000..295d58e --- /dev/null +++ b/cloud_file/utils/system/src/dfsu_timer.cpp @@ -0,0 +1,66 @@ +/* + * 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 "dfsu_timer.h" + +#include "common_timer_errors.h" +#include "utils_log.h" + +namespace OHOS::FileManagement { +using namespace std; + +DfsuTimer &DfsuTimer::GetInstance() +{ + static DfsuTimer instance; + return instance; +} + +DfsuTimer::DfsuTimer() : timer_(std::make_unique("OH_DfsTimer")) +{ + timer_->Setup(); +} + +DfsuTimer::~DfsuTimer() +{ + if (timer_) { + timer_->Shutdown(true); + timer_ = nullptr; + } +} + +void DfsuTimer::Register(const Utils::Timer::TimerCallback &callback, uint32_t &outTimerId, uint32_t interval) +{ + if (timer_ == nullptr) { + LOGE("timer is nullptr"); + return; + } + + uint32_t ret = timer_->Register(callback, interval); + if (ret == Utils::TIMER_ERR_DEAL_FAILED) { + LOGE("Register timer failed"); + return; + } + outTimerId = ret; +} + +void DfsuTimer::Unregister(uint32_t timerId) +{ + if ((timerId == 0) || (!timer_)) { + LOGE("timerId is 0 or timer_ is nullptr"); + return; + } + timer_->Unregister(timerId); +} +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/cloud_file/utils/system/src/sys_utils.cpp b/cloud_file/utils/system/src/sys_utils.cpp new file mode 100644 index 0000000..4f22b3d --- /dev/null +++ b/cloud_file/utils/system/src/sys_utils.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 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 "sys_utils.h" + +#include +#include +#include + +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudSync { + +void SlowDown() +{ + cpu_set_t cpuSet; + CPU_ZERO(&cpuSet); + for (int cpu = CPU_IDX_0; cpu <= CPU_IDX_6; cpu++) { + CPU_SET(cpu, &cpuSet); + } + if (sched_setaffinity(0, sizeof(cpuSet), &cpuSet) < 0) { + LOGE("set thread affinity failed, errno %{public}d", errno); + } +} + +void ResetCpu() +{ + cpu_set_t cpuSet; + CPU_ZERO(&cpuSet); + + if (sched_setaffinity(0, sizeof(cpuSet), &cpuSet) < 0) { + LOGE("set thread affinity failed, errno %{public}d", errno); + return; + } +} +} +} +} \ No newline at end of file diff --git a/cloud_file/utils/system/src/utils_directory.cpp b/cloud_file/utils/system/src/utils_directory.cpp new file mode 100644 index 0000000..ed2f0ac --- /dev/null +++ b/cloud_file/utils/system/src/utils_directory.cpp @@ -0,0 +1,377 @@ +/* + * Copyright (c) 2021-2025 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 "utils_directory.h" + +#include +#include +#include +#include +#include + +#include "dfs_error.h" +#include "directory_ex.h" +#include "hisysevent.h" +#include "utils_log.h" + +namespace OHOS { +namespace Storage { +namespace DistributedFile { +namespace Utils { +using namespace std; + +namespace { + static const uint32_t STAT_MODE_DIR = 0771; +} + +std::string GetAnonyString(const std::string &value) +{ + constexpr size_t shortIdLength = 20; + constexpr size_t plaintextLength = 4; + constexpr size_t minIdLength = 3; + std::string res; + std::string tmpStr("******"); + size_t strLen = value.length(); + if (strLen < minIdLength) { + return tmpStr; + } + + if (strLen <= shortIdLength) { + res += value[0]; + res += tmpStr; + res += value[strLen - 1]; + } else { + res.append(value, 0, plaintextLength); + res += tmpStr; + res.append(value, strLen - plaintextLength, plaintextLength); + } + return res; +} + +void SysEventWrite(string &uid) +{ + if (uid.empty()) { + LOGE("uid is empty."); + return; + } + int32_t ret = DEMO_SYNC_SYS_EVENT("PERMISSION_EXCEPTION", + HiviewDFX::HiSysEvent::EventType::SECURITY, + "CALLER_UID", uid, + "PERMISSION_NAME", "account"); + if (ret != ERR_OK) { + LOGE("report PERMISSION_EXCEPTION error %{public}d", ret); + } +} + +void SysEventFileParse(int64_t maxTime) +{ + int32_t ret = DEMO_SYNC_SYS_EVENT("INDEX_FILE_PARSE", + HiviewDFX::HiSysEvent::EventType::STATISTIC, + "MAX_TIME", maxTime); + if (ret != ERR_OK) { + LOGE("report INDEX_FILE_PARSE error %{public}d", ret); + } +} + +void RadarDotsReportOpenSession(struct RadarInfo &info) +{ + int32_t res = ERR_OK; + if (info.state == StageRes::STAGE_SUCCESS) { + res = DEMO_SYNC_SYS_EVENT(DISTRIBUTEDFILE_CONNECT_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "TO_CALL_PKG", SOFTBUSNAME, + "FUNC", info.funcName, + "BIZ_SCENE", static_cast(BizScene::DFS_CONNECT), + "BIZ_STAGE", static_cast(BizStage::DFS_OPEN_SESSION), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_START), + "STAGE_RES", static_cast(StageRes::STAGE_SUCCESS), + "LOCAL_SESS_NAME", info.localSessionName, + "PEER_SESS_NAME", info.peerSessionName); + } else { + res = DEMO_SYNC_SYS_EVENT(DISTRIBUTEDFILE_CONNECT_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "TO_CALL_PKG", SOFTBUSNAME, + "FUNC", info.funcName, + "BIZ_SCENE", static_cast(BizScene::DFS_CONNECT), + "BIZ_STAGE", static_cast(BizStage::DFS_OPEN_SESSION), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), + "LOCAL_SESS_NAME", info.localSessionName, + "PEER_SESS_NAME", info.peerSessionName, + "ERROR_CODE", std::abs(info.errCode)); + } + if (res != ERR_OK) { + LOGE("report RadarDotsReportOpenSession error %{public}d", res); + } +} + +void RadarDotsOpenSession(const std::string funcName, const std::string &sessionName, + const std::string &peerSssionName, int32_t errCode, StageRes state) +{ + struct RadarInfo info = { + .funcName = funcName, + .localSessionName = sessionName, + .peerSessionName = peerSssionName, + .errCode = errCode, + .state = state, + }; + RadarDotsReportOpenSession(info); +} + +void RadarDotsReportSendFile(struct RadarInfo &info) +{ + int32_t res = ERR_OK; + if (info.state == StageRes::STAGE_SUCCESS) { + res = DEMO_SYNC_SYS_EVENT(DISTRIBUTEDFILE_CONNECT_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "TO_CALL_PKG", SOFTBUSNAME, + "FUNC", info.funcName, + "BIZ_SCENE", static_cast(BizScene::DFS_CONNECT), + "BIZ_STAGE", static_cast(BizStage::DFS_SENDFILE), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "STAGE_RES", static_cast(StageRes::STAGE_SUCCESS), + "LOCAL_SESS_NAME", info.localSessionName, + "PEER_SESS_NAME", info.peerSessionName); + } else { + res = DEMO_SYNC_SYS_EVENT(DISTRIBUTEDFILE_CONNECT_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "TO_CALL_PKG", SOFTBUSNAME, + "FUNC", info.funcName, + "BIZ_SCENE", static_cast(BizScene::DFS_CONNECT), + "BIZ_STAGE", static_cast(BizStage::DFS_SENDFILE), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), + "LOCAL_SESS_NAME", info.localSessionName, + "PEER_SESS_NAME", info.peerSessionName, + "ERROR_CODE", std::abs(info.errCode)); + } + if (res != ERR_OK) { + LOGE("report RadarDotsReportSendFile error %{public}d", res); + } +} + +void RadarDotsSendFile(const std::string funcName, const std::string &sessionName, + const std::string &peerSssionName, int32_t errCode, StageRes state) +{ + struct RadarInfo info = { + .funcName = funcName, + .localSessionName = sessionName, + .peerSessionName = peerSssionName, + .errCode = errCode, + .state = state, + }; + RadarDotsReportSendFile(info); +} + +void ForceCreateDirectory(const string &path, function onSubDirCreated) +{ + string::size_type index = 0; + do { + string subPath; + index = path.find('/', index + 1); + if (index == string::npos) { + subPath = path; + } else { + subPath = path.substr(0, index); + } + + if (access(subPath.c_str(), F_OK) != 0) { + if (mkdir(subPath.c_str(), STAT_MODE_DIR) != 0) { + LOGE("failed to mkdir, errno:%{public}d", errno); + return; + } + onSubDirCreated(subPath); + } + } while (index != string::npos); +} + +void ForceCreateDirectory(const string &path) +{ + ForceCreateDirectory(path, nullptr); +} + +void ForceCreateDirectory(const string &path, mode_t mode) +{ + ForceCreateDirectory(path, [mode](const string &subPath) { + if (chmod(subPath.c_str(), mode) == -1) { + LOGE("failed to chmod, errno:%{public}d", errno); + } + }); +} + +void ForceCreateDirectory(const string &path, mode_t mode, uid_t uid, gid_t gid) +{ + ForceCreateDirectory(path, [mode, uid, gid](const string &subPath) { + if (chmod(subPath.c_str(), mode) == -1 || chown(subPath.c_str(), uid, gid) == -1) { + LOGE("failed to chmod or chown, errno:%{public}d", errno); + } + }); +} + +void ForceRemoveDirectory(const string &path) +{ + if (!OHOS::ForceRemoveDirectory(path)) { + LOGE("failed to forcibly remove directory, errno:%{public}d", errno); + } +} + +bool ForceRemoveDirectoryDeepFirst(const string& path) +{ + string subPath; + bool ret = true; + DIR *dir = opendir(path.c_str()); + if (dir == nullptr) { + LOGE("opendir failed, path = %{public}s, err:%{public}d", GetAnonyString(path).c_str(), errno); + return false; + } + + while (true) { + struct dirent *ptr = readdir(dir); + if (ptr == nullptr) { + break; + } + + // current dir OR parent dir + if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) { + continue; + } + subPath = IncludeTrailingPathDelimiter(path) + string(ptr->d_name); + if (ptr->d_type == DT_DIR) { + if (!ForceRemoveDirectoryDeepFirst(subPath)) { + ret = false; + } + } else if (access(subPath.c_str(), F_OK) == 0) { + if (remove(subPath.c_str()) != 0) { + closedir(dir); + LOGE("remove failed, subPath = %{public}s, err:%{public}d", + GetAnonyString(subPath).c_str(), errno); + return false; + } + } + } + closedir(dir); + + string currentPath = ExcludeTrailingPathDelimiter(path); + if (access(currentPath.c_str(), F_OK) == 0) { + if (remove(currentPath.c_str()) != 0) { + LOGE("remove failed, currentPath = %{public}s, err:%{public}d", + GetAnonyString(currentPath).c_str(), errno); + return false; + } + } + + return ret && (access(path.c_str(), F_OK) != 0); +} + +bool IsFile(const std::string &path) +{ + if (path.empty()) { + return false; + } + struct stat buf = {}; + if (stat(path.c_str(), &buf) != 0) { + LOGE("stat failed, errno = %{public}d", errno); + return false; + } + return S_ISREG(buf.st_mode); +} + +bool IsFolder(const std::string &name) +{ + if (name.empty()) { + return false; + } + struct stat buf = {}; + if (stat(name.c_str(), &buf) != 0) { + LOGE("stat failed, errno = %{public}d", errno); + return false; + } + return S_ISDIR(buf.st_mode); +} + +std::vector GetFilePath(const std::string &name) +{ + std::vector path; + if (!IsFolder(name)) { + path.emplace_back(name); + return path; + } + auto dir = opendir(name.data()); + struct dirent *ent = nullptr; + if (dir) { + while ((ent = readdir(dir)) != nullptr) { + auto tmpPath = std::string(name).append("/").append(ent->d_name); + if (strcmp(ent->d_name, "..") == 0 || strcmp(ent->d_name, ".") == 0) { + continue; + } else if (IsFolder(tmpPath)) { + auto dirPath = GetFilePath(tmpPath); + path.insert(path.end(), dirPath.begin(), dirPath.end()); + } else { + path.emplace_back(tmpPath); + } + } + closedir(dir); + } + return path; +} + +int32_t ChangeOwnerRecursive(const std::string &path, uid_t uid, gid_t gid) +{ + std::unique_ptr dir(opendir(path.c_str()), &closedir); + if (dir == nullptr) { + LOGE("Directory is null"); + return -1; + } + + struct dirent *entry = nullptr; + while ((entry = readdir(dir.get())) != nullptr) { + if (entry->d_type == DT_DIR) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { + continue; + } + std::string subPath = path + "/" + entry->d_name; + if (chown(subPath.c_str(), uid, gid) == -1) { + LOGE("Change owner recursive failed"); + return -1; + } + return ChangeOwnerRecursive(subPath, uid, gid); + } else { + std::string filePath = path + "/" + entry->d_name; + if (chown(filePath.c_str(), uid, gid) == -1) { + LOGE("Change owner recursive failed"); + return -1; + } + } + } + return 0; +} + +bool IsInt32(const nlohmann::json &jsonObj, const std::string &key) +{ + bool res = jsonObj.contains(key) && jsonObj[key].is_number_integer() && jsonObj[key] >= INT32_MIN && + jsonObj[key] <= INT32_MAX; + if (!res) { + LOGE("the key %{public}s in jsonObj is invalid.", key.c_str()); + } + return res; +} +} // namespace Utils +} // namespace DistributedFile +} // namespace Storage +} // namespace OHOS \ No newline at end of file diff --git a/cloud_file/utils/work/include/async_work.h b/cloud_file/utils/work/include/async_work.h new file mode 100644 index 0000000..76f0b40 --- /dev/null +++ b/cloud_file/utils/work/include/async_work.h @@ -0,0 +1,30 @@ +/* + * 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 OHOS_FILEMGMT_ASYNC_WORK_H +#define OHOS_FILEMGMT_ASYNC_WORK_H + +#include "filemgmt_libn.h" +#include "n_func_arg.h" +#include "n_async_context.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { + std::unique_ptr GetPromiseOrCallBackWork(napi_env env, const NFuncArg& funcArg, size_t maxArgSize); +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS +#endif // OHOS_FILEMGMT_ASYNC_WORK_H \ No newline at end of file diff --git a/cloud_file/utils/work/src/async_work.cpp b/cloud_file/utils/work/src/async_work.cpp new file mode 100644 index 0000000..1707fc5 --- /dev/null +++ b/cloud_file/utils/work/src/async_work.cpp @@ -0,0 +1,42 @@ +/* + * 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 "async_work.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace LibN { + +std::unique_ptr GetPromiseOrCallBackWork(napi_env env, const NFuncArg &funcArg, size_t maxArgSize) +{ + std::unique_ptr asyncWork = nullptr; + NVal thisVar(env, funcArg.GetThisVar()); + if (funcArg.GetArgc() != maxArgSize) { + asyncWork = std::make_unique(env, thisVar); + } else { + NVal cb(env, funcArg[(int)maxArgSize - 1]); + if (cb.TypeIs(napi_function)) { + asyncWork = std::make_unique(env, thisVar, cb); + } else { + LOGE("Argument type mismatch"); + NError(E_PARAMS).ThrowErr(env); + } + } + return asyncWork; +} +} // namespace LibN +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file -- Gitee