Commit 5436c3a1 authored by wangfugui's avatar wangfugui

优化上传功能api

parent 26960122
......@@ -8,13 +8,21 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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.MyDeckResponse;
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.Response;
public class DeckSquareApiUtil {
private static final String TAG = DeckSquareListAdapter.class.getSimpleName();
//获取指定用户的卡组列表
public static MyDeckResponse getUserDecks(Integer serverUserId, String serverToken) {
if (serverToken == null) {
......@@ -42,7 +50,7 @@ public class DeckSquareApiUtil {
throw new RuntimeException(e);
}
if(result.code == 20){//用户身份验证失败
if (result.code == 20) {//用户身份验证失败
YGOUtil.showTextToast("Login first", Toast.LENGTH_LONG);
......@@ -50,4 +58,77 @@ public class DeckSquareApiUtil {
return result;
}
//根据卡组ID查询一个卡组
public static DownloadDeckResponse getDeckById(String deckId) {
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();
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);
}
return result;
}
//首先获取卡组id,之后将卡组id设置到ydk中,之后将其上传
public static void pushDeck(String deckPath, Integer userId) {
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");
try {
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);
}
String deckId = deckIdResult.getDeckId();//从服务器获取
DeckSquareFileUtil.setDeckId(deckPath, userId, deckId);
//todo 构造卡组的json
OkhttpUtil.postJson(url, null, headers, 1000, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
LogUtil.i(TAG, "push deck fail");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
LogUtil.i(TAG, "push deck success");
}
});
Gson gson = new Gson();
// Convert JSON to Java object using Gson
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
\ 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.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import cn.garymb.ygomobile.AppsSettings;
import cn.garymb.ygomobile.Constants;
import cn.garymb.ygomobile.utils.IOUtils;
import cn.garymb.ygomobile.utils.LogUtil;
public class DeckSquareFileUtil {
//
private static final String TAG = DeckSquareListAdapter.class.getSimpleName();
// public static List<String> readLastLinesWithNIO(File file, int numLines) {
// try {
// List<String> lines = Files.readAllLines(file);
// int fromIndex = Math.max(0, lines.size() - numLines);
// return lines.subList(fromIndex, lines.size());
// } catch (IOException e) {
// e.printStackTrace();
// return Collections.emptyList();
// }
// }
//
// 使用示例
// Path logPath = Paths.get(context.getFilesDir().getAbsolutePath(), "log.txt");
// List<String> lastTwo = readLastLinesWithNIO(logPath, 2);
public static String getId(File file) {
String deckId = null;
Integer userId;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
InputStreamReader in = null;
in = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(in);
String line = null;
while ((line = reader.readLine()) != null) {
// LogUtil.i(TAG, line);
if (line.startsWith("###")) {//注意,先判断###,后判断##。因为###会包括##的情况
line = line.replace("#", "");
userId = Integer.parseInt(line);
// userId = Integer.parseInt(line.replaceAll("###", ""));
} else if (line.startsWith("##")) {
line = line.replace("#", "");
deckId = line;
}
}
} catch (Exception e) {
Log.e(TAG, "read 1", e);
} finally {
IOUtils.close(inputStream);
}
return deckId;
}
public static File[] getAllYdk() {
File dir = new File(AppsSettings.get().getResourcePath(), Constants.CORE_DECK_PATH);
File[] files = dir.listFiles((file, s) -> s.toLowerCase(Locale.US).endsWith(Constants.YDK_FILE_EX));
return files;
}
public static List<MyDeckItem> getMyDeckItem() {
List<MyDeckItem> result = new ArrayList<>();
File[] files = getAllYdk();
for (File file : files) {
String deckId = getId(file);
MyDeckItem item = new MyDeckItem();
item.deckName = file.getName();
item.setDeckSouce(0);
item.setDeckPath(file.getPath());
if (deckId != null) {
item.deckId = deckId;
item.idUploaded = 2;
} else {
item.idUploaded = 0;
}
result.add(item);
}
return result;
}
//将卡组id、用户id设置到卡组文件上
//下载卡组后,保存之前将其原有id清除
//上传卡组前,填入新的卡组id、用户id
public static String setDeckId(String deckPath, Integer userId, String deckId) {
StringBuilder contentBuilder = new StringBuilder();
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(deckPath);
InputStreamReader in = null;
in = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(in);
String line = null;
while ((line = reader.readLine()) != null) {
contentBuilder.append(line);
}
String content = contentBuilder.toString();
} catch (Exception e) {
LogUtil.e(TAG, "read 1", e);
} finally {
IOUtils.close(inputStream);
}
String content = contentBuilder.toString();
//先替换XXX用户id
//后替换XX卡组id
String original = "这是##测试1\r\n的内容,还有##测试2\r\n等其他部分";
String modified = original.replaceAll("##(.*?)\r\n", "##替换后的内容\r\n");
System.out.println("修改前: " + original);
System.out.println("修改后: " + modified);
return content;
}
}
......@@ -12,14 +12,14 @@ import androidx.recyclerview.widget.GridLayoutManager;
import cn.garymb.ygomobile.deck_square.api_response.ApiDeckRecord;
import cn.garymb.ygomobile.deck_square.api_response.DeckDetail;
import cn.garymb.ygomobile.lite.R;
import cn.garymb.ygomobile.lite.databinding.FragmentUserOnlineDeckBinding;
import cn.garymb.ygomobile.lite.databinding.FragmentDeckSquareMyDeckBinding;
//打开页面后,先扫描本地的卡组,读取其是否包含deckId,是的话代表平台上可能有
//之后读取平台上的卡组,与本地卡组列表做比较。
public class DeckSquareMyDeckFragment extends Fragment {
private FragmentUserOnlineDeckBinding binding;
private FragmentDeckSquareMyDeckBinding binding;
private MyDeckListAdapter deckListAdapter;
@Override
......@@ -28,13 +28,15 @@ public class DeckSquareMyDeckFragment extends Fragment {
Bundle savedInstanceState
) {
binding = FragmentUserOnlineDeckBinding.inflate(inflater, container, false);
binding = FragmentDeckSquareMyDeckBinding.inflate(inflater, container, false);
deckListAdapter = new MyDeckListAdapter(R.layout.item_deck_info);
deckListAdapter = new MyDeckListAdapter(R.layout.item_my_deck);
GridLayoutManager linearLayoutManager = new GridLayoutManager(getContext(), 2);
binding.listMyDeckInfo.setLayoutManager(linearLayoutManager);
binding.listMyDeckInfo.setAdapter(deckListAdapter);
deckListAdapter.loadData();
binding.refreshData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
......@@ -42,18 +44,11 @@ public class DeckSquareMyDeckFragment extends Fragment {
}
});
binding.uploadDeck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//todo 打开一个dialog
}
});
deckListAdapter.setOnItemClickListener(
(adapter, view, position) -> {
// Handle item click
DeckDetail item = (DeckDetail) adapter.getItem(position);
MyDeckItem item = (MyDeckItem) adapter.getItem(position);
MyDeckDetailDialog dialog = new MyDeckDetailDialog(getContext(), item);
......
......@@ -4,34 +4,30 @@ 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 com.google.gson.Gson;
import android.widget.LinearLayout;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import cn.garymb.ygomobile.AppsSettings;
import cn.garymb.ygomobile.deck_square.api_response.ApiDeckRecord;
import cn.garymb.ygomobile.deck_square.api_response.DeckDetail;
import cn.garymb.ygomobile.deck_square.api_response.DownloadDeckResponse;
import cn.garymb.ygomobile.lite.R;
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;
public class MyDeckDetailDialog extends Dialog {
private static final String TAG = DeckSquareListAdapter.class.getSimpleName();
private String deckId;
private String deckName;
private Integer userId;
// private String deckId;
// private String deckName;
// private Integer userId;
MyDeckItem item;
public interface ActionListener {
void onDownloadClicked();
......@@ -41,11 +37,13 @@ public class MyDeckDetailDialog extends Dialog {
private ActionListener listener;
public MyDeckDetailDialog(Context context, DeckDetail item) {
public MyDeckDetailDialog(Context context, MyDeckItem item) {
super(context);
deckId = item.getDeckId();
deckName = item.getDeckName();
userId = item.getUserId();
// deckId = item.getDeckId();
// deckName = item.getDeckName();
// userId = item.getUserId();
this.item = item;
}
@Override
......@@ -54,36 +52,44 @@ public class MyDeckDetailDialog extends Dialog {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_square_my_deck_detail);
Button btnDownload = findViewById(R.id.btnDownload);
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) {//来自本地
downloadLayout.setVisibility(View.GONE);
uploadLayout.setVisibility(View.VISIBLE);
//btnDownload.setBackground(R.id.ic);
} else if (item.getDeckSouce() == 1) {//来自服务器
downloadLayout.setVisibility(View.VISIBLE);
uploadLayout.setVisibility(View.GONE);
} else if (item.getDeckSouce() == 2) {//来自服务器
downloadLayout.setVisibility(View.VISIBLE);
uploadLayout.setVisibility(View.VISIBLE);
}
btnDownload.setOnClickListener(v -> {
VUiKit.defer().when(() -> {
btnPush.setOnClickListener(v -> {
DownloadDeckResponse result = null;
String url = "http://rarnu.xyz:38383/api/mdpro3/deck/" + deckId;
Integer userId = SharedPreferenceUtil.getServerUserId();
Map<String, String> headers = new HashMap<>();
VUiKit.defer().when(() -> {
DeckSquareApiUtil.pushDeck(item.getDeckPath(),userId);
});//.done();
});
headers.put("ReqSource", "MDPro3");
Response response = null;
try {
response = OkhttpUtil.synchronousGet(url, null, headers);
String responseBodyString = response.body().string();
btnDownload.setOnClickListener(v -> {
VUiKit.defer().when(() -> {
DownloadDeckResponse response = DeckSquareApiUtil.getDeckById(item.getDeckId());
if (response != null) {
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;
return response.getData();
} else {
return result.getData();
return null;
}
}).fail((e) -> {
......@@ -100,7 +106,7 @@ public class MyDeckDetailDialog extends Dialog {
}).done((deckData) -> {
if (deckData != null) {
String path = AppsSettings.get().getDeckDir();
saveFileToPath(path, deckName + ".ydk", deckData.deckYdk);
saveFileToPath(path, item.getDeckName() + ".ydk", deckData.deckYdk);
LogUtil.i(TAG, "square deck detail done");
YGOUtil.showTextToast(R.string.down_complete);
......
package cn.garymb.ygomobile.deck_square;
public class MyDeckItem {
//0代表未推到服务器,3代表包含deckId,1代表服务器存在可下载到本地,2代表已同步
public int idUploaded;
public int userId;
public String deckName;
public String deckId;
public String updateDate;
public int deckSouce;//卡组来源,0代表来自本地,1代表来自服务器
public String deckPath;//本地卡组时,存储卡组路径
public int deckCoverCard1;
public int getIdUploaded() {
return idUploaded;
}
public void setIdUploaded(int idUploaded) {
this.idUploaded = idUploaded;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getDeckName() {
return deckName;
}
public void setDeckName(String deckName) {
this.deckName = deckName;
}
public String getDeckId() {
return deckId;
}
public void setDeckId(String deckId) {
this.deckId = deckId;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
public int getDeckSouce() {
return deckSouce;
}
public void setDeckSouce(int deckSouce) {
this.deckSouce = deckSouce;
}
public int getDeckCoverCard1() {
return deckCoverCard1;
}
public void setDeckCoverCard1(int deckCoverCard1) {
this.deckCoverCard1 = deckCoverCard1;
}
public String getDeckPath() {
return deckPath;
}
public void setDeckPath(String deckPath) {
this.deckPath = deckPath;
}
}
......@@ -3,7 +3,6 @@ package cn.garymb.ygomobile.deck_square;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
......@@ -17,10 +16,9 @@ import cn.garymb.ygomobile.loader.ImageLoader;
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;
//提供“我的”卡组数据,打开后先从sharePreference查询,没有则从服务器查询,然后缓存到sharePreference
public class MyDeckListAdapter extends BaseQuickAdapter<DeckDetail, BaseViewHolder> {
public class MyDeckListAdapter extends BaseQuickAdapter<MyDeckItem, BaseViewHolder> {
private static final String TAG = DeckSquareListAdapter.class.getSimpleName();
private ImageLoader imageLoader;
......@@ -31,6 +29,8 @@ public class MyDeckListAdapter extends BaseQuickAdapter<DeckDetail, BaseViewHold
}
public void loadData() {
List<MyDeckItem> localDecks = DeckSquareFileUtil.getMyDeckItem();
// final DialogPlus dialog_read_ex = DialogPlus.show(getContext(), null, getContext().getString(R.string.fetch_ex_card));
String serverToken = SharedPreferenceUtil.getServerToken();
Integer serverUserId = SharedPreferenceUtil.getServerUserId();
......@@ -57,14 +57,32 @@ public class MyDeckListAdapter extends BaseQuickAdapter<DeckDetail, BaseViewHold
// }
// }
LogUtil.i(TAG, "load mycard from server fail");
}).done((exCardDataList) -> {
if (exCardDataList != null) {
LogUtil.i(TAG, "load mycard from server done");
getData().clear();
addData(exCardDataList);
notifyDataSetChanged();
//只展示本地卡组
getData().clear();
addData(localDecks);
notifyDataSetChanged();
}).done((serverDecks) -> {
// List<MyDeckItem> serverItems = new ArrayList<>();
if (serverDecks != null) {//将服务端的卡组也放到LocalDecks中
for (DeckDetail detail : serverDecks) {
MyDeckItem item = new MyDeckItem();
item.setDeckName(detail.getDeckName());
item.setDeckSouce(1);
item.setDeckId(detail.getDeckId());
item.setUserId(detail.getUserId());
item.setUpdateDate(detail.getDeckUpdateDate());
localDecks.add(item);
}
}
LogUtil.i(TAG, "load mycard from server done");
//展示本地卡组和服务器上的卡组
getData().clear();
addData(localDecks);
notifyDataSetChanged();
// if (dialog_read_ex.isShowing()) {
// try {
// dialog_read_ex.dismiss();
......@@ -85,17 +103,29 @@ public class MyDeckListAdapter extends BaseQuickAdapter<DeckDetail, BaseViewHold
}
@Override
protected void convert(BaseViewHolder helper, DeckDetail item) {
helper.setText(R.id.deck_info_name, item.getDeckName());
helper.setText(R.id.deck_contributor, item.getDeckContributor());
ImageView cardImage = helper.getView(R.id.deck_info_image);
long code = item.getDeckCoverCard1();
LogUtil.i(TAG, code + " " + item.getDeckName());
if (code != 0) {
imageLoader.bindImage(cardImage, code, null, ImageLoader.Type.small);
protected void convert(BaseViewHolder helper, MyDeckItem item) {
helper.setText(R.id.my_deck_name, item.getDeckName());
//helper.setText(R.id.deck_upload_date, item.getDeckUploadDate());
ImageView imageView = helper.getView(R.id.deck_upload_state_img);
if (item.getDeckSouce() == 0) {//本地
helper.setText(R.id.my_deck_id, "本地卡组");
imageView.setImageResource(R.drawable.ic_server_push);
helper.setVisible(R.id.deck_update_date, false);
helper.setVisible(R.id.deck_upload_date, false);
} else if (item.getDeckSouce() == 1) {
helper.setText(R.id.my_deck_id, item.getDeckId());
imageView.setImageResource(R.drawable.ic_server_download);
helper.setText(R.id.deck_update_date, item.getUpdateDate());
}
// long code = item.getDeckCoverCard1();
// LogUtil.i(TAG, code + " " + item.getDeckName());
// if (code != 0) {
// imageLoader.bindImage(cardImage, code, null, ImageLoader.Type.small);
// }
//
// ImageView imageview = helper.getView(R.id.ex_card_image);
//the function cn.garymb.ygomobile.loader.ImageLoader.bindT(...)
//cn.garymb.ygomobile.loader.ImageLoader.setDefaults(...)
......
......@@ -26,6 +26,7 @@ public class DeckDetail implements Parcelable {
public String isPublic;
public String isDelete;
protected DeckDetail(Parcel in) {
deckId = in.readString();
deckContributor = in.readString();
......@@ -220,4 +221,6 @@ public class DeckDetail implements Parcelable {
public void setIsDelete(String isDelete) {
this.isDelete = isDelete;
}
}
\ No newline at end of file
package cn.garymb.ygomobile.deck_square.api_response;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class DeckIdResponse {
@Expose
public int code;
@Expose
public String message;
@Expose
@SerializedName("data")
public String deckId;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDeckId() {
return deckId;
}
public void setDeckId(String deckId) {
this.deckId = deckId;
}
}
......@@ -20,9 +20,11 @@ import java.nio.charset.StandardCharsets;
import cn.garymb.ygomobile.Constants;
import cn.garymb.ygomobile.bean.Deck;
import cn.garymb.ygomobile.bean.DeckInfo;
import cn.garymb.ygomobile.deck_square.DeckSquareListAdapter;
import cn.garymb.ygomobile.ui.cards.deck.DeckItemType;
import cn.garymb.ygomobile.ui.cards.deck.DeckUtils;
import cn.garymb.ygomobile.utils.IOUtils;
import cn.garymb.ygomobile.utils.LogUtil;
import cn.hutool.core.util.ArrayUtil;
import ocgcore.data.Card;
import ocgcore.data.LimitList;
......@@ -35,7 +37,7 @@ public class DeckLoader {
FileInputStream fileinputStream = null;
try {
fileinputStream = new FileInputStream(file);
deckInfo = readDeck(cardLoader, fileinputStream, limitList);
deckInfo = readDeck(cardLoader, fileinputStream);
if (deckInfo != null) {
deckInfo.source = file;
if (isChanged) {
......@@ -51,7 +53,7 @@ public class DeckLoader {
return deckInfo;
}
private static DeckInfo readDeck(CardLoader cardLoader, InputStream inputStream, LimitList limitList) {
private static DeckInfo readDeck(CardLoader cardLoader, InputStream inputStream) {
Deck deck = new Deck();
SparseArray<Integer> mIds = new SparseArray<>();
InputStreamReader in = null;
......@@ -60,6 +62,7 @@ public class DeckLoader {
in = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(in);
String line = null;
//按行读取ydk文件
while ((line = reader.readLine()) != null) {
if (line.startsWith("!side")) {
type = DeckItemType.SideCard;
......
......@@ -1029,6 +1029,7 @@ public class DeckManagerFragment extends BaseFragemnt implements RecyclerViewIte
return null;
}
//从存储卡组的文件夹中获取所有名字以.ydk结尾的文件,并将mPreLoadFile也加入到返回结果中
private List<File> getYdkFiles() {
File dir = new File(mSettings.getResourcePath(), Constants.CORE_DECK_PATH);
File[] files = dir.listFiles((file, s) -> s.toLowerCase(Locale.US).endsWith(Constants.YDK_FILE_EX));
......
......@@ -588,7 +588,7 @@ public class DeckAdapater extends RecyclerView.Adapter<DeckViewHolder> implement
// else
// Toast.makeText(context,"空点击"+position,Toast.LENGTH_SHORT).show();
// }
// });
// });//将cardInfo在LimitList中检查,根据结果(限制、准限制、禁止)对应显示卡图
if (cardInfo != null) {
holder.setCardType(cardInfo.Type);
if (mImageTop == null) {
......
......@@ -20,6 +20,7 @@ import cn.garymb.ygomobile.utils.IOUtils;
import ocgcore.data.Card;
public class DeckUtils {
//将Deck通过ByteArrayOutputStream)转为String
public static String getDeckString(Deck deck) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
save(deck, outputStream);
......@@ -28,6 +29,7 @@ public class DeckUtils {
return str;
}
//将DeckInfo(通过ByteArrayOutputStream)转为String
public static String getDeckString(DeckInfo deck) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
save(deck, outputStream);
......@@ -36,6 +38,13 @@ public class DeckUtils {
return str;
}
/**
* 将DeckInfo对象以ydk文件的格式存入到outputStream对应的文件中
*
* @param deck
* @param outputStream
* @return
*/
private static boolean save(DeckInfo deck, OutputStream outputStream) {
OutputStreamWriter writer = null;
try {
......@@ -64,6 +73,8 @@ public class DeckUtils {
return true;
}
//将Deck对象以ydk文件的格式存入到outputStream对应的文件中
private static boolean save(Deck deck, OutputStream outputStream) {
OutputStreamWriter writer = null;
try {
......@@ -92,6 +103,7 @@ public class DeckUtils {
return true;
}
//将deck对象以ydk文件的格式存入到file对应的文件中
public static boolean save(DeckInfo deck, File file) {
if (deck == null) return false;
FileOutputStream outputStream = null;
......@@ -113,6 +125,7 @@ public class DeckUtils {
return true;
}
//将Deck对象以ydk文件的格式存入到File对应的文件中
public static boolean save(Deck deck, File file) {
if (deck == null) return false;
FileOutputStream outputStream = null;
......@@ -127,7 +140,7 @@ public class DeckUtils {
outputStream = new FileOutputStream(file);
save(deck, outputStream);
} catch (Exception e) {
Log.e("DeckUtil","保存出错"+e);
Log.e("DeckUtil", "保存出错" + e);
//ignore
} finally {
IOUtils.close(outputStream);
......@@ -135,11 +148,12 @@ public class DeckUtils {
return true;
}
public static File save(String name,String deckMessage) throws IOException {
@Deprecated
public static File save(String name, String deckMessage) throws IOException {
FileWriter fw = null;
//如果文件存在,则重写内容;如果文件不存在,则创建文件
File f = new File(AppsSettings.get().getDeckDir(),name + Constants.YDK_FILE_EX);
File f = new File(AppsSettings.get().getDeckDir(), name + Constants.YDK_FILE_EX);
fw = new FileWriter(f, false);
PrintWriter pw = new PrintWriter(fw);
......
......@@ -9,7 +9,6 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import cn.garymb.ygomobile.bean.Header;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
......@@ -34,81 +33,80 @@ public class OkhttpUtil {
// post(address, map, null, oyHeader, tag, timeout, callback);
// }
public static void post(String address, Map<String, Object> map, String cookie, Header oyHeader, String tag, int timeout, Callback callback) {
okHttpClient = new OkHttpClient();
if (timeout != 0)
okHttpClient = okHttpClient.newBuilder().connectTimeout(timeout, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(timeout, TimeUnit.SECONDS)//设置读取超时时间
.build();
MultipartBody.Builder builder1 = new MultipartBody.Builder();
if (map != null) {
builder1.setType(MultipartBody.FORM);
for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
String key = stringObjectEntry.getKey();
Object value = stringObjectEntry.getValue();
if (value instanceof List) {
List list = (List) value;
for (Object object : list) {
if (object instanceof File) {
File file = (File) object;
builder1.addFormDataPart(key
, file.getName(),
RequestBody.create(MediaType.parse("multipart/form-data"), file));
} else {
builder1.addFormDataPart(key, value.toString());
}
}
} else if (value instanceof File) {//如果请求的值是文件
File file = (File) value;
//MediaType.parse("application/octet-stream")以二进制的形式上传文件
builder1.addFormDataPart(key, file.getName(),
RequestBody.create(MediaType.parse("multipart/form-data"), file));
} else if (value instanceof String[]) {
String[] list = (String[]) value;
for (Object object : list) {
if (object instanceof File) {
File file = (File) object;
builder1.addFormDataPart(key
, file.getName(),
RequestBody.create(MediaType.parse("multipart/form-data"), file));
} else {
Log.e("OkHttpUtil", key + "添加数组" + object.toString());
builder1.addFormDataPart(key, object.toString());
}
}
// Log.e("OkhttpUtil","添加数组"+new Gson().toJson(value));
} else {
//如果请求的值是string类型
builder1.addFormDataPart(key, value.toString());
}
}
}
Request.Builder request = new Request.Builder()
.url(address);
if (oyHeader != null)
request = request.header(oyHeader.getName(), oyHeader.getValue());
// request.addHeader("Connection", "keep-alive");
if (!TextUtils.isEmpty(tag))
request = request.tag(tag);
if (map != null)
request.post(builder1.build());
else
request.post(okhttp3.internal.Util.EMPTY_REQUEST);
// Log.e("OkhttpUtil","post请求:"+builder1.build().toString());
if (!TextUtils.isEmpty(cookie)) {
request.addHeader("cookie", cookie);
}
okHttpClient.newCall(request.build()).enqueue(callback);
}
// public static void post(String address, Map<String, Object> map, String cookie, Header oyHeader, String tag, int timeout, Callback callback) {
// okHttpClient = new OkHttpClient();
//
// if (timeout != 0)
// okHttpClient = okHttpClient.newBuilder().connectTimeout(timeout, TimeUnit.SECONDS)//设置连接超时时间
// .readTimeout(timeout, TimeUnit.SECONDS)//设置读取超时时间
// .build();
//
// MultipartBody.Builder builder1 = new MultipartBody.Builder();
// if (map != null) {
// builder1.setType(MultipartBody.FORM);
// for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
// String key = stringObjectEntry.getKey();
// Object value = stringObjectEntry.getValue();
// if (value instanceof List) {
// List list = (List) value;
// for (Object object : list) {
// if (object instanceof File) {
// File file = (File) object;
// builder1.addFormDataPart(key
// , file.getName(),
// RequestBody.create(MediaType.parse("multipart/form-data"), file));
// } else {
// builder1.addFormDataPart(key, value.toString());
// }
// }
// } else if (value instanceof File) {//如果请求的值是文件
// File file = (File) value;
// //MediaType.parse("application/octet-stream")以二进制的形式上传文件
// builder1.addFormDataPart(key, file.getName(),
// RequestBody.create(MediaType.parse("multipart/form-data"), file));
// } else if (value instanceof String[]) {
//
// String[] list = (String[]) value;
// for (Object object : list) {
// if (object instanceof File) {
// File file = (File) object;
// builder1.addFormDataPart(key
// , file.getName(),
// RequestBody.create(MediaType.parse("multipart/form-data"), file));
// } else {
// Log.e("OkHttpUtil", key + "添加数组" + object.toString());
// builder1.addFormDataPart(key, object.toString());
// }
// }
//// Log.e("OkhttpUtil","添加数组"+new Gson().toJson(value));
// } else {
// //如果请求的值是string类型
// builder1.addFormDataPart(key, value.toString());
// }
// }
// }
// Request.Builder request = new Request.Builder()
// .url(address);
// if (oyHeader != null)
// request = request.header(oyHeader.getName(), oyHeader.getValue());
//
//// request.addHeader("Connection", "keep-alive");
//
// if (!TextUtils.isEmpty(tag))
// request = request.tag(tag);
// if (map != null)
// request.post(builder1.build());
// else
// request.post(okhttp3.internal.Util.EMPTY_REQUEST);
//
//
/// / Log.e("OkhttpUtil","post请求:"+builder1.build().toString());
// if (!TextUtils.isEmpty(cookie)) {
// request.addHeader("cookie", cookie);
// }
// okHttpClient.newCall(request.build()).enqueue(callback);
// }
public static void put(String address, Map<String, Object> map, String cookie, Callback callback) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
......@@ -286,11 +284,8 @@ public class OkhttpUtil {
}
}
public static void postJson(String url, String json, Callback callback) {
postJson(url, json, null, null, null, 0, callback);
}
public static void postJson(String url, String json, String cookie, Header oyHeader, String tag, int timeout, Callback callback) {
public static void postJson(String url, String json, Map<String, String> headers, int timeout, Callback callback) {
okHttpClient = new OkHttpClient();
if (timeout != 0)
......@@ -308,15 +303,12 @@ public class OkhttpUtil {
else
request.post(requestBody);
if (oyHeader != null)
request = request.header(oyHeader.getName(), oyHeader.getValue());
if (!TextUtils.isEmpty(tag))
request = request.tag(tag);
if (!TextUtils.isEmpty(cookie)) {
request.addHeader("cookie", cookie);
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
request.addHeader(header.getKey(), header.getValue().toString());
}
}
Log.e("OkhttpUtil", json + " 状态 " + request.build());
okHttpClient.newCall(request.build()).enqueue(callback);
}
......
......@@ -15,15 +15,44 @@
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnDownload"
style="@style/Widget.AppCompat.Button.Borderless"
<LinearLayout
android:id="@+id/server_download_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:drawableStart="@drawable/ic_download"
android:drawablePadding="8dp"
android:text="Upload" />
android:orientation="horizontal">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/ic_server_download" />
<Button
android:id="@+id/dialog_my_deck_btn_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/Download" />
</LinearLayout>
<LinearLayout
android:id="@+id/server_upload_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/ic_server_push" />
<Button
android:id="@+id/dialog_my_deck_btn_push"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/upload" />
</LinearLayout>
<Button
android:id="@+id/btnLike"
......
......@@ -31,12 +31,12 @@
android:layout_gravity="right|bottom"
android:text="刷新"></Button>
<Button
<!-- <Button
android:id="@+id/upload_deck"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center|bottom"
android:text="上传卡组"></Button>
android:text="上传卡组"></Button>-->
</FrameLayout>
<!--<com.google.android.material.floatingactionbutton.FloatingActionButton
......
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_height="wrap_content"
android:background="@color/holo_blue_bright"
android:orientation="vertical">
<ImageView
android:id="@+id/deck_info_image"
android:layout_width="@dimen/card_width_middle"
android:layout_height="@dimen/card_height_middle" />
<!-- <ImageView
android:id="@+id/deck_info_image"
android:layout_width="@dimen/card_width_middle"
android:layout_height="@dimen/card_height_middle" />-->
<TextView
android:id="@+id/deck_upload_state"
android:id="@+id/my_deck_id"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/deck_id"
android:id="@+id/deck_type_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/deck_info_name"
android:id="@+id/my_deck_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
......@@ -37,13 +37,29 @@
android:orientation="horizontal">
<TextView
android:id="@+id/deck_contributor"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="更新时间" />
<TextView
android:id="@+id/deck_update_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/deck_last_date"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="上传时间" />
<TextView
android:id="@+id/deck_upload_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
......@@ -54,16 +70,33 @@
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/deck_upload_state_img"
android:layout_width="40dp"
android:layout_height="40dp" />
<TextView
android:id="@+id/text_download_precard"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/ic_like"
android:clickable="false"
android:gravity="center"
android:textAlignment="center"
android:textColor="@color/gold"
android:textSize="10sp" />
android:id="@+id/upload_state"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- <TextView-->
<!-- android:id="@+id/text_download_precard"-->
<!-- android:layout_width="30dp"-->
<!-- android:layout_height="30dp"-->
<!-- android:clickable="false"-->
<!-- android:gravity="center"-->
<!-- android:textAlignment="center"-->
<!-- android:textColor="@color/gold"-->
<!-- android:text="点赞数"-->
<!-- android:textSize="10sp" />-->
<TextView
android:id="@+id/deck_like"
......
......@@ -368,4 +368,5 @@
<string name="down_complete">下载完成</string>
<string name="upload">上传</string>
</resources>
......@@ -427,4 +427,5 @@
</string>
<string name="down_complete">download complete</string>
<string name="upload">upload</string>
</resources>
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