1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. 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 distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 * KIND, either express or implied. See the License for the specific language governing
12 * permissions and limitations under the License.
13 */
14
15package com.android.settings;
16
17import android.app.Service;
18import android.content.Context;
19import android.content.Intent;
20import android.content.SharedPreferences;
21import android.content.pm.PackageManager;
22import android.content.pm.ResolveInfo;
23import android.net.ConnectivityManager;
24import android.net.NetworkTemplate;
25import android.net.Uri;
26import android.os.IBinder;
27import android.os.storage.StorageManager;
28import android.os.storage.VolumeInfo;
29import android.telephony.SubscriptionInfo;
30import android.telephony.SubscriptionManager;
31import android.telephony.TelephonyManager;
32
33import com.android.internal.annotations.VisibleForTesting;
34import com.android.settings.applications.ProcStatsData;
35import com.android.settings.fuelgauge.batterytip.AnomalyConfigJobService;
36import com.android.settingslib.net.DataUsageController;
37
38import org.json.JSONArray;
39import org.json.JSONException;
40import org.json.JSONObject;
41
42import java.io.File;
43import java.io.FileDescriptor;
44import java.io.PrintWriter;
45
46public class SettingsDumpService extends Service {
47    @VisibleForTesting
48    static final String KEY_SERVICE = "service";
49    @VisibleForTesting
50    static final String KEY_STORAGE = "storage";
51    @VisibleForTesting
52    static final String KEY_DATAUSAGE = "datausage";
53    @VisibleForTesting
54    static final String KEY_MEMORY = "memory";
55    @VisibleForTesting
56    static final String KEY_DEFAULT_BROWSER_APP = "default_browser_app";
57    @VisibleForTesting
58    static final String KEY_ANOMALY_DETECTION = "anomaly_detection";
59    @VisibleForTesting
60    static final Intent BROWSER_INTENT =
61            new Intent("android.intent.action.VIEW", Uri.parse("http://"));
62
63    @Override
64    public IBinder onBind(Intent intent) {
65        return null;
66    }
67
68    @Override
69    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
70        JSONObject dump = new JSONObject();
71
72        try {
73            dump.put(KEY_SERVICE, "Settings State");
74            dump.put(KEY_STORAGE, dumpStorage());
75            dump.put(KEY_DATAUSAGE, dumpDataUsage());
76            dump.put(KEY_MEMORY, dumpMemory());
77            dump.put(KEY_DEFAULT_BROWSER_APP, dumpDefaultBrowser());
78            dump.put(KEY_ANOMALY_DETECTION, dumpAnomalyDetection());
79        } catch (Exception e) {
80            e.printStackTrace();
81        }
82
83        writer.println(dump);
84    }
85
86    private JSONObject dumpMemory() throws JSONException {
87        JSONObject obj = new JSONObject();
88        ProcStatsData statsManager = new ProcStatsData(this, false);
89        statsManager.refreshStats(true);
90        ProcStatsData.MemInfo memInfo = statsManager.getMemInfo();
91
92        obj.put("used", String.valueOf(memInfo.realUsedRam));
93        obj.put("free", String.valueOf(memInfo.realFreeRam));
94        obj.put("total", String.valueOf(memInfo.realTotalRam));
95        obj.put("state", statsManager.getMemState());
96
97        return obj;
98    }
99
100    private JSONObject dumpDataUsage() throws JSONException {
101        JSONObject obj = new JSONObject();
102        DataUsageController controller = new DataUsageController(this);
103        ConnectivityManager connectivityManager = getSystemService(ConnectivityManager.class);
104        SubscriptionManager manager = SubscriptionManager.from(this);
105        TelephonyManager telephonyManager = TelephonyManager.from(this);
106        if (connectivityManager.isNetworkSupported(ConnectivityManager.TYPE_MOBILE)) {
107            JSONArray array = new JSONArray();
108            for (SubscriptionInfo info : manager.getAllSubscriptionInfoList()) {
109                NetworkTemplate mobileAll = NetworkTemplate.buildTemplateMobileAll(
110                        telephonyManager.getSubscriberId(info.getSubscriptionId()));
111                final JSONObject usage = dumpDataUsage(mobileAll, controller);
112                usage.put("subId", info.getSubscriptionId());
113                array.put(usage);
114            }
115            obj.put("cell", array);
116        }
117        if (connectivityManager.isNetworkSupported(ConnectivityManager.TYPE_WIFI)) {
118            obj.put("wifi", dumpDataUsage(NetworkTemplate.buildTemplateWifiWildcard(), controller));
119        }
120        if (connectivityManager.isNetworkSupported(ConnectivityManager.TYPE_ETHERNET)) {
121            obj.put("ethernet", dumpDataUsage(NetworkTemplate.buildTemplateEthernet(), controller));
122        }
123        return obj;
124    }
125
126    private JSONObject dumpDataUsage(NetworkTemplate template, DataUsageController controller)
127            throws JSONException {
128        JSONObject obj = new JSONObject();
129        DataUsageController.DataUsageInfo usage = controller.getDataUsageInfo(template);
130        obj.put("carrier", usage.carrier);
131        obj.put("start", usage.startDate);
132        obj.put("usage", usage.usageLevel);
133        obj.put("warning", usage.warningLevel);
134        obj.put("limit", usage.limitLevel);
135        return obj;
136    }
137
138    private JSONObject dumpStorage() throws JSONException {
139        JSONObject obj = new JSONObject();
140        StorageManager manager = getSystemService(StorageManager.class);
141        for (VolumeInfo volume : manager.getVolumes()) {
142            JSONObject volObj = new JSONObject();
143            if (volume.isMountedReadable()) {
144                File path = volume.getPath();
145                volObj.put("used", String.valueOf(path.getTotalSpace() - path.getFreeSpace()));
146                volObj.put("total", String.valueOf(path.getTotalSpace()));
147            }
148            volObj.put("path", volume.getInternalPath());
149            volObj.put("state", volume.getState());
150            volObj.put("stateDesc", volume.getStateDescription());
151            volObj.put("description", volume.getDescription());
152            obj.put(volume.getId(), volObj);
153        }
154        return obj;
155    }
156
157    @VisibleForTesting
158    String dumpDefaultBrowser() {
159        final ResolveInfo resolveInfo = getPackageManager().resolveActivity(
160                BROWSER_INTENT, PackageManager.MATCH_DEFAULT_ONLY);
161
162        if (resolveInfo == null || resolveInfo.activityInfo.packageName.equals("android")) {
163            return null;
164        } else {
165            return resolveInfo.activityInfo.packageName;
166        }
167    }
168
169    @VisibleForTesting
170    JSONObject dumpAnomalyDetection() throws JSONException {
171        final JSONObject obj = new JSONObject();
172        final SharedPreferences sharedPreferences = getSharedPreferences(
173                AnomalyConfigJobService.PREF_DB,
174                Context.MODE_PRIVATE);
175        final int currentVersion = sharedPreferences.getInt(
176                AnomalyConfigJobService.KEY_ANOMALY_CONFIG_VERSION,
177                0 /* defValue */);
178        obj.put("anomaly_config_version", String.valueOf(currentVersion));
179
180        return obj;
181    }
182}
183