• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
16import rpc from "@ohos.rpc";
17import fileio from '@ohos.fileio';
18import backgroundTaskManager from '@ohos.backgroundTaskManager';
19import wantAgent from '@ohos.wantAgent';
20import featureAbility from '@ohos.ability.featureAbility';
21
22function startContinuousTask() {
23    let wantAgentInfo = {
24        wants: [
25            {
26                bundleName: "com.ohos.fileiotest",
27                abilityName: "com.ohos.fileiotest.ServiceAbility"
28            }
29        ],
30        operationType: wantAgent.OperationType.START_SERVICE,
31        requestCode: 0,
32        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
33    };
34
35    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
36        try{
37            backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
38                backgroundTaskManager.BackgroundMode.MULTI_DEVICE_CONNECTION, wantAgentObj).then(() => {
39                console.info("Operation startBackgroundRunning succeeded");
40            }).catch((err) => {
41                console.error("Operation startBackgroundRunning failed Cause: " + err);
42            });
43        }catch(error){
44            console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
45        }
46    });
47}
48
49function stopContinuousTask() {
50    try{
51        backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
52            console.info("Operation stopBackgroundRunning succeeded");
53        }).catch((err) => {
54            console.error("Operation stopBackgroundRunning failed Cause: " + err);
55        });
56    }catch(error){
57        console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
58    }
59}
60
61export default {
62    onStart() {
63        console.info('FileioServer: onStart')
64        startContinuousTask();
65        console.info('FileioServer: startContinuousTask');
66    },
67    onStop() {
68        console.info('FileioServer: onStop')
69        stopContinuousTask();
70        console.info('FileioServer: stopContinuousTask');
71    },
72    onCommand(want, startId) {
73        console.info('FileioServer: onCommand, want: ' + JSON.stringify(want) + ', startId: ' + startId)
74    },
75    onConnect(want) {
76        console.info('FileioServer: service onConnect called.')
77        return new Stub("rpcTestAbility")
78    },
79    onDisconnect(want) {
80        console.info('FileioServer: service onDisConnect called.')
81    },
82    onReconnect(want) {
83        console.info('FileioServer: service onReConnect called.')
84    }
85}
86
87function checkDirExists(destDirPath) {
88    console.info("start check dir :" + destDirPath);
89    try {
90        fileio.accessSync(destDirPath, 0);
91        console.info('------------------- dest dir exists.');
92        return true;
93    } catch (e) {
94        console.info('------------------- dest dir is not exists.');
95        return false;
96    }
97}
98
99function checkFileExists(destFilePath,) {
100    console.info("start check file :" + destFilePath);
101    try {
102        fileio.accessSync(destFilePath, 0);
103        console.info('------------------- ' + destFilePath + ' exists.');
104        return true;
105    } catch (e) {
106        console.info('------------------- ' + destFilePath + ' not exists.');
107        return false;
108    }
109}
110
111function getFileContent(fpath) {
112    console.info("start get file content:" + fpath);
113    let content = "";
114    try {
115        content = fileio.readTextSync(fpath);
116        console.info("-------------- dest file content :" + content);
117    } catch (e) {
118        content = "serverSide readTextSync failed";
119        console.info("-------------- read dest file content failed." + e);
120    }
121    return content;
122}
123
124const CODE_MK_DIR = 1;
125const CODE_RM_DIR = 2;
126const CODE_CREATE_FILE = 3;
127const CODE_DELETE_FILE = 4;
128const CODE_GET_FILE_CONTENT = 5;
129const CODE_GET_FILE_STAT = 6;
130const CODE_FSYNC_FILE = 7;
131
132class Stub extends rpc.RemoteObject {
133    constructor(descriptor) {
134        super(descriptor);
135    }
136
137    onRemoteRequest(code, data, reply, option) {
138        try {
139            console.info("onRemoteRequest: " + code)
140            switch (code) {
141                case CODE_MK_DIR:
142                {
143                    console.info("case CODE_MK_DIR start")
144                    let path = data.readString()
145                    console.info("The server's readString result is " + path);
146                    let checkResult = checkDirExists(path);
147                    let result;
148                    if (checkResult == true) {
149                        result = reply.writeString("SUCCESS");
150                    } else {
151                        result = reply.writeString("Server side dir synchronization creation failed.");
152                    }
153
154                    console.info("The server's writeString result is " + result);
155                    return true;
156                }
157                case CODE_RM_DIR:
158                {
159                    console.info("case CODE_RM_DIR start");
160                    let path = data.readString();
161                    console.info("The server's readString result is " + path);
162                    let result;
163                    try {
164                        let dir = fileio.openDirSync(path);
165                        result = reply.writeString("Server side dir synchronization creation failed!");
166                        dir.closeSync();
167                    } catch (error) {
168                        result = reply.writeString("SUCCESS");
169                    }
170
171                    console.info("The server's writeString result is " + result);
172                    return true;
173                }
174                case CODE_CREATE_FILE:
175                {
176                    console.info("case CODE_CREATE_FILE start");
177                    let path = data.readString();
178                    console.info("The server's readString result is " + path);
179
180                    let checkResult = checkFileExists(path);
181                    let result;
182                    if (checkResult == true) {
183                        result = reply.writeString("SUCCESS");
184                    } else {
185                        result = reply.writeString("Server side file synchronization creation failed!");
186                    }
187
188                    console.info("The server's writeString result is " + result);
189                    return true;
190                }
191                case CODE_DELETE_FILE:
192                {
193                    console.info("case CODE_DELETE_FILE start");
194                    let path = data.readString();
195                    console.info("The server's readString result is " + path);
196                    let result;
197                    try {
198                        let fd = fileio.openSync(path);
199                        result = reply.writeString("Server side file synchronization creation failed!");
200                        fileio.closeSync(fd);
201                    } catch (error) {
202                        result = reply.writeString("SUCCESS");
203                    }
204
205                    console.info("The server's writeString result is " + result);
206                    return true;
207                }
208                case CODE_GET_FILE_CONTENT:
209                {
210                    console.info("case CODE_GET_FILE_CONTENT start");
211                    let path = data.readString();
212                    console.info("The server's readString result is " + path);
213                    checkFileExists(path);
214                    let content ="";
215                    try {
216                        console.info("---------------- start get file content:" + path);
217                        content = getFileContent(path);
218                        console.info("-------------- dest file content :" + content);
219                    } catch (e) {
220                        console.info("-------------- read dest file content failed." + e);
221                    }
222
223                    let result = reply.writeString(content);
224                    console.info("The server's writeString result is " + result);
225                    return true;
226                }
227                case CODE_GET_FILE_STAT:
228                {
229                    console.info("case CODE_GET_FILE_STAT start");
230                    let path = data.readString();
231                    console.info("The server's readString result is " + path);
232                    let localStat = fileio.statSync(path);
233                    let localStatInfo = "localStat.size = " + localStat.size + ",localStat.mode = " + localStat.mode;
234                    let result = reply.writeString(localStatInfo);
235                    console.info("The server's writeString result is " + result);
236                    return true;
237                }
238                case CODE_FSYNC_FILE:
239                {
240                    console.info("case CODE_FSYNC_FILE start");
241                    let path = data.readString();
242                    console.info("The server's readString result is " + path);
243                    let result;
244                    try{
245                        let fd = fileio.openSync(path, 0o2);
246                        fileio.fsyncSync(fd);
247                        console.info("sync data succeed");
248                        result = reply.writeString("SUCCESS");
249                    } catch (e) {
250                        console.info("sync data failed with error:" + e);
251                        result = reply.writeString("FAILED");
252                    }
253                    console.info("The server's writeString result is " + result);
254                    return true;
255                }
256                default:
257                    console.error("default case " + code);
258                    return super.onRemoteMessageRequest(code, data, reply, option);
259            }
260        } catch (error) {
261            console.info("onRemoteMessageRequest: " + error);
262        }
263        return false
264    }
265}