Skip to content

Commit

Permalink
cast server
Browse files Browse the repository at this point in the history
  • Loading branch information
naman14 committed Dec 8, 2017
1 parent e5e7735 commit 08a199e
Show file tree
Hide file tree
Showing 8 changed files with 158 additions and 29 deletions.
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ dependencies {
transitive = true;
}
implementation 'com.anjlab.android.iab.v3:library:1.0.+'
implementation 'org.nanohttpd:nanohttpd:2.3.1'


}
Original file line number Diff line number Diff line change
Expand Up @@ -300,12 +300,6 @@ protected String doInBackground(String... params) {

@Override
protected void onPostExecute(String result) {
// QuickControlsFragment.topContainer.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// NavigationUtils.navigateToNowplaying(BaseActivity.this, false);
// }
// });
}

@Override
Expand Down
32 changes: 32 additions & 0 deletions app/src/main/java/com/naman14/timber/activities/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,11 @@
import com.google.android.gms.cast.framework.Session;
import com.google.android.gms.cast.framework.SessionManager;
import com.google.android.gms.cast.framework.SessionManagerListener;
import com.google.android.gms.cast.framework.media.widget.MiniControllerFragment;
import com.naman14.timber.MusicPlayer;
import com.naman14.timber.R;
import com.naman14.timber.cast.SimpleSessionManagerListener;
import com.naman14.timber.cast.WebServer;
import com.naman14.timber.fragments.AlbumDetailFragment;
import com.naman14.timber.fragments.ArtistDetailFragment;
import com.naman14.timber.fragments.FoldersFragment;
Expand All @@ -60,6 +62,7 @@
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

Expand Down Expand Up @@ -172,18 +175,25 @@ public void permissionRefused() {
private SessionManager mSessionManager;
private final SessionManagerListener mSessionManagerListener =
new SessionManagerListenerImpl();
private WebServer castServer;

private class SessionManagerListenerImpl extends SimpleSessionManagerListener {
@Override
public void onSessionStarted(Session session, String sessionId) {
invalidateOptionsMenu();
mCastSession = mSessionManager.getCurrentCastSession();
startCastServer();
showCastMiniController();
}
@Override
public void onSessionResumed(Session session, boolean wasSuspended) {
invalidateOptionsMenu();
mCastSession = mSessionManager.getCurrentCastSession();
}
@Override
public void onSessionEnded(Session session, int error) {
new initQuickControls().execute("");
stopCastServer();
}
}

Expand Down Expand Up @@ -285,6 +295,7 @@ public void onClick(View view) {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_cast, menu);

CastButtonFactory.setUpMediaRouteButton(getApplicationContext(),
menu,
Expand Down Expand Up @@ -497,6 +508,27 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
getSupportFragmentManager().findFragmentById(R.id.fragment_container).onActivityResult(requestCode, resultCode, data);
}

private void showCastMiniController() {
MiniControllerFragment controllerFragment = new MiniControllerFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.quickcontrols_container, controllerFragment).commitAllowingStateLoss();
}

private void startCastServer() {
castServer = new WebServer(this);
try {
castServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}

private void stopCastServer() {
if (castServer != null) {
castServer.stop();
}
}

}


28 changes: 17 additions & 11 deletions app/src/main/java/com/naman14/timber/adapters/BaseSongAdapter.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.naman14.timber.adapters;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.View;
Expand All @@ -14,9 +13,12 @@
import com.google.android.gms.common.images.WebImage;
import com.naman14.timber.MusicPlayer;
import com.naman14.timber.activities.MainActivity;
import com.naman14.timber.cast.WebServer;
import com.naman14.timber.models.Song;
import com.naman14.timber.utils.TimberUtils;

import java.io.IOException;

/**
* Created by naman on 7/12/17.
*/
Expand Down Expand Up @@ -63,16 +65,20 @@ public void playAll(final Activity context, final long[] list, int position,

musicMetadata.putString(MediaMetadata.KEY_TITLE, currentSong.title);
musicMetadata.putString(MediaMetadata.KEY_SUBTITLE, currentSong.artistName);
musicMetadata.addImage(new WebImage(TimberUtils.getAlbumArtUri(currentSong.albumId)));

MediaInfo mediaInfo = new MediaInfo.Builder("url")
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setContentType("audio/mpeg")
.setMetadata(musicMetadata)
.setStreamDuration(currentSong.duration * 1000)
.build();
RemoteMediaClient remoteMediaClient = castSession.getRemoteMediaClient();
remoteMediaClient.load(mediaInfo, true, position);
musicMetadata.addImage(new WebImage(Uri.parse("192.168.1.5:8080/albumart")));

try {
MediaInfo mediaInfo = new MediaInfo.Builder("192.168.1.5:8080/song")
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setContentType("audio/mpeg")
.setMetadata(musicMetadata)
.setStreamDuration(currentSong.duration * 1000)
.build();
RemoteMediaClient remoteMediaClient = castSession.getRemoteMediaClient();
remoteMediaClient.load(mediaInfo, true, position);
} catch (Exception e) {
e.printStackTrace();
}

} else {
MusicPlayer.playAll(context, list, position, -1, TimberUtils.IdType.NA, false);
Expand Down
77 changes: 77 additions & 0 deletions app/src/main/java/com/naman14/timber/cast/WebServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.naman14.timber.cast;

import android.content.Context;
import android.net.Uri;

import com.naman14.timber.utils.TimberUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

public class WebServer extends NanoHTTPD {

private Context context;
private Uri songUri, albumArtUri;

public WebServer(Context context) {
super(8080);
this.context = context;
}

@Override
public Response serve(String uri, Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
if (uri.contains("albumart")) {
//serve the picture

Uri url = Uri.parse(uri);
String albumId = url.getQueryParameter("id");
this.albumArtUri = TimberUtils.getAlbumArtUri(Long.parseLong(albumId));

if (albumArtUri != null) {
String mediasend = "image/jpg";
FileInputStream fisAlbumArt = null;
File albumArt = new File(albumArtUri.getPath());
try {
fisAlbumArt = new FileInputStream(albumArt);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Response.Status st = Response.Status.OK;

//serve the song
return newFixedLengthResponse(st, mediasend, fisAlbumArt, albumArt.length());
}

} else if (uri.contains("song")) {

Uri url = Uri.parse(uri);
String songId = url.getQueryParameter("id");
this.songUri = TimberUtils.getSongUri(context, Long.parseLong(songId));

if (songUri != null) {
String mediasend = "audio/mp3";
FileInputStream fisSong = null;
File song = new File(songUri.getPath());
try {
fisSong = new FileInputStream(song);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Response.Status st = Response.Status.OK;

//serve the song
return newFixedLengthResponse(st, mediasend, fisSong, song.length());
}

}
return newFixedLengthResponse("Error");
}

}
25 changes: 19 additions & 6 deletions app/src/main/java/com/naman14/timber/utils/TimberUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,17 @@ public static void deleteTracks(final Context context, final long[] list) {

public static void shareTrack(final Context context, long id) {

try {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, getSongUri(context, id));
context.startActivity(Intent.createChooser(share, "Share"));
} catch (Exception e) {
e.printStackTrace();
}
}

public static Uri getSongUri(Context context, long id) {
final String[] projection = new String[]{
BaseColumns._ID, MediaStore.MediaColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM_ID
};
Expand All @@ -324,19 +335,21 @@ public static void shareTrack(final Context context, long id) {
null, null);

if (c == null) {
return;
return null;
}
c.moveToFirst();


try {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(c.getString(1))));
context.startActivity(Intent.createChooser(share, "Share"));

Uri uri = Uri.parse(c.getString(1));
c.close();

return uri;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


}
12 changes: 12 additions & 0 deletions app/src/main/res/menu/menu_cast.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">


<item
android:id="@+id/media_route_menu_item"
android:title="@string/cast"
app:actionProviderClass="android.support.v7.app.MediaRouteActionProvider"
app:showAsAction="always" />

</menu>
6 changes: 0 additions & 6 deletions app/src/main/res/menu/menu_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,6 @@
<item android:id="@+id/action_settings" android:title="@string/action_settings"
android:orderInCategory="101" app:showAsAction="never" />

<item
android:id="@+id/media_route_menu_item"
android:title="@string/cast"
app:actionProviderClass="android.support.v7.app.MediaRouteActionProvider"
app:showAsAction="always" />

<item
android:id="@+id/action_search"
android:orderInCategory="1"
Expand Down

0 comments on commit 08a199e

Please sign in to comment.