From 596d0bcbacd8dde70f0bbcfdf07db5cf694220ef Mon Sep 17 00:00:00 2001
From: zuoxiao <470321431@qq.com>
Date: 星期三, 08 一月 2025 09:33:20 +0800
Subject: [PATCH] 1.修复上传文件取消上传还会上传bug 2.添加上传视频功能 3.添加关闭activity时关闭上传功能。

---
 app/src/main/java/com/dayu/pipirrapp/net/ApiManager.java |  297 ++++++++++++++++++++++++++++++++++++++++++++++++----------
 1 files changed, 244 insertions(+), 53 deletions(-)

diff --git a/app/src/main/java/com/dayu/pipirrapp/net/ApiManager.java b/app/src/main/java/com/dayu/pipirrapp/net/ApiManager.java
index 58a4dd0..7e5671c 100644
--- a/app/src/main/java/com/dayu/pipirrapp/net/ApiManager.java
+++ b/app/src/main/java/com/dayu/pipirrapp/net/ApiManager.java
@@ -1,15 +1,36 @@
 package com.dayu.pipirrapp.net;
 
+import static com.dayu.pipirrapp.bean.net.UplodFileState.STATE_DONE;
+import static com.dayu.pipirrapp.bean.net.UplodFileState.STATE_ERROR;
+import static com.dayu.pipirrapp.bean.net.UplodFileState.STATE_UPDING;
+import static com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread;
+
+import android.annotation.SuppressLint;
 import android.content.Context;
+import android.content.Intent;
+import android.text.TextUtils;
 import android.util.Log;
 
-import com.dayu.pipirrapp.bean.WeatherResponse;
+import com.dayu.pipirrapp.MyApplication;
+import com.dayu.pipirrapp.activity.LoginActivity;
+import com.dayu.pipirrapp.adapter.AddPictureAdapter;
+import com.dayu.pipirrapp.bean.net.CodeResult;
+import com.dayu.pipirrapp.bean.net.UplodFileState;
+import com.dayu.pipirrapp.bean.net.WeatherResponse;
 import com.dayu.pipirrapp.net.subscribers.BaseProgressSubscriber;
+import com.dayu.pipirrapp.net.subscribers.CodeListener;
 import com.dayu.pipirrapp.net.subscribers.ProgressSubscriber;
 import com.dayu.pipirrapp.net.subscribers.SubscriberListener;
+import com.dayu.pipirrapp.net.upload.ProgressRequestBody;
+import com.dayu.pipirrapp.net.upload.UploadFileListener;
+import com.dayu.pipirrapp.utils.CleanDataUtils;
 import com.dayu.pipirrapp.utils.MapJpgUtils;
 import com.dayu.pipirrapp.utils.MyJsonParser;
+import com.dayu.pipirrapp.utils.MyLog;
+import com.dayu.pipirrapp.utils.NetUtils;
+import com.google.gson.internal.LinkedTreeMap;
 
+import java.io.File;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -19,9 +40,13 @@
 import io.reactivex.rxjava3.disposables.CompositeDisposable;
 import io.reactivex.rxjava3.functions.Function;
 import io.reactivex.rxjava3.schedulers.Schedulers;
+import okhttp3.MediaType;
+import okhttp3.MultipartBody;
+import okhttp3.RequestBody;
 import okhttp3.ResponseBody;
 import retrofit2.Call;
 import retrofit2.Callback;
+import retrofit2.Response;
 
 
 /**
@@ -39,7 +64,8 @@
     int uplodFilerepeatSize = 3;
 
     ApiService apiService;
-    private CompositeDisposable compositeDisposable = new CompositeDisposable(); // 绠$悊璁㈤槄浜嬩欢
+    // 绠$悊璁㈤槄浜嬩欢
+    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
 
     /**
      * 鍒濆鍖栭�氫俊妗嗘灦
@@ -72,6 +98,14 @@
         request(context, false, path, false, tClass, params, listener);
     }
 
+    public <T> void requestGet(final Context context, final String path, final Class<T> tClass, final Map<String, Object> params, final SubscriberListener listener) {
+        request(context, false, path, true, tClass, params, listener);
+    }
+
+    public <T> void requestGetHideLoading(final Context context, final String path, final Class<T> tClass, final Map<String, Object> params, final SubscriberListener listener) {
+        request(context, true, path, true, tClass, params, listener);
+    }
+
     /**
      * 鍙戦�佽姹�
      *
@@ -91,10 +125,9 @@
 
         if (isGet) {
             if (params == null) {
-                observable = apiService.requestGet(path);
+                observable = apiService.requestGet(path, MyApplication.myApplication.token);
             } else {
-
-                observable = apiService.requestGet(path, params);
+                observable = apiService.requestGet(path, params, MyApplication.myApplication.token);
             }
         } else {
             observable = apiService.requestPost(path, params);
@@ -107,37 +140,31 @@
                     public BaseResponse<T> apply(Object o) {
                         if (o instanceof BaseResponse) {
                             BaseResponse tem = (BaseResponse) o;
+                            if (tem.getCode().equals(Constants.TOKEN_INVALID)) {
+                                //褰揷ode涓�0000鏄烦杞埌鐧诲綍鐣岄潰
+                                tem.setMsg("鐧诲綍澶辨晥璇烽噸鏂扮櫥褰�");
+                                redirectToLogin();
+                                return tem;
+                            }
                             BaseResponse<T> response = new BaseResponse<>();
                             response.setCode(tem.getCode());
-                            response.setMsg(tem.getMsg());
-
-                            if (tClass != null && tem.getContent() instanceof Map) {
-                                try {
-//                                    response.setData(MyJsonParser.getBeanFromMap((Map<String, Object>) tem.getData(), tClass));
-                                    String jsonData = MyJsonParser.getJsontoMap((Map) tem.getContent());
-                                    response.setContent(MyJsonParser.getBeanFromJson(jsonData, tClass));
-                                } catch (Exception e) {
-                                    e.printStackTrace();
-                                }
-                            } else if (tClass != null && tem.getContent() instanceof List) {
-                                try {
-                                    response.setContent((T) MyJsonParser.getListByJson(MyJsonParser.getJsonbyList((List) tem.getContent()), tClass));
-                                } catch (Exception e) {
-                                    e.printStackTrace();
-                                }
-                            } else if (tClass != null && tem.getContent() instanceof Integer) {
-                                response.setContent((T) tem.getContent());
+                            if (!TextUtils.isEmpty(tem.getMsg())) {
+                                response.setMsg(tem.getMsg());
+                            } else {
+                                response.setMsg("");
                             }
-                            if (tClass != null && tClass.getName() instanceof String && tem.getContent() instanceof String) {
-                                try {
+
+
+                            if (tClass != null) {
+                                if (tem.getContent() instanceof Map) {
+                                    response.setContent(parseMapContent(tem.getContent(), tClass));
+                                } else if (tem.getContent() instanceof List) {
+                                    response.setContent(parseListContent(tem.getContent(), tClass));
+                                } else if (tem.getContent() instanceof Integer || tem.getContent() instanceof String) {
                                     response.setContent((T) tem.getContent());
-                                } catch (Exception e) {
-                                    e.printStackTrace();
                                 }
                             }
                             return response;
-
-
                         }
 
                         return null;
@@ -147,6 +174,29 @@
                 .observeOn(AndroidSchedulers.mainThread())
                 .subscribe(mySubscriber);
 
+    }
+
+
+    // 瑙f瀽 Map 绫诲瀷鐨勬暟鎹�
+    private <T> T parseMapContent(Object content, Class<T> tClass) {
+        try {
+            String jsonData = MyJsonParser.getJsontoMap((Map<String, Object>) content);
+            return MyJsonParser.getBeanFromJson(jsonData, tClass);
+        } catch (Exception e) {
+            Log.e(TAG, "Error parsing map content", e);
+            return null;
+        }
+    }
+
+    // 瑙f瀽 List 绫诲瀷鐨勬暟鎹�
+    private <T> T parseListContent(Object content, Class<T> tClass) {
+        try {
+            String jsonData = MyJsonParser.getJsonbyList((List<?>) content);
+            return (T) MyJsonParser.getListByJson(jsonData, tClass);
+        } catch (Exception e) {
+            Log.e(TAG, "Error parsing list content", e);
+            return null;
+        }
     }
 
 
@@ -169,32 +219,65 @@
     }
 
 
+    /**
+     * 鑾峰彇楠岃瘉鐮�
+     *
+     * @param params
+     * @param listener
+     * @param <T>
+     */
+    public <T> void getCode(Map<String, Object> params, CodeListener listener) {
+        if (NetUtils.isNetworkAvailable(MyApplication.myApplication)) {
+            Observable observable;
+            observable = apiService.getCode(params);
+            observable.subscribeOn(Schedulers.io())
+                    .unsubscribeOn(Schedulers.newThread())
+                    .observeOn(AndroidSchedulers.mainThread())
+                    .subscribe(responseBody -> {
+                        listener.onNext((CodeResult) responseBody);
+                    }, throwable -> {
+                        listener.error((Throwable) throwable);
+                    });
+        } else {
+            listener.onNext(null);
+        }
+
+    }
+
+
+    /**
+     * 涓嬭浇鍦板浘鐡︾墖
+     *
+     * @param urlPath
+     */
+    @SuppressLint("CheckResult")
     public void donwLoadTile(Context context, String urlPath) {
-        Observable<ResponseBody> observable;
-        observable = apiService.downloadTile(urlPath);
+        if (NetUtils.isNetworkAvailable(context)) {
+            Observable<ResponseBody> observable;
+            observable = apiService.downloadTile(urlPath);
+            observable
+                    // 缃戠粶璇锋眰鍦� I/O 绾跨▼涓繘琛�
+                    .subscribeOn(Schedulers.io())
+                    // 鍥炶皟澶勭悊涔熷湪 I/O 绾跨▼
+                    .observeOn(Schedulers.io())
+                    .subscribe(
+                            responseBody -> {
 
-
-        compositeDisposable.add(
-                observable
-                        .subscribeOn(Schedulers.io())  // 缃戠粶璇锋眰鍦� I/O 绾跨▼涓繘琛�
-                        .observeOn(Schedulers.io())    // 鍥炶皟澶勭悊涔熷湪 I/O 绾跨▼
-                        .subscribe(
-                                responseBody -> {
-                                    boolean success = false;
-                                    if (!MapJpgUtils.getInsatance(context).isHasFiles(urlPath)) {
-                                        success = MapJpgUtils.getInsatance(context).saveTileToCache(urlPath, responseBody);
-                                    }
-                                    if (success) {
-                                        Log.d(TAG, "Download success for tile: " + urlPath);
-                                    } else {
-                                        Log.e(TAG, "Failed to save tile to disk: " + urlPath);
-                                    }
-                                },
-                                throwable -> Log.e(TAG, "Download failed for tile: " + urlPath)
-                        )
-        );
-
-
+                                boolean success = false;
+                                if (!MapJpgUtils.getInsatance().isHasFiles(urlPath)) {
+                                    success = MapJpgUtils.getInsatance().saveTileToCache(urlPath, responseBody);
+                                }
+                                if (success) {
+                                    Log.d(TAG, "Download success for tile: " + urlPath);
+                                } else {
+                                    Log.e(TAG, "Failed to save tile to disk: " + urlPath);
+                                }
+                            },
+                            throwable -> Log.e(TAG, "Download failed for tile: " + urlPath)
+                    );
+        } else {
+            Log.e(TAG, "娌℃湁缃戠粶涓嶄笅杞�: " + urlPath);
+        }
     }
 
     // 鍋滄绾跨▼姹狅紝閲婃斁璧勬簮
@@ -204,4 +287,112 @@
         }
     }
 
+
+//    public void uploadFile(final Context context, final UplodFileState uplodData, final UploadFileListener listener) {
+//        uploadFile(context, uplodData, listener, null);
+//    }
+
+    /**
+     * 涓婁紶鍥剧墖鏂囦欢
+     *
+     * @param context
+     * @param uplodData
+     * @param listener
+     */
+    public void uploadFile(final Context context, final UplodFileState uplodData, final UploadFileListener listener, final AddPictureAdapter adapter) {
+
+        if (!TextUtils.isEmpty(uplodData.getFilePath())) {
+            MyLog.d("progressRequestBody>>>" + "path:" + uplodData.getFilePath()+">>>uploadType:"+uplodData.getUploadType());
+            uplodData.setState(STATE_UPDING);
+            File file = new File(uplodData.getFilePath());
+            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
+            ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, (bytesWritten, contentLength, done) -> {
+//            MyLog.d("progressRequestBody>>>" + "bytesWritten:" + bytesWritten + ">>>contentLength: " + contentLength );
+                // 鏇存柊杩涘害鏉℃垨杩涜鍏朵粬鎿嶄綔
+                int progress = (int) (100 * bytesWritten / contentLength);
+                // 渚嬪锛氭洿鏂� ProgressBar 鎴栨樉绀鸿繘搴�
+                runOnUiThread(() -> {
+                    uplodData.setProgress(progress);
+                    // 杩涘害鏉℃洿鏂颁唬鐮�
+                    if (adapter != null && uplodData.getAdapterPosition() != -1) {
+                        adapter.updateProgress(uplodData);
+                    }
+                    MyLog.d("progressRequestBody>>>" + "adapterPosition:" + uplodData.getAdapterPosition() + ">>>涓婁紶杩涘害: " + progress + "%");
+                });
+
+            });
+            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), progressRequestBody);
+            RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "file description");
+            Call<BaseResponse> uploadFile = null;
+            switch (uplodData.getUploadType()) {
+                case UplodFileState.IMG_TYPE:
+                    uploadFile = apiService.uploadImgFile(body, description);
+                    break;
+                case UplodFileState.VIDEO_TYPE:
+                    uploadFile = apiService.uploadVideoFile(body, description);
+                    break;
+                default:
+                    uploadFile = apiService.uploadImgFile(body, description);
+                    break;
+            }
+
+            uplodData.setThisCall(uploadFile);
+            uploadFile.enqueue(new Callback<BaseResponse>() {
+                @Override
+                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
+                    if (response.body() != null) {
+                        if (response.body().isSuccess()) {
+                            uplodData.setState(STATE_DONE);
+                            uplodData.setPostId(((LinkedTreeMap) response.body().getContent()).get("id").toString());
+                            uplodData.setWebPath(((LinkedTreeMap) response.body().getContent()).get("webPath").toString());
+                            listener.onBack(uplodData);
+                        } else {
+                            MyLog.d("progressRequestBody>>>" + response.body().getMsg());
+                            if (uplodData.getNumber() <= uplodFilerepeatSize) {
+                                uplodData.setNumber(uplodData.getNumber() + 1);
+                                uplodData.setState(STATE_ERROR);
+                                uploadFile(context, uplodData, listener, adapter);
+                            } else {
+                                uplodData.setState(STATE_ERROR);
+                                uplodData.setNumber(0);
+                                listener.onBack(uplodData);
+                            }
+                        }
+                    }
+                }
+
+                @Override
+                public void onFailure(Call<BaseResponse> call, Throwable t) {
+                    MyLog.d("progressRequestBody>>>" + "onFailure:" + t.getMessage());
+                    if (!t.getMessage().equals("Canceled")) {
+                        uplodData.setState(STATE_ERROR);
+                        if (uplodData.getNumber() <= uplodFilerepeatSize) {
+                            uplodData.setNumber(uplodData.getNumber() + 1);
+                            uploadFile(context, uplodData, listener, adapter);
+                        } else {
+                            uplodData.setNumber(0);
+                            listener.onBack(uplodData);
+                        }
+                    }
+
+                }
+            });
+        } else {
+            uplodData.setState(STATE_ERROR);
+            listener.onBack(uplodData);
+        }
+    }
+
+
+    /**
+     * 褰揷ode涓衡��0000鈥濇椂璺宠浆鍒扮櫥褰曠晫闈�
+     */
+    private void redirectToLogin() {
+
+        Context context = MyApplication.myApplication.getApplicationContext();
+        CleanDataUtils.cleanUserData(context);
+        Intent intent = new Intent(context, LoginActivity.class); // Assuming LoginActivity is your login screen
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // Clear task stack
+        context.startActivity(intent);
+    }
 }
\ No newline at end of file

--
Gitblit v1.8.0