|
package ai.pai.lensman.session;
import android.os.AsyncTask;
import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import ai.pai.lensman.BuildConfig;
import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.bean.SessionBean;
import ai.pai.lensman.db.DBService;
import ai.pai.lensman.utils.BoxUrlContainer;
import ai.pai.lensman.utils.Constants;
import ai.pai.lensman.utils.HttpPostTask;
public class SessionInteractor {
private SessionBean sessionBean;
private Timer timer;
private SessionListener listener;
private HttpPostTask sessionStartTask;
private HttpPostTask sessionEndTask;
private String randomSessionId;
private long maxId = 0;
private boolean isWorking;
private boolean isLastQueryReturned = true;
private static final String TAG = "SessionInteractor";
public SessionInteractor(SessionBean sessionBean, SessionListener listener) {
this.listener = listener;
this.sessionBean = sessionBean;
}
public interface SessionListener {
void onSessionStartSuccess(String session);
void onSessionStartError(String session);
void onSessionPhotoCaptured(PhotoBean bean);
void onSessionEnd(String session);
}
public void startSession(){
LogHelper.d(TAG,"startSession");
if(BuildConfig.isTestMode){
isWorking = true;
listener.onSessionStartSuccess(sessionBean.sessionId);
startCapture();
return;
}
cancelTask(sessionStartTask);
ArrayList<PhotoBean> photoList = DBService.getInstance().getPhotoListBySessionId(sessionBean.sessionId);
if(photoList!=null && photoList.size()>0){
for(PhotoBean photoBean : photoList){
if(photoBean.photoId>maxId){
maxId = photoBean.photoId;
}
}
}
HashMap<String,String> params = new HashMap<>();
params.put("lensman",sessionBean.lensmanId);
randomSessionId = sessionBean.sessionId+"_"+(new Random().nextInt(9999)+10000);
params.put("session",randomSessionId);
sessionStartTask = new HttpPostTask(params){
@Override
protected boolean parseResponse(String response) {
LogHelper.d(TAG,"startSession get response string = "+response);
try{
JSONObject json = new JSONObject(response);
int status = json.getInt("status");
if(status == 200){
return true;
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
@Override
protected void onPostFail() {
LogHelper.d(TAG,"sessionStartTask onPostFail sessionId = "+randomSessionId);
super.onPostFail();
listener.onSessionStartError(sessionBean.sessionId);
}
@Override
protected void onPostSuccess() {
super.onPostSuccess();
listener.onSessionStartSuccess(sessionBean.sessionId);
isWorking = true;
LogHelper.d(TAG,"sessionStartTask onPostSuccess sessionId = "+randomSessionId + "and startCapture");
startCapture();
}
};
sessionStartTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), BoxUrlContainer.SESSION_START_URL);
LogHelper.d(TAG,"startSession sessionStartTask execute");
}
public void startCapture() {
if(timer!=null){
timer.cancel();
timer = null;
}
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
fetchThumbnailTask();
}
},1000,1000);
}
private void fetchThumbnailTask(){
if(!isWorking){
return;
}
if(!isLastQueryReturned){
return;
}
if(BuildConfig.isTestMode){
PhotoBean bean = new PhotoBean();
long milisec = System.currentTimeMillis();
bean.photoName = milisec+".jpg";
bean.photoId = milisec;
if(milisec%5==0){
bean.photoPath = "http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1408/11/c0/37303155_1407746429945_800x600.jpg";
}else if(milisec%5==1){
bean.photoPath ="http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1408/07/c0/37179063_1407421362265_800x600.jpg";
}else if(milisec%5==2){
bean.photoPath ="http://h.hiphotos.baidu.com/zhidao/pic/item/6d81800a19d8bc3ed69473cb848ba61ea8d34516.jpg";
}else if(milisec%5==3){
bean.photoPath ="http://img.boqiicdn.com/Data/BK/A/1607/25/imagick97881469425045_y.jpg";
}else{
bean.photoPath = "http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1408/11/c0/37303160_1407746433139_800x600.jpg";
}
bean.captureTime = bean.photoId;
bean.isRawPhoto = false;
bean.uploadStatus = PhotoBean.UploadStatus.STATUS_NO_BEGIN;
bean.sessionId = sessionBean.sessionId;
bean.lensmanId = sessionBean.lensmanId;
bean.sessionSeq = sessionBean.sessionSeq;
bean.sessionDate = sessionBean.sessionDate;
new SavePhotoTask(bean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),bean);
return;
}
HashMap<String,String> params = new HashMap<>();
params.put("lensman",sessionBean.lensmanId);
params.put("session",randomSessionId);
params.put("maxid",String.valueOf(maxId));
HttpPostTask fetchThumbnailTask = new HttpPostTask(params){
ArrayList<PhotoBean> photoList = new ArrayList<>();
@Override
protected boolean parseResponse(String response) {
LogHelper.d(TAG,"fetchThumbnailTask get response string = "+response);
try{
JSONObject json = new JSONObject(response);
int status = json.getInt("status");
if(status == 200){
JSONObject data = json.getJSONObject("data");
JSONArray files = data.getJSONArray("files");
if(files!=null && files.length()>0){
for(int k = 0 ; k< files.length();k++){
JSONObject file = files.getJSONObject(k);
PhotoBean bean = new PhotoBean();
bean.photoName = file.getString("name");
bean.photoId = file.getLong("id");
bean.photoPath = file.getString("path");
bean.captureTime = bean.photoId;
bean.isRawPhoto = false;
bean.uploadStatus = PhotoBean.UploadStatus.STATUS_NO_BEGIN;
bean.sessionId = sessionBean.sessionId;
bean.lensmanId = sessionBean.lensmanId;
bean.sessionSeq = sessionBean.sessionSeq;
bean.sessionDate = sessionBean.sessionDate;
if(bean.photoId>maxId){
maxId = bean.photoId;
}
photoList.add(bean);
}
}
return true;
}
}catch (Exception e){
LogHelper.e(TAG,"fetchThumbnailTask exception occurs "+e);
}
return false;
}
@Override
protected void onPostFail() {
LogHelper.d(TAG,"fetchThumbnailTask onPostFail");
super.onPostFail();
isLastQueryReturned = true;
}
@Override
protected void onPostSuccess() {
super.onPostSuccess();
isLastQueryReturned = true;
LogHelper.d(TAG,"fetchThumbnailTask onPostSuccess with photo number = "+photoList.size());
for(PhotoBean bean :photoList){
new SavePhotoTask(bean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),bean);
LogHelper.d(TAG,"SavePhotoTask starts "+bean);
}
}
};
fetchThumbnailTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), BoxUrlContainer.FETCH_THUMBNAIL_URL);
isLastQueryReturned = false;
LogHelper.d(TAG,"fetchThumbnailTask starts");
}
class SavePhotoTask extends AsyncTask<PhotoBean, Integer, Boolean> {
private PhotoBean photoBean;
public SavePhotoTask(PhotoBean bean){
this.photoBean = bean;
}
@Override
protected Boolean doInBackground(PhotoBean... params) {
PhotoBean photoBean = params[0];
String path = BoxUrlContainer.PHOTO_PATH_PREFIX_URL+photoBean.photoPath;
if(BuildConfig.isTestMode){
path = photoBean.photoPath;
}
LogHelper.d(TAG,"SavePhotoTask save photo to phone , photo remote url = "+path);
FileOutputStream fOut = null;
HttpURLConnection conn = null;
InputStream inStream = null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
inStream = conn.getInputStream();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
String dirPath = Constants.APP_IMAGE_DIR +File.separator+photoBean.sessionId+File.separator+Constants.THUMBNAIL_DIR_NAME;
File dir = new File(dirPath);
dir.mkdirs();
File file = new File(dir, photoBean.photoName);
fOut = new FileOutputStream(file);
byte[] buffer = new byte[2048];
int len ;
while((len=inStream.read(buffer))!=-1){
fOut.write(buffer,0,len);
fOut.flush();
}
fOut.flush();
LogHelper.d(TAG,"SavePhotoTask save photo to local path = "+file.getAbsolutePath()+" photo bytes = "+file.length()+"\n");
}
return true;
} catch (Exception e) {
LogHelper.e(TAG,"SavePhotoTask exception occurs "+e);
} finally {
try{
inStream.close();
conn.disconnect();
fOut.close();
}catch (Exception e){
e.printStackTrace();
}
}
try{
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
LogHelper.d(TAG,"SavePhotoTask onPostExecute success " + photoBean);
listener.onSessionPhotoCaptured(photoBean);
}else{
LogHelper.d(TAG,"SavePhotoTask onPostExecute fail and retry "+photoBean);
new SavePhotoTask(photoBean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),photoBean);
}
}
}
public void endSession(){
isWorking = false;
if(timer!=null){
timer.cancel();
timer = null;
}
cancelTask(sessionEndTask);
HashMap<String,String> params = new HashMap<>();
params.put("lensman",sessionBean.lensmanId);
params.put("session",randomSessionId);
sessionEndTask = new HttpPostTask(params);
sessionEndTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), BoxUrlContainer.SESSION_END_URL);
LogHelper.d(TAG,"sessionEndTask execute ");
listener.onSessionEnd(sessionBean.sessionId);
}
public void deletePhoto(PhotoBean photoBean){
HashMap<String,String> params = new HashMap<>();
params.put("lensman",photoBean.lensmanId);
params.put("session",photoBean.sessionId);
params.put("id",String.valueOf(photoBean.photoId));
params.put("name",photoBean.photoName);
params.put("path",photoBean.photoPath);
HttpPostTask deleteTask = new HttpPostTask(params);
deleteTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), BoxUrlContainer.DELETE_PHOTO_URL);
LogHelper.d(TAG,"deletePhoto execute "+photoBean);
}
private void cancelTask(HttpPostTask task){
if(task==null){
return;
}
if(task.getStatus()== AsyncTask.Status.RUNNING){
task.cancel(true);
}
}
}
|