Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package px.ks1702;
- import android.annotation.SuppressLint;
- import android.app.Activity;
- import android.app.ActivityManager;
- import android.app.admin.DevicePolicyManager;
- import android.app.admin.SystemUpdatePolicy;
- import android.content.BroadcastReceiver;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.content.SharedPreferences;
- import android.content.pm.ActivityInfo;
- import android.content.pm.PackageManager;
- import android.graphics.PixelFormat;
- import android.net.Uri;
- import android.os.AsyncTask;
- import android.os.BatteryManager;
- import android.os.UserManager;
- import android.provider.Settings;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.WindowManager;
- import android.webkit.WebChromeClient;
- import android.webkit.WebSettings;
- import android.webkit.WebView;
- import android.webkit.WebViewClient;
- import android.widget.Button;
- import android.widget.FrameLayout;
- import android.widget.MediaController;
- import android.widget.TextView;
- import android.widget.Toast;
- import android.widget.VideoView;
- import com.google.firebase.iid.FirebaseInstanceId;
- import com.google.firebase.messaging.FirebaseMessaging;
- import com.google.firebase.messaging.RemoteMessage;
- import org.apache.commons.net.ftp.FTPClient;
- import org.w3c.dom.Text;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.NetworkInterface;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Random;
- import java.util.Timer;
- import java.util.TimerTask;
- public class MainActivity extends Activity {
- private static final String LOG_TAG = "MainActivity";
- private WebView mWebView;
- private TextView databaseTextView;
- private Button unlockButton;
- //Lockdown
- private DevicePolicyManager mDevicePolicyManager;
- private PackageManager mPackageManager;
- private ComponentName mAdminComponentName;
- // listens for when FTP settings are initialised
- private BroadcastReceiver ftpSettingsReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- TextView textview = (TextView) findViewById(R.id.database_textview);
- Bundle bundle = intent.getBundleExtra("msg");
- // Log.e(LOG_TAG, mWebView.getUrl());
- if (mWebView.getUrl().equals("file:///android_asset/www/loading.html"))
- {
- textview.setText("Database ID: " + bundle.getString("databaseId"));
- saveConfig();
- }
- }
- };
- // listens for when the screen orientation is updated and display it on the screen
- private BroadcastReceiver screenOrientationReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- saveConfig();
- setScreenOrientation();
- }
- };
- // listens for when the screen orientation is updated and display it on the screen
- private BroadcastReceiver lockdownReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- Bundle bundle = intent.getBundleExtra("msg");
- String lockdown = bundle.getString("lockdown");
- if (lockdown.equals("yes")) {
- Log.d(LOG_TAG, "Lockdown message recieved, initiating");
- // setupLockdown();
- // startLockdown();
- }
- else if (lockdown.equals("no")) {
- Log.d(LOG_TAG, "Removing lockdown");
- // stopLockdown();
- }
- }
- };
- // listens for when the client and screen ID is updated
- private BroadcastReceiver clientAndScreenIdReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- saveConfig();
- // determine if there is a internet connection
- // if there is a connection start downloading files.
- TextView textview = (TextView) findViewById(R.id.database_textview);
- // Append a -R to text_view to signal that the application has RECIEVED
- // a message to change its client and screen id
- if (! textview.getText().equals("") )
- {
- textview.setText(textview.getText() + "-R");
- }
- // TODO Need to put check for update command here. So that when the IDs change they automatically refresh
- // TODO Uncomment to work with Admin Page and Firebase
- DetermineConnection();
- }
- };
- // listens for when reload screen is called
- private BroadcastReceiver reloadScreenReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- mWebView.reload();
- }
- };
- // listens for when force update is called
- private BroadcastReceiver forceUpdateReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- Bundle bundle = intent.getBundleExtra("msg");
- FtpDownloader FTP = new FtpDownloader(context, mWebView, databaseTextView);
- if (bundle.getString("delete").equals("yes"))
- {
- Log.d(LOG_TAG, "Deleting..." + Util.CLIENT_ID);
- FTP.Delete(Util.CLIENT_ID);
- }
- Log.d(LOG_TAG, "Updating...");
- FTP.execute(Util.FTP_SERVER, Util.FTP_USERNAME, Util.FTP_PASSWORD, Util.CLIENT_ID + "/" + Util.SCREEN_ID);
- }
- };
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // load global config settings (load global variables into Util.java)
- loadConfig();
- // initialise the message listeners
- initaliseReceivers();
- // TODO uncomment for lockdown
- //initialise Lockdown
- //setupLockdown();
- //startLockdown();
- // textview for displaying the database ID
- databaseTextView = (TextView) findViewById(R.id.database_textview);
- databaseTextView.bringToFront();
- databaseTextView.setText(Util.DATABASE_ID);
- //hidden unlock button
- unlockButton = (Button) findViewById(R.id.button2);
- unlockButton.bringToFront();
- unlockButton.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- // TODO uncomment for lockdown
- //stopLockdown();
- //startLockdown();
- }
- });
- // setup webview
- mWebView = (WebView) findViewById(R.id.activity_main_webview);
- // Force links and redirects to open in the WebView instead of in a browser
- mWebView.setWebChromeClient(new WebChromeClient());
- mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
- mWebView.getSettings().setLoadWithOverviewMode(true);
- mWebView.getSettings().setUseWideViewPort(true);
- mWebView.getSettings().setJavaScriptEnabled(true);
- mWebView.getSettings().setAllowFileAccess(true);
- mWebView.getSettings().setAllowContentAccess(true);
- // mWebView.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
- // String url = new String("http://broken-links.com/tests/video/");
- //// mWebView.setWebChromeClient(new MyWebChromeClient(this));
- //// mWebView.setWebViewClient(new WebViewClient());
- // mWebView.setWebViewClient(n);
- // mWebView.getSettings().setJavaScriptEnabled(true);
- // mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
- // mWebView.loadUrl(url);
- // mWebView = (WebView) findViewById(R.id.activity_main_webview);
- // mWebView.getSettings().setJavaScriptEnabled(true);
- // mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
- // mWebView.getSettings().setSupportMultipleWindows(true);
- // mWebView.getSettings().setSaveFormData(false);
- // mWebView.getSettings().setSavePassword(false);
- // mWebView.getSettings().setDomStorageEnabled(true);
- //
- // mWebView.getSettings().setAllowFileAccess(true);
- // mWebView.getSettings().setLightTouchEnabled(true);
- // mWebView.getSettings().setJavaScriptEnabled(true);
- // mWebView.getSettings().setBuiltInZoomControls(true);
- // mWebView.getSettings().setUseWideViewPort(true);
- // mWebView.getSettings().setLoadWithOverviewMode(true);
- // getWindow().setFormat(PixelFormat.TRANSLUCENT);
- // VideoView videoHolder = new VideoView(this);
- // //if you want the controls to appear
- // videoHolder.setMediaController(new MediaController(this));
- //// Uri video = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.small); //do not add any extension
- //// videoHolder.setVideoURI(video);
- // videoHolder.setVideoPath("/data/user/0/px.ks1702/files/10001/screen5/content/videos/fbc0f56c611508725420.webm");
- // setContentView(videoHolder);
- // videoHolder.start();
- // create token and register to database
- // TODO change this so it only calls once. So it doesn't flood the server and network
- CreateToken();
- sendIpAddress();
- String indexFileLocation = "/data/user/0/px.ks1702/files/" + Util.CLIENT_ID + "/" + Util.SCREEN_ID + "/" + Util.INDEX_FILE_NAME;
- File index = new File(indexFileLocation);
- Log.d(LOG_TAG, "Checking: " + indexFileLocation);
- // check if there is already a local index1.hmtl file
- // if (index.exists()) {
- // // index exists
- // mWebView.loadUrl("file://" + index);
- // // so you can't see database id anymore
- // databaseTextView.setText("");
- // }
- // else {
- // // index doesn't exist
- // Log.d(LOG_TAG, "Can't find a local index file");
- // mWebView.loadUrl("file:///android_asset/www/loading.html");
- //
- // }
- mWebView.loadUrl("file:///data/user/0/px.ks1702/files/10001/screen5/content/videos/fbc0f56c611508725420.webm");
- // String summary = "<html><body><video controls autoplay src='file:///data/user/0/px.ks1702/files/10001/screen5/content/videos/fbc0f56c611508725420.webm'></video></body></html>";
- // String summary = "<html><body><input type='file' accept='video/*'/> <video controls autoplay></video></body></html>";
- // mWebView.loadData(summary, "text/html", null);
- // mWebView.loadUrl("http://broken-links.com/tests/video/");
- // mWebView.loadUrl("http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm");
- // mWebView.loadUrl("file:///data/user/0/px.ks1702/files/10001/screen5/content/videos/fbc0f56c611508725420.webm");
- // mWebView.loadData("file:///data/user/0/px.ks1702/files/10001/screen5/content/videos/fbc0f56c611508725420.webm", "text/html", "utf-8");
- // mWebView.loadDataWithBaseURL(mStory.getUrl(), mStory.getUnparsedContent(),
- // "text/html; charset=utf-8", "UTF-8", null);
- Timer T = new Timer();
- T.schedule(new TimerTask()
- {
- @Override
- public void run()
- {
- DownloadContent(Util.CLIENT_ID + "/" + Util.SCREEN_ID);
- }
- }, (30 * 60000), (30 * 60000));
- }
- /*
- * Create Firebase Token and upload it to the database
- */
- public void CreateToken() {
- String token = FirebaseInstanceId.getInstance().getToken();
- // Log and toast
- Log.d(LOG_TAG, "Creating token...");
- Log.d(LOG_TAG, "InstanceID Token: " + token);
- // regisister token in database
- MyFirebaseMessagingService service = new MyFirebaseMessagingService();
- // service.sendFtpSync("insert_ftp_sync_date_here", "insert_ftp_sync_update_date_here");
- DeviceDetails device = new DeviceDetails();
- String mac = device.getMacAddress();
- Map<String, String> message = new HashMap<String, String>();
- message.put("token", token);
- message.put("mac", mac);
- message.put("command", "addToken");
- service.sendMessage(message);
- }
- /*
- * Send the devices IP address to the database
- */
- public void sendIpAddress() {
- MyFirebaseMessagingService service = new MyFirebaseMessagingService();
- DeviceDetails device = new DeviceDetails();
- String mac = device.getMacAddress();
- Map<String, String> message = new HashMap<String, String>();
- String ip = device.getIpAddress();
- message.put("ipAddress", ip);
- message.put("mac", mac);
- message.put("command", "addIpAddress");
- service.sendMessage(message);
- }
- /*
- * Determine if there is an internet connection
- */
- public void DetermineConnection() {
- Log.d(LOG_TAG, "Determining connection");
- // manually determine if connected to internet on start up
- NetworkStatus determineConnection = new NetworkStatus(this, new NetworkStatusInterface() {
- @Override
- public void hasActiveInternetConnection(boolean result) {
- Log.d(LOG_TAG, "Result of internet connection: " + result);
- if (result == true) {
- // connected successfully
- TextView textview = (TextView)findViewById(R.id.database_textview);
- // Append -D to signal DOWNLOADING has begun
- if ( !textview.getText().equals("") ) {
- textview.setText(textview.getText() + "-D");
- }
- DownloadContent(Util.CLIENT_ID + "/" + Util.SCREEN_ID);
- // DownloadContent("client1/screen1");
- } else {
- // connection failed
- mWebView.loadUrl("file:///android_asset/www/loading.html");
- databaseTextView.setText("Database ID: " + Util.DATABASE_ID);
- }
- }
- });
- // attempt to connect to the internet
- determineConnection.execute();
- }
- /*
- * Download content for the FTP server
- */
- private void DownloadContent(String folderPath)
- {
- // load config settings
- // PropertiesHandler config = new PropertiesHandler();
- //
- // String server = config.getConfigValue(this, "ftp_server");
- // String username = config.getConfigValue(this, "ftp_username");
- // String password = config.getConfigValue(this, "ftp_password");
- String server = Util.FTP_SERVER;
- String username = Util.FTP_USERNAME;
- String password = Util.FTP_PASSWORD;
- Log.d(LOG_TAG, server + " " + username + " " + password);
- FtpDownloader test = new FtpDownloader(this, mWebView, databaseTextView);
- test.execute(server, username, password, folderPath);
- }
- private void loadConfig() {
- // Restore preferences
- SharedPreferences settings = getPreferences(0);
- // Get the property values
- // If it can't find the value. Set the string to the second parameter
- Util.FTP_SERVER = settings.getString("ftp_server", Util.FTP_SERVER);
- Util.FTP_USERNAME = settings.getString("ftp_username", Util.FTP_USERNAME);
- Util.FTP_PASSWORD = settings.getString("ftp_password", Util.FTP_PASSWORD);
- Util.CLIENT_ID = settings.getString("client_id", Util.CLIENT_ID);
- Util.SCREEN_ID = settings.getString("screen_id", Util.SCREEN_ID);
- Util.DATABASE_ID = settings.getString("database_id", Util.DATABASE_ID);
- Util.SENDER_ID = settings.getString("sender_id", Util.SENDER_ID);
- Util.INDEX_FILE_NAME = settings.getString("index_file_name", Util.INDEX_FILE_NAME);
- Util.SCREEN_ORIENTATION = settings.getString("screen_orientation", Util.SCREEN_ORIENTATION);
- setScreenOrientation();
- Log.d(LOG_TAG, "Configuration loaded!");
- Util.printValues();
- }
- // save global variables
- private void saveConfig() {
- SharedPreferences settings = getPreferences(0);
- SharedPreferences.Editor editor = settings.edit();
- editor.putString("ftp_server", Util.FTP_SERVER);
- editor.putString("ftp_username", Util.FTP_USERNAME);
- editor.putString("ftp_password", Util.FTP_PASSWORD);
- editor.putString("client_id", Util.CLIENT_ID);
- editor.putString("screen_id", Util.SCREEN_ID);
- editor.putString("database_id", Util.DATABASE_ID);
- editor.putString("sender_id", Util.SENDER_ID);
- editor.putString("index_file_name", Util.INDEX_FILE_NAME);
- editor.putString("screen_orientation", Util.SCREEN_ORIENTATION);
- // Commit the edits!
- editor.commit();
- Log.d(LOG_TAG, "Configuration saved!");
- }
- private void initaliseReceivers() {
- // initialise the database ID update listener
- if (ftpSettingsReceiver != null) {
- IntentFilter intentFilter = new IntentFilter("updateDatabaseId");
- registerReceiver(ftpSettingsReceiver, intentFilter);
- }
- // initialise the database ID update listener
- if (screenOrientationReceiver != null) {
- IntentFilter intentFilter = new IntentFilter("updateScreenRotation");
- registerReceiver(screenOrientationReceiver, intentFilter);
- }
- // initialise the client and screen id update listener
- if (clientAndScreenIdReceiver != null) {
- IntentFilter intentFilter = new IntentFilter("updateClientAndScreenId");
- registerReceiver(clientAndScreenIdReceiver, intentFilter);
- }
- if (reloadScreenReceiver != null) {
- IntentFilter intentFilter = new IntentFilter("reloadScreen");
- registerReceiver(reloadScreenReceiver, intentFilter);
- }
- if (forceUpdateReceiver != null) {
- IntentFilter intentFilter = new IntentFilter("forceUpdate");
- registerReceiver(forceUpdateReceiver, intentFilter);
- }
- if (lockdownReceiver != null) {
- IntentFilter intentFilter = new IntentFilter("handleLockdown");
- registerReceiver(lockdownReceiver, intentFilter);
- }
- }
- private void setScreenOrientation() {
- if (Util.SCREEN_ORIENTATION.equals("landscape")) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
- } else if (Util.SCREEN_ORIENTATION.equals("portrait")) {
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- } else if (Util.SCREEN_ORIENTATION.equals("reverseLandscape")) {
- Log.d(LOG_TAG, "Reverse landscape recieved");
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- } else if (Util.SCREEN_ORIENTATION.equals("reversePortrait")) {
- Log.d(LOG_TAG, "Reverse portrait recieved");
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- }
- }
- //So the contents of the webview does not disappear on rotation of device
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- mWebView.saveState(outState);
- }
- //So the contents of the webview does not disappear on rotation of device
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- mWebView.restoreState(savedInstanceState);
- }
- // TODO uncomment for lockdown
- /*
- void setupLockdown() {
- mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
- mAdminComponentName = DeviceAdminReceiver.getComponentName(this);
- mPackageManager = this.getPackageManager();
- //stopLockdown();
- }
- void stopLockdown() {
- ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
- if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED) {
- stopLockTask();
- setDefaultCosuPolicies(false);
- }
- }
- void startLockdown() {
- if(mDevicePolicyManager.isDeviceOwnerApp(getPackageName())){
- setDefaultCosuPolicies(true);
- }
- else {
- Log.d(LOG_TAG, "Not Device Owner. To set device owner factory reset then run adb shell dpm set-device-owner px.ks1702/.DeviceAdminReceiver ");
- }
- if(mDevicePolicyManager.isLockTaskPermitted(getPackageName())){
- ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
- if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_NONE) {
- startLockTask();
- }
- }
- }
- private void setDefaultCosuPolicies(boolean active){
- // Set user restrictions
- setUserRestriction(UserManager.DISALLOW_SAFE_BOOT, active);
- setUserRestriction(UserManager.DISALLOW_FACTORY_RESET, active);
- setUserRestriction(UserManager.DISALLOW_ADD_USER, active);
- setUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, active);
- setUserRestriction(UserManager.DISALLOW_ADJUST_VOLUME, active);
- //setUserRestriction(UserManager.DISALLOW_APPS_CONTROL, active);
- //setUserRestriction(UserManager.DISALLOW_NETWORK_RESET, active);
- // Disable keyguard and status bar
- mDevicePolicyManager.setKeyguardDisabled(mAdminComponentName, active);
- mDevicePolicyManager.setStatusBarDisabled(mAdminComponentName, active);
- // Enable STAY_ON_WHILE_PLUGGED_IN
- enableStayOnWhilePluggedIn(active);
- // Set system update policy
- if (active){
- mDevicePolicyManager.setSystemUpdatePolicy(mAdminComponentName,
- SystemUpdatePolicy.createWindowedInstallPolicy(60, 120));
- } else {
- mDevicePolicyManager.setSystemUpdatePolicy(mAdminComponentName,
- null);
- }
- // set this Activity as a lock task package
- mDevicePolicyManager.setLockTaskPackages(mAdminComponentName,
- active ? new String[]{getPackageName()} : new String[]{});
- IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MAIN);
- intentFilter.addCategory(Intent.CATEGORY_HOME);
- intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
- if (active) {
- // set Cosu activity as home intent receiver so that it is started
- // on reboot
- mDevicePolicyManager.addPersistentPreferredActivity(
- mAdminComponentName, intentFilter, new ComponentName(
- getPackageName(), MainActivity.class.getName()));
- } else {
- mDevicePolicyManager.clearPackagePersistentPreferredActivities(
- mAdminComponentName, getPackageName());
- }
- }
- private void setUserRestriction(String restriction, boolean disallow){
- if (disallow) {
- mDevicePolicyManager.addUserRestriction(mAdminComponentName, restriction);
- } else {
- mDevicePolicyManager.clearUserRestriction(mAdminComponentName, restriction);
- }
- }
- private void enableStayOnWhilePluggedIn(boolean enabled){
- if (enabled) {
- mDevicePolicyManager.setGlobalSetting(
- mAdminComponentName, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
- Integer.toString(BatteryManager.BATTERY_PLUGGED_AC
- | BatteryManager.BATTERY_PLUGGED_USB
- | BatteryManager.BATTERY_PLUGGED_WIRELESS));
- } else {
- mDevicePolicyManager.setGlobalSetting(mAdminComponentName,
- Settings.Global.STAY_ON_WHILE_PLUGGED_IN, "0");
- }
- }
- */
- // Load config settings on device start up
- @Override
- protected void onStart() {
- super.onStart();
- Log.d(LOG_TAG, "onStart Called");
- loadConfig();
- // TODO uncomment for lockdown
- //startLockdown();
- // PropertiesHandler prop = new PropertiesHandler();
- // prop.readProperities();
- // prop.loadProperities();
- }
- // Load config settings on device resume
- @Override
- protected void onResume() {
- super.onResume();
- Log.d(LOG_TAG, "onResume Called");
- loadConfig();
- // TODO uncomment for lockdown
- //startLockdown();
- }
- // save config settings on device pause
- @Override
- protected void onPause() {
- super.onPause();
- Log.d(LOG_TAG, "onPause Called");
- saveConfig();
- }
- // save config settings on device stop
- @Override
- protected void onStop() {
- super.onStop(); // Always call the superclass method first
- Log.d(LOG_TAG, "OnStop Called");
- //
- // PropertiesHandler prop = new PropertiesHandler();
- // prop.saveProperties();
- saveConfig();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement