diff --git a/frameworks/innerkitsimpl/media_library_helper/include/media_asset_rdbstore.h b/frameworks/innerkitsimpl/media_library_helper/include/media_asset_rdbstore.h index 4fc104ac8c9e8021a073584d978a01dace909b9f..2b86829b764fae30709cf2cc1875ea9204fefad3 100644 --- a/frameworks/innerkitsimpl/media_library_helper/include/media_asset_rdbstore.h +++ b/frameworks/innerkitsimpl/media_library_helper/include/media_asset_rdbstore.h @@ -52,6 +52,7 @@ private: int32_t TryGetRdbStore(bool isIngnoreSELinux = false); EXPORT static const std::string CloudSyncTriggerFunc(const std::vector& args); EXPORT static const std::string IsCallerSelfFunc(const std::vector& args); + EXPORT static const std::string PhotoAlbumNotifyFunc(const std::vector& args); bool IsQueryGroupPhotoAlbumAssets(const std::string& albumId); std::shared_ptr rdbStore_ {nullptr}; }; diff --git a/frameworks/innerkitsimpl/media_library_helper/src/media_asset_rdbstore.cpp b/frameworks/innerkitsimpl/media_library_helper/src/media_asset_rdbstore.cpp index 1f5ee2b6ed56f34f6d905cfc4de4ee06c0e2e2b4..2a53417f35c04083d20996fe3be6d69f0630e8aa 100644 --- a/frameworks/innerkitsimpl/media_library_helper/src/media_asset_rdbstore.cpp +++ b/frameworks/innerkitsimpl/media_library_helper/src/media_asset_rdbstore.cpp @@ -105,6 +105,11 @@ const std::string MediaAssetRdbStore::IsCallerSelfFunc(const std::vector &args) +{ + return ""; +} + MediaAssetRdbStore::MediaAssetRdbStore() { MEDIA_INFO_LOG("init visitor rdb"); @@ -149,6 +154,7 @@ int32_t MediaAssetRdbStore::TryGetRdbStore(bool isIgnoreSELinux) config.SetRoleType(RoleType::VISITOR); config.SetScalarFunction("cloud_sync_func", 0, CloudSyncTriggerFunc); config.SetScalarFunction("is_caller_self_func", 0, IsCallerSelfFunc); + config.SetScalarFunction("photo_album_notify_func", 1, PhotoAlbumNotifyFunc); MediaLibraryDataCallBack rdbDataCallBack; rdbStore_ = RdbHelper::GetRdbStore(config, MEDIA_RDB_VERSION, rdbDataCallBack, errCode); diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/BUILD.gn b/frameworks/innerkitsimpl/medialibrary_data_extension/BUILD.gn index a0f651e7024f10833b9619e664dc798edbfb4532..2f83015e2935fc610c13ae642860ae68ba5c3b56 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/BUILD.gn +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/BUILD.gn @@ -57,6 +57,10 @@ config("media_data_extension_public_config") { "${MEDIALIB_SERVICES_PATH}/media_cloud_sync/include/media_cloud_asset_download", ] + include_cloud_dirty_handle = [ + "${MEDIALIB_SERVICES_PATH}/media_cloud_sync/include/cloud_dirty_handle", + ] + include_dirs = [ "${MEDIALIB_INTERFACES_PATH}/innerkits/native/include", "${MEDIALIB_INTERFACES_PATH}/inner_api/media_library_helper/include", @@ -84,6 +88,7 @@ config("media_data_extension_public_config") { include_dirs += include_dfx include_dirs += include_cloud_enhancement include_dirs += include_cloud_asset_download + include_dirs += include_cloud_dirty_handle if (defined(global_parts_info) && defined( @@ -254,7 +259,7 @@ ohos_shared_library("medialibrary_data_extension") { "${MEDIALIB_SERVICES_PATH}/media_power_efficiency/src/medialibrary_standby_service_subscriber.cpp", ] - meidia_cloud_asset_download_source = [ + media_cloud_asset_download_source = [ "${MEDIALIB_SERVICES_PATH}/media_cloud_sync/src/cloud_sync_utils/cloud_sync_utils.cpp", "${MEDIALIB_SERVICES_PATH}/media_cloud_sync/src/media_cloud_asset_download/cloud_media_asset_callback.cpp", "${MEDIALIB_SERVICES_PATH}/media_cloud_sync/src/media_cloud_asset_download/cloud_media_asset_download_operation.cpp", @@ -262,6 +267,8 @@ ohos_shared_library("medialibrary_data_extension") { "${MEDIALIB_SERVICES_PATH}/media_cloud_sync/src/media_cloud_asset_download/cloud_media_asset_observer.cpp", ] + media_cloud_dirty_handle_source = [ "${MEDIALIB_SERVICES_PATH}/media_cloud_sync/src/cloud_dirty_handle/cloud_upload_checker.cpp" ] + sources = [ "${MEDIALIB_SERVICES_PATH}/media_analysis_extension/src/media_analysis_callback_stub.cpp", "${MEDIALIB_SERVICES_PATH}/media_analysis_extension/src/media_analysis_helper.cpp", @@ -335,7 +342,8 @@ ohos_shared_library("medialibrary_data_extension") { sources += media_permission_source sources += media_cloud_enhancement_source sources += media_power_efficiency_source - sources += meidia_cloud_asset_download_source + sources += media_cloud_asset_download_source + sources += media_cloud_dirty_handle_source public_configs = [ ":media_data_extension_public_config" ] diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_album_compatibility_fusion_sql.h b/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_album_compatibility_fusion_sql.h index 733518e2439b09ec7de5616f0f54aa39425a619b..a3e73d237970edf5694d0058c03c38c2e7913a03 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_album_compatibility_fusion_sql.h +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_album_compatibility_fusion_sql.h @@ -76,6 +76,11 @@ const std::string FILL_ALBUM_ID_FOR_PHOTOS = PhotoAlbumColumns::ALBUM_SUBTYPE + " = " + std::to_string(OHOS::Media::PhotoAlbumSubType::SOURCE_GENERIC) + " AND dirty != 4 ORDER BY priority DESC LIMIT 1) WHERE file_id = new.file_id"; +const std::string PHOTO_ALBUM_NOTIFY_FUNC = + "SELECT photo_album_notify_func((SELECT " + PhotoColumn::PHOTO_OWNER_ALBUM_ID + + " FROM " + PhotoColumn::PHOTOS_TABLE + + " WHERE " + MediaColumn::MEDIA_ID + " = NEW." + MediaColumn::MEDIA_ID + "));"; + const std::string CREATE_INSERT_SOURCE_PHOTO_CREATE_SOURCE_ALBUM_TRIGGER = "CREATE TRIGGER IF NOT EXISTS insert_source_photo_create_source_album_trigger AFTER INSERT ON " + PhotoColumn::PHOTOS_TABLE + WHEN_SOURCE_PHOTO_COUNT + " = 0 " + @@ -96,7 +101,7 @@ const std::string CREATE_INSERT_SOURCE_PHOTO_CREATE_SOURCE_ALBUM_TRIGGER = "NEW.owner_package AND COALESCE(NEW.owner_package,'')!= '') OR album_name = NEW.package_name) " "and priority ='1'), '/Pictures/'||NEW.package_name), 1, " "strftime('%s000', 'now')" + - ");" + FILL_ALBUM_ID_FOR_PHOTOS + "; END;"; + ");" + FILL_ALBUM_ID_FOR_PHOTOS + "; " + PHOTO_ALBUM_NOTIFY_FUNC + " END;"; const std::string CREATE_INSERT_SOURCE_UPDATE_ALBUM_ID_TRIGGER = "CREATE TRIGGER IF NOT EXISTS insert_source_photo_update_album_id_trigger AFTER INSERT ON " + diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_notify.h b/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_notify.h index c53a594813e364d6741a8fed27e2ffd2ca6050ac..1432aac4401133a42727032c252861ca36bb8397 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_notify.h +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_notify.h @@ -43,7 +43,6 @@ public: int albumId_; bool hiddenOnly_ = false; }; -constexpr size_t MAX_NOTIFY_LIST_SIZE = 32; constexpr size_t MNOTIFY_TIME_INTERVAL = 100; class MediaLibraryNotify { public: @@ -55,8 +54,8 @@ public: EXPORT int32_t GetAlbumIdBySubType(const PhotoAlbumSubType subType); static void GetNotifyUris(const NativeRdb::AbsRdbPredicates &predicates, std::vector ¬ifyUris); - Utils::Timer timer_; - static uint32_t timerId_; + static std::atomic counts_; + static int32_t threadId_; static std::mutex mutex_; static std::unordered_map>> nfListMap_; private: diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_rdbstore.h b/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_rdbstore.h index 1ae14eba6efbadbbeea303ffd157f23fb174419d..f37a0bfc978eea259b1a236c590e7b551f8f09db 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_rdbstore.h +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_rdbstore.h @@ -137,6 +137,7 @@ private: friend class TransactionOperations; static std::shared_ptr rdbStore_; EXPORT static const std::string BeginGenerateHighlightThumbnail(const std::vector& args); + EXPORT static const std::string PhotoAlbumNotifyFunc(const std::vector& args); static std::mutex reconstructLock_; static std::mutex walCheckPointMutex_; #ifdef DISTRIBUTED diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_subscriber.h b/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_subscriber.h index 43a2ce04e22d0562bef1c67549c32e9abf3368b6..2f9655c6f2b312e4918455399149d1d765a26973 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_subscriber.h +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/include/medialibrary_subscriber.h @@ -22,7 +22,6 @@ #include "common_event_subscriber.h" #include "common_event_support.h" #include "matching_skills.h" -#include "timer.h" namespace OHOS { namespace Media { @@ -38,8 +37,6 @@ enum class StatusEventType { class EXPORT MedialibrarySubscriber : public EventFwk::CommonEventSubscriber { public: - EXPORT void StartTimer(); - EXPORT void ShutDownTimer(); EXPORT MedialibrarySubscriber() = default; EXPORT explicit MedialibrarySubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo); EXPORT static bool Subscribe(void); @@ -62,9 +59,6 @@ private: int32_t deviceTemperatureLevel_ {0}; int32_t newTemperatureLevel_ {0}; int64_t lockTime_ {0}; - static Utils::Timer timer_; - static uint32_t timerId_; - static std::mutex timeMutex_; std::mutex delayTaskLock_; std::condition_variable delayTaskCv_; @@ -90,7 +84,6 @@ private: void DoThumbnailOperation(); bool IsDelayTaskTimeOut(); void EndBackgroundOperationThread(); - void UpdateSubcriberStatus(); void UpdateCloudAssetNetStatus(); }; } // namespace Media diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_inotify.cpp b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_inotify.cpp index 600181e282dd7cae86eb583302f01353f2cf9b40..2f9d2144f448a91f0379bcbc2784f9503f9b7cec 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_inotify.cpp +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_inotify.cpp @@ -27,13 +27,14 @@ #include "medialibrary_errno.h" #include "medialibrary_uripermission_operations.h" #include "permission_utils.h" +#include "dfx_utils.h" using namespace std; namespace OHOS { namespace Media { std::shared_ptr MediaLibraryInotify::instance_ = nullptr; std::mutex MediaLibraryInotify::mutex_; -const int32_t MAX_WATCH_LIST = 500; +const int32_t MAX_WATCH_LIST = 300; const int32_t MAX_AGING_WATCH_LIST = 100; shared_ptr MediaLibraryInotify::GetInstance() @@ -110,6 +111,7 @@ void MediaLibraryInotify::WatchCallBack() } } } + MEDIA_INFO_LOG("MediaLibraryInotify end watchthread"); isWatching_ = false; } @@ -196,20 +198,18 @@ int32_t MediaLibraryInotify::AddWatchList(const string &path, const string &uri, lock_guard lock(mutex_); if (watchList_.size() > MAX_WATCH_LIST) { MEDIA_ERR_LOG("watch list full, add uri:%{public}s fail", uri.c_str()); - // reset watchlist - Init(); - isWatching_ = false; + return E_FAIL; } int32_t wd = inotify_add_watch(inotifyFd_, path.c_str(), IN_CLOSE | IN_MODIFY); if (wd > 0) { string bundleName = MediaLibraryBundleManager::GetInstance()->GetClientBundleName(); struct WatchInfo item(path, uri, bundleName, api); + MEDIA_INFO_LOG("inotify emplace path:%{public}s", DfxUtils::GetSafePath(path).c_str()); watchList_.emplace(wd, item); } if (!isWatching_.load()) { isWatching_ = true; thread(&MediaLibraryInotify::WatchCallBack, this).detach(); - MEDIA_INFO_LOG("start inotify thread end"); } return E_SUCCESS; } diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_notify.cpp b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_notify.cpp index 81310aec509a507e9b839a7e35216303a84152df..0b087618ffa3c8a473281cb5096e7f636f5976ba 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_notify.cpp +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_notify.cpp @@ -15,6 +15,7 @@ #define MLOG_TAG "FileNotify" #include "medialibrary_notify.h" #include "medialibrary_async_worker.h" +#include "medialibrary_period_worker.h" #include "data_ability_helper_impl.h" #include "media_file_utils.h" #include "media_log.h" @@ -39,7 +40,9 @@ static const int32_t WAIT_TIME = 2; shared_ptr MediaLibraryNotify::instance_; mutex MediaLibraryNotify::mutex_; unordered_map MediaLibraryNotify::nfListMap_ = {}; -uint32_t MediaLibraryNotify::timerId_ = 0; +int32_t MediaLibraryNotify::threadId_{-1}; +atomic MediaLibraryNotify::counts_(0); +static const uint16_t IDLING_TIME = 50; shared_ptr MediaLibraryNotify::GetInstance() { @@ -57,12 +60,15 @@ shared_ptr MediaLibraryNotify::GetInstance() } return instance_; } -MediaLibraryNotify::MediaLibraryNotify() : timer_("on_notify") {}; +MediaLibraryNotify::MediaLibraryNotify() {}; MediaLibraryNotify::~MediaLibraryNotify() { - timer_.Shutdown(); - timer_.Unregister(timerId_); + auto periodWorker = MediaLibraryPeriodWorker::GetInstance(); + if (periodWorker == nullptr) { + MEDIA_ERR_LOG("failed to get period worker instance"); + } + periodWorker->CloseThreadById(MediaLibraryNotify::threadId_); }; static bool SolveUris(const list &uris, Parcel &parcel) @@ -149,7 +155,18 @@ static void PushNotification() { lock_guard lock(MediaLibraryNotify::mutex_); if (MediaLibraryNotify::nfListMap_.empty()) { + ++MediaLibraryNotify::counts_; + if (MediaLibraryNotify::counts_.load() > IDLING_TIME) { + auto periodWorker = MediaLibraryPeriodWorker::GetInstance(); + if (periodWorker == nullptr) { + MEDIA_ERR_LOG("failed to get period worker instance"); + return; + } + periodWorker->CloseThreadById(MediaLibraryNotify::threadId_); + } return; + } else { + MediaLibraryNotify::counts_.store(0); } MediaLibraryNotify::nfListMap_.swap(tmpNfListMap); MediaLibraryNotify::nfListMap_.clear(); @@ -264,19 +281,35 @@ static void AddNfListMap(AsyncTaskData *data) int32_t MediaLibraryNotify::Init() { - MediaLibraryNotify::timerId_ = MediaLibraryNotify::timer_.Register(PushNotification, MNOTIFY_TIME_INTERVAL); - MediaLibraryNotify::timer_.Setup(); + auto periodWorker = MediaLibraryPeriodWorker::GetInstance(); + if (periodWorker == nullptr) { + MEDIA_ERR_LOG("failed to get period worker instance"); + return E_ERR; + } + auto periodTask = make_shared(PushNotification, MNOTIFY_TIME_INTERVAL); + MediaLibraryNotify::threadId_ = periodWorker->AddTask(periodTask); + if (MediaLibraryNotify::threadId_ == E_ERR) { + MEDIA_ERR_LOG("failed to add task"); + return E_ERR; + } return E_OK; } int32_t MediaLibraryNotify::Notify(const string &uri, const NotifyType notifyType, const int albumId, const bool hiddenOnly) { - if (MediaLibraryNotify::nfListMap_.size() > MAX_NOTIFY_LIST_SIZE) { - MediaLibraryNotify::timer_.Shutdown(); - PushNotification(); - MediaLibraryNotify::timer_.Register(PushNotification, MNOTIFY_TIME_INTERVAL); - MediaLibraryNotify::timer_.Setup(); + if (counts_.load() > IDLING_TIME) { + MediaLibraryNotify::counts_.store(0); + auto periodWorker = MediaLibraryPeriodWorker::GetInstance(); + if (periodWorker != nullptr) { + auto periodTask = make_shared(PushNotification, MNOTIFY_TIME_INTERVAL); + MediaLibraryNotify::threadId_ = periodWorker->AddTask(periodTask); + if (MediaLibraryNotify::threadId_ == E_ERR) { + MEDIA_ERR_LOG("failed to add task"); + } + } else { + MEDIA_ERR_LOG("failed to get period worker instance"); + } } unique_ptr &asyncWorker = NotifyTaskWorker::GetInstance(); CHECK_AND_RETURN_RET_LOG(asyncWorker != nullptr, E_ASYNC_WORKER_IS_NULL, "AsyncWorker is null"); diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_rdbstore.cpp b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_rdbstore.cpp index b1e9c2ae9d5948aba3759454853be7b6db0e08bd..133134d12ee305472b60180ded52817a82604a4c 100755 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_rdbstore.cpp +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_rdbstore.cpp @@ -459,6 +459,24 @@ const std::string MediaLibraryRdbStore::IsCallerSelfFunc(const std::vector &args) +{ + if (args.size() < 1) { + MEDIA_ERR_LOG("Invalid input: args must contain at least 1 strings"); + return ""; + } + std::string albumId = args[0].c_str(); + MEDIA_DEBUG_LOG("albumId = %{public}s", albumId.c_str()); + auto watch = MediaLibraryNotify::GetInstance(); + if (watch == nullptr) { + MEDIA_ERR_LOG("Failed to get MediaLibraryNotify"); + return ""; + } + watch->Notify(MediaFileUtils::GetUriByExtrConditions(PhotoAlbumColumns::ALBUM_URI_PREFIX, albumId), + NotifyType::NOTIFY_ADD); + return ""; +} + MediaLibraryRdbStore::MediaLibraryRdbStore(const shared_ptr &context) { if (context == nullptr) { @@ -480,6 +498,7 @@ MediaLibraryRdbStore::MediaLibraryRdbStore(const shared_ptr sqls = { + DROP_INSERT_SOURCE_PHOTO_CREATE_SOURCE_ALBUM_TRIGGER, + CREATE_INSERT_SOURCE_PHOTO_CREATE_SOURCE_ALBUM_TRIGGER, + }; + ExecSqls(sqls, store); + MEDIA_INFO_LOG("end update source photo album trigger"); +} + static void AddSupportedWatermarkType(RdbStore &store) { const vector sqls = { @@ -4251,6 +4281,10 @@ static void UpgradeExtensionPart4(RdbStore &store, int32_t oldVersion) if (oldVersion < VERSION_THUMBNAIL_READY_FIX) { AddThumbnailReadyColumnsFix(store); } + + if (oldVersion < VERSION_UPDATE_SOURCE_PHOTO_ALBUM_TRIGGER) { + UpdateSourcePhotoAlbumTrigger(store); + } } static void UpgradeExtensionPart3(RdbStore &store, int32_t oldVersion) diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_subscriber.cpp b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_subscriber.cpp index fdc2f74c963095a2a266e4e23c4a830ddb8d8f5d..d4b8289949799273bc6bf7a801ec8b0d58da35ae 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_subscriber.cpp +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_subscriber.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#define MLOG_TAG "Subscribe" +#define MLOG_TAG "MedialibrarySubscribe" #include "medialibrary_subscriber.h" @@ -27,6 +27,7 @@ #include "cloud_media_asset_manager.h" #include "cloud_media_asset_types.h" #include "cloud_sync_utils.h" +#include "cloud_upload_checker.h" #include "common_event_manager.h" #include "common_event_support.h" #include "common_event_utils.h" @@ -83,16 +84,13 @@ const int32_t PROPER_DEVICE_TEMPERATURE_LEVEL_HOT = 3; // WIFI should be available in this state const int32_t WIFI_STATE_CONNECTED = 4; -const int32_t SUBSCRIBER_STATUS_TIME = 30 * 60 * 1000; const int32_t DELAY_TASK_TIME = 30000; const int32_t COMMON_EVENT_KEY_GET_DEFAULT_PARAM = -1; const int32_t MegaByte = 1024*1024; const int32_t MAX_FILE_SIZE_MB = 200; const std::string COMMON_EVENT_KEY_BATTERY_CAPACITY = "soc"; const std::string COMMON_EVENT_KEY_DEVICE_TEMPERATURE = "0"; -std::mutex MedialibrarySubscriber::timeMutex_; -uint32_t MedialibrarySubscriber::timerId_ = 0; -Utils::Timer MedialibrarySubscriber::timer_("medialibrary_subscriber"); + // The network should be available in this state const int32_t NET_CONN_STATE_CONNECTED = 3; const std::vector MedialibrarySubscriber::events_ = { @@ -219,73 +217,6 @@ void MedialibrarySubscriber::CheckHalfDayMissions() #endif } -void MedialibrarySubscriber::UpdateSubcriberStatus() -{ -#ifdef HAS_POWER_MANAGER_PART - auto& powerMgrClient = PowerMgr::PowerMgrClient::GetInstance(); - isScreenOff_ = !powerMgrClient.IsScreenOn(); -#endif -#ifdef HAS_BATTERY_MANAGER_PART - auto& batteryClient = PowerMgr::BatterySrvClient::GetInstance(); - auto chargeState = batteryClient.GetChargingStatus(); - isCharging_ = (chargeState == PowerMgr::BatteryChargeState::CHARGE_STATE_ENABLE) || - (chargeState == PowerMgr::BatteryChargeState::CHARGE_STATE_FULL); - isPowerSufficient_ = batteryClient.GetCapacity() >= PROPER_DEVICE_BATTERY_CAPACITY; -#endif -#ifdef HAS_THERMAL_MANAGER_PART - auto& thermalMgrClient = PowerMgr::ThermalMgrClient::GetInstance(); - newTemperatureLevel_ = static_cast(thermalMgrClient.GetThermalLevel()); - isDeviceTemperatureProper_ = newTemperatureLevel_ <= PROPER_DEVICE_TEMPERATURE_LEVEL; -#endif - std::lock_guard lock(mutex_); - if (deviceTemperatureLevel_ != newTemperatureLevel_) { - deviceTemperatureLevel_ = newTemperatureLevel_; - ThumbnailService::GetInstance()->NotifyTempStatusForReady(deviceTemperatureLevel_); - } - bool newStatus = isScreenOff_ && isCharging_ && isPowerSufficient_ && isDeviceTemperatureProper_; - - if (currentStatus_ == newStatus) { - return; - } - currentStatus_ = newStatus; - ThumbnailService::GetInstance()->UpdateCurrentStatusForTask(newStatus); - EndBackgroundOperationThread(); - if (currentStatus_) { - isTaskWaiting_ = true; - backgroundOperationThread_ = std::thread([this] { this->DoBackgroundOperation(); }); - } else { - StopBackgroundOperation(); - } -} - -void MedialibrarySubscriber::StartTimer() -{ - std::unique_lock lock(timeMutex_); - if (timerId_ != 0) { - return; - } - uint32_t ret = timer_.Setup(); - if (ret != Utils::TIMER_ERR_OK) { - MEDIA_ERR_LOG("Failed to start subscriber timer, err: %{public}d", ret); - } - Utils::Timer::TimerCallback timerCallback = [this]() { - UpdateSubcriberStatus(); - }; - timerId_ = timer_.Register(timerCallback, SUBSCRIBER_STATUS_TIME, false); -} - -void MedialibrarySubscriber::ShutDownTimer() -{ - std::unique_lock lock(timeMutex_); - if (timerId_ == 0) { - return; - } - MEDIA_INFO_LOG("MedialibrarySubscriber ShutDownTimer id %{public}d", timerId_); - timer_.Unregister(timerId_); - timerId_ = 0; - timer_.Shutdown(); -} - void MedialibrarySubscriber::UpdateCurrentStatus() { std::lock_guard lock(mutex_); @@ -307,11 +238,9 @@ void MedialibrarySubscriber::UpdateCurrentStatus() EndBackgroundOperationThread(); if (currentStatus_) { isTaskWaiting_ = true; - StartTimer(); backgroundOperationThread_ = std::thread([this] { this->DoBackgroundOperation(); }); } else { StopBackgroundOperation(); - ShutDownTimer(); } } @@ -623,6 +552,7 @@ void MedialibrarySubscriber::DoBackgroundOperation() if (ret != E_OK) { MEDIA_ERR_LOG("DoUpdateBurstFromGallery faild"); } + CloudUploadChecker::HandleNoOriginPhoto(); // migration highlight info to new path if (MediaFileUtils::IsFileExists(ROOT_MEDIA_DIR + HIGHLIGHT_INFO_OLD)) { diff --git a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_uripermission_operations.cpp b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_uripermission_operations.cpp index a9b9e3c5937c56a3bb0d1c9cb47ee727dcbfb095..4754d8174d524e2383b07a73166d79aadf2baf17 100644 --- a/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_uripermission_operations.cpp +++ b/frameworks/innerkitsimpl/medialibrary_data_extension/src/medialibrary_uripermission_operations.cpp @@ -103,6 +103,7 @@ static void DeleteAllTemporaryOperation(AsyncTaskData *data) auto rdbStore = MediaLibraryUnistoreManager::GetInstance().GetRdbStore(); if (rdbStore == nullptr) { MEDIA_ERR_LOG("UriPermission update operation, rdbStore is null."); + return; } NativeRdb::RdbPredicates rdbPredicate(AppUriPermissionColumn::APP_URI_PERMISSION_TABLE); vector permissionTypes; diff --git a/frameworks/innerkitsimpl/test/fuzztest/medialibraryextension_fuzzer/medialibraryextension_fuzzer.cpp b/frameworks/innerkitsimpl/test/fuzztest/medialibraryextension_fuzzer/medialibraryextension_fuzzer.cpp index 6ec51f07fdfd4e94c9405553184628e24c2e1caa..9048988711796d0c4aae23bc95e1b194952f453a 100644 --- a/frameworks/innerkitsimpl/test/fuzztest/medialibraryextension_fuzzer/medialibraryextension_fuzzer.cpp +++ b/frameworks/innerkitsimpl/test/fuzztest/medialibraryextension_fuzzer/medialibraryextension_fuzzer.cpp @@ -123,14 +123,14 @@ static inline DataSharePredicates FuzzDataSharePredicates(const uint8_t *data, s return DataSharePredicates(FuzzVectorOperationItem(data, size)); } -static inline DataShareValuesBucket FuzzDataShareValuesBucket(const uint8_t *data, size_t size) +static inline DataShareValuesBucket FuzzDataShareValuesBucket() { return {}; } -static inline vector FuzzVectorDataShareValuesBucket(const uint8_t *data, size_t size) +static inline vector FuzzVectorDataShareValuesBucket() { - return {FuzzDataShareValuesBucket(data, size)}; + return {FuzzDataShareValuesBucket()}; } static inline DatashareBusinessError FuzzDataShareBusinessError(const uint8_t *data, size_t size) @@ -176,18 +176,18 @@ static inline void OpenRawFileFuzzer(MediaDataShareExtAbility &extension, const static inline void InsertFuzzer(MediaDataShareExtAbility &extension, const uint8_t* data, size_t size) { - extension.Insert(FuzzUri(data, size), FuzzDataShareValuesBucket(data, size)); + extension.Insert(FuzzUri(data, size), FuzzDataShareValuesBucket()); } static inline void InsertExtFuzzer(MediaDataShareExtAbility &extension, const uint8_t* data, size_t size) { string uri; - extension.InsertExt(FuzzUri(data, size), FuzzDataShareValuesBucket(data, size), uri); + extension.InsertExt(FuzzUri(data, size), FuzzDataShareValuesBucket(), uri); } static inline void UpdateFuzzer(MediaDataShareExtAbility &extension, const uint8_t* data, size_t size) { - extension.Update(FuzzUri(data, size), FuzzDataSharePredicates(data, size), FuzzDataShareValuesBucket(data, size)); + extension.Update(FuzzUri(data, size), FuzzDataSharePredicates(data, size), FuzzDataShareValuesBucket()); } static inline void DeleteFuzzer(MediaDataShareExtAbility &extension, const uint8_t* data, size_t size) @@ -209,7 +209,7 @@ static inline void GetTypeFuzzer(MediaDataShareExtAbility &extension, const uint static inline void BatchInsertFuzzer(MediaDataShareExtAbility &extension, const uint8_t* data, size_t size) { - extension.BatchInsert(FuzzUri(data, size), FuzzVectorDataShareValuesBucket(data, size)); + extension.BatchInsert(FuzzUri(data, size), FuzzVectorDataShareValuesBucket()); } static inline void RegisterObserverFuzzer(MediaDataShareExtAbility &extension, const uint8_t* data, size_t size) diff --git a/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensionbatchinsert_fuzzer/src/medialibrary_extension_batch_insert_fuzzer.cpp b/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensionbatchinsert_fuzzer/src/medialibrary_extension_batch_insert_fuzzer.cpp index 632840d93ee52c1a465071215d17e3b9033b12fb..516b6f4ed3fa5e9be892c2cde2fdcb1924502deb 100644 --- a/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensionbatchinsert_fuzzer/src/medialibrary_extension_batch_insert_fuzzer.cpp +++ b/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensionbatchinsert_fuzzer/src/medialibrary_extension_batch_insert_fuzzer.cpp @@ -41,19 +41,19 @@ static inline Uri FuzzUri(const uint8_t *data, size_t size) return Uri(FuzzString(data, size)); } -static inline DataShareValuesBucket FuzzDataShareValuesBucket(const uint8_t *data, size_t size) +static inline DataShareValuesBucket FuzzDataShareValuesBucket() { return {}; } -static inline vector FuzzVectorDataShareValuesBucket(const uint8_t *data, size_t size) +static inline vector FuzzVectorDataShareValuesBucket() { - return {FuzzDataShareValuesBucket(data, size)}; + return {FuzzDataShareValuesBucket()}; } static inline void BatchInsertFuzzer(MediaDataShareExtAbility &extension, const uint8_t* data, size_t size) { - extension.BatchInsert(FuzzUri(data, size), FuzzVectorDataShareValuesBucket(data, size)); + extension.BatchInsert(FuzzUri(data, size), FuzzVectorDataShareValuesBucket()); } static inline MediaDataShareExtAbility Init() diff --git a/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensioninsert_fuzzer/src/medialibrary_extension_insert_fuzzer.cpp b/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensioninsert_fuzzer/src/medialibrary_extension_insert_fuzzer.cpp index 85052294b15e09f47ee5f11505ef9b84184eefdd..30efe0a86bbd21df24c69edbff29f6353c82f243 100644 --- a/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensioninsert_fuzzer/src/medialibrary_extension_insert_fuzzer.cpp +++ b/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensioninsert_fuzzer/src/medialibrary_extension_insert_fuzzer.cpp @@ -41,7 +41,7 @@ static inline Uri FuzzUri(const uint8_t *data, size_t size) return Uri(FuzzString(data, size)); } -static inline DataShareValuesBucket FuzzDataShareValuesBucket(const uint8_t *data, size_t size) +static inline DataShareValuesBucket FuzzDataShareValuesBucket() { return {}; } @@ -50,7 +50,7 @@ static inline void InsertFuzzer(MediaDataShareExtAbility &extension, const uint8 { DataSharePredicates predicates; DataShareValuesBucket values; - extension.Insert(FuzzUri(data, size), FuzzDataShareValuesBucket(data, size)); + extension.Insert(FuzzUri(data, size), FuzzDataShareValuesBucket()); } static inline MediaDataShareExtAbility Init() diff --git a/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensionupdate_fuzzer/src/medialibrary_extension_update_fuzzer.cpp b/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensionupdate_fuzzer/src/medialibrary_extension_update_fuzzer.cpp index 3f057db8d2e0dea0e1aa41a7ee18a1319c2f944e..de6e50c86c5f7189cffeeca7b5771db6d505953a 100644 --- a/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensionupdate_fuzzer/src/medialibrary_extension_update_fuzzer.cpp +++ b/frameworks/innerkitsimpl/test/fuzztest/medialibraryextensionupdate_fuzzer/src/medialibrary_extension_update_fuzzer.cpp @@ -110,7 +110,7 @@ static inline DataSharePredicates FuzzDataSharePredicates(const uint8_t *data, s return DataSharePredicates(FuzzVectorOperationItem(data, size)); } -static inline DataShareValuesBucket FuzzDataShareValuesBucket(const uint8_t *data, size_t size) +static inline DataShareValuesBucket FuzzDataShareValuesBucket() { return {}; } @@ -118,7 +118,7 @@ static inline DataShareValuesBucket FuzzDataShareValuesBucket(const uint8_t *dat static inline void UpdateFuzzer(MediaDataShareExtAbility &extension, const uint8_t* data, size_t size) { DataSharePredicates predicates; - extension.Update(FuzzUri(data, size), FuzzDataSharePredicates(data, size), FuzzDataShareValuesBucket(data, size)); + extension.Update(FuzzUri(data, size), FuzzDataSharePredicates(data, size), FuzzDataShareValuesBucket()); } static inline MediaDataShareExtAbility Init() diff --git a/frameworks/innerkitsimpl/test/fuzztest/medialibraryrestore_fuzzer/medialibraryrestore_fuzzer.cpp b/frameworks/innerkitsimpl/test/fuzztest/medialibraryrestore_fuzzer/medialibraryrestore_fuzzer.cpp index 66fd3b8db4d509cbb4c457b8dda3f4f22b160580..773268ef9a3787627466fdd23111b64f2516c370 100644 --- a/frameworks/innerkitsimpl/test/fuzztest/medialibraryrestore_fuzzer/medialibraryrestore_fuzzer.cpp +++ b/frameworks/innerkitsimpl/test/fuzztest/medialibraryrestore_fuzzer/medialibraryrestore_fuzzer.cpp @@ -113,7 +113,7 @@ const NativeRdb::RdbStoreConfig GetConfig() return config; } -static void MediaLibraryRestoreTest(const uint8_t *data, size_t size) +static void MediaLibraryRestoreTest() { auto config = GetConfig(); Media::FuzzRestoreDataCallback callBack; @@ -151,6 +151,6 @@ static void MediaLibraryRestoreTest(const uint8_t *data, size_t size) extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* Run your code on data */ - OHOS::MediaLibraryRestoreTest(data, size); + OHOS::MediaLibraryRestoreTest(); return 0; } \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/fuzztest/medialibraryutil_fuzzer/src/medialibrary_util_fuzzer.cpp b/frameworks/innerkitsimpl/test/fuzztest/medialibraryutil_fuzzer/src/medialibrary_util_fuzzer.cpp index 5c0736e7734f38b4f7e280afd238817c8f7e385b..d701021475546133295c3b750c01d073cd3c9709 100644 --- a/frameworks/innerkitsimpl/test/fuzztest/medialibraryutil_fuzzer/src/medialibrary_util_fuzzer.cpp +++ b/frameworks/innerkitsimpl/test/fuzztest/medialibraryutil_fuzzer/src/medialibrary_util_fuzzer.cpp @@ -172,7 +172,7 @@ static void AppPermissionTest(const uint8_t *data, size_t size) Media::MediaLibraryAppUriPermissionOperations::QueryOperation(sharedPred, columns); } -static void AppStateTest(const uint8_t *data, size_t size) +static void AppStateTest() { Media::MedialibraryAppStateObserverManager::GetInstance().SubscribeAppState(); Media::MedialibraryAppStateObserverManager::GetInstance().UnSubscribeAppState(); @@ -194,7 +194,7 @@ static void MultistageTest(const uint8_t *data, size_t size) Media::MultiStagesCaptureDfxFirstVisit::GetInstance().Report(FuzzString(data, size)); } -static void RefreshAlbumTest(const uint8_t *data, size_t size) +static void RefreshAlbumTest() { Media::RefreshAlbums(true); } @@ -230,10 +230,10 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) OHOS::UriPermissionTest(data, size); OHOS::AnalysisTest(data, size); OHOS::AppPermissionTest(data, size); - OHOS::AppStateTest(data, size); + OHOS::AppStateTest(); OHOS::MediaLibraryManagerTest(data, size); OHOS::MultistageTest(data, size); - OHOS::RefreshAlbumTest(data, size); + OHOS::RefreshAlbumTest(); OHOS::ActiveAnalysisTest(); OHOS::CloudDownloadTest(); return 0; diff --git a/frameworks/innerkitsimpl/test/unittest/media_permission_test/src/media_permission_test.cpp b/frameworks/innerkitsimpl/test/unittest/media_permission_test/src/media_permission_test.cpp index b97c481bf7452626f84b605b214ddcfe960ec75b..22d64c22abeac67cc0f9e92b0c8f9bab07cd1194 100644 --- a/frameworks/innerkitsimpl/test/unittest/media_permission_test/src/media_permission_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/media_permission_test/src/media_permission_test.cpp @@ -109,7 +109,7 @@ HWTEST_F(MediaPermissionTest, MediaPermissionTest_004, TestSize.Level0) }; permissionHandler_ = std::make_shared(); int err = permissionHandler_->CheckPermission(cmd, permParam); - EXPECT_LT(err, 0); + EXPECT_EQ(err, 0); MEDIA_INFO_LOG("MediaPermissionTest_004 end"); } diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/BUILD.gn b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/BUILD.gn index 414b0c0cf693b66110f5204e06bc015012f75c6d..0e58c5d6be612a6e9d344b00a566781f3c055cf1 100755 --- a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/BUILD.gn +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/BUILD.gn @@ -25,6 +25,7 @@ ohos_unittest("medialibrary_backup_test") { include_dirs = [ "./include", "./include/database", + "./include/report", "./include/restore", "./include/utils", "${MEDIALIB_CLOUD_SYNC_PATH}/include", @@ -70,6 +71,7 @@ ohos_unittest("medialibrary_backup_test") { "./src/external_source.cpp", "./src/gallery_source.cpp", "./src/medialibrary_backup_test.cpp", + "./src/report/upgrade_restore_gallery_media_task_test.cpp", "./src/restore/photo_album_dao_test.cpp", "./src/restore/photos_clone_test.cpp", "./src/restore/photos_restore_test.cpp", diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/report/upgrade_restore_gallery_media_task_test.h b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/report/upgrade_restore_gallery_media_task_test.h new file mode 100644 index 0000000000000000000000000000000000000000..2376574c1dc9dc1b84e218485db9f3dc70ee2f7c --- /dev/null +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/include/report/upgrade_restore_gallery_media_task_test.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 OHOS_MEDIA_BACKUP_UPGRADE_RESTORE_GALLERY_MEDIA_TASK_TEST_H +#define OHOS_MEDIA_BACKUP_UPGRADE_RESTORE_GALLERY_MEDIA_TASK_TEST_H + +#include + +#include "gtest/gtest.h" + +namespace OHOS::Media { +class UpgradeRestoreGalleryMediaTaskTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + +public: + const std::string SQL_JSON_TASK_INFO = "\ + { \ + \"resultInfo\": [ \ + { \ + \"errorCode\": \"13500099\", \ + \"errorInfo\": \"Move failed\", \ + \"type\": \"ErrorInfo\" \ + }, \ + { \ + \"infos\": [ \ + { \ + \"backupInfo\": \"photo\", \ + \"details\": [], \ + \"duplicateCount\": 0, \ + \"failedCount\": 0, \ + \"successCount\": 318 \ + }, \ + { \ + \"backupInfo\": \"video\", \ + \"details\": [], \ + \"duplicateCount\": 0, \ + \"failedCount\": 0, \ + \"successCount\": 29 \ + }, \ + { \ + \"backupInfo\": \"audio\", \ + \"details\": [], \ + \"duplicateCount\": 0, \ + \"failedCount\": 0, \ + \"successCount\": 0 \ + } \ + ], \ + \"type\": \"CountInfo\" \ + } \ + ] \ + }"; +}; +} // namespace OHOS::Media +#endif // OHOS_MEDIA_BACKUP_UPGRADE_RESTORE_GALLERY_MEDIA_TASK_TEST_H \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/report/upgrade_restore_gallery_media_task_test.cpp b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/report/upgrade_restore_gallery_media_task_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5761253183fea5fb7020bb2bc348381f1b9e780 --- /dev/null +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_backup_test/src/report/upgrade_restore_gallery_media_task_test.cpp @@ -0,0 +1,124 @@ +/* + * 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 MLOG_TAG "UpgradeRestoreGalleryMediaTaskTest" + +#include + +#define private public +#define protected public +#include "upgrade_restore_gallery_media_task.h" +#undef private +#undef protected + +#include "upgrade_restore_gallery_media_task_test.h" +#include "media_log.h" + +using namespace testing::ext; + +namespace OHOS::Media { +void UpgradeRestoreGalleryMediaTaskTest::SetUpTestCase(void) +{ + MEDIA_INFO_LOG("SetUpTestCase"); +} + +void UpgradeRestoreGalleryMediaTaskTest::TearDownTestCase(void) +{ + MEDIA_INFO_LOG("TearDownTestCase"); +} + +void UpgradeRestoreGalleryMediaTaskTest::SetUp() +{ + MEDIA_INFO_LOG("SetUp"); +} + +void UpgradeRestoreGalleryMediaTaskTest::TearDown(void) +{ + MEDIA_INFO_LOG("TearDown"); +} + +HWTEST_F(UpgradeRestoreGalleryMediaTaskTest, CallbackResultData_Check, TestSize.Level0) +{ + UpgradeRestoreGalleryMediaTask task; + CallbackResultData resultData = task.ParseFromJsonStr(this->SQL_JSON_TASK_INFO); + CallbackResultInfo &resultInfo = resultData.resultInfo; + // ASSERT CallbackResultInfo + EXPECT_EQ(resultInfo.errorCode, "13500099"); + EXPECT_EQ(resultInfo.errorInfo, "Move failed"); + EXPECT_EQ(resultInfo.type, "ErrorInfo"); + // ASSERT CallbackBackupInfo + EXPECT_EQ(resultData.infos.size(), 3); + // ASSERT CallbackBackupInfo - Photo + CallbackBackupInfo photoInfo = resultData.infos[0]; + EXPECT_EQ(photoInfo.backupInfo, "photo"); + EXPECT_EQ(photoInfo.duplicateCount, 0); + EXPECT_EQ(photoInfo.failedCount, 0); + EXPECT_EQ(photoInfo.successCount, 318); + // ASSERT CallbackBackupInfo - Video + CallbackBackupInfo videoInfo = resultData.infos[1]; + EXPECT_EQ(videoInfo.backupInfo, "video"); + EXPECT_EQ(videoInfo.duplicateCount, 0); + EXPECT_EQ(videoInfo.failedCount, 0); + EXPECT_EQ(videoInfo.successCount, 29); + // ASSERT CallbackBackupInfo - Audio + CallbackBackupInfo audioInfo = resultData.infos[2]; + EXPECT_EQ(audioInfo.backupInfo, "audio"); + EXPECT_EQ(audioInfo.duplicateCount, 0); + EXPECT_EQ(audioInfo.failedCount, 0); + EXPECT_EQ(audioInfo.successCount, 0); +} + +HWTEST_F(UpgradeRestoreGalleryMediaTaskTest, MediaRestoreResultInfo_Check, TestSize.Level0) +{ + UpgradeRestoreGalleryMediaTask task; + CallbackResultData resultData = task.SetSceneCode(0).SetTaskId("abc").ParseFromJsonStr(this->SQL_JSON_TASK_INFO); + std::vector resultInfo = task.Parse(resultData); + // ASSERT MediaRestoreResultInfo + EXPECT_EQ(resultInfo.size(), 3); + // ASSERT MediaRestoreResultInfo - Photo + MediaRestoreResultInfo photoInfo = resultInfo[0]; + EXPECT_EQ(photoInfo.sceneCode, 0); + EXPECT_EQ(photoInfo.taskId, "abc"); + EXPECT_EQ(photoInfo.errorCode, "13500099"); + EXPECT_EQ(photoInfo.errorInfo, "Move failed"); + EXPECT_EQ(photoInfo.type, "ErrorInfo"); + EXPECT_EQ(photoInfo.backupInfo, "photo"); + EXPECT_EQ(photoInfo.duplicateCount, 0); + EXPECT_EQ(photoInfo.failedCount, 0); + EXPECT_EQ(photoInfo.successCount, 318); + // ASSERT MediaRestoreResultInfo - Video + MediaRestoreResultInfo videoInfo = resultInfo[1]; + EXPECT_EQ(videoInfo.sceneCode, 0); + EXPECT_EQ(videoInfo.taskId, "abc"); + EXPECT_EQ(videoInfo.errorCode, "13500099"); + EXPECT_EQ(videoInfo.errorInfo, "Move failed"); + EXPECT_EQ(videoInfo.type, "ErrorInfo"); + EXPECT_EQ(videoInfo.backupInfo, "video"); + EXPECT_EQ(videoInfo.duplicateCount, 0); + EXPECT_EQ(videoInfo.failedCount, 0); + EXPECT_EQ(videoInfo.successCount, 29); + // ASSERT MediaRestoreResultInfo - Audio + MediaRestoreResultInfo audioInfo = resultInfo[2]; + EXPECT_EQ(audioInfo.sceneCode, 0); + EXPECT_EQ(audioInfo.taskId, "abc"); + EXPECT_EQ(audioInfo.errorCode, "13500099"); + EXPECT_EQ(audioInfo.errorInfo, "Move failed"); + EXPECT_EQ(audioInfo.type, "ErrorInfo"); + EXPECT_EQ(audioInfo.backupInfo, "audio"); + EXPECT_EQ(audioInfo.duplicateCount, 0); + EXPECT_EQ(audioInfo.failedCount, 0); + EXPECT_EQ(audioInfo.successCount, 0); +} +} // namespace OHOS::Media \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/BUILD.gn b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/BUILD.gn index a2d86d71f2a421e8a17103c5cf5472de625c490a..60b98c1ee2168fd691ca6f3d34937b6895f886ec 100644 --- a/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/BUILD.gn +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/BUILD.gn @@ -44,6 +44,7 @@ if (defined(medialibrary_mtp_enable)) { "src/medialibrary_mtp_unit_test.cpp", "src/mock_mtp_driver.cpp", "src/mtp_media_library_unit_test.cpp", + "src/mtp_operation_utils_unit_test.cpp", "src/mtp_payload_data_test.cpp", "src/mtp_set_object_prop_test.cpp", "src/mtp_test.cpp", diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/include/mtp_operation_utils_unit_test.h b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/include/mtp_operation_utils_unit_test.h new file mode 100644 index 0000000000000000000000000000000000000000..d0cad179170451737cb92e80948f703e3cf30976 --- /dev/null +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/include/mtp_operation_utils_unit_test.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 FRAMEWORKS_INNERKITSIMPL_TEST_UNITTEST_MEDIALIBRARY_TEST_INCLUDE_MTP_OPERATION_UTILS_UNIT_TEST_H_ +#define FRAMEWORKS_INNERKITSIMPL_TEST_UNITTEST_MEDIALIBRARY_TEST_INCLUDE_MTP_OPERATION_UTILS_UNIT_TEST_H_ + +#include "gtest/gtest.h" + +namespace OHOS { +namespace Media { +class MtpOperationUtilsUnitTest : public testing::Test { +public: + /* SetUpTestCase:The preset action of the test suite is executed before the first TestCase */ + static void SetUpTestCase(void); + + /* TearDownTestCase:The test suite cleanup action is executed after the last TestCase */ + static void TearDownTestCase(void); + + /* SetUp:Execute before each test case */ + void SetUp(); + + /* TearDown:Execute after each test case */ + void TearDown(); +}; +} // namespace Media +} // namespace OHOS +#endif // FRAMEWORKS_INNERKITSIMPL_TEST_UNITTEST_MEDIALIBRARY_TEST_INCLUDE_MTP_OPERATION_UTILS_UNIT_TEST_H_ \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/medialibrary_mtp_unit_test.cpp b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/medialibrary_mtp_unit_test.cpp index 762044cd86d7ffaf32dafb5a7d0616cf0d5754e5..33a0ef1eb88188384d5f93dd9d7ec5ac91b5a9e0 100644 --- a/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/medialibrary_mtp_unit_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/medialibrary_mtp_unit_test.cpp @@ -237,7 +237,7 @@ HWTEST_F(MediaLibraryMTPUnitTest, medialibrary_MTP_message_testlevel0_005, TestS for (auto && i : output) { MEDIA_DEBUG_LOG("i: %{public}d", i); } - std::vector targetData = { 12, 0, 0, 0, 3, 0, 9, 32, 35, 0, 0, 0 }; + std::vector targetData = { 12, 0, 0, 0, 3, 0, 19, 32, 35, 0, 0, 0 }; MEDIA_DEBUG_LOG("MtpDriver::output.size: %{public}d", output.size()); EXPECT_EQ(output, targetData); @@ -499,6 +499,45 @@ HWTEST_F(MediaLibraryMTPUnitTest, medialibrary_MTP_message_testlevel0_011, TestS EXPECT_EQ(output, targetData); } +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: MTP_OPERATION_SEND_OBJECT_INFO_CODE + */ +HWTEST_F(MediaLibraryMTPUnitTest, medialibrary_MTP_message_testlevel0_012, TestSize.Level0) +{ + std::shared_ptr mtpTest = OHOS::Media::MtpTest::GetInstance(); + std::shared_ptr operationPtr_; + if (operationPtr_ == nullptr) { + operationPtr_ = make_shared(); + } + + // set test data + mtpTest->setOutBuffer(testData_open); + // execute + operationPtr_->Execute(); + + // MTP_OPERATION_SEND_OBJECT_INFO_CODE + static std::vector testData = { 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0c, 0x10, 0xac, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x01, 0x00, 0x07, 0x00, 0x00, 0x00 }; + mtpTest->setOutBuffer(testData); + operationPtr_->Execute(); + + // get output + std::vector output; + mtpTest->getOutBuffer(output); + for (auto && i : output) { + MEDIA_DEBUG_LOG("i: %{public}d", i); + } + std::vector targetData = { 12, 0, 0, 0, 3, 0, 9, 32, 172, 0, 0, 0 }; + + MEDIA_DEBUG_LOG("MtpDriver::output.size: %{public}d", output.size()); + EXPECT_EQ(output, targetData); +} + /* * Feature: MediaLibraryMTP * Function: @@ -1629,7 +1668,7 @@ HWTEST_F(MediaLibraryMTPUnitTest, medialibrary_MTP_message_testlevel0_043, TestS for (auto && i : output) { MEDIA_DEBUG_LOG("i: %{public}d", i); } - std::vector targetData = { 12, 0, 0, 0, 3, 0, 9, 32, 200, 0, 0, 0 }; + std::vector targetData = { 12, 0, 0, 0, 3, 0, 1, 32, 200, 0, 0, 0 }; MEDIA_DEBUG_LOG("MtpDriver::output.size: %{public}d", output.size()); EXPECT_EQ(output, targetData); @@ -1915,7 +1954,7 @@ HWTEST_F(MediaLibraryMTPUnitTest, medialibrary_MTP_message_testlevel0_050, TestS for (auto && i : output) { MEDIA_DEBUG_LOG("i: %{public}d", i); } - std::vector targetData = { 12, 0, 0, 0, 3, 0, 19, 32, 188, 0, 0, 0 }; + std::vector targetData = { 12, 0, 0, 0, 3, 0, 9, 32, 188, 0, 0, 0 }; MEDIA_DEBUG_LOG("MtpDriver::output.size: %{public}d", output.size()); EXPECT_EQ(output, targetData); @@ -2249,7 +2288,7 @@ HWTEST_F(MediaLibraryMTPUnitTest, medialibrary_MTP_message_testlevel0_059, TestS for (auto && i : output) { MEDIA_DEBUG_LOG("i: %{public}d", i); } - std::vector targetData = { 16, 0, 0, 0, 3, 0, 19, 32, 183, 0, 0, 0, 0, 0, 0, 0 }; + std::vector targetData = { 16, 0, 0, 0, 3, 0, 9, 32, 183, 0, 0, 0, 0, 0, 0, 0 }; MEDIA_DEBUG_LOG("MtpDriver::output.size: %{public}d", output.size()); EXPECT_EQ(output, targetData); diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/mtp_media_library_unit_test.cpp b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/mtp_media_library_unit_test.cpp index abecf99f32897ab017d0e66e51849a8f2f5445be..8f1cbaedd1108242cc28010d8fdae5578939e5fa 100644 --- a/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/mtp_media_library_unit_test.cpp +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/mtp_media_library_unit_test.cpp @@ -20,6 +20,7 @@ #include "media_log.h" #include "mtp_storage_manager.h" #include "object_info.h" +#include "mtp_constants.h" using namespace std; using namespace testing::ext; @@ -59,7 +60,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_001, TestSi } mtpMediaLib_->Clear(); - EXPECT_EQ(mtpMediaLib_->id_, 130); + EXPECT_EQ(mtpMediaLib_->id_, 1); } /* @@ -73,6 +74,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_001, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_002, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); //parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); //file path @@ -98,6 +100,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_002, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_003, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); //parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); @@ -126,6 +129,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_003, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_004, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); @@ -148,6 +152,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_004, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_007, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); context->storageID = 2; context->parent = 0; @@ -159,7 +164,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_007, TestSi uint32_t outParent = 0; uint32_t outHandle = 0; mtpMediaLib_->SendObjectInfo(context, outStorageID, outParent, outHandle); - EXPECT_EQ(outStorageID, 0); + EXPECT_NE(outStorageID, context->storageID); } /* @@ -173,6 +178,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_007, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_008, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -193,6 +199,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_008, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_009, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); context->handle = 1; for (int i = 1; i <= 10; i++) { @@ -200,8 +207,8 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_009, TestSi } uint32_t repeatHandle = 0; - mtpMediaLib_->MoveObject(context, repeatHandle); - EXPECT_EQ(repeatHandle, 0); + int32_t errcode = mtpMediaLib_->MoveObject(context, repeatHandle); + EXPECT_NE(errcode, 0); } /* @@ -215,6 +222,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_009, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_010, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); context->handle = 1; for (int i = 1; i <= 10; i++) { @@ -223,8 +231,8 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_010, TestSi uint32_t outObjectHandle = 0; uint32_t oldHandle = 0; - mtpMediaLib_->CopyObject(context, outObjectHandle, oldHandle); - EXPECT_EQ(outObjectHandle, 0); + int32_t errcode = mtpMediaLib_->CopyObject(context, outObjectHandle, oldHandle); + EXPECT_NE(errcode, 0); } /* @@ -238,6 +246,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_010, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_011, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); context->handle = 1; for (int i = 1; i <= 10; i++) { @@ -260,6 +269,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_011, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_012, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); context->handle = 1; for (int i = 1; i <= 10; i++) { @@ -282,6 +292,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_012, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_013, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); context->property = 1; context->depth = MTP_ALL_DEPTH; @@ -307,6 +318,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_013, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_014, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); std::shared_ptr> outProps = std::make_shared>(); context->property = 1; @@ -332,6 +344,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_014, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_015, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); uint64_t outIntVal = 0; uint128_t outLongVal = { 0 }; @@ -357,9 +370,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_015, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_016, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::string outPath = ""; - mtpMediaLib_->GetRealPath(FILE_PATH, outPath); - EXPECT_NE(outPath, ""); + int32_t errcode = mtpMediaLib_->GetRealPath(FILE_PATH, outPath); + EXPECT_NE(errcode, E_ERR); } /* @@ -373,6 +387,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_016, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_017, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); int errcode = -1; errcode = mtpMediaLib_->GetStorageIds(); EXPECT_EQ(errcode, MTP_SUCCESS); @@ -389,6 +404,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_017, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_018, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -411,6 +427,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_018, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_019, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -432,6 +449,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_019, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_020, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); uint32_t id = 1; mtpMediaLib_->AddToHandlePathMap(FILE_PATH, id); uint32_t outId = 0; @@ -450,6 +468,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_020, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_021, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -471,6 +490,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_021, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_022, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -493,6 +513,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_022, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_023, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::string str = "ab"; std::string prefix = "ab"; bool ret = false; @@ -511,6 +532,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_023, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_024, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -532,9 +554,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_024, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_025, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); uint32_t id = 0; id = mtpMediaLib_->GetId(); - EXPECT_EQ(id, 141); + EXPECT_EQ(id, 1); } /* @@ -548,9 +571,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_025, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_026, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); uint32_t parentId = 1; parentId = mtpMediaLib_->GetParentId(FILE_PATH + "/1.txt"); - EXPECT_EQ(parentId, 1); + EXPECT_EQ(parentId, 0); } /* @@ -564,12 +588,12 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_026, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_027, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for(int i = 1; i <= 10; i++) { mtpMediaLib_->AddPathToMap(FILE_PATH + std::to_string(i) + ".txt"); } - mtpMediaLib_->Clear(); - EXPECT_EQ(mtpMediaLib_->id_, 130); + EXPECT_EQ(mtpMediaLib_->id_, 11); } /* @@ -583,6 +607,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_027, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_028, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); //parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); //file path @@ -608,6 +633,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_028, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_029, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); //parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); @@ -636,6 +662,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_029, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_031, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); //parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); //file path @@ -661,6 +688,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_031, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_032, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); //parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); //file path @@ -685,6 +713,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_032, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_033, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::string str = FILE_PATH; std::string prefix = FILE_PATH; //storage file path @@ -696,12 +725,12 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_033, TestSi mtpMediaLib_->ObserverAddPathToMap(FILE_PATH + std::to_string(i) + ".txt"); } - std::string form = FILE_PATH + std::to_string(1) + ".txt"; + std::string from = FILE_PATH + std::to_string(1) + ".txt"; std::string to = STORAGE_FILE; - mtpMediaLib_->MoveHandlePathMap(form, to); + mtpMediaLib_->MoveHandlePathMap(from, to); uint32_t handle = 0; - mtpMediaLib_->GetIdByPath(STORAGE_FILE + std::to_string(1) + ".txt", handle); - EXPECT_GT(handle, 0); + int32_t errcode = mtpMediaLib_->GetIdByPath(STORAGE_FILE + std::to_string(1) + ".txt", handle); + EXPECT_EQ(errcode, E_NO_SUCH_FILE); } /* @@ -715,6 +744,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_033, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_034, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::string str = FILE_PATH; //parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); @@ -736,13 +766,14 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_034, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_035, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::string str = FILE_PATH; //parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); mtpMediaLib_->ObserverDeletePathToMap(FILE_PATH); uint32_t handle = 0; - mtpMediaLib_->GetIdByPath(FILE_PATH, handle); - EXPECT_EQ(handle, 0); + int32_t errcode = mtpMediaLib_->GetIdByPath(FILE_PATH, handle); + EXPECT_EQ(errcode, E_NO_SUCH_FILE); } /* @@ -756,6 +787,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_035, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_036, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); const off_t size = 10; off_t result = mtpMediaLib_->GetSizeFromOfft(size); EXPECT_EQ(result, 10); @@ -772,6 +804,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_036, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_037, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); //storage file path mtpMediaLib_->ObserverAddPathToMap(STORAGE_FILE); @@ -796,6 +829,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_037, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_038, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); std::string outPath = ""; mtpMediaLib_->GetRealPath(FILE_PATH, outPath); @@ -814,6 +848,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_038, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_039, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); //storage file path mtpMediaLib_->ObserverAddPathToMap(STORAGE_FILE); @@ -839,6 +874,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_039, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_040, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); //storage file path mtpMediaLib_->ObserverAddPathToMap(STORAGE_FILE); @@ -868,6 +904,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_040, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_041, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); //storage file path mtpMediaLib_->ObserverAddPathToMap(STORAGE_FILE); @@ -893,6 +930,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_041, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_042, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::string str = FILE_PATH; std::string prefix = FILE_PATH; bool result = mtpMediaLib_->StartsWith(str, prefix); @@ -910,10 +948,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_042, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_045, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); OHOS::Media::PixelMap pixelMap; std::vector data; - bool res = false; - res = mtpMediaLib_->CompressImage(pixelMap, data); + bool res = mtpMediaLib_->CompressImage(pixelMap, data); EXPECT_FALSE(res); } @@ -928,6 +966,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_045, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_046, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -951,6 +990,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_046, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_047, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); std::shared_ptr outThumb = std::make_shared(); context->handle = 2; @@ -974,6 +1014,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_047, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_048, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); uint32_t handle = 0; mtpMediaLib_->GetIdByPath(FILE_PATH, handle); @@ -996,6 +1037,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_048, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_049, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); std::shared_ptr outThumb = std::make_shared(); context->handle = 2; @@ -1018,6 +1060,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_049, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_050, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); std::shared_ptr outThumb = std::make_shared(); context->handle = 2; @@ -1040,6 +1083,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_050, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_051, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr> out = std::make_shared>(); uint32_t errcode = 1; @@ -1058,6 +1102,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_051, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_052, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -1081,6 +1126,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_052, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_053, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::shared_ptr> out = std::make_shared>(); uint32_t errcode = 1; @@ -1099,6 +1145,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_053, TestSi HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_055, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } @@ -1118,9 +1165,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_055, TestSi * EnvConditions: NA * CaseDescription: GetExternalStorages */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_056, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_056, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::string path = FILE_PATH; mtpMediaLib_->GetExternalStorages(); @@ -1136,9 +1184,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_056, TestS * EnvConditions: NA * CaseDescription: MoveRepeatDirHandlePathMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_057, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_057, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); // storage file path mtpMediaLib_->ObserverAddPathToMap(STORAGE_FILE); // parent file path @@ -1162,9 +1211,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_057, TestS * EnvConditions: NA * CaseDescription: MoveObjectSub */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_058, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_058, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); // storage file path mtpMediaLib_->ObserverAddPathToMap(STORAGE_FILE); // parent file path @@ -1185,9 +1235,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_058, TestS * EnvConditions: NA * CaseDescription: ScanDirWithType */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_059, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_059, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); std::string root = FILE_PATH; std::shared_ptr> outMap; mtpMediaLib_->ScanDirWithType(root, outMap); @@ -1203,9 +1254,10 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_059, TestS * EnvConditions: NA * CaseDescription: ErasePathInfo */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_060, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_060, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); + mtpMediaLib_->Clear(); // parent file path mtpMediaLib_->ObserverAddPathToMap(FILE_PATH); uint32_t handle = 0; @@ -1225,7 +1277,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_060, TestS * EnvConditions: NA * CaseDescription: GetParentId */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_061, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_061, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1246,7 +1298,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_061, TestS * EnvConditions: NA * CaseDescription: GetParentId */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_062, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_062, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1268,7 +1320,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_062, TestS * EnvConditions: NA * CaseDescription: ModifyHandlePathMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_063, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_063, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1292,7 +1344,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_063, TestS * EnvConditions: NA * CaseDescription: ModifyPathHandleMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_064, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_064, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1316,7 +1368,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_064, TestS * EnvConditions: NA * CaseDescription: ScanDirNoDepth */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_065, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_065, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1336,7 +1388,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_065, TestS * EnvConditions: NA * CaseDescription: ScanDirNoDepth */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_066, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_066, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1356,7 +1408,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_066, TestS * EnvConditions: NA * CaseDescription: StartsWith */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_067, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_067, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1375,7 +1427,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_067, TestS * EnvConditions: NA * CaseDescription: StartsWith */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_068, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_068, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1394,7 +1446,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_068, TestS * EnvConditions: NA * CaseDescription: StartsWith */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_069, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_069, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1413,7 +1465,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_069, TestS * EnvConditions: NA * CaseDescription: StartsWith */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_070, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_070, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1432,7 +1484,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_070, TestS * EnvConditions: NA * CaseDescription: DeleteHandlePathMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_071, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_071, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1456,7 +1508,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_071, TestS * EnvConditions: NA * CaseDescription: DeleteHandlePathMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_072, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_072, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1480,7 +1532,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_072, TestS * EnvConditions: NA * CaseDescription: ObserverAddPathToMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_073, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_073, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1490,7 +1542,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_073, TestS std::string path = FILE_PATH + "/11.txt"; uint32_t id = mtpMediaLib_->ObserverAddPathToMap(path); - EXPECT_EQ(id, 130); + EXPECT_EQ(id, 1); } /* @@ -1501,7 +1553,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_073, TestS * EnvConditions: NA * CaseDescription: ObserverAddPathToMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_074, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_074, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1522,7 +1574,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_074, TestS * EnvConditions: NA * CaseDescription: ObserverDeletePathToMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_075, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_075, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1542,7 +1594,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_075, TestS * EnvConditions: NA * CaseDescription: MoveHandlePathMap */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_076, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_076, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1566,7 +1618,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_076, TestS * EnvConditions: NA * CaseDescription: Branch */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_077, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_077, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1588,7 +1640,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_077, TestS * EnvConditions: NA * CaseDescription: Branch */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_078, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_078, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1608,7 +1660,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_078, TestS * EnvConditions: NA * CaseDescription: Branch */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_079, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_079, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1629,7 +1681,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_079, TestS * EnvConditions: NA * CaseDescription: Branch */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_080, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_080, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -1650,7 +1702,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_080, TestS * EnvConditions: NA * CaseDescription: Branch */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_081, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_081, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -2034,7 +2086,7 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_095, TestSi * EnvConditions: NA * CaseDescription: ScanDirNoDepth */ -HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel0_096, TestSize.Level0) +HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_096, TestSize.Level0) { ASSERT_NE(mtpMediaLib_, nullptr); mtpMediaLib_->Clear(); @@ -2199,14 +2251,14 @@ HWTEST_F(MtpMediaLibraryUnitTest, medialibrary_MTP_message_testlevel_103, TestSi mtpMediaLib_->Clear(); std::shared_ptr context = std::make_shared(); std::shared_ptr outHandles = std::make_shared(); - context->parent = 0xFFFFFFFF; + context->parent = MTP_ALL_HANDLE_ID; context->storageID = 1; for (int i = 1; i <= 10; i++) { mtpMediaLib_->AddToHandlePathMap(FILE_PATH + "/" + std::to_string(i) + ".txt", i); } - mtpMediaLib_->GetHandles(context, outHandles); - EXPECT_EQ(context->parent, 1); + int32_t res = mtpMediaLib_->GetHandles(context, outHandles); + EXPECT_EQ(res, MTP_ERROR_STORE_NOT_AVAILABLE); } -}// namespace Media -}// namespace OHOS \ No newline at end of file +} // namespace Media +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/mtp_operation_utils_unit_test.cpp b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/mtp_operation_utils_unit_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..738e83b76c91acdf44c758850ba3423d3866bf0f --- /dev/null +++ b/frameworks/innerkitsimpl/test/unittest/medialibrary_mtp_test/src/mtp_operation_utils_unit_test.cpp @@ -0,0 +1,559 @@ +/* + * 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 "mtp_operation_utils_unit_test.h" +#include "mtp_operation_utils.h" +#include "medialibrary_errno.h" +#include "payload_data.h" +#include "mtp_constants.h" +#include "media_mtp_utils.h" +#include "mtp_manager.h" +#include "mtp_driver.h" + +using namespace std; +using namespace testing::ext; + +namespace OHOS { +namespace Media { + +void MtpOperationUtilsUnitTest::SetUpTestCase(void) {} +void MtpOperationUtilsUnitTest::TearDownTestCase(void) {} +void MtpOperationUtilsUnitTest::SetUp() {} +void MtpOperationUtilsUnitTest::TearDown(void) {} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetNumObjects + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_001, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t res = mtpOperationUtils->GetNumObjects(data); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetNumObjects + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_002, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->storageID = MTP_STORAGE_ID_ALL; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t res = mtpOperationUtils->GetNumObjects(data); + EXPECT_EQ(res, MTP_INVALID_STORAGEID_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: HasStorage + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_003, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + int errcode = 0; + mtpOperationUtils->HasStorage(errcode); + EXPECT_EQ(errcode, MTP_ERROR_CONTEXT_IS_NULL); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: HasStorage + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_004, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->sessionOpen = false; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + int errcode = 0; + mtpOperationUtils->HasStorage(errcode); + EXPECT_EQ(errcode, MTP_ERROR_SESSION_NOT_OPEN); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: HasStorage + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_005, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->sessionOpen = true; + context->storageID = MTP_STORAGE_ID_ALL; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + int errcode = 0; + mtpOperationUtils->HasStorage(errcode); + EXPECT_EQ(errcode, MTP_ERROR_INVALID_STORAGE_ID); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetObjectPropDesc + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_006, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + int errcode = 0; + uint16_t containerType = DATA_CONTAINER_TYPE; + uint16_t res = mtpOperationUtils->GetObjectPropDesc(data, containerType, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetObjectPropValue + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_007, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + int errcode = 0; + uint16_t containerType = DATA_CONTAINER_TYPE; + uint16_t res = mtpOperationUtils->GetObjectPropValue(data, containerType, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: DoSetObjectPropValue + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_008, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + int errcode = 0; + mtpOperationUtils->DoSetObjectPropValue(errcode); + EXPECT_EQ(errcode, MTP_ERROR_CONTEXT_IS_NULL); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: DoSetObjectPropValue + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_009, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + OHOS::Media::MtpManager::GetInstance().mtpMode_ = OHOS::Media::MtpManager::MtpMode::MTP_MODE; + int errcode = 0; + mtpOperationUtils->DoSetObjectPropValue(errcode); + EXPECT_EQ(errcode, MTP_ERROR_INVALID_OBJECTPROP_VALUE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetObjectPropList + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_010, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + int errcode = 0; + uint16_t containerType = DATA_CONTAINER_TYPE; + uint16_t res = mtpOperationUtils->GetObjectPropList(data, containerType, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: SetObjectReferences + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_011, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t res = mtpOperationUtils->SetObjectReferences(data); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: RecevieSendObject + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_012, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + MtpFileRange object; + int fd = 1; + int32_t errcode = mtpOperationUtils->RecevieSendObject(object, fd); + EXPECT_EQ(errcode, MTP_INVALID_PARAMETER_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: RecevieSendObject + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_013, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->mtpDriver = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + MtpFileRange object; + int fd = 1; + int32_t errcode = mtpOperationUtils->RecevieSendObject(object, fd); + EXPECT_EQ(errcode, MTP_INVALID_PARAMETER_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: RecevieSendObject PreDealFd + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_014, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->mtpDriver = std::make_shared(); + ASSERT_NE(context->mtpDriver, nullptr); + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + MtpFileRange object; + int fd = 1; + int32_t errcode = mtpOperationUtils->RecevieSendObject(object, fd); + bool deal = false; + mtpOperationUtils->PreDealFd(deal, fd); + EXPECT_EQ(errcode, 0); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: PreDealFd + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_015, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->mtpDriver = std::make_shared(); + ASSERT_NE(context->mtpDriver, nullptr); + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + MtpFileRange object; + int fd = 0; + int32_t errcode = mtpOperationUtils->RecevieSendObject(object, fd); + bool deal = true; + mtpOperationUtils->PreDealFd(deal, fd); + EXPECT_EQ(errcode, 0); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: PreDealFd + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_016, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->mtpDriver = std::make_shared(); + ASSERT_NE(context->mtpDriver, nullptr); + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + MtpFileRange object; + int fd = 1; + int32_t errcode = mtpOperationUtils->RecevieSendObject(object, fd); + bool deal = true; + mtpOperationUtils->PreDealFd(deal, fd); + EXPECT_EQ(errcode, 0); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: SendObjectInfo + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_017, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + int32_t errcode = 0; + uint16_t res = mtpOperationUtils->SendObjectInfo(data, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetPartialObject + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_018, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t res = mtpOperationUtils->GetPartialObject(data); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetObjectPropsSupported + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_019, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t res = mtpOperationUtils->GetObjectPropsSupported(data); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: DeleteObject + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_020, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + int errcode = 0; + uint16_t res = mtpOperationUtils->DeleteObject(data, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: MoveObject + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_021, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + int errcode = 0; + uint16_t res = mtpOperationUtils->MoveObject(data, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: CopyObject + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_022, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + int errcode = 0; + uint16_t res = mtpOperationUtils->CopyObject(data, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetStorageIDs + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_023, TestSize.Level0) +{ + std::shared_ptr context = nullptr; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t containerType = DATA_CONTAINER_TYPE; + int errcode = 0; + uint16_t res = mtpOperationUtils->GetStorageIDs(data, containerType, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetStorageIDs + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_024, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->sessionOpen = false; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t containerType = DATA_CONTAINER_TYPE; + int errcode = 0; + uint16_t res = mtpOperationUtils->GetStorageIDs(data, containerType, errcode); + EXPECT_EQ(res, MTP_SESSION_NOT_OPEN_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetStorageIDs + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_025, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->sessionOpen = true; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t containerType = DATA_CONTAINER_TYPE; + int errcode = 0; + uint16_t res = mtpOperationUtils->GetStorageIDs(data, containerType, errcode); + EXPECT_EQ(res, MTP_OK_CODE); +} + +/* + * Feature: MediaLibraryMTP + * Function: + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: GetStorageInfo + */ +HWTEST_F(MtpOperationUtilsUnitTest, medialibrary_MTP_message_testlevel_0_026, TestSize.Level0) +{ + std::shared_ptr context = std::make_shared(); + ASSERT_NE(context, nullptr); + context->sessionOpen = false; + std::shared_ptr mtpOperationUtils = std::make_shared(context); + ASSERT_NE(mtpOperationUtils, nullptr); + std::shared_ptr data = nullptr; + uint16_t containerType = DATA_CONTAINER_TYPE; + int errcode = 0; + uint16_t res = mtpOperationUtils->GetStorageInfo(data, containerType, errcode); + EXPECT_EQ(res, MTP_SESSION_NOT_OPEN_CODE); +} +} // namespace Media +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/c_api/media_asset_change_request_impl.cpp b/frameworks/native/c_api/media_asset_change_request_impl.cpp index 47243d0057a85363c5cec3f10afc4c093caf2c71..9550104048de01d275be513d88da042ad291f44c 100644 --- a/frameworks/native/c_api/media_asset_change_request_impl.cpp +++ b/frameworks/native/c_api/media_asset_change_request_impl.cpp @@ -336,10 +336,15 @@ bool MediaAssetChangeRequestImpl::SaveCameraPhotoExecute() { bool containsAddResource = find(assetChangeOperations_.begin(), assetChangeOperations_.end(), AssetChangeOperation::ADD_RESOURCE) != assetChangeOperations_.end(); + std::string uriStr = PAH_SAVE_CAMERA_PHOTO; if (containsAddResource && !PermissionUtils::IsSystemApp()) { // remove high quality photo MEDIA_INFO_LOG("discard high quality photo because add resource by third app"); DiscardHighQualityPhoto(); + + // set dirty flag when third-party hap calling addResource to save camera photo + MediaFileUtils::UriAppendKeyValue(uriStr, PhotoColumn::PHOTO_DIRTY, + to_string(static_cast(DirtyType::TYPE_NEW))); } // The watermark will trigger the scan. If the watermark is turned on, there is no need to trigger the scan again. @@ -349,7 +354,6 @@ bool MediaAssetChangeRequestImpl::SaveCameraPhotoExecute() auto fileAsset = mediaAsset_->GetFileAssetInstance(); CHECK_AND_RETURN_RET_LOG(fileAsset != nullptr, false, "fileAsset is nullptr"); - std::string uriStr = PAH_SAVE_CAMERA_PHOTO; MediaFileUtils::UriAppendKeyValue(uriStr, API_VERSION, to_string(MEDIA_API_VERSION_V10)); MediaFileUtils::UriAppendKeyValue(uriStr, MEDIA_OPERN_KEYWORD, to_string(needScan)); MediaFileUtils::UriAppendKeyValue(uriStr, PhotoColumn::MEDIA_FILE_PATH, fileAsset->GetUri()); diff --git a/frameworks/services/media_async_worker/BUILD.gn b/frameworks/services/media_async_worker/BUILD.gn index 93f1ce518fcd227132a11f590edd2aeaf9ee1051..a03e14a78e77ddb3eb2875bc0e25884361d382d7 100644 --- a/frameworks/services/media_async_worker/BUILD.gn +++ b/frameworks/services/media_async_worker/BUILD.gn @@ -15,9 +15,14 @@ import("//build/ohos.gni") import("//foundation/multimedia/media_library/media_library.gni") ohos_static_library("medialibrary_async_worker") { - sources = [ "src/medialibrary_async_worker.cpp" ] + sources = [ + "src/medialibrary_async_worker.cpp", + "src/medialibrary_period_worker.cpp", + ] include_dirs = [ "${MEDIALIB_SERVICES_PATH}/media_async_worker/include", + "${MEDIALIB_SERVICES_PATH}/media_cloud_sync_notify_handle/include", + "${MEDIALIB_SERVICES_PATH}/media_power_efficiency/include", "${MEDIALIB_INTERFACES_PATH}/inner_api/media_library_helper/include", "${MEDIALIB_UTILS_PATH}/include", ] @@ -25,6 +30,8 @@ ohos_static_library("medialibrary_async_worker") { deps = [ "${MEDIALIB_INNERKITS_PATH}/media_library_helper:media_library" ] external_deps = [ + "data_share:datashare_common", + "data_share:datashare_consumer", "hilog:libhilog", "hitrace:hitrace_meter", ] diff --git a/frameworks/services/media_async_worker/include/medialibrary_period_worker.h b/frameworks/services/media_async_worker/include/medialibrary_period_worker.h new file mode 100644 index 0000000000000000000000000000000000000000..6906805833edb477496a16b412f8ad5a706698c8 --- /dev/null +++ b/frameworks/services/media_async_worker/include/medialibrary_period_worker.h @@ -0,0 +1,83 @@ +/* + * 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 FRAMEWORKS_SERVICE_MEDIA_PERIOD_WORKER_INCLUDE_MEDIALIBRARY_ASYNC_WORKER_H_ +#define FRAMEWORKS_SERVICE_MEDIA_PERIOD_WORKER_INCLUDE_MEDIALIBRARY_ASYNC_WORKER_H_ + +#include +#include +#include +#include +#include +#include +#include "base_handler.h" + +namespace OHOS { +namespace Media { + +#define EXPORT __attribute__ ((visibility ("default"))) +#define COMPILE_HIDDEN __attribute__ ((visibility ("hidden"))) + +using MediaLibraryPeriodExecute = void (*)(); +using AnalysisHandlerPeriodExecute = void (*)(std::shared_ptr &, std::function &); + +class MedialibraryPeriodTask { +public: + MedialibraryPeriodTask(MediaLibraryPeriodExecute executor, int32_t period) + : executor_(executor), period_(period) {} + MedialibraryPeriodTask(AnalysisHandlerPeriodExecute executor, int32_t period) + : analysisHandlerExecutor_(executor), period_(period) {} + virtual ~MedialibraryPeriodTask() {} + MediaLibraryPeriodExecute executor_; + AnalysisHandlerPeriodExecute analysisHandlerExecutor_; + std::thread thread_; + std::atomic isThreadRunning_{false}; + std::atomic isTaskRunning_{false}; + int32_t period_{0}; +}; + + +class MediaLibraryPeriodWorker { +public: + virtual ~MediaLibraryPeriodWorker(); + EXPORT static std::shared_ptr GetInstance(); + EXPORT void StartThreadById(int32_t threadId, size_t period); + EXPORT void StopThreadById(int32_t threadId); + EXPORT void CloseThreadById(int32_t threadId); + EXPORT bool IsThreadRunning(int32_t threadId); + EXPORT int32_t AddTask(const std::shared_ptr &task); + EXPORT int32_t AddTask(const std::shared_ptr &task, + std::shared_ptr &handle, std::function &refreshAlbumsFunc); + +private: + COMPILE_HIDDEN MediaLibraryPeriodWorker(); + COMPILE_HIDDEN void Init(); + COMPILE_HIDDEN int32_t GetValidId(); + COMPILE_HIDDEN void WaitForTask(const std::shared_ptr &task); + COMPILE_HIDDEN void Worker(int32_t threadId); + COMPILE_HIDDEN void Worker(int32_t threadId, + std::shared_ptr &handle, std::function &refreshAlbumsFunc); + + COMPILE_HIDDEN static std::shared_ptr periodWorkerInstance_; + COMPILE_HIDDEN static std::mutex instanceMtx_; + COMPILE_HIDDEN std::map> tasks_; + COMPILE_HIDDEN std::vector validIds_; + COMPILE_HIDDEN std::mutex mtx_; + COMPILE_HIDDEN std::condition_variable cv_; +}; + +} // namespace Media +} // namespace OHOS +#endif // OHOS_MEDIALIBRARY_NOTIFY_H \ No newline at end of file diff --git a/frameworks/services/media_async_worker/src/medialibrary_period_worker.cpp b/frameworks/services/media_async_worker/src/medialibrary_period_worker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..232152765fcf2a14928418b439bc172f0412dfea --- /dev/null +++ b/frameworks/services/media_async_worker/src/medialibrary_period_worker.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 "medialibrary_period_worker.h" +#include "media_log.h" +#include "power_efficiency_manager.h" + +using namespace std; + +namespace OHOS { +namespace Media { + +shared_ptr MediaLibraryPeriodWorker::periodWorkerInstance_{nullptr}; +mutex MediaLibraryPeriodWorker::instanceMtx_; +static constexpr int32_t THREAD_NUM = 2; + +shared_ptr MediaLibraryPeriodWorker::GetInstance() +{ + if (periodWorkerInstance_ == nullptr) { + lock_guard lockGuard(instanceMtx_); + periodWorkerInstance_ = shared_ptr(new MediaLibraryPeriodWorker()); + if (periodWorkerInstance_ != nullptr) { + periodWorkerInstance_->Init(); + } + } + return periodWorkerInstance_; +} + +MediaLibraryPeriodWorker::MediaLibraryPeriodWorker() {} + +MediaLibraryPeriodWorker::~MediaLibraryPeriodWorker() +{ + for (auto &task : tasks_) { + task.second->isThreadRunning_.store(false); + } + cv_.notify_all(); + for (auto &task : tasks_) { + if (task.second->thread_.joinable()) { + task.second->thread_.join(); + } + } + periodWorkerInstance_ = nullptr; +} + +void MediaLibraryPeriodWorker::Init() +{ + validIds_ = vector(THREAD_NUM, false); +} + +int32_t MediaLibraryPeriodWorker::AddTask(const shared_ptr &task) +{ + int32_t threadId = GetValidId(); + if (threadId == -1) { + MEDIA_ERR_LOG("task is over size"); + return threadId; + } + task->isThreadRunning_.store(true); + task->isTaskRunning_.store(true); + task->thread_ = thread([this, threadId]() { this->Worker(threadId); }); + tasks_[threadId] = task; + return threadId; +} + +int32_t MediaLibraryPeriodWorker::AddTask(const shared_ptr &task, + shared_ptr &handle, function &refreshAlbumsFunc) +{ + int32_t threadId = GetValidId(); + if (threadId == -1) { + MEDIA_ERR_LOG("task is over size"); + return threadId; + } + task->isThreadRunning_.store(true); + task->isTaskRunning_.store(true); + task->thread_ = thread([this, threadId, &handle, &refreshAlbumsFunc]() { + this->Worker(threadId, handle, refreshAlbumsFunc); + }); + tasks_[threadId] = task; + return threadId; +} + +int32_t MediaLibraryPeriodWorker::GetValidId() +{ + lock_guard lockGuard(mtx_); + int32_t index = -1; + for (int32_t i = 0; i < THREAD_NUM; i++) { + if (!validIds_[i]) { + index = i; + validIds_[i] = true; + break; + } + } + return index; +} + +void MediaLibraryPeriodWorker::StartThreadById(int32_t threadId, size_t period) +{ + lock_guard lockGuard(mtx_); + auto task = tasks_.find(threadId); + if (task == tasks_.end()) { + return; + } + task->second->isTaskRunning_.store(true); + task->second->period_ = period; + cv_.notify_all(); +} + +void MediaLibraryPeriodWorker::StopThreadById(int32_t threadId) +{ + lock_guard lockGuard(mtx_); + auto task = tasks_.find(threadId); + if (task == tasks_.end()) { + return; + } + task->second->isTaskRunning_.store(false); +} + +void MediaLibraryPeriodWorker::CloseThreadById(int32_t threadId) +{ + lock_guard lockGuard(mtx_); + auto task = tasks_.find(threadId); + if (task == tasks_.end()) { + return; + } + task->second->isThreadRunning_.store(false); + validIds_[threadId] = false; + cv_.notify_all(); + if (task->second->thread_.joinable()) { + task->second->thread_.join(); + task->second = nullptr; + } + tasks_.erase(threadId); +} + +bool MediaLibraryPeriodWorker::IsThreadRunning(int32_t threadId) +{ + lock_guard lockGuard(mtx_); + auto task = tasks_.find(threadId); + if (task == tasks_.end()) { + return false; + } + return task->second->isThreadRunning_.load() && task->second->isTaskRunning_.load(); +} + +void MediaLibraryPeriodWorker::WaitForTask(const std::shared_ptr &task) +{ + unique_lock lock(mtx_); + cv_.wait(lock, [&task] { return task->isTaskRunning_.load() || !task->isThreadRunning_.load(); }); +} + +void MediaLibraryPeriodWorker::Worker(int32_t threadId) +{ + string name("NotifyWorker"); + pthread_setname_np(pthread_self(), name.c_str()); + auto task = tasks_.find(threadId); + if (task == tasks_.end()) { + return; + } + while (task->second->isThreadRunning_.load()) { + WaitForTask(task->second); + if (!task->second->isThreadRunning_.load()) { + return; + } + task->second->executor_(); + this_thread::sleep_for(chrono::milliseconds(task->second->period_)); + } +} + +void MediaLibraryPeriodWorker::Worker(int32_t threadId, + shared_ptr &handle, function &refreshAlbumsFunc) +{ + string name("AnalysisAlbumWorker"); + pthread_setname_np(pthread_self(), name.c_str()); + auto task = tasks_.find(threadId); + if (task == tasks_.end()) { + return; + } + while (task->second->isThreadRunning_.load()) { + WaitForTask(task->second); + if (!task->second->isThreadRunning_.load()) { + return; + } + task->second->analysisHandlerExecutor_(handle, refreshAlbumsFunc); + if (task->second->period_ != PowerEfficiencyManager::GetAlbumUpdateInterval()) { + task->second->period_ = PowerEfficiencyManager::GetAlbumUpdateInterval(); + } + this_thread::sleep_for(chrono::milliseconds(task->second->period_)); + } +} +} // namespace Media +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/services/media_backup_extension/include/backup_database_utils.h b/frameworks/services/media_backup_extension/include/backup_database_utils.h index 3ecad7f1d927860556b6b0d566c5f944f3d6d2ca..071e95ee0a9e3d5ba72a0eda76248f26ecfaafe3 100644 --- a/frameworks/services/media_backup_extension/include/backup_database_utils.h +++ b/frameworks/services/media_backup_extension/include/backup_database_utils.h @@ -128,6 +128,7 @@ public: private: static std::string CloudSyncTriggerFunc(const std::vector &args); static std::string IsCallerSelfFunc(const std::vector &args); + static std::string PhotoAlbumNotifyFunc(const std::vector& args); }; class RdbCallback : public NativeRdb::RdbOpenCallback { diff --git a/frameworks/services/media_backup_extension/include/clone_restore.h b/frameworks/services/media_backup_extension/include/clone_restore.h index e5679c07a1ee14459423aa9508292c7d7ddc69a1..cddfac195524818c3cfbd9d88e27c826ded5fd5c 100644 --- a/frameworks/services/media_backup_extension/include/clone_restore.h +++ b/frameworks/services/media_backup_extension/include/clone_restore.h @@ -59,7 +59,7 @@ private: void RestoreAlbum(void); void RestoreAudio(void) override; void NotifyAlbum() override; - void InsertPhoto(std::vector &fileInfos); + int InsertPhoto(std::vector &fileInfos); std::vector GetInsertValues(int32_t sceneCode, std::vector &fileInfos, int32_t sourceType); std::vector GetInsertValues(std::vector &analysisAlbumTbl); @@ -210,6 +210,7 @@ private: std::shared_ptr oldYearKvStorePtr_ = nullptr; std::shared_ptr newMonthKvStorePtr_ = nullptr; std::shared_ptr newYearKvStorePtr_ = nullptr; + std::vector photosFailedOffsets; }; template diff --git a/frameworks/services/media_backup_extension/include/report/json_utils.h b/frameworks/services/media_backup_extension/include/report/json_utils.h index bc4a5767b5ca0acdb74b3c943aa3a4c1825537e5..c5caabddfee6a596ce35737ac38ca68797183805 100644 --- a/frameworks/services/media_backup_extension/include/report/json_utils.h +++ b/frameworks/services/media_backup_extension/include/report/json_utils.h @@ -24,7 +24,7 @@ namespace OHOS::Media { class JsonUtils { public: - nlohmann::json IsValid(const nlohmann::json &jsonObj) + bool IsValid(const nlohmann::json &jsonObj) { return !(jsonObj.is_discarded() || jsonObj.is_null() || jsonObj.empty()); } @@ -42,6 +42,11 @@ public: return jsonObj; } + bool IsExists(const nlohmann::json &jsonObj, const std::string &key) + { + return jsonObj.find(key) != jsonObj.end(); + } + int32_t GetInt(const nlohmann::json &jsonObj, const std::string &key, int32_t defaultValue = 0) { auto iter = jsonObj.find(key); diff --git a/frameworks/services/media_backup_extension/include/report/media_backup_report_data_type.h b/frameworks/services/media_backup_extension/include/report/media_backup_report_data_type.h index 88b6ccbeff5326282d66c9bae7c90d3743cff42b..44c0d4937454c5f6288d882c338169a226b013c3 100644 --- a/frameworks/services/media_backup_extension/include/report/media_backup_report_data_type.h +++ b/frameworks/services/media_backup_extension/include/report/media_backup_report_data_type.h @@ -16,6 +16,7 @@ #define OHOS_MEDIA_BACKUP_REPORT_DATA_TYPE_H #include +#include namespace OHOS::Media { struct AlbumMediaStatisticInfo { @@ -32,7 +33,9 @@ struct AlbumMediaStatisticInfo { int32_t burstCoverCount; int32_t burstTotalCount; }; -struct MediaRestoreResultInfo { + +class MediaRestoreResultInfo { +public: int32_t sceneCode; std::string taskId; std::string errorCode; @@ -42,6 +45,84 @@ struct MediaRestoreResultInfo { int duplicateCount; int failedCount; int successCount; + +public: + std::string ToString() const + { + std::stringstream ss; + ss << "MediaRestoreResultInfo[" + << ", sceneCode: " << this->sceneCode << ", taskId: " << this->taskId << ", errorCode: " << this->errorCode + << ", errorInfo: " << this->errorInfo << "type: " << this->type << ", backupInfo: " << this->backupInfo + << ", duplicateCount: " << this->duplicateCount << ", failedCount: " << this->failedCount + << ", successCount: " << this->successCount << "]"; + return ss.str(); + } +}; + +class CallbackBackupInfo { +public: + std::string backupInfo; + std::string details; + int duplicateCount; + int failedCount; + int successCount; + +public: + std::string ToString() const + { + std::stringstream ss; + ss << "BackupInfo[ " + << "backupInfo: " << this->backupInfo << ", " + << "details: " << this->details << ", " + << "duplicateCount: " << this->duplicateCount << ", " + << "failedCount: " << this->failedCount << ", " + << "successCount: " << this->successCount << " ]"; + return ss.str(); + } +}; + +class CallbackResultInfo { +public: + std::string errorCode; + std::string errorInfo; + std::string type; + +public: + std::string ToString() const + { + std::stringstream ss; + ss << "ResultInfo[ " + << "errorCode: " << this->errorCode << ", " + << "errorInfo: " << this->errorInfo << ", " + << "type: " << this->type << " ]"; + return ss.str(); + } +}; + +class CallbackResultData { +public: + CallbackResultInfo resultInfo; + std::vector infos; + +private: + std::string ToString(const std::vector &infoList) const + { + std::stringstream ss; + ss << "infos[ "; + for (const auto &info : infoList) { + ss << info.ToString() << ", "; + } + ss << " ]"; + return ss.str(); + } + +public: + std::string ToString() const + { + std::stringstream ss; + ss << "ResultData[ " << this->resultInfo.ToString() << ", " << this->ToString(this->infos) << " ]"; + return ss.str(); + } }; } // namespace OHOS::Media #endif // OHOS_MEDIA_BACKUP_REPORT_DATA_TYPE_H \ No newline at end of file diff --git a/frameworks/services/media_backup_extension/include/report/upgrade_restore_gallery_media_task.h b/frameworks/services/media_backup_extension/include/report/upgrade_restore_gallery_media_task.h index 280a306e44cc9b593b745c80fb72e0a90f015daa..57ea25a68dfc39e22525c5dedc31410eb4bafe0b 100644 --- a/frameworks/services/media_backup_extension/include/report/upgrade_restore_gallery_media_task.h +++ b/frameworks/services/media_backup_extension/include/report/upgrade_restore_gallery_media_task.h @@ -22,26 +22,6 @@ namespace OHOS::Media { class UpgradeRestoreGalleryMediaTask { -private: - struct BackupInfo { - std::string backupInfo; - std::string details; - int duplicateCount; - int failedCount; - int successCount; - }; - - struct ResultInfo { - std::string errorCode; - std::string errorInfo; - std::string type; - std::vector infos; - }; - - struct ResultData { - std::vector resultInfo; - }; - public: UpgradeRestoreGalleryMediaTask &SetSceneCode(int32_t sceneCode) { @@ -56,9 +36,8 @@ public: int32_t Report(const std::string &taskInfo); private: - ResultData ParseFromJsonStr(const std::string &jsonStr); - std::vector Parse(const ResultData &resultData); - std::string ToString(const ResultData &resultData); + CallbackResultData ParseFromJsonStr(const std::string &jsonStr); + std::vector Parse(const CallbackResultData &resultData); private: int32_t sceneCode_; diff --git a/frameworks/services/media_backup_extension/include/restore/gallery_db_upgrade.h b/frameworks/services/media_backup_extension/include/restore/gallery_db_upgrade.h index be45de8db70c65cc69c35fa88523bb810ac52648..808d2e2290ec50383e067c0746b7461f7bc3b227 100644 --- a/frameworks/services/media_backup_extension/include/restore/gallery_db_upgrade.h +++ b/frameworks/services/media_backup_extension/include/restore/gallery_db_upgrade.h @@ -22,11 +22,15 @@ namespace OHOS::Media { namespace DataTransfer { class GalleryDbUpgrade { public: - int32_t OnUpgrade(NativeRdb::RdbStore &store); + int32_t OnUpgrade(std::shared_ptr galleryRdbPtr); private: + int32_t OnUpgrade(NativeRdb::RdbStore &store); int32_t AddPhotoQualityOfGalleryMedia(NativeRdb::RdbStore &store); int32_t AddRelativeBucketIdOfGalleryAlbum(NativeRdb::RdbStore &store); + int32_t GarbageAlbumUpgrade(NativeRdb::RdbStore &store); + int32_t GarbageAlbumCheckOrAddRelativeBucketId(NativeRdb::RdbStore &store); + int32_t GarbageAlbumCheckOrAddType(NativeRdb::RdbStore &store); private: // Note: The column photo_quality's default value is 0. @@ -35,6 +39,10 @@ private: ALTER TABLE gallery_media ADD COLUMN photo_quality INTEGER DEFAULT 1;"; const std::string SQL_GALLERY_ALBUM_TABLE_ADD_RELATIVE_BUCKET_ID = "\ ALTER TABLE gallery_album ADD COLUMN relativeBucketId TEXT;"; + const std::string SQL_GARBAGE_ALBUM_TABLE_ADD_RELATIVE_BUCKET_ID = "\ + ALTER TABLE garbage_album ADD COLUMN relative_bucket_id TEXT;"; + const std::string SQL_GARBAGE_ALBUM_TABLE_ADD_TYPE = "\ + ALTER TABLE garbage_album ADD COLUMN type INTEGER DEFAULT 0;"; private: DbUpgradeUtils dbUpgradeUtils_; diff --git a/frameworks/services/media_backup_extension/src/backup_database_utils.cpp b/frameworks/services/media_backup_extension/src/backup_database_utils.cpp index 9c9224110d1dc5788985414841fedde61ae6d871..37e04b29149c15b0a27e1f4b0f693eade223b9b0 100644 --- a/frameworks/services/media_backup_extension/src/backup_database_utils.cpp +++ b/frameworks/services/media_backup_extension/src/backup_database_utils.cpp @@ -59,6 +59,7 @@ int32_t BackupDatabaseUtils::InitDb(std::shared_ptr &rdbSto if (isMediaLibrary) { config.SetScalarFunction("cloud_sync_func", 0, CloudSyncTriggerFunc); config.SetScalarFunction("is_caller_self_func", 0, IsCallerSelfFunc); + config.SetScalarFunction("photo_album_notify_func", 1, PhotoAlbumNotifyFunc); } int32_t err; RdbCallback cb; @@ -76,6 +77,11 @@ std::string BackupDatabaseUtils::IsCallerSelfFunc(const std::vector return "false"; } +std::string BackupDatabaseUtils::PhotoAlbumNotifyFunc(const std::vector &args) +{ + return ""; +} + static int32_t ExecSqlWithRetry(std::function execSql) { int32_t currentTime = 0; diff --git a/frameworks/services/media_backup_extension/src/clone_restore.cpp b/frameworks/services/media_backup_extension/src/clone_restore.cpp index 32d855b89d87becda69031af24a4af434c6ee95a..ac1effd879d33d1c996cbbeed4673e29a1a2558b 100644 --- a/frameworks/services/media_backup_extension/src/clone_restore.cpp +++ b/frameworks/services/media_backup_extension/src/clone_restore.cpp @@ -278,6 +278,12 @@ void CloneRestore::RestorePhoto() ffrt::task_attr().qos(static_cast(ffrt::qos_utility))); } ffrt::wait(); + size_t vectorLen = photosFailedOffsets.size(); + needReportFailed_ = true; + for (size_t offset = 0; offset < vectorLen; offset++) { + RestorePhotoBatch(offset, 1); + } + needReportFailed_ = false; // Scenario 2, clone photos from Photos only. int32_t totalNumber = this->photosClone_.GetPhotosRowCountNotInPhotoMap(); MEDIA_INFO_LOG("QueryTotalNumberNot, totalNumber = %{public}d", totalNumber); @@ -288,6 +294,11 @@ void CloneRestore::RestorePhoto() ffrt::task_attr().qos(static_cast(ffrt::qos_utility))); } ffrt::wait(); + vectorLen = photosFailedOffsets.size(); + needReportFailed_ = true; + for (size_t offset = 0; offset < vectorLen; offset++) { + RestorePhotoBatch(offset); + } this->photosClone_.OnStop(otherTotalNumber_, otherProcessStatus_); BackupDatabaseUtils::UpdateFaceAnalysisTblStatus(mediaLibraryRdb_); @@ -351,15 +362,15 @@ void CloneRestore::MoveMigrateFile(std::vector &fileInfos, int64_t &fi migrateVideoFileNumber_ += videoFileMoveCount; } -void CloneRestore::InsertPhoto(vector &fileInfos) +int CloneRestore::InsertPhoto(vector &fileInfos) { if (mediaLibraryRdb_ == nullptr) { MEDIA_ERR_LOG("mediaLibraryRdb_ is null"); - return; + return E_OK; } if (fileInfos.empty()) { MEDIA_ERR_LOG("fileInfos are empty"); - return; + return E_OK; } int64_t startGenerate = MediaFileUtils::UTCTimeMilliSeconds(); vector values = GetInsertValues(CLONE_RESTORE_ID, fileInfos, SourceType::PHOTOS); @@ -367,8 +378,10 @@ void CloneRestore::InsertPhoto(vector &fileInfos) int64_t photoRowNum = 0; int32_t errCode = BatchInsertWithRetry(PhotoColumn::PHOTOS_TABLE, values, photoRowNum); if (errCode != E_OK) { - UpdateFailedFiles(fileInfos, RestoreError::INSERT_FAILED); - return; + if (needReportFailed_) { + UpdateFailedFiles(fileInfos, RestoreError::INSERT_FAILED); + } + return errCode; } migrateDatabaseNumber_ += photoRowNum; @@ -385,6 +398,7 @@ void CloneRestore::InsertPhoto(vector &fileInfos) (long)(startInsertPhoto - startGenerate), (long)photoRowNum, (long)(startInsertRelated - startInsertPhoto), (long)(startMove - startInsertRelated), (long)fileMoveCount, (long)(fileMoveCount - videoFileMoveCount), (long)videoFileMoveCount, (long)(end - startMove)); + return E_OK; } vector CloneRestore::GetInsertValues(int32_t sceneCode, vector &fileInfos, @@ -1557,7 +1571,9 @@ void CloneRestore::RestorePhotoBatch(int32_t offset, int32_t isRelatedToPhotoMap MEDIA_INFO_LOG( "start restore photo, offset: %{public}d, isRelatedToPhotoMap: %{public}d", offset, isRelatedToPhotoMap); vector fileInfos = QueryFileInfos(offset, isRelatedToPhotoMap); - InsertPhoto(fileInfos); + if (InsertPhoto(fileInfos) != E_OK) { + photosFailedOffsets.push_back(offset); + } BatchNotifyPhoto(fileInfos); RestoreImageFaceInfo(fileInfos); diff --git a/frameworks/services/media_backup_extension/src/report/upgrade_restore_gallery_media_task.cpp b/frameworks/services/media_backup_extension/src/report/upgrade_restore_gallery_media_task.cpp index 10b4f061cca23b32df5e4b92598308b0ee6a1606..63cf83e0aade34ce9e4399299a215ed5da93e32a 100644 --- a/frameworks/services/media_backup_extension/src/report/upgrade_restore_gallery_media_task.cpp +++ b/frameworks/services/media_backup_extension/src/report/upgrade_restore_gallery_media_task.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "upgrade_restore_task_report.h" +#include "upgrade_restore_gallery_media_task.h" #include #include @@ -20,16 +20,16 @@ #include "media_log.h" #include "hisysevent.h" #include "media_backup_report_data_type.h" -#include "upgrade_restore_gallery_media_task.h" #include "json_utils.h" namespace OHOS::Media { static constexpr char MEDIA_LIBRARY[] = "MEDIALIBRARY"; int32_t UpgradeRestoreGalleryMediaTask::Report(const std::string &taskInfo) { - UpgradeRestoreGalleryMediaTask::ResultData resultData = this->ParseFromJsonStr(taskInfo); - MEDIA_INFO_LOG("GET restoreExInfo: %{public}s", this->ToString(resultData).c_str()); + CallbackResultData resultData = this->ParseFromJsonStr(taskInfo); + MEDIA_INFO_LOG("GET restoreExInfo: %{public}s", resultData.ToString().c_str()); for (const auto &eventInfo : this->Parse(resultData)) { + MEDIA_INFO_LOG("GET restoreExInfo: %{public}s", eventInfo.ToString().c_str()); int32_t ret = HiSysEventWrite(MEDIA_LIBRARY, "MEDIALIB_BACKUP_RESTORE_RESULT", HiviewDFX::HiSysEvent::EventType::STATISTIC, @@ -58,65 +58,58 @@ int32_t UpgradeRestoreGalleryMediaTask::Report(const std::string &taskInfo) return 0; } -UpgradeRestoreGalleryMediaTask::ResultData UpgradeRestoreGalleryMediaTask::ParseFromJsonStr(const std::string &jsonStr) +CallbackResultData UpgradeRestoreGalleryMediaTask::ParseFromJsonStr(const std::string &jsonStr) { JsonUtils jsonUtils; nlohmann::json jsonObj = jsonUtils.Parse(jsonStr); - ResultData resultData; + CallbackResultData resultData; for (const auto &info : jsonUtils.GetArray(jsonObj, "resultInfo")) { - ResultInfo resultInfo; - resultInfo.errorCode = jsonUtils.GetString(info, "errorCode"); - resultInfo.errorInfo = jsonUtils.GetString(info, "errorInfo"); - resultInfo.type = jsonUtils.GetString(info, "type"); + // Parse the resultInfo + bool isResultInfo = jsonUtils.IsExists(info, "errorCode"); + isResultInfo = isResultInfo && jsonUtils.IsExists(info, "errorInfo"); + isResultInfo = isResultInfo && jsonUtils.IsExists(info, "type"); + if (isResultInfo) { + CallbackResultInfo resultInfo; + resultInfo.errorCode = jsonUtils.GetString(info, "errorCode"); + resultInfo.errorInfo = jsonUtils.GetString(info, "errorInfo"); + resultInfo.type = jsonUtils.GetString(info, "type"); + resultData.resultInfo = resultInfo; + continue; + } + // Parse the backupInfo + bool isBackupInfo = jsonUtils.IsExists(info, "infos"); + if (!isBackupInfo) { + continue; + } for (const auto &backup : jsonUtils.GetArray(info, "infos")) { - BackupInfo backupInfo; + CallbackBackupInfo backupInfo; backupInfo.backupInfo = jsonUtils.GetString(backup, "backupInfo"); backupInfo.duplicateCount = jsonUtils.GetInt(backup, "duplicateCount"); backupInfo.failedCount = jsonUtils.GetInt(backup, "failedCount"); backupInfo.successCount = jsonUtils.GetInt(backup, "successCount"); - resultInfo.infos.push_back(backupInfo); + resultData.infos.emplace_back(backupInfo); } - resultData.resultInfo.push_back(resultInfo); } return resultData; } -std::vector UpgradeRestoreGalleryMediaTask::Parse( - const UpgradeRestoreGalleryMediaTask::ResultData &resultData) +std::vector UpgradeRestoreGalleryMediaTask::Parse(const CallbackResultData &resultData) { std::vector result; - for (const auto &resultInfo : resultData.resultInfo) { - for (const auto &backupInfo : resultInfo.infos) { - MediaRestoreResultInfo eventInfo; - eventInfo.sceneCode = this->sceneCode_; - eventInfo.taskId = this->taskId_; - eventInfo.errorCode = resultInfo.errorCode; - eventInfo.errorInfo = resultInfo.errorInfo; - eventInfo.type = resultInfo.type; - eventInfo.backupInfo = backupInfo.backupInfo; - eventInfo.duplicateCount = backupInfo.duplicateCount; - eventInfo.failedCount = backupInfo.failedCount; - eventInfo.successCount = backupInfo.successCount; - result.emplace_back(eventInfo); - } + const CallbackResultInfo &resultInfo = resultData.resultInfo; + for (const auto &backupInfo : resultData.infos) { + MediaRestoreResultInfo eventInfo; + eventInfo.sceneCode = this->sceneCode_; + eventInfo.taskId = this->taskId_; + eventInfo.errorCode = resultInfo.errorCode; + eventInfo.errorInfo = resultInfo.errorInfo; + eventInfo.type = resultInfo.type; + eventInfo.backupInfo = backupInfo.backupInfo; + eventInfo.duplicateCount = backupInfo.duplicateCount; + eventInfo.failedCount = backupInfo.failedCount; + eventInfo.successCount = backupInfo.successCount; + result.emplace_back(eventInfo); } return result; } - -std::string UpgradeRestoreGalleryMediaTask::ToString(const UpgradeRestoreGalleryMediaTask::ResultData &resultData) -{ - std::stringstream ss; - for (const auto &resultInfo : resultData.resultInfo) { - ss << "ErrorCode: " << resultInfo.errorCode << ", "; - ss << "ErrorInfo: " << resultInfo.errorInfo << ", "; - ss << "Type: " << resultInfo.type << ", "; - for (const auto &backupInfo : resultInfo.infos) { - ss << "BackupInfo: " << backupInfo.backupInfo << ", "; - ss << "DuplicateCount: " << backupInfo.duplicateCount << ", "; - ss << "FailedCount: " << backupInfo.failedCount << ", "; - ss << "SuccessCount: " << backupInfo.successCount << ", "; - } - } - return ss.str(); -} } // namespace OHOS::Media \ No newline at end of file diff --git a/frameworks/services/media_backup_extension/src/restore/gallery_db_upgrade.cpp b/frameworks/services/media_backup_extension/src/restore/gallery_db_upgrade.cpp index aef540e5a705ab63d0ceb8f0cf5c87ad8e80da2e..ddbdad0594ac3c5c8167c9253a9db6a04a0c056d 100644 --- a/frameworks/services/media_backup_extension/src/restore/gallery_db_upgrade.cpp +++ b/frameworks/services/media_backup_extension/src/restore/gallery_db_upgrade.cpp @@ -21,6 +21,18 @@ namespace OHOS::Media { namespace DataTransfer { +/** + * @brief Upgrade the database, before data restore or clone. + */ +int32_t GalleryDbUpgrade::OnUpgrade(std::shared_ptr galleryRdbPtr) +{ + if (galleryRdbPtr == nullptr) { + MEDIA_WARN_LOG("galleryRdbPtr is nullptr, Maybe init failed, skip gallery db upgrade."); + return -1; + } + return this->OnUpgrade(*galleryRdbPtr); +} + /** * @brief Upgrade the database, before data restore or clone. */ @@ -31,7 +43,9 @@ int32_t GalleryDbUpgrade::OnUpgrade(NativeRdb::RdbStore &store) int32_t ret = handler.OnUpgrade(store, 0, 0); MEDIA_INFO_LOG("GalleryDbUpgrade::OnUpgrade end, ret: %{public}d", ret); this->AddPhotoQualityOfGalleryMedia(store); - return this->AddRelativeBucketIdOfGalleryAlbum(store); + this->AddRelativeBucketIdOfGalleryAlbum(store); + this->GarbageAlbumUpgrade(store); + return NativeRdb::E_OK; } /** @@ -73,5 +87,43 @@ int32_t GalleryDbUpgrade::AddRelativeBucketIdOfGalleryAlbum(NativeRdb::RdbStore MEDIA_INFO_LOG("Media_Restore: GalleryDbUpgrade::AddRelativeBucketIdOfGalleryAlbum success"); return ret; } + +int32_t GalleryDbUpgrade::GarbageAlbumUpgrade(NativeRdb::RdbStore &store) +{ + this->GarbageAlbumCheckOrAddRelativeBucketId(store); + this->GarbageAlbumCheckOrAddType(store); + return NativeRdb::E_OK; +} + +int32_t GalleryDbUpgrade::GarbageAlbumCheckOrAddRelativeBucketId(NativeRdb::RdbStore &store) +{ + if (this->dbUpgradeUtils_.IsColumnExists(store, "garbage_album", "relative_bucket_id")) { + return NativeRdb::E_OK; + } + std::string sql = this->SQL_GARBAGE_ALBUM_TABLE_ADD_RELATIVE_BUCKET_ID; + int32_t ret = store.ExecuteSql(sql); + if (ret != NativeRdb::E_OK) { + MEDIA_ERR_LOG("Media_Restore: GarbageAlbumCheckOrAddRelativeBucketId failed, ret=%{public}d, sql=%{public}s", + ret, + sql.c_str()); + } + MEDIA_INFO_LOG("Media_Restore: GarbageAlbumCheckOrAddRelativeBucketId success"); + return ret; +} + +int32_t GalleryDbUpgrade::GarbageAlbumCheckOrAddType(NativeRdb::RdbStore &store) +{ + if (this->dbUpgradeUtils_.IsColumnExists(store, "garbage_album", "type")) { + return NativeRdb::E_OK; + } + std::string sql = this->SQL_GARBAGE_ALBUM_TABLE_ADD_TYPE; + int32_t ret = store.ExecuteSql(sql); + if (ret != NativeRdb::E_OK) { + MEDIA_ERR_LOG( + "Media_Restore: GarbageAlbumCheckOrAddType failed, ret=%{public}d, sql=%{public}s", ret, sql.c_str()); + } + MEDIA_INFO_LOG("Media_Restore: GarbageAlbumCheckOrAddType success"); + return ret; +} } // namespace DataTransfer } // namespace OHOS::Media \ No newline at end of file diff --git a/frameworks/services/media_backup_extension/src/upgrade_restore.cpp b/frameworks/services/media_backup_extension/src/upgrade_restore.cpp index 04b6f4591a54f25c152308051c3c58880c0d19f2..e6839d4f19219332abb2e855f0709025da40bafb 100644 --- a/frameworks/services/media_backup_extension/src/upgrade_restore.cpp +++ b/frameworks/services/media_backup_extension/src/upgrade_restore.cpp @@ -305,16 +305,11 @@ bool UpgradeRestore::ParseResultSetFromAudioDb(const std::shared_ptrgalleryRdb_); AnalyzeSource(); InitGarbageAlbum(); HandleClone(); - // upgrade gallery.db - if (this->galleryRdb_ != nullptr) { - DataTransfer::GalleryDbUpgrade galleryDbUpgrade; - galleryDbUpgrade.OnUpgrade(*this->galleryRdb_); - } else { - MEDIA_WARN_LOG("galleryRdb_ is nullptr, Maybe init failed, skip gallery db upgrade."); - } // restore PhotoAlbum this->photoAlbumRestore_.Restore(); RestoreFromGalleryPortraitAlbum(); diff --git a/frameworks/services/media_cloud_sync/include/cloud_dirty_handle/cloud_upload_checker.h b/frameworks/services/media_cloud_sync/include/cloud_dirty_handle/cloud_upload_checker.h new file mode 100644 index 0000000000000000000000000000000000000000..f4e8094b43d9fa3a5bf667829d247811904b6711 --- /dev/null +++ b/frameworks/services/media_cloud_sync/include/cloud_dirty_handle/cloud_upload_checker.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_UPLOAD_CHECKER_H +#define OHOS_CLOUD_UPLOAD_CHECKER_H + +#include +#include +#include + +#include "rdb_predicates.h" + +namespace OHOS { +namespace Media { +struct CheckedPhotoInfo { + int32_t fileId; + std::string path; +}; + +class CloudUploadChecker { +public: + static void HandleNoOriginPhoto(); + +private: + static int32_t GetPhotoCount(int32_t startFileId); + static std::vector QueryPhotoInfo(int32_t startFiled, int32_t &outFileId); + static std::string GetQuerySql(int32_t startFileId, std::string mediaColumns); + static void HandlePhotoInfos(std::vector); + static void UpdateDirty(std::vector idList, int32_t dirtyType); +}; +} // namespace Media +} // namespace OHOS +#endif // OHOS_CLOUD_UPLOAD_CHECKER_H diff --git a/frameworks/services/media_cloud_sync/include/media_cloud_asset_download/cloud_media_asset_download_operation.h b/frameworks/services/media_cloud_sync/include/media_cloud_asset_download/cloud_media_asset_download_operation.h index 29e7ddd2d0c1d25fd72027e38eb52db2b421a1f0..85e4dd7fbf20b264e0b43807ae3cad4f922be388 100644 --- a/frameworks/services/media_cloud_sync/include/media_cloud_asset_download/cloud_media_asset_download_operation.h +++ b/frameworks/services/media_cloud_sync/include/media_cloud_asset_download/cloud_media_asset_download_operation.h @@ -56,20 +56,16 @@ public: std::map fileDownloadMap; std::vector batchFileIdNeedDownload; int64_t batchSizeNeedDownload = 0; + int64_t batchCountNeedDownload = 0; }; enum class Status : int32_t { FORCE_DOWNLOADING, GENTLE_DOWNLOADING, PAUSE_FOR_TEMPERATURE_LIMIT, - PAUSE_FOR_ROM_LIMIT, PAUSE_FOR_NETWORK_FLOW_LIMIT, - PAUSE_FOR_WIFI_UNAVAILABLE, - PAUSE_FOR_POWER_LIMIT, PAUSE_FOR_BACKGROUND_TASK_UNAVAILABLE, - PAUSE_FOR_FREQUENT_USER_REQUESTS, PAUSE_FOR_CLOUD_ERROR, - PAUSE_FOR_USER_PAUSE, RECOVER_FOR_MANAUL_ACTIVE, RECOVER_FOR_PASSIVE_STATUS, IDLE, @@ -98,8 +94,8 @@ public: EXPORT int32_t InitDownloadTaskInfo(); private: - void ClearData(DownloadFileData &datas); - bool IsDataEmpty(const DownloadFileData &datas); + void ClearData(DownloadFileData &data); + bool IsDataEmpty(const DownloadFileData &data); int32_t DoRelativedRegister(); int32_t SetDeathRecipient(); bool IsProperFgTemperature(); @@ -110,7 +106,9 @@ private: std::shared_ptr QueryDownloadFilesNeeded(const bool &isQueryInfo); DownloadFileData ReadyDataForBatchDownload(); EXPORT int32_t DoForceTaskExecute(); - EXPORT int32_t SubmitBatchDownload(DownloadFileData &datas, const bool &isCache); + EXPORT int32_t SubmitBatchDownload(DownloadFileData &data, const bool &isCache); + void StartFileCacheFailed(const int64_t batchNum, const int64_t batchSize); + void StartBatchDownload(const int64_t batchNum, const int64_t batchSize); int32_t DoRecoverExecute(); int32_t PassiveStatusRecover(); diff --git a/frameworks/services/media_cloud_sync/src/cloud_dirty_handle/cloud_upload_checker.cpp b/frameworks/services/media_cloud_sync/src/cloud_dirty_handle/cloud_upload_checker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c81b19784497fa7834243124f3ce113fb3cee32 --- /dev/null +++ b/frameworks/services/media_cloud_sync/src/cloud_dirty_handle/cloud_upload_checker.cpp @@ -0,0 +1,163 @@ +/* + * 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 MLOG_TAG "MediaLibraryCloudUploadChecker" + +#include "cloud_upload_checker.h" + +#include "media_file_utils.h" +#include "media_file_uri.h" +#include "medialibrary_unistore_manager.h" +#include "photo_album_column.h" +#include "thumbnail_const.h" +#include "media_column.h" +#include "preferences.h" +#include "preferences_helper.h" +#include "result_set_utils.h" +#include "thumbnail_const.h" +#include "medialibrary_object_utils.h" +#include "medialibrary_photo_operations.h" + +namespace OHOS { +namespace Media { +using namespace std; +using namespace NativeRdb; +const std::string BATCH_SIZE = "500"; +const std::string TASK_PROGRESS_XML = "/data/storage/el2/base/preferences/task_progress.xml"; +const std::string NO_ORIGIN_PHOTO_NUMBER = "no_origin_photo_number"; + +static const int32_t NO_ORIGIN_BUT_LCD = 100; +static const int32_t NO_ORIGIN_NO_LCD = 101; + +void CloudUploadChecker::HandleNoOriginPhoto() +{ + MEDIA_INFO_LOG("start handle no origin photo!"); + int32_t errCode; + shared_ptr prefs = + NativePreferences::PreferencesHelper::GetPreferences(TASK_PROGRESS_XML, errCode); + if (!prefs) { + MEDIA_ERR_LOG("get preferences error: %{public}d", errCode); + return; + } + int32_t curFileId = prefs->GetInt(NO_ORIGIN_PHOTO_NUMBER, 0); + MEDIA_INFO_LOG("start file id: %{public}d", curFileId); + while (GetPhotoCount(curFileId) > 0) { + MEDIA_INFO_LOG("start handle origin photo start: %{public}d", curFileId); + int32_t nextFileId = curFileId; + std::vector photoInfos = QueryPhotoInfo(curFileId, nextFileId); + HandlePhotoInfos(photoInfos); + curFileId = nextFileId + 1; + prefs->PutInt(NO_ORIGIN_PHOTO_NUMBER, curFileId); + prefs->FlushSync(); + } + MEDIA_INFO_LOG("end handle no origin photo!"); + return; +} + +void CloudUploadChecker::HandlePhotoInfos(std::vector photoInfos) +{ + std::vector lcdList; + std::vector noLcdList; + for (CheckedPhotoInfo photoInfo: photoInfos) { + if (MediaFileUtils::IsFileExists(photoInfo.path)) { + continue; + } + string lcdPath = GetThumbnailPath(photoInfo.path, THUMBNAIL_LCD_SUFFIX); + if (MediaFileUtils::IsFileExists(lcdPath)) { + lcdList.push_back(to_string(photoInfo.fileId)); + } else { + noLcdList.push_back(to_string(photoInfo.fileId)); + } + } + UpdateDirty(lcdList, NO_ORIGIN_BUT_LCD); + UpdateDirty(noLcdList, NO_ORIGIN_NO_LCD); +} + +void CloudUploadChecker::UpdateDirty(std::vector idList, int32_t dirtyType) +{ + auto rdbStore = MediaLibraryUnistoreManager::GetInstance().GetRdbStore(); + if (rdbStore == nullptr) { + MEDIA_ERR_LOG("Failed to get rdbstore!"); + return; + } + RdbPredicates predicates(PhotoColumn::PHOTOS_TABLE); + predicates.In(MediaColumn::MEDIA_ID, idList); + ValuesBucket values; + values.PutInt(PhotoColumn::PHOTO_DIRTY, dirtyType); + int32_t updateCount = 0; + int32_t err = rdbStore->Update(updateCount, values, predicates); + MEDIA_INFO_LOG("dirty: %{public}d, idList size: %{public}d, update size: %{public}d, err: %{public}d", dirtyType, + static_cast(idList.size()), updateCount, err); +} + +int32_t CloudUploadChecker::GetPhotoCount(int32_t startFileId) +{ + auto rdbStore = MediaLibraryUnistoreManager::GetInstance().GetRdbStore(); + if (rdbStore == nullptr) { + MEDIA_ERR_LOG("Failed to get rdbstore!"); + return 0; + } + std::string queryCount = " COUNT(*) AS Count"; + std::string sql = GetQuerySql(startFileId, queryCount); + std::shared_ptr resultSet = rdbStore->QuerySql(sql); + if (resultSet == nullptr || resultSet->GoToFirstRow() != NativeRdb::E_OK) { + MEDIA_ERR_LOG("resultSet is null or count is 0"); + return 0; + } + int32_t count = get(ResultSetUtils::GetValFromColumn("Count", resultSet, TYPE_INT32)); + return count; +} + +std::string CloudUploadChecker::GetQuerySql(int32_t startFileId, std::string mediaColumns) +{ + const std::string sql = "SELECT " + mediaColumns + " FROM Photos WHERE dirty = 1 AND thumbnail_ready >= 3 AND " + + "lcd_visit_time >= 2 AND date_trashed = 0 AND file_id > " + to_string(startFileId) + " LIMIT " + BATCH_SIZE; + return sql; +} + +std::vector CloudUploadChecker::QueryPhotoInfo(int32_t startFileId, int32_t &outFileId) +{ + std::vector photoInfos; + auto rdbStore = MediaLibraryUnistoreManager::GetInstance().GetRdbStore(); + if (rdbStore == nullptr) { + MEDIA_ERR_LOG("Failed to get rdbstore!"); + return photoInfos; + } + const std::string mediaColumns = Media::PhotoColumn::MEDIA_ID + ", " + Media::PhotoColumn::MEDIA_FILE_PATH; + std::string sql = GetQuerySql(startFileId, mediaColumns); + std::shared_ptr resultSet = rdbStore->QuerySql(sql); + if (resultSet == nullptr || resultSet->GoToFirstRow() != NativeRdb::E_OK) { + MEDIA_ERR_LOG("resultSet is null or count is 0"); + return photoInfos; + } + int32_t fileId = startFileId; + while (resultSet->GoToNextRow() == NativeRdb::E_OK) { + CheckedPhotoInfo photoInfo; + std::string path = + get(ResultSetUtils::GetValFromColumn(MediaColumn::MEDIA_FILE_PATH, resultSet, TYPE_STRING)); + if (path.empty()) { + MEDIA_WARN_LOG("Failed to get data path"); + continue; + } + fileId = get(ResultSetUtils::GetValFromColumn(MediaColumn::MEDIA_ID, resultSet, TYPE_INT32)); + photoInfo.fileId = fileId; + photoInfo.path = path; + photoInfos.push_back(photoInfo); + } + outFileId = fileId; + return photoInfos; +} +} // namespace Media +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/services/media_cloud_sync/src/media_cloud_asset_download/cloud_media_asset_download_operation.cpp b/frameworks/services/media_cloud_sync/src/media_cloud_asset_download/cloud_media_asset_download_operation.cpp index a6bec6481a5a67cd0e4412c4b967ed9d69cf7420..ff7b0cff07e5351e42d7da7e6b60a28e69e13c84 100644 --- a/frameworks/services/media_cloud_sync/src/media_cloud_asset_download/cloud_media_asset_download_operation.cpp +++ b/frameworks/services/media_cloud_sync/src/media_cloud_asset_download/cloud_media_asset_download_operation.cpp @@ -74,6 +74,8 @@ static const std::string TOTAL_COUNT = "COUNT(1)"; static const std::string TOTAL_SIZE = "SUM(size)"; static const bool NEED_CLEAN = true; static const int32_t EXIT_TASK = 1; +// E_PATH_NOT_FOUND corresponds to the E_PATH of dfs_error.h +static const int32_t E_PATH_NOT_FOUND = 28; static const int32_t SLEEP_FOR_LOCK = 100; static const int32_t STATUS_CHANGE_ARG_SIZE = 3; static const int32_t INDEX_ZERO = 0; @@ -84,14 +86,9 @@ static const std::map> STATUS_MAP = { { Status::FORCE_DOWNLOADING, {0, 0, 0} }, { Status::GENTLE_DOWNLOADING, {1, 0, 0} }, { Status::PAUSE_FOR_TEMPERATURE_LIMIT, {-1, 1, 1} }, - { Status::PAUSE_FOR_ROM_LIMIT, {-1, 1, 2} }, { Status::PAUSE_FOR_NETWORK_FLOW_LIMIT, {-1, 1, 3} }, - { Status::PAUSE_FOR_WIFI_UNAVAILABLE, {-1, 1, 4} }, - { Status::PAUSE_FOR_POWER_LIMIT, {-1, 1, 5} }, { Status::PAUSE_FOR_BACKGROUND_TASK_UNAVAILABLE, {1, 1, 6} }, - { Status::PAUSE_FOR_FREQUENT_USER_REQUESTS, {-1, 1, 7} }, { Status::PAUSE_FOR_CLOUD_ERROR, {-1, 1, 8} }, - { Status::PAUSE_FOR_USER_PAUSE, {-1, 1, 9} }, { Status::RECOVER_FOR_MANAUL_ACTIVE, {0, 0, 0} }, { Status::RECOVER_FOR_PASSIVE_STATUS, {-1, 0, 0} }, { Status::IDLE, {-1, 2, 0} }, @@ -150,17 +147,18 @@ void CloudMediaAssetDownloadOperation::SetTaskStatus(Status status) statusChangeVec[INDEX_ZERO], statusChangeVec[INDEX_ONE], statusChangeVec[INDEX_TWO]); } -void CloudMediaAssetDownloadOperation::ClearData(CloudMediaAssetDownloadOperation::DownloadFileData &datas) +void CloudMediaAssetDownloadOperation::ClearData(CloudMediaAssetDownloadOperation::DownloadFileData &data) { - datas.pathVec.clear(); - datas.fileDownloadMap.clear(); - datas.batchFileIdNeedDownload.clear(); - datas.batchSizeNeedDownload = 0; + data.pathVec.clear(); + data.fileDownloadMap.clear(); + data.batchFileIdNeedDownload.clear(); + data.batchSizeNeedDownload = 0; + data.batchCountNeedDownload = 0; } -bool CloudMediaAssetDownloadOperation::IsDataEmpty(const CloudMediaAssetDownloadOperation::DownloadFileData &datas) +bool CloudMediaAssetDownloadOperation::IsDataEmpty(const CloudMediaAssetDownloadOperation::DownloadFileData &data) { - return datas.fileDownloadMap.empty(); + return data.fileDownloadMap.empty(); } std::shared_ptr CloudMediaAssetDownloadOperation::QueryDownloadFilesNeeded( @@ -174,6 +172,9 @@ std::shared_ptr CloudMediaAssetDownloadOperation::QueryDow AbsRdbPredicates predicates(PhotoColumn::PHOTOS_TABLE); predicates.EqualTo(PhotoColumn::PHOTO_CLEAN_FLAG, to_string(static_cast(CleanType::TYPE_NOT_CLEAN))); predicates.EqualTo(PhotoColumn::PHOTO_POSITION, to_string(static_cast(PhotoPositionType::CLOUD))); + predicates.EqualTo(MediaColumn::MEDIA_TIME_PENDING, "0"); + predicates.EqualTo(MediaColumn::MEDIA_DATE_TRASHED, "0"); + predicates.EqualTo(PhotoColumn::PHOTO_IS_TEMP, "0"); predicates.IsNotNull(MediaColumn::MEDIA_FILE_PATH); if (static_cast(dataForDownload_.batchFileIdNeedDownload.size()) > 0) { predicates.NotIn(PhotoColumn::MEDIA_ID, dataForDownload_.batchFileIdNeedDownload); @@ -184,6 +185,8 @@ std::shared_ptr CloudMediaAssetDownloadOperation::QueryDow predicates.EqualTo(MediaColumn::MEDIA_TYPE, to_string(static_cast(MEDIA_TYPE_VIDEO))); predicates.EndWrap(); if (isQueryInfo) { + predicates.EqualTo(PhotoColumn::PHOTO_BURST_COVER_LEVEL, + to_string(static_cast(BurstCoverLevelType::COVER))); const std::vector columns = { TOTAL_COUNT, TOTAL_SIZE @@ -195,7 +198,8 @@ std::shared_ptr CloudMediaAssetDownloadOperation::QueryDow const std::vector columns = { MediaColumn::MEDIA_ID, MediaColumn::MEDIA_FILE_PATH, - MediaColumn::MEDIA_SIZE + MediaColumn::MEDIA_SIZE, + PhotoColumn::PHOTO_BURST_COVER_LEVEL }; return rdbStore->Query(predicates, columns); } @@ -233,11 +237,11 @@ CloudMediaAssetDownloadOperation::DownloadFileData CloudMediaAssetDownloadOperat MEDIA_INFO_LOG("enter ReadyDataForBatchDownload"); InitDownloadTaskInfo(); - CloudMediaAssetDownloadOperation::DownloadFileData datas; + CloudMediaAssetDownloadOperation::DownloadFileData data; std::shared_ptr resultSetForDownload = QueryDownloadFilesNeeded(false); if (resultSetForDownload == nullptr) { MEDIA_ERR_LOG("resultSetForDownload is nullptr."); - return datas; + return data; } while (resultSetForDownload->GoToNextRow() == NativeRdb::E_OK) { @@ -250,18 +254,86 @@ CloudMediaAssetDownloadOperation::DownloadFileData CloudMediaAssetDownloadOperat } int64_t fileSize = GetInt64Val(PhotoColumn::MEDIA_SIZE, resultSetForDownload); - datas.pathVec.push_back(path); - datas.fileDownloadMap[path] = fileSize; - datas.batchFileIdNeedDownload.push_back(fileId); - datas.batchSizeNeedDownload += fileSize; + data.pathVec.push_back(path); + int32_t burstCoverLevel = GetInt32Val(PhotoColumn::PHOTO_BURST_COVER_LEVEL, resultSetForDownload); + if (burstCoverLevel == static_cast(BurstCoverLevelType::COVER)) { + data.fileDownloadMap[path] = fileSize; + data.batchSizeNeedDownload += fileSize; + data.batchCountNeedDownload++; + } else { + data.fileDownloadMap[path] = 0; + } + data.batchFileIdNeedDownload.push_back(fileId); } resultSetForDownload->Close(); MEDIA_INFO_LOG("end ReadyDataForBatchDownload"); - return datas; + return data; +} + +void CloudMediaAssetDownloadOperation::StartFileCacheFailed(const int64_t batchNum, const int64_t batchSize) +{ + downloadId_ = DOWNLOAD_ID_DEFAULT; + downloadNum_ = 0; + if (isCache_) { + ClearData(cacheForDownload_); + } + ClearData(readyForDownload_); + ClearData(dataForDownload_); + batchDownloadTotalNum_ -= batchNum; + batchDownloadTotalSize_ -= batchSize; + if (!isThumbnailUpdate_) { + isThumbnailUpdate_ = true; + } + InitDownloadTaskInfo(); + // prepare for data consumption time, don't move this line + CloudMediaAssetDownloadOperation::DownloadFileData data = ReadyDataForBatchDownload(); + if (IsDataEmpty(data)) { + CancelDownloadTask(); + return; + } + readyForDownload_ = data; + // prepare the data and then set task status + SetTaskStatus(Status::PAUSE_FOR_CLOUD_ERROR); +} + +void CloudMediaAssetDownloadOperation::StartBatchDownload(const int64_t batchNum, const int64_t batchSize) +{ + std::thread([this, batchNum, batchSize]() { + this_thread::sleep_for(chrono::milliseconds(SLEEP_FOR_LOCK)); + int32_t ret = cloudSyncManager_.get().StartFileCache(dataForDownload_.pathVec, downloadId_); + if (ret == E_RDB || ret == E_PATH_NOT_FOUND) { + MEDIA_INFO_LOG("failed to StartFileCache, ret: %{public}d, downloadId_: %{public}s.", + ret, to_string(downloadId_).c_str()); + StartFileCacheFailed(batchNum, batchSize); + return; + } + if (ret != E_OK || downloadId_ == DOWNLOAD_ID_DEFAULT) { + MEDIA_ERR_LOG("failed to StartFileCache, ret: %{public}d, downloadId_: %{public}s.", + ret, to_string(downloadId_).c_str()); + downloadId_ = DOWNLOAD_ID_DEFAULT; + downloadNum_ = 0; + cacheForDownload_ = dataForDownload_; + SetTaskStatus(Status::PAUSE_FOR_CLOUD_ERROR); + return; + } + MEDIA_INFO_LOG("Success, downloadId: %{public}d, downloadNum: %{public}d, isCache: %{public}d.", + static_cast(downloadId_), static_cast(downloadNum_), static_cast(isCache_)); + if (isCache_) { + ClearData(cacheForDownload_); + return; + } + CloudMediaAssetDownloadOperation::DownloadFileData data = ReadyDataForBatchDownload(); + if (taskStatus_ == CloudMediaAssetTaskStatus::IDLE) { + MEDIA_INFO_LOG("taskStatus_ is IDLE."); + return; + } + ClearData(readyForDownload_); + readyForDownload_ = data; + }).detach(); } int32_t CloudMediaAssetDownloadOperation::SubmitBatchDownload( - CloudMediaAssetDownloadOperation::DownloadFileData &datas, const bool &isCache) + CloudMediaAssetDownloadOperation::DownloadFileData &data, const bool &isCache) { std::lock_guard lock(mutex_); if (taskStatus_ != CloudMediaAssetTaskStatus::DOWNLOADING || downloadId_ != DOWNLOAD_ID_DEFAULT) { @@ -270,7 +342,7 @@ int32_t CloudMediaAssetDownloadOperation::SubmitBatchDownload( return E_ERR; } isCache_ = isCache; - if (IsDataEmpty(datas)) { + if (IsDataEmpty(data)) { MEDIA_INFO_LOG("No data need to submit."); if (!isCache_) { CancelDownloadTask(); @@ -279,35 +351,14 @@ int32_t CloudMediaAssetDownloadOperation::SubmitBatchDownload( return E_OK; } - downloadNum_ = static_cast(datas.pathVec.size()); - dataForDownload_ = datas; + downloadNum_ = static_cast(data.pathVec.size()); + dataForDownload_ = data; if (!isCache_) { - batchDownloadTotalNum_ += downloadNum_; - batchDownloadTotalSize_ += datas.batchSizeNeedDownload; + batchDownloadTotalNum_ += data.batchCountNeedDownload; + batchDownloadTotalSize_ += data.batchSizeNeedDownload; } - std::thread([this]() { - this_thread::sleep_for(chrono::milliseconds(SLEEP_FOR_LOCK)); - int32_t ret = cloudSyncManager_.get().StartFileCache(dataForDownload_.pathVec, downloadId_); - if (ret != E_OK || downloadId_ == DOWNLOAD_ID_DEFAULT) { - MEDIA_ERR_LOG("failed to StartFileCache, ret: %{public}d, downloadId_: %{public}s.", - ret, to_string(downloadId_).c_str()); - downloadId_ = DOWNLOAD_ID_DEFAULT; - downloadNum_ = 0; - cacheForDownload_ = dataForDownload_; - SetTaskStatus(Status::PAUSE_FOR_CLOUD_ERROR); - return E_ERR; - } - if (!isCache_) { - ClearData(readyForDownload_); - readyForDownload_ = ReadyDataForBatchDownload(); - } else { - ClearData(cacheForDownload_); - } - MEDIA_INFO_LOG("Success, downloadId: %{public}d, downloadNum: %{public}d, isCache: %{public}d.", - static_cast(downloadId_), static_cast(downloadNum_), static_cast(isCache_)); - return E_OK; - }).detach(); + StartBatchDownload(data.batchCountNeedDownload, data.batchSizeNeedDownload); return E_OK; } @@ -558,6 +609,7 @@ int32_t CloudMediaAssetDownloadOperation::CancelDownloadTask() void CloudMediaAssetDownloadOperation::HandleSuccessCallback(const DownloadProgressObj& progress) { + std::lock_guard lock(callbackMutex_); MediaLibraryTracer tracer; tracer.Start("HandleSuccessCallback"); if (progress.downloadId != downloadId_ || @@ -569,10 +621,12 @@ void CloudMediaAssetDownloadOperation::HandleSuccessCallback(const DownloadProgr } int64_t size = dataForDownload_.fileDownloadMap[progress.path]; - remainCount_--; - remainSize_ -= size; - hasDownloadNum_++; - hasDownloadSize_ += size; + if (size != 0) { + remainCount_--; + remainSize_ -= size; + hasDownloadNum_++; + hasDownloadSize_ += size; + } dataForDownload_.fileDownloadMap.erase(progress.path); downloadNum_--; @@ -601,8 +655,9 @@ void CloudMediaAssetDownloadOperation::HandleSuccessCallback(const DownloadProgr void CloudMediaAssetDownloadOperation::MoveDownloadFileToCache(const DownloadProgressObj& progress) { std::lock_guard lock(callbackMutex_); - if (progress.downloadId != downloadId_) { - MEDIA_ERR_LOG("This file is unknown, path: %{public}s, downloadId: %{public}s, downloadId_: %{public}s.", + if (progress.downloadId != downloadId_ || + dataForDownload_.fileDownloadMap.find(progress.path) == dataForDownload_.fileDownloadMap.end()) { + MEDIA_WARN_LOG("This file is unknown, path: %{public}s, downloadId: %{public}s, downloadId_: %{public}s.", MediaFileUtils::DesensitizePath(progress.path).c_str(), to_string(progress.downloadId).c_str(), to_string(downloadId_).c_str()); return; @@ -625,6 +680,7 @@ void CloudMediaAssetDownloadOperation::MoveDownloadFileToCache(const DownloadPro void CloudMediaAssetDownloadOperation::MoveDownloadFileToNotFound(const DownloadProgressObj& progress) { + std::lock_guard lock(callbackMutex_); if (progress.downloadId != downloadId_ || dataForDownload_.fileDownloadMap.find(progress.path) != dataForDownload_.fileDownloadMap.end()) { MEDIA_ERR_LOG("This file is known, path: %{public}s, downloadId: %{public}s, downloadId_: %{public}s.", @@ -638,8 +694,17 @@ void CloudMediaAssetDownloadOperation::MoveDownloadFileToNotFound(const Download return; } notFoundForDownload_.fileDownloadMap[progress.path] = dataForDownload_.fileDownloadMap.at(progress.path); - downloadNum_--; + int64_t size = dataForDownload_.fileDownloadMap.at(progress.path); + if (size != 0) { + totalCount_--; + batchDownloadTotalNum_--; + remainCount_--; + totalSize_ -= size; + batchDownloadTotalSize_ -= size; + remainSize_ -= size; + } dataForDownload_.fileDownloadMap.erase(progress.path); + downloadNum_--; MEDIA_INFO_LOG("success, path: %{public}s.", MediaFileUtils::DesensitizePath(progress.path).c_str()); } @@ -655,17 +720,17 @@ void CloudMediaAssetDownloadOperation::HandleFailedCallback(const DownloadProgre MediaFileUtils::DesensitizePath(progress.path).c_str()); switch (progress.downloadErrorType) { case static_cast(DownloadProgressObj::DownloadErrorType::UNKNOWN_ERROR): { - SetTaskStatus(Status::PAUSE_FOR_CLOUD_ERROR); + PauseDownloadTask(CloudMediaTaskPauseCause::CLOUD_ERROR); MoveDownloadFileToCache(progress); break; } case static_cast(DownloadProgressObj::DownloadErrorType::NETWORK_UNAVAILABLE): { - SetTaskStatus(Status::PAUSE_FOR_WIFI_UNAVAILABLE); + PauseDownloadTask(CloudMediaTaskPauseCause::WIFI_UNAVAILABLE); MoveDownloadFileToCache(progress); break; } case static_cast(DownloadProgressObj::DownloadErrorType::LOCAL_STORAGE_FULL): { - SetTaskStatus(Status::PAUSE_FOR_ROM_LIMIT); + PauseDownloadTask(CloudMediaTaskPauseCause::ROM_LIMIT); MoveDownloadFileToCache(progress); break; } @@ -674,7 +739,7 @@ void CloudMediaAssetDownloadOperation::HandleFailedCallback(const DownloadProgre break; } case static_cast(DownloadProgressObj::DownloadErrorType::FREQUENT_USER_REQUESTS): { - SetTaskStatus(Status::PAUSE_FOR_FREQUENT_USER_REQUESTS); + PauseDownloadTask(CloudMediaTaskPauseCause::FREQUENT_USER_REQUESTS); MoveDownloadFileToCache(progress); break; } diff --git a/frameworks/services/media_cloud_sync_notify_handle/include/analysis_handler.h b/frameworks/services/media_cloud_sync_notify_handle/include/analysis_handler.h index caeae3c02198cf3c2193ff42ac3f30c8ee0eb908..a06a5d7ea94a548a17c343d6224dc6ebc0f139c2 100644 --- a/frameworks/services/media_cloud_sync_notify_handle/include/analysis_handler.h +++ b/frameworks/services/media_cloud_sync_notify_handle/include/analysis_handler.h @@ -16,6 +16,8 @@ #ifndef FRAMEWORKS_SERVICES_CLOUD_SYNC_NOTIFY_HANDLE_INCLUDE_ANALYSYS_HANDLER_H #define FRAMEWORKS_SERVICES_CLOUD_SYNC_NOTIFY_HANDLE_INCLUDE_ANALYSYS_HANDLER_H +#include +#include #include #include "base_handler.h" #include "medialibrary_album_refresh.h" @@ -28,9 +30,17 @@ public: AnalysisHandler(std::function refreshAlbums = nullptr) : refreshAlbumsFunc_(refreshAlbums ? refreshAlbums : [](bool) { RefreshAlbums(true); }) {} + virtual ~AnalysisHandler(); void Handle(const CloudSyncHandleData &handleData) override; + void init() override; + static std::queue taskQueue_; + static std::mutex mtx_; + static int32_t threadId_; + static std::atomic counts_; private: + void MergeTask(const CloudSyncHandleData &handleData); + std::function refreshAlbumsFunc_; }; } //namespace Media diff --git a/frameworks/services/media_cloud_sync_notify_handle/include/base_handler.h b/frameworks/services/media_cloud_sync_notify_handle/include/base_handler.h index 4602ea95e1645f52bd0f15abcc2880a0992386ec..37b1a14e77108b35772b9dab94e4f23d30d0765b 100644 --- a/frameworks/services/media_cloud_sync_notify_handle/include/base_handler.h +++ b/frameworks/services/media_cloud_sync_notify_handle/include/base_handler.h @@ -34,6 +34,7 @@ public: public: virtual void Handle(const CloudSyncHandleData &handleData) = 0; + virtual void init() {} void SetNextHandler(const std::shared_ptr &nextHandler) { nextHandler_ = nextHandler; diff --git a/frameworks/services/media_cloud_sync_notify_handle/src/analysis_handler.cpp b/frameworks/services/media_cloud_sync_notify_handle/src/analysis_handler.cpp index 2d735ed83bec65148f964d51856aefe1fde81393..cc2e1fae2f4b89b9af2e015bda573154fe309b60 100644 --- a/frameworks/services/media_cloud_sync_notify_handle/src/analysis_handler.cpp +++ b/frameworks/services/media_cloud_sync_notify_handle/src/analysis_handler.cpp @@ -15,10 +15,13 @@ #include "analysis_handler.h" +#include "medialibrary_errno.h" +#include "medialibrary_period_worker.h" #include "medialibrary_unistore_manager.h" #include "medialibrary_rdb_utils.h" #include "photo_album_column.h" #include "photo_map_column.h" +#include "power_efficiency_manager.h" #include "result_set_utils.h" #include "vision_column.h" @@ -29,6 +32,21 @@ namespace Media { using ChangeType = DataShare::DataShareObserver::ChangeType; +std::mutex AnalysisHandler::mtx_; +queue AnalysisHandler::taskQueue_; +int32_t AnalysisHandler::threadId_{-1}; +std::atomic AnalysisHandler::counts_(0); +static constexpr uint16_t HANDLE_IDLING_TIME = 5; + +AnalysisHandler::~AnalysisHandler() +{ + auto periodWorker = MediaLibraryPeriodWorker::GetInstance(); + if (periodWorker == nullptr) { + MEDIA_ERR_LOG("failed to get period worker instance"); + } + periodWorker->CloseThreadById(AnalysisHandler::threadId_); +} + static vector GetFileIds(const CloudSyncHandleData &handleData) { vector fileIds; @@ -90,14 +108,39 @@ static void AddNewNotify(CloudSyncHandleData &handleData, const list &sendU return; } -void AnalysisHandler::Handle(const CloudSyncHandleData &handleData) +static int32_t GetHandleData(CloudSyncHandleData &handleData) { + lock_guard lockGuard(AnalysisHandler::mtx_); + if (AnalysisHandler::taskQueue_.empty()) { + ++AnalysisHandler::counts_; + if (AnalysisHandler::counts_.load() > HANDLE_IDLING_TIME) { + auto periodWorker = MediaLibraryPeriodWorker::GetInstance(); + if (periodWorker == nullptr) { + MEDIA_ERR_LOG("failed to get period worker instance"); + return E_ERR; + } + periodWorker->CloseThreadById(AnalysisHandler::threadId_); + } + return E_ERR; + } else { + AnalysisHandler::counts_.store(0); + handleData = AnalysisHandler::taskQueue_.front(); + AnalysisHandler::taskQueue_.pop(); + } + return E_OK; +} + +static void ProcessHandleData(shared_ptr &handle, function &refreshAlbumsFunc) +{ + CloudSyncHandleData handleData; + if (GetHandleData(handleData) != E_OK) { + return; + } auto rdbStore = MediaLibraryUnistoreManager::GetInstance().GetRdbStore(); if (rdbStore == nullptr) { MEDIA_ERR_LOG("Can not get rdbstore"); return; } - vector fileIds; if (handleData.orgInfo.type == ChangeType::OTHER) { MEDIA_INFO_LOG("Update the AnalysisAlbum for ChangeType being OTHER"); @@ -128,11 +171,72 @@ void AnalysisHandler::Handle(const CloudSyncHandleData &handleData) string uriString = newHandleData.orgInfo.uris.front().ToString(); MEDIA_INFO_LOG("refresh: %{public}s, type: %{public}d", uriString.c_str(), static_cast(newHandleData.orgInfo.type)); - refreshAlbumsFunc_(true); + refreshAlbumsFunc(true); + } + if (handle != nullptr) { + handle->Handle(newHandleData); + } +} + +void AnalysisHandler::init() +{ + if (AnalysisHandler::threadId_ != E_ERR) { + return; } + auto periodWorker = MediaLibraryPeriodWorker::GetInstance(); + if (periodWorker == nullptr) { + MEDIA_ERR_LOG("failed to get period worker instance"); + return; + } + auto periodTask = make_shared(ProcessHandleData, + PowerEfficiencyManager::GetAlbumUpdateInterval()); + AnalysisHandler::threadId_ = periodWorker->AddTask(periodTask, nextHandler_, refreshAlbumsFunc_); + if (AnalysisHandler::threadId_ == E_ERR) { + MEDIA_ERR_LOG("failed to add task"); + return; + } + return; +} - if (nextHandler_ != nullptr) { - nextHandler_->Handle(newHandleData); +void AnalysisHandler::MergeTask(const CloudSyncHandleData &handleData) +{ + lock_guard lockGuard(AnalysisHandler::mtx_); + if (AnalysisHandler::taskQueue_.empty()) { + AnalysisHandler::taskQueue_.push(handleData); + return; + } + CloudSyncHandleData &tempHandleData = AnalysisHandler::taskQueue_.front(); + if (tempHandleData.orgInfo.type == ChangeType::OTHER) { + return; + } else { + for (auto info : handleData.notifyInfo) { + auto it = tempHandleData.notifyInfo.find(info.first); + if (it != tempHandleData.notifyInfo.end()) { + tempHandleData.notifyInfo[info.first].splice( + tempHandleData.notifyInfo[info.first].end(), info.second); + } else { + tempHandleData.notifyInfo[info.first] = info.second; + } + } + } +} + +void AnalysisHandler::Handle(const CloudSyncHandleData &handleData) +{ + MergeTask(handleData); + auto periodWorker = MediaLibraryPeriodWorker::GetInstance(); + if (periodWorker == nullptr) { + MEDIA_ERR_LOG("failed to get period worker instance"); + return; + } + if (!periodWorker->IsThreadRunning(AnalysisHandler::threadId_)) { + auto periodTask = make_shared(ProcessHandleData, + PowerEfficiencyManager::GetAlbumUpdateInterval()); + AnalysisHandler::threadId_ = periodWorker->AddTask(periodTask, nextHandler_, refreshAlbumsFunc_); + if (AnalysisHandler::threadId_ == E_ERR) { + MEDIA_ERR_LOG("failed to add task"); + return; + } } } } //namespace Media diff --git a/frameworks/services/media_cloud_sync_notify_handle/src/notify_responsibility_chain_factory.cpp b/frameworks/services/media_cloud_sync_notify_handle/src/notify_responsibility_chain_factory.cpp index 0b90c4abf5eea27054bd30dab03b884592b2c863..c69e904836b6fa1c76b7060b63337c19aca913b5 100644 --- a/frameworks/services/media_cloud_sync_notify_handle/src/notify_responsibility_chain_factory.cpp +++ b/frameworks/services/media_cloud_sync_notify_handle/src/notify_responsibility_chain_factory.cpp @@ -47,6 +47,7 @@ shared_ptr NotifyResponsibilityChainFactory::CreateChain(const Chai shared_ptr preHandler = nullptr; for (const auto& handler : handlerList) { + handler->init(); if (preHandler != nullptr) { preHandler->SetNextHandler(handler); } diff --git a/frameworks/services/media_mtp/BUILD.gn b/frameworks/services/media_mtp/BUILD.gn index ad508bd44a7b3fc323d4eba01cc1a8e2090955e3..6873f3ef51547f9be1708ea5576f2debd3ab34bb 100644 --- a/frameworks/services/media_mtp/BUILD.gn +++ b/frameworks/services/media_mtp/BUILD.gn @@ -78,6 +78,7 @@ if (defined(medialibrary_mtp_enable)) { "src/payload_data/set_object_prop_value_data.cpp", "src/payload_data/set_object_references_data.cpp", "src/property.cpp", + "src/ptp_album_handles.cpp", "src/ptp_media_sync_observer.cpp", "src/storage.cpp", ] diff --git a/frameworks/services/media_mtp/include/mtp_data_utils.h b/frameworks/services/media_mtp/include/mtp_data_utils.h index ed8aae9ab3cf07f42a0ebec2566c034aabff8beb..7e3af10ed2256a04d3f783607c721e5722079ab3 100755 --- a/frameworks/services/media_mtp/include/mtp_data_utils.h +++ b/frameworks/services/media_mtp/include/mtp_data_utils.h @@ -51,6 +51,25 @@ const std::string MTP_FORMAT_MPEG = ".mpeg"; // MPEG video files const std::string MTP_FORMAT_ASF = ".asf"; // ASF files // Unknown image files which are not specified in PTP specification const std::string MTP_FORMAT_DEFINED = ".image"; // Unknown image files +const std::string MTP_FORMAT_HEIC = ".heic"; // HEIC image files +const std::string MTP_FORMAT_HEICS = ".heics"; // HEICS image files +const std::string MTP_FORMAT_HEIFS = ".heifs"; // HEIFS image files +const std::string MTP_FORMAT_BM = ".bm"; // BM image files +const std::string MTP_FORMAT_HEIF = ".heif"; // HEIF image files +const std::string MTP_FORMAT_HIF = ".hif"; // HIF image files +const std::string MTP_FORMAT_AVIF = ".avif"; // AVIF image files +const std::string MTP_FORMAT_CUR = ".cur"; // CUR image files +const std::string MTP_FORMAT_WEBP = ".webp"; // WEBP image files +const std::string MTP_FORMAT_DNG = ".dng"; // DNG image files +const std::string MTP_FORMAT_RAF = ".raf"; // RAF image files +const std::string MTP_FORMAT_ICO = ".ico"; // ICO image files +const std::string MTP_FORMAT_NRW = ".nrw"; // NRW image files +const std::string MTP_FORMAT_RW2 = ".rw2"; // RW2 image files +const std::string MTP_FORMAT_PEF = ".pef"; // PEF image files +const std::string MTP_FORMAT_SRW = ".srw"; // SRW image files +const std::string MTP_FORMAT_ARW = ".arw"; // ARW image files +const std::string MTP_FORMAT_SVG = ".svg"; // SVG image files +const std::string MTP_FORMAT_RAW = ".raw"; // RAW image files const std::string MTP_FORMAT_EXIF_JPEG = ".jpeg?.jpg"; // JPEG image files const std::string MTP_FORMAT_JPEG = ".jpeg"; const std::string MTP_FORMAT_JPG = ".jpg"; @@ -80,7 +99,33 @@ const std::string MTP_FORMAT_WMV = ".wmv"; // WMV video files const std::string MTP_FORMAT_MP4_CONTAINER = ".mp4"; // MP4 files const std::string MTP_FORMAT_MP2 = ".mp2"; // MP2 files const std::string MTP_FORMAT_3GP_CONTAINER = ".3gp"; // 3GP files - +const std::string MTP_FORMAT_3GPP2 = ".3gpp2"; // 3GPP2 files +const std::string MTP_FORMAT_3GP2 = ".3gp2"; // 3GP2 files +const std::string MTP_FORMAT_3G2 = ".3g2"; // 3G2 files +const std::string MTP_FORMAT_3GPP = ".3gpp"; // 3GPP files +const std::string MTP_FORMAT_M4V = ".m4v"; // M4V files +const std::string MTP_FORMAT_F4V = ".f4v"; // F4V files +const std::string MTP_FORMAT_MP4V = ".mp4v"; // MP4V files +const std::string MTP_FORMAT_MPEG4 = ".mpeg4"; // MPEG4 files +const std::string MTP_FORMAT_M2TS = ".m2ts"; // M2TS files +const std::string MTP_FORMAT_MTS = ".mts"; // MTS files +const std::string MTP_FORMAT_TS = ".ts"; // TS files +const std::string MTP_FORMAT_YT = ".yt"; // YT files +const std::string MTP_FORMAT_WRF = ".wrf"; // WRF files +const std::string MTP_FORMAT_MPEG2 = ".mpeg2"; // MPEG2 files +const std::string MTP_FORMAT_MPV2 = ".mpv2"; // MPV2 files +const std::string MTP_FORMAT_MP2V = ".mp2v"; // MP2V files +const std::string MTP_FORMAT_M2V = ".m2v"; // M2V files +const std::string MTP_FORMAT_M2T = ".m2t"; // M2T files +const std::string MTP_FORMAT_MPEG1 = ".mpeg1"; // MPEG1 files +const std::string MTP_FORMAT_MPV1 = ".mpv1"; // MPV1 files +const std::string MTP_FORMAT_MP1V = ".mp1v"; // MP1V files +const std::string MTP_FORMAT_M1V = ".m1v"; // M1V files +const std::string MTP_FORMAT_MPG = ".mpg"; // MPG files +const std::string MTP_FORMAT_MOV = ".mov"; // MOV files +const std::string MTP_FORMAT_MKV = ".mkv"; // MKV files +const std::string MTP_FORMAT_WEBM = ".webm"; // WEBM files +const std::string MTP_FORMAT_H264 = ".h264"; // H264 files const std::string MTP_FORMAT_UNDEFINED_COLLECTION = ".undefinedcollections"; // undefined collections const std::string MTP_FORMAT_ABSTRACT_MULTIMEDIA_ALBUM = ".album"; // multimedia albums const std::string MTP_FORMAT_ABSTRACT_IMAGE_ALBUM = ".albumimage"; // image albums diff --git a/frameworks/services/media_mtp/include/ptp_album_handles.h b/frameworks/services/media_mtp/include/ptp_album_handles.h new file mode 100644 index 0000000000000000000000000000000000000000..03f12c807cafd39b566190d77cd7f23cb413e0fc --- /dev/null +++ b/frameworks/services/media_mtp/include/ptp_album_handles.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 FRAMEWORKS_SERVICES_MEDIA_MTP_INCLUDE_PTP_ALBUM_HANDLES_H_ +#define FRAMEWORKS_SERVICES_MEDIA_MTP_INCLUDE_PTP_ALBUM_HANDLES_H_ + +#include +#include +#include +#include +#include + +#include "datashare_result_set.h" +#include "parcel.h" + +namespace OHOS { +namespace Media { +class PtpAlbumHandles { +public: + PtpAlbumHandles() {} + ~PtpAlbumHandles(); + PtpAlbumHandles(const PtpAlbumHandles&) = delete; + PtpAlbumHandles(PtpAlbumHandles&&) = delete; + PtpAlbumHandles& operator=(const PtpAlbumHandles&) = delete; + PtpAlbumHandles& operator=(PtpAlbumHandles&&) = delete; + static std::shared_ptr GetInstance(); + + void AddHandle(int32_t value); + void RemoveHandle(int32_t value); + void AddAlbumHandles(const std::shared_ptr &resultSet); + bool FindHandle(int32_t value); + int32_t ChangeHandle(const std::shared_ptr &resultSet); + +private: + std::vector dataHandles_; + static std::mutex mutex_; + static std::shared_ptr instance_; +}; +} // namespace Media +} // namespace OHOS +#endif // FRAMEWORKS_SERVICES_MEDIA_MTP_INCLUDE_PTP_ALBUM_HANDLES_H_ \ No newline at end of file diff --git a/frameworks/services/media_mtp/include/ptp_media_sync_observer.h b/frameworks/services/media_mtp/include/ptp_media_sync_observer.h index 230782d11a672eaf9f68ef232d2b9383d8749883..488fde0a2858aa7402ccc2fcadad344a76ac5707 100644 --- a/frameworks/services/media_mtp/include/ptp_media_sync_observer.h +++ b/frameworks/services/media_mtp/include/ptp_media_sync_observer.h @@ -41,11 +41,17 @@ public: void OnChange(const ChangeInfo &changeInfo) override; std::shared_ptr context_ = nullptr; std::shared_ptr dataShareHelper_ = nullptr; + void OnChangeEx(const ChangeInfo &changeInfo); private: void SendEventPackets(uint32_t objectHandle, uint16_t eventCode); void SendEventPacketAlbum(uint32_t objectHandle, uint16_t eventCode); void SendPhotoEvent(ChangeType changeType, std::string suffixString); std::vector GetHandlesFromPhotosInfoBurstKeys(int32_t handle); + void SendEventToPTP(int32_t suff_int, ChangeType changeType); + std::vector GetAllDeleteHandles(); + std::shared_ptr GetAlbumInfo(); + std::vector GetAddEditPhotoHandles(int32_t handle); + void AddMovingPhotoHandle(int32_t handle); }; class MediaSyncNotifyData : public AsyncTaskData { diff --git a/frameworks/services/media_mtp/src/mtp_data_utils.cpp b/frameworks/services/media_mtp/src/mtp_data_utils.cpp index 88c97f43d74970183940d4dad4c3d9f95d95fe49..24dcdc9396fbb91ace28dd02a3d47975a99c8b44 100755 --- a/frameworks/services/media_mtp/src/mtp_data_utils.cpp +++ b/frameworks/services/media_mtp/src/mtp_data_utils.cpp @@ -60,7 +60,7 @@ static const map FormatMap = { { MTP_FORMAT_HTML_CODE, MTP_FORMAT_HTML }, { MTP_FORMAT_MP3_CODE, MTP_FORMAT_MP3 }, { MTP_FORMAT_AVI_CODE, MTP_FORMAT_AVI }, - { MTP_FORMAT_MPEG_CODE, MTP_FORMAT_ASF }, + { MTP_FORMAT_MPEG_CODE, MTP_FORMAT_MPEG }, // image files... { MTP_FORMAT_DEFINED_CODE, MTP_FORMAT_DEFINED }, { MTP_FORMAT_EXIF_JPEG_CODE, MTP_FORMAT_EXIF_JPEG }, @@ -124,6 +124,58 @@ static const map FormatMap = { { MTP_FORMAT_VCARD_2_CODE, MTP_FORMAT_VCARD_2 } }; +static const set UndefinedImageFormatSet = { + MTP_FORMAT_HEIC, + MTP_FORMAT_HEICS, + MTP_FORMAT_HEIFS, + MTP_FORMAT_BM, + MTP_FORMAT_HEIF, + MTP_FORMAT_HIF, + MTP_FORMAT_AVIF, + MTP_FORMAT_CUR, + MTP_FORMAT_WEBP, + MTP_FORMAT_DNG, + MTP_FORMAT_RAF, + MTP_FORMAT_ICO, + MTP_FORMAT_NRW, + MTP_FORMAT_RW2, + MTP_FORMAT_PEF, + MTP_FORMAT_SRW, + MTP_FORMAT_ARW, + MTP_FORMAT_SVG, + MTP_FORMAT_RAW +}; + +static const set UndefinedVideoFormatSet = { + MTP_FORMAT_3GPP2, + MTP_FORMAT_3GP2, + MTP_FORMAT_3G2, + MTP_FORMAT_3GPP, + MTP_FORMAT_M4V, + MTP_FORMAT_F4V, + MTP_FORMAT_MP4V, + MTP_FORMAT_MPEG4, + MTP_FORMAT_M2TS, + MTP_FORMAT_MTS, + MTP_FORMAT_TS, + MTP_FORMAT_YT, + MTP_FORMAT_WRF, + MTP_FORMAT_MPEG2, + MTP_FORMAT_MPV2, + MTP_FORMAT_MP2V, + MTP_FORMAT_M2V, + MTP_FORMAT_M2T, + MTP_FORMAT_MPEG1, + MTP_FORMAT_MPV1, + MTP_FORMAT_MP1V, + MTP_FORMAT_M1V, + MTP_FORMAT_MPG, + MTP_FORMAT_MOV, + MTP_FORMAT_MKV, + MTP_FORMAT_WEBM, + MTP_FORMAT_H264 +}; + static const map FormatAllMap = { { MTP_FORMAT_ALL, MEDIA_TYPE_ALL }, { MTP_FORMAT_ABSTRACT_AUDIO_PLAYLIST, MEDIA_TYPE_AUDIO }, @@ -573,10 +625,11 @@ void MtpDataUtils::SetOneDefaultlPropList(uint32_t handle, uint16_t property, sh int32_t MtpDataUtils::GetMediaTypeByName(std::string &displayName, MediaType &outMediaType) { - size_t displayNameIndex = displayName.find("."); + size_t displayNameIndex = displayName.find_last_of('.'); std::string extension; if (displayNameIndex != std::string::npos) { extension = displayName.substr(displayNameIndex); + transform(extension.begin(), extension.end(), extension.begin(), ::tolower); } else { MEDIA_ERR_LOG("is dir displayName"); outMediaType = MEDIA_TYPE_ALBUM; @@ -591,7 +644,13 @@ int32_t MtpDataUtils::GetMediaTypeByName(std::string &displayName, MediaType &ou format = MTP_FORMAT_UNDEFINED_CODE; } } + if (UndefinedImageFormatSet.find(extension) != UndefinedImageFormatSet.end()) { + format = MTP_FORMAT_DEFINED_CODE; + } else if (UndefinedVideoFormatSet.find(extension) != UndefinedVideoFormatSet.end()) { + format = MTP_FORMAT_UNDEFINED_VIDEO_CODE; + } GetMediaTypeByformat(format, outMediaType); + MEDIA_DEBUG_LOG("GetMediaTypeByName format:%{public}x, outMediaType:%{public}d", format, outMediaType); return E_SUCCESS; } diff --git a/frameworks/services/media_mtp/src/mtp_global.cpp b/frameworks/services/media_mtp/src/mtp_global.cpp index b8cb778b17247cd4af832b88fa4207a291e49e58..25ecb73af75cc1eae15adbe16c71a37e16419efe 100644 --- a/frameworks/services/media_mtp/src/mtp_global.cpp +++ b/frameworks/services/media_mtp/src/mtp_global.cpp @@ -21,7 +21,7 @@ bool MtpGlobal::isBlock_ = true; bool MtpGlobal::IsBlocked() { - return false; + return isBlock_; } void MtpGlobal::ReleaseBlock() diff --git a/frameworks/services/media_mtp/src/mtp_medialibrary_manager.cpp b/frameworks/services/media_mtp/src/mtp_medialibrary_manager.cpp index 0277aab2ff7e46d2170a1df95f55518f7cd0311f..da843401f352ca3904939383ea8f6cb527d1fd08 100644 --- a/frameworks/services/media_mtp/src/mtp_medialibrary_manager.cpp +++ b/frameworks/services/media_mtp/src/mtp_medialibrary_manager.cpp @@ -36,6 +36,7 @@ #include "photo_album_column.h" #include "ptp_media_sync_observer.h" #include "pixel_map.h" +#include "ptp_album_handles.h" #include "ptp_medialibrary_manager_uri.h" #include "system_ability_definition.h" #include "userfilemgr_uri.h" @@ -302,6 +303,10 @@ int32_t MtpMedialibraryManager::GetHandles(const shared_ptr shared_ptr resultSet; if (context->parent == PARENT_ID) { resultSet = GetAlbumInfo(context, true); + auto albumHandles = PtpAlbumHandles::GetInstance(); + if (albumHandles != nullptr) { + albumHandles->AddAlbumHandles(resultSet); + } } else { resultSet = GetPhotosInfo(context, true); } @@ -383,7 +388,7 @@ int32_t MtpMedialibraryManager::SetObjectInfo(const unique_ptr &fileA { CHECK_AND_RETURN_RET_LOG(outObjectInfo != nullptr, MtpErrorUtils::SolveGetObjectInfoError(E_HAS_DB_ERROR), "outObjectInfo is nullptr"); - outObjectInfo->handle = fileAsset->GetId(); + outObjectInfo->handle = static_cast(fileAsset->GetId()); outObjectInfo->name = fileAsset->GetDisplayName(); outObjectInfo->size = static_cast(fileAsset->GetSize()); // need support larger than 4GB file outObjectInfo->parent = static_cast(fileAsset->GetParent()); @@ -435,14 +440,12 @@ int32_t MtpMedialibraryManager::GetFd(const shared_ptr &con shared_ptr resultSet = GetPhotosInfo(context, false); CHECK_AND_RETURN_RET_LOG(resultSet != nullptr, MtpErrorUtils::SolveGetFdError(E_HAS_DB_ERROR), "fail to get handles"); - CHECK_AND_RETURN_RET_LOG(resultSet->GoToFirstRow() == NativeRdb::E_OK, - MtpErrorUtils::SolveGetFdError(E_SUCCESS), "fail to get fd"); std::string sourcePath; - while (resultSet->GoToNextRow() == NativeRdb::E_OK) { + do { string data = GetStringVal(MediaColumn::MEDIA_FILE_PATH, resultSet); int32_t subtype = GetInt32Val(PhotoColumn::PHOTO_SUBTYPE, resultSet); sourcePath = MtpDataUtils::GetMovingOrEnditSourcePath(data, subtype, context); - } + } while (!resultSet->GoToNextRow()); std::string realPath; PathToRealPath(sourcePath, realPath); MEDIA_INFO_LOG("mtp GetFd realPath %{public}s", realPath.c_str()); @@ -467,6 +470,10 @@ bool MtpMedialibraryManager::CompressImage(std::unique_ptr &pixelMap, .alphaType = AlphaType::IMAGE_ALPHA_TYPE_UNPREMUL }; unique_ptr compressImage = PixelMap::Create(*pixelMap, opts); + if (compressImage == nullptr) { + MEDIA_ERR_LOG("Failed to Create and compressImage is nullptr"); + return false; + } PackOption option = { .format = THUMBNAIL_FORMAT, @@ -621,10 +628,6 @@ int32_t MtpMedialibraryManager::GetAssetById(const int32_t id, shared_ptr whereArgs = {to_string(field_id)}; - predicates.NotEqualTo(PhotoColumn::PHOTO_POSITION, POSITION); - predicates.EqualTo(MediaColumn::MEDIA_DATE_TRASHED, "0"); - predicates.EqualTo(MediaColumn::MEDIA_TIME_PENDING, "0"); - predicates.EqualTo(MediaColumn::MEDIA_HIDDEN, "0"); predicates.SetWhereClause(whereClause); predicates.SetWhereArgs(whereArgs); Uri uri(PAH_QUERY_PHOTO); @@ -687,8 +690,8 @@ int32_t MtpMedialibraryManager::SendObjectInfo(const std::shared_ptrformat, mediaType); - CHECK_AND_RETURN_RET_LOG(errCode == MTP_SUCCESS, errCode, "fail to SolveSendObjectFormatData"); + int errCode = MtpDataUtils::GetMediaTypeByName(context->name, mediaType); + CHECK_AND_RETURN_RET_LOG(errCode == MTP_SUCCESS, errCode, "fail to GetMediaTypeByName"); if ((mediaType != MEDIA_TYPE_IMAGE && mediaType != MEDIA_TYPE_VIDEO) || context->parent == uint32_t(-1)) { MEDIA_ERR_LOG("file type not support"); return MTP_ERROR_INVALID_OBJECTHANDLE; diff --git a/frameworks/services/media_mtp/src/mtp_operation_utils.cpp b/frameworks/services/media_mtp/src/mtp_operation_utils.cpp index b9a3e7f312222c1f3b0d08cc89461c19388ac116..76bf6eb304d234101f8f444c7a592347f4edfeeb 100755 --- a/frameworks/services/media_mtp/src/mtp_operation_utils.cpp +++ b/frameworks/services/media_mtp/src/mtp_operation_utils.cpp @@ -82,6 +82,8 @@ static constexpr int RECEVIE_OBJECT_FAILED = -17; static constexpr uint32_t HEADER_LEN = 12; static constexpr uint32_t READ_LEN = 1024; +static constexpr uint32_t SEND_OBJECT_FILE_MAX_SIZE = 0xFFFFFFFF; + MtpOperationUtils::MtpOperationUtils(const shared_ptr &context) : context_(context) { auto saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); @@ -457,7 +459,12 @@ int32_t MtpOperationUtils::DoRecevieSendObject() MtpFileRange object; object.fd = fd; object.offset = initialData; - object.length = static_cast(context_->sendObjectFileSize) - static_cast(initialData); + if (context_->sendObjectFileSize == SEND_OBJECT_FILE_MAX_SIZE) { + // when file size is over 0xFFFFFFFF, driver will read until it receives a short packet + object.length = SEND_OBJECT_FILE_MAX_SIZE; + } else { + object.length = static_cast(context_->sendObjectFileSize) - static_cast(initialData); + } errorCode = RecevieSendObject(object, fd); if (errorCode == MTP_ERROR_TRANSFER_CANCELLED) { MEDIA_DEBUG_LOG("DoRecevieSendObject ReceiveObj Cancelled = %{public}d", MTP_ERROR_TRANSFER_CANCELLED); diff --git a/frameworks/services/media_mtp/src/ptp_album_handles.cpp b/frameworks/services/media_mtp/src/ptp_album_handles.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c3ba8650438d174696bac188b5fc61bb905ab40 --- /dev/null +++ b/frameworks/services/media_mtp/src/ptp_album_handles.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 "ptp_album_handles.h" + +#include "datashare_predicates.h" +#include "datashare_abs_result_set.h" +#include "media_column.h" +#include "media_log.h" +#include "medialibrary_errno.h" +#include "result_set_utils.h" + +namespace OHOS { +namespace Media { +using namespace std; +std::shared_ptr PtpAlbumHandles::instance_ = nullptr; +std::mutex PtpAlbumHandles::mutex_; + +std::shared_ptr PtpAlbumHandles::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock(mutex_); + if (instance_ == nullptr) { + instance_ = std::make_shared(); + } + } + return instance_; +} + +PtpAlbumHandles::~PtpAlbumHandles() +{ + std::lock_guard lock(mutex_); + dataHandles_.clear(); +} + +void PtpAlbumHandles::AddHandle(int32_t value) +{ + std::lock_guard lock(mutex_); + auto iter = std::find(dataHandles_.begin(), dataHandles_.end(), value); + if (iter == dataHandles_.end()) { + dataHandles_.push_back(value); + } +} + +void PtpAlbumHandles::RemoveHandle(int32_t value) +{ + std::lock_guard lock(mutex_); + auto iter = std::find(dataHandles_.begin(), dataHandles_.end(), value); + if (iter != dataHandles_.end()) { + dataHandles_.erase(iter); + } +} + +void PtpAlbumHandles::AddAlbumHandles(const std::shared_ptr &resultSet) +{ + if (resultSet == nullptr) { + MEDIA_ERR_LOG("resultSet is nullptr"); + return; + } + std::lock_guard lock(mutex_); + dataHandles_.clear(); + while (resultSet->GoToNextRow() == NativeRdb::E_OK) { + int32_t id = GetInt32Val(MediaColumn::MEDIA_ID, resultSet); + dataHandles_.push_back(id); + } + resultSet->GoToFirstRow(); +} + +bool PtpAlbumHandles::FindHandle(int32_t value) +{ + std::lock_guard lock(mutex_); + auto iter = std::find(dataHandles_.begin(), dataHandles_.end(), value); + return iter != dataHandles_.end(); +} + +int32_t PtpAlbumHandles::ChangeHandle(const std::shared_ptr &resultSet) +{ + if (resultSet == nullptr) { + MEDIA_ERR_LOG("resultSet is nullptr"); + return E_ERR; + } + std::vector data; + do { + int32_t id = GetInt32Val(MediaColumn::MEDIA_ID, resultSet); + data.push_back(id); + } while (!resultSet->GoToNextRow()); + + std::lock_guard lock(mutex_); + for (auto value : dataHandles_) { + auto iter = std::find(data.begin(), data.end(), value); + if (iter == data.end()) { + return value; + } + } + MEDIA_ERR_LOG("no data handle to remove"); + return E_ERR; +} +} // namespace Media +} // namespace OHOS diff --git a/frameworks/services/media_mtp/src/ptp_media_sync_observer.cpp b/frameworks/services/media_mtp/src/ptp_media_sync_observer.cpp index 341ef3d8b6273e35b8d58bdbaaec097770b6507c..db614d2425d063574900f9634f834abd023853ca 100644 --- a/frameworks/services/media_mtp/src/ptp_media_sync_observer.cpp +++ b/frameworks/services/media_mtp/src/ptp_media_sync_observer.cpp @@ -14,11 +14,13 @@ */ #include "media_log.h" +#include "ptp_album_handles.h" #include "ptp_media_sync_observer.h" #include "photo_album_column.h" #include "datashare_predicates.h" #include "datashare_abs_result_set.h" #include "result_set_utils.h" +#include using namespace std; @@ -28,6 +30,8 @@ constexpr int32_t RESERVE_ALBUM = 10; constexpr int32_t PARENT_ID = 0; const string BURST_COVER_LEVEL = "1"; const string BURST_NOT_COVER_LEVEL = "2"; +const string IS_LOCAL = "2"; +const std::string HIDDEN_ALBUM = ".hiddenAlbum"; bool startsWith(const std::string& str, const std::string& prefix) { if (prefix.size() > str.size() || prefix.empty() || str.empty()) { @@ -72,7 +76,7 @@ void MediaSyncObserver::SendEventPacketAlbum(uint32_t objectHandle, uint16_t eve MtpPacketTool::PutUInt32(outBuffer, objectHandle); event.data = outBuffer; - MEDIA_DEBUG_LOG("MtpMediaLibrary album [%{public}d]", objectHandle); + MEDIA_INFO_LOG("MtpMediaLibrary album [%{public}d]", objectHandle); CHECK_AND_RETURN_LOG(context_ != nullptr, "Mtp Ptp context is nullptr"); CHECK_AND_RETURN_LOG(context_->mtpDriver != nullptr, "Mtp Ptp mtpDriver is nullptr"); context_->mtpDriver->WriteEvent(event); @@ -122,43 +126,130 @@ vector MediaSyncObserver::GetHandlesFromPhotosInfoBurstKeys(int32_t han return handlesResult; } -void MediaSyncObserver::SendPhotoEvent(ChangeType changeType, string suffixString) +vector MediaSyncObserver::GetAllDeleteHandles() { - if (stoi(suffixString) <= 0) { + vector handlesResult; + if (dataShareHelper_ == nullptr) { + MEDIA_ERR_LOG("MtpMedialibraryManager::GetAllDeleteHandles fail to get datasharehelper"); + return handlesResult; + } + Uri uri(PAH_QUERY_PHOTO); + vector columns; + columns.push_back(MediaColumn::MEDIA_ID); + DataShare::DataSharePredicates predicates; + auto now = std::chrono::system_clock::now(); + auto now_seconds = std::chrono::duration_cast(now.time_since_epoch()).count(); + auto new_timestamp = now_seconds - 5; + predicates.GreaterThan(MediaColumn::MEDIA_DATE_TRASHED, to_string(new_timestamp)); + shared_ptr resultSet = dataShareHelper_->Query(uri, predicates, columns); + + CHECK_AND_RETURN_RET_LOG(resultSet != nullptr, + handlesResult, "MtpMedialibraryManager fail to get PHOTO_ALL_DELETE_KEY"); + CHECK_AND_RETURN_RET_LOG(resultSet->GoToFirstRow() == NativeRdb::E_OK, + handlesResult, "MtpMedialibraryManager have no PHOTO_ALL_DELETE_KEY"); + do { + string file_id = GetStringVal(PhotoColumn::MEDIA_ID, resultSet); + handlesResult.push_back(stoi(file_id)); + } while (resultSet->GoToNextRow()==NativeRdb::E_OK); + return handlesResult; +} + +void MediaSyncObserver::AddMovingPhotoHandle(int32_t handle) +{ + if (dataShareHelper_ == nullptr) { + MEDIA_ERR_LOG("MtpMedialibraryManager::GetAllAddHandles fail to get datasharehelper"); return; } Uri uri(PAH_QUERY_PHOTO); vector columns; DataShare::DataSharePredicates predicates; shared_ptr resultSet; + columns.push_back(MediaColumn::MEDIA_ID); + predicates.EqualTo(MediaColumn::MEDIA_ID, to_string(handle)); + predicates.EqualTo(PhotoColumn::PHOTO_SUBTYPE, to_string(static_cast(PhotoSubType::MOVING_PHOTO))); + CHECK_AND_RETURN_LOG(dataShareHelper_ != nullptr, "Mtp AddMovingPhotoHandle dataShareHelper_ is nullptr"); + resultSet = dataShareHelper_->Query(uri, predicates, columns); + CHECK_AND_RETURN_LOG(resultSet != nullptr, "Mtp AddMovingPhotoHandle fail to get handles"); + if (resultSet->GoToFirstRow() == NativeRdb::E_OK) { + SendEventPackets(handle + COMMON_MOVING_OFFSET, MTP_EVENT_OBJECT_ADDED_CODE); + } +} + +vector MediaSyncObserver::GetAddEditPhotoHandles(int32_t handle) +{ + vector handlesResult; + if (dataShareHelper_ == nullptr) { + MEDIA_ERR_LOG("MtpMedialibraryManager::GetAddEditPhotoHandles fail to get datasharehelper"); + return handlesResult; + } + Uri uri(PAH_QUERY_PHOTO); + vector columns; + DataShare::DataSharePredicates predicates; + columns.push_back(PhotoColumn::PHOTO_SUBTYPE); + predicates.EqualTo(MediaColumn::MEDIA_ID, to_string(handle)); + shared_ptr resultSet = dataShareHelper_->Query(uri, predicates, columns); + + CHECK_AND_RETURN_RET_LOG(resultSet != nullptr, + handlesResult, "Mtp GetAddEditPhotoHandles fail to get PHOTO_ALL_DELETE_KEY"); + CHECK_AND_RETURN_RET_LOG(resultSet->GoToFirstRow() == NativeRdb::E_OK, + handlesResult, "Mtp GetAddEditPhotoHandles have no PHOTO_ALL_DELETE_KEY"); + do { + int32_t subtype = GetInt32Val(PhotoColumn::PHOTO_SUBTYPE, resultSet); + if (subtype == static_cast(PhotoSubType::MOVING_PHOTO)) { + handlesResult.push_back(handle + EDITED_PHOTOS_OFFSET); + } else { + handlesResult.push_back(handle + EDITED_PHOTOS_OFFSET); + handlesResult.push_back(handle + EDITED_MOVING_OFFSET); + } + } while (resultSet->GoToNextRow()==NativeRdb::E_OK); + return handlesResult; +} + +void MediaSyncObserver::SendPhotoEvent(ChangeType changeType, string suffixString) +{ + if (!suffixString.empty() && stoi(suffixString) <= 0) { + return; + } + vector editHandles; + vector allDeletedHandles; vector handles; switch (changeType) { case static_cast(NotifyType::NOTIFY_ADD): - MEDIA_DEBUG_LOG("MtpMediaLibrary PHOTO ADD"); + MEDIA_INFO_LOG("MtpMediaLibrary PHOTO ADD"); SendEventPackets(stoi(suffixString) + COMMON_PHOTOS_OFFSET, MTP_EVENT_OBJECT_ADDED_CODE); - columns.push_back(MediaColumn::MEDIA_NAME); - predicates.EqualTo(PhotoColumn::MEDIA_ID, to_string(stoi(suffixString))); - predicates.EqualTo(PhotoColumn::PHOTO_SUBTYPE, to_string(static_cast(PhotoSubType::MOVING_PHOTO))); - CHECK_AND_RETURN_LOG(dataShareHelper_ != nullptr, "Mtp dataShareHelper_ is nullptr"); - resultSet = dataShareHelper_->Query(uri, predicates, columns); - CHECK_AND_RETURN_LOG(resultSet != nullptr, "Mtp fail to get handles"); - if (resultSet->GoToFirstRow() == NativeRdb::E_OK) { - SendEventPackets(stoi(suffixString) + COMMON_MOVING_OFFSET, MTP_EVENT_OBJECT_ADDED_CODE); - } + AddMovingPhotoHandle(stoi(suffixString)); break; case static_cast(NotifyType::NOTIFY_UPDATE): - MEDIA_DEBUG_LOG("MtpMediaLibrary PHOTO UPDATE"); + MEDIA_INFO_LOG("MtpMediaLibrary PHOTO UPDATE"); SendEventPackets(stoi(suffixString) + COMMON_PHOTOS_OFFSET, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + editHandles = GetAddEditPhotoHandles(stoi(suffixString)); + for (const auto editHandle : editHandles) { + SendEventPackets(editHandle, MTP_EVENT_OBJECT_ADDED_CODE); + } break; case static_cast(NotifyType::NOTIFY_REMOVE): - MEDIA_DEBUG_LOG("MtpMediaLibrary PHOTO REMOVE"); - SendEventPackets(stoi(suffixString) + COMMON_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); - SendEventPackets(stoi(suffixString) + EDITED_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); - SendEventPackets(stoi(suffixString) + COMMON_MOVING_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); - SendEventPackets(stoi(suffixString) + EDITED_MOVING_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); - handles = GetHandlesFromPhotosInfoBurstKeys(stoi(suffixString)); - for (const auto handle: handles) { - SendEventPackets(handle+COMMON_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + MEDIA_INFO_LOG("MtpMediaLibrary PHOTO REMOVE"); + if (suffixString.empty()) { + allDeletedHandles = GetAllDeleteHandles(); + for (const auto deletehandle: allDeletedHandles) { + SendEventPackets(deletehandle + COMMON_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + SendEventPackets(deletehandle + EDITED_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + SendEventPackets(deletehandle + COMMON_MOVING_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + SendEventPackets(deletehandle + EDITED_MOVING_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + handles = GetHandlesFromPhotosInfoBurstKeys(deletehandle); + for (const auto handle : handles) { + SendEventPackets(handle+COMMON_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + } + } + } else { + SendEventPackets(stoi(suffixString) + COMMON_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + SendEventPackets(stoi(suffixString) + EDITED_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + SendEventPackets(stoi(suffixString) + COMMON_MOVING_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + SendEventPackets(stoi(suffixString) + EDITED_MOVING_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + handles = GetHandlesFromPhotosInfoBurstKeys(stoi(suffixString)); + for (const auto handle : handles) { + SendEventPackets(handle+COMMON_PHOTOS_OFFSET, MTP_EVENT_OBJECT_REMOVED_CODE); + } } break; default: @@ -166,21 +257,81 @@ void MediaSyncObserver::SendPhotoEvent(ChangeType changeType, string suffixStrin } } -void MediaSyncObserver::OnChange(const ChangeInfo &changeInfo) +std::shared_ptr MediaSyncObserver::GetAlbumInfo() +{ + DataShare::DataSharePredicates predicates; + Uri uri(PAH_QUERY_PHOTO_ALBUM); + vector columns; + columns.push_back(PhotoAlbumColumns::ALBUM_ID + " as " + MEDIA_DATA_DB_ID); + predicates.IsNotNull(MEDIA_DATA_DB_ALBUM_NAME); + predicates.NotEqualTo(MEDIA_DATA_DB_ALBUM_NAME, HIDDEN_ALBUM); + predicates.BeginWrap(); + predicates.NotEqualTo(MEDIA_DATA_DB_IS_LOCAL, IS_LOCAL); + predicates.Or(); + predicates.IsNull(MEDIA_DATA_DB_IS_LOCAL); + predicates.EndWrap(); + return dataShareHelper_->Query(uri, predicates, columns); +} + +void MediaSyncObserver::SendEventToPTP(int32_t suff_int, ChangeType changeType) +{ + auto albumHandles = PtpAlbumHandles::GetInstance(); + if (albumHandles == nullptr) { + MEDIA_ERR_LOG("albumHandles is nullptr"); + return; + } + switch (changeType) { + case static_cast(NotifyType::NOTIFY_ADD): + MEDIA_INFO_LOG("MtpMediaLibrary ALBUM ADD"); + albumHandles->AddHandle(suff_int); + SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_ADDED_CODE); + SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + SendEventPacketAlbum(PARENT_ID, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + break; + case static_cast(NotifyType::NOTIFY_UPDATE): + MEDIA_INFO_LOG("MtpMediaLibrary ALBUM UPDATE"); + if (albumHandles->FindHandle(suff_int)) { + SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + SendEventPacketAlbum(PARENT_ID, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + } else { + albumHandles->AddHandle(suff_int); + auto suff_removed_int = albumHandles->ChangeHandle(GetAlbumInfo()); + if (suff_removed_int != E_ERR) { + albumHandles->RemoveHandle(suff_removed_int); + SendEventPacketAlbum(suff_removed_int, MTP_EVENT_OBJECT_REMOVED_CODE); + SendEventPacketAlbum(PARENT_ID, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + } + SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_ADDED_CODE); + SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + SendEventPacketAlbum(PARENT_ID, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + } + break; + case static_cast(NotifyType::NOTIFY_REMOVE): + MEDIA_INFO_LOG("MtpMediaLibrary ALBUM REMOVE"); + albumHandles->RemoveHandle(suff_int); + SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_REMOVED_CODE); + SendEventPacketAlbum(PARENT_ID, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); + break; + default: + break; + } +} + +void MediaSyncObserver::OnChangeEx(const ChangeInfo &changeInfo) { std::string PhotoPrefix = PhotoColumn::PHOTO_URI_PREFIX; std::string PhotoAlbumPrefix = PhotoAlbumColumns::ALBUM_URI_PREFIX; - MEDIA_DEBUG_LOG("MtpMediaLibrary changeType [%{public}d]", changeInfo.changeType_); + MEDIA_INFO_LOG("MtpMediaLibrary changeType [%{public}d]", changeInfo.changeType_); for (const auto& it : changeInfo.uris_) { std::string uri = it.ToString(); - MEDIA_DEBUG_LOG("MtpMediaLibrary uris [%{public}s]", uri.c_str()); + MEDIA_INFO_LOG("MtpMediaLibrary uris [%{public}s]", uri.c_str()); if (startsWith(uri, PhotoPrefix)) { std::string suffixString = uri.substr(PhotoPrefix.size()); - if (suffixString.empty()) { + if (suffixString.empty() && changeInfo.changeType_ != static_cast(NotifyType::NOTIFY_REMOVE)) { MEDIA_ERR_LOG("MtpMediaLibrary suffixString is empty"); continue; } - MEDIA_DEBUG_LOG("MtpMediaLibrary suffixString [%{public}s]", suffixString.c_str()); + MEDIA_INFO_LOG("MtpMediaLibrary suffixString [%{public}s]", suffixString.c_str()); SendPhotoEvent(changeInfo.changeType_, suffixString); } else if (startsWith(uri, PhotoAlbumPrefix)) { std::string suffixString = uri.substr(PhotoAlbumPrefix.size()); @@ -192,28 +343,14 @@ void MediaSyncObserver::OnChange(const ChangeInfo &changeInfo) if (suff_int <= RESERVE_ALBUM) { continue; } - switch (changeInfo.changeType_) { - case static_cast(NotifyType::NOTIFY_ADD): - MEDIA_DEBUG_LOG("MtpMediaLibrary ALBUM ADD"); - SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_ADDED_CODE); - SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); - SendEventPacketAlbum(PARENT_ID, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); - break; - case static_cast(NotifyType::NOTIFY_UPDATE): - MEDIA_DEBUG_LOG("MtpMediaLibrary ALBUM UPDATE"); - SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); - SendEventPacketAlbum(PARENT_ID, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); - break; - case static_cast(NotifyType::NOTIFY_REMOVE): - MEDIA_DEBUG_LOG("MtpMediaLibrary ALBUM REMOVE"); - SendEventPacketAlbum(suff_int, MTP_EVENT_OBJECT_REMOVED_CODE); - SendEventPacketAlbum(PARENT_ID, MTP_EVENT_OBJECT_INFO_CHANGED_CODE); - break; - default: - break; - } + SendEventToPTP(suff_int, changeInfo.changeType_); } } } + +void MediaSyncObserver::OnChange(const ChangeInfo &changeInfo) +{ + std::thread([this, changeInfo] { this->OnChangeEx(changeInfo); }).detach(); +} } // namespace Media } // namespace OHOS \ No newline at end of file diff --git a/frameworks/services/media_thumbnail/src/thumbnail_source_loading.cpp b/frameworks/services/media_thumbnail/src/thumbnail_source_loading.cpp index 4761a6519ab419410c889df992280074f3d9d9ec..9139e4a8af68e3c82c9c4d64359548c6ae53844c 100644 --- a/frameworks/services/media_thumbnail/src/thumbnail_source_loading.cpp +++ b/frameworks/services/media_thumbnail/src/thumbnail_source_loading.cpp @@ -367,8 +367,8 @@ bool SourceLoader::CreateImagePixelMap(const std::string &sourcePath) Size targetSize = ConvertDecodeSize(data_, imageInfo.size, desiredSize_); Size sourceSize = imageInfo.size; - // When encode picture, if mainPixel width or height is odd, hard encode would fail. - // For the safety of encode process, only those of even desiredSize is allowed to generate througth picture. + // When encode picture, if mainPixel width or height is odd, hardware encode would fail. + // For the safety of encode process, only those of even desiredSize are allowed to generate througth picture. bool shouldGeneratePicture = data_.loaderOpts.isHdr && imageSource->IsHdrImage() && data_.lcdDesiredSize.width % 2 == 0 && data_.lcdDesiredSize.height % 2 == 0; bool isGenerateSucceed = shouldGeneratePicture ? @@ -376,11 +376,15 @@ bool SourceLoader::CreateImagePixelMap(const std::string &sourcePath) if (!isGenerateSucceed && shouldGeneratePicture) { MEDIA_ERR_LOG("SourceLoader generate picture source failed, generate pixelmap instead, path:%{public}s", DfxUtils::GetSafePath(data_.path).c_str()); - isGenerateSucceed = GeneratePixelMapSource(imageSource, sourceSize, targetSize); + std::unique_ptr retryImageSource = LoadImageSource(sourcePath, err); + if (err != E_OK || retryImageSource == nullptr) { + MEDIA_ERR_LOG("LoadImageSource retryImageSource error:%{public}d, errorno:%{public}d", err, errno); + return false; + } + isGenerateSucceed = GeneratePixelMapSource(retryImageSource, sourceSize, targetSize); } if (!isGenerateSucceed) { - MEDIA_ERR_LOG("SourceLoader CreateImagePixelMap generate source failed, path:%{public}s", - DfxUtils::GetSafePath(data_.path).c_str()); + MEDIA_ERR_LOG("ImagePixelMap generate failed, path:%{public}s", DfxUtils::GetSafePath(data_.path).c_str()); return false; } tracer.Finish(); diff --git a/frameworks/services/media_thumbnail/src/thumbnail_utils.cpp b/frameworks/services/media_thumbnail/src/thumbnail_utils.cpp index f0271e17c3ac53c56c4d445b19c2952b65fa4d9d..9aa65591fa65334732b04812c1fe86e64e7ad192 100644 --- a/frameworks/services/media_thumbnail/src/thumbnail_utils.cpp +++ b/frameworks/services/media_thumbnail/src/thumbnail_utils.cpp @@ -1557,24 +1557,29 @@ bool ThumbnailUtils::CopyPictureSource(std::shared_ptr &picture, std::s if (pixelMap == nullptr || gainMap == nullptr) { return false; } - Size pixelMapSize = {pixelMap->GetWidth(), pixelMap->GetHeight()}; - Media::InitializationOptions opts = { - .size = pixelMapSize, + Media::InitializationOptions pixelMapOpts = { + .size = {pixelMap->GetWidth(), pixelMap->GetHeight()}, .pixelFormat = pixelMap->GetPixelFormat(), .alphaType = pixelMap->GetAlphaType() }; - - auto copyPixelMapPtr = PixelMap::Create(*pixelMap, opts); + auto copyPixelMapPtr = PixelMap::Create(*pixelMap, pixelMapOpts); std::shared_ptr copyPixelMap = std::move(copyPixelMapPtr); if (copyPixelMap == nullptr) { return false; } - auto copyGainMapPtr = PixelMap::Create(*gainMap, opts); + + Media::InitializationOptions gainMapOpts = { + .size = {gainMap->GetWidth(), gainMap->GetHeight()}, + .pixelFormat = gainMap->GetPixelFormat(), + .alphaType = gainMap->GetAlphaType() + }; + auto copyGainMapPtr = PixelMap::Create(*gainMap, gainMapOpts); std::shared_ptr copyGainMap = std::move(copyGainMapPtr); if (copyGainMap == nullptr) { return false; } - auto auxiliaryPicturePtr = AuxiliaryPicture::Create(copyGainMap, AuxiliaryPictureType::GAINMAP, pixelMapSize); + Size copyGainMapSize = {copyGainMap->GetWidth(), copyGainMap->GetHeight()}; + auto auxiliaryPicturePtr = AuxiliaryPicture::Create(copyGainMap, AuxiliaryPictureType::GAINMAP, copyGainMapSize); std::shared_ptr auxiliaryPicture = std::move(auxiliaryPicturePtr); if (auxiliaryPicture == nullptr) { return false; diff --git a/frameworks/utils/src/media_privacy_manager.cpp b/frameworks/utils/src/media_privacy_manager.cpp index 6873f1e71607be24c891263251cbc6ee03ebe536..5410dae05c5fb02b9a15014a3f19e9f17972335a 100644 --- a/frameworks/utils/src/media_privacy_manager.cpp +++ b/frameworks/utils/src/media_privacy_manager.cpp @@ -341,9 +341,8 @@ static int32_t CollectRanges(const string &path, const HideSensitiveType &sensit return E_SUCCESS; } - if ((err != E_SUCCESS) && (err != E_NO_EXIF) && (err != E_NO_PRIVACY_EXIF_TAG)) { - MEDIA_ERR_LOG("Failed to get privacy area with type %{public}d, err: %{public}u", sensitiveType, err); - return E_ERR; + if (err != E_SUCCESS) { + MEDIA_WARN_LOG("Failed to get privacy area with type %{public}d, err: %{public}u", sensitiveType, err); } for (auto &range : areas) { ranges.insert(ranges.end(), std::make_pair(range.first, range.first + range.second)); diff --git a/interfaces/inner_api/media_library_helper/include/medialibrary_db_const.h b/interfaces/inner_api/media_library_helper/include/medialibrary_db_const.h index 988ad804d7d2a0528bd9a68e881ba23fef5776aa..c1dfbab3f0834e2a3ba099d0a892bfdf1af342a0 100644 --- a/interfaces/inner_api/media_library_helper/include/medialibrary_db_const.h +++ b/interfaces/inner_api/media_library_helper/include/medialibrary_db_const.h @@ -23,7 +23,7 @@ namespace OHOS { namespace Media { -const int32_t MEDIA_RDB_VERSION = 135; +const int32_t MEDIA_RDB_VERSION = 136; enum { VERSION_ADD_CLOUD = 2, VERSION_ADD_META_MODIFED = 3, @@ -161,6 +161,7 @@ enum { VERSION_HDR_AND_CLOUD_ENHANCEMENT_FIX = 133, VERSION_THUMBNAIL_READY_FIX = 134, VERSION_UPDATE_DATETAKEN_AND_DETAILTIME = 135, + VERSION_UPDATE_SOURCE_PHOTO_ALBUM_TRIGGER = 136, }; enum {