Commit 18305c8c authored by wangfugui's avatar wangfugui

完善卡组上传功能,重构代码,提高可读性

parent d26e8a1d
......@@ -8,23 +8,36 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import cn.garymb.ygomobile.deck_square.api_response.BasicResponse;
import cn.garymb.ygomobile.deck_square.api_response.DeckIdResponse;
import cn.garymb.ygomobile.deck_square.api_response.DownloadDeckResponse;
import cn.garymb.ygomobile.deck_square.api_response.LoginRequest;
import cn.garymb.ygomobile.deck_square.api_response.LoginResponse;
import cn.garymb.ygomobile.deck_square.api_response.MyDeckResponse;
import cn.garymb.ygomobile.deck_square.api_response.PushCardJson;
import cn.garymb.ygomobile.deck_square.api_response.PushDeckResponse;
import cn.garymb.ygomobile.utils.LogUtil;
import cn.garymb.ygomobile.utils.OkhttpUtil;
import cn.garymb.ygomobile.utils.YGOUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class DeckSquareApiUtil {
private static final String TAG = DeckSquareListAdapter.class.getSimpleName();
//获取指定用户的卡组列表
public static MyDeckResponse getUserDecks(Integer serverUserId, String serverToken) {
/**
* 阻塞方法
* 获取指定用户的卡组列表
*
* @param serverUserId
* @param serverToken
* @return
*/
public static MyDeckResponse getUserDecks(Integer serverUserId, String serverToken) throws IOException {
if (serverToken == null) {
YGOUtil.showTextToast("Login first", Toast.LENGTH_LONG);
......@@ -32,117 +45,185 @@ public class DeckSquareApiUtil {
return null;
}
MyDeckResponse result = null;
try {
String url = "http://rarnu.xyz:38383/api/mdpro3/sync/" + serverUserId + "/nodel";
String url = "http://rarnu.xyz:38383/api/mdpro3/sync/" + serverUserId + "/nodel";
Map<String, String> headers = new HashMap<>();
Map<String, String> headers = new HashMap<>();
headers.put("ReqSource", "MDPro3");
headers.put("token", serverToken);
headers.put("ReqSource", "MDPro3");
headers.put("token", serverToken);
Response response = OkhttpUtil.synchronousGet(url, null, headers);
String responseBodyString = response.body().string();
// Type listType = new TypeToken<List<DeckInfo>>() {
// }.getType();
Gson gson = new Gson();
// Convert JSON to Java object using Gson
result = gson.fromJson(responseBodyString, MyDeckResponse.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
Response response = OkhttpUtil.synchronousGet(url, null, headers);
String responseBodyString = response.body().string();
Gson gson = new Gson();
result = gson.fromJson(responseBodyString, MyDeckResponse.class);
if (result.code == 20) {//用户身份验证失败
if (result.code == 20) {//用户身份验证失败
YGOUtil.showTextToast("Login first", Toast.LENGTH_LONG);
}
return result;
}
//根据卡组ID查询一个卡组
public static DownloadDeckResponse getDeckById(String deckId) {
/**
* 阻塞方法
* 根据卡组ID查询一个卡组
*
* @param deckId
* @return
*/
public static DownloadDeckResponse getDeckById(String deckId) throws IOException {
DownloadDeckResponse result = null;
String url = "http://rarnu.xyz:38383/api/mdpro3/deck/" + deckId;
Map<String, String> headers = new HashMap<>();
headers.put("ReqSource", "MDPro3");
Response response = null;
try {
response = OkhttpUtil.synchronousGet(url, null, headers);
String responseBodyString = response.body().string();
Response response = OkhttpUtil.synchronousGet(url, null, headers);
String responseBodyString = response.body().string();
Gson gson = new Gson();
// Convert JSON to Java object using Gson
result = gson.fromJson(responseBodyString, DownloadDeckResponse.class);
LogUtil.i(TAG, responseBodyString);
} catch (IOException e) {
throw new RuntimeException(e);
}
Gson gson = new Gson();
// Convert JSON to Java object using Gson
result = gson.fromJson(responseBodyString, DownloadDeckResponse.class);
LogUtil.i(TAG, responseBodyString);
return result;
}
//首先获取卡组id,之后将卡组id设置到ydk中,之后将其上传
public static void pushDeck(String deckPath, String deckName, Integer userId) {
/**
* 阻塞方法
* 先同步推送,之后异步推送。首先获取卡组id,之后将卡组id设置到ydk中,之后将其上传
*
* @param deckPath
* @param deckName
* @param userId
*/
public static PushDeckResponse pushDeck(String deckPath, String deckName, Integer userId, String serverToken) throws IOException {
PushDeckResponse result = null;
if (serverToken == null) {
return null;
}
String url = "http://rarnu.xyz:38383/api/mdpro3/sync/single";
String getDeckIdUrl = "http://rarnu.xyz:38383/api/mdpro3/deck/deckId";
Map<String, String> headers = new HashMap<>();
headers.put("ReqSource", "MDPro3");
headers.put("token", serverToken);
Gson gson = new Gson();
DeckIdResponse deckIdResult = null;
{
Response response = OkhttpUtil.synchronousGet(getDeckIdUrl, null, headers);
String responseBodyString = response.body().string();
// Convert JSON to Java object using Gson
deckIdResult = gson.fromJson(responseBodyString, DeckIdResponse.class);
LogUtil.i(TAG, "deck id result:" + deckIdResult.toString());
}
String deckId = deckIdResult.getDeckId();//从服务器获取
try {
String deckContent = DeckSquareFileUtil.setDeckId(deckPath, userId, deckId);
DeckIdResponse deckIdResult = null;
{
Response response = OkhttpUtil.synchronousGet(getDeckIdUrl, null, headers);
String responseBodyString = response.body().string();
Gson gson = new Gson();
// Convert JSON to Java object using Gson
deckIdResult = gson.fromJson(responseBodyString, DeckIdResponse.class);
LogUtil.i(TAG, "deck id result:" + deckIdResult.toString());
}
PushCardJson pushCardJson = new PushCardJson();
pushCardJson.setDeckContributor(userId.toString());
pushCardJson.setUserId(userId);
PushCardJson.DeckData deckData = new PushCardJson.DeckData();
deckData.setDeckId(deckId);
deckData.setDeckName(deckName);
deckData.setDelete(false);
deckData.setDeckYdk(deckContent);
pushCardJson.setDeck(deckData);
String deckId = deckIdResult.getDeckId();//从服务器获取
String json = gson.toJson(pushCardJson);
String deckContent = DeckSquareFileUtil.setDeckId(deckPath, userId, deckId);
PushCardJson pushCardJson = new PushCardJson();
pushCardJson.setDeckContributor(userId.toString());
pushCardJson.setUserId(userId);
PushCardJson.DeckData deckData = new PushCardJson.DeckData();
Response response = OkhttpUtil.postJson(url, json, headers, 1000);
String responseBodyString = response.body().string();
// Convert JSON to Java object using Gson
result = gson.fromJson(responseBodyString, PushDeckResponse.class);
LogUtil.i(TAG, "push deck response:" + responseBodyString);
return result;
}
deckData.setDeckId(deckId);
deckData.setDeckName(deckName);
deckData.setDelete(false);
deckData.setDeckYdk(deckContent);
pushCardJson.setDeck(deckData);
/**
* 异步方法,给卡组点赞
*
* @param deckId
*/
public static BasicResponse likeDeck(String deckId) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(pushCardJson);
BasicResponse result = null;
//todo 构造卡组的json
OkhttpUtil.postJson(url, json, headers, 1000, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
String url = "http://rarnu.xyz:38383/api/mdpro3/deck/like/" + deckId;
Map<String, String> headers = new HashMap<>();
headers.put("ReqSource", "MDPro3");
Response response = OkhttpUtil.postJson(url, null, headers, 1000);
String responseBodyString = response.body().string();
LogUtil.i(TAG, "push deck fail");
}
Gson gson = new Gson();
result = gson.fromJson(responseBodyString, BasicResponse.class);
LogUtil.i(TAG, responseBodyString);
@Override
public void onResponse(Call call, Response response) throws IOException {
return result;
LogUtil.i(TAG, "push deck success");
}
});
}
} catch (IOException e) {
throw new RuntimeException(e);
public static LoginResponse login(String userId, String password) throws IOException {
LoginResponse result = null;
String url = "https://sapi.moecube.com:444/accounts/signin";
String baseUrl = "https://sapi.moecube.com:444/accounts/signin";
// Create request body using Gson
Gson gson = new Gson();
userId = "1076306278@qq.com";
password = "Qbz95qbz96";
LoginRequest loginRequest = new LoginRequest(userId, password);
String json = gson.toJson(loginRequest);//"{\"id\":1,\"name\":\"John\"}";
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
Response response = okHttpClient.newCall(request).execute();
// Read the response body
String responseBody = response.body().string();
LogUtil.i(TAG, "Login Response body: " + responseBody);
// Process the response
if (response.isSuccessful()) {
// Successful response (code 200-299)
// Parse the JSON response if needed
result = gson.fromJson(responseBody, LoginResponse.class);
LogUtil.i(TAG, "Login response: " + result);
} else {
// Error response
LogUtil.e(TAG, "Request failed: " + responseBody);
}
return result;
}
}
\ No newline at end of file
package cn.garymb.ygomobile.deck_square;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
......@@ -15,6 +15,9 @@ import cn.garymb.ygomobile.AppsSettings;
import cn.garymb.ygomobile.Constants;
import cn.garymb.ygomobile.utils.IOUtils;
import cn.garymb.ygomobile.utils.LogUtil;
import ocgcore.CardManager;
import ocgcore.DataManager;
import ocgcore.data.Card;
public class DeckSquareFileUtil {
//
......@@ -38,7 +41,7 @@ public class DeckSquareFileUtil {
//读取file指定的ydk文件,返回其内包含的deckId。如果不包含deckId,返回null
public static String getId(File file) {
String deckId = null;
Integer userId;
Integer userId = null;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
......@@ -49,22 +52,31 @@ public class DeckSquareFileUtil {
String line = null;
while ((line = reader.readLine()) != null) {
// LogUtil.i(TAG, line);
LogUtil.i(TAG, line);
if (line.startsWith("###")) {//注意,先判断###,后判断##。因为###会包括##的情况
line = line.replace("#", "");
userId = Integer.parseInt(line);
// userId = Integer.parseInt(line.replaceAll("###", ""));
try {
String data = line.replace("#", "");
if (!data.isEmpty()) {
userId = Integer.parseInt(data);
}
// userId = Integer.parseInt(line.replaceAll("###", ""));
} catch (NumberFormatException e) {
LogUtil.e(TAG, "integer" + line + "parse error" + e.toString());
}
} else if (line.startsWith("##")) {
line = line.replace("#", "");
deckId = line;
}
}
} catch (Exception e) {
Log.e(TAG, "read 1", e);
} catch (IOException e) {
LogUtil.e(TAG, "read 1", e);
} finally {
IOUtils.close(inputStream);
}
return deckId;
......@@ -150,4 +162,48 @@ public class DeckSquareFileUtil {
return content;
}
public static boolean saveFileToPath(String path, String fileName, String content) {
try {
// Create file object
File file = new File(path, fileName);
// Create file output stream
FileOutputStream fos = new FileOutputStream(file);
// Write content
fos.write(content.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static List<Card> convertTempDeckYdk(String deckYdk) {
String[] deckLine = deckYdk.split("\r\n|\r|\n");
List<Integer> tempDeck = new ArrayList<>();//存储当前卡组的基本内容
List<Card> cardList = new ArrayList<>();
CardManager mCardManager = DataManager.get().getCardManager();
for (String line : deckLine) {
if (!line.contains("#") && !line.contains("!")) {
//line.to
try {
Integer cardId = Integer.parseInt(line);
tempDeck.add(cardId);
Card card = mCardManager.getCard(cardId);
cardList.add(card);
} catch (NumberFormatException e) {
LogUtil.i(TAG, "cannot parse Interget" + line + e.getMessage());
}
}
}
return cardList;
}
}
......@@ -11,21 +11,12 @@ import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.IOException;
import cn.garymb.ygomobile.deck_square.api_response.LoginRequest;
import cn.garymb.ygomobile.deck_square.api_response.LoginResponse;
import cn.garymb.ygomobile.lite.R;
import cn.garymb.ygomobile.ui.plus.VUiKit;
import cn.garymb.ygomobile.utils.LogUtil;
import cn.garymb.ygomobile.utils.SharedPreferenceUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import cn.garymb.ygomobile.utils.YGOUtil;
public class LoginDialog extends Dialog {
......@@ -75,59 +66,10 @@ public class LoginDialog extends Dialog {
btnLogin.setEnabled(false);
btnCancel.setEnabled(false);
// Simulate network call
// new Handler().postDelayed(() -> {
// if (listener != null) {
// listener.onLogin(username, password);
// }
// dismiss();
// }, 1500);
VUiKit.defer().when(() -> {
LogUtil.d(TAG, "start fetch");
LoginResponse result = null;
try {
String url = "https://sapi.moecube.com:444/accounts/signin";
String baseUrl = "https://sapi.moecube.com:444/accounts/signin";
// Create request body using Gson
Gson gson = new Gson();
LoginRequest loginRequest = new LoginRequest("1076306278@qq.com", "Qbz95qbz96");
String json = gson.toJson(loginRequest);//"{\"id\":1,\"name\":\"John\"}";
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
Response response = okHttpClient.newCall(request).execute();
// Read the response body
String responseBody = response.body().string();
LogUtil.i(TAG, "Response body: " + responseBody);
// Process the response
if (response.isSuccessful()) {
// Successful response (code 200-299)
// Parse the JSON response if needed
result = gson.fromJson(responseBody, LoginResponse.class);
LogUtil.i(TAG, "Login response: " + result);
} else {
// Error response
LogUtil.e(TAG, "Request failed: " + responseBody);
}
} catch (IOException e) {
Log.e(TAG, "Error occured when fetching data from pre-card server");
return null;
}
LoginResponse result = DeckSquareApiUtil.login("", "");
SharedPreferenceUtil.setServerToken(result.token);
SharedPreferenceUtil.setServerUserId(result.user.id);
return result;
......@@ -136,6 +78,7 @@ public class LoginDialog extends Dialog {
Log.e(TAG, e + "");
listener.notifyResult(false, null);
LogUtil.i(TAG, "login fail");
dismiss();
......@@ -143,9 +86,9 @@ public class LoginDialog extends Dialog {
if (result != null) {
LogUtil.i(TAG, "login done");
listener.notifyResult(true, result);
// getData().clear();
// addData(exCardDataList);
// notifyDataSetChanged();
YGOUtil.showTextToast("Login success!");
} else {
listener.notifyResult(false, null);
}
......
......@@ -3,46 +3,41 @@ package cn.garymb.ygomobile.deck_square;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import cn.garymb.ygomobile.AppsSettings;
import cn.garymb.ygomobile.deck_square.api_response.DeckDetail;
import cn.garymb.ygomobile.deck_square.api_response.DownloadDeckResponse;
import cn.garymb.ygomobile.deck_square.api_response.PushDeckResponse;
import cn.garymb.ygomobile.lite.R;
import cn.garymb.ygomobile.ui.adapters.DeckPreviewListAdapter;
import cn.garymb.ygomobile.ui.plus.VUiKit;
import cn.garymb.ygomobile.utils.LogUtil;
import cn.garymb.ygomobile.utils.SharedPreferenceUtil;
import cn.garymb.ygomobile.utils.YGOUtil;
import ocgcore.data.Card;
public class MyDeckDetailDialog extends Dialog {
private static final String TAG = DeckSquareListAdapter.class.getSimpleName();
// private String deckId;
// private String deckName;
// private Integer userId;
MyDeckItem item;
public interface ActionListener {
void onDownloadClicked();
DeckPreviewListAdapter mListAdapter;
private RecyclerView mListView;
private DeckDetail mDeckDetail = null;
void onLikeClicked();
}
private ActionListener listener;
MyDeckItem mItem = null;//存储触发本dialog的卡组的基本信息
public MyDeckDetailDialog(Context context, MyDeckItem item) {
super(context);
// deckId = item.getDeckId();
// deckName = item.getDeckName();
// userId = item.getUserId();
this.item = item;
this.mItem = item;
}
......@@ -55,103 +50,100 @@ public class MyDeckDetailDialog extends Dialog {
Button btnDownload = findViewById(R.id.dialog_my_deck_btn_download);
Button btnPush = findViewById(R.id.dialog_my_deck_btn_push);
Button btnLike = findViewById(R.id.btnLike);
LinearLayout downloadLayout = findViewById(R.id.server_download_layout);
LinearLayout uploadLayout = findViewById(R.id.server_upload_layout);
if (item.getDeckSouce() == 0) {//来自本地
if (mItem.getDeckSouce() == 0) {//来自本地
downloadLayout.setVisibility(View.GONE);
uploadLayout.setVisibility(View.VISIBLE);
//btnDownload.setBackground(R.id.ic);
} else if (item.getDeckSouce() == 1) {//来自服务器
} else if (mItem.getDeckSouce() == 1) {//来自服务器
downloadLayout.setVisibility(View.VISIBLE);
uploadLayout.setVisibility(View.GONE);
} else if (item.getDeckSouce() == 2) {//本地、服务器均存在
previewDeckCard();
} else if (mItem.getDeckSouce() == 2) {//本地、服务器均存在
downloadLayout.setVisibility(View.VISIBLE);
uploadLayout.setVisibility(View.VISIBLE);
previewDeckCard();
}
btnPush.setOnClickListener(v -> {
Integer userId = SharedPreferenceUtil.getServerUserId();
if (userId == null) {
YGOUtil.showTextToast("Please login first!");
return;
}
VUiKit.defer().when(() -> {
DeckSquareApiUtil.pushDeck(item.getDeckPath(),item.getDeckName(), userId);
});//.done();
});
mListAdapter = new DeckPreviewListAdapter(R.layout.item_square_deck_card_preview);
mListView = findViewById(R.id.dialog_my_deck_detail_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
mListView.setLayoutManager(linearLayoutManager);
mListView.setAdapter(mListAdapter);
btnDownload.setOnClickListener(v -> {
//上传卡组
btnPush.setOnClickListener(v -> {
Integer userId = SharedPreferenceUtil.getServerUserId();
if (userId == null) {
String serverToken = SharedPreferenceUtil.getServerToken();//todo serverToken要外部传入还是此处获取?考虑
if (userId == null || serverToken == null) {
YGOUtil.showTextToast("Please login first!");
return;
}
VUiKit.defer().when(() -> {
DownloadDeckResponse response = DeckSquareApiUtil.getDeckById(item.getDeckId());
if (response != null) {
return response.getData();
VUiKit.defer().when(() -> {
PushDeckResponse result = DeckSquareApiUtil.pushDeck(mItem.getDeckPath(), mItem.getDeckName(), userId, serverToken);
return result;
}).fail(e -> {
LogUtil.i(TAG, "square deck detail fail" + e.getMessage());
}).done(data -> {
if (data.isData()) {
YGOUtil.showTextToast("push success!");
} else {
return null;
}
}).fail((e) -> {
Log.e(TAG, e + "");
// if (dialog_read_ex.isShowing()) {//关闭异常
// try {
// dialog_read_ex.dismiss();
// } catch (Exception ex) {
//
// }
// }
LogUtil.i(TAG, "square deck detail fail");
}).done((deckData) -> {
if (deckData != null) {
String path = AppsSettings.get().getDeckDir();
saveFileToPath(path, item.getDeckName() + ".ydk", deckData.deckYdk);
LogUtil.i(TAG, "square deck detail done");
YGOUtil.showTextToast(R.string.down_complete);
YGOUtil.showTextToast(data.getMessage());
}
// if (dialog_read_ex.isShowing()) {
// try {
// dialog_read_ex.dismiss();
// } catch (Exception ex) {
// }
// }
});
dismiss();
//todo,改造pushDeck,传入回调,得到推送的http响应
});
btnLike.setOnClickListener(v -> {
//下载用户在平台上的卡组
btnDownload.setOnClickListener(v -> {
dismiss();
if (mDeckDetail != null) {
String path = AppsSettings.get().getDeckDir();
DeckSquareFileUtil.saveFileToPath(path, mDeckDetail.getDeckName() + ".ydk", mDeckDetail.getDeckYdk());
}
});
}
public void saveFileToPath(String path, String fileName, String content) {
try {
// Create file object
File file = new File(path, fileName);
private void previewDeckCard() {
Integer userId = SharedPreferenceUtil.getServerUserId();
if (userId == null) {
YGOUtil.showTextToast("Please login first!");
return;
}
VUiKit.defer().when(() -> {
DownloadDeckResponse response = DeckSquareApiUtil.getDeckById(mItem.getDeckId());
if (response != null) {
return response.getData();
} else {
return null;
}
// Create file output stream
FileOutputStream fos = new FileOutputStream(file);
}).fail((e) -> {
LogUtil.i(TAG, "square deck detail fail" + e.getMessage());
}).done((deckData) -> {
if (deckData != null) {
mDeckDetail = deckData;
LogUtil.i(TAG, "square deck detail done");
List<Card> cardList = DeckSquareFileUtil.convertTempDeckYdk(deckData.getDeckYdk());
mListAdapter.updateData(cardList);
}
});
// Write content
fos.write(content.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
......@@ -3,50 +3,41 @@ package cn.garymb.ygomobile.deck_square;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Button;
import com.google.gson.Gson;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import cn.garymb.ygomobile.AppsSettings;
import cn.garymb.ygomobile.deck_square.api_response.ApiDeckRecord;
import cn.garymb.ygomobile.deck_square.api_response.BasicResponse;
import cn.garymb.ygomobile.deck_square.api_response.DeckDetail;
import cn.garymb.ygomobile.deck_square.api_response.DownloadDeckResponse;
import cn.garymb.ygomobile.deck_square.api_response.MyDeckResponse;
import cn.garymb.ygomobile.lite.R;
import cn.garymb.ygomobile.ui.adapters.DeckPreviewListAdapter;
import cn.garymb.ygomobile.ui.plus.VUiKit;
import cn.garymb.ygomobile.utils.LogUtil;
import cn.garymb.ygomobile.utils.OkhttpUtil;
import cn.garymb.ygomobile.utils.SharedPreferenceUtil;
import cn.garymb.ygomobile.utils.YGOUtil;
import okhttp3.Response;
import ocgcore.data.Card;
public class SquareDeckDetailDialog extends Dialog {
private static final String TAG = DeckSquareListAdapter.class.getSimpleName();
private String deckId;
private String deckName;
private Integer userId;
public interface ActionListener {
void onDownloadClicked();
DeckPreviewListAdapter mListAdapter;
private RecyclerView mListView;
private DeckDetail mDeckDetail = null;
void onLikeClicked();
}
private ActionListener listener;
private ApiDeckRecord mItem = null;
public SquareDeckDetailDialog(Context context, ApiDeckRecord item) {
super(context);
deckId = item.getDeckId();
deckName = item.getDeckName();
userId = item.getUserId();
mItem = item;
}
@Override
......@@ -55,88 +46,83 @@ public class SquareDeckDetailDialog extends Dialog {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_square_deck_detail);
Button btnDownload = findViewById(R.id.btnDownload);
Button btnDownload = findViewById(R.id.dialog_square_deck_btn_download);
Button btnLike = findViewById(R.id.btnLike);
btnDownload.setOnClickListener(v -> {
VUiKit.defer().when(() -> {
DownloadDeckResponse result = null;
String url = "http://rarnu.xyz:38383/api/mdpro3/deck/" + deckId;
Map<String, String> headers = new HashMap<>();
previewDeckCard();
headers.put("ReqSource", "MDPro3");
mListAdapter = new DeckPreviewListAdapter(R.layout.item_square_deck_card_preview);
Response response = null;
try {
response = OkhttpUtil.synchronousGet(url, null, headers);
String responseBodyString = response.body().string();
mListView = findViewById(R.id.dialog_square_deck_detail_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
mListView.setLayoutManager(linearLayoutManager);
mListView.setAdapter(mListAdapter);
//下载卡组广场的卡组
btnDownload.setOnClickListener(v -> {
if (mDeckDetail != null) {
String path = AppsSettings.get().getDeckDir();
boolean result = DeckSquareFileUtil.saveFileToPath(path, mDeckDetail.getDeckName() + ".ydk", mDeckDetail.getDeckYdk());
if (result) {
Gson gson = new Gson();
// Convert JSON to Java object using Gson
result = gson.fromJson(responseBodyString, DownloadDeckResponse.class);
LogUtil.i(TAG, responseBodyString);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (result == null) {
return null;
YGOUtil.showTextToast("Download deck success!");
} else {
return result.getData();
}
}).fail((e) -> {
Log.e(TAG, e + "");
// if (dialog_read_ex.isShowing()) {//关闭异常
// try {
// dialog_read_ex.dismiss();
// } catch (Exception ex) {
//
// }
// }
LogUtil.i(TAG, "square deck detail fail");
}).done((deckData) -> {
if (deckData != null) {
String path = AppsSettings.get().getDeckDir();
saveFileToPath(path, deckName + ".ydk", deckData.deckYdk);
LogUtil.i(TAG, "square deck detail done");
YGOUtil.showTextToast(R.string.down_complete);
YGOUtil.showTextToast("Download deck fail!");
}
// if (dialog_read_ex.isShowing()) {
// try {
// dialog_read_ex.dismiss();
// } catch (Exception ex) {
// }
// }
});
dismiss();
}
});
//给卡组点赞
btnLike.setOnClickListener(v -> {
dismiss();
VUiKit.defer().when(() -> {
BasicResponse result = DeckSquareApiUtil.likeDeck(mItem.getDeckId());
return result;
}).fail(e -> {
LogUtil.i(TAG, "Like deck fail" + e.getMessage());
}).done(data -> {
if (data.getMessage().equals("true")) {
YGOUtil.showTextToast("Like deck success!");
} else {
YGOUtil.showTextToast(data.getMessage());
}
});
});
}
public void saveFileToPath(String path, String fileName, String content) {
try {
// Create file object
File file = new File(path, fileName);
private void previewDeckCard() {
Integer userId = SharedPreferenceUtil.getServerUserId();
if (userId == null) {
YGOUtil.showTextToast("Please login first!");
return;
}
VUiKit.defer().when(() -> {
// Create file output stream
FileOutputStream fos = new FileOutputStream(file);
DownloadDeckResponse response = DeckSquareApiUtil.getDeckById(mItem.getDeckId());
if (response != null) {
return response.getData();
} else {
return null;
}
}).fail((e) -> {
LogUtil.i(TAG, "square deck detail fail" + e.getMessage());
}).done((deckData) -> {
if (deckData != null) {
mDeckDetail = deckData;
LogUtil.i(TAG, "square deck detail done");
List<Card> cardList = DeckSquareFileUtil.convertTempDeckYdk(deckData.getDeckYdk());
mListAdapter.updateData(cardList);
}
});
// Write content
fos.write(content.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
package cn.garymb.ygomobile.deck_square.api_response;
public class BasicResponse {
private Integer code;
private String message;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
......@@ -8,23 +8,23 @@ import androidx.annotation.NonNull;
public class DeckDetail implements Parcelable {
public String deckId;
public String deckContributor;
public String deckName;
public String deckRank;
public String deckLike;
public String deckUploadDate;
public String deckUpdateDate;
public int deckCoverCard1;
public int deckCoverCard2;
public int deckCoverCard3;
public String deckCase;
public String deckProtector;
public String deckMainSerial;
public String deckYdk;
public Integer userId;
public String isPublic;
public String isDelete;
private String deckId;
private String deckContributor;
private String deckName;
private String deckRank;
private String deckLike;
private String deckUploadDate;
private String deckUpdateDate;
private int deckCoverCard1;
private int deckCoverCard2;
private int deckCoverCard3;
private String deckCase;
private String deckProtector;
private String deckMainSerial;
private String deckYdk;
private Integer userId;
private String isPublic;
private String isDelete;
protected DeckDetail(Parcel in) {
......
package cn.garymb.ygomobile.deck_square.api_response;
public class DownloadDeckResponse {
public Integer code;
public String message;
public DeckDetail data;
private Integer code;
private String message;
private DeckDetail data;
public Integer getCode() {
return code;
......
package cn.garymb.ygomobile.deck_square.api_response;
//将卡组上传后,返回的响应
//对应接口http://rarnu.xyz:38383/api/mdpro3/sync/single
public class PushDeckResponse {
private Integer code;
private String message;
private boolean data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isData() {
return data;
}
public void setData(boolean data) {
this.data = data;
}
}
package cn.garymb.ygomobile.ui.adapters;
import androidx.annotation.NonNull;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import java.util.List;
import cn.garymb.ygomobile.ex_card.ExCardListAdapter;
import cn.garymb.ygomobile.lite.R;
import ocgcore.data.Card;
//卡组预览的adapter
public class DeckPreviewListAdapter extends BaseQuickAdapter<Card, BaseViewHolder> {
private static final String TAG = ExCardListAdapter.class.getSimpleName();
public DeckPreviewListAdapter(int layoutResId) {
super(layoutResId);
}
public void updateData(List<Card> dataList) {
getData().clear();
addData(dataList);
notifyDataSetChanged();
}
@Override
protected void convert(@NonNull BaseViewHolder baseViewHolder, Card item) {
baseViewHolder.setText(R.id.preview_card_name, item.Name);
baseViewHolder.setText(R.id.preview_card_id, Integer.toString(item.Code));
}
}
......@@ -257,10 +257,8 @@ public class OkhttpUtil {
public static void post(String url, String json, String cookie, Callback callback) {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, json);
Request.Builder request = new Request.Builder()
.url(url);//请求的url
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
Request.Builder request = new Request.Builder().url(url);//请求的url
if (TextUtils.isEmpty(json))
request.post(okhttp3.internal.Util.EMPTY_REQUEST);
else
......@@ -284,8 +282,13 @@ public class OkhttpUtil {
}
}
public static void postJson(String url, String json, Map<String, String> headers, int timeout, Callback callback) {
/**
* @param url
* @param json 可以传入null或空字符串,均代表不需要发送json
* @param headers 可以传入null
* @param timeout 可以为0,为0代表使用默认值
*/
public static Response postJson(String url, String json, Map<String, String> headers, int timeout) throws IOException {
okHttpClient = new OkHttpClient();
if (timeout != 0)
......@@ -294,15 +297,15 @@ public class OkhttpUtil {
.build();
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, json);
Request.Builder request = new Request.Builder()
.url(url);//请求的url
if (TextUtils.isEmpty(json))
Request.Builder request = new Request.Builder().url(url);//请求的url
if (json == null || TextUtils.isEmpty(json)) {
request.post(okhttp3.internal.Util.EMPTY_REQUEST);
else
} else {
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
request.post(requestBody);
}
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
request.addHeader(header.getKey(), header.getValue().toString());
......@@ -310,7 +313,8 @@ public class OkhttpUtil {
}
Log.e("OkhttpUtil", json + " 状态 " + request.build());
okHttpClient.newCall(request.build()).enqueue(callback);
return okHttpClient.newCall(request.build()).execute();
//okHttpClient.newCall(request.build()).enqueue(callback);
}
/**
......
......@@ -5,34 +5,50 @@
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/tvTitle"
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:gravity="center"
android:text="Choose Action"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnDownload"
style="@style/Widget.AppCompat.Button.Borderless"
android:orientation="horizontal">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/ic_server_download" />
<Button
android:id="@+id/dialog_square_deck_btn_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/Download" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:drawableStart="@drawable/ic_download"
android:drawablePadding="8dp"
android:text="Download" />
<Button
android:id="@+id/btnLike"
style="@style/Widget.AppCompat.Button.Borderless"
android:orientation="horizontal">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/ic_like" />
<Button
android:id="@+id/btnLike"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawablePadding="8dp"
android:text="Like" />
</LinearLayout>
<com.tubb.smrv.SwipeMenuRecyclerView
android:id="@+id/dialog_square_deck_detail_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableStart="@drawable/ic_like"
android:drawablePadding="8dp"
android:text="Like" />
android:divider="@android:color/transparent"
android:dividerHeight="4dp"
android:padding="5dp"
android:scrollbars="vertical" />
</LinearLayout>
\ No newline at end of file
......@@ -5,16 +5,6 @@
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:gravity="center"
android:text="Choose Action"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:id="@+id/server_download_layout"
android:layout_width="match_parent"
......@@ -54,14 +44,13 @@
</LinearLayout>
<Button
android:id="@+id/btnLike"
style="@style/Widget.AppCompat.Button.Borderless"
<com.tubb.smrv.SwipeMenuRecyclerView
android:id="@+id/dialog_my_deck_detail_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableStart="@drawable/ic_like"
android:drawablePadding="8dp"
android:text="Delete" />
android:divider="@android:color/transparent"
android:dividerHeight="4dp"
android:padding="5dp"
android:scrollbars="vertical" />
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/preview_card_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:background="@drawable/veil"
android:gravity="top"
android:paddingLeft="8dp"
android:singleLine="true"
android:textColor="@color/white"
android:textSize="12sp"
tools:text="name" />
<TextView
android:id="@+id/preview_card_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:textSize="12sp" />
</LinearLayout>
<!-- <ImageView-->
<!-- android:id="@+id/card_image"-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:layout_marginLeft="1px"-->
<!-- android:layout_marginRight="1px"-->
<!-- android:layout_marginBottom="1px"-->
<!-- tools:src="@drawable/unknown" />-->
<ImageView
android:id="@+id/right_top"
android:layout_width="@dimen/right_size2"
android:layout_height="@dimen/right_size2"
android:layout_alignParentRight="true"
android:visibility="visible"
app:srcCompat="@drawable/ic_close_black_24dp" />
</RelativeLayout>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment