1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "print_service_ability.h"
16
17 #include <cerrno>
18 #include <ctime>
19 #include <string>
20 #include <sys/time.h>
21 #include <thread>
22 #include <unistd.h>
23
24 #ifdef CUPS_ENABLE
25 #include "print_cups_client.h"
26 #endif // CUPS_ENABLE
27 #include "accesstoken_kit.h"
28 #include "array_wrapper.h"
29 #include "int_wrapper.h"
30 #include "ipc_skeleton.h"
31 #include "iservice_registry.h"
32 #include "print_bms_helper.h"
33 #include "print_constant.h"
34 #include "print_log.h"
35 #include "printer_info.h"
36 #include "print_utils.h"
37 #include "string_wrapper.h"
38 #include "system_ability_definition.h"
39 #include "want_params_wrapper.h"
40 #include "common_event_data.h"
41 #include "common_event_manager.h"
42 #include "common_event_support.h"
43 #include "print_security_guard_manager.h"
44 #include "hisys_event_util.h"
45 #include "nlohmann/json.hpp"
46 #ifdef IPPOVERUSB_ENABLE
47 #include "print_ipp_over_usb_manager.h"
48 #endif // IPPOVERUSB_ENABLE
49 #include <fstream>
50 #include <streambuf>
51
52 namespace OHOS::Print {
53 using namespace std;
54 using namespace OHOS::HiviewDFX;
55 using namespace Security::AccessToken;
56 using json = nlohmann::json;
57 const std::string PRINTER_PREFERENCE_FILE = "/data/service/el2/public/print_service/printer_preference.json";
58
59 const uint32_t MAX_JOBQUEUE_NUM = 512;
60 const uint32_t ASYNC_CMD_DELAY = 10;
61 const int64_t INIT_INTERVAL = 5000L;
62 const int32_t UID_TRANSFORM_DIVISOR = 200000;
63 const std::int32_t START_USER_ID = 100;
64 const std::int32_t MAX_USER_ID = 1099;
65 const uint32_t UNLOAD_SA_INTERVAL = 90000;
66
67 static const std::string SPOOLER_BUNDLE_NAME = "com.ohos.spooler";
68 static const std::string SPOOLER_PACKAGE_NAME = "com.ohos.spooler";
69 static const std::string PRINT_EXTENSION_BUNDLE_NAME = "com.ohos.hwprintext";
70 static const std::string EPRINTER_ID = "com.ohos.hwprintext:ePrintID";
71 static const std::string SPOOLER_ABILITY_NAME = "MainAbility";
72 static const std::string LAUNCH_PARAMETER_DOCUMENT_NAME = "documentName";
73 static const std::string LAUNCH_PARAMETER_JOB_ID = "jobId";
74 static const std::string LAUNCH_PARAMETER_FILE_LIST = "fileList";
75 static const std::string LAUNCH_PARAMETER_FD_LIST = "fdList";
76 static const std::string LAUNCH_PARAMETER_PRINT_ATTRIBUTE = "printAttributes";
77 static const std::string PRINTER_EVENT_TYPE = "printerStateChange";
78 static const std::string PRINTJOB_EVENT_TYPE = "jobStateChange";
79 static const std::string EXTINFO_EVENT_TYPE = "extInfoChange";
80 static const std::string PRINT_ADAPTER_EVENT_TYPE = "printCallback_adapter";
81 static const std::string PRINT_GET_FILE_EVENT_TYPE = "getPrintFileCallback_adapter";
82 static const std::string EVENT_BLOCK = "block";
83 static const std::string EVENT_SUCCESS = "succeed";
84 static const std::string EVENT_FAIL = "fail";
85 static const std::string EVENT_CANCEL = "cancel";
86 static const std::string CALLER_PKG_NAME = "caller.pkgName";
87
88 static const std::string FD = "FD";
89 static const std::string TYPE_PROPERTY = "type";
90 static const std::string VALUE_PROPERTY = "value";
91 static const std::string QUEUE_JOB_LIST_CHANGED = "queuedJobListChanged";
92 static const std::string ACTION_QUEUE_JOB_LIST_CHANGED = "action.printkit.queuedJobListChanged";
93 static const std::string QUEUE_JOB_LIST_PRINTING = "printing";
94 static const std::string QUEUE_JOB_LIST_COMPLETED = "completed";
95 static const std::string QUEUE_JOB_LIST_BLOCKED = "blocked";
96 static const std::string QUEUE_JOB_LIST_CLEAR_BLOCKED = "clear_blocked";
97 static const std::string QUEUE_JOB_LIST_UNSUBSCRIBE = "unsubscribe";
98 static const std::string QUEUE_JOB_LIST_HIDE = "hide";
99 static const std::string SPOOLER_PREVIEW_ABILITY_NAME = "PrintServiceExtAbility";
100 static const std::string SPOOLER_STATUS_BAR_ABILITY_NAME = "PluginPrintIconExtAbility";
101 static const std::string TOKEN_KEY = "ohos.ability.params.token";
102
103 static const std::string NOTIFY_INFO_SPOOLER_CLOSED_FOR_CANCELLED = "spooler_closed_for_cancelled";
104 static const std::string NOTIFY_INFO_SPOOLER_CLOSED_FOR_STARTED = "spooler_closed_for_started";
105
106 static const std::string PRINTER_ID_DELIMITER = ":";
107
108 static bool g_publishState = false;
109
110 REGISTER_SYSTEM_ABILITY_BY_ID(PrintServiceAbility, PRINT_SERVICE_ID, true);
111
112 std::mutex PrintServiceAbility::instanceLock_;
113 sptr<PrintServiceAbility> PrintServiceAbility::instance_;
114 std::shared_ptr<AppExecFwk::EventHandler> PrintServiceAbility::serviceHandler_;
115 std::chrono::time_point<std::chrono::high_resolution_clock> PrintServiceAbility::startPrintTime_;
116 std::string PrintServiceAbility::ingressPackage;
117
PrintServiceAbility(int32_t systemAbilityId,bool runOnCreate)118 PrintServiceAbility::PrintServiceAbility(int32_t systemAbilityId, bool runOnCreate)
119 : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START),
120 spoolerBundleName_(SPOOLER_BUNDLE_NAME), spoolerAbilityName_(SPOOLER_ABILITY_NAME), currentJobOrderId_(0),
121 helper_(nullptr), isJobQueueBlocked_(false), currentUserId_(-1), printAppCount_(0), unloadCount_(0)
122 {}
123
~PrintServiceAbility()124 PrintServiceAbility::~PrintServiceAbility()
125 {
126 PRINT_HILOGE("~PrintServiceAbility state_ is %{public}d.", static_cast<int>(state_));
127 }
128
GetInstance()129 sptr<PrintServiceAbility> PrintServiceAbility::GetInstance()
130 {
131 if (instance_ == nullptr) {
132 std::lock_guard<std::mutex> autoLock(instanceLock_);
133 if (instance_ == nullptr) {
134 instance_ = new PrintServiceAbility(PRINT_SERVICE_ID, true);
135 }
136 }
137 return instance_;
138 }
139
Init()140 int32_t PrintServiceAbility::Init()
141 {
142 if (helper_ == nullptr) {
143 helper_ = std::make_shared<PrintServiceHelper>();
144 }
145 DelayedSingleton<PrintBMSHelper>::GetInstance()->SetHelper(helper_);
146 if (!g_publishState) {
147 bool ret = Publish(PrintServiceAbility::GetInstance());
148 if (!ret) {
149 PRINT_HILOGE("PrintServiceAbility Publish failed.");
150 return E_PRINT_SERVER_FAILURE;
151 }
152 g_publishState = true;
153 }
154 printSystemData_.Init();
155 InitPreferenceMap();
156 state_ = ServiceRunningState::STATE_RUNNING;
157 PRINT_HILOGI("state_ is %{public}d.", static_cast<int>(state_));
158 PRINT_HILOGI("Init PrintServiceAbility success.");
159 helper_->PrintSubscribeCommonEvent();
160 #ifdef IPPOVERUSB_ENABLE
161 PRINT_HILOGD("before PrintIppOverUsbManager Init");
162 DelayedSingleton<PrintIppOverUsbManager>::GetInstance()->Init();
163 PRINT_HILOGD("end PrintIppOverUsbManager Init");
164 #endif // IPPOVERUSB_ENABLE
165 #ifdef CUPS_ENABLE
166 return DelayedSingleton<PrintCupsClient>::GetInstance()->InitCupsResources();
167 #endif // CUPS_ENABLE
168 return ERR_OK;
169 }
170
OnStart()171 void PrintServiceAbility::OnStart()
172 {
173 PRINT_HILOGI("PrintServiceAbility::Enter OnStart.");
174 if (instance_ == nullptr) {
175 instance_ = this;
176 }
177 if (state_ == ServiceRunningState::STATE_RUNNING) {
178 PRINT_HILOGI("PrintServiceAbility is already running.");
179 #ifdef CUPS_ENABLE
180 DelayedSingleton<PrintCupsClient>::GetInstance()->InitCupsResources();
181 #endif // CUPS_ENABLE
182 return;
183 }
184 InitServiceHandler();
185 int32_t ret = Init();
186 if (ret != ERR_OK) {
187 auto callback = [=]() { Init(); };
188 serviceHandler_->PostTask(callback, INIT_INTERVAL);
189 PRINT_HILOGE("PrintServiceAbility Init failed. Try again 5s later");
190 return;
191 }
192 state_ = ServiceRunningState::STATE_RUNNING;
193 return;
194 }
195
InitServiceHandler()196 void PrintServiceAbility::InitServiceHandler()
197 {
198 PRINT_HILOGI("InitServiceHandler started.");
199 if (serviceHandler_ != nullptr) {
200 PRINT_HILOGI("InitServiceHandler already init.");
201 return;
202 }
203 std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("PrintServiceAbility");
204 serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
205 PRINT_HILOGI("InitServiceHandler succeeded.");
206 }
207
ManualStart()208 void PrintServiceAbility::ManualStart()
209 {
210 if (state_ != ServiceRunningState::STATE_RUNNING) {
211 PRINT_HILOGI("PrintServiceAbility restart.");
212 OnStart();
213 } else {
214 #ifdef CUPS_ENABLE
215 DelayedSingleton<PrintCupsClient>::GetInstance()->InitCupsResources();
216 #endif // CUPS_ENABLE
217 }
218 }
219
GetPrintJobOrderId()220 std::string PrintServiceAbility::GetPrintJobOrderId()
221 {
222 std::lock_guard<std::mutex> autoLock(instanceLock_);
223 return std::to_string(currentJobOrderId_++);
224 }
225
OnStop()226 void PrintServiceAbility::OnStop()
227 {
228 PRINT_HILOGI("OnStop started.");
229 if (state_ != ServiceRunningState::STATE_RUNNING) {
230 return;
231 }
232 serviceHandler_ = nullptr;
233 state_ = ServiceRunningState::STATE_NOT_START;
234 PRINT_HILOGI("OnStop end.");
235 }
236
StartService()237 int32_t PrintServiceAbility::StartService()
238 {
239 ManualStart();
240 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
241 PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION);
242 return E_PRINT_NO_PERMISSION;
243 }
244 int64_t callerTokenId = static_cast<int64_t>(IPCSkeleton::GetCallingTokenID());
245 auto iter = printUserDataMap_.find(callerTokenId);
246 if (iter == printUserDataMap_.end()) {
247 auto userData = std::make_shared<PrintUserData>();
248 if (userData != nullptr) {
249 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
250 printUserDataMap_.insert(std::make_pair(callerTokenId, userData));
251 }
252 }
253 PRINT_HILOGI("nativePrint PrintServiceAbility StartService started.");
254 printAppCount_++;
255 PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
256 #ifdef CUPS_ENABLE
257 return DelayedSingleton<PrintCupsClient>::GetInstance()->InitCupsResources();
258 #endif // CUPS_ENABLE
259 return E_PRINT_NONE;
260 }
261
StartPrint(const std::vector<std::string> & fileList,const std::vector<uint32_t> & fdList,std::string & taskId)262 int32_t PrintServiceAbility::StartPrint(const std::vector<std::string> &fileList,
263 const std::vector<uint32_t> &fdList, std::string &taskId)
264 {
265 return CallSpooler(fileList, fdList, taskId);
266 }
267
CallSpooler(const std::vector<std::string> & fileList,const std::vector<uint32_t> & fdList,std::string & taskId)268 int32_t PrintServiceAbility::CallSpooler(const std::vector<std::string> &fileList, const std::vector<uint32_t> &fdList,
269 std::string &taskId)
270 {
271 ManualStart();
272 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
273 PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION);
274 return E_PRINT_NO_PERMISSION;
275 }
276 PRINT_HILOGD("PrintServiceAbility StartPrint started.");
277 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
278 if (taskId.empty()) {
279 PRINT_HILOGE("jobId is empty");
280 return E_PRINT_INVALID_PARAMETER;
281 }
282 PRINT_HILOGI("CallSpooler jobId: %{public}s", taskId.c_str());
283 auto printJob = std::make_shared<PrintJob>();
284 printJob->SetFdList(fdList);
285 printJob->SetJobId(taskId);
286 printJob->SetJobState(PRINT_JOB_PREPARED);
287 RegisterAdapterListener(taskId);
288 std::string callerPkg = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
289 ingressPackage = callerPkg;
290 AddToPrintJobList(taskId, printJob);
291 SendPrintJobEvent(*printJob);
292 securityGuardManager_.receiveBaseInfo(taskId, callerPkg, fileList);
293
294 printAppCount_++;
295 PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
296 return E_PRINT_NONE;
297 }
298
StopPrint(const std::string & taskId)299 int32_t PrintServiceAbility::StopPrint(const std::string &taskId)
300 {
301 ManualStart();
302 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
303 PRINT_HILOGE("no permission to access print service");
304 return E_PRINT_NO_PERMISSION;
305 }
306
307 PRINT_HILOGD("PrintServiceAbility StopPrint started.");
308 return E_PRINT_NONE;
309 }
310
ConnectPrinter(const std::string & printerId)311 int32_t PrintServiceAbility::ConnectPrinter(const std::string &printerId)
312 {
313 ManualStart();
314 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
315 PRINT_HILOGE("no permission to access print service");
316 return E_PRINT_NO_PERMISSION;
317 }
318
319 PRINT_HILOGD("ConnectPrinter started.");
320 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
321
322 if (printerInfoList_.find(printerId) == printerInfoList_.end()) {
323 PRINT_HILOGE("Invalid printer id");
324 return E_PRINT_INVALID_PRINTER;
325 }
326
327 std::string extensionId = PrintUtils::GetExtensionId(printerId);
328 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_CONNECT_PRINTER);
329 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
330 PRINT_HILOGW("ConnectPrinter Not Register Yet!!!");
331 return E_PRINT_SERVER_FAILURE;
332 }
333
334 #ifdef IPPOVERUSB_ENABLE
335 int32_t port = 0;
336 std::string newPrinterId = printerId;
337 auto ret = DelayedSingleton<PrintIppOverUsbManager>::GetInstance()->ConnectPrinter(printerId, port);
338 if (ret && port > 0) {
339 newPrinterId = PrintUtils::GetGlobalId(printerId, std::to_string(port));
340 }
341 auto cbFunc = extCallbackMap_[cid];
342 auto callback = [=]() {
343 if (cbFunc != nullptr) {
344 cbFunc->OnCallback(newPrinterId);
345 }
346 };
347 if (helper_->IsSyncMode()) {
348 callback();
349 } else {
350 serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
351 }
352 #endif // IPPOVERUSB_ENABLE
353 return E_PRINT_NONE;
354 }
355
DisconnectPrinter(const std::string & printerId)356 int32_t PrintServiceAbility::DisconnectPrinter(const std::string &printerId)
357 {
358 ManualStart();
359 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
360 PRINT_HILOGE("no permission to access print service");
361 return E_PRINT_NO_PERMISSION;
362 }
363
364 PRINT_HILOGD("DisconnectPrinter started.");
365 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
366
367 if (printerInfoList_.find(printerId) == printerInfoList_.end()) {
368 PRINT_HILOGE("Invalid printer id");
369 return E_PRINT_INVALID_PRINTER;
370 }
371
372 std::string extensionId = PrintUtils::GetExtensionId(printerId);
373 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_DISCONNECT_PRINTER);
374 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
375 PRINT_HILOGW("DisconnectPrinter Not Register Yet!!!");
376 return E_PRINT_SERVER_FAILURE;
377 }
378
379 auto cbFunc = extCallbackMap_[cid];
380 auto callback = [=]() {
381 if (cbFunc != nullptr) {
382 cbFunc->OnCallback(printerId);
383 }
384 };
385 if (helper_->IsSyncMode()) {
386 callback();
387 } else {
388 serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
389 }
390 return E_PRINT_NONE;
391 }
392
StartDiscoverPrinter(const std::vector<std::string> & extensionIds)393 int32_t PrintServiceAbility::StartDiscoverPrinter(const std::vector<std::string> &extensionIds)
394 {
395 ManualStart();
396 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
397 PRINT_HILOGE("no permission to access print service");
398 return E_PRINT_NO_PERMISSION;
399 }
400
401 PRINT_HILOGD("StartDiscoverPrinter started.");
402 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
403 printerInfoList_.clear();
404 std::map<std::string, AppExecFwk::ExtensionAbilityInfo> abilityList;
405 for (auto extensionId : extensionIds) {
406 if (extensionList_.find(extensionId) != extensionList_.end()) {
407 abilityList.insert(std::make_pair(extensionId, extensionList_[extensionId]));
408 }
409 }
410
411 if (abilityList.empty() && extensionIds.size() > 0) {
412 PRINT_HILOGW("No valid extension found");
413 return E_PRINT_INVALID_EXTENSION;
414 }
415
416 if (extensionIds.empty()) {
417 for (auto extension : extensionList_) {
418 abilityList.insert(std::make_pair(extension.first, extension.second));
419 }
420 }
421
422 if (abilityList.empty()) {
423 PRINT_HILOGW("No extension found");
424 return E_PRINT_INVALID_EXTENSION;
425 }
426
427 for (auto ability : abilityList) {
428 AAFwk::Want want;
429 want.SetElementName(ability.second.bundleName, ability.second.name);
430 if (!StartAbility(want)) {
431 PRINT_HILOGE("Failed to load extension %{public}s", ability.second.name.c_str());
432 continue;
433 }
434 extensionStateList_[ability.second.bundleName] = PRINT_EXTENSION_LOADING;
435 }
436
437 PRINT_HILOGD("StartDiscoverPrinter end.");
438 return E_PRINT_NONE;
439 }
440
DelayStartDiscovery(const std::string & extensionId)441 bool PrintServiceAbility::DelayStartDiscovery(const std::string &extensionId)
442 {
443 PRINT_HILOGD("DelayStartDiscovery started. %{public}s", extensionId.c_str());
444 if (extensionStateList_.find(extensionId) == extensionStateList_.end()) {
445 PRINT_HILOGE("invalid extension id");
446 return false;
447 }
448
449 if (extensionStateList_[extensionId] != PRINT_EXTENSION_LOADED) {
450 PRINT_HILOGE("invalid extension state");
451 return false;
452 }
453
454 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_DISCOVERY);
455 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
456 PRINT_HILOGE("StartDiscoverPrinter Not Register, BUT State is LOADED");
457 return false;
458 }
459
460 int32_t ret = E_PRINT_SERVER_FAILURE;
461 if (extCallbackMap_[cid]->OnCallback()) {
462 ret = E_PRINT_NONE;
463 }
464 return ret == E_PRINT_NONE;
465 }
466
StopDiscoverPrinter()467 int32_t PrintServiceAbility::StopDiscoverPrinter()
468 {
469 ManualStart();
470 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
471 PRINT_HILOGE("no permission to access print service");
472 return E_PRINT_NO_PERMISSION;
473 }
474 PRINT_HILOGD("StopDiscoverPrinter started.");
475 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
476
477 for (auto extension : extensionStateList_) {
478 if (extension.second < PRINT_EXTENSION_LOADING) {
479 continue;
480 }
481 extension.second = PRINT_EXTENSION_UNLOAD;
482 std::string cid = PrintUtils::EncodeExtensionCid(extension.first, PRINT_EXTCB_STOP_DISCOVERY);
483 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
484 PRINT_HILOGE("StopDiscoverPrinter Not Register, BUT State is LOADED");
485 continue;
486 }
487
488 auto cbFunc = extCallbackMap_[cid];
489 auto callback = [=]() {
490 if (cbFunc != nullptr) {
491 cbFunc->OnCallback();
492 }
493 };
494 if (helper_->IsSyncMode()) {
495 callback();
496 } else {
497 serviceHandler_->PostTask(callback, 0);
498 }
499 }
500 PRINT_HILOGW("StopDiscoverPrinter out.");
501 return E_PRINT_NONE;
502 }
503
DestroyExtension()504 int32_t PrintServiceAbility::DestroyExtension()
505 {
506 ManualStart();
507 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
508 PRINT_HILOGE("no permission to access print service");
509 return E_PRINT_NO_PERMISSION;
510 }
511 PRINT_HILOGD("DestroyExtension started.");
512 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
513
514 for (auto extension : extensionStateList_) {
515 if (extension.second < PRINT_EXTENSION_LOADING) {
516 continue;
517 }
518 extension.second = PRINT_EXTENSION_UNLOAD;
519 std::string cid = PrintUtils::EncodeExtensionCid(extension.first, PRINT_EXTCB_DESTROY_EXTENSION);
520 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
521 PRINT_HILOGE("Destroy extension Not Register, BUT State is LOADED");
522 continue;
523 }
524
525 auto cbFunc = extCallbackMap_[cid];
526 if (cbFunc != nullptr) {
527 cbFunc->OnCallback();
528 }
529 }
530 PRINT_HILOGW("DestroyExtension out.");
531 return E_PRINT_NONE;
532 }
533
QueryAllExtension(std::vector<PrintExtensionInfo> & extensionInfos)534 int32_t PrintServiceAbility::QueryAllExtension(std::vector<PrintExtensionInfo> &extensionInfos)
535 {
536 ManualStart();
537 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
538 PRINT_HILOGE("no permission to access print service");
539 return E_PRINT_NO_PERMISSION;
540 }
541 PRINT_HILOGD("QueryAllExtension started.");
542 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
543
544 std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfo;
545 if (!DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryExtensionInfos(extensionInfo)) {
546 PRINT_HILOGE("Failed to query extension");
547 return E_PRINT_SERVER_FAILURE;
548 }
549
550 extensionList_.clear();
551 extensionStateList_.clear();
552 for (auto extInfo : extensionInfo) {
553 PRINT_HILOGD("bundleName = %{public}s", extInfo.bundleName.c_str());
554 PRINT_HILOGD("moduleName = %{public}s", extInfo.moduleName.c_str());
555 PRINT_HILOGD("name = %{public}s", extInfo.name.c_str());
556 PrintExtensionInfo printExtInfo = ConvertToPrintExtensionInfo(extInfo);
557 extensionInfos.emplace_back(printExtInfo);
558 extensionList_.insert(std::make_pair(printExtInfo.GetExtensionId(), extInfo));
559 extensionStateList_.insert(std::make_pair(printExtInfo.GetExtensionId(), PRINT_EXTENSION_UNLOAD));
560 }
561 PRINT_HILOGI("QueryAllExtension End.");
562 return E_PRINT_NONE;
563 }
564
QueryAllPrintJob(std::vector<PrintJob> & printJobs)565 int32_t PrintServiceAbility::QueryAllPrintJob(std::vector<PrintJob> &printJobs)
566 {
567 ManualStart();
568 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
569 PRINT_HILOGE("no permission to access print service");
570 return E_PRINT_NO_PERMISSION;
571 }
572 PRINT_HILOGD("QueryAllPrintJob started.");
573 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
574 auto userData = GetCurrentUserData();
575 if (userData == nullptr) {
576 PRINT_HILOGE("Get user data failed.");
577 return E_PRINT_INVALID_USERID;
578 }
579 int32_t ret = userData->QueryAllPrintJob(printJobs);
580 if (ret != E_PRINT_NONE) {
581 PRINT_HILOGE("QueryAllPrintJob failed.");
582 return ret;
583 }
584 return E_PRINT_NONE;
585 }
586
QueryAddedPrinter(std::vector<std::string> & printerList)587 int32_t PrintServiceAbility::QueryAddedPrinter(std::vector<std::string> &printerList)
588 {
589 ManualStart();
590 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
591 PRINT_HILOGE("no permission to access print service");
592 return E_PRINT_NO_PERMISSION;
593 }
594 PRINT_HILOGD("QueryAddedPrinter started.");
595 std::vector<std::string> printerNameList;
596 printSystemData_.GetAddedPrinterListFromSystemData(printerNameList);
597 if (printerNameList.size() <= 0) {
598 PRINT_HILOGW("no added printerId");
599 return E_PRINT_NONE;
600 }
601 for (uint32_t i = 0; i < printerNameList.size(); i++) {
602 PRINT_HILOGD("QueryAddedPrinter in printerName %{public}s", printerNameList[i].c_str());
603 std::string printerId = printSystemData_.QueryPrinterIdByStandardizeName(printerNameList[i]);
604 PRINT_HILOGD("QueryAddedPrinter in printerId %{public}s", printerId.c_str());
605 if (printerId.empty()) {
606 continue;
607 }
608 printerList.push_back(printerId);
609 }
610 return E_PRINT_NONE;
611 }
612
QueryPrinterInfoByPrinterId(const std::string & printerId,PrinterInfo & info)613 int32_t PrintServiceAbility::QueryPrinterInfoByPrinterId(const std::string &printerId, PrinterInfo &info)
614 {
615 ManualStart();
616 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
617 PRINT_HILOGE("no permission to access print service");
618 return E_PRINT_NO_PERMISSION;
619 }
620 PRINT_HILOGD("QueryPrinterInfoByPrinterId started %{public}s", printerId.c_str());
621 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
622 info.SetPrinterId(printerId);
623 bool findCapsInSystemData = false;
624 OHOS::Print::CupsPrinterInfo cupsPrinter;
625 if (printSystemData_.QueryCupsPrinterInfoByPrinterId(printerId, cupsPrinter)) {
626 info.SetPrinterName(PrintUtil::RemoveUnderlineFromPrinterName(cupsPrinter.name));
627 nlohmann::json option;
628 option["printerName"] = cupsPrinter.name;
629 option["printerUri"] = cupsPrinter.uri;
630 option["make"] = cupsPrinter.maker;
631 option["alias"] = cupsPrinter.alias;
632 info.SetOption(option.dump());
633 PrinterCapability printerCapability;
634 if (printSystemData_.GetPrinterCapabilityFromSystemData(cupsPrinter, printerId, printerCapability)) {
635 findCapsInSystemData = true;
636 info.SetCapability(printerCapability);
637 }
638 info.SetPrinterStatus(cupsPrinter.printerStatus);
639 PRINT_HILOGI("QueryPrinterInfoByPrinterId printerStatus: %{public}d", info.GetPrinterStatus());
640 }
641 PRINT_HILOGD("QueryPrinterInfoByPrinterId printerName = %{public}s", info.GetPrinterName().c_str());
642 if (!findCapsInSystemData) {
643 #ifdef CUPS_ENABLE
644 int32_t ret = DelayedSingleton<PrintCupsClient>::GetInstance()->QueryPrinterInfoByPrinterId(printerId, info);
645 if (ret != 0) {
646 PRINT_HILOGE("cups QueryPrinterInfoByPrinterId fail, ret = %{public}d", ret);
647 return E_PRINT_INVALID_PRINTER;
648 }
649 #endif // CUPS_ENABLE
650 }
651 if (info.HasCapability()) {
652 printSystemData_.InsertPrinterInfo(printerId, info);
653 }
654 if (CheckIsDefaultPrinter(printerId)) {
655 PRINT_HILOGI("is default printer");
656 info.SetIsDefaultPrinter(true);
657 }
658 if (CheckIsLastUsedPrinter(printerId)) {
659 PRINT_HILOGI("is last used printer");
660 info.SetIsLastUsedPrinter(true);
661 }
662 return E_PRINT_NONE;
663 }
664
QueryPrinterProperties(const std::string & printerId,const std::vector<std::string> & keyList,std::vector<std::string> & valueList)665 int32_t PrintServiceAbility::QueryPrinterProperties(const std::string &printerId,
666 const std::vector<std::string> &keyList, std::vector<std::string> &valueList)
667 {
668 ManualStart();
669 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
670 PRINT_HILOGE("no permission to access print service");
671 return E_PRINT_NO_PERMISSION;
672 }
673 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
674 PRINT_HILOGI("printerId %{public}s", printerId.c_str());
675 PrinterInfo printerInfo;
676 uint32_t ret = QueryPrinterInfoByPrinterId(printerId, printerInfo);
677 if (ret != E_PRINT_NONE) {
678 PRINT_HILOGW("no printerInfo");
679 return E_PRINT_INVALID_PRINTER;
680 }
681 PRINT_HILOGD("printerInfo %{public}s", printerInfo.GetPrinterName().c_str());
682 for (auto &key : keyList) {
683 PRINT_HILOGD("QueryPrinterProperties key %{public}s", key.c_str());
684 if (key == "printerPreference") {
685 std::string printerPreference;
686 if (GetPrinterPreference(printerId, printerPreference) == E_PRINT_NONE) {
687 nlohmann::json preferenceJson = json::parse(printerPreference);
688 valueList.emplace_back(preferenceJson.at("setting").dump());
689 PRINT_HILOGD("getPrinterPreference success");
690 }
691 }
692 }
693 return E_PRINT_NONE;
694 }
695
QueryPrintJobById(std::string & printJobId,PrintJob & printJob)696 int32_t PrintServiceAbility::QueryPrintJobById(std::string &printJobId, PrintJob &printJob)
697 {
698 ManualStart();
699 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
700 PRINT_HILOGE("no permission to access print service");
701 return E_PRINT_NO_PERMISSION;
702 }
703 PRINT_HILOGD("QueryPrintJobById started.");
704 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
705
706 auto userData = GetCurrentUserData();
707 if (userData == nullptr) {
708 PRINT_HILOGE("Get user data failed.");
709 return E_PRINT_INVALID_USERID;
710 }
711 int32_t ret = userData->QueryPrintJobById(printJobId, printJob);
712 if (ret != E_PRINT_NONE) {
713 PRINT_HILOGE("QueryPrintJobById failed.");
714 return ret;
715 }
716 return E_PRINT_NONE;
717 }
718
AddPrinterToCups(const std::string & printerUri,const std::string & printerName,const std::string & printerMake)719 int32_t PrintServiceAbility::AddPrinterToCups(const std::string &printerUri, const std::string &printerName,
720 const std::string &printerMake)
721 {
722 ManualStart();
723 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
724 PRINT_HILOGE("no permission to access print service");
725 return E_PRINT_NO_PERMISSION;
726 }
727 PRINT_HILOGD("AddPrinterToCups started.");
728 #ifdef CUPS_ENABLE
729 auto ret = DelayedSingleton<PrintCupsClient>::GetInstance()->AddPrinterToCups(printerUri, printerName, printerMake);
730 if (ret != E_PRINT_NONE) {
731 PRINT_HILOGW("AddPrinterToCups error = %{public}d.", ret);
732 return ret;
733 }
734 #endif // CUPS_ENABLE
735 std::string id = QueryPrinterIdByStandardizeName(printerName);
736 if (id.empty()) {
737 PRINT_HILOGE("can not find the printer");
738 return E_PRINT_INVALID_PRINTER;
739 }
740 CupsPrinterInfo info;
741 info.name = printerName;
742 info.uri = printerUri;
743 info.maker = printerMake;
744 info.printerStatus = PRINTER_STATUS_IDLE;
745 ret = QueryPrinterCapabilityByUri(printerUri, id, info.printerCapability);
746 if (ret != 0) {
747 PRINT_HILOGE("AddPrinterToCups QueryPrinterCapabilityByUri fail");
748 return ret;
749 }
750 if (!printSystemData_.IsPrinterAdded(id)) {
751 printSystemData_.InsertCupsPrinter(id, info, true);
752 printSystemData_.SaveCupsPrinterMap();
753 PrinterInfo printerInfo;
754 printSystemData_.QueryPrinterInfoById(id, printerInfo);
755 printerInfo.SetIsLastUsedPrinter(true);
756 SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, printerInfo);
757 SendPrinterChangeEvent(PRINTER_EVENT_ADDED, printerInfo);
758 SetLastUsedPrinter(id);
759 }
760 PRINT_HILOGD("AddPrinterToCups End.");
761 return E_PRINT_NONE;
762 }
763
QueryPrinterIdByStandardizeName(const std::string & printerName)764 std::string PrintServiceAbility::QueryPrinterIdByStandardizeName(const std::string &printerName)
765 {
766 PRINT_HILOGD("QueryPrinterIdByStandardizeName printerName : %{public}s.", printerName.c_str());
767 for (auto iter = printerInfoList_.begin(); iter != printerInfoList_.end(); ++iter) {
768 auto printerInfoPtr = iter->second;
769 if (printerInfoPtr == nullptr) {
770 continue;
771 }
772 std::string stdName = PrintUtil::StandardizePrinterName(printerInfoPtr->GetPrinterName());
773 PRINT_HILOGD("QueryPrinterIdByStandardizeName stdName : %{public}s.", stdName.c_str());
774 if (stdName != PrintUtil::StandardizePrinterName(printerName)) {
775 continue;
776 }
777 std::string id = iter->first;
778 PRINT_HILOGD("QueryPrinterIdByStandardizeName printerId : %{public}s.", id.c_str());
779 return id;
780 }
781 return "";
782 }
783
QueryPrinterCapabilityByUri(const std::string & printerUri,const std::string & printerId,PrinterCapability & printerCaps)784 int32_t PrintServiceAbility::QueryPrinterCapabilityByUri(const std::string &printerUri, const std::string &printerId,
785 PrinterCapability &printerCaps)
786 {
787 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
788 ManualStart();
789 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
790 PRINT_HILOGE("no permission to access print service");
791 return E_PRINT_NO_PERMISSION;
792 }
793 PRINT_HILOGD("QueryPrinterCapabilityByUri started.");
794 #ifdef CUPS_ENABLE
795 DelayedSingleton<PrintCupsClient>::GetInstance()->QueryPrinterCapabilityByUri(printerUri, printerId, printerCaps);
796 #endif // CUPS_ENABLE
797 PRINT_HILOGD("QueryPrinterCapabilityByUri End.");
798 WritePrinterPreference(printerId, printerCaps);
799 return E_PRINT_NONE;
800 }
801
StandardizePrinterId(const std::string & printerId)802 std::string PrintServiceAbility::StandardizePrinterId(const std::string &printerId)
803 {
804 PRINT_HILOGI("printerId: %{public}s", printerId.c_str());
805 std::string standardPrinterId = printerId;
806 auto pos = printerId.find(PRINTER_ID_DELIMITER);
807 if (pos == std::string::npos) {
808 return "";
809 }
810 if (printerId.substr(0, pos) != SPOOLER_BUNDLE_NAME) {
811 standardPrinterId.assign(SPOOLER_BUNDLE_NAME + PRINTER_ID_DELIMITER + printerId);
812 }
813 return standardPrinterId;
814 }
815
BuildPrinterPreferenceByDefault(nlohmann::json & capOpt,PreferenceSetting & printerDefaultAttr)816 void PrintServiceAbility::BuildPrinterPreferenceByDefault(nlohmann::json& capOpt, PreferenceSetting &printerDefaultAttr)
817 {
818 if (capOpt.contains("defaultPageSizeId") && capOpt["defaultPageSizeId"].is_string()) {
819 printerDefaultAttr.pagesizeId = capOpt["defaultPageSizeId"].get<std::string>();
820 }
821 if (capOpt.contains("orientation-requested-default") && capOpt["orientation-requested-default"].is_string()) {
822 printerDefaultAttr.orientation = capOpt["orientation-requested-default"].get<std::string>();
823 }
824 if (capOpt.contains("sides-default") && capOpt["sides-default"].is_string()) {
825 printerDefaultAttr.duplex = capOpt["sides-default"].get<std::string>();
826 }
827 if (capOpt.contains("print-quality-default") && capOpt["print-quality-default"].is_string()) {
828 printerDefaultAttr.quality = capOpt["print-quality-default"].get<std::string>();
829 }
830 }
831
BuildPrinterPreferenceByOption(std::string & key,std::string & supportedOpts,std::vector<std::string> & optAttrs)832 void PrintServiceAbility::BuildPrinterPreferenceByOption(std::string& key, std::string& supportedOpts,
833 std::vector<std::string>& optAttrs)
834 {
835 if (supportedOpts.length() <= 0) {
836 return;
837 }
838 PRINT_HILOGI("BuildPrinterPreferenceByOption %{public}s", supportedOpts.c_str());
839 if (json::accept(supportedOpts) && supportedOpts.find("{") != std::string::npos) {
840 nlohmann::json ArrJson = json::parse(supportedOpts);
841 BuildPrinterAttrComponentByJson(key, ArrJson, optAttrs);
842 } else {
843 PrintUtil::Str2VecStr(supportedOpts, optAttrs);
844 }
845 }
846
BuildPrinterPreference(PrinterCapability & cap,PrinterPreference & printPreference)847 int32_t PrintServiceAbility::BuildPrinterPreference(PrinterCapability &cap, PrinterPreference &printPreference)
848 {
849 std::string capOption = cap.GetOption();
850 PRINT_HILOGI("printer capOption %{public}s", capOption.c_str());
851 if (!json::accept(capOption)) {
852 PRINT_HILOGW("capOption can not parse to json object");
853 return E_PRINT_INVALID_PARAMETER;
854 }
855 nlohmann::json capJson = json::parse(capOption);
856 if (!capJson.contains("cupsOptions")) {
857 PRINT_HILOGW("The capJson does not have a cupsOptions attribute.");
858 return E_PRINT_INVALID_PARAMETER;
859 }
860 nlohmann::json capOpt = capJson["cupsOptions"];
861
862 std::string key = "id";
863 if (capOpt.contains("supportedPageSizeArray") && capOpt["supportedPageSizeArray"].is_string()) {
864 std::string supportedPageSizeOpts = capOpt["supportedPageSizeArray"].get<std::string>();
865 BuildPrinterPreferenceByOption(key, supportedPageSizeOpts, printPreference.pagesizeId);
866 }
867
868 key = "orientation";
869 if (capOpt.contains("orientation-requested-supported") && capOpt["orientation-requested-supported"].is_string()) {
870 std::string supportedOriOpts = capOpt["orientation-requested-supported"].get<std::string>();
871 BuildPrinterPreferenceByOption(key, supportedOriOpts, printPreference.orientation);
872 }
873
874 key = "duplex";
875 if (capOpt.contains("sides-supported") && capOpt["sides-supported"].is_string()) {
876 std::string supportedDeplexOpts = capOpt["sides-supported"].get<std::string>();
877 BuildPrinterPreferenceByOption(key, supportedDeplexOpts, printPreference.duplex);
878 }
879
880 key = "quality";
881 if (capOpt.contains("print-quality-supported") && capOpt["print-quality-supported"].is_string()) {
882 std::string supportedQualityOpts = capOpt["print-quality-supported"].get<std::string>();
883 BuildPrinterPreferenceByOption(key, supportedQualityOpts, printPreference.quality);
884 }
885
886 BuildPrinterPreferenceByDefault(capOpt, printPreference.defaultSetting);
887 return E_PRINT_NONE;
888 }
889
BuildPrinterAttrComponentByJson(std::string & key,nlohmann::json & jsonArrObject,std::vector<std::string> & printerAttrs)890 void PrintServiceAbility::BuildPrinterAttrComponentByJson(std::string& key, nlohmann::json& jsonArrObject,
891 std::vector<std::string> &printerAttrs)
892 {
893 if (!jsonArrObject.is_array()) {
894 PRINT_HILOGW("can not PrinterAttrsComponent by jsonArrObject");
895 return;
896 }
897 for (auto &element : jsonArrObject.items()) {
898 nlohmann::json object = element.value();
899 if (object.contains(key)) {
900 if (object[key].is_string()) {
901 printerAttrs.push_back(object[key].get<std::string>());
902 } else if (object[key].is_number()) {
903 int value = object[key];
904 printerAttrs.push_back(std::to_string(value));
905 }
906 }
907 }
908 }
909
GetPrinterPreference(const std::string & printerId,std::string & printerPreference)910 int32_t PrintServiceAbility::GetPrinterPreference(const std::string &printerId, std::string &printerPreference)
911 {
912 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
913 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
914 PRINT_HILOGE("no permission to access print service");
915 return E_PRINT_NO_PERMISSION;
916 }
917 int printerPreferenceNum = static_cast<int>(printerIdAndPreferenceMap_.size());
918 if (printerPreferenceNum <= 0) {
919 InitPreferenceMap();
920 }
921 if (printerIdAndPreferenceMap_.size() > 0 && ReadPreferenceFromFile(printerId, printerPreference)) {
922 PRINT_HILOGI("ReadPreferenceFromFile %{public}s", printerPreference.c_str());
923 return E_PRINT_NONE;
924 }
925 return E_PRINT_INVALID_PRINTER;
926 }
927
SetPrinterPreference(const std::string & printerId,const std::string & printerSetting)928 int32_t PrintServiceAbility::SetPrinterPreference(const std::string &printerId, const std::string &printerSetting)
929 {
930 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
931 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
932 PRINT_HILOGE("no permission to access print service");
933 return E_PRINT_NO_PERMISSION;
934 }
935 int printerPreferenceNum = static_cast<int>(printerIdAndPreferenceMap_.size());
936 if (printerPreferenceNum <= 0) {
937 InitPreferenceMap();
938 }
939 std::string printPreference;
940 if (printerIdAndPreferenceMap_.size() > 0 && ReadPreferenceFromFile(printerId, printPreference)) {
941 if (!nlohmann::json::accept(printPreference) && !nlohmann::json::accept(printerSetting)) {
942 PRINT_HILOGW("json accept fail");
943 return E_PRINT_INVALID_PRINTER;
944 }
945 nlohmann::json objectJson = nlohmann::json::parse(printPreference);
946 PrinterPreference oldPrintPreference = PrinterPreference::BuildPrinterPreferenceFromJson(objectJson);
947
948 PRINT_HILOGD("printerSetting %{public}s", printerSetting.c_str());
949 nlohmann::json settingJson = nlohmann::json::parse(printerSetting);
950 PreferenceSetting newSetting = PreferenceSetting::BuildPreferenceSettingFromJson(settingJson);
951 oldPrintPreference.setting = newSetting;
952
953 nlohmann::json savePrinterPreference = oldPrintPreference.BuildPrinterPreferenceJson();
954 std::string newPrintPreference = savePrinterPreference.dump();
955 PRINT_HILOGI("WriteNewPreferenceToFile %{public}s", newPrintPreference.c_str());
956 printerIdAndPreferenceMap_[printerId] = newPrintPreference;
957 PrinterInfo info;
958 printSystemData_.QueryPrinterInfoById(printerId, info);
959 SendPrinterChangeEvent(PRINTER_EVENT_PREFERENCE_CHANGED, info);
960 WritePreferenceToFile();
961 return E_PRINT_NONE;
962 }
963 return E_PRINT_INVALID_PRINTER;
964 }
965
ReadPreferenceFromFile(const std::string & printerId,std::string & printPreference)966 bool PrintServiceAbility::ReadPreferenceFromFile(const std::string &printerId, std::string& printPreference)
967 {
968 auto iter = printerIdAndPreferenceMap_.find(printerId);
969 if (iter != printerIdAndPreferenceMap_.end()) {
970 printPreference = printerIdAndPreferenceMap_[printerId];
971 PRINT_HILOGE("open printer preference find %{public}s", printPreference.c_str());
972 return true;
973 }
974 return false;
975 }
976
InitPreferenceMap()977 void PrintServiceAbility::InitPreferenceMap()
978 {
979 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
980 std::ifstream ifs(PRINTER_PREFERENCE_FILE.c_str(), std::ios::in | std::ios::binary);
981 if (!ifs.is_open()) {
982 PRINT_HILOGW("open printer preference file fail");
983 return;
984 }
985 std::string fileData((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
986 ifs.close();
987 if (!nlohmann::json::accept(fileData)) {
988 PRINT_HILOGW("json accept fail");
989 return;
990 }
991 nlohmann::json jsonObject = nlohmann::json::parse(fileData);
992 if (!jsonObject.contains("printer_list") || !jsonObject["printer_list"].is_array()) {
993 PRINT_HILOGW("can not find printer_list");
994 return;
995 }
996 for (auto &element : jsonObject["printer_list"].items()) {
997 nlohmann::json object = element.value();
998 for (auto it = object.begin(); it != object.end(); it++) {
999 std::string printerId = it.key();
1000 nlohmann::json printPreferenceJson = object[printerId];
1001 printerIdAndPreferenceMap_[printerId] = printPreferenceJson.dump();
1002 }
1003 }
1004 }
1005
WritePreferenceToFile()1006 bool PrintServiceAbility::WritePreferenceToFile()
1007 {
1008 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1009 int32_t fd = open(PRINTER_PREFERENCE_FILE.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0740);
1010 PRINT_HILOGD("SavePrinterPreferenceMap fd: %{public}d", fd);
1011 if (fd < 0) {
1012 PRINT_HILOGW("Failed to open file errno: %{public}s", std::to_string(errno).c_str());
1013 close(fd);
1014 return false;
1015 }
1016 nlohmann::json printerMapJson = nlohmann::json::array();
1017
1018 for (auto& printPreference : printerIdAndPreferenceMap_) {
1019 if (json::accept(printPreference.second)) {
1020 nlohmann::json printPreferenceJson = nlohmann::json::parse(printPreference.second);
1021 nlohmann::json objectJson;
1022 objectJson[printPreference.first] = printPreferenceJson;
1023 printerMapJson.push_back(objectJson);
1024 }
1025 }
1026
1027 nlohmann::json jsonObject;
1028 jsonObject["printer_list"] = printerMapJson;
1029 std::string jsonString = jsonObject.dump();
1030 size_t jsonLength = jsonString.length();
1031 auto writeLength = write(fd, jsonString.c_str(), jsonLength);
1032 close(fd);
1033 return (size_t)writeLength == jsonLength;
1034 }
1035
WritePrinterPreference(const std::string & printerId,PrinterCapability & printerCaps)1036 bool PrintServiceAbility::WritePrinterPreference(const std::string &printerId, PrinterCapability &printerCaps)
1037 {
1038 std::string standardPrinterId = StandardizePrinterId(printerId);
1039 if (printerCaps.HasOption()) {
1040 if (printerIdAndPreferenceMap_.count(standardPrinterId)) {
1041 return false;
1042 }
1043 PrinterPreference printPreference;
1044 int32_t ret = BuildPrinterPreference(printerCaps, printPreference);
1045 if (ret != E_PRINT_NONE) {
1046 PRINT_HILOGE("printerCaps can not success to printPreference");
1047 return false;
1048 }
1049 nlohmann::json jsonObject = nlohmann::json::object();
1050 jsonObject = printPreference.BuildPrinterPreferenceJson();
1051 std::string savePrinterPreference = jsonObject.dump();
1052 printerIdAndPreferenceMap_.insert(std::make_pair(standardPrinterId, savePrinterPreference));
1053 return WritePreferenceToFile();
1054 }
1055 return false;
1056 }
1057
WriteEprinterPreference(const std::string & printerId,PrinterCapability & printerCaps)1058 bool PrintServiceAbility::WriteEprinterPreference(const std::string &printerId, PrinterCapability &printerCaps)
1059 {
1060 if (printerIdAndPreferenceMap_.count(printerId)) {
1061 return false;
1062 }
1063 json printerPreference;
1064 std::vector<PrintPageSize> pageSize;
1065 printerCaps.GetPageSize(pageSize);
1066 json pageSizeList = json::array();
1067 for (auto& item : pageSize) {
1068 pageSizeList.push_back(item.GetId());
1069 }
1070 std::vector<std::string> emptyStrArr;
1071 printerPreference["pagesizeId"] = pageSizeList;
1072 printerPreference["orientation"] = emptyStrArr;
1073 printerPreference["duplex"] = {to_string(printerCaps.GetDuplexMode())};
1074 printerPreference["quality"] = emptyStrArr;
1075 PreferenceSetting preferenceSetting;
1076 printerPreference["defaultSetting"] = preferenceSetting.BuildPreferenceSettingJson();
1077 printerPreference["setting"] = preferenceSetting.BuildPreferenceSettingJson();
1078 std::string savePrinterPreference = printerPreference.dump();
1079 PRINT_HILOGD("savePrinterPreference = %{public}s", savePrinterPreference.c_str());
1080 printerIdAndPreferenceMap_.insert(std::make_pair(printerId, savePrinterPreference));
1081 return WritePreferenceToFile();
1082 }
1083
UpdatePrintJobOptionByPrinterId(PrintJob & printJob)1084 bool PrintServiceAbility::UpdatePrintJobOptionByPrinterId(PrintJob &printJob)
1085 {
1086 CupsPrinterInfo printerInfo;
1087 if (!printSystemData_.QueryCupsPrinterInfoByPrinterId(printJob.GetPrinterId(), printerInfo)) {
1088 PRINT_HILOGW("cannot find printer info by printerId");
1089 return false;
1090 }
1091 std::string oldOption = printJob.GetOption();
1092 PRINT_HILOGD("Print job option: %{public}s", oldOption.c_str());
1093 if (!json::accept(oldOption)) {
1094 PRINT_HILOGW("old option not accepted");
1095 return false;
1096 }
1097 nlohmann::json infoJson = json::parse(oldOption);
1098 infoJson["printerName"] = printerInfo.name;
1099 infoJson["printerUri"] = printerInfo.uri;
1100 infoJson["alias"] = printerInfo.alias;
1101 std::string updatedOption = infoJson.dump();
1102 PRINT_HILOGD("Updated print job option: %{public}s", updatedOption.c_str());
1103 printJob.SetOption(updatedOption);
1104 return true;
1105 }
1106
AddNativePrintJob(const std::string & jobId,PrintJob & printJob)1107 std::shared_ptr<PrintJob> PrintServiceAbility::AddNativePrintJob(const std::string &jobId, PrintJob &printJob)
1108 {
1109 PRINT_HILOGD("jobId %{public}s", jobId.c_str());
1110 printJob.SetJobId(jobId);
1111 printJob.SetJobState(PRINT_JOB_PREPARED);
1112 auto nativePrintJob = std::make_shared<PrintJob>();
1113 if (nativePrintJob == nullptr) {
1114 PRINT_HILOGW("nativePrintJob is null");
1115 return nullptr;
1116 }
1117 nativePrintJob->UpdateParams(printJob);
1118 nativePrintJob->Dump();
1119 AddToPrintJobList(jobId, nativePrintJob);
1120 return nativePrintJob;
1121 }
1122
StartNativePrintJob(PrintJob & printJob)1123 int32_t PrintServiceAbility::StartNativePrintJob(PrintJob &printJob)
1124 {
1125 startPrintTime_ = std::chrono::high_resolution_clock::now();
1126 ManualStart();
1127 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
1128 PRINT_HILOGE("no permission to access print service");
1129 return E_PRINT_NO_PERMISSION;
1130 }
1131 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1132 if (!UpdatePrintJobOptionByPrinterId(printJob)) {
1133 PRINT_HILOGW("cannot update printer name/uri");
1134 return E_PRINT_INVALID_PRINTER;
1135 }
1136 std::string jobId = PrintUtils::GetPrintJobId();
1137 auto nativePrintJob = AddNativePrintJob(jobId, printJob);
1138 if (nativePrintJob == nullptr) {
1139 return E_PRINT_SERVER_FAILURE;
1140 }
1141 auto printerId = nativePrintJob->GetPrinterId();
1142 auto extensionId = PrintUtils::GetExtensionId(printerId);
1143 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT);
1144 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
1145 return E_PRINT_SERVER_FAILURE;
1146 }
1147 UpdateQueuedJobList(jobId, nativePrintJob);
1148 printerJobMap_[printerId].insert(std::make_pair(jobId, true));
1149 #ifdef CUPS_ENABLE
1150 if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) {
1151 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
1152 DelayedSingleton<PrintCupsClient>::GetInstance()->AddCupsPrintJob(printJob);
1153 CallStatusBar();
1154 return E_PRINT_NONE;
1155 }
1156 #endif // CUPS_ENABLE
1157 auto cbFunc = extCallbackMap_[cid];
1158 auto callback = [=]() {
1159 if (cbFunc != nullptr) {
1160 StartPrintJobCB(jobId, nativePrintJob);
1161 cbFunc->OnCallback(*nativePrintJob);
1162 CallStatusBar();
1163 }
1164 };
1165 if (helper_->IsSyncMode()) {
1166 callback();
1167 } else {
1168 serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
1169 }
1170 return E_PRINT_NONE;
1171 }
1172
StartPrintJob(PrintJob & jobInfo)1173 int32_t PrintServiceAbility::StartPrintJob(PrintJob &jobInfo)
1174 {
1175 startPrintTime_ = std::chrono::high_resolution_clock::now();
1176 ManualStart();
1177 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1178 PRINT_HILOGE("no permission to access print service");
1179 return E_PRINT_NO_PERMISSION;
1180 }
1181 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1182 if (!CheckPrintJob(jobInfo)) {
1183 PRINT_HILOGW("check printJob unavailable");
1184 return E_PRINT_INVALID_PRINTJOB;
1185 }
1186 auto jobId = jobInfo.GetJobId();
1187 auto printerId = jobInfo.GetPrinterId();
1188 auto extensionId = PrintUtils::GetExtensionId(printerId);
1189 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT);
1190 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
1191 return E_PRINT_SERVER_FAILURE;
1192 }
1193 auto printJob = std::make_shared<PrintJob>();
1194 printJob->UpdateParams(jobInfo);
1195 UpdateQueuedJobList(jobId, printJob);
1196 printerJobMap_[printerId].insert(std::make_pair(jobId, true));
1197 #ifdef CUPS_ENABLE
1198 if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) {
1199 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
1200 DelayedSingleton<PrintCupsClient>::GetInstance()->AddCupsPrintJob(jobInfo);
1201 CallStatusBar();
1202 return E_PRINT_NONE;
1203 }
1204 #endif // CUPS_ENABLE
1205 auto cbFunc = extCallbackMap_[cid];
1206 auto callback = [=]() {
1207 if (cbFunc != nullptr) {
1208 StartPrintJobCB(jobId, printJob);
1209 cbFunc->OnCallback(*printJob);
1210 CallStatusBar();
1211 }
1212 };
1213 if (helper_->IsSyncMode()) {
1214 callback();
1215 } else {
1216 serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
1217 }
1218 return E_PRINT_NONE;
1219 }
1220
CheckPrintJob(PrintJob & jobInfo)1221 bool PrintServiceAbility::CheckPrintJob(PrintJob &jobInfo)
1222 {
1223 if (!UpdatePrintJobOptionByPrinterId(jobInfo)) {
1224 PRINT_HILOGW("cannot update printer name/uri");
1225 return false;
1226 }
1227 auto jobIt = printJobList_.find(jobInfo.GetJobId());
1228 if (jobIt == printJobList_.end()) {
1229 PRINT_HILOGE("invalid job id");
1230 return false;
1231 }
1232 printJobList_.erase(jobIt);
1233 return true;
1234 }
1235
UpdateQueuedJobList(const std::string & jobId,const std::shared_ptr<PrintJob> & printJob)1236 void PrintServiceAbility::UpdateQueuedJobList(const std::string &jobId, const std::shared_ptr<PrintJob> &printJob)
1237 {
1238 PRINT_HILOGI("enter UpdateQueuedJobList, jobId: %{public}s.", jobId.c_str());
1239 #ifdef IPPOVERUSB_ENABLE
1240 int32_t port = 0;
1241 DelayedSingleton<PrintIppOverUsbManager>::GetInstance()->ConnectPrinter(printJob->GetPrinterId(), port);
1242 #endif // IPPOVERUSB_ENABLE
1243 std::string jobOrderId = GetPrintJobOrderId();
1244 if (jobOrderId == "0") {
1245 jobOrderList_.clear();
1246 }
1247 PRINT_HILOGI("UpdateQueuedJobList jobOrderId: %{public}s.", jobOrderId.c_str());
1248 if (queuedJobList_.find(jobId) != queuedJobList_.end()) {
1249 queuedJobList_[jobId] = printJob;
1250 jobOrderList_[jobOrderId] = jobId;
1251 } else if (static_cast<uint32_t>(queuedJobList_.size()) < MAX_JOBQUEUE_NUM) {
1252 queuedJobList_.insert(std::make_pair(jobId, printJob));
1253 jobOrderList_.insert(std::make_pair(jobOrderId, jobId));
1254 } else {
1255 PRINT_HILOGE("UpdateQueuedJobList out of MAX_JOBQUEUE_NUM");
1256 }
1257
1258 int32_t userId = GetCurrentUserId();
1259 if (userId == E_PRINT_INVALID_USERID) {
1260 PRINT_HILOGE("Invalid user id.");
1261 return;
1262 }
1263 auto iter = printUserMap_.find(userId);
1264 if (iter == printUserMap_.end() || iter->second == nullptr) {
1265 PRINT_HILOGE("Invalid user id");
1266 return;
1267 }
1268 iter->second->UpdateQueuedJobList(jobId, printJob, jobOrderId);
1269
1270 std::string printerId = printJob->GetPrinterId();
1271 auto iterator = printerInfoList_.find(printerId);
1272 if (iterator != printerInfoList_.end()) {
1273 iterator->second->SetPrinterStatus(PRINTER_STATUS_BUSY);
1274 iterator->second->SetPrinterName(PrintUtil::RemoveUnderlineFromPrinterName(iterator->second->GetPrinterName()));
1275 printSystemData_.UpdatePrinterStatus(printerId, PRINTER_STATUS_BUSY);
1276 iterator->second->SetIsLastUsedPrinter(true);
1277 SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *iterator->second);
1278 SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *iterator->second);
1279 }
1280 SetLastUsedPrinter(printerId);
1281 }
1282
SetLastUsedPrinter(const std::string & printerId)1283 void PrintServiceAbility::SetLastUsedPrinter(const std::string &printerId)
1284 {
1285 PRINT_HILOGD("SetLastUsedPrinter started.");
1286 if (!printSystemData_.IsPrinterAdded(printerId)) {
1287 PRINT_HILOGE("Printer is not added to cups.");
1288 return;
1289 }
1290
1291 auto userData = GetCurrentUserData();
1292 if (userData == nullptr) {
1293 PRINT_HILOGE("Get user data failed.");
1294 return;
1295 }
1296 int32_t ret = userData->SetLastUsedPrinter(printerId);
1297 if (ret != E_PRINT_NONE) {
1298 PRINT_HILOGE("SetLastUsedPrinter failed.");
1299 return;
1300 }
1301 }
1302
StartPrintJobCB(const std::string & jobId,const std::shared_ptr<PrintJob> & printJob)1303 void PrintServiceAbility::StartPrintJobCB(const std::string &jobId, const std::shared_ptr<PrintJob> &printJob)
1304 {
1305 PRINT_HILOGD("Start send task to Extension PrintJob %{public}s", jobId.c_str());
1306 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
1307 printJob->SetJobState(PRINT_JOB_QUEUED);
1308 UpdatePrintJobState(jobId, PRINT_JOB_QUEUED, PRINT_JOB_BLOCKED_UNKNOWN);
1309 }
1310
CancelPrintJob(const std::string & jobId)1311 int32_t PrintServiceAbility::CancelPrintJob(const std::string &jobId)
1312 {
1313 ManualStart();
1314 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1315 PRINT_HILOGE("no permission to access print service");
1316 return E_PRINT_NO_PERMISSION;
1317 }
1318 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1319
1320 auto userData = GetUserDataByJobId(jobId);
1321 if (userData == nullptr) {
1322 PRINT_HILOGE("Get user data failed.");
1323 return E_PRINT_INVALID_USERID;
1324 }
1325 auto jobIt = userData->queuedJobList_.find(jobId);
1326 if (jobIt == userData->queuedJobList_.end()) {
1327 PRINT_HILOGE("invalid job id");
1328 return E_PRINT_INVALID_PRINTJOB;
1329 }
1330
1331 if (jobIt->second->GetJobState() >= PRINT_JOB_QUEUED) {
1332 std::string extensionId = PrintUtils::GetExtensionId(jobIt->second->GetPrinterId());
1333 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_CANCEL_PRINT);
1334 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
1335 PRINT_HILOGW("CancelPrintJob Not Register Yet!!!");
1336 UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED);
1337 return E_PRINT_SERVER_FAILURE;
1338 }
1339 #ifdef CUPS_ENABLE
1340 if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) {
1341 DelayedSingleton<PrintCupsClient>::GetInstance()->CancelCupsJob(jobIt->second->GetJobId());
1342 return E_PRINT_NONE;
1343 }
1344 #endif // CUPS_ENABLE
1345
1346 auto cbFunc = extCallbackMap_[cid];
1347 auto tmpPrintJob = userData->queuedJobList_[jobId];
1348 auto callback = [=]() {
1349 if (cbFunc != nullptr && cbFunc->OnCallback(*tmpPrintJob) == false) {
1350 UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED);
1351 }
1352 };
1353 if (helper_->IsSyncMode()) {
1354 callback();
1355 } else {
1356 serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
1357 }
1358 } else {
1359 SetPrintJobCanceled(*jobIt->second);
1360 }
1361 return E_PRINT_NONE;
1362 }
1363
SetPrintJobCanceled(PrintJob & jobinfo)1364 void PrintServiceAbility::SetPrintJobCanceled(PrintJob &jobinfo)
1365 {
1366 auto printJob = std::make_shared<PrintJob>(jobinfo);
1367 if (printJob == nullptr) {
1368 PRINT_HILOGE("create printJob failed.");
1369 return;
1370 }
1371 std::string jobId = printJob->GetJobId();
1372 auto userData = GetUserDataByJobId(jobId);
1373 if (userData == nullptr) {
1374 PRINT_HILOGE("Get user data failed.");
1375 return;
1376 }
1377 printJob->SetJobState(PRINT_JOB_COMPLETED);
1378 printJob->SetSubState(PRINT_JOB_COMPLETED_CANCELLED);
1379 userData->printJobList_.insert(std::make_pair(jobId, printJob));
1380 printJobList_.insert(std::make_pair(jobId, printJob));
1381 UpdatePrintJobState(jobId, PRINT_JOB_COMPLETED, PRINT_JOB_COMPLETED_CANCELLED);
1382 }
1383
CancelUserPrintJobs(const int32_t userId)1384 void PrintServiceAbility::CancelUserPrintJobs(const int32_t userId)
1385 {
1386 auto removedUser = printUserMap_.find(userId);
1387 if (removedUser == printUserMap_.end()) {
1388 PRINT_HILOGE("User dose not exist.");
1389 return;
1390 }
1391 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1392 if (removedUser->second == nullptr) {
1393 PRINT_HILOGE("PrintUserData is nullptr.");
1394 return;
1395 }
1396 for (auto jobIt: removedUser->second->queuedJobList_) {
1397 PRINT_HILOGI("CancelUserPrintJobs user jobId: %{public}s", jobIt.first.c_str());
1398 int32_t ret = CancelPrintJob(jobIt.first);
1399 PRINT_HILOGI("CancelUserPrintJobs CancelPrintJob ret: %{public}d", ret);
1400 userJobMap_.erase(jobIt.first);
1401 }
1402 printUserMap_.erase(userId);
1403 PRINT_HILOGI("remove user-%{publis}d success.", userId);
1404 }
1405
NotifyCurrentUserChanged(const int32_t userId)1406 void PrintServiceAbility::NotifyCurrentUserChanged(const int32_t userId)
1407 {
1408 PRINT_HILOGD("NotifyAppCurrentUserChanged begin");
1409 PRINT_HILOGI("currentUserId_ is: %{public}d", userId);
1410 currentUserId_ = userId;
1411 auto userData = GetUserDataByUserId(userId);
1412 if (userData == nullptr) {
1413 PRINT_HILOGE("Get user data failed.");
1414 return;
1415 }
1416 auto status = DetermineUserJobStatus(userData->queuedJobList_);
1417
1418 switch (status) {
1419 case PRINT_JOB_BLOCKED:
1420 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_BLOCKED);
1421 break;
1422 case PRINT_JOB_COMPLETED:
1423 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_HIDE);
1424 break;
1425 case PRINT_JOB_RUNNING:
1426 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
1427 break;
1428 default:
1429 break;
1430 }
1431 PRINT_HILOGD("NotifyAppCurrentUserChanged end");
1432 }
1433
SendQueuePrintJob(const std::string & printerId)1434 void PrintServiceAbility::SendQueuePrintJob(const std::string &printerId)
1435 {
1436 if (printerJobMap_[printerId].empty()) {
1437 return;
1438 }
1439
1440 auto userData = GetCurrentUserData();
1441 if (userData == nullptr) {
1442 PRINT_HILOGE("Get user data failed.");
1443 return;
1444 }
1445 auto jobId = printerJobMap_[printerId].begin()->first;
1446 auto jobIt = userData->queuedJobList_.find(jobId);
1447 if (jobIt == userData->queuedJobList_.end()) {
1448 PRINT_HILOGE("invalid print job, jobId:%{public}s", jobId.c_str());
1449 return;
1450 }
1451
1452 if (jobIt->second->GetJobState() != PRINT_JOB_PREPARED) {
1453 PRINT_HILOGE("job state isn't prepared, jobId:%{public}s", jobId.c_str());
1454 return;
1455 }
1456
1457 auto extensionId = PrintUtils::GetExtensionId(printerId);
1458 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_START_PRINT);
1459 #ifdef CUPS_ENABLE
1460 if (cid.find(SPOOLER_BUNDLE_NAME) != string::npos) {
1461 PRINT_HILOGD("default spooler extension, no need SendQueuePrintJob");
1462 return;
1463 }
1464 #endif // CUPS_ENABLE
1465
1466 auto cbFunc = extCallbackMap_[cid];
1467 auto printJob = jobIt->second;
1468 auto callback = [=]() {
1469 PRINT_HILOGD("Start Next Print Job %{public}s", jobId.c_str());
1470 if (cbFunc != nullptr && cbFunc->OnCallback(*printJob)) {
1471 printJob->SetJobState(PRINT_JOB_QUEUED);
1472 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_PRINTING);
1473 UpdatePrintJobState(jobId, PRINT_JOB_QUEUED, PRINT_JOB_BLOCKED_UNKNOWN);
1474 }
1475 };
1476 if (helper_->IsSyncMode()) {
1477 callback();
1478 } else {
1479 serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
1480 }
1481 }
1482
CheckPrinterUriDifferent(const std::shared_ptr<PrinterInfo> & info)1483 bool PrintServiceAbility::CheckPrinterUriDifferent(const std::shared_ptr<PrinterInfo> &info)
1484 {
1485 CupsPrinterInfo cupsPrinter;
1486 std::string option = info->GetOption();
1487 if (printSystemData_.QueryCupsPrinterInfoByPrinterId(info->GetPrinterId(), cupsPrinter) && json::accept(option)) {
1488 json optionJson = json::parse(option);
1489 if (optionJson.contains("printerUri") && optionJson["printerUri"].is_string()) {
1490 std::string printerUri = optionJson["printerUri"].get<std::string>();
1491 if (!printerUri.empty() && printerUri != cupsPrinter.uri) {
1492 return true;
1493 }
1494 }
1495 }
1496 return false;
1497 }
1498
AddPrinters(const std::vector<PrinterInfo> & printerInfos)1499 int32_t PrintServiceAbility::AddPrinters(const std::vector<PrinterInfo> &printerInfos)
1500 {
1501 ManualStart();
1502 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1503 PRINT_HILOGE("no permission to access print service");
1504 return E_PRINT_NO_PERMISSION;
1505 }
1506 PRINT_HILOGD("AddPrinters started. Total size is %{public}zd", printerInfoList_.size());
1507
1508 std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1509 PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1510
1511 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1512
1513 for (auto info : printerInfos) {
1514 if (printerInfoList_.find(info.GetPrinterId()) != printerInfoList_.end()) {
1515 PRINT_HILOGW("duplicate printer id, ignore it");
1516 continue;
1517 }
1518 auto printerInfo = std::make_shared<PrinterInfo>(info);
1519 printerInfo->SetPrinterId(PrintUtils::GetGlobalId(extensionId, printerInfo->GetPrinterId()));
1520 PRINT_HILOGD("AddPrinters printerId = %{public}s", printerInfo->GetPrinterId().c_str());
1521 printerInfo->SetPrinterState(PRINTER_ADDED);
1522 printerInfoList_[printerInfo->GetPrinterId()] = printerInfo;
1523 SendPrinterDiscoverEvent(PRINTER_ADDED, *printerInfo);
1524 SendPrinterEvent(*printerInfo);
1525 SendQueuePrintJob(printerInfo->GetPrinterId());
1526 if (printSystemData_.IsPrinterAdded(printerInfo->GetPrinterId()) &&
1527 !printSystemData_.CheckPrinterBusy(printerInfo->GetPrinterId())) {
1528 if (CheckPrinterUriDifferent(printerInfo)) {
1529 PRINT_HILOGW("different printer uri, ignore it");
1530 } else {
1531 printerInfo->SetPrinterStatus(PRINTER_STATUS_IDLE);
1532 printSystemData_.UpdatePrinterStatus(printerInfo->GetPrinterId(), PRINTER_STATUS_IDLE);
1533 SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
1534 SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *printerInfo);
1535 }
1536 }
1537 }
1538 PRINT_HILOGD("AddPrinters end. Total size is %{public}zd", printerInfoList_.size());
1539 return E_PRINT_NONE;
1540 }
1541
RemovePrinters(const std::vector<std::string> & printerIds)1542 int32_t PrintServiceAbility::RemovePrinters(const std::vector<std::string> &printerIds)
1543 {
1544 ManualStart();
1545 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1546 PRINT_HILOGE("no permission to access print service");
1547 return E_PRINT_NO_PERMISSION;
1548 }
1549
1550 auto count = printerInfoList_.size();
1551 PRINT_HILOGI("RemovePrinters started. Total size is %{public}zd", count);
1552 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1553
1554 std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1555
1556 for (auto printerId : printerIds) {
1557 printerId = PrintUtils::GetGlobalId(extensionId, printerId);
1558 PRINT_HILOGD("RemovePrinters printerId = %{public}s", printerId.c_str());
1559 auto printerIt = printerInfoList_.find(printerId);
1560 if (printerIt == printerInfoList_.end()) {
1561 PRINT_HILOGE("invalid printer id, ingore it");
1562 continue;
1563 }
1564 std::string option = printerIt->second->GetOption();
1565 std::string printerUri = "";
1566 if (json::accept(option)) {
1567 json jsonObj = json::parse(option);
1568 if (jsonObj.contains("printerUri") && jsonObj["printerUri"].is_string()) {
1569 printerUri = jsonObj["printerUri"];
1570 }
1571 }
1572 bool mdnsPrinter = printerId.find("mdns") != string::npos;
1573 const uint32_t waitTime = 1000;
1574 JobMonitorParam monitorParam{nullptr, "", 0, printerUri, "", printerId};
1575 PRINT_HILOGD("printerid is %{public}s, printer type is %{public}d", printerId.c_str(), mdnsPrinter);
1576 // 连接类型为mdns且为spooler显示的已经连接的打印机才判断是否离线
1577 if (!printerUri.empty() && mdnsPrinter &&
1578 DelayedSingleton<PrintCupsClient>::GetInstance()->CheckPrinterOnline(&monitorParam, waitTime)) {
1579 PRINT_HILOGI("printer is online, do not remove.");
1580 return E_PRINT_INVALID_PRINTER;
1581 }
1582 PrinterInfo info = *printerIt->second;
1583 info.SetPrinterState(PRINTER_REMOVED);
1584 SendPrinterDiscoverEvent(PRINTER_REMOVED, info);
1585 SendPrinterEvent(info);
1586 printerInfoList_.erase(printerIt);
1587 if (printSystemData_.IsPrinterAdded(info.GetPrinterId())) {
1588 info.SetPrinterStatus(PRINTER_STATUS_UNAVAILABLE);
1589 printSystemData_.UpdatePrinterStatus(info.GetPrinterId(), PRINTER_STATUS_UNAVAILABLE);
1590 SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, info);
1591 SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, info);
1592 }
1593 }
1594 PRINT_HILOGI("RemovePrinters end. Total size is %{public}zd", printerInfoList_.size());
1595 return E_PRINT_NONE;
1596 }
1597
UpdatePrinters(const std::vector<PrinterInfo> & printerInfos)1598 int32_t PrintServiceAbility::UpdatePrinters(const std::vector<PrinterInfo> &printerInfos)
1599 {
1600 ManualStart();
1601 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1602 PRINT_HILOGE("no permission to access print service");
1603 return E_PRINT_NO_PERMISSION;
1604 }
1605
1606 PRINT_HILOGD("UpdatePrinters started. Total size is %{public}zd", printerInfoList_.size());
1607 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1608 std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1609 PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1610 std::vector<std::shared_ptr<PrinterInfo>> updatedPrinters;
1611 bool isChanged = false;
1612 for (auto info: printerInfos) {
1613 std::string printExtId = info.GetPrinterId();
1614 if (printExtId.find(SPOOLER_PACKAGE_NAME) == std::string::npos &&
1615 printExtId.find(PRINT_EXTENSION_BUNDLE_NAME) == std::string::npos) {
1616 printExtId = PrintUtils::GetGlobalId(extensionId, printExtId);
1617 }
1618 if (UpdatePrinterSystemData(printExtId, info)) {
1619 isChanged = true;
1620 }
1621 auto printerIt = printerInfoList_.find(printExtId);
1622 if (printerIt == printerInfoList_.end()) {
1623 PRINT_HILOGE("invalid printer id, ignore it");
1624 continue;
1625 }
1626 *printerIt->second = info;
1627 printerIt->second->SetPrinterState(PRINTER_UPDATE_CAP);
1628 printerIt->second->SetPrinterId(printExtId);
1629 if (printerIt->second->HasCapability()) {
1630 if (UpdatePrinterCapability(printExtId, info)) {
1631 isChanged = true;
1632 }
1633 updatedPrinters.push_back(printerIt->second);
1634 }
1635 }
1636 if (isChanged) {
1637 printSystemData_.SaveCupsPrinterMap();
1638 }
1639 for (const auto &printerInfo: updatedPrinters) {
1640 SendPrinterDiscoverEvent(PRINTER_UPDATE_CAP, *printerInfo);
1641 SendPrinterEvent(*printerInfo);
1642 }
1643 PRINT_HILOGD("UpdatePrinters end. Total size is %{private}zd", printerInfoList_.size());
1644 return E_PRINT_NONE;
1645 }
1646
UpdatePrinterSystemData(const std::string & printerId,PrinterInfo & info)1647 bool PrintServiceAbility::UpdatePrinterSystemData(const std::string &printerId, PrinterInfo &info)
1648 {
1649 std::string option = info.GetOption();
1650 if (json::accept(option)) {
1651 json optionJson = json::parse(option);
1652 if (optionJson.contains("alias") && optionJson["alias"].is_string()) {
1653 if (printSystemData_.UpdatePrinterAlias(printerId, optionJson["alias"])) {
1654 SendPrinterEventChangeEvent(PRINTER_EVENT_INFO_CHANGED, info);
1655 return true;
1656 }
1657 }
1658 }
1659 return false;
1660 }
1661
UpdatePrinterCapability(const std::string & printerId,PrinterInfo & info)1662 bool PrintServiceAbility::UpdatePrinterCapability(const std::string &printerId, PrinterInfo &info)
1663 {
1664 PRINT_HILOGI("UpdatePrinterCapability Enter");
1665 if (printerId.compare(0, EPRINTER_ID.size(), EPRINTER_ID) == 0) {
1666 PRINT_HILOGI("ePrinter Enter");
1667 info.Dump();
1668 PrinterCapability printerCaps;
1669 info.GetCapability(printerCaps);
1670 WriteEprinterPreference(printerId, printerCaps);
1671 }
1672
1673 if (printerId.compare(0, SPOOLER_PACKAGE_NAME.size(), SPOOLER_PACKAGE_NAME) != 0) {
1674 CupsPrinterInfo cupsPrinterInfo;
1675 cupsPrinterInfo.name = info.GetPrinterName();
1676 info.GetCapability(cupsPrinterInfo.printerCapability);
1677 cupsPrinterInfo.printerStatus = PRINTER_STATUS_IDLE;
1678 printSystemData_.InsertCupsPrinter(printerId, cupsPrinterInfo, true);
1679 info.SetIsLastUsedPrinter(true);
1680 info.SetPrinterStatus(PRINTER_STATUS_IDLE);
1681 info.SetPrinterId(printerId);
1682 SendPrinterEventChangeEvent(PRINTER_EVENT_ADDED, info);
1683 SendPrinterChangeEvent(PRINTER_EVENT_ADDED, info);
1684 SetLastUsedPrinter(printerId);
1685 return true;
1686 }
1687 return false;
1688 }
1689
UpdatePrinterState(const std::string & printerId,uint32_t state)1690 int32_t PrintServiceAbility::UpdatePrinterState(const std::string &printerId, uint32_t state)
1691 {
1692 ManualStart();
1693 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1694 PRINT_HILOGE("no permission to access print service");
1695 return E_PRINT_NO_PERMISSION;
1696 }
1697
1698 if (state > PRINTER_UNKNOWN) {
1699 return E_PRINT_INVALID_PARAMETER;
1700 }
1701
1702 std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1703 PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1704 std::string printerExtId = PrintUtils::GetGlobalId(extensionId, printerId);
1705 PRINT_HILOGD("UpdatePrinterState started. %{private}s, state [%{public}d]", printerExtId.c_str(), state);
1706 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1707
1708 if (printerInfoList_.find(printerExtId) == printerInfoList_.end()) {
1709 PRINT_HILOGD("Invalid printer id");
1710 return E_PRINT_INVALID_PRINTER;
1711 }
1712
1713 printerInfoList_[printerExtId]->SetPrinterState(state);
1714 SendPrinterDiscoverEvent(PRINTER_CONNECTED, *printerInfoList_[printerExtId]);
1715 SendPrinterEvent(*printerInfoList_[printerExtId]);
1716 PRINT_HILOGD("UpdatePrinterState end.");
1717 return E_PRINT_NONE;
1718 }
1719
checkJobState(uint32_t state,uint32_t subState)1720 bool PrintServiceAbility::checkJobState(uint32_t state, uint32_t subState)
1721 {
1722 if (state > PRINT_JOB_UNKNOWN) {
1723 return false;
1724 }
1725 if (state == PRINT_JOB_BLOCKED && subState < PRINT_JOB_BLOCKED_OFFLINE) {
1726 return false;
1727 }
1728 if (state == PRINT_JOB_COMPLETED && subState > PRINT_JOB_COMPLETED_FILE_CORRUPT) {
1729 return false;
1730 }
1731
1732 return true;
1733 }
1734
UpdatePrintJobStateOnlyForSystemApp(const std::string & jobId,uint32_t state,uint32_t subState)1735 int32_t PrintServiceAbility::UpdatePrintJobStateOnlyForSystemApp(
1736 const std::string &jobId, uint32_t state, uint32_t subState)
1737 {
1738 ManualStart();
1739 if (state != PRINT_JOB_CREATE_FILE_COMPLETED && !CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1740 PRINT_HILOGE("no permission to access print service");
1741 return E_PRINT_NO_PERMISSION;
1742 }
1743 return UpdatePrintJobState(jobId, state, subState);
1744 }
1745
UpdatePrintJobState(const std::string & jobId,uint32_t state,uint32_t subState)1746 int32_t PrintServiceAbility::UpdatePrintJobState(const std::string &jobId, uint32_t state, uint32_t subState)
1747 {
1748 ManualStart();
1749 if (state == PRINT_JOB_CREATE_FILE_COMPLETED) {
1750 return AdapterGetFileCallBack(jobId, state, subState);
1751 }
1752
1753 if (!checkJobState(state, subState)) {
1754 return E_PRINT_INVALID_PARAMETER;
1755 }
1756
1757 PRINT_HILOGI("UpdatePrintJobState started jobId:%{public}s, state:[%{public}d %{public}s], subState[%{public}d]",
1758 jobId.c_str(), state, PrintUtils::GetJobStateChar(state).c_str(), subState);
1759 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1760
1761 return CheckAndSendQueuePrintJob(jobId, state, subState);
1762 }
1763
AdapterGetFileCallBack(const std::string & jobId,uint32_t state,uint32_t subState)1764 int32_t PrintServiceAbility::AdapterGetFileCallBack(const std::string &jobId, uint32_t state, uint32_t subState)
1765 {
1766 if (state != PRINT_JOB_CREATE_FILE_COMPLETED) {
1767 return E_PRINT_NONE;
1768 }
1769 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
1770 PRINT_HILOGE("no permission to access print service");
1771 return E_PRINT_NO_PERMISSION;
1772 }
1773
1774 auto eventIt = registeredListeners_.find(PRINT_GET_FILE_EVENT_TYPE);
1775 if (eventIt != registeredListeners_.end()) {
1776 PRINT_HILOGI("print job adapter file created subState[%{public}d]", subState);
1777 uint32_t fileCompletedState = subState;
1778 if (subState == PRINT_JOB_CREATE_FILE_COMPLETED_SUCCESS) {
1779 fileCompletedState = PRINT_FILE_CREATED_SUCCESS;
1780 } else if (subState == PRINT_JOB_CREATE_FILE_COMPLETED_FAILED) {
1781 fileCompletedState = PRINT_FILE_CREATED_FAIL;
1782 }
1783 eventIt->second->OnCallbackAdapterGetFile(fileCompletedState);
1784 }
1785 return E_PRINT_NONE;
1786 }
1787
CheckAndSendQueuePrintJob(const std::string & jobId,uint32_t state,uint32_t subState)1788 int32_t PrintServiceAbility::CheckAndSendQueuePrintJob(const std::string &jobId, uint32_t state, uint32_t subState)
1789 {
1790 auto userData = GetUserDataByJobId(jobId);
1791 if (userData == nullptr) {
1792 PRINT_HILOGE("Get user data failed.");
1793 return E_PRINT_INVALID_USERID;
1794 }
1795 auto jobIt = userData->queuedJobList_.find(jobId);
1796 bool jobInQueue = true;
1797 if (jobIt == userData->queuedJobList_.end()) {
1798 jobInQueue = false;
1799 jobIt = userData->printJobList_.find(jobId);
1800 if (jobIt == userData->printJobList_.end()) {
1801 PRINT_HILOGD("Invalid print job id");
1802 return E_PRINT_INVALID_PRINTJOB;
1803 }
1804 }
1805
1806 jobIt->second->SetJobState(state);
1807 jobIt->second->SetSubState(subState);
1808 SendPrintJobEvent(*jobIt->second);
1809 notifyAdapterJobChanged(jobId, state, subState);
1810 CheckJobQueueBlocked(*jobIt->second);
1811
1812 auto printerId = jobIt->second->GetPrinterId();
1813 if (state == PRINT_JOB_BLOCKED) {
1814 ReportHisysEvent(jobIt->second, printerId, subState);
1815 }
1816 if (state == PRINT_JOB_COMPLETED) {
1817 if (jobInQueue) {
1818 printerJobMap_[printerId].erase(jobId);
1819 userData->queuedJobList_.erase(jobId);
1820 queuedJobList_.erase(jobId);
1821 }
1822 if (printerJobMap_[printerId].empty()) {
1823 auto iter = printerInfoList_.find(printerId);
1824 if (iter != printerInfoList_.end()) {
1825 iter->second->SetPrinterStatus(PRINTER_STATUS_IDLE);
1826 printSystemData_.UpdatePrinterStatus(printerId, PRINTER_STATUS_IDLE);
1827 SendPrinterEventChangeEvent(PRINTER_EVENT_STATE_CHANGED, *iter->second);
1828 SendPrinterChangeEvent(PRINTER_EVENT_STATE_CHANGED, *iter->second);
1829 }
1830 }
1831 if (IsQueuedJobListEmpty(jobId)) {
1832 ReportCompletedPrint(printerId);
1833 }
1834 SendQueuePrintJob(printerId);
1835 }
1836
1837 PRINT_HILOGD("CheckAndSendQueuePrintJob end.");
1838 return E_PRINT_NONE;
1839 }
1840
IsQueuedJobListEmpty(const std::string & jobId)1841 bool PrintServiceAbility::IsQueuedJobListEmpty(const std::string &jobId)
1842 {
1843 auto userData = GetUserDataByJobId(jobId);
1844 if (userData == nullptr) {
1845 PRINT_HILOGE("Get user data failed.");
1846 return false;
1847 }
1848 if (!userData->queuedJobList_.empty()) {
1849 PRINT_HILOGD("This user still has print jobs in progress.");
1850 return false;
1851 }
1852 if (GetUserIdByJobId(jobId) != currentUserId_) {
1853 PRINT_HILOGE("The user corresponding to this task is different from the current user.");
1854 return false;
1855 }
1856 return true;
1857 }
1858
ReportCompletedPrint(const std::string & printerId)1859 void PrintServiceAbility::ReportCompletedPrint(const std::string &printerId)
1860 {
1861 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_COMPLETED);
1862 PRINT_HILOGD("no print job exists, destroy extension");
1863 PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
1864 if (queuedJobList_.size() == 0 && printAppCount_ == 0) {
1865 UnloadSystemAbility();
1866 }
1867 json msg;
1868 auto endPrintTime = std::chrono::high_resolution_clock::now();
1869 auto printTime = std::chrono::duration_cast<std::chrono::milliseconds>(endPrintTime - startPrintTime_);
1870 msg["PRINT_TIME"] = printTime.count();
1871 msg["INGRESS_PACKAGE"] = ingressPackage;
1872 msg["STATUS"] = 0;
1873 HisysEventUtil::reportPrintSuccess(msg.dump());
1874 }
1875
ReportHisysEvent(const std::shared_ptr<PrintJob> & jobInfo,const std::string & printerId,uint32_t subState)1876 void PrintServiceAbility::ReportHisysEvent(
1877 const std::shared_ptr<PrintJob> &jobInfo, const std::string &printerId, uint32_t subState)
1878 {
1879 json msg;
1880 auto endPrintTime = std::chrono::high_resolution_clock::now();
1881 auto printTime = std::chrono::duration_cast<std::chrono::milliseconds>(endPrintTime - startPrintTime_);
1882 msg["PRINT_TIME"] = printTime.count();
1883 msg["INGRESS_PACKAGE"] = ingressPackage;
1884 if (isEprint(printerId)) {
1885 msg["PRINT_TYPE"] = 1;
1886 } else {
1887 msg["PRINT_TYPE"] = 0;
1888 }
1889 auto printInfo = printerInfoList_.find(printerId);
1890 std::vector<uint32_t> fdList;
1891 jobInfo->GetFdList(fdList);
1892 msg["FILE_NUM"] = fdList.size();
1893 msg["PAGE_NUM"] = fdList.size();
1894 if (printInfo == printerInfoList_.end()) {
1895 msg["MODEL"] = "";
1896 } else {
1897 msg["MODEL"] = printInfo->second->GetPrinterName();
1898 }
1899 msg["COPIES_SETTING"] = jobInfo->GetCopyNumber();
1900 std::string option = jobInfo->GetOption();
1901 PRINT_HILOGI("option:%{public}s", option.c_str());
1902 std::string jobDescription = "";
1903 if (option != "") {
1904 if (json::accept(option)) {
1905 json optionJson = json::parse(option);
1906 PRINT_HILOGI("optionJson: %{public}s", optionJson.dump().c_str());
1907 if (optionJson.contains("jobDescription") && optionJson["jobDescription"].is_string()) {
1908 jobDescription = optionJson["jobDescription"].get<std::string>();
1909 PRINT_HILOGI("jobDescription: %{public}s", jobDescription.c_str());
1910 }
1911 }
1912 }
1913 msg["JOB_DESCRIPTION"] = jobDescription;
1914 msg["PRINT_STYLE_SETTING"] = jobInfo->GetDuplexMode();
1915 msg["FAIL_REASON_CODE"] = subState;
1916 HisysEventUtil::faultPrint("PRINT_JOB_BLOCKED", msg.dump());
1917 }
1918
NotifyAppJobQueueChanged(const std::string & applyResult)1919 void PrintServiceAbility::NotifyAppJobQueueChanged(const std::string &applyResult)
1920 {
1921 PRINT_HILOGD("NotifyAppJobQueueChanged started. %{public}s ", applyResult.c_str());
1922 AAFwk::Want want;
1923 want.SetAction(ACTION_QUEUE_JOB_LIST_CHANGED);
1924 want.SetParam(QUEUE_JOB_LIST_CHANGED, applyResult);
1925 EventFwk::CommonEventData commonData { want };
1926 EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1927 PRINT_HILOGD("NotifyAppJobQueueChanged end.");
1928 }
1929
isEprint(const std::string & printerId)1930 bool PrintServiceAbility::isEprint(const std::string &printerId)
1931 {
1932 if (printerId.length() <= 0) {
1933 return false;
1934 }
1935 std::string ePrintID = "ePrintID";
1936 if (printerId.length() < ePrintID.length()) {
1937 return false;
1938 }
1939 return std::equal(ePrintID.rbegin(), ePrintID.rend(), printerId.rbegin());
1940 }
1941
UpdateExtensionInfo(const std::string & extInfo)1942 int32_t PrintServiceAbility::UpdateExtensionInfo(const std::string &extInfo)
1943 {
1944 ManualStart();
1945 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1946 PRINT_HILOGE("no permission to access print service");
1947 return E_PRINT_NO_PERMISSION;
1948 }
1949
1950 std::string extensionId = DelayedSingleton<PrintBMSHelper>::GetInstance()->QueryCallerBundleName();
1951 PRINT_HILOGD("extensionId = %{public}s", extensionId.c_str());
1952
1953 PRINT_HILOGD("UpdateExtensionInfo started. %{public}s, extInfo [%{public}s]",
1954 extensionId.c_str(), extInfo.c_str());
1955 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1956 if (extensionList_.find(extensionId) == extensionList_.end()) {
1957 PRINT_HILOGD("Invalid extension id");
1958 return E_PRINT_INVALID_EXTENSION;
1959 }
1960 SendExtensionEvent(extensionId, extInfo);
1961 PRINT_HILOGD("UpdateExtensionInfo end.");
1962 return E_PRINT_NONE;
1963 }
1964
RequestPreview(const PrintJob & jobInfo,std::string & previewResult)1965 int32_t PrintServiceAbility::RequestPreview(const PrintJob &jobInfo, std::string &previewResult)
1966 {
1967 ManualStart();
1968 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
1969 PRINT_HILOGE("no permission to access print service");
1970 return E_PRINT_NO_PERMISSION;
1971 }
1972 PRINT_HILOGD("RequestPreview started.");
1973 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
1974
1975 auto userData = GetCurrentUserData();
1976 if (userData == nullptr) {
1977 PRINT_HILOGE("Get user data failed.");
1978 return E_PRINT_INVALID_USERID;
1979 }
1980 auto jobId = jobInfo.GetJobId();
1981 auto printerId = jobInfo.GetPrinterId();
1982 auto extensionId = PrintUtils::GetExtensionId(printerId);
1983
1984 auto jobIt = userData->printJobList_.find(jobId);
1985 if (jobIt == userData->printJobList_.end()) {
1986 PRINT_HILOGD("invalid job id");
1987 return E_PRINT_INVALID_PRINTJOB;
1988 }
1989
1990 if (userData->printJobList_[jobId] == nullptr) {
1991 PRINT_HILOGE("printJob is nullptr.");
1992 return E_PRINT_INVALID_PRINTJOB;
1993 }
1994 if (userData->printJobList_[jobId]->GetJobState() < PRINT_JOB_QUEUED) {
1995 PRINT_HILOGD("invalid job state [%{public}d]", userData->printJobList_[jobId]->GetJobState());
1996 return E_PRINT_INVALID_PRINTJOB;
1997 }
1998
1999 if (printerInfoList_.find(printerId) == printerInfoList_.end()) {
2000 PRINT_HILOGD("invalid printer of the print job");
2001 return E_PRINT_INVALID_PRINTJOB;
2002 }
2003
2004 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_REQUEST_PREVIEW);
2005 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
2006 PRINT_HILOGW("RequestPreview Not Register Yet!!!");
2007 return E_PRINT_SERVER_FAILURE;
2008 }
2009
2010 userData->printJobList_[jobId]->UpdateParams(jobInfo);
2011 auto cbFunc = extCallbackMap_[cid];
2012 if (cbFunc == nullptr) {
2013 PRINT_HILOGE("cbFunc is nullptr.");
2014 return E_PRINT_SERVER_FAILURE;
2015 }
2016 auto callback = [=]() { cbFunc->OnCallback(*userData->printJobList_[jobId]); };
2017 return E_PRINT_NONE;
2018 }
2019
QueryPrinterCapability(const std::string & printerId)2020 int32_t PrintServiceAbility::QueryPrinterCapability(const std::string &printerId)
2021 {
2022 ManualStart();
2023 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2024 PRINT_HILOGE("no permission to access print service");
2025 return E_PRINT_NO_PERMISSION;
2026 }
2027 PRINT_HILOGD("QueryPrinterCapability started %{private}s", printerId.c_str());
2028 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2029 if (printerInfoList_.find(printerId) == printerInfoList_.end()) {
2030 PRINT_HILOGE("Invalid printer id");
2031 return E_PRINT_INVALID_PRINTER;
2032 }
2033
2034 std::string extensionId = PrintUtils::GetExtensionId(printerId);
2035 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, PRINT_EXTCB_REQUEST_CAP);
2036 if (extCallbackMap_.find(cid) == extCallbackMap_.end()) {
2037 PRINT_HILOGW("QueryPrinterCapability Not Register Yet!!!");
2038 return E_PRINT_SERVER_FAILURE;
2039 }
2040
2041 auto cbFunc = extCallbackMap_[cid];
2042 auto callback = [=]() {
2043 if (cbFunc != nullptr) {
2044 cbFunc->OnCallback(printerId);
2045 }
2046 };
2047 if (helper_->IsSyncMode()) {
2048 callback();
2049 } else {
2050 serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
2051 }
2052 return E_PRINT_NONE;
2053 }
2054
NotifyPrintServiceEvent(std::string & jobId,uint32_t event)2055 int32_t PrintServiceAbility::NotifyPrintServiceEvent(std::string &jobId, uint32_t event)
2056 {
2057 ManualStart();
2058 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2059 PRINT_HILOGE("no permission to access print service");
2060 return E_PRINT_NO_PERMISSION;
2061 }
2062
2063 if (event < APPLICATION_CREATED || event > APPLICATION_CLOSED_FOR_CANCELED) {
2064 PRINT_HILOGE("Invalid parameter");
2065 return E_PRINT_INVALID_PARAMETER;
2066 }
2067
2068 switch (event) {
2069 case APPLICATION_CREATED:
2070 if (printJobList_.find(jobId) == printJobList_.end()) {
2071 PRINT_HILOGI("add printJob from phone, jobId: %{public}s", jobId.c_str());
2072 auto printJob = std::make_shared<PrintJob>();
2073 printJob->SetJobId(jobId);
2074 printJob->SetJobState(PRINT_JOB_PREPARED);
2075 RegisterAdapterListener(jobId);
2076 AddToPrintJobList(jobId, printJob);
2077 SendPrintJobEvent(*printJob);
2078 }
2079 printAppCount_++;
2080 PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
2081 break;
2082 case APPLICATION_CLOSED_FOR_STARTED:
2083 ReduceAppCount();
2084 break;
2085 case APPLICATION_CLOSED_FOR_CANCELED:
2086 ReduceAppCount();
2087 break;
2088 default:
2089 break;
2090 }
2091 return E_PRINT_NONE;
2092 }
2093
UnloadSystemAbility()2094 void PrintServiceAbility::UnloadSystemAbility()
2095 {
2096 PRINT_HILOGI("delay unload task begin");
2097 auto unloadTask = [this]() {
2098 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2099 unloadCount_--;
2100 PRINT_HILOGI("do unload task, unloadCount_: %{public}u", unloadCount_);
2101 if (printAppCount_ != 0 || queuedJobList_.size() > 0 || unloadCount_ != 0) {
2102 PRINT_HILOGE("There are still print jobs being executed.");
2103 return;
2104 }
2105 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_UNSUBSCRIBE);
2106 int32_t ret = DestroyExtension();
2107 if (ret != E_PRINT_NONE) {
2108 PRINT_HILOGE("DestroyExtension failed.");
2109 return;
2110 }
2111 #ifdef CUPS_ENABLE
2112 DelayedSingleton<PrintCupsClient>::GetInstance()->StopCupsdService();
2113 #endif // CUPS_ENABLE
2114 auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2115 if (samgrProxy == nullptr) {
2116 PRINT_HILOGE("get samgr failed");
2117 return;
2118 }
2119 ret = samgrProxy->UnloadSystemAbility(PRINT_SERVICE_ID);
2120 if (ret != ERR_OK) {
2121 PRINT_HILOGE("unload print system ability failed");
2122 return;
2123 }
2124 PRINT_HILOGI("unload print system ability successfully");
2125 };
2126 serviceHandler_->PostTask(unloadTask, UNLOAD_SA_INTERVAL);
2127 unloadCount_++;
2128 PRINT_HILOGI("unloadCount_: %{public}u", unloadCount_);
2129 }
2130
CheckPermission(const std::string & permissionName)2131 bool PrintServiceAbility::CheckPermission(const std::string &permissionName)
2132 {
2133 if (helper_ == nullptr) {
2134 return false;
2135 }
2136 return helper_->CheckPermission(permissionName);
2137 }
2138
RegisterPrinterCallback(const std::string & type,const sptr<IPrintCallback> & listener)2139 int32_t PrintServiceAbility::RegisterPrinterCallback(const std::string &type, const sptr<IPrintCallback> &listener)
2140 {
2141 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2142 PRINT_HILOGE("no permission to access print service");
2143 return E_PRINT_NO_PERMISSION;
2144 }
2145 if (listener == nullptr) {
2146 PRINT_HILOGE("Invalid listener");
2147 return E_PRINT_INVALID_PARAMETER;
2148 }
2149 int64_t callerTokenId = static_cast<int64_t>(IPCSkeleton::GetCallingTokenID());
2150 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2151 auto iter = printUserDataMap_.find(callerTokenId);
2152 if (iter == printUserDataMap_.end() || iter->second == nullptr) {
2153 PRINT_HILOGE("Invalid token");
2154 return E_PRINT_INVALID_TOKEN;
2155 }
2156 iter->second->RegisterPrinterCallback(type, listener);
2157 PRINT_HILOGD("PrintServiceAbility::RegisterPrinterCallback end.");
2158 return E_PRINT_NONE;
2159 }
2160
UnregisterPrinterCallback(const std::string & type)2161 int32_t PrintServiceAbility::UnregisterPrinterCallback(const std::string &type)
2162 {
2163 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2164 PRINT_HILOGE("no permission to access print service");
2165 return E_PRINT_NO_PERMISSION;
2166 }
2167 int64_t callerTokenId = static_cast<int64_t>(IPCSkeleton::GetCallingTokenID());
2168 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2169 auto iter = printUserDataMap_.find(callerTokenId);
2170 if (iter == printUserDataMap_.end() || iter->second == nullptr) {
2171 PRINT_HILOGE("Invalid token");
2172 return E_PRINT_INVALID_TOKEN;
2173 }
2174 iter->second->UnregisterPrinterCallback(type);
2175 PRINT_HILOGD("PrintServiceAbility::UnregisterPrinterCallback end.");
2176 if (type == PRINTER_CHANGE_EVENT_TYPE) {
2177 ReduceAppCount();
2178 }
2179 return E_PRINT_NONE;
2180 }
2181
RegisterExtCallback(const std::string & extensionCID,const sptr<IPrintExtensionCallback> & listener)2182 int32_t PrintServiceAbility::RegisterExtCallback(const std::string &extensionCID,
2183 const sptr<IPrintExtensionCallback> &listener)
2184 {
2185 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2186 PRINT_HILOGE("no permission to access print service");
2187 return E_PRINT_NO_PERMISSION;
2188 }
2189 std::string extensionId = "";
2190 uint32_t callbackId = 0;
2191 if (!PrintUtils::DecodeExtensionCid(extensionCID, extensionId, callbackId)) {
2192 PRINT_HILOGE("Failed to decode extension");
2193 return E_PRINT_INVALID_PARAMETER;
2194 }
2195
2196 PRINT_HILOGD("extensionCID = %{public}s, extensionId = %{public}s", extensionCID.c_str(), extensionId.c_str());
2197
2198 auto extensionStateIt = extensionStateList_.find(extensionId);
2199 if (extensionStateIt == extensionStateList_.end()) {
2200 PRINT_HILOGE("Invalid extension id");
2201 return E_PRINT_INVALID_EXTENSION;
2202 }
2203
2204 if (extensionStateIt->second != PRINT_EXTENSION_LOADING) {
2205 PRINT_HILOGE("Invalid Extension State [%{public}d]", extensionStateIt->second);
2206 return E_PRINT_INVALID_EXTENSION;
2207 }
2208
2209 PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback started.");
2210 if (callbackId >= PRINT_EXTCB_MAX) {
2211 PRINT_HILOGE("Invalid callback id [%{public}d]", callbackId);
2212 return E_PRINT_INVALID_PARAMETER;
2213 }
2214
2215 if (listener == nullptr) {
2216 PRINT_HILOGE("Invalid listener");
2217 return E_PRINT_INVALID_PARAMETER;
2218 }
2219
2220 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2221 if (extCallbackMap_.find(extensionCID) == extCallbackMap_.end()) {
2222 extCallbackMap_.insert(std::make_pair(extensionCID, listener));
2223 } else {
2224 PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback Replace listener.");
2225 extCallbackMap_[extensionCID] = listener;
2226 }
2227
2228 PRINT_HILOGD("PrintServiceAbility::RegisterExtCallback end.");
2229 return E_PRINT_NONE;
2230 }
2231
UnregisterAllExtCallback(const std::string & extensionId)2232 int32_t PrintServiceAbility::UnregisterAllExtCallback(const std::string &extensionId)
2233 {
2234 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2235 PRINT_HILOGE("no permission to access print service");
2236 return E_PRINT_NO_PERMISSION;
2237 }
2238
2239 PRINT_HILOGD("PrintServiceAbility::UnregisterAllExtCallback started.");
2240 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2241 for (uint32_t callbackId = PRINT_EXTCB_START_DISCOVERY; callbackId < PRINT_EXTCB_MAX; callbackId++) {
2242 std::string cid = PrintUtils::EncodeExtensionCid(extensionId, callbackId);
2243 auto callbackIt = extCallbackMap_.find(cid);
2244 if (callbackIt != extCallbackMap_.end()) {
2245 extCallbackMap_.erase(callbackIt);
2246 }
2247 }
2248 PRINT_HILOGD("PrintServiceAbility::UnregisterAllExtCallback end.");
2249 return E_PRINT_NONE;
2250 }
2251
LoadExtSuccess(const std::string & extensionId)2252 int32_t PrintServiceAbility::LoadExtSuccess(const std::string &extensionId)
2253 {
2254 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2255 PRINT_HILOGE("no permission to access print service");
2256 return E_PRINT_NO_PERMISSION;
2257 }
2258
2259 PRINT_HILOGD("PrintServiceAbility::LoadExtSuccess started.");
2260 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2261 if (extensionStateList_.find(extensionId) == extensionStateList_.end()) {
2262 PRINT_HILOGE("Invalid extension id");
2263 return E_PRINT_INVALID_EXTENSION;
2264 }
2265
2266 if (extensionStateList_[extensionId] != PRINT_EXTENSION_LOADING) {
2267 PRINT_HILOGE("Invalid Extension State");
2268 return E_PRINT_INVALID_EXTENSION;
2269 }
2270 extensionStateList_[extensionId] = PRINT_EXTENSION_LOADED;
2271
2272 PRINT_HILOGD("Auto Stat Printer Discovery");
2273 auto callback = [=]() { DelayStartDiscovery(extensionId); };
2274 if (helper_->IsSyncMode()) {
2275 callback();
2276 } else {
2277 serviceHandler_->PostTask(callback, ASYNC_CMD_DELAY);
2278 }
2279 PRINT_HILOGD("PrintServiceAbility::LoadExtSuccess end.");
2280 return E_PRINT_NONE;
2281 }
2282
On(const std::string taskId,const std::string & type,const sptr<IPrintCallback> & listener)2283 int32_t PrintServiceAbility::On(const std::string taskId, const std::string &type, const sptr<IPrintCallback> &listener)
2284 {
2285 ManualStart();
2286 std::string permission = PERMISSION_NAME_PRINT_JOB;
2287 std::string eventType = type;
2288 if (taskId != "") {
2289 permission = PERMISSION_NAME_PRINT;
2290 eventType = PrintUtils::GetTaskEventId(taskId, type);
2291 }
2292
2293 if (type == PRINT_CALLBACK_ADAPTER) {
2294 permission = PERMISSION_NAME_PRINT;
2295 eventType = type;
2296 }
2297
2298 if (type == PRINTER_CHANGE_EVENT_TYPE) {
2299 int32_t callerPid = IPCSkeleton::GetCallingPid();
2300 eventType = PrintUtils::GetEventTypeWithToken(callerPid, type);
2301 }
2302
2303 if (!CheckPermission(permission)) {
2304 PRINT_HILOGE("no permission to access print service");
2305 return E_PRINT_NO_PERMISSION;
2306 }
2307
2308 if (eventType == "") {
2309 PRINT_HILOGE("Invalid event type");
2310 return E_PRINT_INVALID_PARAMETER;
2311 }
2312
2313 if (listener == nullptr) {
2314 PRINT_HILOGE("Invalid listener");
2315 return E_PRINT_INVALID_PARAMETER;
2316 }
2317
2318 PRINT_HILOGD("PrintServiceAbility::On started. type=%{public}s", eventType.c_str());
2319 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2320 if (registeredListeners_.find(eventType) == registeredListeners_.end()) {
2321 registeredListeners_.insert(std::make_pair(eventType, listener));
2322 } else {
2323 PRINT_HILOGD("PrintServiceAbility::On Replace listener.");
2324 registeredListeners_[eventType] = listener;
2325 }
2326 if (PrintUtils::GetEventType(eventType) == PRINTER_CHANGE_EVENT_TYPE) {
2327 PRINT_HILOGI("begin on printerChange, StartDiscoverPrinter");
2328 std::vector<PrintExtensionInfo> extensionInfos;
2329 QueryAllExtension(extensionInfos);
2330 std::vector<std::string> extensionIds;
2331 StartDiscoverPrinter(extensionIds);
2332 printAppCount_++;
2333 PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
2334 }
2335 PRINT_HILOGD("PrintServiceAbility::On end.");
2336 return E_PRINT_NONE;
2337 }
2338
Off(const std::string taskId,const std::string & type)2339 int32_t PrintServiceAbility::Off(const std::string taskId, const std::string &type)
2340 {
2341 std::string permission = PERMISSION_NAME_PRINT_JOB;
2342 std::string eventType = type;
2343 if (taskId != "") {
2344 permission = PERMISSION_NAME_PRINT;
2345 eventType = PrintUtils::GetTaskEventId(taskId, type);
2346 }
2347 if (type == PRINTER_CHANGE_EVENT_TYPE) {
2348 int32_t callerPid = IPCSkeleton::GetCallingPid();
2349 eventType = PrintUtils::GetEventTypeWithToken(callerPid, type);
2350 }
2351 if (!CheckPermission(permission)) {
2352 PRINT_HILOGE("no permission to access print service");
2353 return E_PRINT_NO_PERMISSION;
2354 }
2355
2356 if (eventType == "") {
2357 PRINT_HILOGE("Invalid event type");
2358 return E_PRINT_INVALID_PARAMETER;
2359 }
2360
2361 PRINT_HILOGD("PrintServiceAbility::Off started.");
2362 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2363 auto iter = registeredListeners_.find(eventType);
2364 if (iter != registeredListeners_.end()) {
2365 PRINT_HILOGD("PrintServiceAbility::Off delete type=%{public}s object message.", eventType.c_str());
2366 registeredListeners_.erase(iter);
2367 if (PrintUtils::GetEventType(eventType) == PRINTER_CHANGE_EVENT_TYPE) {
2368 ReduceAppCount();
2369 }
2370 return E_PRINT_NONE;
2371 }
2372 return E_PRINT_INVALID_PARAMETER;
2373 }
2374
StartAbility(const AAFwk::Want & want)2375 bool PrintServiceAbility::StartAbility(const AAFwk::Want &want)
2376 {
2377 if (helper_ == nullptr) {
2378 return false;
2379 }
2380 return helper_->StartAbility(want);
2381 }
2382
ConvertToPrintExtensionInfo(const AppExecFwk::ExtensionAbilityInfo & extInfo)2383 PrintExtensionInfo PrintServiceAbility::ConvertToPrintExtensionInfo(const AppExecFwk::ExtensionAbilityInfo &extInfo)
2384 {
2385 PrintExtensionInfo printExtInfo;
2386 printExtInfo.SetExtensionId(extInfo.bundleName);
2387 printExtInfo.SetVendorId(extInfo.bundleName);
2388 printExtInfo.SetVendorName(extInfo.bundleName);
2389 printExtInfo.SetVendorIcon(0);
2390 printExtInfo.SetVersion("1.0.0");
2391 return printExtInfo;
2392 }
2393
SendPrinterDiscoverEvent(int event,const PrinterInfo & info)2394 void PrintServiceAbility::SendPrinterDiscoverEvent(int event, const PrinterInfo &info)
2395 {
2396 PRINT_HILOGD("PrintServiceAbility::SendPrinterDiscoverEvent type %{private}s, %{public}d",
2397 info.GetPrinterId().c_str(), event);
2398 for (auto &item : printUserDataMap_) {
2399 if (item.second != nullptr) {
2400 item.second->SendPrinterEvent(PRINTER_DISCOVER_EVENT_TYPE, event, info);
2401 }
2402 }
2403 }
2404
SendPrinterChangeEvent(int event,const PrinterInfo & info)2405 void PrintServiceAbility::SendPrinterChangeEvent(int event, const PrinterInfo &info)
2406 {
2407 PRINT_HILOGD("PrintServiceAbility::SendPrinterChangeEvent type %{private}s, %{public}d",
2408 info.GetPrinterId().c_str(), event);
2409 for (auto &item : printUserDataMap_) {
2410 if (item.second != nullptr) {
2411 item.second->SendPrinterEvent(PRINTER_CHANGE_EVENT_TYPE, event, info);
2412 }
2413 }
2414 }
SendPrinterEvent(const PrinterInfo & info)2415 void PrintServiceAbility::SendPrinterEvent(const PrinterInfo &info)
2416 {
2417 PRINT_HILOGD("PrintServiceAbility::SendPrinterEvent type %{private}s, %{public}d",
2418 info.GetPrinterId().c_str(), info.GetPrinterState());
2419 auto eventIt = registeredListeners_.find(PRINTER_EVENT_TYPE);
2420 if (eventIt != registeredListeners_.end()) {
2421 eventIt->second->OnCallback(info.GetPrinterState(), info);
2422 }
2423 }
2424
SendPrinterEventChangeEvent(PrinterEvent printerEvent,const PrinterInfo & info)2425 void PrintServiceAbility::SendPrinterEventChangeEvent(PrinterEvent printerEvent, const PrinterInfo &info)
2426 {
2427 PRINT_HILOGD("PrintServiceAbility::SendPrinterEventChangeEvent printerId: %{public}s, printerEvent: %{public}d",
2428 info.GetPrinterId().c_str(), printerEvent);
2429 for (auto eventIt: registeredListeners_) {
2430 if (PrintUtils::GetEventType(eventIt.first) == PRINTER_CHANGE_EVENT_TYPE && eventIt.second != nullptr) {
2431 PRINT_HILOGD("PrintServiceAbility::SendPrinterEventChangeEvent find PRINTER_CHANGE_EVENT_TYPE");
2432 eventIt.second->OnCallback(printerEvent, info);
2433 }
2434 }
2435 }
2436
SendPrintJobEvent(const PrintJob & jobInfo)2437 void PrintServiceAbility::SendPrintJobEvent(const PrintJob &jobInfo)
2438 {
2439 PRINT_HILOGD("PrintServiceAbility::SendPrintJobEvent jobId: %{public}s, state: %{public}d, subState: %{public}d",
2440 jobInfo.GetJobId().c_str(), jobInfo.GetJobState(), jobInfo.GetSubState());
2441 auto eventIt = registeredListeners_.find(PRINTJOB_EVENT_TYPE);
2442 if (eventIt != registeredListeners_.end()) {
2443 eventIt->second->OnCallback(jobInfo.GetJobState(), jobInfo);
2444 }
2445
2446 // notify securityGuard
2447 if (jobInfo.GetJobState() == PRINT_JOB_COMPLETED) {
2448 std::shared_ptr<PrinterInfo> printerInfo = getPrinterInfo(jobInfo.GetPrinterId());
2449 if (printerInfo != nullptr) {
2450 securityGuardManager_.receiveJobStateUpdate(jobInfo.GetJobId(), *printerInfo, jobInfo);
2451 } else {
2452 PRINT_HILOGD("receiveJobStateUpdate printer is empty");
2453 }
2454 }
2455
2456 std::string stateInfo = "";
2457 if (jobInfo.GetJobState() == PRINT_JOB_BLOCKED) {
2458 stateInfo = EVENT_BLOCK;
2459 } else if (jobInfo.GetJobState() == PRINT_JOB_COMPLETED) {
2460 switch (jobInfo.GetSubState()) {
2461 case PRINT_JOB_COMPLETED_SUCCESS:
2462 stateInfo = EVENT_SUCCESS;
2463 break;
2464
2465 case PRINT_JOB_COMPLETED_FAILED:
2466 stateInfo = EVENT_FAIL;
2467 break;
2468
2469 case PRINT_JOB_COMPLETED_CANCELLED:
2470 stateInfo = EVENT_CANCEL;
2471 break;
2472 default:
2473 break;
2474 }
2475 }
2476 if (stateInfo != "") {
2477 std::string taskEvent = PrintUtils::GetTaskEventId(jobInfo.GetJobId(), stateInfo);
2478 auto taskEventIt = registeredListeners_.find(taskEvent);
2479 if (taskEventIt != registeredListeners_.end()) {
2480 taskEventIt->second->OnCallback();
2481 }
2482 }
2483 }
2484
SendExtensionEvent(const std::string & extensionId,const std::string & extInfo)2485 void PrintServiceAbility::SendExtensionEvent(const std::string &extensionId, const std::string &extInfo)
2486 {
2487 PRINT_HILOGD("PrintServiceAbility::SendExtensionEvent type %{public}s", extInfo.c_str());
2488 auto eventIt = registeredListeners_.find(EXTINFO_EVENT_TYPE);
2489 if (eventIt != registeredListeners_.end()) {
2490 eventIt->second->OnCallback(extensionId, extInfo);
2491 }
2492 }
2493
getPrinterInfo(const std::string printerId)2494 std::shared_ptr<PrinterInfo> PrintServiceAbility::getPrinterInfo(const std::string printerId)
2495 {
2496 auto printerIt = printerInfoList_.find(printerId);
2497 if (printerIt != printerInfoList_.end()) {
2498 return printerIt ->second;
2499 }
2500 return nullptr;
2501 }
2502
SetHelper(const std::shared_ptr<PrintServiceHelper> & helper)2503 void PrintServiceAbility::SetHelper(const std::shared_ptr<PrintServiceHelper> &helper)
2504 {
2505 helper_ = helper;
2506 DelayedSingleton<PrintBMSHelper>::GetInstance()->SetHelper(helper_);
2507 }
2508
CheckJobQueueBlocked(const PrintJob & jobInfo)2509 void PrintServiceAbility::CheckJobQueueBlocked(const PrintJob &jobInfo)
2510 {
2511 PRINT_HILOGD("CheckJobQueueBlocked started,isJobQueueBlocked_=%{public}s", isJobQueueBlocked_ ? "true" : "false");
2512 PRINT_HILOGD("CheckJobQueueBlocked %{public}s, %{public}d", jobInfo.GetJobId().c_str(), jobInfo.GetJobState());
2513 if (!isJobQueueBlocked_ && jobInfo.GetJobState() == PRINT_JOB_BLOCKED) {
2514 // going blocked
2515 isJobQueueBlocked_ = true;
2516 if (GetUserIdByJobId(jobInfo.GetJobId()) == currentUserId_) {
2517 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_BLOCKED);
2518 }
2519 }
2520
2521 if (isJobQueueBlocked_ && jobInfo.GetJobState() != PRINT_JOB_BLOCKED) {
2522 bool hasJobBlocked = false;
2523 auto userData = GetUserDataByJobId(jobInfo.GetJobId());
2524 if (userData == nullptr) {
2525 PRINT_HILOGE("Get user data failed.");
2526 return;
2527 }
2528 for (auto printJob : userData->queuedJobList_) {
2529 if (printJob.second->GetJobState() == PRINT_JOB_BLOCKED) {
2530 hasJobBlocked = true;
2531 break;
2532 }
2533 }
2534 if (!hasJobBlocked) {
2535 // clear blocked
2536 isJobQueueBlocked_ = false;
2537 if (GetUserIdByJobId(jobInfo.GetJobId()) == currentUserId_) {
2538 NotifyAppJobQueueChanged(QUEUE_JOB_LIST_CLEAR_BLOCKED);
2539 }
2540 }
2541 }
2542 PRINT_HILOGD("CheckJobQueueBlocked end,isJobQueueBlocked_=%{public}s", isJobQueueBlocked_ ? "true" : "false");
2543 }
2544
PrintByAdapter(const std::string jobName,const PrintAttributes & printAttributes,std::string & taskId)2545 int32_t PrintServiceAbility::PrintByAdapter(const std::string jobName, const PrintAttributes &printAttributes,
2546 std::string &taskId)
2547 {
2548 ManualStart();
2549 if (!CheckPermission(PERMISSION_NAME_PRINT)) {
2550 PRINT_HILOGE("no permission to access print service");
2551 return E_PRINT_NO_PERMISSION;
2552 }
2553 PRINT_HILOGI("PrintServiceAbility::PrintByAdapter start");
2554
2555 std::vector<std::string> fileList;
2556 std::vector<uint32_t> fdList;
2557 int32_t ret = CallSpooler(fileList, fdList, taskId);
2558 if (ret != E_PRINT_NONE) {
2559 PRINT_HILOGE("PrintServiceAbility::PrintByAdapter CallSpooler failed, ret: %{public}d", ret);
2560 }
2561 PRINT_HILOGI("PrintServiceAbility::PrintByAdapter end");
2562 return ret;
2563 }
2564
StartGetPrintFile(const std::string & jobId,const PrintAttributes & printAttributes,const uint32_t fd)2565 int32_t PrintServiceAbility::StartGetPrintFile(const std::string &jobId, const PrintAttributes &printAttributes,
2566 const uint32_t fd)
2567 {
2568 ManualStart();
2569 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2570 PRINT_HILOGE("no permission to access print service");
2571 return E_PRINT_NO_PERMISSION;
2572 }
2573 PRINT_HILOGI("PrintServiceAbility::StartGetPrintFile start");
2574 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2575 auto eventIt = adapterListenersByJobId_.find(jobId);
2576 if (eventIt != adapterListenersByJobId_.end() && eventIt->second != nullptr) {
2577 PrintAttributes oldAttrs;
2578 auto attrIt = printAttributesList_.find(jobId);
2579 if (attrIt == printAttributesList_.end()) {
2580 printAttributesList_.insert(std::make_pair(jobId, printAttributes));
2581 } else {
2582 oldAttrs = attrIt->second;
2583 PRINT_HILOGD("PrintServiceAbility::StartGetPrintFile Replace printAttributes.");
2584 printAttributesList_[jobId] = printAttributes;
2585 }
2586
2587 eventIt->second->OnCallbackAdapterLayout(jobId, oldAttrs, printAttributes, fd);
2588 } else {
2589 PRINT_HILOGW("PrintServiceAbility find event:%{public}s not found", PRINT_ADAPTER_EVENT_TYPE.c_str());
2590 }
2591 PRINT_HILOGI("PrintServiceAbility::StartGetPrintFile end");
2592 return E_PRINT_NONE;
2593 }
2594
NotifyPrintService(const std::string & jobId,const std::string & type)2595 int32_t PrintServiceAbility::NotifyPrintService(const std::string &jobId, const std::string &type)
2596 {
2597 std::string permission = PERMISSION_NAME_PRINT_JOB;
2598 if (!CheckPermission(permission)) {
2599 PRINT_HILOGE("no permission to access print service");
2600 return E_PRINT_NO_PERMISSION;
2601 }
2602
2603 if (type == "0" || type == NOTIFY_INFO_SPOOLER_CLOSED_FOR_STARTED) {
2604 PRINT_HILOGI("Notify Spooler Closed for started jobId : %{public}s", jobId.c_str());
2605 notifyAdapterJobChanged(jobId, PRINT_JOB_SPOOLER_CLOSED, PRINT_JOB_SPOOLER_CLOSED_FOR_STARTED);
2606 ReduceAppCount();
2607 return E_PRINT_NONE;
2608 }
2609
2610 if (type == NOTIFY_INFO_SPOOLER_CLOSED_FOR_CANCELLED) {
2611 PRINT_HILOGI("Notify Spooler Closed for canceled jobId : %{public}s", jobId.c_str());
2612 notifyAdapterJobChanged(jobId, PRINT_JOB_SPOOLER_CLOSED, PRINT_JOB_SPOOLER_CLOSED_FOR_CANCELED);
2613 ReduceAppCount();
2614 return E_PRINT_NONE;
2615 }
2616 return E_PRINT_INVALID_PARAMETER;
2617 }
2618
ReduceAppCount()2619 void PrintServiceAbility::ReduceAppCount()
2620 {
2621 printAppCount_ = printAppCount_ >= 1 ? printAppCount_ - 1 : 0;
2622 PRINT_HILOGI("printAppCount_: %{public}u", printAppCount_);
2623 if (printAppCount_ == 0 && queuedJobList_.size() == 0) {
2624 UnloadSystemAbility();
2625 }
2626 }
2627
notifyAdapterJobChanged(const std::string jobId,const uint32_t state,const uint32_t subState)2628 void PrintServiceAbility::notifyAdapterJobChanged(const std::string jobId, const uint32_t state,
2629 const uint32_t subState)
2630 {
2631 if (state != PRINT_JOB_BLOCKED && state != PRINT_JOB_COMPLETED && state != PRINT_JOB_SPOOLER_CLOSED) {
2632 return;
2633 }
2634 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2635 auto attrIt = printAttributesList_.find(jobId);
2636 if (attrIt != printAttributesList_.end()) {
2637 printAttributesList_.erase(attrIt);
2638 }
2639
2640 PRINT_HILOGI("get adapterListenersByJobId_ %{public}s", jobId.c_str());
2641 auto eventIt = adapterListenersByJobId_.find(jobId);
2642 if (eventIt == adapterListenersByJobId_.end() || eventIt->second == nullptr) {
2643 return;
2644 }
2645
2646 uint32_t printAdapterListeningState = PRINT_TASK_FAIL;
2647 if (state == PRINT_JOB_SPOOLER_CLOSED) {
2648 printAdapterListeningState = GetListeningState(subState);
2649 } else if (state == PRINT_JOB_BLOCKED) {
2650 printAdapterListeningState = PRINT_TASK_BLOCK;
2651 } else {
2652 switch (subState) {
2653 case PRINT_JOB_COMPLETED_SUCCESS:
2654 printAdapterListeningState = PRINT_TASK_SUCCEED;
2655 break;
2656 case PRINT_JOB_COMPLETED_FAILED:
2657 printAdapterListeningState = PRINT_TASK_FAIL;
2658 break;
2659 case PRINT_JOB_COMPLETED_CANCELLED:
2660 printAdapterListeningState = PRINT_TASK_CANCEL;
2661 break;
2662 default:
2663 printAdapterListeningState = PRINT_TASK_FAIL;
2664 break;
2665 }
2666 }
2667 PRINT_HILOGI("notifyAdapterJobChanged for subState: %{public}d, listeningState: %{public}d",
2668 subState, printAdapterListeningState);
2669 eventIt->second->onCallbackAdapterJobStateChanged(jobId, state, printAdapterListeningState);
2670
2671 if (subState == PRINT_JOB_SPOOLER_CLOSED_FOR_CANCELED || state == PRINT_JOB_COMPLETED) {
2672 PRINT_HILOGI("erase adapterListenersByJobId_ %{public}s", jobId.c_str());
2673 adapterListenersByJobId_.erase(jobId);
2674 }
2675 }
2676
GetListeningState(const uint32_t subState)2677 uint32_t PrintServiceAbility::GetListeningState(const uint32_t subState)
2678 {
2679 switch (subState) {
2680 case PRINT_JOB_SPOOLER_CLOSED_FOR_CANCELED:
2681 return PREVIEW_ABILITY_DESTROY_FOR_CANCELED;
2682 break;
2683 case PRINT_JOB_SPOOLER_CLOSED_FOR_STARTED:
2684 return PREVIEW_ABILITY_DESTROY_FOR_STARTED;
2685 break;
2686 default:
2687 return PREVIEW_ABILITY_DESTROY;
2688 break;
2689 }
2690 }
2691
CallStatusBar()2692 int32_t PrintServiceAbility::CallStatusBar()
2693 {
2694 PRINT_HILOGI("PrintServiceAbility CallStatusBar enter.");
2695 ManualStart();
2696 if (!CheckPermission(PERMISSION_NAME_PRINT) && !CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2697 PRINT_HILOGE("no permission to access print service, ErrorCode:[%{public}d]", E_PRINT_NO_PERMISSION);
2698 return E_PRINT_NO_PERMISSION;
2699 }
2700 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2701 AAFwk::Want want;
2702 want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_STATUS_BAR_ABILITY_NAME);
2703 int32_t callerTokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
2704 std::string callerPkg = SPOOLER_PACKAGE_NAME;
2705 ingressPackage = callerPkg;
2706 int32_t callerUid = IPCSkeleton::GetCallingUid();
2707 int32_t callerPid = IPCSkeleton::GetCallingPid();
2708 want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_TOKEN, callerTokenId);
2709 want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_UID, callerUid);
2710 want.SetParam(AAFwk::Want::PARAM_RESV_CALLER_PID, callerPid);
2711 want.SetParam(CALLER_PKG_NAME, callerPkg);
2712 if (!StartPluginPrintIconExtAbility(want)) {
2713 PRINT_HILOGE("Failed to start PluginPrintIconExtAbility");
2714 return E_PRINT_SERVER_FAILURE;
2715 }
2716 return E_PRINT_NONE;
2717 }
2718
StartPluginPrintIconExtAbility(const AAFwk::Want & want)2719 bool PrintServiceAbility::StartPluginPrintIconExtAbility(const AAFwk::Want &want)
2720 {
2721 if (helper_ == nullptr) {
2722 PRINT_HILOGE("Invalid print service helper.");
2723 return false;
2724 }
2725 PRINT_HILOGI("enter PrintServiceAbility::StartPluginPrintIconExtAbility");
2726 return helper_->StartPluginPrintIconExtAbility(want);
2727 }
2728
GetCurrentUserData()2729 std::shared_ptr<PrintUserData> PrintServiceAbility::GetCurrentUserData()
2730 {
2731 int32_t userId = GetCurrentUserId();
2732 if (userId == E_PRINT_INVALID_USERID) {
2733 PRINT_HILOGE("Invalid user id.");
2734 return nullptr;
2735 }
2736 auto iter = printUserMap_.find(userId);
2737 if (iter == printUserMap_.end()) {
2738 PRINT_HILOGE("Current user is not added, add it.");
2739 UpdatePrintUserMap();
2740 iter = printUserMap_.find(userId);
2741 if (iter == printUserMap_.end()) {
2742 PRINT_HILOGE("add user failed.");
2743 return nullptr;
2744 }
2745 }
2746 return iter->second;
2747 }
2748
GetCurrentUserId()2749 int32_t PrintServiceAbility::GetCurrentUserId()
2750 {
2751 int32_t userId = IPCSkeleton::GetCallingUid() / UID_TRANSFORM_DIVISOR;
2752 PRINT_HILOGI("Current userId = %{public}d", userId);
2753 if (userId < START_USER_ID) {
2754 PRINT_HILOGE("id %{public}d is system reserved", userId);
2755 return E_PRINT_INVALID_USERID;
2756 }
2757 if (userId > MAX_USER_ID) {
2758 PRINT_HILOGE("id %{public}d is out of range", userId);
2759 return E_PRINT_INVALID_USERID;
2760 }
2761 return userId;
2762 }
2763
GetUserDataByJobId(const std::string jobId)2764 std::shared_ptr<PrintUserData> PrintServiceAbility::GetUserDataByJobId(const std::string jobId)
2765 {
2766 int32_t userId = GetUserIdByJobId(jobId);
2767 PRINT_HILOGI("the job is belong to user-%{public}d.", userId);
2768 if (userId == E_PRINT_INVALID_PRINTJOB) {
2769 PRINT_HILOGE("Invalid job id.");
2770 return nullptr;
2771 }
2772 auto iter = printUserMap_.find(userId);
2773 if (iter == printUserMap_.end()) {
2774 PRINT_HILOGE("Current user is not added.");
2775 UpdatePrintUserMap();
2776 iter = printUserMap_.find(userId);
2777 if (iter == printUserMap_.end()) {
2778 PRINT_HILOGE("add user failed.");
2779 return nullptr;
2780 }
2781 }
2782 return iter->second;
2783 }
2784
GetUserIdByJobId(const std::string jobId)2785 int32_t PrintServiceAbility::GetUserIdByJobId(const std::string jobId)
2786 {
2787 for (std::map<std::string, int32_t>::iterator it = userJobMap_.begin(); it != userJobMap_.end();
2788 ++it) {
2789 PRINT_HILOGI("jobId: %{public}s, userId: %{public}d.", it->first.c_str(), it->second);
2790 }
2791 auto iter = userJobMap_.find(jobId);
2792 if (iter == userJobMap_.end()) {
2793 PRINT_HILOGE("Invalid job id.");
2794 return E_PRINT_INVALID_PRINTJOB;
2795 }
2796 return iter->second;
2797 }
2798
UpdatePrintUserMap()2799 void PrintServiceAbility::UpdatePrintUserMap()
2800 {
2801 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2802 int32_t userId = GetCurrentUserId();
2803 if (userId == E_PRINT_INVALID_USERID) {
2804 PRINT_HILOGE("Invalid user id.");
2805 return;
2806 }
2807 PRINT_HILOGI("new user id: %{public}d.", userId);
2808 currentUserId_ = userId;
2809 auto iter = printUserMap_.find(userId);
2810 if (iter == printUserMap_.end()) {
2811 auto userData = std::make_shared<PrintUserData>();
2812 if (userData != nullptr) {
2813 printUserMap_.insert(std::make_pair(userId, userData));
2814 userData->SetUserId(userId);
2815 userData->ParseUserData();
2816 PRINT_HILOGI("add user success");
2817 }
2818 }
2819 }
2820
AddToPrintJobList(const std::string jobId,const std::shared_ptr<PrintJob> & printjob)2821 void PrintServiceAbility::AddToPrintJobList(const std::string jobId, const std::shared_ptr<PrintJob> &printjob)
2822 {
2823 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2824 PRINT_HILOGD("begin AddToPrintJobList.");
2825 UpdatePrintUserMap();
2826 printJobList_.insert(std::make_pair(jobId, printjob));
2827 for (auto printjob : printJobList_) {
2828 PRINT_HILOGI("printjob in printJobList_, jobId: %{public}s.", printjob.first.c_str());
2829 }
2830 int32_t userId = GetCurrentUserId();
2831 auto userData = GetCurrentUserData();
2832 if (userData == nullptr) {
2833 PRINT_HILOGE("Get user data failed.");
2834 return;
2835 }
2836 userJobMap_.insert(std::make_pair(jobId, userId));
2837 userData->AddToPrintJobList(jobId, printjob);
2838 }
2839
RegisterAdapterListener(const std::string & jobId)2840 void PrintServiceAbility::RegisterAdapterListener(const std::string &jobId)
2841 {
2842 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2843 PRINT_HILOGD("RegisterAdapterListener for jobId %{public}s", jobId.c_str());
2844 auto eventIt = registeredListeners_.find(PRINT_ADAPTER_EVENT_TYPE);
2845 if (eventIt != registeredListeners_.end()) {
2846 PRINT_HILOGI("adapterListenersByJobId_ set adapterListenersByJobId_ %{public}s", jobId.c_str());
2847 adapterListenersByJobId_.insert(std::make_pair(jobId, eventIt->second));
2848 }
2849 }
2850
SetDefaultPrinter(const std::string & printerId,uint32_t type)2851 int32_t PrintServiceAbility::SetDefaultPrinter(const std::string &printerId, uint32_t type)
2852 {
2853 ManualStart();
2854 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2855 PRINT_HILOGE("no permission to access print service");
2856 return E_PRINT_NO_PERMISSION;
2857 }
2858 PRINT_HILOGD("SetDefaultPrinter started.");
2859 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2860
2861 auto userData = GetCurrentUserData();
2862 if (userData == nullptr) {
2863 PRINT_HILOGE("Get user data failed.");
2864 return E_PRINT_INVALID_USERID;
2865 }
2866 int32_t ret = userData->SetDefaultPrinter(printerId, type);
2867 if (ret != E_PRINT_NONE) {
2868 PRINT_HILOGE("SetDefaultPrinter failed.");
2869 return ret;
2870 }
2871 return E_PRINT_NONE;
2872 }
2873
CheckIsDefaultPrinter(const std::string & printerId)2874 bool PrintServiceAbility::CheckIsDefaultPrinter(const std::string &printerId)
2875 {
2876 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2877 auto userData = GetCurrentUserData();
2878 if (userData == nullptr) {
2879 PRINT_HILOGE("Get user data failed.");
2880 return false;
2881 }
2882 if (printerId != userData->GetDefaultPrinter()) {
2883 return false;
2884 }
2885 return true;
2886 }
2887
CheckIsLastUsedPrinter(const std::string & printerId)2888 bool PrintServiceAbility::CheckIsLastUsedPrinter(const std::string &printerId)
2889 {
2890 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2891 auto userData = GetCurrentUserData();
2892 if (userData == nullptr) {
2893 PRINT_HILOGE("Get user data failed.");
2894 return false;
2895 }
2896 if (printerId != userData->GetLastUsedPrinter()) {
2897 return false;
2898 }
2899 return true;
2900 }
2901
DeletePrinterFromCups(const std::string & printerUri,const std::string & printerName,const std::string & printerMake)2902 int32_t PrintServiceAbility::DeletePrinterFromCups(
2903 const std::string &printerUri, const std::string &printerName, const std::string &printerMake)
2904 {
2905 ManualStart();
2906 if (!CheckPermission(PERMISSION_NAME_PRINT_JOB)) {
2907 PRINT_HILOGE("no permission to access print service");
2908 return E_PRINT_NO_PERMISSION;
2909 }
2910 PRINT_HILOGD("DeletePrinterFromCups started.");
2911 std::lock_guard<std::recursive_mutex> lock(apiMutex_);
2912 #ifdef CUPS_ENABLE
2913 auto ret =
2914 DelayedSingleton<PrintCupsClient>::GetInstance()->DeletePrinterFromCups(printerUri, printerName, printerMake);
2915 if (ret != E_PRINT_NONE) {
2916 PRINT_HILOGW("DeletePrinterFromCups error = %{public}d.", ret);
2917 return ret;
2918 }
2919 #endif // CUPS_ENABLE
2920 std::string printerId = printSystemData_.QueryPrinterIdByStandardizeName(printerName);
2921 #ifdef IPPOVERUSB_ENABLE
2922 DelayedSingleton<PrintIppOverUsbManager>::GetInstance()->DisConnectPrinter(printerId);
2923 #endif // IPPOVERUSB_ENABLE
2924 DeletePrinterFromUserData(printerId);
2925 NotifyAppDeletePrinterWithDefaultPrinter(printerId);
2926 printSystemData_.DeleteCupsPrinter(printerId);
2927 return E_PRINT_NONE;
2928 }
2929
DeletePrinterFromUserData(const std::string & printerId)2930 void PrintServiceAbility::DeletePrinterFromUserData(const std::string &printerId)
2931 {
2932 std::vector<int32_t> allPrintUserList;
2933 printSystemData_.GetAllPrintUser(allPrintUserList);
2934 for (auto userId : allPrintUserList) {
2935 PRINT_HILOGI("DeletePrinterFromUserData userId %{public}d.", userId);
2936 auto iter = printUserMap_.find(userId);
2937 if (iter != printUserMap_.end()) {
2938 ChangeDefaultPrinterForDelete(iter->second, printerId);
2939 } else {
2940 auto userData = std::make_shared<PrintUserData>();
2941 userData->SetUserId(userId);
2942 userData->ParseUserData();
2943 ChangeDefaultPrinterForDelete(userData, printerId);
2944 }
2945 }
2946 }
2947
ChangeDefaultPrinterForDelete(std::shared_ptr<PrintUserData> & userData,const std::string & printerId)2948 void PrintServiceAbility::ChangeDefaultPrinterForDelete(
2949 std::shared_ptr<PrintUserData> &userData, const std::string &printerId)
2950 {
2951 userData->DeletePrinter(printerId);
2952 std::string defaultPrinterId = userData->GetDefaultPrinter();
2953 bool ret = userData->CheckIfUseLastUsedPrinterForDefault();
2954 PRINT_HILOGI("DeletePrinterFromUserData defaultPrinterId %{public}s.", defaultPrinterId.c_str());
2955 if (!strcmp(printerId.c_str(), defaultPrinterId.c_str())) {
2956 if (!ret) {
2957 userData->SetDefaultPrinter("", DELETE_DEFAULT_PRINTER);
2958 } else {
2959 userData->SetDefaultPrinter("", DELETE_LAST_USED_PRINTER);
2960 }
2961 }
2962 }
2963
GetUserDataByUserId(int32_t userId)2964 std::shared_ptr<PrintUserData> PrintServiceAbility::GetUserDataByUserId(int32_t userId)
2965 {
2966 auto iter = printUserMap_.find(userId);
2967 if (iter == printUserMap_.end()) {
2968 PRINT_HILOGE("Current user is not added, add it.");
2969 auto userData = std::make_shared<PrintUserData>();
2970 if (userData != nullptr) {
2971 printUserMap_.insert(std::make_pair(userId, userData));
2972 userData->SetUserId(userId);
2973 userData->ParseUserData();
2974 PRINT_HILOGI("add user success");
2975 return userData;
2976 } else {
2977 return nullptr;
2978 }
2979 }
2980 return iter->second;
2981 }
2982
DetermineUserJobStatus(const std::map<std::string,std::shared_ptr<PrintJob>> & jobList)2983 PrintJobState PrintServiceAbility::DetermineUserJobStatus(
2984 const std::map<std::string, std::shared_ptr<PrintJob>> &jobList)
2985 {
2986 bool hasBlocked = std::any_of(jobList.begin(), jobList.end(),
2987 [](const auto& pair) { return pair.second->GetJobState() == PRINT_JOB_BLOCKED; });
2988 if (hasBlocked) {
2989 return PRINT_JOB_BLOCKED;
2990 }
2991 bool allComplete = std::all_of(jobList.begin(), jobList.end(),
2992 [](const auto& pair) { return pair.second->GetJobState() == PRINT_JOB_COMPLETED; });
2993 if (allComplete) {
2994 return PRINT_JOB_COMPLETED;
2995 }
2996 return PRINT_JOB_RUNNING;
2997 }
2998
NotifyAppDeletePrinterWithDefaultPrinter(const std::string & printerId)2999 void PrintServiceAbility::NotifyAppDeletePrinterWithDefaultPrinter(const std::string &printerId)
3000 {
3001 auto userData = GetCurrentUserData();
3002 if (userData == nullptr) {
3003 PRINT_HILOGE("Get user data failed.");
3004 return;
3005 }
3006 std::string dafaultPrinterId = userData->GetDefaultPrinter();
3007 PrinterInfo printerInfo;
3008 printSystemData_.QueryPrinterInfoById(printerId, printerInfo);
3009 printerInfo.SetPrinterName(PrintUtil::RemoveUnderlineFromPrinterName(printerInfo.GetPrinterName()));
3010 std::string ops = printerInfo.GetOption();
3011 if (!json::accept(ops)) {
3012 PRINT_HILOGW("ops can not parse to json object");
3013 return;
3014 }
3015 nlohmann::json opsJson = json::parse(ops);
3016 opsJson["nextDefaultPrinter"] = dafaultPrinterId;
3017 printerInfo.SetOption(opsJson.dump());
3018 SendPrinterEventChangeEvent(PRINTER_EVENT_DELETED, printerInfo);
3019 SendPrinterChangeEvent(PRINTER_EVENT_DELETED, printerInfo);
3020 }
3021 } // namespace OHOS::Print
3022