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