package de.thedevstack.conversationsplus.services.filetransfer.http.download; import java.io.IOException; import java.io.OutputStream; import de.thedevstack.android.logcat.Logging; import de.thedevstack.conversationsplus.entities.DownloadableFile; import de.thedevstack.conversationsplus.enums.FileStatus; import de.thedevstack.conversationsplus.persistance.FileBackend; import de.thedevstack.conversationsplus.services.AbstractConnectionManager; import de.thedevstack.conversationsplus.utils.MessageUtil; import de.thedevstack.conversationsplus.utils.StreamUtil; import de.thedevstack.conversationsplus.utils.XmppConnectionServiceAccessor; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * */ public class HttpFileDownloadCallback implements Callback { private HttpDownloadFileTransferEntity entity; public HttpFileDownloadCallback(HttpDownloadFileTransferEntity entity) { this.entity = entity; } @Override public void onFailure(Call call, IOException e) { changeStatus(FileStatus.DOWNLOAD_FAILED); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Logging.d("http-download", "Receiving file from remote host"); DownloadableFile file = this.entity.getFile(); OutputStream os = AbstractConnectionManager.createOutputStream(file, true); os.write(response.body().bytes()); StreamUtil.close(os); FileBackend.updateMediaScanner(file, XmppConnectionServiceAccessor.xmppConnectionService); this.entity.transferred(); MessageUtil.updateFileParams(this.entity.getMessage()); changeStatus(FileStatus.DOWNLOADED); } else { Logging.e("http-download", "Failed to retrieve file from remote host. HTTP response: " + response.code() + ", " + response.body().string()); changeStatus(FileStatus.DOWNLOAD_FAILED); } if (entity.wakeLock.isHeld()) { entity.wakeLock.release(); } } private void changeStatus(FileStatus status) { MessageUtil.setAndSaveFileStatus(this.entity.getMessage(), status); } }