1 // Copyright (C) 2023 Huawei Device Co., Ltd. 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 use std::collections::HashSet; 15 use std::mem::MaybeUninit; 16 use std::sync::atomic::Ordering; 17 use std::sync::{Mutex, Once}; 18 19 use super::account::{BACKGROUND_ACCOUNTS, FOREGROUND_ACCOUNT}; 20 use super::network::{NetworkInner, NetworkState}; 21 use super::task_manager::TaskManagerTx; 22 use crate::manage::network::Network; 23 24 pub(crate) struct NetworkManager { 25 pub(crate) network: Network, 26 pub(crate) tx: Option<TaskManagerTx>, 27 } 28 29 impl NetworkManager { get_instance() -> &'static Mutex<NetworkManager>30 pub(crate) fn get_instance() -> &'static Mutex<NetworkManager> { 31 static mut NETWORK_MANAGER: MaybeUninit<Mutex<NetworkManager>> = MaybeUninit::uninit(); 32 static ONCE: Once = Once::new(); 33 unsafe { 34 ONCE.call_once(|| { 35 let inner = NetworkInner::new(); 36 let network = Network { 37 inner, 38 _registry: None, 39 }; 40 let network_manager = NetworkManager { network, tx: None }; 41 NETWORK_MANAGER.write(Mutex::new(network_manager)); 42 }); 43 &*NETWORK_MANAGER.as_ptr() 44 } 45 } 46 is_online() -> bool47 pub(crate) fn is_online() -> bool { 48 let network_manager = NetworkManager::get_instance().lock().unwrap(); 49 matches!(network_manager.network.state(), NetworkState::Online(_)) 50 } 51 query_network() -> NetworkState52 pub(super) fn query_network() -> NetworkState { 53 let network_manager = NetworkManager::get_instance().lock().unwrap(); 54 network_manager.network.state() 55 } 56 query_active_accounts() -> (u64, HashSet<u64>)57 pub(super) fn query_active_accounts() -> (u64, HashSet<u64>) { 58 let mut active_accounts = HashSet::new(); 59 let foreground_account = FOREGROUND_ACCOUNT.load(Ordering::SeqCst) as u64; 60 active_accounts.insert(foreground_account); 61 if let Some(background_accounts) = BACKGROUND_ACCOUNTS.lock().unwrap().as_ref() { 62 for account in background_accounts.iter() { 63 active_accounts.insert(*account as u64); 64 } 65 } 66 (foreground_account, active_accounts) 67 } 68 } 69