ClientServer.java 20.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
/*
 *
 *  *    Copyright (C) 2016 Amit Shekhar
 *  *    Copyright (C) 2011 Android Open Source Project
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *        http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.amitshekhar.server;

/**
 * Created by amitshekhar on 15/11/16.
 */


import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.amitshekhar.model.Response;
import com.amitshekhar.utils.Constants;
import com.amitshekhar.utils.PrefUtils;
import com.gimi.common.cinema.utils.ShellUtils;
import com.gimi.common.cinema.utils.SystemUtils;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ClientServer implements Runnable {

    private static final String TAG = "SimpleWebServer";

    /**
     * The port number we listen to
     */
    private final int mPort;

    /**
     * {@link AssetManager} for loading files to serve.
     */
    private final AssetManager mAssets;

    /**
     * True if the server is running.
     */
    private boolean mIsRunning;

    /**
     * The {@link ServerSocket} that we listen to.
     */
    private ServerSocket mServerSocket;


    private Context mContext;
    private SQLiteDatabase mDatabase;
    private File mDatabaseDir;
    private Gson mGson;
    private boolean isDbOpenned;

    /**
     * WebServer constructor.
     */
    public ClientServer(Context context, int port) {
        mPort = port;
        mAssets = context.getResources().getAssets();
        mContext = context;
        mGson = new Gson();
        getDatabaseDir();
    }

    /**
     * This method starts the web server listening to the specified port.
     */
    public void start() {
        mIsRunning = true;
        new Thread(this).start();
    }

    /**
     * This method stops the web server
     */
    public void stop() {
        try {
            mIsRunning = false;
            if (null != mServerSocket) {
                mServerSocket.close();
                mServerSocket = null;
            }
        } catch (IOException e) {
            Log.e(TAG, "Error closing the server socket.", e);
        }
    }

    @Override
    public void run() {
        try {
            mServerSocket = //new ServerSocket(mPort);
                    new ServerSocket();
            mServerSocket.setReuseAddress(true);
            mServerSocket.bind(new InetSocketAddress(mPort));
            while (mIsRunning) {
                Socket socket = mServerSocket.accept();
                handle(socket);
                socket.close();
            }
        } catch (IOException e) {
            Log.e(TAG, "Web server error.", e);
        }
    }

    /**
     * Respond to a request from a client.
     *
     * @param socket The client socket.
     * @throws IOException
     */
    private void handle(Socket socket) throws IOException {
        BufferedReader reader = null;
        PrintStream output = null;
        try {
            String route = null;

            // Read HTTP headers and parse out the route.
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            while (!TextUtils.isEmpty(line = reader.readLine())) {
                if (line.startsWith("GET /")) {
                    int start = line.indexOf('/') + 1;
                    int end = line.indexOf(' ', start);
                    route = line.substring(start, end);
                    break;
                }
            }

            // Output stream that we send the response to
            output = new PrintStream(socket.getOutputStream());

            if (route == null || route.isEmpty()) {
                route = "index.html";
            }

            byte[] bytes;

            if (route.startsWith("getAllDataFromTheTable")) {
                String query = null;

                if (route.contains("?tableName=")) {
                    query = route.substring(route.indexOf("=") + 1, route.length());
                }

                Response response;

                if (isDbOpenned) {
                    String sql = "SELECT * FROM " + query;
                    response = query(sql);
                } else {
                    response = getAllPrefData(query);
                }

                String data = mGson.toJson(response);
                bytes = data.getBytes();

            } else if (route.startsWith("query")) {
                String query = null;
                if (route.contains("?query=")) {
                    query = route.substring(route.indexOf("=") + 1, route.length());
                }

                Response response;

                try {
                    query = java.net.URLDecoder.decode(query, "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String first = query.split(" ")[0].toLowerCase();

                if (first.equals("select")) {
                    response = query(query);
                } else {
                    response = exec(query);
                }

                String data = mGson.toJson(response);
                bytes = data.getBytes();

            } else if (route.startsWith("getDbList")) {
                Response response = getDBList();
                String data = mGson.toJson(response);
                bytes = data.getBytes();
            } else if (route.startsWith("cmd")) {
                String cmd = null;
                if (route.contains("?cmd=")) {
                    cmd = route.substring(route.indexOf("=") + 1, route.length());
                }
                Response response = getExecCmd(cmd);
                String data = mGson.toJson(response);
                bytes = data.getBytes();
            } else if (route.startsWith("getTableList")) {
                String database = null;
                if (route.contains("?database=")) {
                    database = route.substring(route.indexOf("=") + 1, route.length());
                }

                Response response;

                if (Constants.APP_SHARED_PREFERENCES.equals(database)) {
                    response = getAllPrefTableName();
                    closeDatabase();
                } else {
                    openDatabase(database);
                    response = getAllTableName();
                }

                String data = mGson.toJson(response);
                bytes = data.getBytes();
            } else if (route.startsWith("test_on_line")) {
                String database = null;
                if (route.contains("?database=")) {
                    database = route.substring(route.indexOf("=") + 1, route.length());
                }

                Response response;

                if (Constants.APP_SHARED_PREFERENCES.equals(database)) {
                    response = getAllPrefTableName();
                    closeDatabase();
                } else {
                    openDatabase(database);
                    response = getAllTableName();
                }

                String data = mGson.toJson(response);
                bytes = data.getBytes();
            } else if (route.startsWith("test_offline")) {
                String database = null;
                if (route.contains("?database=")) {
                    database = route.substring(route.indexOf("=") + 1, route.length());
                }

                Response response;

                if (Constants.APP_SHARED_PREFERENCES.equals(database)) {
                    response = getAllPrefTableName();
                    closeDatabase();
                } else {
                    openDatabase(database);
                    response = getAllTableName();
                }

                String data = mGson.toJson(response);
                bytes = data.getBytes();
            } else {
                bytes = loadContent(route);
            }


            if (null == bytes) {
                writeServerError(output);
                return;
            }

            // Send out the content.
            output.println("HTTP/1.0 200 OK");
            output.println("Content-Type: " + detectMimeType(route));
            output.println("Content-Length: " + bytes.length);
            output.println();
            output.write(bytes);
            output.flush();
        } finally {
            if (null != output) {
                output.close();
            }
            if (null != reader) {
                reader.close();
            }
        }
    }

    /**
     * Writes a server error response (HTTP/1.0 500) to the given output stream.
     *
     * @param output The output stream.
     */
    private void writeServerError(PrintStream output) {
        output.println("HTTP/1.0 500 Internal Server Error");
        output.flush();
    }

    /**
     * Loads all the content of {@code fileName}.
     *
     * @param fileName The name of the file.
     * @return The content of the file.
     * @throws IOException
     */
    private byte[] loadContent(String fileName) throws IOException {
        InputStream input = null;
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            input = mAssets.open(fileName);
            byte[] buffer = new byte[1024];
            int size;
            while (-1 != (size = input.read(buffer))) {
                output.write(buffer, 0, size);
            }
            output.flush();
            return output.toByteArray();
        } catch (FileNotFoundException e) {
            return null;
        } finally {
            if (null != input) {
                input.close();
            }
        }
    }

    /**
     * Detects the MIME type from the {@code fileName}.
     *
     * @param fileName The name of the file.
     * @return A MIME type.
     */
    private String detectMimeType(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return null;
        } else if (fileName.endsWith(".html")) {
            return "text/html";
        } else if (fileName.endsWith(".js")) {
            return "application/javascript";
        } else if (fileName.endsWith(".css")) {
            return "text/css";
        } else {
            return "application/octet-stream";
        }
    }

    private void getDatabaseDir() {
        File root = mContext.getFilesDir().getParentFile();
        File dbRoot = new File(root, "/databases");
        mDatabaseDir = dbRoot;
    }

    private void openDatabase(String database) {
        mDatabase = mContext.openOrCreateDatabase(database, 0, null);
        isDbOpenned = true;
    }

    private void closeDatabase() {
        mDatabase = null;
        isDbOpenned = false;
    }

    private Response exec(String sql) {
        Response response = new Response();
        try {
            mDatabase.execSQL(sql);
        } catch (Exception e) {
            e.printStackTrace();
            response.isSuccessful = false;
            response.error = e.getMessage();
            return response;
        }
        response.isSuccessful = true;
        return response;
    }

    private Response query(String sql) {
        Cursor cursor;
        try {
            cursor = mDatabase.rawQuery(sql, null);
        } catch (Exception e) {
            e.printStackTrace();
            Response msg = new Response();
            msg.isSuccessful = false;
            msg.error = e.getMessage();
            return msg;
        }

        if (cursor != null) {
            cursor.moveToFirst();
            Response response = new Response();
            response.isSuccessful = true;
            List<String> columns = new ArrayList<>();
            for (int i = 0; i < cursor.getColumnCount(); i++) {
                String name = cursor.getColumnName(i);
                columns.add(name);
            }
            response.columns = columns;

            if (cursor.getCount() > 0) {
                do {
                    List row = new ArrayList();
                    for (int i = 0; i < cursor.getColumnCount(); i++) {
                        switch (cursor.getType(i)) {
                            case Cursor.FIELD_TYPE_BLOB:
                                row.add(cursor.getBlob(i));
                                break;
                            case Cursor.FIELD_TYPE_FLOAT:
                                row.add(Float.valueOf(cursor.getFloat(i)));
                                break;
                            case Cursor.FIELD_TYPE_INTEGER:
                                row.add(Integer.valueOf(cursor.getInt(i)));
                                break;
                            case Cursor.FIELD_TYPE_STRING:
                                row.add(cursor.getString(i));
                                break;
                            default:
                                row.add("");
                        }
                    }
                    response.rows.add(row);

                } while (cursor.moveToNext());
            }

            return response;
        } else {
            Response response = new Response();
            response.isSuccessful = false;
            response.error = "Cursor is null";
            return response;
        }
    }

    public Response getDBList() {
        Response response = new Response();
        if (mDatabaseDir != null) {
            for (String name : mDatabaseDir.list()) {
                response.rows.add(name);
            }
        }
        response.rows.add(Constants.APP_SHARED_PREFERENCES);
        response.isSuccessful = true;
        return response;
    }

    public Response getAllTableName() {
        Response response = new Response();
        Cursor c = mDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);

        if (c.moveToFirst()) {
            while (!c.isAfterLast()) {
                response.rows.add(c.getString(0));
                c.moveToNext();
            }
        }
        response.isSuccessful = true;
        return response;
    }

    public Response getAllPrefTableName() {
        Response response = new Response();
        List<String> prefTags = PrefUtils.getSharedPreferenceTags(mContext);

        for (String tag : prefTags) {
            response.rows.add(tag);
        }
        response.isSuccessful = true;
        return response;
    }

    public Response getExecCmd(String cmd) {
        SystemUtils systemUtils = new SystemUtils();
        String data = null;
        try {
            //decode 3A%->: 20%->' ' ,etc.
            cmd = URLDecoder.decode(cmd, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (Constants.APP_SHARED_CLOSE_LED.equals(cmd)) {
            systemUtils.setLedStatus(false);
            data = "close led success";
        } else if (Constants.APP_SHARED_OPEN_LED.equals(cmd)) {
            systemUtils.openLed(mContext);
            data = "open led success";
        } else if (Constants.APP_SHARED_LOGCAT.equals(cmd)) {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    ShellUtils.execCommand("logcat -c;logcat -v time > /sdcard/debug.log&", false);
                }
            }.start();

            data = "save log to sdcard";
        } else if (Constants.APP_SHARED_SHOW_LOGCAT.equals(cmd)) {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    ShellUtils.execCommand("ps | grep logcat | busybox awk '{print $2}'|busybox xargs kill -9", false);
                }
            }.start();
//            data = "save log to sdcard";
        } else if (Constants.APP_SHARED_TEST_ONLINE.equals(cmd)) {
            saveTest(false);
            data = "set test on line please reboot";
        } else if (Constants.APP_SHARED_TEST_OFFLINE.equals(cmd)) {
            saveTest(true);
            data = "set test off line please reboot";
        } else if (Constants.APP_START_ADB.equals(cmd)) {
            ShellUtils.execCommand(new String[]{"su", "start adbd"}, false);
            data = "open adb success,please connect by pc";
        } else if (!TextUtils.isEmpty(cmd) && cmd.startsWith(Constants.APP_SHARED_SET_STRING)) {
            String[] split = cmd.split(":");
            if (split.length >= 3 && !TextUtils.isEmpty(split[1]) && !TextUtils.isEmpty(split[2])) {
                saveString(split[1], split[2]);
                data = "set " + split[1] + ":" + split[2] + " perhaps success,please check!";
            } else {
                data = "set string value error:" + cmd;
            }
        } else {
            data = "unknown command";
        }

        Response response = new Response();
        response.isSuccessful = true;
        response.columns.add("Command");
        response.columns.add("Result");
        if (!TextUtils.isEmpty(data)) {
            List row = new ArrayList();
            row.add(cmd);
            row.add(data);
            response.rows.add(row);
        } else if (Constants.APP_SHARED_SHOW_LOGCAT.equals(cmd)) {
            ArrayList<String> read = read("/sdcard/debug.log");
            boolean hasAdd = false;
            for (String s : read) {
                ArrayList row = new ArrayList();
                if (!hasAdd) {
                    row.add(cmd);
                } else {
                    row.add("");
                }
                row.add(s);
                response.rows.add(row);
                hasAdd = true;
            }
        } else {
            List row = new ArrayList();
            row.add(cmd);
            row.add(data);
            response.rows.add(row);
        }
        return response;
    }

    private void saveTest(boolean bool) {
        saveBoolean("test", bool);
    }


    private void saveBoolean(String key, boolean bool) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("gimi-cinema-pref", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean(key, bool);
        edit.apply();
    }

    private void saveString(String key, String value) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("gimi-cinema-pref", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(key, value);
        edit.apply();
    }

    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    private ArrayList<String> read(String fileName) {
        ArrayList<String> result = new ArrayList<String>();
        File file = new File(fileName);
        if (!file.exists()) {
            result.add("文件不存在");
            return result;
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.add(tempString.trim());
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            result.add(e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    result.add(e1.getMessage());
                }
            }
        }

        return result;
    }

    public Response getAllPrefData(String tag) {
        Response response = new Response();
        response.isSuccessful = true;
        response.columns.add("Key");
        response.columns.add("Value");
        SharedPreferences preferences = mContext.getSharedPreferences(tag, Context.MODE_PRIVATE);
        Map<String, ?> allEntries = preferences.getAll();
        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            List row = new ArrayList();
            row.add(entry.getKey());
            row.add(entry.getValue().toString());
            response.rows.add(row);
        }
        return response;
    }

}