TicketNo:#IB4VH1 Description:utils模块缺少屏保和时间等方法

Signed-off-by: LongestDistance <cdwango@isoftstone.com>
This commit is contained in:
LongestDistance 2024-11-17 12:03:22 +08:00
parent a3d15bad46
commit 318bda558d
12 changed files with 232 additions and 45 deletions

View File

@ -58,7 +58,6 @@ public:
virtual int32_t Release() = 0;
virtual int32_t NotifyEvent(EventId eventId, std::string &jsonParam) = 0;
virtual int32_t SetCastMode(CastMode mode, std::string &jsonParam) = 0;
virtual void OnSessionEvent(const std::string &deviceId, const ReasonCode eventCode) {}
virtual int32_t GetRemoteDeviceInfo(std::string deviceId, CastRemoteDevice &remoteDevice)
{
return 0;

View File

@ -49,15 +49,19 @@ bool FillCastRemoteDevices(MessageParcel &data, const std::vector<CastRemoteDevi
CLOGE("devices size <= 0");
return false;
}
if (!data.WriteInt32(static_cast<int32_t>(size))) {
CLOGE("Failed to write the device size:%lu", size);
return false;
}
for (auto &device : devices) {
if (!WriteCastRemoteDevice(data, device)) {
CLOGE("Failed to write the remote device item");
return false;
}
}
return true;
}

View File

@ -65,17 +65,12 @@ bool CastDeviceDataManager::AddDevice(const CastInnerRemoteDevice &device, const
data.wifiDeviceInfo = data.wifiDeviceInfo.extraData.size() > 0 ? data.wifiDeviceInfo : dmDeviceInfo;
} else if (extraJson.contains(PARAM_KEY_BLE_MAC) && extraJson[PARAM_KEY_BLE_MAC].is_string()) {
data.bleDeviceInfo = dmDeviceInfo;
} else if (extraJson.contains(PARAM_KEY_WIFI_IP) && extraJson[PARAM_KEY_WIFI_IP].is_string()) {
data.wifiDeviceInfo = dmDeviceInfo;
} else {
data.wifiDeviceInfo = dmDeviceInfo;
}
int sessionId = device.sessionId != INVALID_ID ? device.sessionId : data.device.sessionId;
data.device = device;
data.device.sessionId = sessionId;
data.networkId = strlen(dmDeviceInfo.networkId) > 0 ? dmDeviceInfo.networkId : data.networkId;
CLOGI("sessionId is %d", sessionId);
RemoveDeviceLocked(device.deviceId);
devices_.push_back(data);
@ -185,6 +180,8 @@ int CastDeviceDataManager::GetDeviceTransId(const std::string &deviceId)
int CastDeviceDataManager::ResetDeviceTransId(const std::string &deviceId)
{
CLOGD("ResetDeviceTransId in.");
std::lock_guard<std::mutex> lock(mutex_);
auto it = GetDeviceLocked(deviceId);
if (it == devices_.end()) {

View File

@ -159,7 +159,6 @@ private:
void ChangeDeviceStateLocked(
DeviceState state, const std::string &deviceId, int32_t reasonCode = REASON_DEFAULT);
void ReportDeviceStateInfo(DeviceState state, const std::string &deviceId, const ReasonCode eventCode);
void OnSessionEvent(const std::string& deviceId, const ReasonCode eventCode) override;
void ChangeDeviceStateInner(DeviceState state, const std::string &deviceId,
int32_t reasonCode = REASON_DEFAULT);
void OnEvent(EventId eventId, const std::string &data);

View File

@ -1079,18 +1079,6 @@ void CastSessionImpl::ReportDeviceStateInfo(DeviceState state, const std::string
}
}
void CastSessionImpl::OnSessionEvent(const std::string &deviceId, const ReasonCode eventCode)
{
std::lock_guard<std::mutex> lock(mutex_);
CLOGD("Session event: %{public}d", static_cast<int32_t>(eventCode));
if (static_cast<int32_t>(eventCode) < 0 or eventCode == ReasonCode::REASON_CANCEL_BY_SOURCE) {
ConnectionManager::GetInstance().UpdateDeviceState(deviceId, RemoteDeviceState::FOUND);
SendCastMessage(Message(MessageId::MSG_DISCONNECT, deviceId, eventCode));
} else {
SendCastMessage(Message(MessageId::MSG_START_AUTH, deviceId, eventCode));
}
}
void CastSessionImpl::OnEvent(EventId eventId, const std::string &data)
{
std::unique_lock<std::mutex> lock(mutex_);

View File

@ -33,7 +33,6 @@ public:
int what_;
int arg1_{ 0 };
int arg2_{ 0 };
ReasonCode eventCode_{ ReasonCode::REASON_DEFAULT };
using Function = std::function<void()>;
Function task_ = nullptr;
@ -51,8 +50,6 @@ public:
Message &operator=(const Message &msg);
explicit Message(int what);
Message(int what, std::string strArg);
Message(int what, std::string deviceId, ReasonCode eventCode) : what_(what),
eventCode_(eventCode), strArg_(deviceId) {}
Message(int what, int arg1);
Message(int what, int arg1, int arg2);
Message(int what, int arg1, int arg2, std::string strArg);

View File

@ -22,6 +22,7 @@
#include <locale>
#include <string>
#include <vector>
#include <atomic>
namespace OHOS {
namespace CastEngine {
@ -42,6 +43,8 @@ namespace CastEngineService {
DISALLOW_COPY_AND_ASSIGN(TypeName)
#endif
#define USEC_1000 1000
struct PacketData {
uint8_t *data;
int length;
@ -52,6 +55,14 @@ struct ConstPacketData {
int length;
};
enum class DrmType {
DRM_BASE = 1,
CLEARKEY = DRM_BASE << 1,
WIDEVINE = DRM_BASE << 2,
PLAYREADY = DRM_BASE << 3,
CHINADRM = DRM_BASE << 4,
};
class Utils {
public:
Utils() {}
@ -65,13 +76,19 @@ public:
static int32_t StringToInt(const std::string &str, int base = DECIMALISM);
static std::string GetWifiIp();
static bool IsArrayAllZero(const uint8_t *input, int length);
static uint64_t TimeMilliSecond();
static std::string Mask(const std::string &str);
static bool Base64Encode(const std::string &source, std::string &encoded);
static bool Base64Decode(const std::string &encoded, std::string &decoded);
static DrmType DrmUuidToType(std::string drmUUID);
static int32_t GetCurrentActiveAccountUserId();
static std::string GetOhosAccountId();
static int SetFirstTokenID();
static void EnablePowerForceTimingOut();
static void ResetPowerForceTimingOut();
static void LightAndLockScreen();
static void SetThreadName(const std::string &name);
private:
@ -85,14 +102,23 @@ private:
constexpr static int MASK_MIN_LEN = 2;
constexpr static int MASK_PRINT_PREFIX_LEN = 4;
constexpr static int MASK_PRINT_POSTFIX_LEN = 2;
static std::atomic<bool> isEnablePowerForceTimingOut;
};
inline const std::string UUID_CHINADRM = "3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c";
inline const std::string UUID_WIDEVINE = "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";
inline const std::string UUID_PLAYREADY = "9a04f079-9840-4286-ab92-e65be0885f95";
inline constexpr char SANDBOX_PATH[] = "/data/service/el1/public/cast_engine_service";
inline constexpr char PARAM_MEDIA_DUMP[] = "debug.cast.media.dump";
inline constexpr char PARAM_MEDIA_DUMP_FOR_BETA[] = "debug.cast.media.dump.beta";
inline constexpr char PARAM_VIDEO_CACHE[] = "debug.cast.video.cache";
inline constexpr char PARAM_PERFORMANCE[] = "debug.cast.performance";
inline constexpr char UNIQUE_SCREEN[] = "debug.cast.unique.screen";
inline constexpr char NOTIFY_DEVICE_FOUND[] = "debug.cast.device.found";
inline constexpr char USED_AGGR_SEND[] = "debug.cast.aggr.send";
inline constexpr char PARAM_VTP_SUPPORT[] = "debug.cast.vtp.support";
inline constexpr char PARAM_YUV_SUPPORT[] = "debug.cast.yuv.support";
inline constexpr char FLASH_LIGHT[] = "debug.cast.flash.light";
} // namespace CastEngineService
} // namespace CastEngine
} // namespace OHOS

View File

@ -14,6 +14,7 @@
*/
#include "cast_timer.h"
#include "cast_engine_log.h"
#include "utils.h"
namespace OHOS {
namespace CastEngine {
@ -32,9 +33,15 @@ CastTimer::~CastTimer()
void CastTimer::Start(std::function<void()> task, int interval)
{
CLOGD("%s In, exit_ = %d.", __FUNCTION__, exit_.load());
std::unique_lock<std::mutex> locker(threadMutex_);
if (!IsStopped()) {
return;
}
exit_ = false;
workThread_ = std::thread([this, interval, task]() {
Utils::SetThreadName("CastTimerStart");
while (!exit_.load()) {
{
// sleep every interval and do the task again and again until times up
@ -56,12 +63,17 @@ void CastTimer::Start(std::function<void()> task, int interval)
void CastTimer::Stop()
{
CLOGD("%s In, exit_ = %d.", __FUNCTION__, exit_.load());
std::unique_lock<std::mutex> locker(threadMutex_);
if (IsStopped()) {
return;
}
exit_ = true;
{
std::unique_lock<std::mutex> locker(mutex_);
cond_.notify_all();
}
if (workThread_.joinable()) {
workThread_.join();
}

View File

@ -17,6 +17,7 @@
*/
#include "handler.h"
#include "utils.h"
namespace OHOS {
namespace CastEngine {
@ -24,6 +25,7 @@ namespace CastEngineService {
Handler::Handler() : stop_(false), stopWhenEmpty_(false)
{
looper_ = std::thread([this]() {
Utils::SetThreadName("Handler");
for (;;) {
Message msg;
{

View File

@ -20,6 +20,8 @@
#include <string>
#include <unistd.h>
#include "utils.h"
#include "cast_engine_log.h"
#include "ipc_skeleton.h"
#include "accesstoken_kit.h"
@ -34,20 +36,32 @@ namespace CastEngineService {
DEFINE_CAST_ENGINE_LABEL("Cast-Permission");
namespace {
const std::string MIRROR_PERMISSION = "ohos.permission.ACCESS_CAST_ENGINE_MIRROR";
const std::string STREAM_PERMISSION = "ohos.permission.ACCESS_CAST_ENGINE_STREAM";
std::string GetPermissionDescription(const std::string &permission)
{
if (permission == "ohos.permission.ACCESS_CAST_ENGINE_MIRROR") {
if (permission == MIRROR_PERMISSION) {
return "Mirror permission";
}
if (permission == "ohos.permission.ACCESS_CAST_ENGINE_STREAM") {
if (permission == STREAM_PERMISSION) {
return "Stream permission";
}
return "Unkown permission";
return "Unknown permission";
}
bool CheckPermission(const std::string &permission)
{
CLOGE("%{public}s succ", GetPermissionDescription(permission).c_str());
AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
int result = AccessTokenKit::VerifyAccessToken(callerToken, permission);
if (result != PERMISSION_GRANTED) {
CLOGE("%{public}s denied!", GetPermissionDescription(permission).c_str());
return false;
}
return true;
}
} // namespace
@ -60,12 +74,12 @@ int32_t Permission::appPid_;
bool Permission::CheckMirrorPermission()
{
return CheckPermission("ohos.permission.ACCESS_CAST_ENGINE_MIRROR");
return CheckPermission(MIRROR_PERMISSION);
}
bool Permission::CheckStreamPermission()
{
return CheckPermission("ohos.permission.ACCESS_CAST_ENGINE_STREAM");
return CheckPermission(STREAM_PERMISSION);
}
void Permission::SavePid(pid_t pid)
@ -99,7 +113,7 @@ bool Permission::CheckPidPermission()
pid_t pid = IPCSkeleton::GetCallingPid();
pid_t myPid = getpid();
CLOGD("Calling pid is %{public}d, my pid is %{public}d", pid, myPid);
if (pid == myPid || pid == 0) { // 0 means role is proxy
if (pid == myPid) {
return true;
}
@ -114,7 +128,8 @@ bool Permission::CheckPidPermission()
void Permission::SaveMirrorAppInfo(std::tuple<int32_t, uint32_t, int32_t> appInfo)
{
std::tie(appUid_, appTokenId_, appPid_) = appInfo;
CLOGD("appUid %{public}d, appTokenId %{public}u, appPid %{public}d", appUid_, appTokenId_, appPid_);
CLOGD("appUid %{public}d, appTokenId %{public}s, appPid %{public}d",
appUid_, Utils::Mask(std::to_string(appTokenId_)).c_str(), appPid_);
}
std::tuple<int32_t, uint32_t, int32_t> Permission::GetMirrorAppInfo()

View File

@ -33,7 +33,9 @@ void StateMachine::HandleMessage(const Message &msg)
std::shared_ptr<State> cur = state_;
while (cur != nullptr && !cur->HandleMessage(msg)) {
cur = cur->GetParentState();
CLOGD("Delegate to ParentState.");
}
if (cur == nullptr) {
CLOGW("message: %d unhandled in parent state", msg.what_);
}
@ -89,6 +91,7 @@ void StateMachine::ProcessDeferredMessages()
state_->HandleMessage(msg);
}
}
} // namespace CastEngineService
} // namespace CastEngine
} // namespace OHOS

View File

@ -17,45 +17,117 @@
*/
#include "utils.h"
#include <cctype>
#include <glib.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <sys/prctl.h>
#include <sys/time.h>
#include "wifi_device.h"
#include "ohos_account_kits.h"
#include "os_account_manager.h"
#include "os_account_constants.h"
#include "cast_engine_log.h"
#include "ipc_skeleton.h"
#include "token_setproc.h"
#include "power_mgr_client.h"
using namespace OHOS::PowerMgr;
namespace OHOS {
namespace CastEngine {
namespace CastEngineService {
DEFINE_CAST_ENGINE_LABEL("Cast-Utils");
const uint32_t BASE64_UNIT_ONE_PADDING = 1;
const uint32_t BASE64_UNIT_TWO_PADDING = 2;
const uint32_t BASE64_SRC_UNIT_SIZE = 3;
const uint32_t BASE64_DEST_UNIT_SIZE = 4;
constexpr static int32_t DEFAULT_OS_ACCOUNT_ID = 100;
std::atomic<bool> Utils::isEnablePowerForceTimingOut = false;
bool Utils::Base64Encode(const std::string &source, std::string &encoded)
{
gchar *out = g_base64_encode(reinterpret_cast<const guchar *>(source.c_str()), source.size());
if (!out) {
BIO *bio = BIO_new(BIO_s_mem());
if (bio == nullptr) {
CLOGE("Base64Encode error: BIO_new failed");
return false;
}
gsize out_len = strlen(out);
encoded = std::string(out, out_len);
g_free(out);
return true;
BIO *b64 = BIO_new(BIO_f_base64());
if (b64 == nullptr) {
CLOGE("Base64Encode error: BIO_f_base64 failed");
BIO_free(bio);
return false;
}
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_push(b64, bio);
int result = BIO_write(b64, source.c_str(), source.length());
if (result <= 0) {
CLOGE("Base64Encode error: bio write fail.");
BIO_free_all(b64);
return false;
}
BIO_flush(b64);
BUF_MEM *bptr = nullptr;
bool ret = false;
BIO_get_mem_ptr(b64, &bptr);
if (bptr != nullptr) {
encoded = std::string(bptr->data, bptr->length);
ret = true;
}
BIO_free_all(b64);
return ret;
}
bool Utils::Base64Decode(const std::string &encoded, std::string &decoded)
{
gsize out_len = 0;
guchar *decodeData = g_base64_decode(encoded.c_str(), &out_len);
if (!decodeData) {
if (encoded.length() % BASE64_DEST_UNIT_SIZE != 0 || encoded.length() == 0) {
return false;
}
decoded = std::string(reinterpret_cast<const char *>(decodeData), out_len);
g_free(decodeData);
return true;
}
uint32_t decodedLen = encoded.length() * BASE64_SRC_UNIT_SIZE / BASE64_DEST_UNIT_SIZE;
if (encoded.at(encoded.length() - BASE64_UNIT_ONE_PADDING) == '=') {
decodedLen--;
if (encoded.at(encoded.length() - BASE64_UNIT_TWO_PADDING) == '=') {
decodedLen--;
}
}
bool ret = false;
char* buffer = static_cast<char *>(malloc(decodedLen));
if (buffer == nullptr) {
return ret;
}
BIO *bio = BIO_new_mem_buf(encoded.c_str(), encoded.length());
if (bio == nullptr) {
free(buffer);
return ret;
}
BIO *b64 = BIO_new(BIO_f_base64());
if (b64 == nullptr) {
CLOGE("Base64Encode error: BIO_f_base64 failed");
free(buffer);
BIO_free(bio);
return false;
}
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_push(b64, bio);
if (BIO_read(b64, buffer, encoded.length()) == static_cast<int32_t>(decodedLen)) {
decoded = std::string(buffer, decodedLen);
ret = true;
}
free(buffer);
BIO_free_all(b64);
return ret;
}
void Utils::SplitString(const std::string &src, std::vector<std::string> &dest, const std::string &seperator)
{
@ -170,6 +242,13 @@ bool Utils::IsArrayAllZero(const uint8_t *input, int length)
return isAllZero;
}
uint64_t Utils::TimeMilliSecond()
{
struct timeval curTime = {0, 0};
gettimeofday(&curTime, nullptr);
return static_cast<int64_t>(curTime.tv_sec) * USEC_1000 + curTime.tv_usec / USEC_1000;
}
std::string Utils::Mask(const std::string &str)
{
if (str.empty() || str.length() <= MASK_MIN_LEN) {
@ -181,14 +260,31 @@ std::string Utils::Mask(const std::string &str)
}
}
DrmType Utils::DrmUuidToType(std::string drmUUID)
{
if (drmUUID == UUID_CHINADRM) {
return DrmType::CHINADRM;
} else if (drmUUID == UUID_WIDEVINE) {
return DrmType::WIDEVINE;
} else if (drmUUID == UUID_PLAYREADY) {
return DrmType::PLAYREADY;
}
return DrmType::DRM_BASE;
}
int32_t Utils::GetCurrentActiveAccountUserId()
{
std::vector<int> activatedOsAccountIds;
OHOS::ErrCode res = OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(activatedOsAccountIds);
if (res != OHOS::ERR_OK || activatedOsAccountIds.size() <= 0) {
CLOGE("QueryActiveOsAccountIds failed res:%{public}d", res);
return DEFAULT_OS_ACCOUNT_ID;
}
int osAccountId = activatedOsAccountIds[0];
if (osAccountId != DEFAULT_OS_ACCOUNT_ID) {
CLOGI("currentOsAccount:%{public}d", osAccountId);
}
return osAccountId;
}
@ -198,8 +294,10 @@ std::string Utils::GetOhosAccountId()
AccountSA::OhosAccountInfo accountInfo;
OHOS::ErrCode res = AccountSA::OhosAccountKits::GetInstance().GetOhosAccountInfo(accountInfo);
if (res != OHOS::ERR_OK || accountInfo.uid_ == "") {
CLOGE("GetOhosAccountInfo failed res:%{public}d", res);
return "";
}
return accountInfo.uid_;
}
@ -207,9 +305,55 @@ int Utils::SetFirstTokenID()
{
uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
auto ret = SetFirstCallerTokenID(tokenId);
CLOGI("SetFirstCallerTokenID ret %{public}d tokenId %{public}d", ret, tokenId);
return ret;
}
void Utils::EnablePowerForceTimingOut()
{
CLOGI("in");
if (isEnablePowerForceTimingOut.load()) {
CLOGI("already enable");
return;
}
isEnablePowerForceTimingOut = true;
auto& powerMgrClient = PowerMgrClient::GetInstance();
// 强制使能超时灭屏
powerMgrClient.SetForceTimingOut(true);
// 超时锁屏,但有常亮锁时不锁屏(如华为视频播放视频时不锁屏),且不发送熄屏广播
powerMgrClient.LockScreenAfterTimingOut(true, true, false);
}
void Utils::ResetPowerForceTimingOut()
{
CLOGI("in");
if (!isEnablePowerForceTimingOut.load()) {
CLOGI("already reset");
return;
}
isEnablePowerForceTimingOut = false;
auto& powerMgrClient = PowerMgrClient::GetInstance();
// 不强制使能超时灭屏
powerMgrClient.SetForceTimingOut(false);
// 超时锁屏,不受常亮锁影响(如华为视频播放视频时也锁屏),恢复发送熄屏广播
powerMgrClient.LockScreenAfterTimingOut(true, false, true);
}
void Utils::LightAndLockScreen()
{
auto& powerMgrClient = PowerMgrClient::GetInstance();
// 结束投屏时,如果手机是熄屏状态,要亮屏并锁屏
bool isScreenOn = powerMgrClient.IsScreenOn();
CLOGI("isScreenOn: %{public}d", isScreenOn);
if (!isScreenOn) {
PowerErrors wakeupRet = powerMgrClient.WakeupDevice(WakeupDeviceType::WAKEUP_DEVICE_APPLICATION,
std::string("cast+ exit playing"));
PowerErrors suspendRet = powerMgrClient.SuspendDevice();
CLOGI("wakeupRet: %{public}d, suspendRet: %{public}d", wakeupRet, suspendRet);
}
}
void Utils::SetThreadName(const std::string &name)
{
@ -220,9 +364,10 @@ void Utils::SetThreadName(const std::string &name)
static std::atomic<unsigned int> suffix = 0;
std::string threadName = name + "-" + std::to_string(suffix++);
if (prctl(PR_SET_NAME, threadName.c_str()) < 0) {
return;
CLOGE("prctl errno %d", errno);
}
}
} // namespace CastEngineService
} // namespace CastEngine
} // namespace OHOS