!189 后台任务通知

Merge pull request !189 from Jeam.wang/master
This commit is contained in:
openharmony_ci 2022-08-01 12:32:39 +00:00 committed by Gitee
commit cf4517f391
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
13 changed files with 266 additions and 51 deletions

View File

@ -276,7 +276,7 @@ DataAbility能力DataAbility的使用方用户获取DataAbility文件协
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>boolean</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>下载背景</p>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>下载通知</p>
</td>
</tr>
</tbody>
@ -474,13 +474,6 @@ DataAbility能力DataAbility的使用方用户获取DataAbility文件协
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>上传请求表单列表信息。</p>
</td>
</tr>
<tr id="row204321219393"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1893413268144"><a name="p1893413268144"></a><a name="p1893413268144"></a>background</p>
</td>
<td class="cellrowborder" valign="top" width="10%" headers="mcps1.2.3.1.2 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>boolean</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.3 "><p id="p18761104812149"><a name="p18761104812149"></a><a name="p18761104812149"></a>上传背景。</p>
</td>
</tr>
</tbody>
</table>

View File

@ -45,13 +45,19 @@ public:
void SetFDError(int32_t fdError);
void SetBundleName(const std::string &bundleName);
void SetBackground(bool background);
void SetApplicationInfoUid(const int32_t uid);
[[nodiscard]] const std::string &GetUrl() const;
[[nodiscard]] const std::map<std::string, std::string> &GetHeader() const;
[[nodiscard]] bool GetMetered() const;
[[nodiscard]] bool IsMetered() const;
[[nodiscard]] bool GetRoaming() const;
[[nodiscard]] bool IsRoaming() const;
[[nodiscard]] const std::string &GetDescription() const;
@ -65,28 +71,28 @@ public:
int32_t GetFDError() const;
[[nodiscard]] const std::string &GetBundleName() const;
[[nodiscard]] bool IsBackground() const;
int32_t GetApplicationInfoUid() const;
void Dump(bool isFull = true) const;
private:
bool enableMetered_ = false;
bool enableRoaming_ = false;
bool background_ = false;
int32_t fd_ = -1;
int32_t fdError_ = 0;
int32_t uid_ = -1;
uint32_t networkType_ = 0;
std::string url_;
std::map<std::string, std::string> header_;
bool enableMetered_;
bool enableRoaming_;
std::string description_;
uint32_t networkType_;
std::string filePath_;
std::string title_;
int32_t fd_;
int32_t fdError_;
std::string bundleName_;
std::map<std::string, std::string> header_;
};
} // namespace OHOS::Request::Download

View File

@ -19,8 +19,7 @@
namespace OHOS::Request::Download {
DownloadConfig::DownloadConfig()
: url_(""), enableMetered_(false), enableRoaming_(false), description_(""), networkType_(0),
filePath_(""), title_(""), fd_(-1), fdError_(0) {
{
}
void DownloadConfig::SetUrl(const std::string &url)
@ -73,6 +72,21 @@ void DownloadConfig::SetFDError(int32_t fdError)
fdError_ = fdError;
}
void DownloadConfig::SetBundleName(const std::string &bundleName)
{
bundleName_ = bundleName;
}
void DownloadConfig::SetBackground(bool background)
{
background_ = background;
}
void DownloadConfig::SetApplicationInfoUid(const int32_t uid)
{
uid_ = uid;
}
const std::string &DownloadConfig::GetUrl() const
{
return url_;
@ -83,12 +97,12 @@ const std::map<std::string, std::string> &DownloadConfig::GetHeader() const
return header_;
}
bool DownloadConfig::GetMetered() const
bool DownloadConfig::IsMetered() const
{
return enableMetered_;
}
bool DownloadConfig::GetRoaming() const
bool DownloadConfig::IsRoaming() const
{
return enableRoaming_;
}
@ -123,6 +137,21 @@ int32_t DownloadConfig::GetFDError() const
return fdError_;
}
const std::string &DownloadConfig::GetBundleName() const
{
return bundleName_;
}
bool DownloadConfig::IsBackground() const
{
return background_;
}
int32_t DownloadConfig::GetApplicationInfoUid() const
{
return uid_;
}
void DownloadConfig::Dump(bool isFull) const
{
DOWNLOAD_HILOGD("fd: %{public}d", fd_);
@ -147,5 +176,8 @@ void DownloadConfig::Dump(bool isFull) const
});
DOWNLOAD_HILOGD("Header Information -------------- End");
}
DOWNLOAD_HILOGD("bundleName: %{public}s", bundleName_.c_str());
DOWNLOAD_HILOGD("background: %{public}s", background_ ? "true" : "false");
DOWNLOAD_HILOGD("uid: %{public}d", uid_);
}
} // namespace OHOS::Request::Download

View File

@ -115,9 +115,12 @@ DownloadTask* DownloadManager::EnqueueTask(const DownloadConfig &config)
rawContactValues.PutString("description", config.GetDescription().c_str());
rawContactValues.PutString("title", config.GetTitle().c_str());
rawContactValues.PutString("filePath", config.GetFilePath().c_str());
rawContactValues.PutBool("metered", config.GetMetered());
rawContactValues.PutBool("roaming", config.GetRoaming());
rawContactValues.PutBool("metered", config.IsMetered());
rawContactValues.PutBool("roaming", config.IsRoaming());
rawContactValues.PutInt("network", config.GetNetworkType());
rawContactValues.PutBool("background", config.IsBackground());
rawContactValues.PutString("bundleName", config.GetBundleName());
rawContactValues.PutInt("uid", config.GetApplicationInfoUid());
if (dataAbilityHelper_ != nullptr) {
int rowId = dataAbilityHelper_->Insert(uriDownload, rawContactValues);

View File

@ -72,12 +72,16 @@ int32_t DownloadServiceProxy::Request(const DownloadConfig &config)
}
data.WriteInt32(err);
data.WriteString(config.GetUrl());
data.WriteBool(config.GetMetered());
data.WriteBool(config.GetRoaming());
data.WriteBool(config.IsMetered());
data.WriteBool(config.IsRoaming());
data.WriteString(config.GetDescription());
data.WriteUint32(config.GetNetworkType());
data.WriteString(config.GetFilePath());
data.WriteString(config.GetTitle());
data.WriteString(config.GetDescription());
data.WriteBool(config.IsBackground());
data.WriteString(config.GetBundleName());
data.WriteInt32(config.GetApplicationInfoUid());
data.WriteUint32(config.GetHeader().size());
std::map<std::string, std::string>::const_iterator iter;
for (iter = config.GetHeader().begin(); iter != config.GetHeader().end(); ++iter) {

View File

@ -31,6 +31,7 @@
#include "napi_utils.h"
#include "legacy/download_manager.h"
#include "napi_base_context.h"
#include "ipc_skeleton.h"
static constexpr const char *FUNCTION_ON = "on";
static constexpr const char *FUNCTION_OFF = "off";
@ -48,6 +49,7 @@ static constexpr const char *PARAM_KEY_DESCRIPTION = "description";
static constexpr const char *PARAM_KEY_NETWORKTYPE = "networkType";
static constexpr const char *PARAM_KEY_FILE_PATH = "filePath";
static constexpr const char *PARAM_KEY_TITLE = "title";
static constexpr const char *PARAM_KEY_BACKGROUND = "background";
namespace OHOS::Request::Download {
constexpr const std::uint32_t CONFIG_PARAM_AT_FIRST = 0;
@ -134,12 +136,17 @@ napi_value DownloadTaskNapi::Initialize(napi_env env, napi_callback_info info)
DOWNLOAD_HILOGE("Initialize. GetContext fail.");
return nullptr;
}
if (context->GetApplicationInfo() == nullptr) {
DOWNLOAD_HILOGE("ApplicationInfo is null");
return nullptr;
}
DownloadConfig config;
if (!ParseConfig(env, argv[parametersPosition], config)) {
DOWNLOAD_HILOGE("download config has wrong type");
return nullptr;
}
config.SetBundleName(context->GetBundleName());
config.SetApplicationInfoUid(IPCSkeleton::GetCallingUid());
DownloadManager::GetInstance()->SetDataAbilityHelper(GetDataAbilityHelper(env));
auto *task = DownloadManager::GetInstance()->EnqueueTask(config);
if (task == nullptr) {
@ -200,6 +207,7 @@ bool DownloadTaskNapi::ParseConfig(napi_env env, napi_value configValue, Downloa
config.SetNetworkType(NapiUtils::GetUint32Property(env, configValue, PARAM_KEY_NETWORKTYPE));
config.SetFilePath(NapiUtils::GetStringPropertyUtf8(env, configValue, PARAM_KEY_FILE_PATH));
config.SetTitle(NapiUtils::GetStringPropertyUtf8(env, configValue, PARAM_KEY_TITLE));
config.SetBackground(NapiUtils::GetBooleanProperty(env, configValue, PARAM_KEY_BACKGROUND));
return true;
}

View File

@ -33,6 +33,7 @@ ohos_shared_library("download_server") {
"//base/request/request/download/interfaces/kits/js/napi/download_single/src/download_config.cpp",
"//base/request/request/download/interfaces/kits/js/napi/download_single/src/download_info.cpp",
"//base/request/request/upload/frameworks/libs/src/module_init.cpp",
"src/download_background_notification.cpp",
"src/download_notify_proxy.cpp",
"src/download_service_ability.cpp",
"src/download_service_manager.cpp",
@ -50,6 +51,7 @@ ohos_shared_library("download_server") {
"//commonlibrary/c_utils/base/include",
"//utils/system/safwk/native/include",
"//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient/include",
"//base/notification/distributed_notification_service/interfaces/inner_api",
"//base/request/request/download/interfaces/innerkits/include",
"//base/request/request/download/utils/include",
"//base/telephony/core_service/interfaces/innerkits/include",
@ -65,6 +67,7 @@ ohos_shared_library("download_server") {
"//base/request/request/download/dfx/event/fault",
]
deps = [
"//base/notification/distributed_notification_service/frameworks/ans:ans_innerkits",
"//base/request/request/download/dfx:misc_request_dfx_static",
"//base/telephony/core_service/interfaces/innerkits:tel_core_service_api",
"//foundation/communication/netmanager_base/interfaces/innerkits/netconnclient:net_conn_manager_if",
@ -76,6 +79,8 @@ ohos_shared_library("download_server") {
defines = [ "NO_SSL_CERTIFICATION=1" ]
external_deps = [
"ability_base:base",
"ability_base:want",
"ability_base:zuri",
"access_token:libaccesstoken_sdk",
"bundle_framework:appexecfwk_core",
@ -89,6 +94,7 @@ ohos_shared_library("download_server") {
"ipc:ipc_core",
"multimedia_image_standard:image_native",
"os_account:os_account_innerkits",
"relational_store:native_rdb",
]
subsystem_name = "request"
part_name = "request"

View File

@ -0,0 +1,27 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DOWNLOAD_BACKGROUND_NOTIFICATION_H
#define DOWNLOAD_BACKGROUND_NOTIFICATION_H
namespace OHOS::Request::Download {
class DownloadBackgroundNotification {
public:
DownloadBackgroundNotification() = default;
~DownloadBackgroundNotification() = default;
static void PublishNotification(uint32_t taskId, pid_t uid, const std::string &filePath, uint32_t percent);
};
} // Download
#endif // DOWNLOAD_BACKGROUND_NOTIFICATION_H

View File

@ -85,6 +85,10 @@ private:
bool SetHttpsCertificationOption(CURL *curl);
std::string ReadCertification();
void RecordTaskEvent(int32_t httpCode);
void PublishNotification(bool background, uint32_t percent);
void PublishNotification(bool background, uint32_t prevSize, uint32_t downloadSize, uint32_t totalSize);
std::time_t GetCurTimestamp();
uint32_t ProgressNotification(uint32_t prevSize, uint32_t downloadSize, uint32_t totalSize);
private:
uint32_t taskId_;
DownloadConfig config_;
@ -106,6 +110,10 @@ private:
bool hasFileSize_;
bool isOnline_;
uint32_t prevSize_;
static constexpr uint32_t HUNDRED_PERCENT = 100;
static constexpr uint32_t TEN_PERCENT_THRESHOLD = 10;
static constexpr uint32_t NOTIFICATION_FREQUENCY = 2000;
std::time_t lastTimestamp_ = 0;
};
} // namespace OHOS::Request::Download
#endif // DOWNLOAD_TASK_H

View File

@ -0,0 +1,62 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "notification.h"
#include "notification_helper.h"
#include "notification_constant.h"
#include "notification_content.h"
#include "int_wrapper.h"
#include "string_wrapper.h"
#include "want_params.h"
#include "log.h"
#include "download_background_notification.h"
using namespace OHOS::Notification;
namespace OHOS::Request::Download {
void DownloadBackgroundNotification::PublishNotification(uint32_t taskId, pid_t uid, const std::string &filePath,
uint32_t percent)
{
auto downloadTemplate = std::make_shared<NotificationTemplate>();
if (downloadTemplate == nullptr) {
DOWNLOAD_HILOGE("taskId: %{public}d, downloadTemplate is null", taskId);
return;
}
downloadTemplate->SetTemplateName("downloadTemplate");
AAFwk::WantParams wantParams;
wantParams.SetParam("progressValue", AAFwk::Integer::Box(percent));
wantParams.SetParam("fileName", AAFwk::String::Box(filePath));
wantParams.SetParam("title", AAFwk::String::Box("Download"));
downloadTemplate->SetTemplateData(std::make_shared<AAFwk::WantParams>(wantParams));
auto normalContent = std::make_shared<NotificationNormalContent>();
if (normalContent == nullptr) {
DOWNLOAD_HILOGE("taskId: %{public}d, normalContent is null", taskId);
return;
}
auto content = std::make_shared<NotificationContent>(normalContent);
if (content == nullptr) {
DOWNLOAD_HILOGE("taskId: %{public}d, content is null", taskId);
return;
}
NotificationRequest req(taskId);
req.SetCreatorUid(uid);
req.SetContent(content);
req.SetTemplate(downloadTemplate);
req.SetSlotType(NotificationConstant::OTHER);
ErrCode errCode = NotificationHelper::PublishNotification(req);
if (errCode != ERR_OK) {
DOWNLOAD_HILOGE("notification errCode: %{public}d", errCode);
}
}
} // Download

View File

@ -88,7 +88,9 @@ bool DownloadServiceStub::OnRequest(MessageParcel &data, MessageParcel &reply)
config.SetFilePath(data.ReadString());
config.SetTitle(data.ReadString());
config.SetDescription(data.ReadString());
config.SetBackground(data.ReadBool());
config.SetBundleName(data.ReadString());
config.SetApplicationInfoUid(data.ReadInt32());
uint32_t headerSize = data.ReadUint32();
for (uint32_t i = 0; i < headerSize; i++) {
config.SetHeader(data.ReadString(), data.ReadString());

View File

@ -34,6 +34,7 @@
#include "hitrace_meter.h"
#include "task_statistics.h"
#include "task_fault.h"
#include "download_background_notification.h"
namespace OHOS::Request::Download {
static const std::string URL_HTTPS = "https";
@ -162,8 +163,8 @@ bool DownloadServiceTask::Query(DownloadInfo &info)
info.SetDownloadTitle(config_.GetTitle());
info.SetDownloadTotalBytes(totalSize_);
info.SetNetworkType(config_.GetNetworkType());
info.SetMetered(config_.GetMetered());
info.SetRoaming(config_.GetRoaming());
info.SetMetered(config_.IsMetered());
info.SetRoaming(config_.IsRoaming());
return true;
}
@ -449,24 +450,26 @@ size_t DownloadServiceTask::HeaderCallback(void *buffer, size_t size, size_t num
int DownloadServiceTask::ProgressCallback(void *pParam, double dltotal, double dlnow, double ultotal, double ulnow)
{
DownloadServiceTask *this_ = static_cast<DownloadServiceTask *>(pParam);
if (this_ != nullptr) {
if (this_->isRemoved_) {
DownloadServiceTask *task = static_cast<DownloadServiceTask *>(pParam);
if (task != nullptr) {
if (task->isRemoved_) {
DOWNLOAD_HILOGI("download task has been removed");
return 0;
}
if (this_->forceStop_) {
if (task->forceStop_) {
DOWNLOAD_HILOGI("Pause issued by user");
return HTTP_FORCE_STOP;
}
if (this_->eventCb_ == nullptr) {
if (task->eventCb_ == nullptr) {
return 0;
}
if (this_->prevSize_ != this_->downloadSize_) {
std::lock_guard<std::recursive_mutex> autoLock(this_->mutex_);
if (this_->status_ != SESSION_PAUSED) {
this_->eventCb_("progress", this_->taskId_, this_->downloadSize_, this_->totalSize_);
this_->prevSize_ = this_->downloadSize_;
if (task->prevSize_ != task->downloadSize_) {
std::lock_guard<std::recursive_mutex> autoLock(task->mutex_);
if (task->status_ != SESSION_PAUSED) {
task->eventCb_("progress", task->taskId_, task->downloadSize_, task->totalSize_);
task->PublishNotification(task->config_.IsBackground(), task->prevSize_,
task->downloadSize_, task->totalSize_);
task->prevSize_ = task->downloadSize_;
}
}
// calc the download speed
@ -510,6 +513,7 @@ bool DownloadServiceTask::ExecHttp()
downloadSize_ = totalSize_;
DOWNLOAD_HILOGI("Download task has already completed");
SetStatus(SESSION_SUCCESS);
PublishNotification(config_.IsBackground(), HUNDRED_PERCENT);
return true;
}
}
@ -517,7 +521,7 @@ bool DownloadServiceTask::ExecHttp()
} else {
DOWNLOAD_HILOGD("Failed to open download file");
}
PublishNotification(config_.IsBackground(), prevSize_, downloadSize_, totalSize_);
CURLcode code = CurlPerformFileTransfer(handle.get());
int32_t httpCode;
curl_easy_getinfo(handle.get(), CURLINFO_RESPONSE_CODE, &httpCode);
@ -718,6 +722,7 @@ void DownloadServiceTask::HandleResponseCode(CURLcode code, int32_t httpCode)
case CURLE_OK:
if (httpCode == HTTP_OK || (isPartialMode_ && httpCode == HTTP_PARIAL_FILE)) {
SetStatus(SESSION_SUCCESS);
PublishNotification(config_.IsBackground(), HUNDRED_PERCENT);
return;
}
break;
@ -819,11 +824,11 @@ bool DownloadServiceTask::IsSatisfiedConfiguration()
DOWNLOAD_HILOGD("isRoaming_: %{public}d, isMetered_: %{public}d, networkType_: %{public}u",
networkInfo.isRoaming_, networkInfo.isMetered_, networkInfo.networkType_);
DOWNLOAD_HILOGD("config_ { isRoaming_: %{public}d,isMetered_: %{public}d, networkType_: %{public}u}",
config_.GetRoaming(), config_.GetMetered(), config_.GetNetworkType());
if (networkInfo.isRoaming_ && !config_.GetRoaming()) {
config_.IsRoaming(), config_.IsMetered(), config_.GetNetworkType());
if (networkInfo.isRoaming_ && !config_.IsRoaming()) {
return false;
}
if (networkInfo.isMetered_ && !config_.GetMetered()) {
if (networkInfo.isMetered_ && !config_.IsMetered()) {
return false;
}
if ((networkInfo.networkType_ & config_.GetNetworkType()) == NETWORK_INVALID) {
@ -883,4 +888,56 @@ std::string DownloadServiceTask::ReadCertification()
inFile.close();
return certInfo;
}
void DownloadServiceTask::PublishNotification(bool background, uint32_t percent)
{
if (!background) {
return;
}
pid_t pid = static_cast<pid_t>(config_.GetApplicationInfoUid());
std::string filePath = config_.GetFilePath();
DownloadBackgroundNotification::PublishNotification(taskId_, pid, filePath, percent);
}
void DownloadServiceTask::PublishNotification(bool background, uint32_t prevSize,
uint32_t downloadSize, uint32_t totalSize)
{
if (!background) {
return;
}
if (prevSize == 0) {
PublishNotification(background, 0);
lastTimestamp_ = GetCurTimestamp();
} else {
uint32_t percent = ProgressNotification(prevSize, downloadSize, totalSize);
if (percent > 0) {
PublishNotification(background, percent);
}
}
}
std::time_t DownloadServiceTask::GetCurTimestamp()
{
auto tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
return tp.time_since_epoch().count();
}
uint32_t DownloadServiceTask::ProgressNotification(uint32_t prevSize, uint32_t downloadSize, uint32_t totalSize)
{
uint32_t ret = 0;
if (totalSize != 0) {
uint32_t percent = static_cast<uint32_t>(downloadSize * 100.0 / totalSize);
uint32_t lastPercent = static_cast<uint32_t>(prevSize * 100.0 / totalSize);
std::time_t curTimestamp = GetCurTimestamp();
if (curTimestamp < lastTimestamp_) {
return 0;
}
if ((percent - lastPercent) >= TEN_PERCENT_THRESHOLD ||
(curTimestamp - lastTimestamp_) >= NOTIFICATION_FREQUENCY) {
ret = percent;
lastTimestamp_ = curTimestamp;
}
}
return ret;
}
} // namespace OHOS::Request::Download

View File

@ -340,6 +340,13 @@ declare namespace request {
* @permission ohos.permission.INTERNET
*/
title?: string;
/**
* Whether to display the background.
*
* @since 9
* @permission N/A
*/
background?: boolean;
}
/**