use of com.squareup.okhttp.Request in project storymaker by StoryMaker.
the class StorymakerDownloadManager method downloadWithTor.
private void downloadWithTor(boolean useTor, Uri uri, String title, String desc, File targetFile) {
initNotificationManager();
// generate id/tag for notification
String nTag = indexItem.getExpansionId();
int nId = 0;
if (fileName.contains(scal.io.liger.Constants.MAIN)) {
nId = Integer.parseInt(indexItem.getExpansionFileVersion());
} else if (fileName.contains(scal.io.liger.Constants.PATCH)) {
nId = Integer.parseInt(indexItem.getPatchFileVersion());
}
// incompatible with lungcast certificate
// StrongHttpsClient httpClient = getHttpClientInstance();
OkHttpClient httpClient = new OkHttpClient();
// we're now using this method to support non-tor downloads as well, so settings must be checked
if (useTor) {
if (checkTor(context)) {
Timber.d("DOWNLOAD WITH TOR PROXY: " + scal.io.liger.Constants.TOR_PROXY_HOST + "/" + scal.io.liger.Constants.TOR_PROXY_PORT);
SocketAddress torSocket = new InetSocketAddress(scal.io.liger.Constants.TOR_PROXY_HOST, scal.io.liger.Constants.TOR_PROXY_PORT);
Proxy torProxy = new Proxy(Proxy.Type.HTTP, torSocket);
httpClient.setProxy(torProxy);
} else {
Timber.e("CANNOT DOWNLOAD WITH TOR, TOR IS NOT ACTIVE");
if (context instanceof Activity) {
// FIXME move to strings
Utils.toastOnUiThread((Activity) context, "Check settings, can't use tor if orbot isn't running", true);
}
StorymakerQueueManager.checkQueueFinished(context, targetFile.getName());
return;
}
}
// disable attempts to retry (more retries ties up connection and prevents failure handling)
httpClient.setRetryOnConnectionFailure(false);
// set modest timeout (longer timeout ties up connection and prevents failure handling)
httpClient.setConnectTimeout(3000, TimeUnit.MILLISECONDS);
String actualFileName = targetFile.getName().substring(0, targetFile.getName().lastIndexOf("."));
Timber.d("CHECKING URI: " + uri.toString());
try {
// FIXME - adding the "Connection: close" header to resolve an issue that seemed to be caused
// FIXME - by a lingering connection. when possible, the better solution would be to track
// FIXME - down the possible end states and add appropriate cleanup steps.
Request request = new Request.Builder().url(uri.toString()).addHeader("Connection", "close").build();
// check for partially downloaded file
File partFile = new File(targetFile.getPath().replace(".tmp", ".part"));
if (partFile.exists()) {
long partBytes = partFile.length();
Timber.d("PARTIAL FILE " + partFile.getPath() + " FOUND, SETTING RANGE HEADER: " + "Range" + " / " + "bytes=" + Long.toString(partBytes) + "-");
// request.setHeader("Range", "bytes=" + Long.toString(partBytes) + "-");
request = new Request.Builder().url(uri.toString()).addHeader("Connection", "close").addHeader("Range", "bytes=" + Long.toString(partBytes) + "-").build();
} else {
Timber.d("PARTIAL FILE " + partFile.getPath() + " NOT FOUND, STARTING AT BYTE 0");
}
Response response = httpClient.newCall(request).execute();
int statusCode = response.code();
if ((statusCode == 200) || (statusCode == 206)) {
Timber.d("DOWNLOAD SUCCEEDED, STATUS CODE: " + statusCode);
// queue item here, "download" doesn't start until after we get a status code
// queue item, use date to get a unique long, subtract to get a negative number (to distinguish from download manager items)
Date startTime = new Date();
long queueId = 0 - startTime.getTime();
StorymakerQueueManager.addToQueue(context, queueId, targetFile.getName(), queueDao);
targetFile.getParentFile().mkdirs();
Timber.d("DOWNLOAD SUCCEEDED, GETTING ENTITY...");
BufferedInputStream responseInput = new BufferedInputStream(response.body().byteStream());
try {
FileOutputStream targetOutput = new FileOutputStream(targetFile);
byte[] buf = new byte[1024];
int i;
int oldPercent = 0;
long thisTime;
long lastTime = -1;
int lastPercent = 0;
while ((i = responseInput.read(buf)) > 0) {
// create status bar notification
int nPercent = StorymakerDownloadHelper.getDownloadPercent(context, fileName, installedDao);
thisTime = System.currentTimeMillis();
if (oldPercent == nPercent) {
// need to cut back on notification traffic
} else {
if (nPercent % 10 == 0 && nPercent != lastPercent) {
if (lastTime == -1 || (thisTime - lastTime) > 1000) {
lastPercent = nPercent;
oldPercent = nPercent;
lastTime = thisTime;
Notification nProgress = new Notification.Builder(context).setContentTitle(mAppTitle + " content download").setContentText(// assignment file names are meaningless uuids
indexItem.getTitle() + " - " + (nPercent / 10.0) + "%").setSmallIcon(android.R.drawable.arrow_down_float).setProgress(100, (nPercent / 10), false).setWhen(startTime.getTime()).build();
nManager.notify(nTag, nId, nProgress);
// Log.d("Storymaker Download Manager", "** NOTIFICATION ** " + nPercent );
}
}
}
targetOutput.write(buf, 0, i);
}
targetOutput.close();
responseInput.close();
Timber.d("SAVED DOWNLOAD TO " + targetFile);
} catch (ConnectTimeoutException cte) {
Timber.e(cte, "FAILED TO SAVE DOWNLOAD TO " + actualFileName + " (CONNECTION EXCEPTION)");
} catch (SocketTimeoutException ste) {
Timber.e(ste, "FAILED TO SAVE DOWNLOAD TO " + actualFileName + " (SOCKET EXCEPTION)");
} catch (IOException ioe) {
Timber.e(ioe, "FAILED TO SAVE DOWNLOAD TO " + actualFileName + " (IO EXCEPTION)");
}
// remove from queue here, regardless of success
StorymakerQueueManager.removeFromQueue(context, queueId, queueDao);
// remove notification, regardless of success
nManager.cancel(nTag, nId);
// (assumes .tmp file will exist if download is interrupted)
if (!handleFile(targetFile)) {
Timber.e("ERROR DURING FILE PROCESSING FOR " + actualFileName);
}
} else {
Timber.e("DOWNLOAD FAILED FOR " + actualFileName + ", STATUS CODE: " + statusCode);
StorymakerQueueManager.checkQueueFinished(context, targetFile.getName());
}
// clean up connection
// EntityUtils.consume(entity);
// request.abort();
// request.releaseConnection();
} catch (IOException ioe) {
Timber.e(ioe, "DOWNLOAD FAILED FOR " + actualFileName + ", EXCEPTION THROWN");
StorymakerQueueManager.checkQueueFinished(context, targetFile.getName());
}
}
use of com.squareup.okhttp.Request in project Android-IMSI-Catcher-Detector by CellularPrivacy.
the class RequestTask method doInBackground.
@Override
protected String doInBackground(String... commandString) {
// We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
switch(mType) {
// OCID upload request from "APPLICATION" drawer title
case DBE_UPLOAD_REQUEST:
try {
@Cleanup Realm realm = Realm.getDefaultInstance();
boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);
log.info("OCID upload data prepared - " + String.valueOf(prepared));
if (prepared) {
File file = new File((mAppContext.getExternalFilesDir(null) + File.separator) + "OpenCellID/aimsicd-ocid-data.csv");
publishProgress(25, 100);
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile", "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file)).build();
Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv").post(requestBody).build();
publishProgress(60, 100);
Response response = okHttpClient.newCall(request).execute();
publishProgress(80, 100);
if (response != null) {
log.info("OCID Upload Response: " + response.code() + " - " + response.message());
if (response.code() == 200) {
Realm.Transaction transaction = mDbAdapter.ocidProcessed();
realm.executeTransaction(transaction);
}
publishProgress(95, 100);
}
return "Successful";
} else {
Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
return null;
}
// all caused by httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
log.error("Upload OpenCellID data Exception", e);
} catch (FileNotFoundException e) {
log.error("Upload OpenCellID data Exception", e);
} catch (IOException e) {
log.error("Upload OpenCellID data Exception", e);
} catch (Exception e) {
log.error("Upload OpenCellID data Exception", e);
}
// DOWNLOADING...
case // OCID download request from "APPLICATION" drawer title
DBE_DOWNLOAD_REQUEST:
mTimeOut = REQUEST_TIMEOUT_MENU;
case // OCID download request from "Antenna Map Viewer"
DBE_DOWNLOAD_REQUEST_FROM_MAP:
int count;
try {
long total;
int progress = 0;
String dirName = getOCDBDownloadDirectoryPath(mAppContext);
File dir = new File(dirName);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, OCDB_File_Name);
log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);
Request request = new Request.Builder().url(commandString[0]).get().build();
Response response;
try {
// OCID's API can be slow. Give it up to a minute to do its job. Since this
// is a backgrounded task, it's ok to wait for a while.
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
response = okHttpClient.newCall(request).execute();
// Restore back to default
okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
} catch (SocketTimeoutException e) {
log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
return "Timeout";
}
if (response.code() != 200) {
try {
String error = response.body().string();
Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
log.error("Download OCID data error: " + error);
} catch (Exception e) {
Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + e.getClass().getName() + " - " + e.getMessage());
log.error("Download OCID exception: ", e);
}
return "Error";
} else {
// This returns "-1" for streamed response (Chunked Transfer Encoding)
total = response.body().contentLength();
if (total == -1) {
log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
// Let's set it arbitrarily to something other than "-1"
total = 1024;
} else {
log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
// Let's show something!
publishProgress((int) (0.25 * total), (int) total);
}
FileOutputStream output = new FileOutputStream(file, false);
InputStream input = new BufferedInputStream(response.body().byteStream());
byte[] data = new byte[1024];
while ((count = input.read(data)) > 0) {
// writing data to file
output.write(data, 0, count);
progress += count;
publishProgress(progress, (int) total);
}
input.close();
// flushing output
output.flush();
output.close();
}
return "Successful";
} catch (IOException e) {
log.warn("Problem reading data from steam", e);
return null;
}
}
return null;
}
use of com.squareup.okhttp.Request in project Android-IMSI-Catcher-Detector by CellularPrivacy.
the class DeviceFragment method onRefresh.
@Override
public void onRefresh() {
if (CellTracker.OCID_API_KEY != null && !CellTracker.OCID_API_KEY.equals("NA")) {
Request request = createOpenCellIdApiCall();
okHttpClient.newCall(request).enqueue(getOpenCellIdResponseCallback());
} else {
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
Helpers.sendMsg(getActivity(), getString(R.string.no_opencellid_key_detected));
swipeRefreshLayout.setRefreshing(false);
}
});
}
}
use of com.squareup.okhttp.Request in project Android-IMSI-Catcher-Detector by CellularPrivacy.
the class DeviceFragment method getOpenCellIdResponseCallback.
@NonNull
private Callback getOpenCellIdResponseCallback() {
return new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
refreshFailed();
}
});
}
@Override
public void onResponse(final Response response) throws IOException {
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
Cell cell = responseToCell(response);
processFinish(cell);
}
});
}
};
}
use of com.squareup.okhttp.Request in project SimpleNews by liuling07.
the class OkHttpUtils method buildPostRequest.
private Request buildPostRequest(String url, List<Param> params) {
FormEncodingBuilder builder = new FormEncodingBuilder();
for (Param param : params) {
builder.add(param.key, param.value);
}
RequestBody requestBody = builder.build();
return new Request.Builder().url(url).post(requestBody).build();
}
Aggregations