1/*
2 * Copyright (c) 2021-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
16import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility';
17import rpc from "@ohos.rpc"
18import avSession from '@ohos.multimedia.avsession';
19import backgroundTaskManager from '@ohos.backgroundTaskManager';
20import wantAgent from '@ohos.wantAgent';
21
22function startContinuousTask() {
23    let wantAgentInfo = {
24        wants: [
25            {
26                bundleName: "com.example.myapplication",
27                abilityName: "com.example.myapplication.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(this.context,
38            backgroundTaskManager.BackgroundMode.MULTI_DEVICE_CONNECTION, wantAgentObj).then(() => {
39                console.info(`Operation startBackgroundRunning succeeded`);
40            }).catch((error) => {
41                console.error(`Operation startBackgroundRunning failed. code is ${error.code}, message is ${error.message}`);
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(this.context).then(() => {
52            console.info(`Operation stopBackgroundRunning success`);
53        }) .catch((error) => {
54            console.error(`Operation stopBackgroundRunning failed. code is ${error.code}, message is ${error.message}`);
55        })
56    } catch (error) {
57        console.error(`Operation stopBackgroundRunning failed. code is ${error.code}, message is ${error.message}`);
58    }
59
60}
61
62export default class ServiceAbility extends ServiceExtension {
63    onCreate(want) {
64        console.info('AVSessionServer: onStart');
65        startContinuousTask();
66        console.info('AVSessionServer: startContinuousTask');
67    }
68
69    onConnect(want) {
70        console.info('AVSessionServer: service onConnect called.')
71        return new Stub("rpcTestAbility")
72    }
73
74    onDisconnect(want) {
75        console.info('AVSessionServer: service onDisConnect called.')
76    }
77
78    onReconnect(want) {
79        console.info('AVSessionServer: service onReConnect called.')
80    }
81
82    onRequest(want, startId){
83        console.info('AVSessionServer: onCommand, want: ' + JSON.stringify(want) + ', startId: ' + startId)
84    }
85
86    onDestroy() {
87        console.info('AVSessionServer: onStop');
88        stopContinuousTask();
89        console.info('AVSessionServer: stopContinuousTask');
90    }
91};
92
93const CODE_CAST_AUDIO = 1;
94let descriptor;
95let controller;
96
97class Stub extends rpc.RemoteObject {
98    constructor(descriptor) {
99        super(descriptor);
100    }
101
102    async onRemoteMessageRequest(code, data, reply, option) {
103        try {
104            console.info(`AVSessionServer: onRemoteRequest: ${code}`);
105            switch (code) {
106                case CODE_CAST_AUDIO:
107                {
108                    console.info('AVSessionServer:case  CODE_CAST_AUDIO');
109                    await avSession.getAllSessionDescriptors().then((descriptors) => {
110                        console.info(`${descriptors.length}`);
111                        console.info('AVSessionServer: Get descriptors Successfully');
112                        if (descriptors.length === 0) {
113                            console.info('AVSessionServer: Get descriptors : Fail');
114                        }
115                        descriptor = descriptors[0];
116                    }).catch((err) => {
117                        console.info(`AVSessionServer: ${err.message}`);
118                        return false;
119                    });
120
121                    await avSession.createController(descriptor.sessionId).then((data) => {
122                        console.info('AVSessionServer: Create controller Successfully');
123                        controller = data;
124                    }).catch((err) => {
125                        console.info(`AVSessionServer: ${err.message}`);
126                        return false;
127                    });
128
129                    await controller.getAVMetadata().then((data) => {
130                        console.info(data.assetId);
131                        console.info(data.artist);
132                        console.info('AVSessionServer: Get Metadata');
133                        if (data.assetId === '121278' && data.artist === 'Eminem') {
134                            console.info(`AVSessionServer: Get Metadata is ${data}`);
135                            let writeResult = reply.writeString('case 1 get successfully');
136                            console.info(`AVSessionServer writeString result is ${writeResult}`);
137                            return true;
138                        }
139                    }).catch((err) => {
140                        console.info(`AVSessionServer: ${err.message}`);
141                        return false;
142                    });
143
144                }
145                default:
146                    console.error(`AVSessionServer: default case code is ${code}`);
147                    return super.onRemoteMessageRequest(code, data, reply, option);
148            }
149        } catch (error) {
150            console.info(`AVSessionServer: onRemoteRequest: ${error.message}`);
151        }
152        return false;
153    }
154}