更新接口

优先使用局域网服务器
This commit is contained in:
yutou 2020-12-04 14:08:01 +08:00
parent 4a08266816
commit cc04892205
11 changed files with 197 additions and 112 deletions

View File

@ -295,7 +295,7 @@ public class MusicLibsAdapter extends ArrayAdapter<MusicData> {
});
} else {//添加整个文件夹
JSONObject json = new JSONObject();
json.put("path", data.getFileBase64());
json.put("path", data.getFile());
json.put("type", true);
MusicContainer.getLibs().onDirMusicData(json, new NetworkInterface() {
@Override
@ -363,7 +363,7 @@ public class MusicLibsAdapter extends ArrayAdapter<MusicData> {
public void onClick(DialogInterface dialog, int which) {
hud = AppTools.showLoading(getContext());
JSONObject json = new JSONObject();
json.put("path", data.getFileBase64());
json.put("path", data.getFile());
json.put("type", true);
MusicContainer.getLibs().onDirMusicData(json, new NetworkInterface() {
@Override

View File

@ -8,6 +8,7 @@ import android.media.ThumbnailUtils;
import android.util.Base64;
import com.alibaba.fastjson.JSONObject;
import com.yutou.nas_music_player.Interfaces.DownloadInterface;
import com.yutou.nas_music_player.Interfaces.NetworkInterface;
import com.yutou.nas_music_player.MyApplication;
import com.yutou.nas_music_player.R;
@ -23,6 +24,8 @@ import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import java.io.File;
@Entity
public class MusicData {
@PrimaryKey(autoGenerate = true)
@ -195,17 +198,20 @@ public class MusicData {
public String getFileBase64() {
if (StringUtil.isEmpty(file))
return null;
return file;
return new String(Base64.encode(file.getBytes(), Base64.DEFAULT)).replace("\n", "");
}
public String getPlayUrl() {
System.out.println("播放地址:"+NetworkTool.NetworkAPI.HOME + NetworkTool.NetworkAPI.MUSIC_PLAY
+ "?random=false&token=" + NetworkTool.NetworkAPI.HTTP_KEY + "&filePath=" + getFileBase64());
return NetworkTool.NetworkAPI.HOME + NetworkTool.NetworkAPI.MUSIC_PLAY
+ "?random=false&token=" + NetworkTool.NetworkAPI.HTTP_KEY + "&filePath=" + getFileBase64();
}
public String getImageUrl() {
return NetworkTool.NetworkAPI.MUSIC_IMAGE + "?fileName=" + getFileBase64();
return NetworkTool.NetworkAPI.MUSIC_IMAGE + "?fileName=" +getFileBase64();
}
public Bitmap getImg() {
@ -234,7 +240,8 @@ public class MusicData {
img = BitmapFactory.decodeResource(MyApplication.application.getResources(), R.mipmap.ic_launcher);
return img;
}
img = AppTools.getSaveBitmap(getFileBase64());
String imageSaveName=(StringUtil.isEmpty(album)?title:album)+".png";
img = AppTools.getSaveBitmap(imageSaveName);
if (img != null) {
if (width == -1 && height == -1) {
if (networkInterface != null)
@ -248,8 +255,21 @@ public class MusicData {
img = null;
isDownloadImg = true;
JSONObject json = new JSONObject();
json.put("fileName", getFileBase64());
NetworkTool.init().httpGet(NetworkTool.NetworkAPI.MUSIC_IMAGE, json, new NetworkInterface() {
json.put("fileName", getFile());
NetworkTool.init().download(NetworkTool.NetworkAPI.MUSIC_IMAGE,json, "image_cache" + File.separator + imageSaveName,"post", new DownloadInterface() {
@Override
public void onDownloadOver(File oldJar) {
AppTools.saveBitmap(oldJar,imageSaveName);
img=BitmapFactory.decodeFile(oldJar.getAbsolutePath());
}
@Override
public void onError(Exception e) {
super.onError(e);
img = BitmapFactory.decodeResource(MyApplication.application.getResources(), R.mipmap.ic_launcher);
}
});
/* NetworkTool.init().httpGet(NetworkTool.NetworkAPI.MUSIC_IMAGE, json, new NetworkInterface() {
@Override
public void httpGetData(Object data, int state) {
JSONObject json = JSONObject.parseObject(data.toString());
@ -280,7 +300,7 @@ public class MusicData {
public void httpError(Exception e) {
isDownloadImg = false;
}
});
});*/
if (width == -1 && height == -1) {
return img;
}

View File

@ -5,10 +5,11 @@ import java.io.File;
/**
* 下载接口
*/
public interface DownloadInterface {
public abstract class DownloadInterface {
/**
* 下载完成
* @param oldJar
*/
void DownloadOver(File oldJar);
public abstract void onDownloadOver(File oldJar);
public void onError(Exception e){};
}

View File

@ -151,10 +151,9 @@ public class MusicContainer {
return container;
}
public void randomMusic() {
playIndex = new Random().nextInt(libs.mainData.size());
}
/**
* 更新媒体控制器的数据
*/
private void updateMusicData() {
for (MediaBrowserHelper browserHelper : browserHelpers) {
if (browserHelper != null)
@ -162,7 +161,12 @@ public class MusicContainer {
}
}
public void playOfAllRandom() {
/**
* 随机下一首歌
* @param play 是否直接播放
* @param networkInterface 获取完成
*/
private void playOfAllRandom(boolean play,NetworkInterface networkInterface) {
System.out.println("随机下一首");
NetworkTool.init().httpGet(NetworkTool.NetworkAPI.MUSIC_RANDOM, new JSONObject(), new NetworkInterface() {
@Override
@ -182,14 +186,20 @@ public class MusicContainer {
JSONObject json = JSONObject.parseObject((String) data);
if (json.getInteger("code") == 0) {
nowPlayData = JSONArray.parseObject(json.getString("data"), MusicData.class);
play(nowPlayData);
updateMusicData();
if(networkInterface!=null){
networkInterface.httpGetData(nowPlayData,state);
}
if (play) {
play(nowPlayData);
updateMusicData();
}
}
}
@Override
public void httpError(Exception e) {
if(networkInterface!=null)
networkInterface.httpError(e);
}
});
}
@ -202,6 +212,13 @@ public class MusicContainer {
});
}
/**
* 默认直接播放下一首
*/
public void playOfAllRandom() {
playOfAllRandom(true,null);
}
public void play(MusicData data) {
System.out.println("准备播放:" + data.getTitle());
if (isPause) {
@ -561,16 +578,16 @@ public class MusicContainer {
String url = NetworkTool.NetworkAPI.MUSIC_Collection_Dir_List;
if (collection != null) {
url = NetworkTool.NetworkAPI.MUSIC_Collection_Get;
json.put("fid",Integer.parseInt(collection));
json.put("fid", Integer.parseInt(collection));
}
NetworkTool.init().httpGet(url, json, new NetworkInterface() {
@Override
public void httpGetData(Object data, int state) {
JSONObject json = JSONObject.parseObject((String) data);
if (json.getInteger("code") == 0) {
if(json.getJSONArray("data").toJSONString().contains("md5")){
if (json.getJSONArray("data").toJSONString().contains("md5")) {
networkInterface.httpGetData(JSONArray.parseArray(json.getJSONArray("data").toJSONString(), MusicData.class), 0);
}else{
} else {
List<MusicData> list = new ArrayList<>();
for (Object album : json.getJSONArray("data")) {
JSONObject js = (JSONObject) album;
@ -595,25 +612,26 @@ public class MusicContainer {
}
});
}
public void removeCollection(int fid,NetworkInterface networkInterface,MusicData... musicData){
JSONObject json=new JSONObject();
JSONArray array=new JSONArray();
public void removeCollection(int fid, NetworkInterface networkInterface, MusicData... musicData) {
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
for (MusicData data : musicData) {
JSONObject js=new JSONObject();
js.put("md5",data.getMd5());
js.put("fid",fid);
JSONObject js = new JSONObject();
js.put("md5", data.getMd5());
js.put("fid", fid);
array.add(js);
}
json.put("data",array);
json.put("data", array);
NetworkTool.init().httpGet(NetworkTool.NetworkAPI.MUSIC_Collection_Remove, json, new NetworkInterface() {
@Override
public void httpGetData(Object data, int state) {
JSONObject json=JSONObject.parseObject((String) data);
if(networkInterface!=null){
networkInterface.httpGetData(data,state);
JSONObject json = JSONObject.parseObject((String) data);
if (networkInterface != null) {
networkInterface.httpGetData(data, state);
}
Toast.makeText(MyApplication.application,json.getString("msg"),Toast.LENGTH_LONG).show();
Toast.makeText(MyApplication.application, json.getString("msg"), Toast.LENGTH_LONG).show();
}
@Override
@ -628,9 +646,26 @@ public class MusicContainer {
}
private void initData() {
if (initInterface != null)
initInterface.init();
initInterface = null;
if (nowPlayData == null) {
playOfAllRandom(false, new NetworkInterface() {
@Override
public void httpGetData(Object data, int state) {
//获取到下一首的信息完成初始化
if (initInterface != null)
initInterface.init();
initInterface = null;
}
@Override
public void httpError(Exception e) {
}
});
} else {
if (initInterface != null)
initInterface.init();
initInterface = null;
}
}
public void onAlbumMusicData(String album, NetworkInterface networkInterface) {

View File

@ -3,12 +3,14 @@ package com.yutou.nas_music_player.tools;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Toast;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.yutou.nas_music_player.MyApplication;
import com.yutou.nas_music_player.R;
import java.io.File;
@ -31,36 +33,12 @@ public class AppTools {
public static KProgressHUD showLoading(Context context){
return showLoading(context,"loading...");
}
public static void saveBitmap(final Bitmap bitmap, final String saveKey){
new Thread(new Runnable() {
@Override
public void run() {
String md5=getMD5(saveKey);
File path=new File(AppData.dir+"img_cache"+File.separator);
if(!path.exists()){
path.mkdirs();
}
File image=new File(AppData.dir+"img_cache"+File.separator+md5);
try {
if(!image.exists()){
image.createNewFile();
}
FileOutputStream outputStream=new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();
outputStream.close();
ConfigTools.getPreferences().edit().putString("img_"+md5,image.getAbsolutePath()).apply();
} catch (Exception e) {
e.printStackTrace();
System.out.println(image.getAbsolutePath());
}
}
}).start();
public static void saveBitmap(final File img, final String saveKey){
ConfigTools.getPreferences().edit().putString("img_"+saveKey,img.getAbsolutePath()).apply();
}
public static Bitmap getSaveBitmap(String saveKey){
String path=ConfigTools.getPreferences().getString("img_"+getMD5(saveKey),null);
String path=ConfigTools.getPreferences().getString("img_"+saveKey,null);
if(path==null){
return null;
}
@ -114,4 +92,13 @@ public class AppTools {
imageLoader.init(builder.build());
return imageLoader;
}
public static void toast(String s) {
AppData.handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MyApplication.application,s,Toast.LENGTH_LONG).show();
}
});
}
}

View File

@ -18,7 +18,7 @@ public class Log {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
File path = new File(NetworkTool.donwloadPath);
File path = new File(NetworkTool.downloadPath);
StringBuilder files = new StringBuilder();
if (path.exists()) {
for (File file : path.listFiles()) {

View File

@ -22,8 +22,6 @@ import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@ -54,31 +52,42 @@ public class NetworkTool {
private static final String TAG = NetworkTool.class.getName();
private static NetworkTool network;
public boolean isNet = true;
public static String donwloadPath = AppData.dir + AppData.download_dir + File.separator;
public static String downloadPath = AppData.dir + AppData.download_dir + File.separator;
private NetworkTool() {
//HOME = "http://192.168.31.92:8000/nas";
HOME = "http://192.168.137.1:8000/nas";
if (StringUtil.isEmpty(HOME)) {
httpGet("http://tools.yutou233.cn/nas/music/getlocalhost.do", new JSONObject(), new NetworkInterface() {
ping("http://192.168.31.88:8000/public/version.do", new NetworkInterface() {
@Override
public void httpGetData(Object data, int state) {
try {
JSONObject json = JSONObject.parseObject(data.toString());
if (json.getInteger("code") == 0) {
HOME = json.getString("data") + ":8000/nas";
}
} catch (JSONException e) {
e.printStackTrace();
}
HOME="http://192.168.31.88:8000/nas";
AppTools.toast("检测到局域网在线,使用局域网模式");
}
@Override
public void httpError(Exception e) {
System.out.println("局域网不在线,走互联网");
httpGet("http://tools.yutou233.cn/nas/music/getlocalhost.do", new JSONObject(), new NetworkInterface() {
@Override
public void httpGetData(Object data, int state) {
try {
JSONObject json = JSONObject.parseObject(data.toString());
if (json.getInteger("code") == 0) {
HOME = json.getString("data") + ":8000/nas";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void httpError(Exception e) {
}
});
}
});
}
}
@ -92,6 +101,23 @@ public class NetworkTool {
public void httpGet(String url, JSONObject body, NetworkInterface networkInterface) {
httpPost(url, body, networkInterface);
}
private void ping(String url,NetworkInterface networkInterface){
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url ).openConnection();
connection.connect();
connection.setConnectTimeout(100);
connection.setReadTimeout(100);
System.out.println(connection.getResponseCode());
networkInterface.httpGetData(null,0);
} catch (Exception e) {
networkInterface.httpError(e);
}
}
}).start();
}
@Deprecated
public void httpGet_old(final String url, final JSONObject body, final NetworkInterface networkInterface) {
if (!url.startsWith("http:") && !StringUtil.isEmpty(HOME)) {
@ -186,8 +212,8 @@ public class NetworkTool {
connection.setReadTimeout(10 * 1000);
//connection.addRequestProperty("Connection", "keep-alive");
//connection.addRequestProperty("User-Agent", getExtUa());
connection.addRequestProperty("content-type","application/json");
connection.addRequestProperty("charset","UTF-8");
connection.addRequestProperty("content-type", "application/json");
connection.addRequestProperty("charset", "UTF-8");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(body.toJSONString().getBytes());
@ -244,8 +270,8 @@ public class NetworkTool {
} catch (Exception e) {
e.printStackTrace();
networkInterface.httpError(e);
}finally {
Log.e(TAG, url + "\n传参:" + body.toString() + "\n接收" + str );
} finally {
Log.e(TAG, url + "\n传参:" + body.toString() + "\n接收" + str);
}
}
}).start();
@ -282,34 +308,46 @@ public class NetworkTool {
return string.toString();
}
public synchronized static void download(final String url, final String saveName) {
download(url, saveName, null);
public void download(final String url, final String saveName) {
download(url,new JSONObject(), saveName,"GET", null);
}
private static int reindex = 0;
static Set<String> downloadCache = Collections.synchronizedSet(new HashSet<String>());
public synchronized static void download(final String url, final String saveName, final DownloadInterface downloadInterface) {
if (downloadCache.contains(url)) return;
downloadCache.add(url);
public void download(final String url,final JSONObject body, final String saveName,String method, final DownloadInterface downloadInterface) {
System.out.println(">>>>>>>>>>"+url);
if (!url.startsWith("http:") && !StringUtil.isEmpty(HOME)) {
download(HOME+url,body,saveName,method,downloadInterface);
return;
}
new Thread(new Runnable() {
@Override
public void run() {
File jar = null;
try {
File savePath = new File(NetworkTool.donwloadPath);
File savePath = new File(downloadPath + saveName + "_tmp.tmp");
if (!savePath.exists()) {
savePath.mkdirs();
savePath.getParentFile().mkdirs();
}
Log.i(TAG, "下载文件:" + url + " 保存文件:" + saveName);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
// Log.i(TAG,"获取到网络请求:"+connection.getResponseCode());
if(method.toLowerCase().equals("post")){
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(10 * 1000);
connection.addRequestProperty("content-type", "application/json");
connection.addRequestProperty("charset", "UTF-8");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(body.toJSONString().getBytes());
outputStream.flush();
outputStream.close();
}
InputStream inputStream = connection.getInputStream();
jar = new File(donwloadPath + saveName + "_tmp.tmp");
jar = new File(downloadPath + saveName + "_tmp.tmp");
jar.createNewFile();
Log.i(NetworkTool.class, "临时保存文件:" + jar.getAbsolutePath());
OutputStream outputStream = new FileOutputStream(jar);
@ -320,7 +358,7 @@ public class NetworkTool {
}
outputStream.close();
inputStream.close();
File oldJar = new File(donwloadPath + saveName);
File oldJar = new File(downloadPath + saveName);
if (oldJar.exists()) {
oldJar.delete();
}
@ -329,20 +367,14 @@ public class NetworkTool {
Log.toast(MyApplication.application, "下载完成,重启生效");
if (downloadInterface != null) {
downloadInterface.DownloadOver(oldJar);
downloadInterface.onDownloadOver(oldJar);
}
} catch (Exception e) {
e.printStackTrace();
if (jar != null) {
jar.delete();
}
if (reindex < 3) {
reindex++;
download(url, saveName, downloadInterface);
}
} finally {
downloadCache.remove(url);
if (downloadInterface != null)
downloadInterface.onError(e);
}
}
}).start();

View File

@ -2,14 +2,10 @@ package com.yutou.nas_music_player.views;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
@ -17,13 +13,13 @@ import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.appbar.AppBarLayout;
import com.yutou.nas_music_player.Adapters.AlbumsRecyclerAdapter;
import com.yutou.nas_music_player.Datas.MusicData;
import com.yutou.nas_music_player.Interfaces.NetworkInterface;
import com.yutou.nas_music_player.R;
import com.yutou.nas_music_player.containers.MediaBrowserHelper;
import com.yutou.nas_music_player.containers.MusicContainer;
import com.yutou.nas_music_player.tools.StringUtil;
import java.util.ArrayList;
import java.util.List;
@ -35,6 +31,8 @@ public class AlbumsActivity extends AppCompatActivity {
private RecyclerView listView;
private MediaBrowserHelper browserHelper;
private AlbumsRecyclerAdapter adapter;
private AppBarLayout appBarLayout;
private TextView breakApp;
private int model;//0 专辑, 1 歌手, 2 收藏
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
@ -133,9 +131,20 @@ public class AlbumsActivity extends AppCompatActivity {
album_image = findViewById(R.id.album_image);
image_background = findViewById(R.id.image_background);
listView = findViewById(R.id.album_list);
breakApp = findViewById(R.id.breakApp);
appBarLayout = findViewById(R.id.appbar);
listView.setLayoutManager(new LinearLayoutManager(this));
adapter = new AlbumsRecyclerAdapter(AlbumsActivity.this, new ArrayList<>(),model);
listView.setAdapter(adapter);
appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
if(verticalOffset<-200){
breakApp.setTextColor(getResources().getColor(R.color.musicArtist,null));
}else{
breakApp.setTextColor(getResources().getColor(R.color.musicTitle,null));
}
});
appBarLayout.setOnClickListener(v -> finish());
}
@Override

View File

@ -147,7 +147,7 @@ public class MusicLibsFragment extends Fragment {
MusicData musicData = adapter.getItem(position);
if (musicData != null) {
if (musicData.isDir()) {
changeList(musicData.getFileBase64());
changeList(musicData.getFile());
} else {
if (browserHelper != null) {
browserHelper.play(adapter.getItem(position));

View File

@ -225,7 +225,7 @@ public class MainActivity extends AppCompatActivity {
MusicContainer.getInstance().setNowPlayData(data);
setPlayData(data);
} else {
data = MusicContainer.getLibs().getMainData().size() > 0 ? MusicContainer.getLibs().getMainData().get(0) : null;
data = MusicContainer.getInstance().getNowPlayData();
if (data != null) {
setPlayData(data);
} else {

View File

@ -17,6 +17,7 @@
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:id="@+id/toolbar_layout"
app:toolbarId="@+id/toolbar">
<ImageView
android:id="@+id/image_background"