");
+
for (int i = 1; i < files.length; i++) {
-
- String[] fileDetails = files[i].replace(">","").split("", "").split("
- *
*/
public class DLinkRouterBTAdapter implements IDaemonAdapter {
@@ -115,54 +114,54 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
try {
switch (task.getMethod()) {
- case Retrieve:
+ case Retrieve:
- // Request all torrents from server
- JSONObject result = makeRequest(API_GET);
- return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result),null);
+ // Request all torrents from server
+ JSONObject result = makeRequest(log, API_GET);
+ return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result), null);
- case GetFileList:
+ case GetFileList:
- // Request all details for a specific torrent
- JSONObject result2 = makeRequest(API_GET_FILES + task.getTargetTorrent().getUniqueID());
- return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFileList(result2, task
- .getTargetTorrent().getUniqueID()));
+ // Request all details for a specific torrent
+ JSONObject result2 = makeRequest(log, API_GET_FILES + task.getTargetTorrent().getUniqueID());
+ return new GetFileListTaskSuccessResult((GetFileListTask) task,
+ parseJsonFileList(result2, task.getTargetTorrent().getUniqueID()));
- case AddByFile:
+ case AddByFile:
- // Add a torrent to the server by sending the contents of a local .torrent file
- String file = ((AddByFileTask) task).getFile();
+ // Add a torrent to the server by sending the contents of a local .torrent file
+ String file = ((AddByFileTask) task).getFile();
- // put .torrent file's data into the request
- makeRequest(API_ADD_BY_FILE, new File(URI.create(file)));
- return new DaemonTaskSuccessResult(task);
+ // put .torrent file's data into the request
+ makeRequest(log, API_ADD_BY_FILE, new File(URI.create(file)));
+ return new DaemonTaskSuccessResult(task);
- case AddByUrl:
+ case AddByUrl:
- // Request to add a torrent by URL
- String url = ((AddByUrlTask) task).getUrl();
- makeRequest(API_ADD + url);
- return new DaemonTaskSuccessResult(task);
+ // Request to add a torrent by URL
+ String url = ((AddByUrlTask) task).getUrl();
+ makeRequest(log, API_ADD + url);
+ return new DaemonTaskSuccessResult(task);
- case Remove:
+ case Remove:
- // Remove a torrent
- RemoveTask removeTask = (RemoveTask) task;
- makeRequest(API_REMOVE + removeTask.getTargetTorrent().getUniqueID()
- + (removeTask.includingData() ? API_DEL_DATA + "yes" : ""), false);
- return new DaemonTaskSuccessResult(task);
+ // Remove a torrent
+ RemoveTask removeTask = (RemoveTask) task;
+ makeRequest(log, API_REMOVE + removeTask.getTargetTorrent().getUniqueID() +
+ (removeTask.includingData() ? API_DEL_DATA + "yes" : ""), false);
+ return new DaemonTaskSuccessResult(task);
// case Stop:
- case Pause:
+ case Pause:
- // Pause a torrent
- PauseTask pauseTask = (PauseTask) task;
- makeRequest(API_STOP + pauseTask.getTargetTorrent().getUniqueID(), false);
- return new DaemonTaskSuccessResult(task);
+ // Pause a torrent
+ PauseTask pauseTask = (PauseTask) task;
+ makeRequest(log, API_STOP + pauseTask.getTargetTorrent().getUniqueID(), false);
+ return new DaemonTaskSuccessResult(task);
// case PauseAll:
@@ -172,12 +171,12 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
// return new DaemonTaskSuccessResult(task);
// case Start:
- case Resume:
+ case Resume:
- // Resume a torrent
- ResumeTask resumeTask = (ResumeTask) task;
- makeRequest(API_START + resumeTask.getTargetTorrent().getUniqueID(), false);
- return new DaemonTaskSuccessResult(task);
+ // Resume a torrent
+ ResumeTask resumeTask = (ResumeTask) task;
+ makeRequest(log, API_START + resumeTask.getTargetTorrent().getUniqueID(), false);
+ return new DaemonTaskSuccessResult(task);
// case ResumeAll:
@@ -206,10 +205,9 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
// makeRequest( RPC_METHOD_SESSIONSET );
// return new DaemonTaskSuccessResult(task);
- default:
- return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task
- .getMethod()
- + " is not supported by " + getType()));
+ default:
+ return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
+ task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
@@ -218,31 +216,31 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
}
}
- private JSONObject makeRequest(String requestUrl, File upload) throws DaemonException {
- return makeRequest(requestUrl, false, upload);
+ private JSONObject makeRequest(Log log, String requestUrl, File upload) throws DaemonException {
+ return makeRequest(log, requestUrl, false, upload);
}
- private JSONObject makeRequest(String requestUrl) throws DaemonException {
- return makeRequest(requestUrl, true, null);
+ private JSONObject makeRequest(Log log, String requestUrl) throws DaemonException {
+ return makeRequest(log, requestUrl, true, null);
}
- private JSONObject makeRequest(String requestUrl, boolean hasRespond) throws DaemonException {
- return makeRequest(requestUrl, hasRespond, null);
+ private JSONObject makeRequest(Log log, String requestUrl, boolean hasRespond) throws DaemonException {
+ return makeRequest(log, requestUrl, hasRespond, null);
}
- private JSONObject makeRequest(String requestUrl, boolean hasRespond, File upload) throws DaemonException {
+ private JSONObject makeRequest(Log log, String requestUrl, boolean hasRespond, File upload) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
- initialise(HttpHelper.DEFAULT_CONNECTION_TIMEOUT);
+ initialise();
}
// Setup request using POST stream with URL and data
HttpPost httppost = new HttpPost(buildWebUIUrl() + requestUrl);
if (upload != null) {
- Part[] parts = { new FilePart(BT_ADD_BY_FILE, upload) };
+ Part[] parts = {new FilePart(BT_ADD_BY_FILE, upload)};
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
}
@@ -264,8 +262,9 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
response = httpclient.execute(httppost);
}
- if (!hasRespond)
+ if (!hasRespond) {
return null;
+ }
HttpEntity entity = response.getEntity();
if (entity != null) {
@@ -276,24 +275,24 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
JSONObject json = new JSONObject(result);
instream.close();
- DLog.d(LOG_NAME, "Success: "
- + (result.length() > 300 ? result.substring(0, 300) + "... (" + result.length() + " chars)"
- : result));
+ log.d(LOG_NAME, "Success: " +
+ (result.length() > 300 ? result.substring(0, 300) + "... (" + result.length() + " chars)" :
+ result));
// Return the JSON object
return json;
}
- DLog.d(LOG_NAME, "Error: No entity in HTTP response");
+ log.d(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
} catch (DaemonException e) {
throw e;
} catch (JSONException e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.UnexpectedResponse, e.toString());
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
@@ -301,39 +300,40 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
/**
* Instantiates an HTTP client with proper credentials that can be used for all Transmission requests.
- *
- * @param connectionTimeout
- * The connection timeout in milliseconds
- * @throws DaemonException
- * On conflicting or missing settings
+ * @throws DaemonException On conflicting or missing settings
*/
- private void initialise(int connectionTimeout) throws DaemonException {
+ private void initialise() throws DaemonException {
httpclient = HttpHelper.createStandardHttpClient(settings, true);
}
/**
* Build the URL of the Transmission web UI from the user settings.
- *
* @return The URL of the RPC API
*/
private String buildWebUIUrl() {
- return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort()
- + PATH_TO_API;
+ return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() +
+ PATH_TO_API;
}
private TorrentStatus convertStatus(String state) {
- if ("allocating".equals(state))
+ if ("allocating".equals(state)) {
return TorrentStatus.Checking;
- if ("seeding".equals(state))
+ }
+ if ("seeding".equals(state)) {
return TorrentStatus.Seeding;
- if ("finished".equals(state))
+ }
+ if ("finished".equals(state)) {
return TorrentStatus.Downloading;
- if ("connecting_to_tracker".equals(state))
+ }
+ if ("connecting_to_tracker".equals(state)) {
return TorrentStatus.Checking;
- if ("queued_for_checking".equals(state))
+ }
+ if ("queued_for_checking".equals(state)) {
return TorrentStatus.Queued;
- if ("downloading".equals(state))
+ }
+ if ("downloading".equals(state)) {
return TorrentStatus.Downloading;
+ }
return TorrentStatus.Unknown;
}
@@ -345,15 +345,18 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
for (int i = 0; i < rarray.length(); i++) {
JSONObject tor = rarray.getJSONObject(i);
// Add the parsed torrent to the list
- TorrentStatus status = TorrentStatus.Unknown;
- if (tor.getInt(BT_STOPPED) == 1)
+ TorrentStatus status;
+ if (tor.getInt(BT_STOPPED) == 1) {
status = TorrentStatus.Paused;
- else
+ } else {
status = convertStatus(tor.getString(BT_STATE));
- int eta = (int) (tor.getLong(BT_SIZE) / (tor.getInt(BT_DOWNLOAD_RATE) + 1));
- if (0 > eta)
+ }
+ int eta = (int) ((tor.getLong(BT_SIZE) - tor.getLong(BT_DONE)) / (tor.getInt(BT_DOWNLOAD_RATE) + 1));
+ if (0 > eta) {
eta = -1;
+ }
+ // @formatter:off
Torrent new_t = new Torrent(
i,
tor.getString(BT_HASH),
@@ -366,17 +369,18 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
tor.getInt(BT_PEERS_TOTAL),
tor.getInt(BT_SEEDS_CONNECTED),
tor.getInt(BT_SEEDS_TOTAL),
- (int) ((tor.getLong(BT_SIZE) - tor.getLong(BT_DONE)) / (tor.getInt(BT_DOWNLOAD_RATE) + 1)),
+ eta,
tor.getLong(BT_DONE),
tor.getLong(BT_PAYLOAD_UPLOAD),
tor.getLong(BT_SIZE),
- (float) (tor.getLong(BT_DONE) / (float) tor.getLong(BT_SIZE)),
+ tor.getLong(BT_DONE) / (float) tor.getLong(BT_SIZE),
Float.parseFloat(tor.getString(BT_COPYS)),
null,
null,
null,
null,
settings.getType());
+ // @formatter:on
torrents.add(new_t);
}
@@ -395,15 +399,16 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
JSONArray files = jobj.getJSONArray(hash); // "Hash id"
for (int i = 0; i < files.length(); i++) {
JSONObject file = files.getJSONObject(i);
+ // @formatter:off
torrentfiles.add(new TorrentFile(
- i + "",
- // TODO: How is an individual file identified? Index in the array?
+ String.valueOf(i),
file.getString(BT_FILE_NAME),
file.getString(BT_FILE_NAME),
null, // Not supported?
file.getLong(BT_FILE_SIZE),
file.getLong(BT_FILE_DONE),
convertTransmissionPriority(file.getInt(BT_FILE_PRIORITY))));
+ // @formatter:on
}
}
@@ -414,12 +419,12 @@ public class DLinkRouterBTAdapter implements IDaemonAdapter {
private Priority convertTransmissionPriority(int priority) {
switch (priority) {
- case 1:
- return Priority.High;
- case -1:
- return Priority.Low;
- default:
- return Priority.Normal;
+ case 1:
+ return Priority.High;
+ case -1:
+ return Priority.Low;
+ default:
+ return Priority.Normal;
}
}
diff --git a/app/src/main/java/org/transdroid/daemon/Daemon.java b/app/src/main/java/org/transdroid/daemon/Daemon.java
index e4d5cc92..c19fe717 100644
--- a/app/src/main/java/org/transdroid/daemon/Daemon.java
+++ b/app/src/main/java/org/transdroid/daemon/Daemon.java
@@ -306,7 +306,7 @@ public enum Daemon {
}
public static boolean supportsSetTransferRates(Daemon type) {
- return type == Deluge || type == Transmission || type == uTorrent || type == BitTorrent || type == Deluge || type == rTorrent || type == Vuze || type == BuffaloNas || type == BitComet || type == Aria2 || type == Dummy;
+ return type == Deluge || type == Transmission || type == uTorrent || type == BitTorrent || type == rTorrent || type == Vuze || type == BuffaloNas || type == BitComet || type == Aria2 || type == Dummy;
}
public static boolean supportsAddByFile(Daemon type) {
@@ -351,7 +351,7 @@ public enum Daemon {
}
public static boolean supportsForceRecheck(Daemon type) {
- return type == uTorrent || type == BitTorrent || type == Deluge || type == rTorrent || type == Dummy;
+ return type == uTorrent || type == BitTorrent || type == Deluge || type == rTorrent || type == Transmission || type == Dummy;
}
public static boolean supportsExtraPassword(Daemon type) {
diff --git a/app/src/main/java/org/transdroid/daemon/Deluge/DelugeAdapter.java b/app/src/main/java/org/transdroid/daemon/Deluge/DelugeAdapter.java
index 2c7972dd..2d0be0a0 100644
--- a/app/src/main/java/org/transdroid/daemon/Deluge/DelugeAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Deluge/DelugeAdapter.java
@@ -17,19 +17,12 @@
*/
package org.transdroid.daemon.Deluge;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
+import com.android.internalcopy.http.multipart.FilePart;
+import com.android.internalcopy.http.multipart.MultipartEntity;
+import com.android.internalcopy.http.multipart.Part;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
-import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
@@ -38,6 +31,7 @@ import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonException.ExceptionType;
@@ -70,18 +64,21 @@ import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetLabelTask;
import org.transdroid.daemon.task.SetTrackersTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
-import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
-import com.android.internalcopy.http.multipart.FilePart;
-import com.android.internalcopy.http.multipart.MultipartEntity;
-import com.android.internalcopy.http.multipart.Part;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
/**
* The daemon adapter from the Deluge torrent client.
- *
* @author erickok
- *
*/
public class DelugeAdapter implements IDaemonAdapter {
@@ -89,7 +86,7 @@ public class DelugeAdapter implements IDaemonAdapter {
private static final String PATH_TO_RPC = "/json";
private static final String PATH_TO_UPLOAD = "/upload";
-
+
private static final String RPC_ID = "id";
private static final String RPC_METHOD = "method";
private static final String RPC_PARAMS = "params";
@@ -141,34 +138,30 @@ public class DelugeAdapter implements IDaemonAdapter {
private static final String RPC_LABEL = "label";
private static final String RPC_TRACKERS = "trackers";
private static final String RPC_TRACKER_STATUS = "tracker_status";
-
+ private static final String[] RPC_FIELDS_ARRAY =
+ new String[]{RPC_NAME, RPC_STATUS, RPC_SAVEPATH, RPC_RATEDOWNLOAD, RPC_RATEUPLOAD, RPC_NUMPEERS,
+ RPC_NUMSEEDS, RPC_TOTALPEERS, RPC_TOTALSEEDS, RPC_ETA, RPC_DOWNLOADEDEVER, RPC_UPLOADEDEVER,
+ RPC_TOTALSIZE, RPC_PARTDONE, RPC_LABEL, RPC_MESSAGE, RPC_TIMEADDED, RPC_TRACKER_STATUS};
private static final String RPC_DETAILS = "files";
private static final String RPC_INDEX = "index";
private static final String RPC_PATH = "path";
private static final String RPC_SIZE = "size";
private static final String RPC_FILEPROGRESS = "file_progress";
private static final String RPC_FILEPRIORITIES = "file_priorities";
-
- private static final String[] RPC_FIELDS_ARRAY = new String[] {
- RPC_NAME, RPC_STATUS, RPC_SAVEPATH, RPC_RATEDOWNLOAD, RPC_RATEUPLOAD,
- RPC_NUMPEERS, RPC_NUMSEEDS, RPC_TOTALPEERS,
- RPC_TOTALSEEDS, RPC_ETA, RPC_DOWNLOADEDEVER, RPC_UPLOADEDEVER,
- RPC_TOTALSIZE, RPC_PARTDONE, RPC_LABEL, RPC_MESSAGE, RPC_TIMEADDED, RPC_TRACKER_STATUS };
-
private DaemonSettings settings;
private DefaultHttpClient httpclient;
private Cookie sessionCookie;
- private int version = -1;
-
+ private int version = -1;
+
public DelugeAdapter(DaemonSettings settings) {
this.settings = settings;
}
- public JSONArray AddTorrentByFile(String file) throws JSONException, ClientProtocolException, IOException, DaemonException {
+ public JSONArray addTorrentByFile(String file, Log log) throws JSONException, IOException, DaemonException {
String url = buildWebUIUrl() + PATH_TO_UPLOAD;
-
- DLog.d(LOG_NAME, "Uploading a file to the Deluge daemon: " + url);
+
+ log.d(LOG_NAME, "Uploading a file to the Deluge daemon: " + url);
// Initialise the HTTP client
if (httpclient == null) {
@@ -178,7 +171,7 @@ public class DelugeAdapter implements IDaemonAdapter {
// Setup client using POST
HttpPost httppost = new HttpPost(url);
File upload = new File(URI.create(file));
- Part[] parts = { new FilePart(RPC_FILE, upload) };
+ Part[] parts = {new FilePart(RPC_FILE, upload)};
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
// Make request
@@ -199,17 +192,17 @@ public class DelugeAdapter implements IDaemonAdapter {
fileu.put("options", new JSONArray());
files.put(fileu);
params.put(files);
-
+
return params;
-
+
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
-
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
+
try {
- ensureVersion();
-
+ ensureVersion(log);
+
JSONArray params = new JSONArray();
// Array of the fields needed for files listing calls
@@ -217,202 +210,209 @@ public class DelugeAdapter implements IDaemonAdapter {
ffields.put(RPC_DETAILS);
ffields.put(RPC_FILEPROGRESS);
ffields.put(RPC_FILEPRIORITIES);
-
+
switch (task.getMethod()) {
- case Retrieve:
+ case Retrieve:
- // Request all torrents from server
- JSONArray fields = new JSONArray();
- for (String field : RPC_FIELDS_ARRAY) {
- fields.put(field);
- }
- params.put(fields); // keys
- params.put(new JSONArray()); // filter_dict
- // params.put(-1); // cache_id
-
- JSONObject result = makeRequest(buildRequest(RPC_METHOD_GET, params));
- return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result.getJSONObject(RPC_RESULT)), parseJsonRetrieveLabels(result.getJSONObject(RPC_RESULT)));
-
- case GetTorrentDetails:
-
- // Array of the fields needed for files listing calls
- JSONArray dfields = new JSONArray();
- dfields.put(RPC_TRACKERS);
- dfields.put(RPC_TRACKER_STATUS);
-
- // Request file listing of a torrent
- params.put(task.getTargetTorrent().getUniqueID()); // torrent_id
- params.put(dfields); // keys
-
- JSONObject dinfo = makeRequest(buildRequest(RPC_METHOD_STATUS, params));
- return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(dinfo.getJSONObject(RPC_RESULT)));
-
- case GetFileList:
-
- // Request file listing of a torrent
- params.put(task.getTargetTorrent().getUniqueID()); // torrent_id
- params.put(ffields); // keys
-
- JSONObject finfo = makeRequest(buildRequest(RPC_METHOD_STATUS, params));
- return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFileListing(finfo.getJSONObject(RPC_RESULT), task.getTargetTorrent()));
-
- case AddByFile:
-
- // Request to add a torrent by local .torrent file
- String file = ((AddByFileTask)task).getFile();
- makeRequest(buildRequest(RPC_METHOD_ADD_FILE, AddTorrentByFile(file)));
- return new DaemonTaskSuccessResult(task);
-
- case AddByUrl:
-
- // Request to add a torrent by URL
- String url = ((AddByUrlTask)task).getUrl();
- params.put(url);
- params.put(new JSONArray());
-
- makeRequest(buildRequest(RPC_METHOD_ADD, params));
- return new DaemonTaskSuccessResult(task);
-
- case AddByMagnetUrl:
-
- // Request to add a magnet link by URL
- String magnet = ((AddByMagnetUrlTask)task).getUrl();
- // Deluge doesn't support (fully) application/x-www-form-urlencoded magnet links
- magnet = URLDecoder.decode(magnet, "UTF-8");
- params.put(magnet);
- params.put(new JSONArray());
-
- makeRequest(buildRequest(RPC_METHOD_ADD_MAGNET, params));
- return new DaemonTaskSuccessResult(task);
-
- case Remove:
-
- // Remove a torrent
- RemoveTask removeTask = (RemoveTask) task;
- params.put(removeTask.getTargetTorrent().getUniqueID());
- params.put(removeTask.includingData());
- makeRequest(buildRequest(RPC_METHOD_REMOVE, params));
- return new DaemonTaskSuccessResult(task);
-
- case Pause:
-
- // Pause a torrent
- PauseTask pauseTask = (PauseTask) task;
- makeRequest(buildRequest(RPC_METHOD_PAUSE,
- ((new JSONArray()).put((new JSONArray()).put(pauseTask.getTargetTorrent().getUniqueID())))));
- return new DaemonTaskSuccessResult(task);
-
- case PauseAll:
-
- // Resume all torrents
- makeRequest(buildRequest(RPC_METHOD_PAUSE_ALL, null));
- return new DaemonTaskSuccessResult(task);
-
- case Resume:
-
- // Resume a torrent
- ResumeTask resumeTask = (ResumeTask) task;
- makeRequest(buildRequest(RPC_METHOD_RESUME,
- ((new JSONArray()).put((new JSONArray()).put(resumeTask.getTargetTorrent().getUniqueID())))));
- return new DaemonTaskSuccessResult(task);
-
- case ResumeAll:
-
- // Resume all torrents
- makeRequest(buildRequest(RPC_METHOD_RESUME_ALL, null));
- return new DaemonTaskSuccessResult(task);
-
- case SetFilePriorities:
-
- // Set the priorities of files in a specific torrent
- SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
-
- // We first need a listing of all the files (because we can only set the priorities all at once)
- params.put(task.getTargetTorrent().getUniqueID()); // torrent_id
- params.put(ffields); // keys
- JSONObject pinfo = makeRequest(buildRequest(RPC_METHOD_STATUS, params));
- ArrayList pfiles = parseJsonFileListing(pinfo.getJSONObject(RPC_RESULT), prioTask.getTargetTorrent());
-
- // Now prepare the new list of priorities
- params = new JSONArray();
- params.put(task.getTargetTorrent().getUniqueID()); // torrent_id
- JSONArray pfields = new JSONArray();
- // Override the priorities in the just retrieved list of all files
- for (TorrentFile pfile : pfiles) {
- Priority newPriority = pfile.getPriority();
- for (TorrentFile forFile : prioTask.getForFiles()) {
- if (forFile.getKey().equals(pfile.getKey())) {
- // This is a file that we want to assign a new priority to
- newPriority = prioTask.getNewPriority();
- break;
+ // Request all torrents from server
+ JSONArray fields = new JSONArray();
+ for (String field : RPC_FIELDS_ARRAY) {
+ fields.put(field);
+ }
+ params.put(fields); // keys
+ params.put(new JSONArray()); // filter_dict
+ // params.put(-1); // cache_id
+
+ JSONObject result = makeRequest(buildRequest(RPC_METHOD_GET, params), log);
+ return new RetrieveTaskSuccessResult((RetrieveTask) task,
+ parseJsonRetrieveTorrents(result.getJSONObject(RPC_RESULT)),
+ parseJsonRetrieveLabels(result.getJSONObject(RPC_RESULT)));
+
+ case GetTorrentDetails:
+
+ // Array of the fields needed for files listing calls
+ JSONArray dfields = new JSONArray();
+ dfields.put(RPC_TRACKERS);
+ dfields.put(RPC_TRACKER_STATUS);
+
+ // Request file listing of a torrent
+ params.put(task.getTargetTorrent().getUniqueID()); // torrent_id
+ params.put(dfields); // keys
+
+ JSONObject dinfo = makeRequest(buildRequest(RPC_METHOD_STATUS, params), log);
+ return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
+ parseJsonTorrentDetails(dinfo.getJSONObject(RPC_RESULT)));
+
+ case GetFileList:
+
+ // Request file listing of a torrent
+ params.put(task.getTargetTorrent().getUniqueID()); // torrent_id
+ params.put(ffields); // keys
+
+ JSONObject finfo = makeRequest(buildRequest(RPC_METHOD_STATUS, params), log);
+ return new GetFileListTaskSuccessResult((GetFileListTask) task,
+ parseJsonFileListing(finfo.getJSONObject(RPC_RESULT), task.getTargetTorrent()));
+
+ case AddByFile:
+
+ // Request to add a torrent by local .torrent file
+ String file = ((AddByFileTask) task).getFile();
+ makeRequest(buildRequest(RPC_METHOD_ADD_FILE, addTorrentByFile(file, log)), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByUrl:
+
+ // Request to add a torrent by URL
+ String url = ((AddByUrlTask) task).getUrl();
+ params.put(url);
+ params.put(new JSONArray());
+
+ makeRequest(buildRequest(RPC_METHOD_ADD, params), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByMagnetUrl:
+
+ // Request to add a magnet link by URL
+ String magnet = ((AddByMagnetUrlTask) task).getUrl();
+ // Deluge doesn't support (fully) application/x-www-form-urlencoded magnet links
+ magnet = URLDecoder.decode(magnet, "UTF-8");
+ params.put(magnet);
+ params.put(new JSONArray());
+
+ makeRequest(buildRequest(RPC_METHOD_ADD_MAGNET, params), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case Remove:
+
+ // Remove a torrent
+ RemoveTask removeTask = (RemoveTask) task;
+ params.put(removeTask.getTargetTorrent().getUniqueID());
+ params.put(removeTask.includingData());
+ makeRequest(buildRequest(RPC_METHOD_REMOVE, params), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case Pause:
+
+ // Pause a torrent
+ PauseTask pauseTask = (PauseTask) task;
+ makeRequest(buildRequest(RPC_METHOD_PAUSE, ((new JSONArray())
+ .put((new JSONArray()).put(pauseTask.getTargetTorrent().getUniqueID())))), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case PauseAll:
+
+ // Resume all torrents
+ makeRequest(buildRequest(RPC_METHOD_PAUSE_ALL, null), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case Resume:
+
+ // Resume a torrent
+ ResumeTask resumeTask = (ResumeTask) task;
+ makeRequest(buildRequest(RPC_METHOD_RESUME, ((new JSONArray())
+ .put((new JSONArray()).put(resumeTask.getTargetTorrent().getUniqueID())))), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case ResumeAll:
+
+ // Resume all torrents
+ makeRequest(buildRequest(RPC_METHOD_RESUME_ALL, null), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case SetFilePriorities:
+
+ // Set the priorities of files in a specific torrent
+ SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
+
+ // We first need a listing of all the files (because we can only set the priorities all at once)
+ params.put(task.getTargetTorrent().getUniqueID()); // torrent_id
+ params.put(ffields); // keys
+ JSONObject pinfo = makeRequest(buildRequest(RPC_METHOD_STATUS, params), log);
+ ArrayList pfiles =
+ parseJsonFileListing(pinfo.getJSONObject(RPC_RESULT), prioTask.getTargetTorrent());
+
+ // Now prepare the new list of priorities
+ params = new JSONArray();
+ params.put(task.getTargetTorrent().getUniqueID()); // torrent_id
+ JSONArray pfields = new JSONArray();
+ // Override the priorities in the just retrieved list of all files
+ for (TorrentFile pfile : pfiles) {
+ Priority newPriority = pfile.getPriority();
+ for (TorrentFile forFile : prioTask.getForFiles()) {
+ if (forFile.getKey().equals(pfile.getKey())) {
+ // This is a file that we want to assign a new priority to
+ newPriority = prioTask.getNewPriority();
+ break;
+ }
}
+ pfields.put(convertPriority(newPriority));
}
- pfields.put(convertPriority(newPriority));
- }
- params.put(pfields); // keys
-
- // Make a single call to set the priorities on all files at once
- makeRequest(buildRequest(RPC_METHOD_SETFILE, params));
- return new DaemonTaskSuccessResult(task);
-
- case SetDownloadLocation:
-
- // Set the download location of some torrent
- SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task;
- // This works, but does not move the torrent
- //makeRequest(buildRequest(RPC_METHOD_SETOPTIONS, buildSetTorrentOptions(
- // sdlTask.getTargetTorrent().getUniqueID(), RPC_DOWNLOADLOCATION, sdlTask.getNewLocation())));
- params.put(new JSONArray().put(task.getTargetTorrent().getUniqueID()));
- params.put(sdlTask.getNewLocation());
- makeRequest(buildRequest(RPC_METHOD_MOVESTORAGE, params));
- return new DaemonTaskSuccessResult(task);
-
- case SetTransferRates:
-
- // Request to set the maximum transfer rates
- SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
- JSONObject map = new JSONObject();
- map.put(RPC_MAXUPLOAD, (ratesTask.getUploadRate() == null? -1: ratesTask.getUploadRate().intValue()));
- map.put(RPC_MAXDOWNLOAD, (ratesTask.getDownloadRate() == null? -1: ratesTask.getDownloadRate().intValue()));
-
- makeRequest(buildRequest(RPC_METHOD_SETCONFIG, (new JSONArray()).put(map)));
- return new DaemonTaskSuccessResult(task);
-
- case SetLabel:
-
- // Request to set the label
- SetLabelTask labelTask = (SetLabelTask) task;
- params.put(task.getTargetTorrent().getUniqueID());
- params.put(labelTask.getNewLabel() == null ? "" : labelTask.getNewLabel());
- makeRequest(buildRequest(RPC_METHOD_SETLABEL, params));
- return new DaemonTaskSuccessResult(task);
-
- case SetTrackers:
-
- // Set the trackers of some torrent
- SetTrackersTask trackersTask = (SetTrackersTask) task;
- JSONArray trackers = new JSONArray();
- // Build an JSON arrays of objcts that each have a tier (order) number and an url
- for (int i = 0; i < trackersTask.getNewTrackers().size(); i++) {
- JSONObject trackerObj = new JSONObject();
- trackerObj.put("tier", i);
- trackerObj.put("url", trackersTask.getNewTrackers().get(i));
- trackers.put(trackerObj);
- }
- params.put(new JSONArray().put(task.getTargetTorrent().getUniqueID()));
- params.put(trackers);
- makeRequest(buildRequest(RPC_METHOD_SETTRACKERS, params));
- return new DaemonTaskSuccessResult(task);
-
- case ForceRecheck:
-
- // Pause a torrent
- makeRequest(buildRequest(RPC_METHOD_FORCERECHECK,
- ((new JSONArray()).put((new JSONArray()).put(task.getTargetTorrent().getUniqueID())))));
- return new DaemonTaskSuccessResult(task);
-
- default:
- return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
+ params.put(pfields); // keys
+
+ // Make a single call to set the priorities on all files at once
+ makeRequest(buildRequest(RPC_METHOD_SETFILE, params), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case SetDownloadLocation:
+
+ // Set the download location of some torrent
+ SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task;
+ // This works, but does not move the torrent
+ //makeRequest(buildRequest(RPC_METHOD_SETOPTIONS, buildSetTorrentOptions(
+ // sdlTask.getTargetTorrent().getUniqueID(), RPC_DOWNLOADLOCATION, sdlTask.getNewLocation())));
+ params.put(new JSONArray().put(task.getTargetTorrent().getUniqueID()));
+ params.put(sdlTask.getNewLocation());
+ makeRequest(buildRequest(RPC_METHOD_MOVESTORAGE, params), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case SetTransferRates:
+
+ // Request to set the maximum transfer rates
+ SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
+ JSONObject map = new JSONObject();
+ map.put(RPC_MAXUPLOAD, (ratesTask.getUploadRate() == null ? -1 : ratesTask.getUploadRate()));
+ map.put(RPC_MAXDOWNLOAD, (ratesTask.getDownloadRate() == null ? -1 : ratesTask.getDownloadRate()));
+
+ makeRequest(buildRequest(RPC_METHOD_SETCONFIG, (new JSONArray()).put(map)), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case SetLabel:
+
+ // Request to set the label
+ SetLabelTask labelTask = (SetLabelTask) task;
+ params.put(task.getTargetTorrent().getUniqueID());
+ params.put(labelTask.getNewLabel() == null ? "" : labelTask.getNewLabel());
+ makeRequest(buildRequest(RPC_METHOD_SETLABEL, params), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case SetTrackers:
+
+ // Set the trackers of some torrent
+ SetTrackersTask trackersTask = (SetTrackersTask) task;
+ JSONArray trackers = new JSONArray();
+ // Build an JSON arrays of objcts that each have a tier (order) number and an url
+ for (int i = 0; i < trackersTask.getNewTrackers().size(); i++) {
+ JSONObject trackerObj = new JSONObject();
+ trackerObj.put("tier", i);
+ trackerObj.put("url", trackersTask.getNewTrackers().get(i));
+ trackers.put(trackerObj);
+ }
+ params.put(new JSONArray().put(task.getTargetTorrent().getUniqueID()));
+ params.put(trackers);
+ makeRequest(buildRequest(RPC_METHOD_SETTRACKERS, params), log);
+ return new DaemonTaskSuccessResult(task);
+
+ case ForceRecheck:
+
+ // Pause a torrent
+ makeRequest(buildRequest(RPC_METHOD_FORCERECHECK,
+ ((new JSONArray()).put((new JSONArray()).put(task.getTargetTorrent().getUniqueID())))),
+ log);
+ return new DaemonTaskSuccessResult(task);
+
+ default:
+ return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
+ task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
@@ -435,9 +435,10 @@ public class DelugeAdapter implements IDaemonAdapter {
return params;
}*/
- private void ensureVersion() throws DaemonException {
- if (version > 0)
+ private void ensureVersion(Log log) throws DaemonException {
+ if (version > 0) {
return;
+ }
// We still need to retrieve the version number from the server
// Do this by getting the web interface main html page and trying to parse the version number
// Format is something like 'Deluge: Web UI 1.3.6 '
@@ -464,9 +465,10 @@ public class DelugeAdapter implements IDaemonAdapter {
String numbers = "";
for (char c : parts[2].toCharArray()) {
if (Character.isDigit(c))
- // Still a number; add it to the numbers string
+ // Still a number; add it to the numbers string
+ {
numbers += Character.toString(c);
- else {
+ } else {
// No longer reading numbers; stop reading
break;
}
@@ -478,10 +480,10 @@ public class DelugeAdapter implements IDaemonAdapter {
}
}
} catch (NumberFormatException e) {
- DLog.d(LOG_NAME, "Error parsing the Deluge version code as number: " + e.toString());
+ log.d(LOG_NAME, "Error parsing the Deluge version code as number: " + e.toString());
// Continue though, ignoring the version number
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
// Unable to establish version number; assume an old version by setting it to version 1
@@ -496,21 +498,21 @@ public class DelugeAdapter implements IDaemonAdapter {
request.put(RPC_PARAMS, (params == null) ? new JSONArray() : params);
request.put(RPC_ID, 2);
return request;
-
+
}
-
- private synchronized JSONObject makeRequest(JSONObject data) throws DaemonException {
+
+ private synchronized JSONObject makeRequest(JSONObject data, Log log) throws DaemonException {
try {
-
+
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
-
+
// Login first?
if (sessionCookie == null) {
-
+
// Build login object
String extraPass = settings.getExtraPassword();
if (extraPass == null) {
@@ -539,11 +541,13 @@ public class DelugeAdapter implements IDaemonAdapter {
}
}
}
-
+
// Still no session cookie?
if (sessionCookie == null) {
// Set error message and cancel the action that was requested
- throw new DaemonException(ExceptionType.AuthenticationFailure, "Password error? Server time difference? No (valid) cookie in response and JSON was: " + HttpHelper.convertStreamToString(instream));
+ throw new DaemonException(ExceptionType.AuthenticationFailure,
+ "Password error? Server time difference? No (valid) cookie in response and JSON was: " +
+ HttpHelper.convertStreamToString(instream));
}
}
@@ -566,7 +570,7 @@ public class DelugeAdapter implements IDaemonAdapter {
if (!cookiePresent) {
httpclient.getCookieStore().addCookie(sessionCookie);
}
-
+
// Execute
HttpResponse response = httpclient.execute(httppost);
@@ -579,8 +583,10 @@ public class DelugeAdapter implements IDaemonAdapter {
JSONObject json = new JSONObject(result);
instream.close();
- DLog.d(LOG_NAME, "Success: " + (result.length() > 300? result.substring(0, 300) + "... (" + result.length() + " chars)": result));
-
+ log.d(LOG_NAME, "Success: " +
+ (result.length() > 300 ? result.substring(0, 300) + "... (" + result.length() + " chars)" :
+ result));
+
// Return JSON object
return json;
@@ -590,34 +596,35 @@ public class DelugeAdapter implements IDaemonAdapter {
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity in response object.");
} catch (JSONException e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.UnexpectedResponse, e.toString());
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
-
+
}
/**
* Instantiates an HTTP client with proper credentials that can be used for all Transmission requests.
- * @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On missing settings
*/
private void initialise() throws DaemonException {
- httpclient = HttpHelper.createStandardHttpClient(settings, settings.getUsername() != null && settings.getUsername() != "");
- httpclient.addRequestInterceptor(HttpHelper.gzipRequestInterceptor);
- httpclient.addResponseInterceptor(HttpHelper.gzipResponseInterceptor);
-
+ httpclient = HttpHelper.createStandardHttpClient(settings,
+ settings.getUsername() != null && !settings.getUsername().equals(""));
+ httpclient.addRequestInterceptor(HttpHelper.gzipRequestInterceptor);
+ httpclient.addResponseInterceptor(HttpHelper.gzipResponseInterceptor);
+
}
- /**
+ /**
* Build the URL of the Transmission web UI from the user settings.
* @return The URL of the RPC API
*/
private String buildWebUIUrl() {
- return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + (settings.getFolder() == null? "": settings.getFolder());
+ return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() +
+ (settings.getFolder() == null ? "" : settings.getFolder());
}
private ArrayList parseJsonRetrieveTorrents(JSONObject response) throws JSONException, DaemonException {
@@ -625,43 +632,47 @@ public class DelugeAdapter implements IDaemonAdapter {
// Parse response
ArrayList torrents = new ArrayList();
if (response.isNull(RPC_TORRENTS)) {
- throw new DaemonException(ExceptionType.NotConnected, "Web interface probably not connected to a daemon yet, because 'torrents' is null: " + response.toString());
+ throw new DaemonException(ExceptionType.NotConnected,
+ "Web interface probably not connected to a daemon yet, because 'torrents' is null: " +
+ response.toString());
}
JSONObject objects = response.getJSONObject(RPC_TORRENTS);
JSONArray names = objects.names();
if (names != null) {
for (int j = 0; j < names.length(); j++) {
-
+
JSONObject tor = objects.getJSONObject(names.getString(j));
// Add the parsed torrent to the list
TorrentStatus status = convertDelugeState(tor.getString(RPC_STATUS));
String error = tor.getString(RPC_MESSAGE);
if (tor.getString(RPC_TRACKER_STATUS).indexOf("Error") > 0) {
- error += (error.length() > 0? "\n": "") + tor.getString(RPC_TRACKER_STATUS);
+ error += (error.length() > 0 ? "\n" : "") + tor.getString(RPC_TRACKER_STATUS);
//status = TorrentStatus.Error; // Don't report this as blocking error
}
- torrents.add(new Torrent(j,
- names.getString(j),
- tor.getString(RPC_NAME),
+ // @formatter:off
+ torrents.add(new Torrent(j,
+ names.getString(j),
+ tor.getString(RPC_NAME),
status,
tor.getString(RPC_SAVEPATH) + settings.getOS().getPathSeperator(),
- tor.getInt(RPC_RATEDOWNLOAD),
- tor.getInt(RPC_RATEUPLOAD),
- tor.getInt(RPC_NUMSEEDS),
- tor.getInt(RPC_TOTALSEEDS),
- tor.getInt(RPC_NUMPEERS),
- tor.getInt(RPC_TOTALPEERS),
+ tor.getInt(RPC_RATEDOWNLOAD),
+ tor.getInt(RPC_RATEUPLOAD),
+ tor.getInt(RPC_NUMSEEDS),
+ tor.getInt(RPC_TOTALSEEDS),
+ tor.getInt(RPC_NUMPEERS),
+ tor.getInt(RPC_TOTALPEERS),
tor.getInt(RPC_ETA),
- tor.getLong(RPC_DOWNLOADEDEVER),
- tor.getLong(RPC_UPLOADEDEVER),
- tor.getLong(RPC_TOTALSIZE),
+ tor.getLong(RPC_DOWNLOADEDEVER),
+ tor.getLong(RPC_UPLOADEDEVER),
+ tor.getLong(RPC_TOTALSIZE),
((float) tor.getDouble(RPC_PARTDONE)) / 100f, // Percentage to [0..1]
0f, // Not available
tor.has(RPC_LABEL)? tor.getString(RPC_LABEL): null,
tor.has(RPC_TIMEADDED)? new Date((long) (tor.getDouble(RPC_TIMEADDED) * 1000L)): null,
null, // Not available
- tor.getString(RPC_MESSAGE),
+ error,
settings.getType()));
+ // @formatter:on
}
}
@@ -673,23 +684,26 @@ public class DelugeAdapter implements IDaemonAdapter {
private ArrayList parseJsonRetrieveLabels(JSONObject response) throws JSONException {
// Get the labels, of they exist (which is dependent on the plugin)
- if (!response.has("filters"))
+ if (!response.has("filters")) {
return null;
+ }
JSONObject filters = response.getJSONObject("filters");
- if (!filters.has("label"))
+ if (!filters.has("label")) {
return null;
+ }
JSONArray labels = filters.getJSONArray("label");
// Parse response
ArrayList allLabels = new ArrayList();
for (int i = 0; i < labels.length(); i++) {
JSONArray labelAndCount = labels.getJSONArray(i);
- if (labelAndCount.getString(0).equals("All"))
+ if (labelAndCount.getString(0).equals("All")) {
continue; // Ignore the 'All' filter, which is not an actual label
+ }
allLabels.add(new Label(labelAndCount.getString(0), labelAndCount.getInt(1)));
}
return allLabels;
-
+
}
private ArrayList parseJsonFileListing(JSONObject response, Torrent torrent) throws JSONException {
@@ -701,9 +715,10 @@ public class DelugeAdapter implements IDaemonAdapter {
JSONArray priorities = response.getJSONArray(RPC_FILEPRIORITIES);
if (objects != null) {
for (int j = 0; j < objects.length(); j++) {
-
+
JSONObject file = objects.getJSONObject(j);
// Add the parsed torrent to the list
+ // @formatter:off
files.add(new TorrentFile(
"" + file.getInt(RPC_INDEX),
file.getString(RPC_PATH),
@@ -712,6 +727,7 @@ public class DelugeAdapter implements IDaemonAdapter {
file.getLong(RPC_SIZE),
(long) (progress.getDouble(j) * file.getLong(RPC_SIZE)),
convertDelugePriority(priorities.getInt(j))));
+ // @formatter:on
}
}
@@ -724,25 +740,25 @@ public class DelugeAdapter implements IDaemonAdapter {
if (version >= 10303) {
// Priority codes changes from Deluge 1.3.3 onwards
switch (priority) {
- case 0:
- return Priority.Off;
- case 1:
- return Priority.Low;
- case 7:
- return Priority.High;
- default:
- return Priority.Normal;
+ case 0:
+ return Priority.Off;
+ case 1:
+ return Priority.Low;
+ case 7:
+ return Priority.High;
+ default:
+ return Priority.Normal;
}
} else {
switch (priority) {
- case 0:
- return Priority.Off;
- case 2:
- return Priority.Normal;
- case 5:
- return Priority.High;
- default:
- return Priority.Low;
+ case 0:
+ return Priority.Off;
+ case 2:
+ return Priority.Normal;
+ case 5:
+ return Priority.High;
+ default:
+ return Priority.Low;
}
}
}
@@ -751,25 +767,25 @@ public class DelugeAdapter implements IDaemonAdapter {
if (version >= 10303) {
// Priority codes changes from Deluge 1.3.3 onwards
switch (priority) {
- case Off:
- return 0;
- case Low:
- return 1;
- case High:
- return 7;
- default:
- return 5;
+ case Off:
+ return 0;
+ case Low:
+ return 1;
+ case High:
+ return 7;
+ default:
+ return 5;
}
} else {
switch (priority) {
- case Off:
- return 0;
- case Normal:
- return 2;
- case High:
- return 5;
- default:
- return 1;
+ case Off:
+ return 0;
+ case Normal:
+ return 2;
+ case High:
+ return 5;
+ default:
+ return 1;
}
}
}
@@ -817,5 +833,5 @@ public class DelugeAdapter implements IDaemonAdapter {
public DaemonSettings getSettings() {
return this.settings;
}
-
+
}
diff --git a/app/src/main/java/org/transdroid/daemon/DummyAdapter.java b/app/src/main/java/org/transdroid/daemon/DummyAdapter.java
index d2ecc06c..36b619b7 100644
--- a/app/src/main/java/org/transdroid/daemon/DummyAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/DummyAdapter.java
@@ -25,6 +25,7 @@ import java.util.Date;
import java.util.List;
import java.util.Random;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
@@ -47,7 +48,6 @@ import org.transdroid.daemon.task.SetDownloadLocationTask;
import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetLabelTask;
import org.transdroid.daemon.task.SetTrackersTask;
-import org.transdroid.daemon.util.DLog;
import android.net.Uri;
@@ -124,7 +124,7 @@ public class DummyAdapter implements IDaemonAdapter {
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
try {
switch (task.getMethod()) {
@@ -164,7 +164,7 @@ public class DummyAdapter implements IDaemonAdapter {
case AddByFile:
String file = ((AddByFileTask) task).getFile();
- DLog.d(LOG_NAME, "Adding torrent " + file);
+ log.d(LOG_NAME, "Adding torrent " + file);
File upload = new File(URI.create(file));
dummyTorrents.add(new Torrent(0, "torrent_file", upload.getName(), TorrentStatus.Queued, "/downloads/"
+ file, 0, 0, 0, 0, 0, 0, -1, 0, 0, 1024 * 1024 * 1000, 0, 1F, "isos", new Date(), null, null,
@@ -174,7 +174,7 @@ public class DummyAdapter implements IDaemonAdapter {
case AddByUrl:
String url = ((AddByUrlTask) task).getUrl();
- DLog.d(LOG_NAME, "Adding torrent " + url);
+ log.d(LOG_NAME, "Adding torrent " + url);
if (url == null || url.equals(""))
throw new DaemonException(DaemonException.ExceptionType.ParsingFailed, "No url specified");
Uri uri = Uri.parse(url);
@@ -186,7 +186,7 @@ public class DummyAdapter implements IDaemonAdapter {
case AddByMagnetUrl:
String magnet = ((AddByMagnetUrlTask) task).getUrl();
- DLog.d(LOG_NAME, "Adding torrent " + magnet);
+ log.d(LOG_NAME, "Adding torrent " + magnet);
Uri magnetUri = Uri.parse(magnet);
dummyTorrents.add(new Torrent(0, "torrent_magnet", magnetUri.getLastPathSegment(),
TorrentStatus.Queued, "/downloads/" + magnetUri.getLastPathSegment(), 0, 0, 0, 0, 0, 0, -1, 0,
diff --git a/app/src/main/java/org/transdroid/daemon/IDaemonAdapter.java b/app/src/main/java/org/transdroid/daemon/IDaemonAdapter.java
index 163758ba..3408cdb0 100644
--- a/app/src/main/java/org/transdroid/daemon/IDaemonAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/IDaemonAdapter.java
@@ -17,6 +17,7 @@
*/
package org.transdroid.daemon;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskResult;
@@ -29,7 +30,7 @@ import org.transdroid.daemon.task.DaemonTaskResult;
*/
public interface IDaemonAdapter {
- public DaemonTaskResult executeTask(DaemonTask task);
+ public DaemonTaskResult executeTask(Log log, DaemonTask task);
public Daemon getType();
diff --git a/app/src/main/java/org/transdroid/daemon/Ktorrent/KtorrentAdapter.java b/app/src/main/java/org/transdroid/daemon/Ktorrent/KtorrentAdapter.java
index 3bec35f5..4455b051 100644
--- a/app/src/main/java/org/transdroid/daemon/Ktorrent/KtorrentAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Ktorrent/KtorrentAdapter.java
@@ -17,15 +17,9 @@
*/
package org.transdroid.daemon.Ktorrent;
-import java.io.File;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.math.BigInteger;
-import java.net.URI;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.List;
+import com.android.internalcopy.http.multipart.FilePart;
+import com.android.internalcopy.http.multipart.MultipartEntity;
+import com.android.internalcopy.http.multipart.Part;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
@@ -37,14 +31,15 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
+import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentFile;
-import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
@@ -57,19 +52,23 @@ import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetFilePriorityTask;
-import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
-import com.android.internalcopy.http.multipart.FilePart;
-import com.android.internalcopy.http.multipart.MultipartEntity;
-import com.android.internalcopy.http.multipart.Part;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.math.BigInteger;
+import java.net.URI;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.List;
/**
- * An adapter that allows for easy access to Ktorrent's web interface. Communication
- * is handled via HTTP GET requests and XML responses.
- *
+ * An adapter that allows for easy access to Ktorrent's web interface. Communication is handled via HTTP GET requests
+ * and XML responses.
* @author erickok
- *
*/
public class KtorrentAdapter implements IDaemonAdapter {
@@ -86,10 +85,9 @@ public class KtorrentAdapter implements IDaemonAdapter {
private static final String RPC_URL_FILES = "/data/torrent/files.xml?torrent=";
//private static final String RPC_COOKIE_NAME = "KT_SESSID";
private static final String RPC_SUCCESS = "OK ";
-
+ static private int retries = 0;
private DaemonSettings settings;
private DefaultHttpClient httpclient;
- static private int retries = 0;
/**
* Initialises an adapter that provides operations to the Ktorrent web interface
@@ -98,167 +96,189 @@ public class KtorrentAdapter implements IDaemonAdapter {
this.settings = settings;
}
+ /**
+ * Calculate the SHA1 hash of a password/challenge string to use with the login requests.
+ * @param passkey A concatenation of the challenge string and plain text password
+ * @return A hex-formatted SHA1-hashed string of the challenge and password strings
+ */
+ public static String sha1Pass(String passkey) {
+ try {
+ MessageDigest m = MessageDigest.getInstance("SHA1");
+ byte[] data = passkey.getBytes();
+ m.update(data, 0, data.length);
+ BigInteger i = new BigInteger(1, m.digest());
+ return String.format("%1$040X", i).toLowerCase();
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
-
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
+
try {
switch (task.getMethod()) {
- case Retrieve:
-
- // Request all torrents from server
- return new RetrieveTaskSuccessResult((RetrieveTask) task, makeStatsRequest(),null);
-
- case GetFileList:
-
- // Request file listing for a torrent
- return new GetFileListTaskSuccessResult((GetFileListTask) task, makeFileListRequest(task.getTargetTorrent()));
-
- case AddByFile:
-
- // Add a torrent to the server by sending the contents of a local .torrent file
- String file = ((AddByFileTask)task).getFile();
- makeFileUploadRequest(file);
- return null;
-
- case AddByUrl:
-
- // Request to add a torrent by URL
- String url = ((AddByUrlTask)task).getUrl();
- makeActionRequest("load_torrent=" + url);
- return new DaemonTaskSuccessResult(task);
-
- case AddByMagnetUrl:
-
- // Request to add a magnet link by URL
- String magnet = ((AddByMagnetUrlTask)task).getUrl();
- makeActionRequest("load_torrent=" + magnet);
- return new DaemonTaskSuccessResult(task);
-
- case Remove:
-
- // Remove a torrent
- // Note that removing with data is not supported
- makeActionRequest("remove=" + task.getTargetTorrent().getUniqueID());
- return new DaemonTaskSuccessResult(task);
-
- case Pause:
-
- // Pause a torrent
- makeActionRequest("stop=" + task.getTargetTorrent().getUniqueID());
- return new DaemonTaskSuccessResult(task);
-
- case PauseAll:
-
- // Pause all torrents
- makeActionRequest("stopall=true");
- return new DaemonTaskSuccessResult(task);
-
- case Resume:
-
- // Resume a torrent
- makeActionRequest("start=" + task.getTargetTorrent().getUniqueID());
- return new DaemonTaskSuccessResult(task);
-
- case ResumeAll:
-
- // Resume all torrents
- makeActionRequest("startall=true");
- return new DaemonTaskSuccessResult(task);
-
- case SetFilePriorities:
-
- // Set the priorities of the files of some torrent
- SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
- String act = "file_np=" + task.getTargetTorrent().getUniqueID() + "-";
- switch (prioTask.getNewPriority()) {
- case Off:
- act = "file_stop=" + task.getTargetTorrent().getUniqueID() + "-";
- break;
- case Low:
- case Normal:
- act = "file_lp=" + task.getTargetTorrent().getUniqueID() + "-";
- break;
- case High:
- act = "file_hp=" + task.getTargetTorrent().getUniqueID() + "-";
- break;
- }
- // It seems KTorrent's web UI does not allow for setting all priorities in one request :(
- for (TorrentFile forFile : prioTask.getForFiles()) {
- makeActionRequest(act + forFile.getKey());
- }
- return new DaemonTaskSuccessResult(task);
-
- case SetTransferRates:
-
- // Request to set the maximum transfer rates
- // TODO: Implement this?
- return null;
-
- default:
- return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
+ case Retrieve:
+
+ // Request all torrents from server
+ return new RetrieveTaskSuccessResult((RetrieveTask) task, makeStatsRequest(log), null);
+
+ case GetFileList:
+
+ // Request file listing for a torrent
+ return new GetFileListTaskSuccessResult((GetFileListTask) task,
+ makeFileListRequest(log, task.getTargetTorrent()));
+
+ case AddByFile:
+
+ // Add a torrent to the server by sending the contents of a local .torrent file
+ String file = ((AddByFileTask) task).getFile();
+ makeFileUploadRequest(log, file);
+ return null;
+
+ case AddByUrl:
+
+ // Request to add a torrent by URL
+ String url = ((AddByUrlTask) task).getUrl();
+ makeActionRequest(log, "load_torrent=" + url);
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByMagnetUrl:
+
+ // Request to add a magnet link by URL
+ String magnet = ((AddByMagnetUrlTask) task).getUrl();
+ makeActionRequest(log, "load_torrent=" + magnet);
+ return new DaemonTaskSuccessResult(task);
+
+ case Remove:
+
+ // Remove a torrent
+ // Note that removing with data is not supported
+ makeActionRequest(log, "remove=" + task.getTargetTorrent().getUniqueID());
+ return new DaemonTaskSuccessResult(task);
+
+ case Pause:
+
+ // Pause a torrent
+ makeActionRequest(log, "stop=" + task.getTargetTorrent().getUniqueID());
+ return new DaemonTaskSuccessResult(task);
+
+ case PauseAll:
+
+ // Pause all torrents
+ makeActionRequest(log, "stopall=true");
+ return new DaemonTaskSuccessResult(task);
+
+ case Resume:
+
+ // Resume a torrent
+ makeActionRequest(log, "start=" + task.getTargetTorrent().getUniqueID());
+ return new DaemonTaskSuccessResult(task);
+
+ case ResumeAll:
+
+ // Resume all torrents
+ makeActionRequest(log, "startall=true");
+ return new DaemonTaskSuccessResult(task);
+
+ case SetFilePriorities:
+
+ // Set the priorities of the files of some torrent
+ SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
+ String act = "file_np=" + task.getTargetTorrent().getUniqueID() + "-";
+ switch (prioTask.getNewPriority()) {
+ case Off:
+ act = "file_stop=" + task.getTargetTorrent().getUniqueID() + "-";
+ break;
+ case Low:
+ case Normal:
+ act = "file_lp=" + task.getTargetTorrent().getUniqueID() + "-";
+ break;
+ case High:
+ act = "file_hp=" + task.getTargetTorrent().getUniqueID() + "-";
+ break;
+ }
+ // It seems KTorrent's web UI does not allow for setting all priorities in one request :(
+ for (TorrentFile forFile : prioTask.getForFiles()) {
+ makeActionRequest(log, act + forFile.getKey());
+ }
+ return new DaemonTaskSuccessResult(task);
+
+ case SetTransferRates:
+
+ // Request to set the maximum transfer rates
+ // TODO: Implement this?
+ return null;
+
+ default:
+ return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
+ task.getMethod() + " is not supported by " + getType()));
}
} catch (LoggedOutException e) {
-
+
// Invalidate our session
httpclient = null;
if (retries < 2) {
retries++;
// Retry
- DLog.d(LOG_NAME, "We were logged out without knowing: retry");
- return executeTask(task);
+ log.d(LOG_NAME, "We were logged out without knowing: retry");
+ return executeTask(log, task);
} else {
// Never retry more than twice; in this case just return a task failure
- return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ConnectionError, "Retried " + retries + " already, so we stopped now"));
+ return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ConnectionError,
+ "Retried " + retries + " already, so we stopped now"));
}
-
+
} catch (DaemonException e) {
// Invalidate our session
httpclient = null;
// Return the task failure
return new DaemonTaskFailureResult(task, e);
-
+
}
}
- private List makeStatsRequest() throws DaemonException, LoggedOutException {
+ private List makeStatsRequest(Log log) throws DaemonException, LoggedOutException {
try {
-
+
// Initialise the HTTP client
initialise();
- makeLoginRequest();
-
+ makeLoginRequest(log);
+
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl() + RPC_URL_STATS);
HttpResponse response = httpclient.execute(httpget);
// Read XML response
InputStream instream = response.getEntity().getContent();
- List torrents = StatsParser.parse(new InputStreamReader(instream), settings.getDownloadDir(), settings.getOS().getPathSeperator());
+ List torrents = StatsParser.parse(new InputStreamReader(instream), settings.getDownloadDir(),
+ settings.getOS().getPathSeperator());
instream.close();
- return torrents;
-
+ return torrents;
+
} catch (LoggedOutException e) {
throw e;
} catch (DaemonException e) {
- DLog.d(LOG_NAME, "Parsing error: " + e.toString());
+ log.d(LOG_NAME, "Parsing error: " + e.toString());
throw e;
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
-
+
}
- private List makeFileListRequest(Torrent torrent) throws DaemonException, LoggedOutException {
+ private List makeFileListRequest(Log log, Torrent torrent) throws DaemonException, LoggedOutException {
try {
-
+
// Initialise the HTTP client
initialise();
- makeLoginRequest();
-
+ makeLoginRequest(log);
+
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl() + RPC_URL_FILES + torrent.getUniqueID());
HttpResponse response = httpclient.execute(httpget);
@@ -267,26 +287,28 @@ public class KtorrentAdapter implements IDaemonAdapter {
InputStream instream = response.getEntity().getContent();
List files = FileListParser.parse(new InputStreamReader(instream), torrent.getLocationDir());
instream.close();
-
+
// If the files list is empty, it means that this is a single-file torrent
// We can mimic this single file form the torrent statistics itself
- files.add(new TorrentFile("" + 0, torrent.getName(), torrent.getName(), torrent.getLocationDir() + torrent.getName(), torrent.getTotalSize(), torrent.getDownloadedEver(), Priority.Normal));
-
- return files;
-
+ files.add(new TorrentFile("" + 0, torrent.getName(), torrent.getName(),
+ torrent.getLocationDir() + torrent.getName(), torrent.getTotalSize(), torrent.getDownloadedEver(),
+ Priority.Normal));
+
+ return files;
+
} catch (LoggedOutException e) {
throw e;
} catch (DaemonException e) {
- DLog.d(LOG_NAME, "Parsing error: " + e.toString());
+ log.d(LOG_NAME, "Parsing error: " + e.toString());
throw e;
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
-
+
}
- private void makeLoginRequest() throws DaemonException {
+ private void makeLoginRequest(Log log) throws DaemonException {
try {
@@ -294,10 +316,10 @@ public class KtorrentAdapter implements IDaemonAdapter {
HttpGet httpget = new HttpGet(buildWebUIUrl() + RPC_URL_CHALLENGE);
HttpResponse response = httpclient.execute(httpget);
InputStream instream = response.getEntity().getContent();
- String challengeString = HttpHelper.convertStreamToString(instream).replaceAll("\\<.*?>","").trim();
+ String challengeString = HttpHelper.convertStreamToString(instream).replaceAll("<.*?>", "").trim();
instream.close();
// Challenge string should be something like TncpX3TB8uZ0h8eqztZ6
- if (challengeString == null || challengeString.length() != 20) {
+ if (challengeString.length() != 20) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "No (valid) challenge string received");
}
@@ -305,54 +327,38 @@ public class KtorrentAdapter implements IDaemonAdapter {
HttpPost httppost2 = new HttpPost(buildWebUIUrl() + RPC_URL_LOGIN);
List params = new ArrayList(3);
params.add(new BasicNameValuePair(RPC_URL_LOGIN_USER, settings.getUsername()));
- params.add(new BasicNameValuePair(RPC_URL_LOGIN_PASS, "")); // Password is send (as SHA1 hex) in the challenge field
- params.add(new BasicNameValuePair(RPC_URL_LOGIN_CHAL, sha1Pass(challengeString + settings.getPassword()))); // Make a SHA1 encrypted hex-formated string of the challenge code and password
+ params.add(new BasicNameValuePair(RPC_URL_LOGIN_PASS,
+ "")); // Password is send (as SHA1 hex) in the challenge field
+ params.add(new BasicNameValuePair(RPC_URL_LOGIN_CHAL, sha1Pass(challengeString +
+ settings.getPassword()))); // Make a SHA1 encrypted hex-formated string of the challenge code and password
httppost2.setEntity(new UrlEncodedFormEntity(params));
// This sets the authentication cookie
httpclient.execute(httppost2);
/*InputStream instream2 = response2.getEntity().getContent();
String result2 = HttpHelper.ConvertStreamToString(instream2);
instream2.close();*/
-
+
// Successfully logged in; we may retry later if needed
retries = 0;
} catch (DaemonException e) {
- DLog.d(LOG_NAME, "Login error: " + e.toString());
+ log.d(LOG_NAME, "Login error: " + e.toString());
throw e;
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error during login: " + e.toString());
+ log.d(LOG_NAME, "Error during login: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
-
- }
- /**
- * Calculate the SHA1 hash of a password/challenge string to use with the login requests.
- * @param passkey A concatenation of the challenge string and plain text password
- * @return A hex-formatted SHA1-hashed string of the challenge and password strings
- */
- public static String sha1Pass(String passkey) {
- try {
- MessageDigest m = MessageDigest.getInstance("SHA1");
- byte[] data = passkey.getBytes();
- m.update(data,0,data.length);
- BigInteger i = new BigInteger(1,m.digest());
- return String.format("%1$040X", i).toLowerCase();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- return null;
}
- private boolean makeActionRequest(String action) throws DaemonException, LoggedOutException {
+ private boolean makeActionRequest(Log log, String action) throws DaemonException, LoggedOutException {
try {
-
+
// Initialise the HTTP client
initialise();
- makeLoginRequest();
-
+ makeLoginRequest(log);
+
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl() + RPC_URL_ACTION + action);
HttpResponse response = httpclient.execute(httpget);
@@ -374,34 +380,39 @@ public class KtorrentAdapter implements IDaemonAdapter {
} catch (LoggedOutException e) {
throw e;
} catch (DaemonException e) {
- DLog.d(LOG_NAME, action + " request error: " + e.toString());
+ log.d(LOG_NAME, action + " request error: " + e.toString());
throw e;
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
-
+
}
- private boolean makeFileUploadRequest(String target) throws DaemonException, LoggedOutException {
+ private boolean makeFileUploadRequest(Log log, String target) throws DaemonException, LoggedOutException {
try {
-
+
// Initialise the HTTP client
initialise();
- makeLoginRequest();
-
+ makeLoginRequest(log);
+
// Make request
- HttpPost httppost = new HttpPost(buildWebUIUrl() + RPC_URL_UPLOAD);
+ HttpPost httppost = new HttpPost(buildWebUIUrl() + RPC_URL_UPLOAD);
File upload = new File(URI.create(target));
- Part[] parts = { new FilePart("load_torrent", upload) };
+ Part[] parts = {new FilePart("load_torrent", upload)};
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
// Make sure we are not automatically redirected
RedirectHandler handler = new RedirectHandler() {
@Override
- public boolean isRedirectRequested(HttpResponse response, HttpContext context) { return false; }
+ public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
+ return false;
+ }
+
@Override
- public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException { return null; }
+ public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
+ return null;
+ }
};
httpclient.setRedirectHandler(handler);
HttpResponse response = httpclient.execute(httppost);
@@ -423,15 +434,15 @@ public class KtorrentAdapter implements IDaemonAdapter {
} catch (LoggedOutException e) {
throw e;
} catch (DaemonException e) {
- DLog.d(LOG_NAME, "File upload error: " + e.toString());
+ log.d(LOG_NAME, "File upload error: " + e.toString());
throw e;
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
-
+
}
-
+
/**
* Indicates if we were already successfully authenticated
* @return True if the proper authentication cookie was already loaded
@@ -448,7 +459,6 @@ public class KtorrentAdapter implements IDaemonAdapter {
/**
* Instantiates an HTTP client that can be used for all Ktorrent requests.
- * @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException Thrown on settings error
*/
private void initialise() throws DaemonException {
@@ -458,7 +468,7 @@ public class KtorrentAdapter implements IDaemonAdapter {
}
httpclient = HttpHelper.createStandardHttpClient(settings, false);
}
-
+
/**
* Build the base URL for a Ktorrent web site request from the user settings.
* @return The base URL of for a request, i.e. http://localhost:8080
@@ -476,5 +486,5 @@ public class KtorrentAdapter implements IDaemonAdapter {
public DaemonSettings getSettings() {
return this.settings;
}
-
+
}
diff --git a/app/src/main/java/org/transdroid/daemon/Qbittorrent/QbittorrentAdapter.java b/app/src/main/java/org/transdroid/daemon/Qbittorrent/QbittorrentAdapter.java
index 1c7d8da6..d543f705 100644
--- a/app/src/main/java/org/transdroid/daemon/Qbittorrent/QbittorrentAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Qbittorrent/QbittorrentAdapter.java
@@ -23,6 +23,7 @@ import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import org.apache.http.HttpEntity;
@@ -36,6 +37,7 @@ import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
@@ -62,7 +64,6 @@ import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
-import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
import com.android.internalcopy.http.multipart.FilePart;
import com.android.internalcopy.http.multipart.MultipartEntity;
@@ -84,13 +85,13 @@ public class QbittorrentAdapter implements IDaemonAdapter {
this.settings = settings;
}
- private synchronized void ensureVersion() throws DaemonException {
+ private synchronized void ensureVersion(Log log) throws DaemonException {
if (version > 0)
return;
// We still need to retrieve the version number from the server
// Do this by getting the web interface about page and trying to parse the version number
// Format is something like 'qBittorrent v2.9.7 (Web UI)'
- String about = makeRequest("/about.html");
+ String about = makeRequest(log, "/about.html");
String aboutStartText = "qBittorrent v";
String aboutEndText = " (Web UI)";
int aboutStart = about.indexOf(aboutStartText);
@@ -129,83 +130,83 @@ public class QbittorrentAdapter implements IDaemonAdapter {
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
try {
- ensureVersion();
+ ensureVersion(log);
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
- JSONArray result = new JSONArray(makeRequest(version >= 30000 ? "/json/torrents" : "/json/events"));
+ JSONArray result = new JSONArray(makeRequest(log, version >= 30000 ? "/json/torrents" : "/json/events"));
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonTorrents(result), null);
case GetTorrentDetails:
// Request tracker and error details for a specific teacher
- String mhash = ((GetTorrentDetailsTask) task).getTargetTorrent().getUniqueID();
- JSONArray messages = new JSONArray(makeRequest("/json/propertiesTrackers/" + mhash));
+ String mhash = task.getTargetTorrent().getUniqueID();
+ JSONArray messages = new JSONArray(makeRequest(log, "/json/propertiesTrackers/" + mhash));
return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
parseJsonTorrentDetails(messages));
case GetFileList:
// Request files listing for a specific torrent
- String fhash = ((GetFileListTask) task).getTargetTorrent().getUniqueID();
- JSONArray files = new JSONArray(makeRequest("/json/propertiesFiles/" + fhash));
+ String fhash = task.getTargetTorrent().getUniqueID();
+ JSONArray files = new JSONArray(makeRequest(log, "/json/propertiesFiles/" + fhash));
return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFiles(files));
case AddByFile:
// Upload a local .torrent file
String ufile = ((AddByFileTask) task).getFile();
- makeUploadRequest("/command/upload", ufile);
+ makeUploadRequest("/command/upload", ufile, log);
return new DaemonTaskSuccessResult(task);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask) task).getUrl();
- makeRequest("/command/download", new BasicNameValuePair("urls", url));
+ makeRequest(log, "/command/download", new BasicNameValuePair("urls", url));
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
// Request to add a magnet link by URL
String magnet = ((AddByMagnetUrlTask) task).getUrl();
- makeRequest("/command/download", new BasicNameValuePair("urls", magnet));
+ makeRequest(log, "/command/download", new BasicNameValuePair("urls", magnet));
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
- makeRequest((removeTask.includingData() ? "/command/deletePerm" : "/command/delete"),
+ makeRequest(log, (removeTask.includingData() ? "/command/deletePerm" : "/command/delete"),
new BasicNameValuePair("hashes", removeTask.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
- makeRequest("/command/pause", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
+ makeRequest(log, "/command/pause", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Resume all torrents
- makeRequest("/command/pauseall");
+ makeRequest(log, "/command/pauseall");
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
- makeRequest("/command/resume", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
+ makeRequest(log, "/command/resume", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
- makeRequest("/command/resumeall");
+ makeRequest(log, "/command/resumeall");
return new DaemonTaskSuccessResult(task);
case SetFilePriorities:
@@ -222,7 +223,7 @@ public class QbittorrentAdapter implements IDaemonAdapter {
}
// We have to make a separate request per file, it seems
for (TorrentFile file : setPrio.getForFiles()) {
- makeRequest("/command/setFilePrio", new BasicNameValuePair("hash", task.getTargetTorrent()
+ makeRequest(log, "/command/setFilePrio", new BasicNameValuePair("hash", task.getTargetTorrent()
.getUniqueID()), new BasicNameValuePair("id", file.getKey()), new BasicNameValuePair(
"priority", newPrio));
}
@@ -233,14 +234,14 @@ public class QbittorrentAdapter implements IDaemonAdapter {
// TODO: This doesn't seem to work yet
// Request to set the maximum transfer rates
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
- int dl = (ratesTask.getDownloadRate() == null ? -1 : ratesTask.getDownloadRate().intValue());
- int ul = (ratesTask.getUploadRate() == null ? -1 : ratesTask.getUploadRate().intValue());
+ int dl = (ratesTask.getDownloadRate() == null ? -1 : ratesTask.getDownloadRate());
+ int ul = (ratesTask.getUploadRate() == null ? -1 : ratesTask.getUploadRate());
// First get the preferences
- JSONObject prefs = new JSONObject(makeRequest("/json/preferences"));
+ JSONObject prefs = new JSONObject(makeRequest(log, "/json/preferences"));
prefs.put("dl_limit", dl);
prefs.put("up_limit", ul);
- makeRequest("/command/setPreferences",
+ makeRequest(log, "/command/setPreferences",
new BasicNameValuePair("json", URLEncoder.encode(prefs.toString(), HTTP.UTF_8)));
return new DaemonTaskSuccessResult(task);
@@ -257,18 +258,16 @@ public class QbittorrentAdapter implements IDaemonAdapter {
}
}
- private String makeRequest(String path, NameValuePair... params) throws DaemonException {
+ private String makeRequest(Log log, String path, NameValuePair... params) throws DaemonException {
try {
// Setup request using POST
HttpPost httppost = new HttpPost(buildWebUIUrl(path));
List nvps = new ArrayList();
- for (NameValuePair param : params) {
- nvps.add(param);
- }
+ Collections.addAll(nvps, params);
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
- return makeWebRequest(path, httppost);
+ return makeWebRequest(httppost, log);
} catch (UnsupportedEncodingException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
@@ -276,7 +275,7 @@ public class QbittorrentAdapter implements IDaemonAdapter {
}
- private String makeUploadRequest(String path, String file) throws DaemonException {
+ private String makeUploadRequest(String path, String file, Log log) throws DaemonException {
try {
@@ -285,7 +284,7 @@ public class QbittorrentAdapter implements IDaemonAdapter {
File upload = new File(URI.create(file));
Part[] parts = { new FilePart("torrentfile", upload) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
- return makeWebRequest(path, httppost);
+ return makeWebRequest(httppost, log);
} catch (FileNotFoundException e) {
throw new DaemonException(ExceptionType.FileAccessError, e.toString());
@@ -293,7 +292,7 @@ public class QbittorrentAdapter implements IDaemonAdapter {
}
- private String makeWebRequest(String path, HttpPost httppost) throws DaemonException {
+ private String makeWebRequest(HttpPost httppost, Log log) throws DaemonException {
try {
@@ -320,11 +319,11 @@ public class QbittorrentAdapter implements IDaemonAdapter {
return result;
}
- DLog.d(LOG_NAME, "Error: No entity in HTTP response");
+ log.d(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
@@ -332,7 +331,6 @@ public class QbittorrentAdapter implements IDaemonAdapter {
/**
* Instantiates an HTTP client with proper credentials that can be used for all qBittorrent requests.
- * @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise() throws DaemonException {
@@ -385,10 +383,31 @@ public class QbittorrentAdapter implements IDaemonAdapter {
eta = (long) (size - (size * progress)) / dlspeed;
// Date added is only available in /json/propertiesGeneral on a per-torrent basis, unfortunately
// Add the parsed torrent to the list
- torrents.add(new Torrent((long) i, tor.getString("hash"), tor.getString("name"), parseStatus(tor
- .getString("state")), null, dlspeed, parseSpeed(tor.getString("upspeed")), seeders[0], seeders[1],
- leechers[0], leechers[1], (int) eta, (long) (size * progress), (long) (size * ratio), size,
- (float) progress, 0f, null, null, null, null, settings.getType()));
+ // @formatter:off
+ torrents.add(new Torrent(
+ (long) i,
+ tor.getString("hash"),
+ tor.getString("name"),
+ parseStatus(tor.getString("state")),
+ null,
+ dlspeed,
+ parseSpeed(tor.getString("upspeed")),
+ seeders[0],
+ seeders[1],
+ leechers[0],
+ leechers[1],
+ (int) eta,
+ (long) (size * progress),
+ (long) (size * ratio),
+ size,
+ (float) progress,
+ 0f,
+ null,
+ null,
+ null,
+ null,
+ settings.getType()));
+ // @formatter:on
}
// Return the list
diff --git a/app/src/main/java/org/transdroid/daemon/Rtorrent/RtorrentAdapter.java b/app/src/main/java/org/transdroid/daemon/Rtorrent/RtorrentAdapter.java
index 36ca1ec4..c4ad22f3 100644
--- a/app/src/main/java/org/transdroid/daemon/Rtorrent/RtorrentAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Rtorrent/RtorrentAdapter.java
@@ -17,22 +17,7 @@
*/
package org.transdroid.daemon.Rtorrent;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonException.ExceptionType;
@@ -61,9 +46,24 @@ import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetLabelTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
-import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
import de.timroes.axmlrpc.XMLRPCClient;
import de.timroes.axmlrpc.XMLRPCClient.UnauthorizdException;
import de.timroes.axmlrpc.XMLRPCException;
@@ -88,14 +88,14 @@ public class RtorrentAdapter implements IDaemonAdapter {
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
try {
switch (task.getMethod()) {
- case Retrieve:
+ case Retrieve:
- // @formatter:off
- Object result = makeRtorrentCall("d.multicall",
+ // @formatter:off
+ Object result = makeRtorrentCall(log,"d.multicall",
new String[] { "main",
"d.get_hash=",
"d.get_name=",
@@ -122,23 +122,24 @@ public class RtorrentAdapter implements IDaemonAdapter {
"d.get_peers_complete=",
"d.get_peers_accounted=" });
// @formatter:on
- return new RetrieveTaskSuccessResult((RetrieveTask) task, onTorrentsRetrieved(result), lastKnownLabels);
+ return new RetrieveTaskSuccessResult((RetrieveTask) task, onTorrentsRetrieved(result),
+ lastKnownLabels);
- case GetTorrentDetails:
+ case GetTorrentDetails:
- // @formatter:off
- Object dresult = makeRtorrentCall("t.multicall", new String[] {
+ // @formatter:off
+ Object dresult = makeRtorrentCall(log,"t.multicall", new String[] {
task.getTargetTorrent().getUniqueID(),
"",
"t.get_url=" });
// @formatter:on
- return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
- onTorrentDetailsRetrieved(dresult));
+ return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
+ onTorrentDetailsRetrieved(log, dresult));
- case GetFileList:
+ case GetFileList:
- // @formatter:off
- Object fresult = makeRtorrentCall("f.multicall", new String[] {
+ // @formatter:off
+ Object fresult = makeRtorrentCall(log,"f.multicall", new String[] {
task.getTargetTorrent().getUniqueID(),
"",
"f.get_path=",
@@ -149,137 +150,139 @@ public class RtorrentAdapter implements IDaemonAdapter {
"f.get_priority=",
"f.get_frozen_path=" });
// @formatter:on
- return new GetFileListTaskSuccessResult((GetFileListTask) task, onTorrentFilesRetrieved(fresult,
- task.getTargetTorrent()));
-
- case AddByFile:
-
- // Request to add a torrent by local .torrent file
- File file = new File(URI.create(((AddByFileTask) task).getFile()));
- FileInputStream in = new FileInputStream(file);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buffer = new byte[(int) file.length()];
- int read = 0;
- while ((read = in.read(buffer, 0, buffer.length)) > 0) {
- baos.write(buffer, 0, read);
- }
- byte[] bytes = baos.toByteArray();
- int size = (int) file.length() * 2;
- final int XMLRPC_EXTRA_PADDING = 1280;
- makeRtorrentCall("set_xmlrpc_size_limit", new Object[] { size + XMLRPC_EXTRA_PADDING });
- makeRtorrentCall("load_raw_start", new Object[] { bytes });
- return new DaemonTaskSuccessResult(task);
-
- case AddByUrl:
-
- // Request to add a torrent by URL
- String url = ((AddByUrlTask) task).getUrl();
- makeRtorrentCall("load_start", new String[] { url });
- return new DaemonTaskSuccessResult(task);
-
- case AddByMagnetUrl:
-
- // Request to add a magnet link by URL
- String magnet = ((AddByMagnetUrlTask) task).getUrl();
- makeRtorrentCall("load_start", new String[] { magnet });
- return new DaemonTaskSuccessResult(task);
-
- case Remove:
-
- // Remove a torrent
- RemoveTask removeTask = (RemoveTask) task;
- if (removeTask.includingData()) {
- makeRtorrentCall("d.set_custom5", new String[] { task.getTargetTorrent().getUniqueID(), "1" });
- }
- makeRtorrentCall("d.erase", new String[] { task.getTargetTorrent().getUniqueID() });
- return new DaemonTaskSuccessResult(task);
+ return new GetFileListTaskSuccessResult((GetFileListTask) task,
+ onTorrentFilesRetrieved(fresult, task.getTargetTorrent()));
+
+ case AddByFile:
+
+ // Request to add a torrent by local .torrent file
+ File file = new File(URI.create(((AddByFileTask) task).getFile()));
+ FileInputStream in = new FileInputStream(file);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ byte[] buffer = new byte[(int) file.length()];
+ int read;
+ while ((read = in.read(buffer, 0, buffer.length)) > 0) {
+ baos.write(buffer, 0, read);
+ }
+ byte[] bytes = baos.toByteArray();
+ int size = (int) file.length() * 2;
+ final int XMLRPC_EXTRA_PADDING = 1280;
+ makeRtorrentCall(log, "set_xmlrpc_size_limit", new Object[]{size + XMLRPC_EXTRA_PADDING});
+ makeRtorrentCall(log, "load_raw_start", new Object[]{bytes});
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByUrl:
+
+ // Request to add a torrent by URL
+ String url = ((AddByUrlTask) task).getUrl();
+ makeRtorrentCall(log, "load_start", new String[]{url});
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByMagnetUrl:
+
+ // Request to add a magnet link by URL
+ String magnet = ((AddByMagnetUrlTask) task).getUrl();
+ makeRtorrentCall(log, "load_start", new String[]{magnet});
+ return new DaemonTaskSuccessResult(task);
+
+ case Remove:
+
+ // Remove a torrent
+ RemoveTask removeTask = (RemoveTask) task;
+ if (removeTask.includingData()) {
+ makeRtorrentCall(log, "d.set_custom5",
+ new String[]{task.getTargetTorrent().getUniqueID(), "1"});
+ }
+ makeRtorrentCall(log, "d.erase", new String[]{task.getTargetTorrent().getUniqueID()});
+ return new DaemonTaskSuccessResult(task);
- case Pause:
+ case Pause:
- // Pause a torrent
- makeRtorrentCall("d.pause", new String[] { task.getTargetTorrent().getUniqueID() });
- return new DaemonTaskSuccessResult(task);
+ // Pause a torrent
+ makeRtorrentCall(log, "d.pause", new String[]{task.getTargetTorrent().getUniqueID()});
+ return new DaemonTaskSuccessResult(task);
- case PauseAll:
+ case PauseAll:
- // Resume all torrents
- makeRtorrentCall("d.multicall", new String[] { "main", "d.pause=" });
- return new DaemonTaskSuccessResult(task);
+ // Resume all torrents
+ makeRtorrentCall(log, "d.multicall", new String[]{"main", "d.pause="});
+ return new DaemonTaskSuccessResult(task);
- case Resume:
+ case Resume:
- // Resume a torrent
- makeRtorrentCall("d.resume", new String[] { task.getTargetTorrent().getUniqueID() });
- return new DaemonTaskSuccessResult(task);
+ // Resume a torrent
+ makeRtorrentCall(log, "d.resume", new String[]{task.getTargetTorrent().getUniqueID()});
+ return new DaemonTaskSuccessResult(task);
- case ResumeAll:
+ case ResumeAll:
- // Resume all torrents
- makeRtorrentCall("d.multicall", new String[] { "main", "d.resume=" });
- return new DaemonTaskSuccessResult(task);
+ // Resume all torrents
+ makeRtorrentCall(log, "d.multicall", new String[]{"main", "d.resume="});
+ return new DaemonTaskSuccessResult(task);
- case Stop:
+ case Stop:
- // Stop a torrent
- makeRtorrentCall("d.stop", new String[] { task.getTargetTorrent().getUniqueID() });
- return new DaemonTaskSuccessResult(task);
+ // Stop a torrent
+ makeRtorrentCall(log, "d.stop", new String[]{task.getTargetTorrent().getUniqueID()});
+ return new DaemonTaskSuccessResult(task);
- case StopAll:
+ case StopAll:
- // Stop all torrents
- makeRtorrentCall("d.multicall", new String[] { "main", "d.stop=" });
- return new DaemonTaskSuccessResult(task);
+ // Stop all torrents
+ makeRtorrentCall(log, "d.multicall", new String[]{"main", "d.stop="});
+ return new DaemonTaskSuccessResult(task);
- case Start:
+ case Start:
- // Start a torrent
- makeRtorrentCall("d.start", new String[] { task.getTargetTorrent().getUniqueID() });
- return new DaemonTaskSuccessResult(task);
+ // Start a torrent
+ makeRtorrentCall(log, "d.start", new String[]{task.getTargetTorrent().getUniqueID()});
+ return new DaemonTaskSuccessResult(task);
- case StartAll:
+ case StartAll:
- // Start all torrents
- makeRtorrentCall("d.multicall", new String[] { "main", "d.start=" });
- return new DaemonTaskSuccessResult(task);
+ // Start all torrents
+ makeRtorrentCall(log, "d.multicall", new String[]{"main", "d.start="});
+ return new DaemonTaskSuccessResult(task);
- case SetFilePriorities:
+ case SetFilePriorities:
- // For each of the chosen files belonging to some torrent, set the priority
- SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
- String newPriority = "" + convertPriority(prioTask.getNewPriority());
- // One at a time; rTorrent doesn't seem to support a multicall on a selective number of files
- for (TorrentFile forFile : prioTask.getForFiles()) {
- makeRtorrentCall("f.set_priority", new String[] {
- task.getTargetTorrent().getUniqueID() + ":f" + forFile.getKey(), newPriority });
- }
- return new DaemonTaskSuccessResult(task);
+ // For each of the chosen files belonging to some torrent, set the priority
+ SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
+ String newPriority = "" + convertPriority(prioTask.getNewPriority());
+ // One at a time; rTorrent doesn't seem to support a multicall on a selective number of files
+ for (TorrentFile forFile : prioTask.getForFiles()) {
+ makeRtorrentCall(log, "f.set_priority",
+ new String[]{task.getTargetTorrent().getUniqueID() + ":f" + forFile.getKey(),
+ newPriority});
+ }
+ return new DaemonTaskSuccessResult(task);
- case SetTransferRates:
+ case SetTransferRates:
- // Request to set the maximum transfer rates
- SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
- makeRtorrentCall("set_download_rate", new String[] { (ratesTask.getDownloadRate() == null ? "0"
- : ratesTask.getDownloadRate().toString() + "k") });
- makeRtorrentCall("set_upload_rate", new String[] { (ratesTask.getUploadRate() == null ? "0" : ratesTask
- .getUploadRate().toString() + "k") });
- return new DaemonTaskSuccessResult(task);
+ // Request to set the maximum transfer rates
+ SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
+ makeRtorrentCall(log, "set_download_rate", new String[]{(ratesTask.getDownloadRate() == null ? "0" :
+ ratesTask.getDownloadRate().toString() + "k")});
+ makeRtorrentCall(log, "set_upload_rate", new String[]{
+ (ratesTask.getUploadRate() == null ? "0" : ratesTask.getUploadRate().toString() + "k")});
+ return new DaemonTaskSuccessResult(task);
- case SetLabel:
+ case SetLabel:
- SetLabelTask labelTask = (SetLabelTask) task;
- makeRtorrentCall("d.set_custom1",
- new String[] { task.getTargetTorrent().getUniqueID(), labelTask.getNewLabel() });
- return new DaemonTaskSuccessResult(task);
+ SetLabelTask labelTask = (SetLabelTask) task;
+ makeRtorrentCall(log, "d.set_custom1",
+ new String[]{task.getTargetTorrent().getUniqueID(), labelTask.getNewLabel()});
+ return new DaemonTaskSuccessResult(task);
- case ForceRecheck:
+ case ForceRecheck:
- // Force re-check of data of a torrent
- makeRtorrentCall("d.check_hash", new String[] { task.getTargetTorrent().getUniqueID() });
- return new DaemonTaskSuccessResult(task);
+ // Force re-check of data of a torrent
+ makeRtorrentCall(log, "d.check_hash", new String[]{task.getTargetTorrent().getUniqueID()});
+ return new DaemonTaskSuccessResult(task);
- default:
- return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
- task.getMethod() + " is not supported by " + getType()));
+ default:
+ return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
+ task.getMethod() + " is not supported by " + getType()));
}
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
@@ -290,8 +293,8 @@ public class RtorrentAdapter implements IDaemonAdapter {
}
}
- private Object makeRtorrentCall(String serverMethod, Object[] arguments) throws DaemonException,
- MalformedURLException {
+ private Object makeRtorrentCall(Log log, String serverMethod, Object[] arguments)
+ throws DaemonException, MalformedURLException {
// Initialise the HTTP client
if (rpcclient == null) {
@@ -299,22 +302,25 @@ public class RtorrentAdapter implements IDaemonAdapter {
}
String params = "";
- for (Object arg : arguments)
+ for (Object arg : arguments) {
params += " " + arg.toString();
+ }
try {
- DLog.d(LOG_NAME,
- "Calling " + serverMethod + " with params ["
- + (params.length() > 100 ? params.substring(0, 100) + "..." : params) + " ]");
+ log.d(LOG_NAME, "Calling " + serverMethod + " with params [" +
+ (params.length() > 100 ? params.substring(0, 100) + "..." : params) + " ]");
return rpcclient.call(serverMethod, arguments);
} catch (XMLRPCException e) {
- DLog.d(LOG_NAME, e.toString());
- if (e.getCause() instanceof UnauthorizdException)
+ log.d(LOG_NAME, e.toString());
+ if (e.getCause() instanceof UnauthorizdException) {
throw new DaemonException(ExceptionType.AuthenticationFailure, e.toString());
- if (e.getCause() instanceof DaemonException)
+ }
+ if (e.getCause() instanceof DaemonException) {
throw (DaemonException) e.getCause();
- throw new DaemonException(ExceptionType.ConnectionError, "Error making call to " + serverMethod
- + " with params [" + (params.length() > 100 ? params.substring(0, 100) + "..." : params) + " ]: "
- + e.toString());
+ }
+ throw new DaemonException(ExceptionType.ConnectionError,
+ "Error making call to " + serverMethod + " with params [" +
+ (params.length() > 100 ? params.substring(0, 100) + "..." : params) + " ]: " +
+ e.toString());
}
}
@@ -336,12 +342,9 @@ public class RtorrentAdapter implements IDaemonAdapter {
* @return The URL of the RPC API
*/
private String buildWebUIUrl() {
- return (settings.getSsl() ? "https://" : "http://")
- + settings.getAddress()
- + ":"
- + settings.getPort()
- + (settings.getFolder() == null || settings.getFolder().equals("") ? DEFAULT_RPC_URL : settings
- .getFolder());
+ return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() +
+ (settings.getFolder() == null || settings.getFolder().equals("") ? DEFAULT_RPC_URL :
+ settings.getFolder());
}
private List onTorrentsRetrieved(Object response) throws DaemonException {
@@ -365,7 +368,7 @@ public class RtorrentAdapter implements IDaemonAdapter {
error = error.equals("") ? null : error;
// Determine the time added
- Date added = null;
+ Date added;
Long addtime = null;
try {
addtime = Long.valueOf(((String) info[19]).trim());
@@ -373,14 +376,16 @@ public class RtorrentAdapter implements IDaemonAdapter {
// Not a number (timestamp); ignore and fall back to using creationtime
}
if (addtime != null)
- // Successfully received the addtime from rTorrent (which is a String like '1337089336\n')
+ // Successfully received the addtime from rTorrent (which is a String like '1337089336\n')
+ {
added = new Date(addtime * 1000L);
- else {
+ } else {
// rTorrent didn't have the addtime (missing plugin?): base it on creationtime instead
- if (info[11] instanceof Long)
+ if (info[11] instanceof Long) {
added = new Date((Long) info[11] * 1000L);
- else
+ } else {
added = new Date((Integer) info[11] * 1000L);
+ }
}
// Determine the seeding time
@@ -392,8 +397,10 @@ public class RtorrentAdapter implements IDaemonAdapter {
// Not a number (timestamp); ignore and fall back to using creationtime
}
if (seedingtime != null)
- // Successfully received the seedingtime from rTorrent (which is a String like '1337089336\n')
+ // Successfully received the seedingtime from rTorrent (which is a String like '1337089336\n')
+ {
finished = new Date(seedingtime * 1000L);
+ }
// Determine the label
String label = null;
@@ -455,11 +462,11 @@ public class RtorrentAdapter implements IDaemonAdapter {
basePath.substring(0, basePath.indexOf((String)info[17])), // locationDir
rateDownload, // rateDownload
(Integer)info[4], // rateUpload
- ((Integer)info[22]).intValue(), // seedersConnected
- ((Integer)info[5]).intValue() + ((Integer)info[6]).intValue(), // seedersKnown
- ((Integer)info[23]).intValue(), // leechersConnected
- ((Integer)info[5]).intValue() + ((Integer)info[6]).intValue(), // leechersKnown
- (rateDownload > 0? (int) ((Integer)info[12] / rateDownload): -1), // eta (bytes left / rate download, if rate > 0)
+ (Integer)info[22], // seedersConnected
+ (Integer)info[5] + (Integer)info[6], // seedersKnown
+ (Integer)info[23], // leechersConnected
+ (Integer)info[5] + (Integer)info[6], // leechersKnown
+ (rateDownload > 0? (Integer)info[12] / rateDownload: -1), // eta (bytes left / rate download, if rate > 0)
(Integer)info[8], // downloadedEver
(Integer)info[9], // uploadedEver
(Integer)info[10], // totalSize
@@ -476,8 +483,9 @@ public class RtorrentAdapter implements IDaemonAdapter {
}
lastKnownLabels = new ArrayList();
for (Entry pair : labels.entrySet()) {
- if (pair.getKey() != null)
+ if (pair.getKey() != null) {
lastKnownLabels.add(new Label(pair.getKey(), pair.getValue()));
+ }
}
return torrents;
@@ -550,24 +558,24 @@ public class RtorrentAdapter implements IDaemonAdapter {
private Priority convertRtorrentPriority(int code) {
// Note that Rtorrent has no low priority value
switch (code) {
- case 0:
- return Priority.Off;
- case 2:
- return Priority.High;
- default:
- return Priority.Normal;
+ case 0:
+ return Priority.Off;
+ case 2:
+ return Priority.High;
+ default:
+ return Priority.Normal;
}
}
private int convertPriority(Priority priority) {
// Note that Rtorrent has no low priority value
switch (priority) {
- case Off:
- return 0;
- case High:
- return 2;
- default:
- return 1;
+ case Off:
+ return 0;
+ case High:
+ return 2;
+ default:
+ return 1;
}
}
@@ -587,7 +595,7 @@ public class RtorrentAdapter implements IDaemonAdapter {
}
}
- private TorrentDetails onTorrentDetailsRetrieved(Object response) throws DaemonException {
+ private TorrentDetails onTorrentDetailsRetrieved(Log log, Object response) throws DaemonException {
if (response == null || !(response instanceof Object[])) {
@@ -601,12 +609,12 @@ public class RtorrentAdapter implements IDaemonAdapter {
List trackers = new ArrayList();
Object[] responseList = (Object[]) response;
try {
- for (int i = 0; i < responseList.length; i++) {
- Object[] info = (Object[]) responseList[i];
+ for (Object aResponseList : responseList) {
+ Object[] info = (Object[]) aResponseList;
trackers.add((String) info[0]);
}
} catch (Exception e) {
- DLog.e(LOG_NAME, e.toString());
+ log.e(LOG_NAME, e.toString());
}
return new TorrentDetails(trackers, null);
diff --git a/app/src/main/java/org/transdroid/daemon/Synology/SynologyAdapter.java b/app/src/main/java/org/transdroid/daemon/Synology/SynologyAdapter.java
index b3fab518..0ec63909 100644
--- a/app/src/main/java/org/transdroid/daemon/Synology/SynologyAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Synology/SynologyAdapter.java
@@ -17,13 +17,6 @@
*/
package org.transdroid.daemon.Synology;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
@@ -31,6 +24,7 @@ import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonException.ExceptionType;
@@ -55,12 +49,17 @@ import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetTransferRatesTask;
import org.transdroid.daemon.util.Collections2;
-import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
/**
* The daemon adapter from the Synology Download Station torrent client.
- *
*/
public class SynologyAdapter implements IDaemonAdapter {
@@ -76,47 +75,48 @@ public class SynologyAdapter implements IDaemonAdapter {
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
String tid;
try {
switch (task.getMethod()) {
case Retrieve:
- return new RetrieveTaskSuccessResult((RetrieveTask) task, tasksList(), null);
+ return new RetrieveTaskSuccessResult((RetrieveTask) task, tasksList(log), null);
case GetStats:
return null;
case GetTorrentDetails:
tid = task.getTargetTorrent().getUniqueID();
- return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, torrentDetails(tid));
+ return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
+ torrentDetails(log, tid));
case GetFileList:
tid = task.getTargetTorrent().getUniqueID();
- return new GetFileListTaskSuccessResult((GetFileListTask) task, fileList(tid));
+ return new GetFileListTaskSuccessResult((GetFileListTask) task, fileList(log, tid));
case AddByFile:
return null;
case AddByUrl:
- String url = ((AddByUrlTask)task).getUrl();
- createTask(url);
+ String url = ((AddByUrlTask) task).getUrl();
+ createTask(log, url);
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
- String magnet = ((AddByMagnetUrlTask)task).getUrl();
- createTask(magnet);
+ String magnet = ((AddByMagnetUrlTask) task).getUrl();
+ createTask(log, magnet);
return new DaemonTaskSuccessResult(task);
case Remove:
tid = task.getTargetTorrent().getUniqueID();
- removeTask(tid);
+ removeTask(log, tid);
return new DaemonTaskSuccessResult(task);
case Pause:
tid = task.getTargetTorrent().getUniqueID();
- pauseTask(tid);
+ pauseTask(log, tid);
return new DaemonTaskSuccessResult(task);
case PauseAll:
- pauseAllTasks();
+ pauseAllTasks(log);
return new DaemonTaskSuccessResult(task);
case Resume:
tid = task.getTargetTorrent().getUniqueID();
- resumeTask(tid);
+ resumeTask(log, tid);
return new DaemonTaskSuccessResult(task);
case ResumeAll:
- resumeAllTasks();
+ resumeAllTasks(log);
return new DaemonTaskSuccessResult(task);
case SetDownloadLocation:
return null;
@@ -124,9 +124,9 @@ public class SynologyAdapter implements IDaemonAdapter {
return null;
case SetTransferRates:
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
- int uploadRate = ratesTask.getUploadRate() == null ? 0 : ratesTask.getUploadRate().intValue();
- int downloadRate = ratesTask.getDownloadRate() == null ? 0 : ratesTask.getDownloadRate().intValue();
- setTransferRates(uploadRate, downloadRate);
+ int uploadRate = ratesTask.getUploadRate() == null ? 0 : ratesTask.getUploadRate();
+ int downloadRate = ratesTask.getDownloadRate() == null ? 0 : ratesTask.getDownloadRate();
+ setTransferRates(log, uploadRate, downloadRate);
return new DaemonTaskSuccessResult(task);
case SetAlternativeMode:
default:
@@ -149,84 +149,87 @@ public class SynologyAdapter implements IDaemonAdapter {
// Synology API
- private String login() throws DaemonException {
- DLog.d(LOG_NAME, "login()");
+ private String login(Log log) throws DaemonException {
+ log.d(LOG_NAME, "login()");
try {
- return new SynoRequest(
- "auth.cgi",
- "SYNO.API.Auth",
- "2"
- ).get("&method=login&account=" + settings.getUsername() + "&passwd=" + settings.getPassword() + "&session=DownloadStation&format=sid"
- ).getData().getString("sid");
+ return new SynoRequest("auth.cgi", "SYNO.API.Auth", "2")
+ .get("&method=login&account=" + settings.getUsername() + "&passwd=" + settings.getPassword() +
+ "&session=DownloadStation&format=sid").getData(log).getString("sid");
} catch (JSONException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
}
}
- private void setTransferRates(int uploadRate, int downloadRate) throws DaemonException {
- authGet("SYNO.DownloadStation.Info", "1", "DownloadStation/info.cgi",
- "&method=setserverconfig&bt_max_upload=" + uploadRate + "&bt_max_download=" + downloadRate).ensureSuccess();
+ private void setTransferRates(Log log, int uploadRate, int downloadRate) throws DaemonException {
+ authGet(log, "SYNO.DownloadStation.Info", "1", "DownloadStation/info.cgi",
+ "&method=setserverconfig&bt_max_upload=" + uploadRate + "&bt_max_download=" + downloadRate)
+ .ensureSuccess(log);
}
- private void createTask(String uri) throws DaemonException {
+ private void createTask(Log log, String uri) throws DaemonException {
try {
- authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=create&uri=" + URLEncoder.encode(uri, "UTF-8")).ensureSuccess();
+ authGet(log, "SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi",
+ "&method=create&uri=" + URLEncoder.encode(uri, "UTF-8")).ensureSuccess(log);
} catch (UnsupportedEncodingException e) {
// Never happens
throw new DaemonException(ExceptionType.UnexpectedResponse, e.toString());
}
}
- private void removeTask(String tid) throws DaemonException {
+ private void removeTask(Log log, String tid) throws DaemonException {
List tids = new ArrayList();
tids.add(tid);
- removeTasks(tids);
+ removeTasks(log, tids);
}
- private void pauseTask(String tid) throws DaemonException {
+ private void pauseTask(Log log, String tid) throws DaemonException {
List tids = new ArrayList();
tids.add(tid);
- pauseTasks(tids);
+ pauseTasks(log, tids);
}
- private void resumeTask(String tid) throws DaemonException {
+ private void resumeTask(Log log, String tid) throws DaemonException {
List tids = new ArrayList();
tids.add(tid);
- resumeTasks(tids);
+ resumeTasks(log, tids);
}
- private void pauseAllTasks() throws DaemonException {
+ private void pauseAllTasks(Log log) throws DaemonException {
List tids = new ArrayList();
- for (Torrent torrent: tasksList()) {
+ for (Torrent torrent : tasksList(log)) {
tids.add(torrent.getUniqueID());
}
- pauseTasks(tids);
+ pauseTasks(log, tids);
}
- private void resumeAllTasks() throws DaemonException {
+ private void resumeAllTasks(Log log) throws DaemonException {
List tids = new ArrayList();
- for (Torrent torrent: tasksList()) {
+ for (Torrent torrent : tasksList(log)) {
tids.add(torrent.getUniqueID());
}
- resumeTasks(tids);
+ resumeTasks(log, tids);
}
- private void removeTasks(List tids) throws DaemonException {
- authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=delete&id=" + Collections2.joinString(tids, ",") + "").ensureSuccess();
+ private void removeTasks(Log log, List tids) throws DaemonException {
+ authGet(log, "SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi",
+ "&method=delete&id=" + Collections2.joinString(tids, ",") + "").ensureSuccess(log);
}
- private void pauseTasks(List tids) throws DaemonException {
- authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=pause&id=" + Collections2.joinString(tids, ",")).ensureSuccess();
+ private void pauseTasks(Log log, List tids) throws DaemonException {
+ authGet(log, "SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi",
+ "&method=pause&id=" + Collections2.joinString(tids, ",")).ensureSuccess(log);
}
- private void resumeTasks(List tids) throws DaemonException {
- authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=resume&id=" + Collections2.joinString(tids, ",")).ensureSuccess();
+ private void resumeTasks(Log log, List tids) throws DaemonException {
+ authGet(log, "SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi",
+ "&method=resume&id=" + Collections2.joinString(tids, ",")).ensureSuccess(log);
}
- private List tasksList() throws DaemonException {
+ private List tasksList(Log log) throws DaemonException {
try {
- JSONArray jsonTasks = authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=list&additional=detail,transfer,tracker").getData().getJSONArray("tasks");
- DLog.d(LOG_NAME, "Tasks = " + jsonTasks.toString());
+ JSONArray jsonTasks = authGet(log, "SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi",
+ "&method=list&additional=detail,transfer,tracker").getData(log).getJSONArray("tasks");
+ log.d(LOG_NAME, "Tasks = " + jsonTasks.toString());
List result = new ArrayList();
for (int i = 0; i < jsonTasks.length(); i++) {
result.add(parseTorrent(i, jsonTasks.getJSONObject(i)));
@@ -237,16 +240,21 @@ public class SynologyAdapter implements IDaemonAdapter {
}
}
- private List fileList(String torrentId) throws DaemonException {
+ private List fileList(Log log, String torrentId) throws DaemonException {
try {
List result = new ArrayList();
- JSONObject jsonTask = authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=getinfo&id=" + torrentId + "&additional=detail,transfer,tracker,file").getData().getJSONArray("tasks").getJSONObject(0);
- DLog.d(LOG_NAME, "File list = " + jsonTask.toString());
+ JSONObject jsonTask = authGet(log, "SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi",
+ "&method=getinfo&id=" + torrentId + "&additional=detail,transfer,tracker,file").getData(log)
+ .getJSONArray("tasks").getJSONObject(0);
+ log.d(LOG_NAME, "File list = " + jsonTask.toString());
JSONObject additional = jsonTask.getJSONObject("additional");
- if (!additional.has("file")) return result;
+ if (!additional.has("file")) {
+ return result;
+ }
JSONArray files = additional.getJSONArray("file");
for (int i = 0; i < files.length(); i++) {
JSONObject task = files.getJSONObject(i);
+ // @formatter:off
result.add(new TorrentFile(
task.getString("filename"),
task.getString("filename"),
@@ -255,6 +263,7 @@ public class SynologyAdapter implements IDaemonAdapter {
task.getLong("size"),
task.getLong("size_downloaded"),
priority(task.getString("priority"))
+ // @formatter:on
));
}
return result;
@@ -263,11 +272,13 @@ public class SynologyAdapter implements IDaemonAdapter {
}
}
- private TorrentDetails torrentDetails(String torrentId) throws DaemonException {
+ private TorrentDetails torrentDetails(Log log, String torrentId) throws DaemonException {
List trackers = new ArrayList();
List errors = new ArrayList();
try {
- JSONObject jsonTorrent = authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=getinfo&id=" + torrentId + "&additional=tracker").getData().getJSONArray("tasks").getJSONObject(0);
+ JSONObject jsonTorrent = authGet(log, "SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi",
+ "&method=getinfo&id=" + torrentId + "&additional=tracker").getData(log).getJSONArray("tasks")
+ .getJSONObject(0);
JSONObject additional = jsonTorrent.getJSONObject("additional");
if (additional.has("tracker")) {
JSONArray tracker = additional.getJSONArray("tracker");
@@ -293,7 +304,7 @@ public class SynologyAdapter implements IDaemonAdapter {
long downloaded = transfer.getLong("size_downloaded");
int speed = transfer.getInt("speed_download");
long size = jsonTorrent.getLong("size");
- Float eta = new Float(size - downloaded) / speed;
+ Float eta = Float.valueOf(size - downloaded) / speed;
int totalSeeders = 0;
int totalLeechers = 0;
if (additional.has("tracker")) {
@@ -306,6 +317,7 @@ public class SynologyAdapter implements IDaemonAdapter {
}
}
}
+ // @formatter:off
return new Torrent(
id,
jsonTorrent.getString("id"),
@@ -322,79 +334,71 @@ public class SynologyAdapter implements IDaemonAdapter {
downloaded,
transfer.getLong("size_uploaded"),
size,
- (size == 0) ? 0 : (new Float(downloaded) / size),
+ (size == 0) ? 0 : (Float.valueOf(downloaded) / size),
0,
jsonTorrent.getString("title"),
new Date(detail.getLong("create_time") * 1000),
null,
"",
settings.getType()
+ // @formatter:on
);
}
private TorrentStatus torrentStatus(String status) {
- if ("downloading".equals(status)) return TorrentStatus.Downloading;
- if ("seeding".equals(status)) return TorrentStatus.Seeding;
- if ("finished".equals(status)) return TorrentStatus.Paused;
- if ("finishing".equals(status)) return TorrentStatus.Paused;
- if ("waiting".equals(status)) return TorrentStatus.Waiting;
- if ("paused".equals(status)) return TorrentStatus.Paused;
- if ("error".equals(status)) return TorrentStatus.Error;
+ if ("downloading".equals(status)) {
+ return TorrentStatus.Downloading;
+ }
+ if ("seeding".equals(status)) {
+ return TorrentStatus.Seeding;
+ }
+ if ("finished".equals(status)) {
+ return TorrentStatus.Paused;
+ }
+ if ("finishing".equals(status)) {
+ return TorrentStatus.Paused;
+ }
+ if ("waiting".equals(status)) {
+ return TorrentStatus.Waiting;
+ }
+ if ("paused".equals(status)) {
+ return TorrentStatus.Paused;
+ }
+ if ("error".equals(status)) {
+ return TorrentStatus.Error;
+ }
return TorrentStatus.Unknown;
}
private Priority priority(String priority) {
- if ("low".equals(priority)) return Priority.Low;
- if ("normal".equals(priority)) return Priority.Normal;
- if ("high".equals(priority)) return Priority.High;
+ if ("low".equals(priority)) {
+ return Priority.Low;
+ }
+ if ("normal".equals(priority)) {
+ return Priority.Normal;
+ }
+ if ("high".equals(priority)) {
+ return Priority.High;
+ }
return Priority.Off;
}
/**
* Authenticated GET. If no session open, a login authGet will be done before-hand.
*/
- private SynoResponse authGet(String api, String version, String path, String params) throws DaemonException {
+ private SynoResponse authGet(Log log, String api, String version, String path, String params)
+ throws DaemonException {
if (sid == null) {
- sid = login();
+ sid = login(log);
}
return new SynoRequest(path, api, version).get(params + "&_sid=" + sid);
}
private DefaultHttpClient getHttpClient() throws DaemonException {
- if (httpClient == null)
+ if (httpClient == null) {
httpClient = HttpHelper.createStandardHttpClient(settings, true);
- return httpClient;
- }
-
- private class SynoRequest {
- private final String path;
- private final String api;
- private final String version;
-
- public SynoRequest(String path, String api, String version) {
- this.path = path;
- this.api = api;
- this.version = version;
}
-
- public SynoResponse get(String params) throws DaemonException {
- try {
- return new SynoResponse(getHttpClient().execute(new HttpGet(buildURL(params))));
- } catch (IOException e) {
- throw new DaemonException(ExceptionType.ConnectionError, e.toString());
- }
- }
-
- private String buildURL(String params) {
- return (settings.getSsl() ? "https://" : "http://")
- + settings.getAddress()
- + ":" + settings.getPort()
- + "/webapi/" + path
- + "?api=" + api
- + "&version=" + version
- + params;
- }
-
+ return httpClient;
}
private static class SynoResponse {
@@ -405,13 +409,13 @@ public class SynologyAdapter implements IDaemonAdapter {
this.response = response;
}
- public JSONObject getData() throws DaemonException {
- JSONObject json = getJson();
+ public JSONObject getData(Log log) throws DaemonException {
+ JSONObject json = getJson(log);
try {
if (json.getBoolean("success")) {
return json.getJSONObject("data");
} else {
- DLog.e(LOG_NAME, "not a success: " + json.toString());
+ log.e(LOG_NAME, "not a success: " + json.toString());
throw new DaemonException(ExceptionType.AuthenticationFailure, json.getString("error"));
}
} catch (JSONException e) {
@@ -419,11 +423,11 @@ public class SynologyAdapter implements IDaemonAdapter {
}
}
- public JSONObject getJson() throws DaemonException {
+ public JSONObject getJson(Log log) throws DaemonException {
try {
HttpEntity entity = response.getEntity();
if (entity == null) {
- DLog.e(LOG_NAME, "Error: No entity in HTTP response");
+ log.e(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
}
// Read JSON response
@@ -436,16 +440,17 @@ public class SynologyAdapter implements IDaemonAdapter {
} catch (JSONException e) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Bad JSON");
} catch (IOException e) {
- DLog.e(LOG_NAME, "getJson error: " + e.toString());
+ log.e(LOG_NAME, "getJson error: " + e.toString());
throw new DaemonException(ExceptionType.AuthenticationFailure, e.toString());
}
}
- public void ensureSuccess() throws DaemonException {
- JSONObject json = getJson();
+ public void ensureSuccess(Log log) throws DaemonException {
+ JSONObject json = getJson(log);
try {
- if (!json.getBoolean("success"))
+ if (!json.getBoolean("success")) {
throw new DaemonException(ExceptionType.UnexpectedResponse, json.getString("error"));
+ }
} catch (JSONException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
}
@@ -453,4 +458,30 @@ public class SynologyAdapter implements IDaemonAdapter {
}
+ private class SynoRequest {
+ private final String path;
+ private final String api;
+ private final String version;
+
+ public SynoRequest(String path, String api, String version) {
+ this.path = path;
+ this.api = api;
+ this.version = version;
+ }
+
+ public SynoResponse get(String params) throws DaemonException {
+ try {
+ return new SynoResponse(getHttpClient().execute(new HttpGet(buildURL(params))));
+ } catch (IOException e) {
+ throw new DaemonException(ExceptionType.ConnectionError, e.toString());
+ }
+ }
+
+ private String buildURL(String params) {
+ return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() +
+ "/webapi/" + path + "?api=" + api + "&version=" + version + params;
+ }
+
+ }
+
}
diff --git a/app/src/main/java/org/transdroid/daemon/TaskQueue.java b/app/src/main/java/org/transdroid/daemon/TaskQueue.java
deleted file mode 100644
index dd16189d..00000000
--- a/app/src/main/java/org/transdroid/daemon/TaskQueue.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * This file is part of Transdroid
- *
- * Transdroid is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * Transdroid is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Transdroid. If not, see .
- *
- */
-package org.transdroid.daemon;
-
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Queue;
-
-import org.transdroid.daemon.task.DaemonTask;
-import org.transdroid.daemon.task.DaemonTaskFailureResult;
-import org.transdroid.daemon.task.DaemonTaskResult;
-import org.transdroid.daemon.task.DaemonTaskSuccessResult;
-import org.transdroid.daemon.util.DLog;
-
-public class TaskQueue implements Runnable {
-
- private static final String LOG_NAME = "Queue";
-
- private List queue;
- private Thread worker;
- private IDaemonCallback callback;
- private boolean paused;;
-
- public TaskQueue(IDaemonCallback callback) {
- queue = Collections.synchronizedList(new LinkedList());
- paused = true;
- this.callback = callback;
- worker = new Thread(this);
- worker.start();
- }
-
- /**
- * Enqueue a single new task to later perform.
- * @param task The task to add to the queue
- */
- public synchronized void enqueue(DaemonTask task) {
- queue.add(task);
- notifyAll();
- }
-
- /**
- * Queues an old set of tasks again in the queue. This for example can be
- * used to restore on old queue after an Activity was destroyed and
- * is restored again.
- * @param tasks A list of daemon tasks to queue
- */
- public synchronized void requeue(List tasks) {
- queue.addAll(tasks);
- notifyAll();
- }
-
- /**
- * Removes all remaining tasks from the queue. Existing operations are still
- * continued and their results posted back.
- */
- public synchronized void clear() {
- queue.clear();
- notifyAll();
- }
-
- /**
- * Removes all remaining tasks from the queue that are of some specific type.
- * Other remaining tasks will still be executed and running operations are
- * still continued and their results posted back.
- * @param class1
- */
- public synchronized void clear(DaemonMethod ofType) {
- Iterator task = queue.iterator();
- while (task.hasNext()) {
- if (task.next().getMethod() == ofType) {
- task.remove();
- }
- }
- notifyAll();
- }
-
- /**
- * Returns a copy of the queue with all remaining tasks. This can be used
- * to save them on an Activity destroy and restore them later using
- * requeue().
- * @return A list containing all remaining tasks
- */
- public Queue getRemainingTasks() {
- return new LinkedList(queue);
- }
-
- /**
- * Request the task perfoming thread to stop all activity
- */
- public synchronized void requestStop() {
- paused = true;
- }
-
- /**
- * Request
- */
- public synchronized void start() {
- paused = false;
- notify();
- }
-
- @Override
- public void run() {
-
- while (true) {
-
- if (this.paused) {
- // We are going to pause
- DLog.d(LOG_NAME, "Task queue pausing");
- }
- synchronized (this) {
- while (this.paused || queue.isEmpty()) {
- try {
- // We are going to run again if wait() succeeded (on notify())
- wait();
- DLog.d(LOG_NAME, "Task queue resuming");
- } catch (Exception e) {
- }
- }
- }
-
- processTask();
-
- if (queue.isEmpty()) {
- callback.onQueueEmpty();
- // We are going to pause
- DLog.d(LOG_NAME, "Task queue pausing (queue empty)");
- }
-
- }
-
- }
-
- private void processTask() {
-
- // Get the task to execute
- DaemonTask task = queue.remove(0);
- if (task == null) {
- return;
- }
-
- if (callback.isAttached())
- callback.onQueuedTaskStarted(task);
-
- // Ask the daemon adapter to perform the task (which does it synchronously)
- DLog.d(LOG_NAME, "Starting task: " + task.toString());
- DaemonTaskResult result = task.execute();
-
- if (callback.isAttached())
- callback.onQueuedTaskFinished(task);
-
- // Return the result (to the UI thread)
- DLog.d(LOG_NAME, "Task result: " + (result == null? "null": result.toString()));
- if (result != null && !this.paused && callback.isAttached()) {
- if (result.wasSuccessful()) {
- callback.onTaskSuccess((DaemonTaskSuccessResult) result);
- } else {
- callback.onTaskFailure((DaemonTaskFailureResult) result);
- }
- }
-
- }
-
-}
diff --git a/app/src/main/java/org/transdroid/daemon/Tfb4rt/Tfb4rtAdapter.java b/app/src/main/java/org/transdroid/daemon/Tfb4rt/Tfb4rtAdapter.java
index c485302e..ddfa5bed 100644
--- a/app/src/main/java/org/transdroid/daemon/Tfb4rt/Tfb4rtAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Tfb4rt/Tfb4rtAdapter.java
@@ -30,6 +30,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
@@ -45,7 +46,6 @@ import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
-import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
import com.android.internalcopy.http.multipart.FilePart;
import com.android.internalcopy.http.multipart.MultipartEntity;
@@ -80,59 +80,59 @@ public class Tfb4rtAdapter implements IDaemonAdapter {
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
- return new RetrieveTaskSuccessResult((RetrieveTask) task, makeStatsRequest(), null);
+ return new RetrieveTaskSuccessResult((RetrieveTask) task, makeStatsRequest(log), null);
case AddByFile:
// Add a torrent to the server by sending the contents of a local .torrent file
String file = ((AddByFileTask) task).getFile();
- makeFileUploadRequest("fileUpload", file);
+ makeFileUploadRequest(log, "fileUpload", file);
return null;
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask) task).getUrl();
- makeActionRequest("urlUpload", url);
+ makeActionRequest(log, "urlUpload", url);
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
- makeActionRequest((removeTask.includingData() ? "deleteWithData" : "delete"), task.getTargetTorrent()
+ makeActionRequest(log, (removeTask.includingData() ? "deleteWithData" : "delete"), task.getTargetTorrent()
.getUniqueID());
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
- makeActionRequest("stop", task.getTargetTorrent().getUniqueID());
+ makeActionRequest(log, "stop", task.getTargetTorrent().getUniqueID());
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Pause all torrents
- makeActionRequest("bulkStop", null);
+ makeActionRequest(log, "bulkStop", null);
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
- makeActionRequest("start", task.getTargetTorrent().getUniqueID());
+ makeActionRequest(log, "start", task.getTargetTorrent().getUniqueID());
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
- makeActionRequest("bulkStart", null);
+ makeActionRequest(log, "bulkStart", null);
return new DaemonTaskSuccessResult(task);
case SetTransferRates:
@@ -150,7 +150,7 @@ public class Tfb4rtAdapter implements IDaemonAdapter {
}
}
- private List makeStatsRequest() throws DaemonException {
+ private List makeStatsRequest(Log log) throws DaemonException {
try {
@@ -170,16 +170,16 @@ public class Tfb4rtAdapter implements IDaemonAdapter {
return torrents;
} catch (DaemonException e) {
- DLog.d(LOG_NAME, "Parsing error: " + e.toString());
+ log.d(LOG_NAME, "Parsing error: " + e.toString());
throw e;
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
- private boolean makeActionRequest(String action, String target) throws DaemonException {
+ private boolean makeActionRequest(Log log, String action, String target) throws DaemonException {
try {
@@ -204,16 +204,16 @@ public class Tfb4rtAdapter implements IDaemonAdapter {
}
} catch (DaemonException e) {
- DLog.d(LOG_NAME, action + " request error: " + e.toString());
+ log.d(LOG_NAME, action + " request error: " + e.toString());
throw e;
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
- private boolean makeFileUploadRequest(String action, String target) throws DaemonException {
+ private boolean makeFileUploadRequest(Log log, String action, String target) throws DaemonException {
try {
@@ -241,10 +241,10 @@ public class Tfb4rtAdapter implements IDaemonAdapter {
}
} catch (DaemonException e) {
- DLog.d(LOG_NAME, action + " request error: " + e.toString());
+ log.d(LOG_NAME, action + " request error: " + e.toString());
throw e;
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
@@ -252,7 +252,6 @@ public class Tfb4rtAdapter implements IDaemonAdapter {
/**
* Instantiates an HTTP client that can be used for all Torrentflux-b4rt requests.
- * @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise() throws DaemonException {
diff --git a/app/src/main/java/org/transdroid/daemon/TorrentFilesComparator.java b/app/src/main/java/org/transdroid/daemon/TorrentFilesComparator.java
index de6a5b09..c2fcb0d8 100644
--- a/app/src/main/java/org/transdroid/daemon/TorrentFilesComparator.java
+++ b/app/src/main/java/org/transdroid/daemon/TorrentFilesComparator.java
@@ -49,7 +49,7 @@ public class TorrentFilesComparator implements Comparator {
case PartDone:
return Float.compare(file1.getPartDone(), file2.getPartDone());
case TotalSize:
- return new Long(file1.getTotalSize()).compareTo(file2.getTotalSize());
+ return Long.valueOf(file1.getTotalSize()).compareTo(file2.getTotalSize());
default:
return alphanumComparator.compare(file1.getName().toLowerCase(), file2.getName().toLowerCase());
}
@@ -58,7 +58,7 @@ public class TorrentFilesComparator implements Comparator {
case PartDone:
return 0 - Float.compare(file1.getPartDone(), file2.getPartDone());
case TotalSize:
- return 0 - new Long(file1.getTotalSize()).compareTo(file2.getTotalSize());
+ return 0 - Long.valueOf(file1.getTotalSize()).compareTo(file2.getTotalSize());
default:
return 0 - alphanumComparator.compare(file1.getName().toLowerCase(), file2.getName().toLowerCase());
}
diff --git a/app/src/main/java/org/transdroid/daemon/TorrentsComparator.java b/app/src/main/java/org/transdroid/daemon/TorrentsComparator.java
index c1682158..ea9d7774 100644
--- a/app/src/main/java/org/transdroid/daemon/TorrentsComparator.java
+++ b/app/src/main/java/org/transdroid/daemon/TorrentsComparator.java
@@ -67,15 +67,15 @@ public class TorrentsComparator implements Comparator {
case DateDone:
return tor1.getDateDone().compareTo(tor2.getDateDone());
case Percent:
- return new Float(tor1.getDownloadedPercentage()).compareTo(new Float(tor2.getDownloadedPercentage()));
+ return Float.valueOf(tor1.getDownloadedPercentage()).compareTo(tor2.getDownloadedPercentage());
case DownloadSpeed:
- return new Integer(tor1.getRateDownload()).compareTo(new Integer(tor2.getRateDownload()));
+ return Integer.valueOf(tor1.getRateDownload()).compareTo(tor2.getRateDownload());
case UploadSpeed:
- return new Integer(tor1.getRateUpload()).compareTo(new Integer(tor2.getRateUpload()));
+ return Integer.valueOf(tor1.getRateUpload()).compareTo(tor2.getRateUpload());
case Ratio:
- return new Double(tor1.getRatio()).compareTo(new Double(tor2.getRatio()));
+ return Double.valueOf(tor1.getRatio()).compareTo(tor2.getRatio());
case Size:
- return new Double(tor1.getTotalSize()).compareTo(new Double(tor2.getTotalSize()));
+ return Double.valueOf(tor1.getTotalSize()).compareTo((double) tor2.getTotalSize());
default:
return alphanumComparator.compare(tor1.getName().toLowerCase(), tor2.getName().toLowerCase());
}
@@ -92,15 +92,15 @@ public class TorrentsComparator implements Comparator {
case DateDone:
return 0 - tor1.getDateDone().compareTo(tor2.getDateDone());
case Percent:
- return 0 - (new Float(tor1.getDownloadedPercentage()).compareTo(new Float(tor2.getDownloadedPercentage())));
+ return 0 - (Float.valueOf(tor1.getDownloadedPercentage()).compareTo(tor2.getDownloadedPercentage()));
case DownloadSpeed:
- return 0 - (new Integer(tor1.getRateDownload()).compareTo(new Integer(tor2.getRateDownload())));
+ return 0 - (Integer.valueOf(tor1.getRateDownload()).compareTo(tor2.getRateDownload()));
case UploadSpeed:
- return 0 - (new Integer(tor1.getRateUpload()).compareTo(new Integer(tor2.getRateUpload())));
+ return 0 - (Integer.valueOf(tor1.getRateUpload()).compareTo(tor2.getRateUpload()));
case Ratio:
- return 0 - new Double(tor1.getRatio()).compareTo(new Double(tor2.getRatio()));
+ return 0 - Double.valueOf(tor1.getRatio()).compareTo(tor2.getRatio());
case Size:
- return 0 - new Double(tor1.getTotalSize()).compareTo(new Double(tor2.getTotalSize()));
+ return 0 - Double.valueOf(tor1.getTotalSize()).compareTo((double) tor2.getTotalSize());
default:
return 0 - alphanumComparator.compare(tor1.getName().toLowerCase(), tor2.getName().toLowerCase());
}
diff --git a/app/src/main/java/org/transdroid/daemon/Transmission/TransmissionAdapter.java b/app/src/main/java/org/transdroid/daemon/Transmission/TransmissionAdapter.java
index d8f20768..da246c7f 100644
--- a/app/src/main/java/org/transdroid/daemon/Transmission/TransmissionAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Transmission/TransmissionAdapter.java
@@ -17,16 +17,6 @@
*/
package org.transdroid.daemon.Transmission;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
@@ -37,6 +27,7 @@ import org.base64.android.Base64.InputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonException.ExceptionType;
@@ -54,6 +45,7 @@ import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
+import org.transdroid.daemon.task.ForceRecheckTask;
import org.transdroid.daemon.task.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetStatsTask;
@@ -69,21 +61,28 @@ import org.transdroid.daemon.task.SetAlternativeModeTask;
import org.transdroid.daemon.task.SetDownloadLocationTask;
import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
-import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
/**
* The daemon adapter from the Transmission torrent client.
- *
* @author erickok
- *
*/
public class TransmissionAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "Transdroid daemon";
-
+
private static final int FOR_ALL = -1;
-
+
private static final String RPC_ID = "id";
private static final String RPC_NAME = "name";
private static final String RPC_STATUS = "status";
@@ -104,234 +103,255 @@ public class TransmissionAdapter implements IDaemonAdapter {
private static final String RPC_DATEDONE = "doneDate";
private static final String RPC_AVAILABLE = "desiredAvailable";
private static final String RPC_COMMENT = "comment";
-
+
private static final String RPC_FILE_NAME = "name";
private static final String RPC_FILE_LENGTH = "length";
private static final String RPC_FILE_COMPLETED = "bytesCompleted";
private static final String RPC_FILESTAT_WANTED = "wanted";
private static final String RPC_FILESTAT_PRIORITY = "priority";
-
+ private static String sessionToken;
private DaemonSettings settings;
private DefaultHttpClient httpclient;
- private static String sessionToken;
-
private long rpcVersion = -1;
-
+
public TransmissionAdapter(DaemonSettings settings) {
this.settings = settings;
}
-
+
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
-
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
+
try {
-
+
// Get the server version
if (rpcVersion <= -1) {
// Get server session statistics
- JSONObject response = makeRequest(buildRequestObject("session-get", new JSONObject()));
+ JSONObject response = makeRequest(log, buildRequestObject("session-get", new JSONObject()));
rpcVersion = response.getJSONObject("arguments").getInt("rpc-version");
}
-
+
JSONObject request = new JSONObject();
switch (task.getMethod()) {
- case Retrieve:
-
- // Request all torrents from server
- JSONArray fields = new JSONArray();
- final String[] fieldsArray = new String[] { RPC_ID, RPC_NAME, RPC_ERROR, RPC_ERRORSTRING, RPC_STATUS,
- RPC_DOWNLOADDIR, RPC_RATEDOWNLOAD, RPC_RATEUPLOAD, RPC_PEERSGETTING, RPC_PEERSSENDING,
- RPC_PEERSCONNECTED, RPC_ETA, RPC_DOWNLOADSIZE1, RPC_DOWNLOADSIZE2, RPC_UPLOADEDEVER,
- RPC_TOTALSIZE, RPC_DATEADDED, RPC_DATEDONE, RPC_AVAILABLE, RPC_COMMENT };
- for (String field : fieldsArray) {
- fields.put(field);
- }
- request.put("fields", fields);
-
- JSONObject result = makeRequest(buildRequestObject("torrent-get", request));
- return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result.getJSONObject("arguments")),null);
-
- case GetStats:
-
- // Request the current server statistics
- JSONObject stats = makeRequest(buildRequestObject("session-get", new JSONObject())).getJSONObject("arguments");
- return new GetStatsTaskSuccessResult((GetStatsTask) task, stats.getBoolean("alt-speed-enabled"),
- rpcVersion >= 12? stats.getLong("download-dir-free-space"): -1);
-
- case GetTorrentDetails:
-
- // Request fine details of a specific torrent
- JSONArray dfields = new JSONArray();
- dfields.put("trackers");
- dfields.put("trackerStats");
-
- JSONObject buildDGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false);
- buildDGet.put("fields", dfields);
- JSONObject getDResult = makeRequest(buildRequestObject("torrent-get", buildDGet));
- return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(getDResult.getJSONObject("arguments")));
-
- case GetFileList:
-
- // Request all details for a specific torrent
- JSONArray ffields = new JSONArray();
- ffields.put("files");
- ffields.put("fileStats");
-
- JSONObject buildGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false);
- buildGet.put("fields", ffields);
- JSONObject getResult = makeRequest(buildRequestObject("torrent-get", buildGet));
- return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFileList(getResult.getJSONObject("arguments"), task.getTargetTorrent()));
-
- case AddByFile:
-
- // Add a torrent to the server by sending the contents of a local .torrent file
- String file = ((AddByFileTask)task).getFile();
-
- // Encode the .torrent file's data
- InputStream in = new Base64.InputStream(new FileInputStream(new File(URI.create(file))), Base64.ENCODE);
- StringWriter writer = new StringWriter();
- int c;
- while ((c = in.read())!= -1) {
- writer.write(c);
- }
- in.close();
-
- // Request to add a torrent by Base64-encoded meta data
- request.put("metainfo", writer.toString());
-
- makeRequest(buildRequestObject("torrent-add", request));
- return new DaemonTaskSuccessResult(task);
-
- case AddByUrl:
-
- // Request to add a torrent by URL
- String url = ((AddByUrlTask)task).getUrl();
- request.put("filename", url);
-
- makeRequest(buildRequestObject("torrent-add", request));
- return new DaemonTaskSuccessResult(task);
-
- case AddByMagnetUrl:
-
- // Request to add a magnet link by URL
- String magnet = ((AddByMagnetUrlTask)task).getUrl();
- request.put("filename", magnet);
-
- makeRequest(buildRequestObject("torrent-add", request));
- return new DaemonTaskSuccessResult(task);
-
- case Remove:
-
- // Remove a torrent
- RemoveTask removeTask = (RemoveTask) task;
- makeRequest(buildRequestObject("torrent-remove", buildTorrentRequestObject(removeTask.getTargetTorrent().getUniqueID(), "delete-local-data", removeTask.includingData())));
- return new DaemonTaskSuccessResult(task);
-
- case Pause:
-
- // Pause a torrent
- PauseTask pauseTask = (PauseTask) task;
- makeRequest(buildRequestObject("torrent-stop", buildTorrentRequestObject(pauseTask.getTargetTorrent().getUniqueID(), null, false)));
- return new DaemonTaskSuccessResult(task);
-
- case PauseAll:
-
- // Resume all torrents
- makeRequest(buildRequestObject("torrent-stop", buildTorrentRequestObject(FOR_ALL, null, false)));
- return new DaemonTaskSuccessResult(task);
-
- case Resume:
-
- // Resume a torrent
- ResumeTask resumeTask = (ResumeTask) task;
- makeRequest(buildRequestObject("torrent-start", buildTorrentRequestObject(resumeTask.getTargetTorrent().getUniqueID(), null, false)));
- return new DaemonTaskSuccessResult(task);
-
- case ResumeAll:
-
- // Resume all torrents
- makeRequest(buildRequestObject("torrent-start", buildTorrentRequestObject(FOR_ALL, null, false)));
- return new DaemonTaskSuccessResult(task);
-
- case SetDownloadLocation:
-
- // Change the download location
- SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task;
- // Build request
- JSONObject sdlrequest = new JSONObject();
- JSONArray sdlids = new JSONArray();
- sdlids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
- sdlrequest.put("ids", sdlids);
- sdlrequest.put("location", sdlTask.getNewLocation());
- sdlrequest.put("move", true);
- makeRequest(buildRequestObject("torrent-set-location", sdlrequest));
- return new DaemonTaskSuccessResult(task);
-
- case SetFilePriorities:
-
- // Set priorities of the files of some torrent
- SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
-
- // Build request
- JSONObject prequest = new JSONObject();
- JSONArray ids = new JSONArray();
- ids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
- prequest.put("ids", ids);
- JSONArray fileids = new JSONArray();
- for (TorrentFile forfile : prioTask.getForFiles()) {
- fileids.put(Integer.parseInt(forfile.getKey())); // The keys are the indices of the files, so always numeric
- }
- switch (prioTask.getNewPriority()) {
- case Off:
- prequest.put("files-unwanted", fileids);
- break;
- case Low:
- prequest.put("files-wanted", fileids);
- prequest.put("priority-low", fileids);
- break;
- case Normal:
- prequest.put("files-wanted", fileids);
- prequest.put("priority-normal", fileids);
- break;
- case High:
- prequest.put("files-wanted", fileids);
- prequest.put("priority-high", fileids);
- break;
- }
-
- makeRequest(buildRequestObject("torrent-set", prequest));
- return new DaemonTaskSuccessResult(task);
-
- case SetTransferRates:
-
- // Request to set the maximum transfer rates
- SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
- if (ratesTask.getUploadRate() == null) {
- request.put("speed-limit-up-enabled", false);
- } else {
- request.put("speed-limit-up-enabled", true);
- request.put("speed-limit-up", ratesTask.getUploadRate().intValue());
- }
- if (ratesTask.getDownloadRate() == null) {
- request.put("speed-limit-down-enabled", false);
- } else {
- request.put("speed-limit-down-enabled", true);
- request.put("speed-limit-down", ratesTask.getDownloadRate().intValue());
- }
+ case Retrieve:
+
+ // Request all torrents from server
+ JSONArray fields = new JSONArray();
+ final String[] fieldsArray =
+ new String[]{RPC_ID, RPC_NAME, RPC_ERROR, RPC_ERRORSTRING, RPC_STATUS, RPC_DOWNLOADDIR,
+ RPC_RATEDOWNLOAD, RPC_RATEUPLOAD, RPC_PEERSGETTING, RPC_PEERSSENDING,
+ RPC_PEERSCONNECTED, RPC_ETA, RPC_DOWNLOADSIZE1, RPC_DOWNLOADSIZE2, RPC_UPLOADEDEVER,
+ RPC_TOTALSIZE, RPC_DATEADDED, RPC_DATEDONE, RPC_AVAILABLE, RPC_COMMENT};
+ for (String field : fieldsArray) {
+ fields.put(field);
+ }
+ request.put("fields", fields);
+
+ JSONObject result = makeRequest(log, buildRequestObject("torrent-get", request));
+ return new RetrieveTaskSuccessResult((RetrieveTask) task,
+ parseJsonRetrieveTorrents(result.getJSONObject("arguments")), null);
+
+ case GetStats:
+
+ // Request the current server statistics
+ JSONObject stats = makeRequest(log, buildRequestObject("session-get", new JSONObject()))
+ .getJSONObject("arguments");
+ return new GetStatsTaskSuccessResult((GetStatsTask) task, stats.getBoolean("alt-speed-enabled"),
+ rpcVersion >= 12 ? stats.getLong("download-dir-free-space") : -1);
- makeRequest(buildRequestObject("session-set", request));
- return new DaemonTaskSuccessResult(task);
-
- case SetAlternativeMode:
-
- // Request to set the alternative speed mode (Tutle Mode)
- SetAlternativeModeTask altModeTask = (SetAlternativeModeTask) task;
- request.put("alt-speed-enabled", altModeTask.isAlternativeModeEnabled());
- makeRequest(buildRequestObject("session-set", request));
- return new DaemonTaskSuccessResult(task);
-
- default:
- return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
+ case GetTorrentDetails:
+
+ // Request fine details of a specific torrent
+ JSONArray dfields = new JSONArray();
+ dfields.put("trackers");
+ dfields.put("trackerStats");
+
+ JSONObject buildDGet =
+ buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false);
+ buildDGet.put("fields", dfields);
+ JSONObject getDResult = makeRequest(log, buildRequestObject("torrent-get", buildDGet));
+ return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
+ parseJsonTorrentDetails(getDResult.getJSONObject("arguments")));
+
+ case GetFileList:
+
+ // Request all details for a specific torrent
+ JSONArray ffields = new JSONArray();
+ ffields.put("files");
+ ffields.put("fileStats");
+
+ JSONObject buildGet = buildTorrentRequestObject(task.getTargetTorrent().getUniqueID(), null, false);
+ buildGet.put("fields", ffields);
+ JSONObject getResult = makeRequest(log, buildRequestObject("torrent-get", buildGet));
+ return new GetFileListTaskSuccessResult((GetFileListTask) task,
+ parseJsonFileList(getResult.getJSONObject("arguments"), task.getTargetTorrent()));
+
+ case AddByFile:
+
+ // Add a torrent to the server by sending the contents of a local .torrent file
+ String file = ((AddByFileTask) task).getFile();
+
+ // Encode the .torrent file's data
+ InputStream in =
+ new Base64.InputStream(new FileInputStream(new File(URI.create(file))), Base64.ENCODE);
+ StringWriter writer = new StringWriter();
+ int c;
+ while ((c = in.read()) != -1) {
+ writer.write(c);
+ }
+ in.close();
+
+ // Request to add a torrent by Base64-encoded meta data
+ request.put("metainfo", writer.toString());
+
+ makeRequest(log, buildRequestObject("torrent-add", request));
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByUrl:
+
+ // Request to add a torrent by URL
+ String url = ((AddByUrlTask) task).getUrl();
+ request.put("filename", url);
+
+ makeRequest(log, buildRequestObject("torrent-add", request));
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByMagnetUrl:
+
+ // Request to add a magnet link by URL
+ String magnet = ((AddByMagnetUrlTask) task).getUrl();
+ request.put("filename", magnet);
+
+ makeRequest(log, buildRequestObject("torrent-add", request));
+ return new DaemonTaskSuccessResult(task);
+
+ case Remove:
+
+ // Remove a torrent
+ RemoveTask removeTask = (RemoveTask) task;
+ makeRequest(log, buildRequestObject("torrent-remove",
+ buildTorrentRequestObject(removeTask.getTargetTorrent().getUniqueID(), "delete-local-data",
+ removeTask.includingData())));
+ return new DaemonTaskSuccessResult(task);
+
+ case Pause:
+
+ // Pause a torrent
+ PauseTask pauseTask = (PauseTask) task;
+ makeRequest(log, buildRequestObject("torrent-stop",
+ buildTorrentRequestObject(pauseTask.getTargetTorrent().getUniqueID(), null, false)));
+ return new DaemonTaskSuccessResult(task);
+
+ case PauseAll:
+
+ // Resume all torrents
+ makeRequest(log,
+ buildRequestObject("torrent-stop", buildTorrentRequestObject(FOR_ALL, null, false)));
+ return new DaemonTaskSuccessResult(task);
+
+ case Resume:
+
+ // Resume a torrent
+ ResumeTask resumeTask = (ResumeTask) task;
+ makeRequest(log, buildRequestObject("torrent-start",
+ buildTorrentRequestObject(resumeTask.getTargetTorrent().getUniqueID(), null, false)));
+ return new DaemonTaskSuccessResult(task);
+
+ case ResumeAll:
+
+ // Resume all torrents
+ makeRequest(log,
+ buildRequestObject("torrent-start", buildTorrentRequestObject(FOR_ALL, null, false)));
+ return new DaemonTaskSuccessResult(task);
+
+ case SetDownloadLocation:
+
+ // Change the download location
+ SetDownloadLocationTask sdlTask = (SetDownloadLocationTask) task;
+ // Build request
+ JSONObject sdlrequest = new JSONObject();
+ JSONArray sdlids = new JSONArray();
+ sdlids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
+ sdlrequest.put("ids", sdlids);
+ sdlrequest.put("location", sdlTask.getNewLocation());
+ sdlrequest.put("move", true);
+ makeRequest(log, buildRequestObject("torrent-set-location", sdlrequest));
+ return new DaemonTaskSuccessResult(task);
+
+ case SetFilePriorities:
+
+ // Set priorities of the files of some torrent
+ SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
+
+ // Build request
+ JSONObject prequest = new JSONObject();
+ JSONArray ids = new JSONArray();
+ ids.put(Long.parseLong(task.getTargetTorrent().getUniqueID()));
+ prequest.put("ids", ids);
+ JSONArray fileids = new JSONArray();
+ for (TorrentFile forfile : prioTask.getForFiles()) {
+ fileids.put(Integer.parseInt(
+ forfile.getKey())); // The keys are the indices of the files, so always numeric
+ }
+ switch (prioTask.getNewPriority()) {
+ case Off:
+ prequest.put("files-unwanted", fileids);
+ break;
+ case Low:
+ prequest.put("files-wanted", fileids);
+ prequest.put("priority-low", fileids);
+ break;
+ case Normal:
+ prequest.put("files-wanted", fileids);
+ prequest.put("priority-normal", fileids);
+ break;
+ case High:
+ prequest.put("files-wanted", fileids);
+ prequest.put("priority-high", fileids);
+ break;
+ }
+
+ makeRequest(log, buildRequestObject("torrent-set", prequest));
+ return new DaemonTaskSuccessResult(task);
+
+ case SetTransferRates:
+
+ // Request to set the maximum transfer rates
+ SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
+ if (ratesTask.getUploadRate() == null) {
+ request.put("speed-limit-up-enabled", false);
+ } else {
+ request.put("speed-limit-up-enabled", true);
+ request.put("speed-limit-up", ratesTask.getUploadRate().intValue());
+ }
+ if (ratesTask.getDownloadRate() == null) {
+ request.put("speed-limit-down-enabled", false);
+ } else {
+ request.put("speed-limit-down-enabled", true);
+ request.put("speed-limit-down", ratesTask.getDownloadRate().intValue());
+ }
+
+ makeRequest(log, buildRequestObject("session-set", request));
+ return new DaemonTaskSuccessResult(task);
+
+ case SetAlternativeMode:
+
+ // Request to set the alternative speed mode (Tutle Mode)
+ SetAlternativeModeTask altModeTask = (SetAlternativeModeTask) task;
+ request.put("alt-speed-enabled", altModeTask.isAlternativeModeEnabled());
+ makeRequest(log, buildRequestObject("session-set", request));
+ return new DaemonTaskSuccessResult(task);
+
+ case ForceRecheck:
+
+ // Verify torrent data integrity
+ ForceRecheckTask verifyTask = (ForceRecheckTask) task;
+ makeRequest(log, buildRequestObject("torrent-verify",
+ buildTorrentRequestObject(verifyTask.getTargetTorrent().getUniqueID(), null, false)));
+ return new DaemonTaskSuccessResult(task);
+
+ default:
+ return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
+ task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
@@ -343,12 +363,14 @@ public class TransmissionAdapter implements IDaemonAdapter {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
}
}
-
- private JSONObject buildTorrentRequestObject(String torrentID, String extraKey, boolean extraValue ) throws JSONException {
+
+ private JSONObject buildTorrentRequestObject(String torrentID, String extraKey, boolean extraValue)
+ throws JSONException {
return buildTorrentRequestObject(Long.parseLong(torrentID), extraKey, extraValue);
}
-
- private JSONObject buildTorrentRequestObject(long torrentID, String extraKey, boolean extraValue ) throws JSONException {
+
+ private JSONObject buildTorrentRequestObject(long torrentID, String extraKey, boolean extraValue)
+ throws JSONException {
// Build request for one specific torrent
JSONObject request = new JSONObject();
@@ -363,7 +385,7 @@ public class TransmissionAdapter implements IDaemonAdapter {
return request;
}
-
+
private JSONObject buildRequestObject(String sendMethod, JSONObject arguments) throws JSONException {
// Build request for method
@@ -373,90 +395,89 @@ public class TransmissionAdapter implements IDaemonAdapter {
request.put("tag", 0);
return request;
}
-
- private synchronized JSONObject makeRequest(JSONObject data) throws DaemonException {
+
+ private synchronized JSONObject makeRequest(Log log, JSONObject data) throws DaemonException {
try {
-
+
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
final String sessionHeader = "X-Transmission-Session-Id";
-
+
// Setup request using POST stream with URL and data
HttpPost httppost = new HttpPost(buildWebUIUrl());
StringEntity se = new StringEntity(data.toString(), "UTF-8");
httppost.setEntity(se);
-
+
// Send the stored session token as a header
if (sessionToken != null) {
httppost.addHeader(sessionHeader, sessionToken);
}
-
+
// Execute
- DLog.d(LOG_NAME, "Execute " + data.getString("method") + " request to " + httppost.getURI().toString());
+ log.d(LOG_NAME, "Execute " + data.getString("method") + " request to " + httppost.getURI().toString());
HttpResponse response = httpclient.execute(httppost);
-
+
// Authentication error?
- if (response.getStatusLine().getStatusCode() == 401) {
+ if (response.getStatusLine().getStatusCode() == 401) {
throw new DaemonException(ExceptionType.AuthenticationFailure,
"401 HTTP response (username or password incorrect)");
}
-
+
// 409 error because of a session id?
if (response.getStatusLine().getStatusCode() == 409) {
-
+
// Retry post, but this time with the new session token that was encapsulated in the 409 response
- DLog.d(LOG_NAME, "Receive HTTP 409 with new session code; now try again for the actual request");
+ log.d(LOG_NAME, "Receive HTTP 409 with new session code; now try again for the actual request");
sessionToken = response.getFirstHeader(sessionHeader).getValue();
httppost.addHeader(sessionHeader, sessionToken);
- DLog.d(LOG_NAME, "Retry to execute " + data.getString("method") + " request, now with " + sessionHeader
- + ": " + sessionToken);
+ log.d(LOG_NAME,
+ "Retry to execute " + data.getString("method") + " request, now with " + sessionHeader + ": " +
+ sessionToken);
response = httpclient.execute(httppost);
-
+
}
-
+
HttpEntity entity = response.getEntity();
if (entity != null) {
-
+
// Read JSON response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.convertStreamToString(instream);
- DLog.d(LOG_NAME,
- "Received content response starting with "
- + (result.length() > 100 ? result.substring(0, 100) + "..." : result));
+ log.d(LOG_NAME, "Received content response starting with " +
+ (result.length() > 100 ? result.substring(0, 100) + "..." : result));
JSONObject json = new JSONObject(result);
instream.close();
-
+
// Return the JSON object
return json;
}
- DLog.d(LOG_NAME, "Error: No entity in HTTP response");
+ log.d(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
} catch (DaemonException e) {
throw e;
} catch (JSONException e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
-
+
}
/**
* Instantiates an HTTP client with proper credentials that can be used for all Transmission requests.
- * @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise() throws DaemonException {
httpclient = HttpHelper.createStandardHttpClient(settings, true);
}
-
+
/**
* Build the URL of the Transmission web UI from the user settings.
* @return The URL of the RPC API
@@ -467,22 +488,23 @@ public class TransmissionAdapter implements IDaemonAdapter {
// Allow the user's folder setting to override /transmission (as per Transmission's rpc-url option)
folder = settings.getFolder().trim();
// Strip any trailing slashes
- if (folder.endsWith("/"))
+ if (folder.endsWith("/")) {
folder = folder.substring(0, folder.length() - 1);
+ }
}
- return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + folder
- + "/rpc";
+ return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() +
+ folder + "/rpc";
}
private ArrayList parseJsonRetrieveTorrents(JSONObject response) throws JSONException {
-
+
// Parse response
ArrayList torrents = new ArrayList();
JSONArray rarray = response.getJSONArray("torrents");
for (int i = 0; i < rarray.length(); i++) {
JSONObject tor = rarray.getJSONObject(i);
// Add the parsed torrent to the list
- float have = (float)(tor.getLong(RPC_DOWNLOADSIZE1) + tor.getLong(RPC_DOWNLOADSIZE2));
+ float have = (float) (tor.getLong(RPC_DOWNLOADSIZE1) + tor.getLong(RPC_DOWNLOADSIZE2));
long total = tor.getLong(RPC_TOTALSIZE);
// Error is a number, see https://trac.transmissionbt.com/browser/trunk/libtransmission/transmission.h#L1747
// We only consider it a real error if it is local (blocking), which is error code 3
@@ -490,16 +512,18 @@ public class TransmissionAdapter implements IDaemonAdapter {
String errorString = tor.getString(RPC_ERRORSTRING).trim();
String commentString = tor.getString(RPC_COMMENT).trim();
if (!commentString.equals("")) {
- errorString = errorString.equals("")? commentString : errorString + "\n" + commentString;
+ errorString = errorString.equals("") ? commentString : errorString + "\n" + commentString;
}
String locationDir = tor.getString(RPC_DOWNLOADDIR);
- if (!locationDir.endsWith(settings.getOS().getPathSeperator()))
+ if (!locationDir.endsWith(settings.getOS().getPathSeperator())) {
locationDir += settings.getOS().getPathSeperator();
+ }
+ // @formatter:off
torrents.add(new Torrent(
tor.getInt(RPC_ID),
null,
tor.getString(RPC_NAME),
- hasError? TorrentStatus.Error: getStatus(tor.getInt(RPC_STATUS)),
+ hasError ? TorrentStatus.Error : getStatus(tor.getInt(RPC_STATUS)),
locationDir,
tor.getInt(RPC_RATEDOWNLOAD),
tor.getInt(RPC_RATEUPLOAD),
@@ -512,18 +536,19 @@ public class TransmissionAdapter implements IDaemonAdapter {
tor.getLong(RPC_UPLOADEDEVER),
tor.getLong(RPC_TOTALSIZE),
//(float) tor.getDouble(RPC_PERCENTDONE),
- (total == 0? 0: have/(float)total),
- (total == 0? 0: (have+(float)tor.getLong(RPC_AVAILABLE))/(float)total),
- null, // No label/category/group support in the RPC API for now
+ (total == 0 ? 0 : have / (float) total),
+ (total == 0 ? 0 : (have + (float) tor.getLong(RPC_AVAILABLE)) / (float) total),
+ // No label/category/group support in the RPC API for now
+ null,
new Date(tor.getLong(RPC_DATEADDED) * 1000L),
new Date(tor.getLong(RPC_DATEDONE) * 1000L),
- errorString,
- settings.getType()));
+ errorString, settings.getType()));
+ // @formatter:on
}
-
+
// Return the list
return torrents;
-
+
}
private TorrentStatus getStatus(int status) {
@@ -531,20 +556,20 @@ public class TransmissionAdapter implements IDaemonAdapter {
return TorrentStatus.Unknown;
} else if (rpcVersion >= 14) {
switch (status) {
- case 0:
- return TorrentStatus.Paused;
- case 1:
- return TorrentStatus.Waiting;
- case 2:
- return TorrentStatus.Checking;
- case 3:
- return TorrentStatus.Queued;
- case 4:
- return TorrentStatus.Downloading;
- case 5:
- return TorrentStatus.Queued;
- case 6:
- return TorrentStatus.Seeding;
+ case 0:
+ return TorrentStatus.Paused;
+ case 1:
+ return TorrentStatus.Waiting;
+ case 2:
+ return TorrentStatus.Checking;
+ case 3:
+ return TorrentStatus.Queued;
+ case 4:
+ return TorrentStatus.Downloading;
+ case 5:
+ return TorrentStatus.Queued;
+ case 6:
+ return TorrentStatus.Seeding;
}
return TorrentStatus.Unknown;
} else {
@@ -553,7 +578,7 @@ public class TransmissionAdapter implements IDaemonAdapter {
}
private ArrayList parseJsonFileList(JSONObject response, Torrent torrent) throws JSONException {
-
+
// Parse response
ArrayList torrentfiles = new ArrayList();
JSONArray rarray = response.getJSONArray("torrents");
@@ -563,20 +588,22 @@ public class TransmissionAdapter implements IDaemonAdapter {
for (int i = 0; i < files.length(); i++) {
JSONObject file = files.getJSONObject(i);
JSONObject stat = fileStats.getJSONObject(i);
+ // @formatter:off
torrentfiles.add(new TorrentFile(
- "" + i,
+ String.valueOf(i),
file.getString(RPC_FILE_NAME),
file.getString(RPC_FILE_NAME),
torrent.getLocationDir() + file.getString(RPC_FILE_NAME),
file.getLong(RPC_FILE_LENGTH),
file.getLong(RPC_FILE_COMPLETED),
convertTransmissionPriority(stat.getBoolean(RPC_FILESTAT_WANTED), stat.getInt(RPC_FILESTAT_PRIORITY))));
+ // @formatter:on
}
}
-
+
// Return the list
return torrentfiles;
-
+
}
private Priority convertTransmissionPriority(boolean isWanted, int priority) {
@@ -584,18 +611,18 @@ public class TransmissionAdapter implements IDaemonAdapter {
return Priority.Off;
} else {
switch (priority) {
- case 1:
- return Priority.High;
- case -1:
- return Priority.Low;
- default:
- return Priority.Normal;
+ case 1:
+ return Priority.High;
+ case -1:
+ return Priority.Low;
+ default:
+ return Priority.Normal;
}
}
}
private TorrentDetails parseJsonTorrentDetails(JSONObject response) throws JSONException {
-
+
// Parse response
// NOTE: Assumes only details for one torrent are requested at a time
JSONArray rarray = response.getJSONArray("torrents");
@@ -616,9 +643,9 @@ public class TransmissionAdapter implements IDaemonAdapter {
}
return new TorrentDetails(trackers, errors);
}
-
+
return null;
-
+
}
@Override
@@ -630,5 +657,5 @@ public class TransmissionAdapter implements IDaemonAdapter {
public DaemonSettings getSettings() {
return this.settings;
}
-
+
}
diff --git a/app/src/main/java/org/transdroid/daemon/Utorrent/UtorrentAdapter.java b/app/src/main/java/org/transdroid/daemon/Utorrent/UtorrentAdapter.java
index 245afcf3..9dd57284 100644
--- a/app/src/main/java/org/transdroid/daemon/Utorrent/UtorrentAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Utorrent/UtorrentAdapter.java
@@ -17,25 +17,18 @@
*/
package org.transdroid.daemon.Utorrent;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
+import com.android.internalcopy.http.multipart.FilePart;
+import com.android.internalcopy.http.multipart.MultipartEntity;
+import com.android.internalcopy.http.multipart.Part;
import org.apache.http.HttpResponse;
-import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonException.ExceptionType;
@@ -66,28 +59,59 @@ import org.transdroid.daemon.task.SetLabelTask;
import org.transdroid.daemon.task.SetTrackersTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
import org.transdroid.daemon.task.StartTask;
-import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
-import com.android.internalcopy.http.multipart.FilePart;
-import com.android.internalcopy.http.multipart.MultipartEntity;
-import com.android.internalcopy.http.multipart.Part;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
/**
- * An adapter that allows for easy access to uTorrent torrent data. Communication
- * is handled via authenticated JSON-RPC HTTP GET requests and responses.
- *
+ * An adapter that allows for easy access to uTorrent torrent data. Communication is handled via authenticated JSON-RPC
+ * HTTP GET requests and responses.
* @author erickok
- *
*/
public class UtorrentAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "uTorrent daemon";
private static final String RPC_URL_HASH = "&hash=";
-
+ private static final int NAME_IDX = 0;
+ private static final int COUNT_IDX = 1;
+ // These are the positions inside the JSON response array of a torrent
+ // See http://forum.utorrent.com/viewtopic.php?id=25661
+ private static final int RPC_HASH_IDX = 0;
+ private static final int RPC_STATUS_IDX = 1;
+ private static final int RPC_NAME_IDX = 2;
+ private static final int RPC_SIZE_IDX = 3;
+ private static final int RPC_PARTDONE = 4;
+ private static final int RPC_DOWNLOADED_IDX = 5;
+ private static final int RPC_UPLOADED_IDX = 6;
+ private static final int RPC_DOWNLOADSPEED_IDX = 9;
+ private static final int RPC_UPLOADSPEED_IDX = 8;
+ private static final int RPC_ETA_IDX = 10;
+ private static final int RPC_LABEL_IDX = 11;
+ private static final int RPC_PEERSCONNECTED_IDX = 12;
+ private static final int RPC_PEERSINSWARM_IDX = 13;
+ private static final int RPC_SEEDSCONNECTED_IDX = 14;
+ private static final int RPC_SEEDSINSWARM_IDX = 15;
+ private static final int RPC_AVAILABILITY_IDX = 16;
+ private static final int RPC_ADDEDON_IDX = 23;
+ private static final int RPC_COMPLETEDON_IDX = 24;
+ // These are the positions inside the JSON response array of a torrent
+ // See http://forum.utorrent.com/viewtopic.php?id=25661
+ private static final int RPC_FILENAME_IDX = 0;
+ private static final int RPC_FILESIZE_IDX = 1;
+ private static final int RPC_FILEDOWNLOADED_IDX = 2;
+ private static final int RPC_FILEPRIORITY_IDX = 3;
+ private static String authtoken;
private DaemonSettings settings;
private DefaultHttpClient httpclient;
- private static String authtoken;
/**
* Initialises an adapter that provides operations to the uTorrent web daemon
@@ -97,166 +121,180 @@ public class UtorrentAdapter implements IDaemonAdapter {
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
-
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
+
try {
switch (task.getMethod()) {
- case Retrieve:
-
- // Request all torrents from server
- JSONObject result = makeUtorrentRequest("&list=1");
- return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result.getJSONArray("torrents")),parseJsonRetrieveGetLabels(result.getJSONArray("label")));
-
- case GetTorrentDetails:
-
- // Request fine details of a specific torrent
- JSONObject dresult = makeUtorrentRequest("&action=getprops" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
- return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(dresult.getJSONArray("props")));
-
- case GetFileList:
-
- // Get the file listing of a torrent
- JSONObject files = makeUtorrentRequest("&action=getfiles" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
- return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFileListing(files.getJSONArray("files").getJSONArray(1), task.getTargetTorrent()));
-
- case AddByFile:
-
- // Add a torrent to the server by sending the contents of a local .torrent file
- String file = ((AddByFileTask)task).getFile();
- uploadTorrentFile(file);
- return new DaemonTaskSuccessResult(task);
-
- case AddByUrl:
-
- // Request to add a torrent by URL
- String url = ((AddByUrlTask)task).getUrl();
- if (url == null || url.equals(""))
- throw new DaemonException(DaemonException.ExceptionType.ParsingFailed, "No url specified");
- makeUtorrentRequest("&action=add-url&s=" + URLEncoder.encode(url, "UTF-8"));
- return new DaemonTaskSuccessResult(task);
-
- case AddByMagnetUrl:
-
- // Request to add a magnet link by URL
- String magnet = ((AddByMagnetUrlTask)task).getUrl();
- makeUtorrentRequest("&action=add-url&s=" + URLEncoder.encode(magnet, "UTF-8"));
- return new DaemonTaskSuccessResult(task);
-
- case Remove:
-
- // Remove a torrent
- RemoveTask removeTask = (RemoveTask) task;
- if (removeTask.includingData()) {
- makeUtorrentRequest("&action=removedata" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
- } else {
- makeUtorrentRequest("&action=remove" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
- }
- return new DaemonTaskSuccessResult(task);
-
- case Pause:
-
- // Pause a torrent
- makeUtorrentRequest("&action=pause" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
- return new DaemonTaskSuccessResult(task);
-
- case PauseAll:
-
- // Pause all torrents
- makeUtorrentRequest("&action=pause" + getAllHashes());
- return new DaemonTaskSuccessResult(task);
-
- case Resume:
-
- // Resume a torrent
- makeUtorrentRequest("&action=unpause" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
- return new DaemonTaskSuccessResult(task);
-
- case ResumeAll:
-
- // Resume all torrents
- makeUtorrentRequest("&action=unpause" + getAllHashes());
- return new DaemonTaskSuccessResult(task);
-
- case Stop:
-
- // Stop a torrent
- makeUtorrentRequest("&action=stop" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
- return new DaemonTaskSuccessResult(task);
-
- case StopAll:
-
- // Stop all torrents
- makeUtorrentRequest("&action=stop" + getAllHashes());
- return new DaemonTaskSuccessResult(task);
-
- case Start:
-
- // Start a torrent (maybe forced)
- StartTask startTask = (StartTask) task;
- if (startTask.isForced()) {
- makeUtorrentRequest("&action=forcestart" + RPC_URL_HASH + startTask.getTargetTorrent().getUniqueID());
- } else {
- makeUtorrentRequest("&action=start" + RPC_URL_HASH + startTask.getTargetTorrent().getUniqueID());
- }
- return new DaemonTaskSuccessResult(task);
-
- case StartAll:
-
- // Start all torrents
- makeUtorrentRequest("&action=start" + getAllHashes());
- return new DaemonTaskSuccessResult(task);
-
- case SetFilePriorities:
-
- // Set priorities of the files of some torrent
- SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
- String prioUrl = "&p=" + convertPriority(prioTask.getNewPriority());
- for (TorrentFile forFile : prioTask.getForFiles()) {
- prioUrl += "&f=" + forFile.getKey();
- }
- makeUtorrentRequest("&action=setprio" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID() + prioUrl);
- return new DaemonTaskSuccessResult(task);
-
- case SetTransferRates:
-
- // Request to set the maximum transfer rates
- SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
- makeUtorrentRequest(
- "&action=setsetting&s=ul_auto_throttle&v=0&s=max_ul_rate&v=" +
- (ratesTask.getUploadRate() == null? 0: ratesTask.getUploadRate().intValue()) +
- "&s=max_dl_rate&v=" +
- (ratesTask.getDownloadRate() == null? 0: ratesTask.getDownloadRate().intValue()));
- return new DaemonTaskSuccessResult(task);
-
- case SetLabel:
-
- // Set the label of some torrent
- SetLabelTask labelTask = (SetLabelTask) task;
- makeUtorrentRequest("&action=setprops" + RPC_URL_HASH + labelTask.getTargetTorrent().getUniqueID() +
- "&s=label&v=" + URLEncoder.encode(labelTask.getNewLabel(), "UTF-8"));
- return new DaemonTaskSuccessResult(task);
-
- case SetTrackers:
-
- // Set the trackers of some torrent
- SetTrackersTask trackersTask = (SetTrackersTask) task;
- // Build list of tracker lines, separated by a \r\n
- String newTrackersText = "";
- for (String tracker : trackersTask.getNewTrackers()) {
- newTrackersText += (newTrackersText.length() == 0? "": "\r\n") + tracker;
- }
- makeUtorrentRequest("&action=setprops" + RPC_URL_HASH + trackersTask.getTargetTorrent().getUniqueID() +
- "&s=trackers&v=" + URLEncoder.encode(newTrackersText, "UTF-8"));
- return new DaemonTaskSuccessResult(task);
+ case Retrieve:
- case ForceRecheck:
+ // Request all torrents from server
+ JSONObject result = makeUtorrentRequest(log, "&list=1");
+ return new RetrieveTaskSuccessResult((RetrieveTask) task,
+ parseJsonRetrieveTorrents(result.getJSONArray("torrents")),
+ parseJsonRetrieveGetLabels(result.getJSONArray("label")));
- // Force re-check of data on a torrent
- makeUtorrentRequest("&action=recheck" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
- return new DaemonTaskSuccessResult(task);
+ case GetTorrentDetails:
- default:
- return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
+ // Request fine details of a specific torrent
+ JSONObject dresult = makeUtorrentRequest(log,
+ "&action=getprops" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
+ return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task,
+ parseJsonTorrentDetails(dresult.getJSONArray("props")));
+
+ case GetFileList:
+
+ // Get the file listing of a torrent
+ JSONObject files = makeUtorrentRequest(log,
+ "&action=getfiles" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
+ return new GetFileListTaskSuccessResult((GetFileListTask) task,
+ parseJsonFileListing(files.getJSONArray("files").getJSONArray(1), task.getTargetTorrent()));
+
+ case AddByFile:
+
+ // Add a torrent to the server by sending the contents of a local .torrent file
+ String file = ((AddByFileTask) task).getFile();
+ uploadTorrentFile(file);
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByUrl:
+
+ // Request to add a torrent by URL
+ String url = ((AddByUrlTask) task).getUrl();
+ if (url == null || url.equals("")) {
+ throw new DaemonException(DaemonException.ExceptionType.ParsingFailed, "No url specified");
+ }
+ makeUtorrentRequest(log, "&action=add-url&s=" + URLEncoder.encode(url, "UTF-8"));
+ return new DaemonTaskSuccessResult(task);
+
+ case AddByMagnetUrl:
+
+ // Request to add a magnet link by URL
+ String magnet = ((AddByMagnetUrlTask) task).getUrl();
+ makeUtorrentRequest(log, "&action=add-url&s=" + URLEncoder.encode(magnet, "UTF-8"));
+ return new DaemonTaskSuccessResult(task);
+
+ case Remove:
+
+ // Remove a torrent
+ RemoveTask removeTask = (RemoveTask) task;
+ if (removeTask.includingData()) {
+ makeUtorrentRequest(log,
+ "&action=removedata" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
+ } else {
+ makeUtorrentRequest(log,
+ "&action=remove" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
+ }
+ return new DaemonTaskSuccessResult(task);
+
+ case Pause:
+
+ // Pause a torrent
+ makeUtorrentRequest(log, "&action=pause" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
+ return new DaemonTaskSuccessResult(task);
+
+ case PauseAll:
+
+ // Pause all torrents
+ makeUtorrentRequest(log, "&action=pause" + getAllHashes(log));
+ return new DaemonTaskSuccessResult(task);
+
+ case Resume:
+
+ // Resume a torrent
+ makeUtorrentRequest(log, "&action=unpause" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
+ return new DaemonTaskSuccessResult(task);
+
+ case ResumeAll:
+
+ // Resume all torrents
+ makeUtorrentRequest(log, "&action=unpause" + getAllHashes(log));
+ return new DaemonTaskSuccessResult(task);
+
+ case Stop:
+
+ // Stop a torrent
+ makeUtorrentRequest(log, "&action=stop" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
+ return new DaemonTaskSuccessResult(task);
+
+ case StopAll:
+
+ // Stop all torrents
+ makeUtorrentRequest(log, "&action=stop" + getAllHashes(log));
+ return new DaemonTaskSuccessResult(task);
+
+ case Start:
+
+ // Start a torrent (maybe forced)
+ StartTask startTask = (StartTask) task;
+ if (startTask.isForced()) {
+ makeUtorrentRequest(log,
+ "&action=forcestart" + RPC_URL_HASH + startTask.getTargetTorrent().getUniqueID());
+ } else {
+ makeUtorrentRequest(log,
+ "&action=start" + RPC_URL_HASH + startTask.getTargetTorrent().getUniqueID());
+ }
+ return new DaemonTaskSuccessResult(task);
+
+ case StartAll:
+
+ // Start all torrents
+ makeUtorrentRequest(log, "&action=start" + getAllHashes(log));
+ return new DaemonTaskSuccessResult(task);
+
+ case SetFilePriorities:
+
+ // Set priorities of the files of some torrent
+ SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
+ String prioUrl = "&p=" + convertPriority(prioTask.getNewPriority());
+ for (TorrentFile forFile : prioTask.getForFiles()) {
+ prioUrl += "&f=" + forFile.getKey();
+ }
+ makeUtorrentRequest(log,
+ "&action=setprio" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID() + prioUrl);
+ return new DaemonTaskSuccessResult(task);
+
+ case SetTransferRates:
+
+ // Request to set the maximum transfer rates
+ SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
+ makeUtorrentRequest(log, "&action=setsetting&s=ul_auto_throttle&v=0&s=max_ul_rate&v=" +
+ (ratesTask.getUploadRate() == null ? 0 : ratesTask.getUploadRate()) +
+ "&s=max_dl_rate&v=" +
+ (ratesTask.getDownloadRate() == null ? 0 : ratesTask.getDownloadRate()));
+ return new DaemonTaskSuccessResult(task);
+
+ case SetLabel:
+
+ // Set the label of some torrent
+ SetLabelTask labelTask = (SetLabelTask) task;
+ makeUtorrentRequest(log,
+ "&action=setprops" + RPC_URL_HASH + labelTask.getTargetTorrent().getUniqueID() +
+ "&s=label&v=" + URLEncoder.encode(labelTask.getNewLabel(), "UTF-8"));
+ return new DaemonTaskSuccessResult(task);
+
+ case SetTrackers:
+
+ // Set the trackers of some torrent
+ SetTrackersTask trackersTask = (SetTrackersTask) task;
+ // Build list of tracker lines, separated by a \r\n
+ String newTrackersText = "";
+ for (String tracker : trackersTask.getNewTrackers()) {
+ newTrackersText += (newTrackersText.length() == 0 ? "" : "\r\n") + tracker;
+ }
+ makeUtorrentRequest(log,
+ "&action=setprops" + RPC_URL_HASH + trackersTask.getTargetTorrent().getUniqueID() +
+ "&s=trackers&v=" + URLEncoder.encode(newTrackersText, "UTF-8"));
+ return new DaemonTaskSuccessResult(task);
+
+ case ForceRecheck:
+
+ // Force re-check of data on a torrent
+ makeUtorrentRequest(log, "&action=recheck" + RPC_URL_HASH + task.getTargetTorrent().getUniqueID());
+ return new DaemonTaskSuccessResult(task);
+
+ default:
+ return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported,
+ task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
@@ -265,14 +303,12 @@ public class UtorrentAdapter implements IDaemonAdapter {
} catch (FileNotFoundException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
} catch (UnsupportedEncodingException e) {
- return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, e.toString()));
+ return new DaemonTaskFailureResult(task,
+ new DaemonException(ExceptionType.MethodUnsupported, e.toString()));
} catch (IOException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ConnectionError, e.toString()));
}
}
-
- private static final int NAME_IDX = 0;
- private static final int COUNT_IDX = 1;
private ArrayList parseJsonRetrieveGetLabels(JSONArray lresults) throws JSONException {
@@ -282,28 +318,25 @@ public class UtorrentAdapter implements IDaemonAdapter {
JSONArray lab = lresults.getJSONArray(i);
String name = lab.getString(NAME_IDX);
int count = lab.getInt(COUNT_IDX);
- labels.add(new Label(
- name,
- count
- ));
+ labels.add(new Label(name, count));
}
return labels;
-
+
}
- private JSONObject makeUtorrentRequest(String addToUrl) throws DaemonException {
- return makeUtorrentRequest(addToUrl, 0);
+ private JSONObject makeUtorrentRequest(Log log, String addToUrl) throws DaemonException {
+ return makeUtorrentRequest(log, addToUrl, 0);
}
-
- private JSONObject makeUtorrentRequest(String addToUrl, int retried) throws DaemonException {
+
+ private JSONObject makeUtorrentRequest(Log log, String addToUrl, int retried) throws DaemonException {
try {
-
+
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
-
+
ensureToken();
// Make request
@@ -317,64 +350,68 @@ public class UtorrentAdapter implements IDaemonAdapter {
// Auth token was invalidated; retry at max 3 times
authtoken = null; // So that ensureToken() will request a new token on the next try
if (retried < 2) {
- return makeUtorrentRequest(addToUrl, retried++);
+ return makeUtorrentRequest(log, addToUrl, ++retried);
}
- throw new DaemonException(ExceptionType.AuthenticationFailure, "Response was '" + result.replace("\n", "") + "' instead of a proper JSON object (and we used auth token '" + authtoken + "')");
+ throw new DaemonException(ExceptionType.AuthenticationFailure,
+ "Response was '" + result.replace("\n", "") +
+ "' instead of a proper JSON object (and we used auth token '" + authtoken + "')");
}
JSONObject json = new JSONObject(result);
instream.close();
- return json;
-
+ return json;
+
} catch (DaemonException e) {
throw e;
} catch (JSONException e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (Exception e) {
- DLog.d(LOG_NAME, "Error: " + e.toString());
+ log.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
-
+
}
- private synchronized void ensureToken() throws IOException, ClientProtocolException, DaemonException {
-
+ private synchronized void ensureToken() throws IOException, DaemonException {
+
// Make sure we have a valid token
if (authtoken == null) {
-
+
// Make a request to /gui/token.html
// See https://github.com/bittorrent/webui/wiki/TokenSystem
HttpGet httpget = new HttpGet(buildWebUIUrl() + "token.html");
-
+
// Parse the response HTML
HttpResponse response = httpclient.execute(httpget);
if (response.getStatusLine().getStatusCode() == 401) {
- throw new DaemonException(ExceptionType.AuthenticationFailure, "Auth denied (401) on token.html retrieval");
+ throw new DaemonException(ExceptionType.AuthenticationFailure,
+ "Auth denied (401) on token.html retrieval");
}
if (response.getStatusLine().getStatusCode() == 404) {
- throw new DaemonException(ExceptionType.ConnectionError, "Not found (404); server doesn't exist or is inaccessible");
+ throw new DaemonException(ExceptionType.ConnectionError,
+ "Not found (404); server doesn't exist or is inaccessible");
}
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.convertStreamToString(instream);
- authtoken = result.replaceAll("\\<.*?>","").trim();
+ authtoken = result.replaceAll("<.*?>", "").trim();
}
-
+
}
- public JSONObject uploadTorrentFile(String file) throws DaemonException, ClientProtocolException, IOException, JSONException {
+ public JSONObject uploadTorrentFile(String file) throws DaemonException, IOException, JSONException {
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
-
+
ensureToken();
// Build and make request
HttpPost httppost = new HttpPost(buildWebUIUrl() + "?token=" + authtoken + "&action=add-file");
File upload = new File(URI.create(file));
- Part[] parts = { new FilePart("torrent_file", upload, FilePart.DEFAULT_CONTENT_TYPE, null) };
+ Part[] parts = {new FilePart("torrent_file", upload, FilePart.DEFAULT_CONTENT_TYPE, null)};
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
HttpResponse response = httpclient.execute(httppost);
@@ -384,24 +421,24 @@ public class UtorrentAdapter implements IDaemonAdapter {
JSONObject json = new JSONObject(result);
instream.close();
return json;
-
+
}
/**
* Instantiates an HTTP client with proper credentials that can be used for all Transmission requests.
- * @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise() throws DaemonException {
this.httpclient = HttpHelper.createStandardHttpClient(settings, true);
}
-
+
/**
* Build the URL of the Transmission web UI from the user settings.
* @return The URL of the RPC API
*/
private String buildWebUIUrl() {
- return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + "/gui/";
+ return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() +
+ "/gui/";
}
private TorrentStatus convertUtorrentStatus(int uStatus, boolean finished) {
@@ -430,57 +467,36 @@ public class UtorrentAdapter implements IDaemonAdapter {
return TorrentStatus.Waiting;
}
}
-
+
private Priority convertUtorrentPriority(int code) {
switch (code) {
- case 0:
- return Priority.Off;
- case 1:
- return Priority.Low;
- case 3:
- return Priority.High;
- default:
- return Priority.Normal;
+ case 0:
+ return Priority.Off;
+ case 1:
+ return Priority.Low;
+ case 3:
+ return Priority.High;
+ default:
+ return Priority.Normal;
}
}
private int convertPriority(Priority newPriority) {
if (newPriority == null) {
- return 2;
+ return 2;
}
switch (newPriority) {
- case Off:
- return 0;
- case Low:
- return 1;
- case High:
- return 3;
- default:
- return 2;
+ case Off:
+ return 0;
+ case Low:
+ return 1;
+ case High:
+ return 3;
+ default:
+ return 2;
}
}
- // These are the positions inside the JSON response array of a torrent
- // See http://forum.utorrent.com/viewtopic.php?id=25661
- private static final int RPC_HASH_IDX = 0;
- private static final int RPC_STATUS_IDX = 1;
- private static final int RPC_NAME_IDX = 2;
- private static final int RPC_SIZE_IDX = 3;
- private static final int RPC_PARTDONE = 4;
- private static final int RPC_DOWNLOADED_IDX = 5;
- private static final int RPC_UPLOADED_IDX = 6;
- private static final int RPC_DOWNLOADSPEED_IDX = 9;
- private static final int RPC_UPLOADSPEED_IDX = 8;
- private static final int RPC_ETA_IDX = 10;
- private static final int RPC_LABEL_IDX = 11;
- private static final int RPC_PEERSCONNECTED_IDX = 12;
- private static final int RPC_PEERSINSWARM_IDX = 13;
- private static final int RPC_SEEDSCONNECTED_IDX = 14;
- private static final int RPC_SEEDSINSWARM_IDX = 15;
- private static final int RPC_AVAILABILITY_IDX = 16;
- private static final int RPC_ADDEDON_IDX = 23;
- private static final int RPC_COMPLETEDON_IDX = 24;
-
private ArrayList parseJsonRetrieveTorrents(JSONArray results) throws JSONException {
// Parse response
@@ -490,7 +506,7 @@ public class UtorrentAdapter implements IDaemonAdapter {
JSONArray tor = results.getJSONArray(i);
String name = tor.getString(RPC_NAME_IDX);
boolean downloaded = (tor.getLong(RPC_PARTDONE) == 1000l);
- float available = ((float)tor.getInt(RPC_AVAILABILITY_IDX)) / 65536f; // Integer in 1/65536ths
+ float available = ((float) tor.getInt(RPC_AVAILABILITY_IDX)) / 65536f; // Integer in 1/65536ths
// The full torrent path is not available in uTorrent web UI API
// Guess the torrent's directory based on the user-specific default download dir and the torrent name
String dir = null;
@@ -505,35 +521,22 @@ public class UtorrentAdapter implements IDaemonAdapter {
TorrentStatus status = convertUtorrentStatus(tor.getInt(RPC_STATUS_IDX), downloaded);
long addedOn = tor.optInt(RPC_ADDEDON_IDX, -1);
long completedOn = tor.optInt(RPC_COMPLETEDON_IDX, -1);
- Date addedOnDate = addedOn == -1? null: new Date(addedOn * 1000L);
- Date completedOnDate = completedOn == -1? null: new Date(completedOn * 1000L);
- torrents.add(new Torrent(
- i, // No ID but a hash is used
- tor.getString(RPC_HASH_IDX),
- name,
- status,
- dir,
- tor.getInt(RPC_DOWNLOADSPEED_IDX),
- tor.getInt(RPC_UPLOADSPEED_IDX),
- tor.getInt(RPC_SEEDSCONNECTED_IDX),
- tor.getInt(RPC_SEEDSINSWARM_IDX),
- tor.getInt(RPC_PEERSCONNECTED_IDX),
- tor.getInt(RPC_PEERSINSWARM_IDX),
- tor.getInt(RPC_ETA_IDX),
- tor.getLong(RPC_DOWNLOADED_IDX),
- tor.getLong(RPC_UPLOADED_IDX),
- tor.getLong(RPC_SIZE_IDX),
+ Date addedOnDate = addedOn == -1 ? null : new Date(addedOn * 1000L);
+ Date completedOnDate = completedOn == -1 ? null : new Date(completedOn * 1000L);
+ torrents.add(new Torrent(i, // No ID but a hash is used
+ tor.getString(RPC_HASH_IDX), name, status, dir, tor.getInt(RPC_DOWNLOADSPEED_IDX),
+ tor.getInt(RPC_UPLOADSPEED_IDX), tor.getInt(RPC_SEEDSCONNECTED_IDX),
+ tor.getInt(RPC_SEEDSINSWARM_IDX), tor.getInt(RPC_PEERSCONNECTED_IDX),
+ tor.getInt(RPC_PEERSINSWARM_IDX), tor.getInt(RPC_ETA_IDX), tor.getLong(RPC_DOWNLOADED_IDX),
+ tor.getLong(RPC_UPLOADED_IDX), tor.getLong(RPC_SIZE_IDX),
((float) tor.getLong(RPC_PARTDONE)) / 1000f, // Integer in promille
Math.min(available, 1f), // Can be > 100% if multiple peers have 100%
- tor.getString(RPC_LABEL_IDX).trim(),
- addedOnDate,
- completedOnDate,
+ tor.getString(RPC_LABEL_IDX).trim(), addedOnDate, completedOnDate,
// uTorrent doesn't give the error message, so just remind that there is some error
- status == TorrentStatus.Error? "See GUI for error message": null,
- settings.getType()));
+ status == TorrentStatus.Error ? "See GUI for error message" : null, settings.getType()));
}
return torrents;
-
+
}
private TorrentDetails parseJsonTorrentDetails(JSONArray results) throws JSONException {
@@ -541,7 +544,7 @@ public class UtorrentAdapter implements IDaemonAdapter {
// Parse response
// NOTE: Assumes only details for one torrent are requested at a time
if (results.length() > 0) {
-
+
JSONObject tor = results.getJSONObject(0);
List trackers = new ArrayList();
for (String tracker : tor.getString("trackers").split("\\r\\n")) {
@@ -554,53 +557,49 @@ public class UtorrentAdapter implements IDaemonAdapter {
// See http://forum.utorrent.com/viewtopic.php?pid=553340#p553340
return new TorrentDetails(trackers, null);
}
-
+
return null;
-
- }
- // These are the positions inside the JSON response array of a torrent
- // See http://forum.utorrent.com/viewtopic.php?id=25661
- private static final int RPC_FILENAME_IDX = 0;
- private static final int RPC_FILESIZE_IDX = 1;
- private static final int RPC_FILEDOWNLOADED_IDX = 2;
- private static final int RPC_FILEPRIORITY_IDX = 3;
+ }
private ArrayList parseJsonFileListing(JSONArray results, Torrent torrent) throws JSONException {
// Parse response
ArrayList files = new ArrayList();
- boolean createPaths = torrent != null && torrent.getLocationDir() != null && !torrent.getLocationDir().equals("");
+ boolean createPaths =
+ torrent != null && torrent.getLocationDir() != null && !torrent.getLocationDir().equals("");
final String pathSep = settings.getOS().getPathSeperator();
for (int i = 0; i < results.length(); i++) {
JSONArray file = results.getJSONArray(i);
// Add the parsed torrent to the list
- files.add(new TorrentFile(
- "" + i,
- file.getString(RPC_FILENAME_IDX), // Name
- (createPaths? file.getString(RPC_FILENAME_IDX).replace((pathSep.equals("/")? "\\": "/"), pathSep): null), // Relative path; 'wrong' path slashes will be replaced
- (createPaths? torrent.getLocationDir() + file.getString(RPC_FILENAME_IDX).replace((pathSep.equals("/")? "\\": "/"), pathSep): null), // Full path; 'wrong' path slashes will be replaced
- file.getLong(RPC_FILESIZE_IDX), // Total size
- file.getLong(RPC_FILEDOWNLOADED_IDX), // Part done
- convertUtorrentPriority(file.getInt(RPC_FILEPRIORITY_IDX)))); // Priority
+ files.add(new TorrentFile("" + i, file.getString(RPC_FILENAME_IDX), // Name
+ (createPaths ?
+ file.getString(RPC_FILENAME_IDX).replace((pathSep.equals("/") ? "\\" : "/"), pathSep) :
+ null), // Relative path; 'wrong' path slashes will be replaced
+ (createPaths ? torrent.getLocationDir() +
+ file.getString(RPC_FILENAME_IDX).replace((pathSep.equals("/") ? "\\" : "/"), pathSep) :
+ null), // Full path; 'wrong' path slashes will be replaced
+ file.getLong(RPC_FILESIZE_IDX), // Total size
+ file.getLong(RPC_FILEDOWNLOADED_IDX), // Part done
+ convertUtorrentPriority(file.getInt(RPC_FILEPRIORITY_IDX)))); // Priority
}
return files;
-
+
}
-
- private String getAllHashes() throws DaemonException, JSONException {
-
+
+ private String getAllHashes(Log log) throws DaemonException, JSONException {
+
// Make a retrieve torrents call first to gather all hashes
- JSONObject result = makeUtorrentRequest("&list=1");
+ JSONObject result = makeUtorrentRequest(log, "&list=1");
ArrayList torrents = parseJsonRetrieveTorrents(result.getJSONArray("torrents"));
-
+
// Build a string of hashes of all the torrents
String hashes = "";
for (Torrent torrent : torrents) {
hashes += RPC_URL_HASH + torrent.getUniqueID();
}
return hashes;
-
+
}
@Override
@@ -612,5 +611,5 @@ public class UtorrentAdapter implements IDaemonAdapter {
public DaemonSettings getSettings() {
return this.settings;
}
-
+
}
diff --git a/app/src/main/java/org/transdroid/daemon/Vuze/VuzeAdapter.java b/app/src/main/java/org/transdroid/daemon/Vuze/VuzeAdapter.java
index 48a8842b..539f0b46 100644
--- a/app/src/main/java/org/transdroid/daemon/Vuze/VuzeAdapter.java
+++ b/app/src/main/java/org/transdroid/daemon/Vuze/VuzeAdapter.java
@@ -29,6 +29,7 @@ import java.util.List;
import java.util.Map;
import org.apache.openjpa.lib.util.Base16Encoder;
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonException.ExceptionType;
@@ -52,7 +53,6 @@ import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
-import org.transdroid.daemon.util.DLog;
/**
* An adapter that allows for easy access to Vuze torrent data. Communication
@@ -81,14 +81,14 @@ public class VuzeAdapter implements IDaemonAdapter {
}
@Override
- public DaemonTaskResult executeTask(DaemonTask task) {
+ public DaemonTaskResult executeTask(Log log, DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
Object result = makeVuzeCall(DaemonMethod.Retrieve, "getDownloads");
- return new RetrieveTaskSuccessResult((RetrieveTask) task, onTorrentsRetrieved(result),null);
+ return new RetrieveTaskSuccessResult((RetrieveTask) task, onTorrentsRetrieved(log, result),null);
case GetFileList:
@@ -189,8 +189,10 @@ public class VuzeAdapter implements IDaemonAdapter {
// Request to set the maximum transfer rates
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
makeVuzeCall(DaemonMethod.SetTransferRates, "setBooleanParameter[String,boolean]", new Object[] { "Auto Upload Speed Enabled", false } );
- makeVuzeCall(DaemonMethod.SetTransferRates, "setCoreIntParameter[String,int]", new Object[] { "Max Upload Speed KBs", (ratesTask.getUploadRate() == null? 0: ratesTask.getUploadRate().intValue())} );
- makeVuzeCall(DaemonMethod.SetTransferRates, "setCoreIntParameter[String,int]", new Object[] { "Max Download Speed KBs", (ratesTask.getDownloadRate() == null? 0: ratesTask.getDownloadRate().intValue())} );
+ makeVuzeCall(DaemonMethod.SetTransferRates, "setCoreIntParameter[String,int]", new Object[] { "Max Upload Speed KBs", (ratesTask.getUploadRate() == null? 0:
+ ratesTask.getUploadRate())} );
+ makeVuzeCall(DaemonMethod.SetTransferRates, "setCoreIntParameter[String,int]", new Object[] { "Max Download Speed KBs", (ratesTask.getDownloadRate() == null? 0:
+ ratesTask.getDownloadRate())} );
return new DaemonTaskSuccessResult(task);
default:
@@ -318,7 +320,7 @@ public class VuzeAdapter implements IDaemonAdapter {
Map torrentData = rpcclient.callXMLRPC(vuzeObjectID, serverMethod, params, savedConnectionID, false);
serverMethod = "addDownload[Torrent]";
vuzeObjectID = savedDownloadManagerID;
- params = new String[] { ((Long) torrentData.get("_object_id")).toString() };
+ params = new String[] { torrentData.get("_object_id").toString() };
paramsAreVuzeObjects = true;
}
@@ -346,7 +348,7 @@ public class VuzeAdapter implements IDaemonAdapter {
}
@SuppressWarnings("unchecked")
- private List onTorrentsRetrieved(Object result) throws DaemonException {
+ private List onTorrentsRetrieved(Log log, Object result) throws DaemonException {
Map response = (Map) result;
@@ -355,7 +357,7 @@ public class VuzeAdapter implements IDaemonAdapter {
return new ArrayList();
}
- DLog.d(LOG_NAME, response.toString().length() > 300? response.toString().substring(0, 300) + "... (" + response.toString().length() + " chars)": response.toString());
+ log.d(LOG_NAME, response.toString().length() > 300? response.toString().substring(0, 300) + "... (" + response.toString().length() + " chars)": response.toString());
List torrents = new ArrayList();
@@ -376,7 +378,7 @@ public class VuzeAdapter implements IDaemonAdapter {
}
*/
Map info = (Map) response.get(key);
- if (info == null || !info.containsKey("_object_id") || ((Long)info.get("_object_id")) == null) {
+ if (info == null || !info.containsKey("_object_id") || info.get("_object_id") == null) {
// No valid XML data object returned
throw new DaemonException(DaemonException.ExceptionType.UnexpectedResponse, "Map of objects returned by Vuze, but these object do not have some attached or no <_object_id> is available");
}
@@ -396,10 +398,10 @@ public class VuzeAdapter implements IDaemonAdapter {
torrents.add(new Torrent(
(Long) info.get("_object_id"), // id
- ((Long) info.get("_object_id")).toString(), // hash //(String) torrentinfo.get("hash"), // hash
- (String) info.get("name").toString().trim(), // name
+ info.get("_object_id").toString(), // hash //(String) torrentinfo.get("hash"), // hash
+ info.get("name").toString().trim(), // name
convertTorrentStatus((Long) info.get("state")), // status
- (String) statsinfo.get("target_file_or_dir") + "/", // locationDir
+ statsinfo.get("target_file_or_dir") + "/", // locationDir
rateDownload, // rateDownload
((Long)statsinfo.get("upload_average")).intValue(), // rateUpload
announceSeedCount, // seedersConnected
@@ -461,7 +463,7 @@ public class VuzeAdapter implements IDaemonAdapter {
String file = (String)info.get("file");
files.add(new TorrentFile(
- "" + (Long)info.get("_object_id"),
+ String.valueOf(info.get("_object_id")),
new File(file).getName(), // name
(file.length() > torrent.getLocationDir().length()? file.substring(torrent.getLocationDir().length()): file), // name
file, // fullPath
diff --git a/app/src/main/java/org/transdroid/daemon/task/DaemonTask.java b/app/src/main/java/org/transdroid/daemon/task/DaemonTask.java
index c858aece..df2ade93 100644
--- a/app/src/main/java/org/transdroid/daemon/task/DaemonTask.java
+++ b/app/src/main/java/org/transdroid/daemon/task/DaemonTask.java
@@ -15,46 +15,51 @@
* along with Transdroid. If not, see .
*
*/
- package org.transdroid.daemon.task;
+package org.transdroid.daemon.task;
+import android.os.Bundle;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import org.transdroid.core.gui.log.Log;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
-import android.os.Bundle;
-import android.os.Parcel;
-import android.os.Parcelable;
-
/**
- * A daemon task represents some action that needs to be performed
- * on the server daemon. It has no capabilities on itself; these are
- * marshaled to the daemon adapter. Therefore all needed info (the
- * parameters) needs to be added to the extras bundle.
- *
- * To help create these tasks and there data, each possible daemon
- * method is created using a task-specific separate class with a
- * create() method.
- *
- * This class is Parcelable so it can be persisted in between an
- * Activity breakdown and recreation.
- *
+ * A daemon task represents some action that needs to be performed on the server daemon. It has no capabilities on
+ * itself; these are marshaled to the daemon adapter. Therefore all needed info (the parameters) needs to be added to
+ * the extras bundle.
+ *
+ * To help create these tasks and there data, each possible daemon method is created using a task-specific separate
+ * class with a create() method.
+ *
+ * This class is Parcelable so it can be persisted in between an Activity breakdown and recreation.
* @author erickok
- *
*/
public class DaemonTask implements Parcelable {
- protected IDaemonAdapter adapter;
+ public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
+ public DaemonTask createFromParcel(Parcel in) {
+ return new DaemonTask(in);
+ }
+
+ public DaemonTask[] newArray(int size) {
+ return new DaemonTask[size];
+ }
+ };
protected final DaemonMethod method;
protected final Torrent targetTorrent;
protected final Bundle extras;
+ protected IDaemonAdapter adapter;
private DaemonTask(Parcel in) {
this.method = DaemonMethod.getStatus(in.readInt());
this.targetTorrent = in.readParcelable(Torrent.class.getClassLoader());
this.extras = in.readBundle();
}
-
+
protected DaemonTask(IDaemonAdapter adapter, DaemonMethod method, Torrent targetTorrent, Bundle extras) {
this.adapter = adapter;
this.method = method;
@@ -65,18 +70,19 @@ public class DaemonTask implements Parcelable {
this.extras = extras;
}
}
-
+
/**
* Execute the task on the appropriate daemon adapter
+ * @param log The logger to use when writing exceptions and debug information
*/
- public DaemonTaskResult execute() {
- return adapter.executeTask(this);
+ public DaemonTaskResult execute(Log log) {
+ return adapter.executeTask(log, this);
}
public DaemonMethod getMethod() {
return method;
}
-
+
public Daemon getAdapterType() {
return this.adapter.getType();
}
@@ -89,33 +95,27 @@ public class DaemonTask implements Parcelable {
return extras;
}
- public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
- public DaemonTask createFromParcel(Parcel in) {
- return new DaemonTask(in);
- }
-
- public DaemonTask[] newArray(int size) {
- return new DaemonTask[size];
- }
- };
-
@Override
public int describeContents() {
return 0;
}
-
+
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(method.getCode());
dest.writeParcelable(targetTorrent, 0);
dest.writeBundle(extras);
}
-
+
/**
- * Returns a readable description of this task in the form 'MethodName on AdapterName with TorrentName and AllExtras'
+ * Returns a readable description of this task in the form 'MethodName on AdapterName with TorrentName and
+ * AllExtras'
*/
public String toString() {
- return method.toString() + (adapter == null? "": " on " + adapter.getType()) + (targetTorrent != null || extras != null? " with ": "") + (targetTorrent == null? "": targetTorrent.toString() + (targetTorrent != null && extras != null? " and ": "")) + (extras == null? "": extras.toString());
+ return method.toString() + (adapter == null ? "" : " on " + adapter.getType()) +
+ (targetTorrent != null || extras != null ? " with " : "") +
+ (targetTorrent == null ? "" : targetTorrent.toString() + (extras != null ? " and " : "")) +
+ (extras == null ? "" : extras.toString());
}
}
diff --git a/app/src/main/java/org/transdroid/daemon/util/Collections2.java b/app/src/main/java/org/transdroid/daemon/util/Collections2.java
index e4a2083d..b0d5ee4b 100644
--- a/app/src/main/java/org/transdroid/daemon/util/Collections2.java
+++ b/app/src/main/java/org/transdroid/daemon/util/Collections2.java
@@ -1,7 +1,5 @@
package org.transdroid.daemon.util;
-import java.util.Iterator;
-
/**
* Helpers on Collections
*/
@@ -13,9 +11,8 @@ public class Collections2 {
public static String joinString(Iterable iterable, String separator) {
boolean first = true;
String result = "";
- Iterator it = iterable.iterator();
- while (it.hasNext()) {
- result += (first ? "" : separator) + it.next().toString();
+ for (T anIterable : iterable) {
+ result += (first ? "" : separator) + anIterable.toString();
first = false;
}
return result;
diff --git a/app/src/main/java/org/transdroid/daemon/util/DLog.java b/app/src/main/java/org/transdroid/daemon/util/DLog.java
deleted file mode 100644
index 7a33faa2..00000000
--- a/app/src/main/java/org/transdroid/daemon/util/DLog.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * This file is part of Transdroid
- *
- * Transdroid is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * Transdroid is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Transdroid. If not, see .
- *
- */
-package org.transdroid.daemon.util;
-
-/**
- * Universal logger; applications using this library should
- * attach an ITLogger using setLogger(ITLogger)
- * to receive any logging information from the daemons.
- *
- * @author erickok
- */
-public class DLog {
-
- private static final String LOG_TAG = "Transdroid";
-
- private static ITLogger instance = null;
-
- public static void setLogger(ITLogger logger) {
- instance = logger;
- }
-
- /**
- * Send a DEBUG log message.
- * @param self Unique source tag, identifying the part of Transdroid it happens in
- * @param msg The debug message to log
- */
- public static void d(String self, String msg) {
- if (instance != null) {
- instance.d(LOG_TAG, self + ": " + msg);
- }
- }
-
- /**
- * Send an ERROR log message.
- * @param self Unique source tag, identifying the part of Transdroid it happens in
- * @param msg The error message to log
- */
- public static void e(String self, String msg) {
- if (instance != null) {
- instance.e(LOG_TAG, self + ": " + msg);
- }
- }
-
-}
diff --git a/app/src/main/java/org/transdroid/daemon/util/HttpHelper.java b/app/src/main/java/org/transdroid/daemon/util/HttpHelper.java
index bee9acd5..90a2db9e 100644
--- a/app/src/main/java/org/transdroid/daemon/util/HttpHelper.java
+++ b/app/src/main/java/org/transdroid/daemon/util/HttpHelper.java
@@ -17,15 +17,7 @@
*/
package org.transdroid.daemon.util;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.zip.GZIPInputStream;
+import android.net.Uri;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
@@ -53,7 +45,15 @@ import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.DaemonSettings;
-import android.net.Uri;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.zip.GZIPInputStream;
/**
* Provides a set of general helper methods that can be used in web-based communication.
@@ -62,15 +62,41 @@ import android.net.Uri;
public class HttpHelper {
public static final int DEFAULT_CONNECTION_TIMEOUT = 8000;
- public static final String SCHEME_HTTP = "http";
- public static final String SCHEME_HTTPS = "https";
- public static final String SCHEME_MAGNET = "magnet";
- public static final String SCHEME_FILE = "file";
/**
* The 'User-Agent' name to send to the server
*/
public static String userAgent = "Transdroid Torrent Connect";
+ /**
+ * HTTP request interceptor to allow for GZip-encoded data transfer
+ */
+ public static HttpRequestInterceptor gzipRequestInterceptor = new HttpRequestInterceptor() {
+ public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
+ if (!request.containsHeader("Accept-Encoding")) {
+ request.addHeader("Accept-Encoding", "gzip");
+ }
+ }
+ };
+ /**
+ * HTTP response interceptor that decodes GZipped data
+ */
+ public static HttpResponseInterceptor gzipResponseInterceptor = new HttpResponseInterceptor() {
+ public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
+ HttpEntity entity = response.getEntity();
+ Header ceheader = entity.getContentEncoding();
+ if (ceheader != null) {
+ HeaderElement[] codecs = ceheader.getElements();
+ for (HeaderElement codec : codecs) {
+
+ if (codec.getName().equalsIgnoreCase("gzip")) {
+ response.setEntity(new GzipDecompressingEntity(response.getEntity()));
+ return;
+ }
+ }
+ }
+ }
+
+ };
/**
* Creates a standard Apache HttpClient that is thread safe, supports different SSL auth methods and basic
@@ -98,8 +124,8 @@ public class HttpHelper {
* @throws DaemonException Thrown when information (such as username/password) is missing
*/
public static DefaultHttpClient createStandardHttpClient(boolean userBasicAuth, String username, String password,
- boolean sslTrustAll, String sslTrustKey, int timeout, String authAddress, int authPort)
- throws DaemonException {
+ boolean sslTrustAll, String sslTrustKey, int timeout,
+ String authAddress, int authPort) throws DaemonException {
// Register http and https sockets
SchemeRegistry registry = new SchemeRegistry();
@@ -122,8 +148,8 @@ public class HttpHelper {
HttpProtocolParams.setUserAgent(httpparams, userAgent);
}
- DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry),
- httpparams);
+ DefaultHttpClient httpclient =
+ new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry), httpparams);
// Authentication credentials
if (userBasicAuth) {
@@ -131,78 +157,20 @@ public class HttpHelper {
throw new DaemonException(ExceptionType.AuthenticationFailure,
"No username or password was provided while we had authentication enabled");
}
- httpclient.getCredentialsProvider().setCredentials(
- new AuthScope(authAddress, authPort, AuthScope.ANY_REALM),
- new UsernamePasswordCredentials(username, password));
+ httpclient.getCredentialsProvider()
+ .setCredentials(new AuthScope(authAddress, authPort, AuthScope.ANY_REALM),
+ new UsernamePasswordCredentials(username, password));
}
return httpclient;
}
- /**
- * HTTP request interceptor to allow for GZip-encoded data transfer
- */
- public static HttpRequestInterceptor gzipRequestInterceptor = new HttpRequestInterceptor() {
- public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
- if (!request.containsHeader("Accept-Encoding")) {
- request.addHeader("Accept-Encoding", "gzip");
- }
- }
- };
-
- /**
- * HTTP response interceptor that decodes GZipped data
- */
- public static HttpResponseInterceptor gzipResponseInterceptor = new HttpResponseInterceptor() {
- public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
- HttpEntity entity = response.getEntity();
- Header ceheader = entity.getContentEncoding();
- if (ceheader != null) {
- HeaderElement[] codecs = ceheader.getElements();
- for (int i = 0; i < codecs.length; i++) {
-
- if (codecs[i].getName().equalsIgnoreCase("gzip")) {
- response.setEntity(new HttpHelper.GzipDecompressingEntity(response.getEntity()));
- return;
- }
- }
- }
- }
-
- };
-
- /**
- * HTTP entity wrapper to decompress GZipped HTTP responses
- */
- private static class GzipDecompressingEntity extends HttpEntityWrapper {
-
- public GzipDecompressingEntity(final HttpEntity entity) {
- super(entity);
- }
-
- @Override
- public InputStream getContent() throws IOException, IllegalStateException {
-
- // the wrapped entity's getContent() decides about repeatability
- InputStream wrappedin = wrappedEntity.getContent();
-
- return new GZIPInputStream(wrappedin);
- }
-
- @Override
- public long getContentLength() {
- // length of ungzipped content is not known
- return -1;
- }
-
- }
-
/*
* To convert the InputStream to String we use the BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
- *
+ *
* Taken from http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
*/
public static String convertStreamToString(InputStream is, String encoding) throws UnsupportedEncodingException {
@@ -215,10 +183,10 @@ public class HttpHelper {
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
- String line = null;
+ String line;
try {
while ((line = reader.readLine()) != null) {
- sb.append(line + "\n");
+ sb.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
@@ -272,4 +240,30 @@ public class HttpHelper {
}
+ /**
+ * HTTP entity wrapper to decompress GZipped HTTP responses
+ */
+ private static class GzipDecompressingEntity extends HttpEntityWrapper {
+
+ public GzipDecompressingEntity(final HttpEntity entity) {
+ super(entity);
+ }
+
+ @Override
+ public InputStream getContent() throws IOException, IllegalStateException {
+
+ // the wrapped entity's getContent() decides about repeatability
+ InputStream wrappedin = wrappedEntity.getContent();
+
+ return new GZIPInputStream(wrappedin);
+ }
+
+ @Override
+ public long getContentLength() {
+ // length of ungzipped content is not known
+ return -1;
+ }
+
+ }
+
}
\ No newline at end of file
diff --git a/app/src/main/java/org/transdroid/daemon/util/ITLogger.java b/app/src/main/java/org/transdroid/daemon/util/ITLogger.java
deleted file mode 100644
index 8882caf4..00000000
--- a/app/src/main/java/org/transdroid/daemon/util/ITLogger.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * This file is part of Transdroid
- *
- * Transdroid is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * Transdroid is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Transdroid. If not, see .
- *
- */
-package org.transdroid.daemon.util;
-
-/**
- * Interface that should be implemented for any logging
- * information to get from the daemons. Applications using
- * this library should attach an instance using
- * TLog.setLogger(ITLogger)
- *
- * @author erickok
- */
-public interface ITLogger {
-
- /**
- * Send a DEBUG log message.
- * @param self Unique source tag, identifying the part of Transdroid it happens in
- * @param msg The debug message to log
- */
- public abstract void d(String self, String msg);
-
- /**
- * Send an ERROR log message.
- * @param self Unique source tag, identifying the part of Transdroid it happens in
- * @param msg The error message to log
- */
- public abstract void e(String self, String msg);
-
-}
diff --git a/app/src/main/java/org/transdroid/daemon/util/Pair.java b/app/src/main/java/org/transdroid/daemon/util/Pair.java
deleted file mode 100644
index bcc01a23..00000000
--- a/app/src/main/java/org/transdroid/daemon/util/Pair.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.transdroid.daemon.util;
-
-/**
- * Container to ease passing around a tuple of two objects. This object provides a sensible
- * implementation of equals(), returning true if equals() is true on each of the contained
- * objects.
- */
-public class Pair {
- public final F first;
- public final S second;
-
- /**
- * Constructor for a Pair. If either are null then equals() and hashCode() will throw
- * a NullPointerException.
- * @param first the first object in the Pair
- * @param second the second object in the pair
- */
- public Pair(F first, S second) {
- this.first = first;
- this.second = second;
- }
-
- /**
- * Checks the two objects for equality by delegating to their respective equals() methods.
- * @param o the Pair to which this one is to be checked for equality
- * @return true if the underlying objects of the Pair are both considered equals()
- */
- @SuppressWarnings("unchecked")
- public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof Pair)) return false;
- final Pair other;
- try {
- other = (Pair) o;
- } catch (ClassCastException e) {
- return false;
- }
- return first.equals(other.first) && second.equals(other.second);
- }
-
- /**
- * Compute a hash code using the hash codes of the underlying objects
- * @return a hashcode of the Pair
- */
- public int hashCode() {
- int result = 17;
- result = 31 * result + first.hashCode();
- result = 31 * result + second.hashCode();
- return result;
- }
-
- /**
- * Convenience method for creating an appropriately typed pair.
- * @param a the first object in the Pair
- * @param b the second object in the pair
- * @return a Pair that is templatized with the types of a and b
- */
- public static Pair create(A a, B b) {
- return new Pair (a, b);
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/org/transdroid/daemon/util/SelfSignedTrustManager.java b/app/src/main/java/org/transdroid/daemon/util/SelfSignedTrustManager.java
index 41bf196a..f79a2209 100644
--- a/app/src/main/java/org/transdroid/daemon/util/SelfSignedTrustManager.java
+++ b/app/src/main/java/org/transdroid/daemon/util/SelfSignedTrustManager.java
@@ -27,7 +27,6 @@ import javax.net.ssl.X509TrustManager;
public class SelfSignedTrustManager implements X509TrustManager {
private static final X509Certificate[] acceptedIssuers = new X509Certificate[]{};
- private static final String LOG_NAME = "TrustManager";
private String certKey = null;
@@ -50,9 +49,9 @@ public class SelfSignedTrustManager implements X509TrustManager {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBuffer buf = new StringBuffer(bytes.length * 2);
- for (int i = 0; i < bytes.length; ++i) {
- buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
- buf.append(hexDigits[bytes[i] & 0x0f]);
+ for (byte aByte : bytes) {
+ buf.append(hexDigits[(aByte & 0xf0) >> 4]);
+ buf.append(hexDigits[aByte & 0x0f]);
}
return buf.toString();
@@ -75,15 +74,15 @@ public class SelfSignedTrustManager implements X509TrustManager {
// Assume self-signed root is okay?
X509Certificate sslCert = chain[0];
String thumbprint = SelfSignedTrustManager.getThumbPrint(sslCert);
- DLog.d(LOG_NAME, thumbprint);
if (ourKey.equalsIgnoreCase(thumbprint)) {
return;
- } else {
- CertificateException certificateException =
- new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
- DLog.e(SelfSignedTrustManager.class.getSimpleName(), certificateException.toString());
- throw certificateException;
}
+
+ CertificateException certificateException =
+ new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
+ //Log.e(SelfSignedTrustManager.class.getSimpleName(), certificateException.toString());
+ throw certificateException;
+
} catch (NoSuchAlgorithmException e) {
throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
}
diff --git a/app/src/main/java/org/transdroid/daemon/util/TlsSniSocketFactory.java b/app/src/main/java/org/transdroid/daemon/util/TlsSniSocketFactory.java
index de22c764..853a3f75 100644
--- a/app/src/main/java/org/transdroid/daemon/util/TlsSniSocketFactory.java
+++ b/app/src/main/java/org/transdroid/daemon/util/TlsSniSocketFactory.java
@@ -19,6 +19,7 @@ package org.transdroid.daemon.util;
import android.annotation.TargetApi;
import android.net.SSLCertificateSocketFactory;
import android.os.Build;
+import android.util.Log;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.ssl.StrictHostnameVerifier;
@@ -130,7 +131,7 @@ public class TlsSniSocketFactory implements LayeredSocketFactory {
java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(ssl, host);
} catch (Exception e) {
- DLog.d(TlsSniSocketFactory.class.getSimpleName(), "SNI not usable: " + e);
+ Log.d(TlsSniSocketFactory.class.getSimpleName(), "SNI not usable: " + e);
}
}