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