io.tehtotalpwnage.musicphp_android.NavigationActivity.java Source code

Java tutorial

Introduction

Here is the source code for io.tehtotalpwnage.musicphp_android.NavigationActivity.java

Source

/*
 * Copyright 2017 Michael Nguyen
 *
 * This file is part of Music.php-Android.
 *
 * Music.php-Android is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Music.php-Android is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Music.php-Android.  If not, see <http://www.gnu.org/licenses/>.
 */

package io.tehtotalpwnage.musicphp_android;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.ActionBar;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NavigationActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, PlayerFragment.OnFragmentInteractionListener {
    private static final String TAG = NavigationActivity.class.getSimpleName();

    private MediaBrowserCompat mMediaBrowser;
    private NavigationView nav;
    private List<MediaSessionCompat.QueueItem> queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        nav = (NavigationView) findViewById(R.id.nav_view);
        nav.setNavigationItemSelectedListener(this);

        mMediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, MediaPlaybackService.class),
                mConnectionCallback, null);

        nav.getMenu().performIdentifierAction(R.id.nav_camera, 0);
        nav.setCheckedItem(R.id.nav_camera);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else if (getCheckedItem(nav) != 0) {
            Log.d(TAG, "MenuItem " + getCheckedItem(nav) + " was selected");
            nav.getMenu().performIdentifierAction(R.id.nav_camera, 0);
            nav.setCheckedItem(R.id.nav_camera);
        } else {
            Log.d(TAG, "Creating exit dialog");
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Quit");
            alert.setMessage("Are you sure you want to exit?");
            alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alert.show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.navigation, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Handle navigation view item clicks here.

        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Everything after this point is actually my code.
            StringRequest req = new StringRequest(Request.Method.GET, UrlGenerator.getServerUrl(this) + "/api/user",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            TextView view = new TextView(getApplicationContext());
                            view.setText(response);
                            FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                            layout.removeAllViews();
                            layout.addView(view);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.v(TAG, "Connection error");
                            TextView view = new TextView(getApplicationContext());
                            view.setText(getResources().getString(R.string.error_connection));
                            FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                            layout.removeAllViews();
                            layout.addView(view);
                            NetworkResponse networkResponse = error.networkResponse;
                            if (networkResponse != null
                                    && networkResponse.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                                Log.v(TAG, "Request was unauthorized, meaning that a new token is needed");
                                AccountManager manager = AccountManager.get(getApplicationContext());
                                manager.invalidateAuthToken(MusicPhpAccount.ACCOUNT_TYPE,
                                        getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                                Intent intent = new Intent(NavigationActivity.this, MainActivity.class);
                                startActivity(intent);
                            }
                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<>();
                    params.put("Accept", "application/json");
                    params.put("Authorization",
                            "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                    return params;
                }
            };
            VolleySingleton.getInstance(this).addToRequestQueue(req);
        } else if (id == R.id.nav_gallery) {
            final Context context = this;
            getListing(Item.albums, 0, new VolleyCallback() {
                @Override
                public void onSuccess(JSONArray result) {
                    Log.d(TAG, "Volley callback reached");
                    String albums[][] = new String[result.length()][3];
                    for (int i = 0; i < result.length(); i++) {
                        try {
                            JSONObject object = result.getJSONObject(i);
                            albums[i][0] = object.getString("name");
                            albums[i][1] = object.getJSONObject("artist").getString("name");
                            albums[i][2] = object.getString("id");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    AlbumListingAdapter adapter = new AlbumListingAdapter(context, albums,
                            getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                    GridView view = new GridView(context);
                    view.setLayoutParams(new DrawerLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    view.setNumColumns(GridView.AUTO_FIT);
                    view.setColumnWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 148,
                            getResources().getDisplayMetrics()));
                    view.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);
                    view.setAdapter(adapter);
                    view.setVerticalSpacing((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8,
                            getResources().getDisplayMetrics()));
                    FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                    layout.removeAllViews();
                    layout.addView(view);
                    Log.d(TAG, "Adapter setup complete");
                }
            });
        } else if (id == R.id.nav_slideshow) {
            getListing(Item.artists, 0, new VolleyCallback() {
                @Override
                public void onSuccess(JSONArray result) {

                }
            });
        } else if (id == R.id.nav_manage) {
            getListing(Item.tracks, 0, new VolleyCallback() {
                @Override
                public void onSuccess(JSONArray result) {
                }
            });
        } else if (id == R.id.nav_share) {
            Log.d(TAG, "Queue contains " + queue.size() + " items. Displaying queue...");
            ListView view = new ListView(this);
            view.setLayoutParams(new DrawerLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            String tracks[][] = new String[queue.size()][2];
            for (int i = 0; i < queue.size(); i++) {
                MediaSessionCompat.QueueItem queueItem = queue.get(i);
                tracks[i][0] = queueItem.getDescription().getMediaId();
                tracks[i][1] = (String) queueItem.getDescription().getTitle();
            }
            AlbumAdapter adapter = new AlbumAdapter(this, tracks,
                    getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN), this);
            view.setAdapter(adapter);
            view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //                    String sAddress = getApplicationContext().getSharedPreferences("Prefs", 0).getString("server", null);
                    //                    Bundle bundle = new Bundle();
                    //                    bundle.putString("Authorization", "Bearer " + token);
                    //                    bundle.putString("Title", tracks[position][1]);
                    //                    bundle.putString("art", getIntent().getStringExtra("art"));
                    //                    bundle.putString("ID", tracks[position][0]);
                    //                    MediaControllerCompat.getMediaController(AlbumActivity.this).getTransportControls().playFromUri(Uri.parse(sAddress + "/api/tracks/" + tracks[position][0] + "/audio"), bundle);
                }
            });
            FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
            layout.removeAllViews();
            layout.addView(view);
        } else if (id == R.id.nav_send) {
            String sAddress = getSharedPreferences("Prefs", 0).getString("server", null);
            StringRequest request = new StringRequest(Request.Method.POST, sAddress + "/api/logout",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject object = new JSONObject(response);
                                if (object.getString("status").equals("OK")) {
                                    Log.v(TAG, "Logged out successfully. Now redirecting to MainActivity...");
                                    AccountManager manager = AccountManager.get(getApplicationContext());
                                    Account accounts[] = manager.getAccountsByType(MusicPhpAccount.ACCOUNT_TYPE);
                                    int account = 0;
                                    for (int i = 0; i < accounts.length; i++) {
                                        if (accounts[i].name.equals(
                                                getIntent().getStringExtra(AccountManager.KEY_ACCOUNT_NAME))) {
                                            account = i;
                                            break;
                                        }
                                    }

                                    final AccountManagerFuture future;

                                    if (Build.VERSION.SDK_INT >= 22) {
                                        future = manager.removeAccount(accounts[account], NavigationActivity.this,
                                                new AccountManagerCallback<Bundle>() {
                                                    @Override
                                                    public void run(AccountManagerFuture<Bundle> future) {

                                                    }
                                                }, null);
                                    } else {
                                        future = manager.removeAccount(accounts[account],
                                                new AccountManagerCallback<Boolean>() {
                                                    @Override
                                                    public void run(AccountManagerFuture<Boolean> future) {

                                                    }
                                                }, null);
                                    }

                                    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                                        @Override
                                        protected Void doInBackground(Void... params) {
                                            try {
                                                future.getResult();
                                                Intent intent = new Intent(NavigationActivity.this,
                                                        MainActivity.class);
                                                startActivity(intent);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            return null;
                                        }
                                    };
                                    task.execute();
                                } else {
                                    Log.v(TAG, "Issue with logging out...");
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, "Issue with parsing JSON...");
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e(TAG, "Error on logging out...");
                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() {
                    Map<String, String> params = new HashMap<>();
                    params.put("Accept", "application/json");
                    params.put("Authorization",
                            "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                    return params;
                }
            };
            VolleySingleton.getInstance(this).addToRequestQueue(request);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        return true;
    }

    private enum Item {
        albums, artists, tracks
    }

    private void getListing(Item item, int id, final VolleyCallback callback) {
        String sAddress = getSharedPreferences("Prefs", 0).getString("server", null);
        StringRequest req = new StringRequest(Request.Method.GET,
                sAddress + "/api/" + item + "/" + (id == 0 ? "" : id), new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("Music.php-Android", "Server response: " + response);
                        try {
                            JSONArray array = new JSONArray(response);
                            Log.d("Music.php-Android",
                                    "JSON contains " + String.valueOf(array.length()) + " objects");
                            callback.onSuccess(array);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.v(TAG, "failure");
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Accept", "application/json");
                params.put("Authorization", "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                return params;
            }
        };
        VolleySingleton.getInstance(this).addToRequestQueue(req);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    interface VolleyCallback {
        void onSuccess(JSONArray result);
    }

    @Override
    public void onStart() {
        super.onStart();
        mMediaBrowser.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (MediaControllerCompat.getMediaController(NavigationActivity.this) != null) {
            MediaControllerCompat.getMediaController(NavigationActivity.this)
                    .unregisterCallback(controllerCallback);
        }
        mMediaBrowser.disconnect();
    }

    private final MediaBrowserCompat.ConnectionCallback mConnectionCallback = new MediaBrowserCompat.ConnectionCallback() {
        @Override
        public void onConnected() {
            MediaSessionCompat.Token token = mMediaBrowser.getSessionToken();
            try {
                MediaControllerCompat mediaController = new MediaControllerCompat(NavigationActivity.this, token);
                MediaControllerCompat.setMediaController(NavigationActivity.this, mediaController);
                queue = mediaController.getQueue();
                mediaController.registerCallback(controllerCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onConnectionSuspended() {

        }

        @Override
        public void onConnectionFailed() {

        }
    };

    MediaControllerCompat.Callback controllerCallback = new MediaControllerCompat.Callback() {
        @Override
        public void onQueueChanged(List<MediaSessionCompat.QueueItem> newQueue) {
            queue = newQueue;
        }
    };

    private int getCheckedItem(NavigationView navView) {
        Menu menu = navView.getMenu();
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            if (item.isChecked()) {
                return i;
            }
        }

        return 0;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}