Commit 5a167240 authored by wangfugui's avatar wangfugui

完善同步功能

parent b38428bf
......@@ -250,7 +250,7 @@ public class DeckSquareApiUtil {
pushSingleDeck.setDeck(deckData);
String json = gson.toJson(pushSingleDeck);
Response response = OkhttpUtil.postJson(url, json, headers, 1000);
Response response = OkhttpUtil.postJson(url, json, headers);
String responseBodyString = response.body().string();
result = gson.fromJson(responseBodyString, PushDeckResponse.class);
......@@ -281,7 +281,7 @@ public class DeckSquareApiUtil {
pushMultiDeck.setDecks(deckDataList);
String json = gson.toJson(pushMultiDeck);
Response response = OkhttpUtil.postJson(url, json, headers, 1000);
Response response = OkhttpUtil.postJson(url, json, headers);
String responseBodyString = response.body().string();
result = gson.fromJson(responseBodyString, SyncDecksResponse.class);
......@@ -326,7 +326,7 @@ public class DeckSquareApiUtil {
pushMultiDeck.setDecks(dataList);
String json = gson.toJson(pushMultiDeck);
Response response = OkhttpUtil.postJson(url, json, headers, 1000);
Response response = OkhttpUtil.postJson(url, json, headers);
String responseBodyString = response.body().string();
result = gson.fromJson(responseBodyString, SyncDecksResponse.class);
......@@ -347,7 +347,7 @@ public class DeckSquareApiUtil {
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);
Response response = OkhttpUtil.postJson(url, null, headers);
String responseBodyString = response.body().string();
Gson gson = new Gson();
......@@ -382,7 +382,7 @@ public class DeckSquareApiUtil {
String json = gson.toJson(pushData);
Response response = OkhttpUtil.postJson(url, json, headers, 1000);
Response response = OkhttpUtil.postJson(url, json, headers);
String responseBodyString = response.body().string();
result = gson.fromJson(responseBodyString, BasicResponse.class);
......@@ -457,7 +457,7 @@ public class DeckSquareApiUtil {
String json = gson.toJson(pushSingleDeck);
Response response = OkhttpUtil.postJson(url, json, headers, 1000);
Response response = OkhttpUtil.postJson(url, json, headers);
String responseBodyString = response.body().string();
// Convert JSON to Java object using Gson
......@@ -524,11 +524,18 @@ public class DeckSquareApiUtil {
if (onlineUpdateDate > localUpdateDate) {
// 在线卡组更新时间更晚,下载在线卡组覆盖本地卡组
LogUtil.w(TAG, "sync-download deck: " + localDeck.getDeckName());
downloadOnlineDeck(onlineDeck, localDeck.getDeckPath(), onlineUpdateDate);
} else {
} else if (onlineUpdateDate == localUpdateDate) {
LogUtil.w(TAG, "no need to sync deck: " + localDeck.getDeckName());
//时间戳相同,不需要更新
} else if (onlineUpdateDate < localUpdateDate) {
// 本地卡组更新时间更晚,上传本地卡组覆盖在线卡组
// uploadLocalDeck(localDeck, onlineDeck.getDeckId(), loginToken);
LogUtil.w(TAG, "sync-upload deck: " + localDeck.getDeckName());
localDeck.setDeckId(onlineDeck.getDeckId());
toUploadDecks.add(localDeck);
result.toUpload.add(localDeck);
......@@ -542,8 +549,10 @@ public class DeckSquareApiUtil {
// 处理只存在于在线的卡组(即本地没有同名卡组)
for (MyOnlineDeckDetail onlineDeck : onlineDecks) {
result.download.add(onlineDeck);
if (!onlineDeckProcessed.get(onlineDeck.getDeckName())) {
result.download.add(onlineDeck);
LogUtil.w(TAG, "sync-download new deck: " + onlineDeck.getDeckName());
SyncMutliDeckResult.DownloadResult downloadResult = downloadMissingDeckToLocal(onlineDeck, convertToUnixTimestamp(onlineDeck.getDeckUpdateDate()));
result.downloadResponse.add(downloadResult);
}
......@@ -626,7 +635,8 @@ public class DeckSquareApiUtil {
MyOnlineDeckDetail deckDetail = deckResponse.getData();
String deckContent = deckDetail.getDeckYdk();
// 保存在线卡组到本地
String fileName = onlineDeck.getDeckName() + Constants.YDK_FILE_EX;
// 保存在线卡组到本地
boolean saved = DeckSquareFileUtil.saveFileToPath(localPath, onlineDeck.getDeckName(), deckContent, onlineUpdateDate);
if (!saved) {
......
......@@ -87,12 +87,49 @@ public class DeckSquareFileUtil {
return deckId;
}
//查询卡组目录下的所有ydk文件,返回File[]
/**
* 查询卡组目录下的所有ydk文件(包含子文件夹)
*
* @return 包含所有ydk文件的File数组
*/
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));
if (!dir.exists() || !dir.isDirectory()) {
return new File[0];
}
// 使用ArrayList存储结果,方便动态添加
ArrayList<File> ydkFiles = new ArrayList<>();
// 递归遍历目录和子目录
findYdkFiles(dir, ydkFiles);
// 将ArrayList转换为File数组
return ydkFiles.toArray(new File[0]);
}
/**
* 递归查找指定目录下的所有YDK文件
*
* @param dir 当前查找的目录
* @param ydkFiles 存储找到的YDK文件
*/
private static void findYdkFiles(File dir, ArrayList<File> ydkFiles) {
// 获取目录下的所有文件和子目录
File[] files = dir.listFiles();
if (files == null) {
return; // 目录不可访问或为空
}
return files;
for (File file : files) {
if (file.isDirectory()) {
// 如果是子目录,递归查找
findYdkFiles(file, ydkFiles);
} else {
// 如果是文件,检查是否为YDK文件
String fileName = file.getName().toLowerCase(Locale.US);
if (fileName.endsWith(Constants.YDK_FILE_EX)) {
ydkFiles.add(file);
}
}
}
}
//读取卡组目录下的所有ydk文件,解析ydk文件(包括从ydk文件内容中读取deckId),生成List<MyDeckItem>解析结果
......@@ -170,12 +207,21 @@ public class DeckSquareFileUtil {
return content;
}
/**
* 保存文件到指定路径,并设置指定的最后修改时间
*
* @param path 保存路径
* @param fileName 文件名
* @param content 文件内容
* @param modificationTime 期望的最后修改时间(毫秒时间戳)
* @return 保存是否成功
*/
public static boolean saveFileToPath(String path, String fileName, String content, long modificationTime) {
FileOutputStream fos = null;
try {
// 创建文件对象
File file = new File(path, fileName);
File file = new File(path);
fos = new FileOutputStream(file);
// 创建文件输出流
// 写入内容
fos.write(content.getBytes());
......@@ -186,6 +232,9 @@ public class DeckSquareFileUtil {
boolean timeSet = file.setLastModified(modificationTime);
if (!timeSet) {
LogUtil.w(TAG, "设置文件修改时间失败: " + file.getPath());
} else {
LogUtil.w(TAG, "设置文件修改时间成功: " + file.getPath());
}
} catch (Exception e) {
LogUtil.e(TAG, "保存文件失败", e);
......
......@@ -3,7 +3,6 @@ package cn.garymb.ygomobile.utils;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
......@@ -11,11 +10,11 @@ import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
......@@ -23,68 +22,15 @@ import okhttp3.Response;
public class OkhttpUtil {
private static OkHttpClient okHttpClient;
public static void put(String address, Map<String, Object> map, String cookie, Callback callback) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
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 (map != null)
request.put(builder1.build());
else
request.put(okhttp3.internal.Util.EMPTY_REQUEST);
// Log.e("OkhttpUtil","post请求:"+builder1.build().toString());
if (!TextUtils.isEmpty(cookie)) {
request.addHeader("cookie", cookie);
}
client.build().newCall(request.build()).enqueue(callback);
}
// private static OkHttpClient okHttpClient;
private static final OkHttpClient client = new OkHttpClient.Builder()
// customize timeouts as needed
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
// keep-alive and connection pool defaults
.connectionPool(new ConnectionPool(2, 40, TimeUnit.SECONDS))
.build();
public static void get(String address, Callback callback) {
......@@ -96,7 +42,6 @@ public class OkhttpUtil {
}
public static void get(String address, Map<String, Object> map, String cookie, Callback callback) {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder httpBuilder = HttpUrl.parse(address).newBuilder();
if (map != null) {
......@@ -115,7 +60,6 @@ public class OkhttpUtil {
}
public static Response synchronousGet(String address, Map<String, Object> paramMap, Map<String, String> headers) throws IOException {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder httpBuilder = HttpUrl.parse(address).newBuilder();
if (paramMap != null) {
......@@ -139,7 +83,6 @@ public class OkhttpUtil {
}
public static void del(String address, Map<String, Object> map, String cookie, Callback callback) {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder httpBuilder = HttpUrl.parse(address).newBuilder();
if (map != null) {
......@@ -174,7 +117,6 @@ 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
if (TextUtils.isEmpty(json))
......@@ -184,16 +126,16 @@ public class OkhttpUtil {
if (!TextUtils.isEmpty(cookie)) {
request.addHeader("cookie", cookie);
}
okHttpClient.newCall(request.build()).enqueue(callback);
client.newCall(request.build()).enqueue(callback);
}
public static void cancelTag(Object tag) {
for (Call call : okHttpClient.dispatcher().queuedCalls()) {
for (Call call : client.dispatcher().queuedCalls()) {
if (tag.equals(call.request().tag())) {
call.cancel();
}
}
for (Call call : okHttpClient.dispatcher().runningCalls()) {
for (Call call : client.dispatcher().runningCalls()) {
if (tag.equals(call.request().tag())) {
call.cancel();
}
......@@ -206,16 +148,8 @@ public class OkhttpUtil {
* @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)
okHttpClient = okHttpClient.newBuilder().connectTimeout(timeout, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(timeout, TimeUnit.SECONDS)//设置读取超时时间
.build();
public static Response postJson(String url, String json, Map<String, String> headers) throws IOException {
Request.Builder request = new Request.Builder().url(url);//请求的url
if (json == null || TextUtils.isEmpty(json)) {
......@@ -233,7 +167,7 @@ public class OkhttpUtil {
}
Log.e("OkhttpUtil", json + " 状态 " + request.build());
return okHttpClient.newCall(request.build()).execute();
return client.newCall(request.build()).execute();
}
/**
......
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