1 /*
2  * Copyright (c) 2024 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 
16 #include "create_gzip.h"
17 
18 #include <memory>
19 #include <tuple>
20 
21 #include "app_log_wrapper.h"
22 #include "class_gzip/gzip_entity.h"
23 #include "class_gzip/gzip_n_exporter.h"
24 #include "common/common_func.h"
25 #include "common/file_utils.h"
26 
27 namespace OHOS {
28 namespace AppExecFwk {
29 namespace LIBZIP {
30 using namespace std;
31 
InstantiateGZip(napi_env env)32 static NapiValue InstantiateGZip(napi_env env)
33 {
34     napi_value objZip = NapiClass::InstantiateClass(env, GZipNExporter::className_, {});
35     if (!objZip) {
36         NapiBusinessError().ThrowErr(env, EFAULT);
37         return NapiValue();
38     }
39 
40     auto zipEntity = NapiClass::GetEntityOf<GZipEntity>(env, objZip);
41     if (!zipEntity) {
42         NapiBusinessError().ThrowErr(env, EFAULT);
43         return NapiValue();
44     }
45 
46     return {env, objZip};
47 }
48 
Sync(napi_env env,napi_callback_info info)49 napi_value CreateGZip::Sync(napi_env env, napi_callback_info info)
50 {
51     return InstantiateGZip(env).val_;
52 }
53 
Async(napi_env env,napi_callback_info info)54 napi_value CreateGZip::Async(napi_env env, napi_callback_info info)
55 {
56     NapiFuncArg funcArg(env, info);
57     if (!funcArg.InitArgs(ArgumentCount::ZERO, ArgumentCount::ONE)) {
58         APP_LOGE("Number of arguments unmatched");
59         NapiBusinessError().ThrowErr(env, EINVAL);
60         return nullptr;
61     }
62 
63     auto cbExec = [](napi_env env) -> NapiBusinessError { return NapiBusinessError(ERRNO_NOERR); };
64 
65     auto cbCompl = [](napi_env env, NapiBusinessError err) -> NapiValue {
66         if (err) {
67             return {env, err.GetNapiErr(env)};
68         }
69         return InstantiateGZip(env);
70     };
71 
72     NapiValue thisVar(env, funcArg.GetThisVar());
73     if (funcArg.GetArgc() == ArgumentCount::ZERO) {
74         return NapiAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_CREATE_GZIP_NAME, cbExec, cbCompl).val_;
75     } else {
76         NapiValue cb(env, funcArg[ArgumentPosition::FIRST]);
77         return NapiAsyncWorkCallback(env, thisVar, cb).Schedule(PROCEDURE_CREATE_GZIP_NAME, cbExec, cbCompl).val_;
78     }
79 }
80 }  // namespace LIBZIP
81 }  // namespace AppExecFwk
82 }  // namespace OHOS