com.kasungunathilaka.sarigama.util.PlayerQueue.java Source code

Java tutorial

Introduction

Here is the source code for com.kasungunathilaka.sarigama.util.PlayerQueue.java

Source

/*
 * </summary>
 * Source File   : PlayerQueue.java
 * Project      : Sarigama
 * Owner      : Kasun
 * </summary>
 *
 * <license>
 * Copyright 2016 Kasun Gunathilaka
 *
 * 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.
 * </license>
 */

package com.kasungunathilaka.sarigama.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;

import com.kasungunathilaka.sarigama.business.URLBusiness;
import com.kasungunathilaka.sarigama.domain.Song;
import com.kasungunathilaka.sarigama.domain.URLDomain;
import com.kasungunathilaka.sarigama.ui.HomeActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Kasun on 17/07/2016.
 */
public class PlayerQueue {

    private ArrayList<Song> songs;
    private int currentPosition;
    private static PlayerQueue playerQueue;
    LocalBroadcastManager localBroadcastManager;
    URLBusiness uRLBusiness;
    Context context;

    private PlayerQueue(Context context) {
        songs = new ArrayList<>();
        currentPosition = 0;
        this.context = context;
        this.localBroadcastManager = LocalBroadcastManager.getInstance(context);
    }

    public static PlayerQueue getInstance(Context context) {
        if (playerQueue == null) {
            playerQueue = new PlayerQueue(context);
        }

        return playerQueue;
    }

    public ArrayList<Song> getSongs() {
        return songs;
    }

    public void setSongs(ArrayList<Song> songs) {
        this.songs = songs;
    }

    public void addSongs(ArrayList<Song> songs) {
        this.songs.addAll(songs);
    }

    public void addSong(Song song) {
        //gettingSongDetails(song);
    }

    public int getCurrentPosition() {
        return currentPosition;
    }

    public void setCurrentPosition(int currentPosition) {
        this.currentPosition = currentPosition;
    }

    public boolean songAlreadyInList(Song song) {
        ArrayList<Song> results = new ArrayList<>();
        for (int i = 0; i < songs.size(); i++) {
            Song result = songs.get(i);
            if (result.getSongItem().contentEquals(song.getSongItem())) {
                if (this.getCurrentPosition() != i) {
                    this.setCurrentPosition(i);
                    localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_CURRENT_POSITION_CHANGED));
                } else {
                    localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_SAME_ADDED_TO_QUEUE));
                }
                results.add(result);
            }
        }
        return results.size() > 0;
    }

    public Song getSongByPosition(int position) {
        return this.songs.get(position);
    }

    public boolean hasPosition(int position) {
        try {
            return songs.get(position) != null;
        } catch (Exception ex) {
            return false;
        }
    }

    //region Set Media Source
    private class mediaLoader extends AsyncTask<Integer, Void, Integer> {

        @Override
        protected Integer doInBackground(final Integer... params) {
            try {
                uRLBusiness = new URLBusiness(context);
                if (uRLBusiness.Exist(getSongByPosition(params[0]).getSongItem())) {
                    getSongDetail(
                            uRLBusiness.SelectSingle(getSongByPosition(params[0]).getSongItem()).getUrlContent(),
                            params[0]);
                    uRLBusiness.Close();
                } else {
                    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
                    asyncHttpClient.post(context, getSongByPosition(params[0]).getSongItem(), null,
                            new AsyncHttpResponseHandler() {
                                @Override
                                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                                    try {
                                        URLDomain uRLDomain = new URLDomain();
                                        uRLDomain.setUrlAddress(
                                                playerQueue.getSongByPosition(params[0]).getSongItem());
                                        uRLDomain.setUrlContent(new String(responseBody));
                                        uRLBusiness.Save(uRLDomain);
                                        uRLBusiness.Close();
                                        getSongDetail(new String(responseBody), params[0]);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
                                        Throwable error) {
                                    Toast.makeText(context, "Song added failed", Toast.LENGTH_SHORT).show();
                                }
                            });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
        }
    }

    private void getSongDetail(String body, int position) {
        int startIndex = body.indexOf("profile-pic");
        startIndex = startIndex + 18;
        int endIndex = body.indexOf("alt", startIndex + 1);
        endIndex = endIndex - 2;
        String imageUrl = body.substring(startIndex, endIndex).trim();
        System.out.println(imageUrl);
        startIndex = body.indexOf("<source");
        startIndex = startIndex + 13;
        endIndex = body.indexOf("type", startIndex + 1);
        endIndex = endIndex - 2;
        String url = body.substring(startIndex, endIndex).trim();
        System.out.println(url);
        url = url.replace(" ", "%20");
        getSongByPosition(position).setSongSource(url);
        getSongByPosition(position).setSongImage(imageUrl);
    }
    //endregion

    //    private void sourceValidate(final Song song) {
    //        try {
    //            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    //            asyncHttpClient.get(context, song.getSongSource(), null, new AsyncHttpResponseHandler() {
    //                @Override
    //                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
    //                    try {
    //                        song.setValid(true);
    //                        MediaPlayer mediaPlayer = new MediaPlayer();
    //                        mediaPlayer.setDataSource(song.getSongSource());
    //                        mediaPlayer.prepareAsync();
    //                        song.setMediaPlayer(mediaPlayer);
    //                        songs.add(song);
    //                        setCurrentPosition(songs.size() - 1);
    //                        Toast.makeText(context, "Song added to now playing..", Toast.LENGTH_SHORT).show();
    //                        localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_ADDED_TO_QUEUE));
    //                    } catch (Exception e) {
    //                        e.printStackTrace();
    //                    }
    //                }
    //
    //                @Override
    //                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
    //                    Toast.makeText(context, "Song added failed", Toast.LENGTH_SHORT).show();
    //                }
    //            });
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }
    //    }

    public void fillSongData() {
        int currentPosition = getCurrentPosition();
        for (int i = (currentPosition - 3); i < (currentPosition + 3); i++) {
            if (hasPosition(i) && getSongByPosition(i).getSongSource().contentEquals("")) {
                executeAsyncTask(new mediaLoader(), i);
            }
        }
    }

    public void clearQueue() {
        songs.clear();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
    public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
        else
            asyncTask.execute(params);
    }
}